@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.
- package/CHANGELOG.md +134 -0
- package/LICENSE +22 -0
- package/NOTICE +13 -0
- package/PRIVACY.md +41 -0
- package/README.md +288 -2
- 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 +122 -4
- 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,2731 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Live dashboard for the Node host. Serves the main HTML page and JSON
|
|
3
|
+
* polling endpoints. All "/api/*.json" endpoints recompute from disk on
|
|
4
|
+
* every request — inkling doesn't have a query layer, but a 1.5 MB JSONL
|
|
5
|
+
* streams in well under 100 ms.
|
|
6
|
+
*
|
|
7
|
+
* Legacy live-poll endpoints (left in place, the existing tick() loop uses
|
|
8
|
+
* them):
|
|
9
|
+
*
|
|
10
|
+
* GET /, /dashboard → main HTML page
|
|
11
|
+
* GET /proxy-stats → JSON aggregate over the in-mem ring
|
|
12
|
+
* GET /proxy-recent → JSON ring buffer of recent requests
|
|
13
|
+
* GET /proxy-latest-png[?crop=N] → raw PNG of the latest rendered image
|
|
14
|
+
*
|
|
15
|
+
* Session endpoints (read-only local metrics — no destructive operations):
|
|
16
|
+
*
|
|
17
|
+
* GET /api/sessions.json → grouped sessions (sha8 + project + counts)
|
|
18
|
+
* GET /api/stats.json → full-history aggregate (formerly `inkling stats`)
|
|
19
|
+
*
|
|
20
|
+
* Metric formulas and HTML shell originally ported from the Python reference
|
|
21
|
+
* implementation (deleted after live cache-rate validation hit 98.7% by tokens).
|
|
22
|
+
*
|
|
23
|
+
* Node-only by design. Workers host has no dashboard; use Workers Logs.
|
|
24
|
+
*
|
|
25
|
+
* Memory bound: ring buffer cap 50 events + a parallel ring of the last 50
|
|
26
|
+
* rendered PNGs (images are never persisted to disk, so this ring is the
|
|
27
|
+
* only place to view them). At a typical 75 KB PNG that's ~3-4 MB resident;
|
|
28
|
+
* a process restart starts the image ring empty.
|
|
29
|
+
*/
|
|
30
|
+
import * as fs from 'node:fs';
|
|
31
|
+
import * as os from 'node:os';
|
|
32
|
+
import * as path from 'node:path';
|
|
33
|
+
import * as readline from 'node:readline';
|
|
34
|
+
import { anthropicReadRate, estimateBillUsd, inputUsdPerMtok, priceMode, PRICE_SNAPSHOT, resolvePriceRates } from './core/pricing.js';
|
|
35
|
+
import { readTurnReport } from './turn-report.js';
|
|
36
|
+
import { computeActualInputEffWithCacheTier, computeBaselineInputEffWithCacheTier, deriveBaselineWarmth, isUsableAnthropicBaselineProbe, observedCacheTtlSec, } from './core/baseline.js';
|
|
37
|
+
import { computeOpenAIActualInputEff, computeOpenAIBaselineRawTokens, computeOpenAISessionBaselineInputEff, deriveOpenAIBaselineWarmth, OPENAI_CACHE_TTL_SEC, openAIOutputRate, } from './core/openai-savings.js';
|
|
38
|
+
import { renderCacheMaxBytes, renderCacheStats } from './core/render.js';
|
|
39
|
+
import { aggregateSessions, claudeCodeMap, filterSessions, } from './sessions.js';
|
|
40
|
+
import { aggregateEventsFile, summaryToJson } from './stats.js';
|
|
41
|
+
// Server-rendered UI (htmx + Alpine, vendored). No client bundle - the
|
|
42
|
+
// fragments module renders finished HTML from the same payloads the JSON
|
|
43
|
+
// endpoints serve.
|
|
44
|
+
import { FICHE_ICON_SVG, renderPage, renderToggleFragment, renderModelsFragment, renderPluginsFragment, renderContextMapFragment, renderSessionSummaryFragment, renderHeaderFragment, renderAnalyticsFragment, renderRecentFragment, renderLatestFragment, renderSessionsFragment, renderStatsTableFragment, } from './dashboard/fragments.js';
|
|
45
|
+
export { FICHE_ICON_SVG };
|
|
46
|
+
import { readBrandEnv } from './core/env.js';
|
|
47
|
+
import { getCalibratedProfile, listCalibratedProfiles } from './core/calibration.js';
|
|
48
|
+
import { getGlobalMmuStore } from './core/context-mmu.js';
|
|
49
|
+
import { getGlobalPrefixTape } from './core/prefix-tape.js';
|
|
50
|
+
import { readerTier } from './core/reader-tier.js';
|
|
51
|
+
import { isTextHygieneActive } from './core/text-hygiene.js';
|
|
52
|
+
import { resolveOpticalHistoryPolicy } from './core/transform.js';
|
|
53
|
+
import { getAllowedModelBases, getConfiguredModelBases, isFicheSupportedModel, isInConfiguredModelBases, setAllowedModelBases, } from './core/applicability.js';
|
|
54
|
+
import { getEnabledProviders, listProviderStatuses, normalizeProviderId, parseProvidersSpec, setEnabledProviders, } from './core/upstream-hosts.js';
|
|
55
|
+
import { isThirdPartyPlugin, mergeStagePlugins, } from './core/stage-plugins.js';
|
|
56
|
+
const RECENT_CAP = 50;
|
|
57
|
+
const DAILY_CHART_DAYS = 14;
|
|
58
|
+
const MAX_DAILY_BUCKETS = 90;
|
|
59
|
+
const MAX_MODEL_KEYS = 256;
|
|
60
|
+
function localDateKey(ms) {
|
|
61
|
+
const d = new Date(ms);
|
|
62
|
+
const year = String(d.getFullYear()).padStart(4, '0');
|
|
63
|
+
const month = String(d.getMonth() + 1).padStart(2, '0');
|
|
64
|
+
const day = String(d.getDate()).padStart(2, '0');
|
|
65
|
+
return `${year}-${month}-${day}`;
|
|
66
|
+
}
|
|
67
|
+
function emptyDailyBucket() {
|
|
68
|
+
return {
|
|
69
|
+
requests: 0,
|
|
70
|
+
compressed: 0,
|
|
71
|
+
imaged: 0,
|
|
72
|
+
textCompressed: 0,
|
|
73
|
+
textHygieneSavedTokens: 0,
|
|
74
|
+
baselineInputWeighted: 0,
|
|
75
|
+
actualInputWeighted: 0,
|
|
76
|
+
rawSavedTokens: 0,
|
|
77
|
+
pricedBaselineInputWeighted: 0,
|
|
78
|
+
pricedActualInputWeighted: 0,
|
|
79
|
+
pricedSavedUsd: 0,
|
|
80
|
+
cliffSavedUsd: 0,
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
/** How many rendered PNGs to keep in the in-memory image ring. Matches
|
|
84
|
+
* RECENT_CAP so every visible recent-requests row can still resolve its
|
|
85
|
+
* image. Images are never written to disk — this ring is the only store. */
|
|
86
|
+
const IMAGE_RING_CAP = 50;
|
|
87
|
+
function emptyTotals(startedAt = Date.now() / 1000) {
|
|
88
|
+
return {
|
|
89
|
+
requests: 0,
|
|
90
|
+
compressedRequests: 0,
|
|
91
|
+
imagedRequests: 0,
|
|
92
|
+
textCompressedRequests: 0,
|
|
93
|
+
rawSavedTokens: 0,
|
|
94
|
+
actualInputWeighted: 0,
|
|
95
|
+
baselineInputWeighted: 0,
|
|
96
|
+
outputWeighted: 0,
|
|
97
|
+
pricedActualInputWeighted: 0,
|
|
98
|
+
pricedBaselineInputWeighted: 0,
|
|
99
|
+
pricedOutputWeighted: 0,
|
|
100
|
+
pricedSavedUsd: 0,
|
|
101
|
+
usdPricedRequests: 0,
|
|
102
|
+
usdUnpricedRequests: 0,
|
|
103
|
+
allBaselineEquivalentWeighted: 0,
|
|
104
|
+
allActualInputWeighted: 0,
|
|
105
|
+
allOutputWeighted: 0,
|
|
106
|
+
allUsageRequests: 0,
|
|
107
|
+
compressedPaidRequests: 0,
|
|
108
|
+
compressedActualInputWeighted: 0,
|
|
109
|
+
compressedOutputWeighted: 0,
|
|
110
|
+
passthroughPaidRequests: 0,
|
|
111
|
+
passthroughActualInputWeighted: 0,
|
|
112
|
+
passthroughOutputWeighted: 0,
|
|
113
|
+
textCharsMeasured: 0,
|
|
114
|
+
thinkingCharsMeasured: 0,
|
|
115
|
+
toolUseCharsMeasured: 0,
|
|
116
|
+
redactedBlockCountMeasured: 0,
|
|
117
|
+
eventsWithMeasurement: 0,
|
|
118
|
+
compressedActualUsdKosha: 0,
|
|
119
|
+
passthroughActualUsdKosha: 0,
|
|
120
|
+
textHygieneSavedTokens: 0,
|
|
121
|
+
textHygieneSavedChars: 0,
|
|
122
|
+
cliffAvoidedEvents: 0,
|
|
123
|
+
cliffSavedUsd: 0,
|
|
124
|
+
startedAt,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
/*
|
|
128
|
+
* ─────────────────────────────────────────────────────────────────────────
|
|
129
|
+
* PROVENANCE — every magic number below should trace to one of these:
|
|
130
|
+
*
|
|
131
|
+
* [docs-pricing] docs.anthropic.com/en/docs/about-claude/pricing
|
|
132
|
+
* Verified 2026-05-19 via WebFetch. The page lists per-model
|
|
133
|
+
* per-million-token rates and the cache-tier multipliers.
|
|
134
|
+
*
|
|
135
|
+
* [count_tokens] docs.anthropic.com/en/api/messages-count-tokens
|
|
136
|
+
* The dashboard's baseline number comes from a free side
|
|
137
|
+
* call to /v1/messages/count_tokens on the PRE-COMPRESSION
|
|
138
|
+
* body. No estimation, no α, no regression.
|
|
139
|
+
* ─────────────────────────────────────────────────────────────────────────
|
|
140
|
+
*/
|
|
141
|
+
/** Output-token rate multiplier (referenced to the input base rate).
|
|
142
|
+
* Source: [docs-pricing] — Opus 4.7 lists $5/Mtok input and $25/Mtok
|
|
143
|
+
* output (5×); Sonnet 4.7 lists $3/Mtok input and $15/Mtok output (5×).
|
|
144
|
+
* Same ratio holds on Haiku 4.5 ($1/$5). */
|
|
145
|
+
const OUTPUT_TOKEN_RATE = 5.0;
|
|
146
|
+
/** Per-million-token input rate ASSUMED for the headline dollar figure.
|
|
147
|
+
* Source: https://docs.claude.com/en/docs/about-claude/pricing — Opus 4.7
|
|
148
|
+
* input is $5/Mtok (same as Opus 4.5 / 4.6; the previous "$2.50" value
|
|
149
|
+
* here was a regression). Cache-write 5m = $6.25/Mtok (1.25×),
|
|
150
|
+
* cache-read = $0.50/Mtok (0.10×).
|
|
151
|
+
*
|
|
152
|
+
* This is exposed on /proxy-stats as `pricing_assumptions.input_per_mtok`
|
|
153
|
+
* so the operator can see what we assumed and override if they're
|
|
154
|
+
* running against a non-default deployment (Bedrock/Vertex add a 10%
|
|
155
|
+
* premium; Sonnet would be $3/Mtok, etc.).
|
|
156
|
+
*
|
|
157
|
+
* NOTE: Opus 4.7 uses a different tokenizer than 4.5/4.6 (per
|
|
158
|
+
* docs.claude.com/en/docs/about-claude/pricing), so even at the same
|
|
159
|
+
* $/Mtok rate, the same string maps to a different token count. The
|
|
160
|
+
* honest oracle for "tokens in this body" is `count_tokens` against the
|
|
161
|
+
* actual target model; do not trust hardcoded chars-per-token or
|
|
162
|
+
* tokens-per-image constants on 4.7 without verifying against the
|
|
163
|
+
* upstream probe. */
|
|
164
|
+
// 2026-06-09: gate is Fable-5-only and Fable 5 bills $10/MTok input,
|
|
165
|
+
// so the dashboard dollar figure uses that rate. Output tokens are
|
|
166
|
+
// excluded entirely (the proxy can't move them), so this still
|
|
167
|
+
// understates the real bill - treat it as "input-side $ saved".
|
|
168
|
+
export const ASSUMED_INPUT_USD_PER_MTOK = 10.0;
|
|
169
|
+
/** Route per-event accounting by upstream. OpenAI paths use the GPT cost
|
|
170
|
+
* model (vision-token imaging, automatic 0.1× prefix cache, no count_tokens
|
|
171
|
+
* probe, 8× output); everything else uses the Anthropic cache-aware baseline.
|
|
172
|
+
* Anthropic paths are `/v1/messages[/count_tokens]`; neither word appears. */
|
|
173
|
+
function isOpenAIEvent(path, accountingProvider) {
|
|
174
|
+
if (accountingProvider)
|
|
175
|
+
return accountingProvider === 'openai';
|
|
176
|
+
if (!path)
|
|
177
|
+
return false;
|
|
178
|
+
return path.includes('responses') || path.includes('chat/completions');
|
|
179
|
+
}
|
|
180
|
+
function googleEff(args) {
|
|
181
|
+
const { inputTokens: inp, outputTokens: out, compressed } = args;
|
|
182
|
+
const haveUsage = inp > 0 || out > 0;
|
|
183
|
+
const measuredBaseline = args.baselineProbeStatus === 'ok' && args.baselineTokens > 0
|
|
184
|
+
? args.baselineTokens
|
|
185
|
+
: 0;
|
|
186
|
+
const hygieneTok = Math.max(0, args.textHygieneSavedTokens ?? 0);
|
|
187
|
+
const estimatedBaseline = compressed
|
|
188
|
+
&& ((args.imageTokens > 0 && args.baselineImagedTokens > 0) || hygieneTok > 0)
|
|
189
|
+
? Math.max(0, inp - args.imageTokens - args.nativeInjectedTokens + args.baselineImagedTokens + hygieneTok)
|
|
190
|
+
: 0;
|
|
191
|
+
const baseline = measuredBaseline || estimatedBaseline;
|
|
192
|
+
const haveBaseline = baseline > 0;
|
|
193
|
+
const creditSaving = haveBaseline && haveUsage && compressed;
|
|
194
|
+
const cached = Math.min(inp, Math.max(0, args.cachedTokens ?? 0));
|
|
195
|
+
if (priceMode() === 'kosha') {
|
|
196
|
+
const rates = resolvePriceRates(args.model, { promptTokens: inp });
|
|
197
|
+
const actualInputEff = haveUsage ? (inp - cached) + cached * rates.read : 0;
|
|
198
|
+
let baselineInputEff = actualInputEff;
|
|
199
|
+
if (creditSaving) {
|
|
200
|
+
if (args.warmth?.selfBusted) {
|
|
201
|
+
const reused = Math.min(baseline, args.warmth.prevPrefixTokens);
|
|
202
|
+
baselineInputEff = reused * rates.read + (baseline - reused) * 1.0;
|
|
203
|
+
}
|
|
204
|
+
else {
|
|
205
|
+
const delta = baseline - inp;
|
|
206
|
+
baselineInputEff = actualInputEff + delta * (cached > 0 ? rates.read : 1);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
const outputEquiv = haveUsage ? out * rates.output : 0;
|
|
210
|
+
return {
|
|
211
|
+
haveUsage,
|
|
212
|
+
haveBaseline,
|
|
213
|
+
creditSaving,
|
|
214
|
+
actualInputEff,
|
|
215
|
+
baselineInputEff,
|
|
216
|
+
outputEquiv,
|
|
217
|
+
rawBaseline: creditSaving ? baseline : inp,
|
|
218
|
+
warmForRow: cached > 0 || Boolean(args.warmth?.warm),
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
let baselineInputEff = creditSaving ? baseline : inp;
|
|
222
|
+
if (creditSaving && args.warmth?.selfBusted) {
|
|
223
|
+
const rates = resolvePriceRates(args.model, { promptTokens: inp });
|
|
224
|
+
const reused = Math.min(baseline, args.warmth.prevPrefixTokens);
|
|
225
|
+
baselineInputEff = reused * rates.read + (baseline - reused) * 1.0;
|
|
226
|
+
}
|
|
227
|
+
return {
|
|
228
|
+
haveUsage,
|
|
229
|
+
haveBaseline,
|
|
230
|
+
creditSaving,
|
|
231
|
+
actualInputEff: inp,
|
|
232
|
+
baselineInputEff,
|
|
233
|
+
outputEquiv: out,
|
|
234
|
+
rawBaseline: creditSaving ? baseline : inp,
|
|
235
|
+
warmForRow: cached > 0 || Boolean(args.warmth?.warm),
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
function gptEff(args) {
|
|
239
|
+
const { model, inputTokens: inp, outputTokens: out, cachedTokens: cached } = args;
|
|
240
|
+
const { imageTokens, baselineImagedTokens, nativeInjectedTokens, compressed } = args;
|
|
241
|
+
const hygieneTok = Math.max(0, args.textHygieneSavedTokens ?? 0);
|
|
242
|
+
const haveUsage = inp > 0 || out > 0;
|
|
243
|
+
// The transform measured what the imaged content would have cost as o200k
|
|
244
|
+
// text (or deterministic text hygiene saved tokens); without it there is no
|
|
245
|
+
// counterfactual to credit.
|
|
246
|
+
const haveBaseline = baselineImagedTokens > 0 || hygieneTok > 0;
|
|
247
|
+
const actualInputEff = haveUsage ? computeOpenAIActualInputEff(inp, cached, model, args.cacheWriteTokens) : 0;
|
|
248
|
+
const creditSaving = haveBaseline && haveUsage && compressed;
|
|
249
|
+
const baselineInputEff = creditSaving
|
|
250
|
+
? computeOpenAISessionBaselineInputEff({
|
|
251
|
+
inputTokens: inp,
|
|
252
|
+
cachedTokens: cached,
|
|
253
|
+
imageTokens,
|
|
254
|
+
baselineImagedTokens,
|
|
255
|
+
nativeInjectedTokens,
|
|
256
|
+
textHygieneSavedTokens: hygieneTok,
|
|
257
|
+
cacheWriteTokens: args.cacheWriteTokens,
|
|
258
|
+
model,
|
|
259
|
+
warmth: args.warmth,
|
|
260
|
+
})
|
|
261
|
+
: actualInputEff;
|
|
262
|
+
const outputEquiv = haveUsage ? out * openAIOutputRate(model) : 0;
|
|
263
|
+
// Raw, rate-free token counts for the session's compression ratio and the
|
|
264
|
+
// Details panel: actual = what we sent; baseline = the text-only equivalent.
|
|
265
|
+
const rawActual = inp;
|
|
266
|
+
const rawBaseline = computeOpenAIBaselineRawTokens(inp, imageTokens, baselineImagedTokens, nativeInjectedTokens, hygieneTok);
|
|
267
|
+
return {
|
|
268
|
+
haveUsage,
|
|
269
|
+
haveBaseline,
|
|
270
|
+
creditSaving,
|
|
271
|
+
actualInputEff,
|
|
272
|
+
baselineInputEff,
|
|
273
|
+
outputEquiv,
|
|
274
|
+
rawActual,
|
|
275
|
+
rawBaseline,
|
|
276
|
+
};
|
|
277
|
+
}
|
|
278
|
+
function defaultDashboardVersion() {
|
|
279
|
+
return typeof __FICHE_VERSION__ !== 'undefined' ? __FICHE_VERSION__ : '0.19.0';
|
|
280
|
+
}
|
|
281
|
+
export class DashboardState {
|
|
282
|
+
recent = [];
|
|
283
|
+
/** Per-session dollar-weighted totals, keyed by `info.firstUserSha8`. The
|
|
284
|
+
* dashboard surfaces ONLY the most-recently-active session via the
|
|
285
|
+
* `serveCurrentSessionJson` endpoint — older sessions linger in the Map
|
|
286
|
+
* so a tab refresh during a brief lull still finds the previous session,
|
|
287
|
+
* but get evicted at `SESSION_CAP` to bound memory in long-running hosts. */
|
|
288
|
+
sessions = new Map();
|
|
289
|
+
/** sha8 of the most-recently-active session id. null when no events have
|
|
290
|
+
* ever carried a `firstUserSha8` (e.g. a cold start with only passthrough
|
|
291
|
+
* hits that the upstream probe never tagged). */
|
|
292
|
+
currentSessionId = null;
|
|
293
|
+
/** Per-session prior row for the cache-aware TEXT baseline. A fresh
|
|
294
|
+
* same-prefix prior makes the text path warm (see deriveBaselineWarmth) and
|
|
295
|
+
* sizes its reused vs grown prefix tokens. Reconstructed identically in
|
|
296
|
+
* replay() from persisted timestamps, so live and restored numbers agree.
|
|
297
|
+
* Capped with sessions. */
|
|
298
|
+
baselineWarmth = new Map();
|
|
299
|
+
openaiWarmth = new Map();
|
|
300
|
+
googleWarmth = new Map();
|
|
301
|
+
/** Default max age of a prior row that can still make the text path warm.
|
|
302
|
+
* A prior that wrote 1h-tier tokens carries its own 3600 s window instead. */
|
|
303
|
+
static CACHE_TTL_SEC = 300;
|
|
304
|
+
/** Hard cap on `sessions` Map entries. Keeps memory bounded in
|
|
305
|
+
* long-running deployments. 50 sessions × ~13 numeric fields each is
|
|
306
|
+
* comfortably under a MB even with fat bucket/passthrough histograms. */
|
|
307
|
+
static SESSION_CAP = 50;
|
|
308
|
+
startedAt = Date.now() / 1000;
|
|
309
|
+
/** Lifetime accounting partitioned by exact model id. The dashboard sums
|
|
310
|
+
* only currently enabled model families, so toggling a model updates the
|
|
311
|
+
* overall numbers without discarding its history. */
|
|
312
|
+
totalsByModel = new Map();
|
|
313
|
+
otherHasSupportedModel = false;
|
|
314
|
+
/** Daily accounting partitioned by local YYYY-MM-DD and exact model id.
|
|
315
|
+
* Capped to MAX_DAILY_BUCKETS days in memory. */
|
|
316
|
+
dailyByDateModel = new Map();
|
|
317
|
+
dailyOtherSupported = new Map();
|
|
318
|
+
apiStatsCache = null;
|
|
319
|
+
apiStatsInFlight = null;
|
|
320
|
+
apiSessionsCache = null;
|
|
321
|
+
apiSessionsInFlight = null;
|
|
322
|
+
/** Bounded ring of the most recently rendered images (last IMAGE_RING_CAP).
|
|
323
|
+
* Each request that rendered an image pushes one entry; the matching
|
|
324
|
+
* RecentRow carries `img_id` so the dashboard can pull any image still in
|
|
325
|
+
* the ring via /proxy-latest-png?id=N. In-memory only — images are never
|
|
326
|
+
* persisted, so a restart starts this empty. */
|
|
327
|
+
images = [];
|
|
328
|
+
/** Monotonic image id source. Never reset, never reused — an evicted id
|
|
329
|
+
* stays dangling on its RecentRow rather than pointing at a new image. */
|
|
330
|
+
nextImageId = 1;
|
|
331
|
+
/** Runtime kill switch for compression. When false, the proxy forwards
|
|
332
|
+
* /v1/messages unchanged to upstream — pure passthrough, no images,
|
|
333
|
+
* no transforms. Controlled by the dashboard "passthrough" toggle so
|
|
334
|
+
* the operator can toggle the proxy's transform instantly.
|
|
335
|
+
*
|
|
336
|
+
* Defaults to TRUE since 2026-06-09: scope is Fable 5 only, which reads
|
|
337
|
+
* renders at 100/100 (no Opus read tax) with the same image billing, and
|
|
338
|
+
* the live proxy record measured ~68% real input-token savings on dense
|
|
339
|
+
* traffic — the old off-default rationale ("cache-illusory savings")
|
|
340
|
+
* cited the superseded dead verdict. Grok stays opt-in until quality
|
|
341
|
+
* matches Fable. Verbatim recall is still lossy; the dashboard toggle
|
|
342
|
+
* remains the kill switch. See FINDINGS.md. */
|
|
343
|
+
compressionEnabled = true;
|
|
344
|
+
/** Recent requests' transform breakdowns, for the Context Map panel + its
|
|
345
|
+
* history selector. In-memory ring, newest last. */
|
|
346
|
+
contextHistory = [];
|
|
347
|
+
setCompressionEnabled(on) {
|
|
348
|
+
this.compressionEnabled = on;
|
|
349
|
+
}
|
|
350
|
+
getCompressionEnabled() {
|
|
351
|
+
return this.compressionEnabled;
|
|
352
|
+
}
|
|
353
|
+
/** Resolved disk paths for the events.jsonl + 4xx-bodies sidecar dir. The
|
|
354
|
+
* new sessions / cleanup endpoints need this; legacy callers that don't
|
|
355
|
+
* pass `paths` opt out of those endpoints by returning 503. */
|
|
356
|
+
paths;
|
|
357
|
+
/** Test hook: when set, /api/sessions.json and /api/sessions/${id}.json
|
|
358
|
+
* call this instead of `claudeCodeMap()` with the real `~/.claude/projects/`
|
|
359
|
+
* path. Lets unit tests run in tens of ms instead of scanning hundreds of
|
|
360
|
+
* the developer's actual Claude Code session files. */
|
|
361
|
+
ccMapFn;
|
|
362
|
+
/** Host-provided persistence hook for the runtime model scope. The core
|
|
363
|
+
* override stays in-memory (Edge-safe); a Node host passes a saver that
|
|
364
|
+
* writes the `models` key of the config file so chip toggles survive a
|
|
365
|
+
* restart. Best-effort: failures are the hook's problem, never the API's. */
|
|
366
|
+
persistModelBases;
|
|
367
|
+
hooks;
|
|
368
|
+
pluginOverrides = {};
|
|
369
|
+
constructor(paths, ccMapFn, persistModelBases, hooks = {}) {
|
|
370
|
+
this.paths = paths;
|
|
371
|
+
this.ccMapFn = ccMapFn ?? (() => claudeCodeMap());
|
|
372
|
+
this.persistModelBases = persistModelBases;
|
|
373
|
+
this.hooks = hooks;
|
|
374
|
+
}
|
|
375
|
+
lruGet(map, key) {
|
|
376
|
+
const val = map.get(key);
|
|
377
|
+
if (val !== undefined) {
|
|
378
|
+
map.delete(key);
|
|
379
|
+
map.set(key, val);
|
|
380
|
+
}
|
|
381
|
+
return val;
|
|
382
|
+
}
|
|
383
|
+
lruSet(map, key, val, cap) {
|
|
384
|
+
if (map.has(key))
|
|
385
|
+
map.delete(key);
|
|
386
|
+
map.set(key, val);
|
|
387
|
+
while (map.size > cap) {
|
|
388
|
+
const firstKey = map.keys().next().value;
|
|
389
|
+
if (firstKey === undefined)
|
|
390
|
+
break;
|
|
391
|
+
map.delete(firstKey);
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
isModelIncludedInStats(model, textHygieneSavedTokens, otherSupported = false) {
|
|
395
|
+
return (isInConfiguredModelBases(model) ||
|
|
396
|
+
isFicheSupportedModel(model) ||
|
|
397
|
+
textHygieneSavedTokens > 0 ||
|
|
398
|
+
(model === 'other' && otherSupported));
|
|
399
|
+
}
|
|
400
|
+
totalsForModel(model) {
|
|
401
|
+
const rawKey = model ?? '';
|
|
402
|
+
let key = rawKey;
|
|
403
|
+
if (!this.totalsByModel.has(rawKey) &&
|
|
404
|
+
(this.totalsByModel.size >= MAX_MODEL_KEYS ||
|
|
405
|
+
(this.totalsByModel.size === MAX_MODEL_KEYS - 1 && !this.totalsByModel.has('other')))) {
|
|
406
|
+
key = 'other';
|
|
407
|
+
if (isInConfiguredModelBases(rawKey) || isFicheSupportedModel(rawKey)) {
|
|
408
|
+
this.otherHasSupportedModel = true;
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
let totals = this.totalsByModel.get(key);
|
|
412
|
+
if (!totals) {
|
|
413
|
+
totals = emptyTotals(this.startedAt);
|
|
414
|
+
this.totalsByModel.set(key, totals);
|
|
415
|
+
}
|
|
416
|
+
return totals;
|
|
417
|
+
}
|
|
418
|
+
enabledTotals() {
|
|
419
|
+
const combined = emptyTotals(this.startedAt);
|
|
420
|
+
for (const [model, totals] of this.totalsByModel) {
|
|
421
|
+
if (!this.isModelIncludedInStats(model, totals.textHygieneSavedTokens, this.otherHasSupportedModel))
|
|
422
|
+
continue;
|
|
423
|
+
for (const key of Object.keys(combined)) {
|
|
424
|
+
if (key !== 'startedAt')
|
|
425
|
+
combined[key] += totals[key];
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
return combined;
|
|
429
|
+
}
|
|
430
|
+
dailyBucketFor(dateKey, model) {
|
|
431
|
+
let byModel = this.dailyByDateModel.get(dateKey);
|
|
432
|
+
if (!byModel) {
|
|
433
|
+
byModel = new Map();
|
|
434
|
+
this.dailyByDateModel.set(dateKey, byModel);
|
|
435
|
+
if (this.dailyByDateModel.size > MAX_DAILY_BUCKETS) {
|
|
436
|
+
let oldestKey;
|
|
437
|
+
for (const k of this.dailyByDateModel.keys()) {
|
|
438
|
+
if (oldestKey === undefined || k < oldestKey)
|
|
439
|
+
oldestKey = k;
|
|
440
|
+
}
|
|
441
|
+
if (oldestKey !== undefined) {
|
|
442
|
+
this.dailyByDateModel.delete(oldestKey);
|
|
443
|
+
this.dailyOtherSupported.delete(oldestKey);
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
const rawKey = model ?? '';
|
|
448
|
+
let modelKey = rawKey;
|
|
449
|
+
if (!byModel.has(rawKey) &&
|
|
450
|
+
(byModel.size >= MAX_MODEL_KEYS ||
|
|
451
|
+
(byModel.size === MAX_MODEL_KEYS - 1 && !byModel.has('other')))) {
|
|
452
|
+
modelKey = 'other';
|
|
453
|
+
if (isInConfiguredModelBases(rawKey) || isFicheSupportedModel(rawKey)) {
|
|
454
|
+
this.dailyOtherSupported.set(dateKey, true);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
let bucket = byModel.get(modelKey);
|
|
458
|
+
if (!bucket) {
|
|
459
|
+
bucket = emptyDailyBucket();
|
|
460
|
+
byModel.set(modelKey, bucket);
|
|
461
|
+
}
|
|
462
|
+
return bucket;
|
|
463
|
+
}
|
|
464
|
+
classifyCompressionMode(compressed, imageCount, hygieneTok, hygieneStages, reason) {
|
|
465
|
+
const textOnlyCompressed = compressed &&
|
|
466
|
+
imageCount === 0 &&
|
|
467
|
+
(hygieneTok > 0 || (hygieneStages?.length ?? 0) > 0 || reason === 'text_hygiene');
|
|
468
|
+
const opticalCompressed = compressed && !textOnlyCompressed;
|
|
469
|
+
const compressionMode = opticalCompressed
|
|
470
|
+
? 'optical'
|
|
471
|
+
: textOnlyCompressed
|
|
472
|
+
? 'text'
|
|
473
|
+
: 'none';
|
|
474
|
+
return { opticalCompressed, textOnlyCompressed, compressionMode };
|
|
475
|
+
}
|
|
476
|
+
recordAccumulators(args) {
|
|
477
|
+
const { model, eventMs, compressed, opticalCompressed, textOnlyCompressed, haveUsage, creditSaving, dollarEligible, actualInputEff, baselineInputEff, outputEquiv, rawActual, rawBaseline, inp, out, cc, cr, cc1h, cachedTok, writeTok, googleOrGpt, sid, hygieneTok, hygieneChars, cliffAvoided, cliffUsd, measurement, } = args;
|
|
478
|
+
const totals = this.totalsForModel(model);
|
|
479
|
+
const daily = this.dailyBucketFor(localDateKey(eventMs), model);
|
|
480
|
+
totals.requests += 1;
|
|
481
|
+
daily.requests += 1;
|
|
482
|
+
if (compressed) {
|
|
483
|
+
totals.compressedRequests += 1;
|
|
484
|
+
daily.compressed += 1;
|
|
485
|
+
}
|
|
486
|
+
if (opticalCompressed) {
|
|
487
|
+
totals.imagedRequests += 1;
|
|
488
|
+
daily.imaged += 1;
|
|
489
|
+
}
|
|
490
|
+
if (textOnlyCompressed) {
|
|
491
|
+
totals.textCompressedRequests += 1;
|
|
492
|
+
daily.textCompressed += 1;
|
|
493
|
+
}
|
|
494
|
+
if (hygieneTok > 0) {
|
|
495
|
+
totals.textHygieneSavedTokens += hygieneTok;
|
|
496
|
+
daily.textHygieneSavedTokens += hygieneTok;
|
|
497
|
+
}
|
|
498
|
+
if (hygieneChars > 0)
|
|
499
|
+
totals.textHygieneSavedChars += hygieneChars;
|
|
500
|
+
if (cliffAvoided) {
|
|
501
|
+
totals.cliffAvoidedEvents += 1;
|
|
502
|
+
totals.cliffSavedUsd += cliffUsd;
|
|
503
|
+
daily.cliffSavedUsd += cliffUsd;
|
|
504
|
+
}
|
|
505
|
+
const rawSaved = creditSaving && rawBaseline > 0 ? rawBaseline - rawActual : 0;
|
|
506
|
+
if (creditSaving) {
|
|
507
|
+
totals.baselineInputWeighted += baselineInputEff;
|
|
508
|
+
totals.actualInputWeighted += actualInputEff;
|
|
509
|
+
totals.outputWeighted += outputEquiv;
|
|
510
|
+
totals.rawSavedTokens += rawSaved;
|
|
511
|
+
daily.baselineInputWeighted += baselineInputEff;
|
|
512
|
+
daily.actualInputWeighted += actualInputEff;
|
|
513
|
+
daily.rawSavedTokens += rawSaved;
|
|
514
|
+
if (dollarEligible) {
|
|
515
|
+
totals.pricedBaselineInputWeighted += baselineInputEff;
|
|
516
|
+
totals.pricedActualInputWeighted += actualInputEff;
|
|
517
|
+
totals.pricedOutputWeighted += outputEquiv;
|
|
518
|
+
daily.pricedBaselineInputWeighted += baselineInputEff;
|
|
519
|
+
daily.pricedActualInputWeighted += actualInputEff;
|
|
520
|
+
const usdPerMtok = inputUsdPerMtok(model, { promptTokens: inp + cc + cr, at: eventMs });
|
|
521
|
+
if (usdPerMtok !== undefined) {
|
|
522
|
+
const rowUsd = ((baselineInputEff - actualInputEff) * usdPerMtok) / 1e6;
|
|
523
|
+
const effectiveRowUsd = rowUsd < 0
|
|
524
|
+
? rowUsd
|
|
525
|
+
: (cliffAvoided && cliffUsd > 0 ? Math.max(rowUsd, cliffUsd) : rowUsd);
|
|
526
|
+
totals.pricedSavedUsd += effectiveRowUsd;
|
|
527
|
+
totals.usdPricedRequests += 1;
|
|
528
|
+
daily.pricedSavedUsd += effectiveRowUsd;
|
|
529
|
+
}
|
|
530
|
+
else {
|
|
531
|
+
totals.usdUnpricedRequests += 1;
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
if (haveUsage && dollarEligible) {
|
|
536
|
+
totals.allBaselineEquivalentWeighted += baselineInputEff;
|
|
537
|
+
totals.allActualInputWeighted += actualInputEff;
|
|
538
|
+
totals.allOutputWeighted += outputEquiv;
|
|
539
|
+
totals.allUsageRequests += 1;
|
|
540
|
+
let rowActualUsdKosha = 0;
|
|
541
|
+
if (priceMode() === 'kosha') {
|
|
542
|
+
const bill = googleOrGpt
|
|
543
|
+
? estimateBillUsd(model, {
|
|
544
|
+
uncachedTokens: Math.max(0, inp - cachedTok - writeTok),
|
|
545
|
+
cachedTokens: cachedTok,
|
|
546
|
+
cacheWriteTokens: writeTok,
|
|
547
|
+
outputTokens: out,
|
|
548
|
+
promptTokens: inp,
|
|
549
|
+
at: eventMs,
|
|
550
|
+
})
|
|
551
|
+
: estimateBillUsd(model, {
|
|
552
|
+
uncachedTokens: inp,
|
|
553
|
+
cachedTokens: cr,
|
|
554
|
+
cacheWriteTokens: cc,
|
|
555
|
+
outputTokens: out,
|
|
556
|
+
ttlSec: cc1h > 0 && cc1h >= cc ? 3600 : 300,
|
|
557
|
+
promptTokens: inp + cc + cr,
|
|
558
|
+
at: eventMs,
|
|
559
|
+
});
|
|
560
|
+
rowActualUsdKosha = bill ?? ((actualInputEff + outputEquiv) * ASSUMED_INPUT_USD_PER_MTOK) / 1e6;
|
|
561
|
+
}
|
|
562
|
+
if (compressed) {
|
|
563
|
+
totals.compressedPaidRequests += 1;
|
|
564
|
+
totals.compressedActualInputWeighted += actualInputEff;
|
|
565
|
+
totals.compressedOutputWeighted += outputEquiv;
|
|
566
|
+
totals.compressedActualUsdKosha += rowActualUsdKosha;
|
|
567
|
+
}
|
|
568
|
+
else {
|
|
569
|
+
totals.passthroughPaidRequests += 1;
|
|
570
|
+
totals.passthroughActualInputWeighted += actualInputEff;
|
|
571
|
+
totals.passthroughOutputWeighted += outputEquiv;
|
|
572
|
+
totals.passthroughActualUsdKosha += rowActualUsdKosha;
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
if (typeof sid === 'string' && sid.length > 0) {
|
|
576
|
+
this.currentSessionId = sid;
|
|
577
|
+
let s = this.lruGet(this.sessions, sid);
|
|
578
|
+
if (!s) {
|
|
579
|
+
s = {
|
|
580
|
+
sessionId: sid,
|
|
581
|
+
baselineInputWeighted: 0,
|
|
582
|
+
actualInputWeighted: 0,
|
|
583
|
+
baselineMeasuredCount: 0,
|
|
584
|
+
allActualInputWeighted: 0,
|
|
585
|
+
allOutputWeighted: 0,
|
|
586
|
+
rawActualTokens: 0,
|
|
587
|
+
rawBaselineTokens: 0,
|
|
588
|
+
rawOutputTokens: 0,
|
|
589
|
+
};
|
|
590
|
+
this.lruSet(this.sessions, sid, s, DashboardState.SESSION_CAP);
|
|
591
|
+
}
|
|
592
|
+
if (creditSaving && dollarEligible) {
|
|
593
|
+
s.baselineInputWeighted += baselineInputEff;
|
|
594
|
+
s.actualInputWeighted += actualInputEff;
|
|
595
|
+
s.baselineMeasuredCount += 1;
|
|
596
|
+
s.rawActualTokens += rawActual;
|
|
597
|
+
s.rawBaselineTokens += rawBaseline;
|
|
598
|
+
s.rawOutputTokens += out;
|
|
599
|
+
}
|
|
600
|
+
if (haveUsage && dollarEligible) {
|
|
601
|
+
s.allActualInputWeighted += actualInputEff;
|
|
602
|
+
s.allOutputWeighted += outputEquiv;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
if (measurement) {
|
|
606
|
+
totals.textCharsMeasured += measurement.textChars;
|
|
607
|
+
totals.thinkingCharsMeasured += measurement.thinkingChars;
|
|
608
|
+
totals.toolUseCharsMeasured += measurement.toolUseChars;
|
|
609
|
+
totals.redactedBlockCountMeasured += measurement.redactedBlockCount;
|
|
610
|
+
totals.eventsWithMeasurement += 1;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
/** Stash every rendered image into the ring (called from onRequest with the
|
|
614
|
+
* raw ProxyEvent before info.firstImagePng is dropped by toTrackEvent).
|
|
615
|
+
* Returns the assigned image ids in render order; empty array when there
|
|
616
|
+
* are no images. The caller stamps ids[0] onto the RecentRow as `img_id`
|
|
617
|
+
* for back-compat and the full list as `img_ids`. */
|
|
618
|
+
captureImage(info) {
|
|
619
|
+
const pngs = info.imagePngs ?? (info.firstImagePng ? [info.firstImagePng] : []);
|
|
620
|
+
if (pngs.length === 0)
|
|
621
|
+
return [];
|
|
622
|
+
const dims = info.imageDims ??
|
|
623
|
+
(info.firstImagePng
|
|
624
|
+
? [{ width: info.firstImageWidth ?? 0, height: info.firstImageHeight ?? 0 }]
|
|
625
|
+
: []);
|
|
626
|
+
const ids = [];
|
|
627
|
+
for (let i = 0; i < pngs.length; i++) {
|
|
628
|
+
const id = this.nextImageId++;
|
|
629
|
+
const width = dims[i]?.width ?? 0;
|
|
630
|
+
const height = dims[i]?.height ?? 0;
|
|
631
|
+
const kb = (pngs[i].length / 1024).toFixed(1);
|
|
632
|
+
const meta = `${width}×${height} · ${kb} KB · image ${i + 1}/${pngs.length}`;
|
|
633
|
+
this.images.push({
|
|
634
|
+
id,
|
|
635
|
+
png: pngs[i],
|
|
636
|
+
meta,
|
|
637
|
+
width,
|
|
638
|
+
height,
|
|
639
|
+
ts: Date.now() / 1000,
|
|
640
|
+
sourceText: info.imageSourceTexts?.[i] ?? info.imageSourceText,
|
|
641
|
+
});
|
|
642
|
+
ids.push(id);
|
|
643
|
+
}
|
|
644
|
+
// Evict the oldest entries past the cap. splice() keeps insertion order
|
|
645
|
+
// so images[images.length - 1] is always the latest render.
|
|
646
|
+
if (this.images.length > IMAGE_RING_CAP) {
|
|
647
|
+
this.images.splice(0, this.images.length - IMAGE_RING_CAP);
|
|
648
|
+
}
|
|
649
|
+
return ids;
|
|
650
|
+
}
|
|
651
|
+
/** Fold one event into the running totals + ring buffer.
|
|
652
|
+
*
|
|
653
|
+
* Savings math is gated on a per-request `baseline_tokens` measurement
|
|
654
|
+
* from the parallel count_tokens probe or model-profile estimation (Google/GPT),
|
|
655
|
+
* plus an upstream usage block. When both probe and estimation are missing,
|
|
656
|
+
* we still count the request but skip its savings contribution. */
|
|
657
|
+
update(ev) {
|
|
658
|
+
// Stash the image bytes before they get GC'd by the request finishing.
|
|
659
|
+
// The returned id (if any) is stamped onto this request's RecentRow so
|
|
660
|
+
// the dashboard can pull the exact image that request rendered.
|
|
661
|
+
const imgIds = ev.info?.compressed ? this.captureImage(ev.info) : [];
|
|
662
|
+
const imgId = imgIds[0];
|
|
663
|
+
const u = ev.usage;
|
|
664
|
+
const info = ev.info;
|
|
665
|
+
const compressed = info?.compressed === true;
|
|
666
|
+
const eventMs = Date.now();
|
|
667
|
+
const inp = u?.input_tokens ?? 0;
|
|
668
|
+
const out = u?.output_tokens ?? 0;
|
|
669
|
+
const cc = u?.cache_creation_input_tokens ?? 0;
|
|
670
|
+
const cc5m = u?.cache_creation?.ephemeral_5m_input_tokens;
|
|
671
|
+
const cc1h = u?.cache_creation?.ephemeral_1h_input_tokens ?? 0;
|
|
672
|
+
const cr = u?.cache_read_input_tokens ?? 0;
|
|
673
|
+
const gpt = isOpenAIEvent(ev.path, ev.accountingProvider);
|
|
674
|
+
const google = ev.accountingProvider === 'google'
|
|
675
|
+
|| ev.path.includes('google-ai-studio') || ev.path.toLowerCase().includes('generatecontent');
|
|
676
|
+
// Unified per-row accounting, filled by the provider branch below. The
|
|
677
|
+
// downstream totals / per-session / recent-row code reads only these —
|
|
678
|
+
// it never re-derives cache math, so Anthropic and GPT can't drift.
|
|
679
|
+
let haveUsage;
|
|
680
|
+
let haveBaseline;
|
|
681
|
+
let creditSaving;
|
|
682
|
+
let actualInputEff;
|
|
683
|
+
let baselineInputEff;
|
|
684
|
+
let outputEquiv;
|
|
685
|
+
let rawActual; // raw tokens sent (session ratio + Details realInput)
|
|
686
|
+
let rawBaseline; // raw text-only counterfactual tokens
|
|
687
|
+
let baselineForRow; // baseline token count for contextHistory/recent
|
|
688
|
+
let cacheReadForRow; // tokens to surface in the "Cache hits" column
|
|
689
|
+
let warmForRow; // did the TEXT baseline read warm? Server-observed:
|
|
690
|
+
// Anthropic cr>0 or GPT cached_tokens>0. Drives Context Map narration.
|
|
691
|
+
if (google) {
|
|
692
|
+
const sidGoogle = info?.firstUserSha8;
|
|
693
|
+
const cachedGoogle = u?.cached_tokens ?? 0;
|
|
694
|
+
const completionSecGoogle = eventMs / 1000;
|
|
695
|
+
const requestStartSecGoogle = completionSecGoogle - Math.max(0, ev.durationMs || 0) / 1000;
|
|
696
|
+
const googlePrev = typeof sidGoogle === 'string' && sidGoogle.length > 0
|
|
697
|
+
? this.lruGet(this.googleWarmth, sidGoogle)
|
|
698
|
+
: undefined;
|
|
699
|
+
const pxShaGoogle = info?.cachePrefixSha8 ?? info?.historyImageSha;
|
|
700
|
+
const warmthGoogle = deriveOpenAIBaselineWarmth(googlePrev, requestStartSecGoogle, cachedGoogle, info?.systemSha8, ev.model, DashboardState.CACHE_TTL_SEC, pxShaGoogle);
|
|
701
|
+
const e = googleEff({
|
|
702
|
+
model: ev.model,
|
|
703
|
+
inputTokens: inp,
|
|
704
|
+
outputTokens: out,
|
|
705
|
+
cachedTokens: cachedGoogle,
|
|
706
|
+
compressed,
|
|
707
|
+
baselineTokens: info?.baselineTokens ?? 0,
|
|
708
|
+
baselineProbeStatus: info?.baselineProbeStatus,
|
|
709
|
+
imageTokens: info?.imageTokens ?? 0,
|
|
710
|
+
baselineImagedTokens: info?.baselineImagedTokens ?? 0,
|
|
711
|
+
nativeInjectedTokens: info?.nativeInjectedTokens ?? 0,
|
|
712
|
+
textHygieneSavedTokens: info?.textHygieneSavedTokens ?? 0,
|
|
713
|
+
warmth: warmthGoogle,
|
|
714
|
+
});
|
|
715
|
+
if (typeof sidGoogle === 'string' && sidGoogle.length > 0 && e.haveUsage) {
|
|
716
|
+
this.lruSet(this.googleWarmth, sidGoogle, {
|
|
717
|
+
ts: completionSecGoogle,
|
|
718
|
+
cachedOrPrefixTokens: cachedGoogle > 0 ? cachedGoogle : Math.max(googlePrev?.cachedOrPrefixTokens ?? 0, inp),
|
|
719
|
+
prefixSha: info?.systemSha8 ?? googlePrev?.prefixSha,
|
|
720
|
+
pxPrefixSha: pxShaGoogle ?? googlePrev?.pxPrefixSha,
|
|
721
|
+
model: ev.model ?? googlePrev?.model,
|
|
722
|
+
}, DashboardState.SESSION_CAP);
|
|
723
|
+
}
|
|
724
|
+
haveUsage = e.haveUsage;
|
|
725
|
+
haveBaseline = e.haveBaseline;
|
|
726
|
+
creditSaving = e.creditSaving;
|
|
727
|
+
actualInputEff = e.actualInputEff;
|
|
728
|
+
baselineInputEff = e.baselineInputEff;
|
|
729
|
+
outputEquiv = e.outputEquiv;
|
|
730
|
+
rawActual = inp;
|
|
731
|
+
rawBaseline = e.rawBaseline;
|
|
732
|
+
baselineForRow = creditSaving ? e.rawBaseline : 0;
|
|
733
|
+
cacheReadForRow = cachedGoogle;
|
|
734
|
+
warmForRow = e.warmForRow;
|
|
735
|
+
}
|
|
736
|
+
else if (gpt) {
|
|
737
|
+
const sidGpt = info?.firstUserSha8;
|
|
738
|
+
const cachedGpt = u?.cached_tokens ?? 0;
|
|
739
|
+
const completionSecGpt = Date.now() / 1000;
|
|
740
|
+
const requestStartSecGpt = completionSecGpt - Math.max(0, ev.durationMs || 0) / 1000;
|
|
741
|
+
const gptPrev = typeof sidGpt === 'string' && sidGpt.length > 0
|
|
742
|
+
? this.lruGet(this.openaiWarmth, sidGpt)
|
|
743
|
+
: undefined;
|
|
744
|
+
const pxShaGpt = info?.cachePrefixSha8 ?? info?.historyImageSha;
|
|
745
|
+
const warmthGpt = deriveOpenAIBaselineWarmth(gptPrev, requestStartSecGpt, cachedGpt, info?.systemSha8, ev.model, OPENAI_CACHE_TTL_SEC, pxShaGpt);
|
|
746
|
+
const e = gptEff({
|
|
747
|
+
model: ev.model,
|
|
748
|
+
inputTokens: inp,
|
|
749
|
+
outputTokens: out,
|
|
750
|
+
cachedTokens: cachedGpt,
|
|
751
|
+
cacheWriteTokens: u?.cache_write_tokens ?? 0,
|
|
752
|
+
imageTokens: info?.imageTokens ?? 0,
|
|
753
|
+
baselineImagedTokens: info?.baselineImagedTokens ?? 0,
|
|
754
|
+
nativeInjectedTokens: info?.nativeInjectedTokens ?? 0,
|
|
755
|
+
textHygieneSavedTokens: info?.textHygieneSavedTokens ?? 0,
|
|
756
|
+
warmth: warmthGpt,
|
|
757
|
+
compressed,
|
|
758
|
+
});
|
|
759
|
+
if (typeof sidGpt === 'string' && sidGpt.length > 0 && e.haveUsage) {
|
|
760
|
+
this.lruSet(this.openaiWarmth, sidGpt, {
|
|
761
|
+
ts: completionSecGpt,
|
|
762
|
+
cachedOrPrefixTokens: cachedGpt > 0 ? cachedGpt : Math.max(gptPrev?.cachedOrPrefixTokens ?? 0, inp),
|
|
763
|
+
prefixSha: info?.systemSha8 ?? gptPrev?.prefixSha,
|
|
764
|
+
pxPrefixSha: pxShaGpt ?? gptPrev?.pxPrefixSha,
|
|
765
|
+
model: ev.model ?? gptPrev?.model,
|
|
766
|
+
}, DashboardState.SESSION_CAP);
|
|
767
|
+
}
|
|
768
|
+
haveUsage = e.haveUsage;
|
|
769
|
+
haveBaseline = e.haveBaseline;
|
|
770
|
+
creditSaving = e.creditSaving;
|
|
771
|
+
actualInputEff = e.actualInputEff;
|
|
772
|
+
baselineInputEff = e.baselineInputEff;
|
|
773
|
+
outputEquiv = e.outputEquiv;
|
|
774
|
+
rawActual = e.rawActual;
|
|
775
|
+
rawBaseline = e.rawBaseline;
|
|
776
|
+
baselineForRow = e.rawBaseline;
|
|
777
|
+
cacheReadForRow = cachedGpt;
|
|
778
|
+
warmForRow = warmthGpt.warm;
|
|
779
|
+
}
|
|
780
|
+
else {
|
|
781
|
+
haveUsage = u !== undefined && (inp > 0 || out > 0 || cc > 0 || cr > 0);
|
|
782
|
+
const baseline = info?.baselineTokens;
|
|
783
|
+
// Honest gating: only attribute savings when BOTH baseline probes
|
|
784
|
+
// resolved (status === 'ok'). When the cacheable-prefix probe failed
|
|
785
|
+
// (status === 'partial') we previously fell through to cacheable=0,
|
|
786
|
+
// which silently charges the unproxied counterfactual the cold-input
|
|
787
|
+
// rate on tokens that actually would have been cache-discounted —
|
|
788
|
+
// fabricating "$ saved". Excluding the row is the only honest move
|
|
789
|
+
// until the probe succeeds.
|
|
790
|
+
const probeOk = isUsableAnthropicBaselineProbe({
|
|
791
|
+
baselineTokens: baseline,
|
|
792
|
+
probeStatus: info?.baselineProbeStatus,
|
|
793
|
+
threadContinue: info?.threadContinue,
|
|
794
|
+
cacheReadTokens: cr,
|
|
795
|
+
});
|
|
796
|
+
haveBaseline = typeof baseline === 'number' && baseline > 0 && probeOk;
|
|
797
|
+
// Weighted INPUT cost we actually paid this turn.
|
|
798
|
+
actualInputEff = haveUsage
|
|
799
|
+
? computeActualInputEffWithCacheTier(inp, cc, cr, cc1h, cc5m, anthropicReadRate(ev.model))
|
|
800
|
+
: 0;
|
|
801
|
+
// inkling only reduces input by imaging the static slab. An UNCOMPRESSED
|
|
802
|
+
// row had its body forwarded untouched, so its unproxied counterfactual
|
|
803
|
+
// IS exactly what it paid — crediting the cache-modeled baseline there
|
|
804
|
+
// (which prices the prefix at the cache-READ rate) fabricates savings on
|
|
805
|
+
// passthrough traffic. Only credit the counterfactual when the row was
|
|
806
|
+
// actually compressed AND we have a usable probe.
|
|
807
|
+
creditSaving = haveBaseline && haveUsage && compressed;
|
|
808
|
+
// Cache-aware baseline. INVARIANT: inkling is credited ONLY for the text it
|
|
809
|
+
// imaged away — NEVER for caching. The imagined text path is warm when
|
|
810
|
+
// cr>0, or when a same-prefix prior completed within the TTL (text would
|
|
811
|
+
// have read its own cache even if inkling's image busted the real one).
|
|
812
|
+
// Uncompressed rows fall back to actualInputEff → zero savings.
|
|
813
|
+
const cacheable = info?.baselineCacheableTokens ?? 0;
|
|
814
|
+
// Use request start for the prior lookup; an overlapping request that had
|
|
815
|
+
// not completed could not have warmed the text cache for this one.
|
|
816
|
+
const sidNow = info?.firstUserSha8;
|
|
817
|
+
const prefixShaNow = info?.systemSha8;
|
|
818
|
+
const completionSec = Date.now() / 1000;
|
|
819
|
+
const requestStartSec = completionSec - Math.max(0, ev.durationMs || 0) / 1000;
|
|
820
|
+
const warmthPrev = typeof sidNow === 'string' && sidNow.length > 0
|
|
821
|
+
? this.lruGet(this.baselineWarmth, sidNow)
|
|
822
|
+
: undefined;
|
|
823
|
+
// Centralised in deriveBaselineWarmth so update()/replay()/sessions can't drift.
|
|
824
|
+
const toolsShaNow = info?.cachePrefixToolsSha8;
|
|
825
|
+
const { warm, prevCacheable } = deriveBaselineWarmth(warmthPrev, requestStartSec, cacheable, cr, DashboardState.CACHE_TTL_SEC, prefixShaNow, toolsShaNow, { pxPrefixSha: info?.cachePrefixSha8, model: ev.model });
|
|
826
|
+
const readRateNow = anthropicReadRate(ev.model);
|
|
827
|
+
baselineInputEff = creditSaving
|
|
828
|
+
? computeBaselineInputEffWithCacheTier(baseline, cacheable, inp, cc, cr, warm, prevCacheable, cc1h, cc5m, readRateNow)
|
|
829
|
+
: actualInputEff;
|
|
830
|
+
const hygieneTok = info?.textHygieneSavedTokens ?? 0;
|
|
831
|
+
if (!haveBaseline && compressed && haveUsage && hygieneTok > 0 && (info?.imageCount ?? 0) === 0) {
|
|
832
|
+
haveBaseline = true;
|
|
833
|
+
creditSaving = true;
|
|
834
|
+
if (warm && cr === 0) {
|
|
835
|
+
const unproxiedRaw = inp + cc + hygieneTok;
|
|
836
|
+
const reusedTarget = prevCacheable > 0 ? prevCacheable : (warmthPrev?.observedCachedTokens ?? 0);
|
|
837
|
+
if (reusedTarget > 0) {
|
|
838
|
+
const reused = Math.min(unproxiedRaw, reusedTarget);
|
|
839
|
+
const createRate = cc > 0 ? (cc1h > 0 && cc1h >= cc ? 2.0 : 1.25) : 1.0;
|
|
840
|
+
baselineInputEff = reused * readRateNow + (unproxiedRaw - reused) * createRate;
|
|
841
|
+
}
|
|
842
|
+
else {
|
|
843
|
+
baselineInputEff = actualInputEff + hygieneTok * readRateNow;
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
else {
|
|
847
|
+
const deltaWeight = cr > 0
|
|
848
|
+
? readRateNow
|
|
849
|
+
: cc > 0 ? (cc1h > 0 && cc1h >= cc ? 2.0 : 1.25) : 1.0;
|
|
850
|
+
baselineInputEff = actualInputEff + hygieneTok * deltaWeight;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
// Record this completed turn's prefix for later warmth/split decisions.
|
|
854
|
+
// Carry the prior cacheable when this row has no probe.
|
|
855
|
+
if (typeof sidNow === 'string' && sidNow.length > 0 && haveUsage) {
|
|
856
|
+
this.lruSet(this.baselineWarmth, sidNow, {
|
|
857
|
+
ts: completionSec,
|
|
858
|
+
cacheable: cacheable > 0 ? cacheable : (warmthPrev?.cacheable ?? 0),
|
|
859
|
+
prefixSha: prefixShaNow ?? warmthPrev?.prefixSha,
|
|
860
|
+
toolsSha: toolsShaNow ?? warmthPrev?.toolsSha,
|
|
861
|
+
pxPrefixSha: info?.cachePrefixSha8 ?? warmthPrev?.pxPrefixSha,
|
|
862
|
+
model: ev.model ?? warmthPrev?.model,
|
|
863
|
+
ttlSec: observedCacheTtlSec(cc1h, warmthPrev?.ttlSec),
|
|
864
|
+
observedCachedTokens: cr > 0 || cc > 0 ? cr + cc : warmthPrev?.observedCachedTokens,
|
|
865
|
+
}, DashboardState.SESSION_CAP);
|
|
866
|
+
}
|
|
867
|
+
// Output tokens are identical with/without compression — the proxy never
|
|
868
|
+
// touches the response body. They show up on BOTH sides of the savings
|
|
869
|
+
// ratio at their actual rate (resolvePriceRates(model).output × input rate) so the
|
|
870
|
+
// denominator reflects the full bill the user actually pays.
|
|
871
|
+
outputEquiv = haveUsage
|
|
872
|
+
? out * resolvePriceRates(ev.model, { promptTokens: inp + cc + cr, at: eventMs }).output
|
|
873
|
+
: 0;
|
|
874
|
+
rawActual = inp + cc + cr;
|
|
875
|
+
rawBaseline = probeOk && typeof baseline === 'number'
|
|
876
|
+
? baseline
|
|
877
|
+
: (creditSaving && hygieneTok > 0 ? rawActual + hygieneTok : 0);
|
|
878
|
+
baselineForRow = rawBaseline;
|
|
879
|
+
cacheReadForRow = cr;
|
|
880
|
+
warmForRow = warm; // server-observed cache read (cr>0)
|
|
881
|
+
}
|
|
882
|
+
// Record the request's transform breakdown for the Context Map panel. This
|
|
883
|
+
// runs AFTER the eff-tokens are computed so the Details headline reads the
|
|
884
|
+
// SAME cache-weighted pair as the recent row's As-text / Sent / Saved
|
|
885
|
+
// columns (baselineInputEff / actualInputEff) — the two panels can no longer
|
|
886
|
+
// disagree. Raw counts are kept for the cache-blind sub-line. Gate on
|
|
887
|
+
// haveUsage so an in-flight request doesn't render a bogus "-100%".
|
|
888
|
+
if (info && haveUsage && imgId !== undefined) {
|
|
889
|
+
// Key by the request's first image id so the recent table's "view" link
|
|
890
|
+
// (which carries that id) maps straight to this breakdown.
|
|
891
|
+
this.contextHistory.push({
|
|
892
|
+
id: imgId,
|
|
893
|
+
baselineTokens: baselineForRow,
|
|
894
|
+
realInput: rawActual,
|
|
895
|
+
baselineInputEff,
|
|
896
|
+
actualInputEff,
|
|
897
|
+
haveBaseline,
|
|
898
|
+
cacheRead: cacheReadForRow,
|
|
899
|
+
warm: warmForRow,
|
|
900
|
+
output: out,
|
|
901
|
+
imageCount: info.imageCount ?? 0,
|
|
902
|
+
nativeImages: info.nativeImages,
|
|
903
|
+
wireImages: info.wireImages,
|
|
904
|
+
imageBudgetSkips: info.imageBudgetSkips,
|
|
905
|
+
baselineImagedTokens: info.baselineImagedTokens,
|
|
906
|
+
buckets: { ...(info.bucketChars ?? {}) },
|
|
907
|
+
imageIds: [...imgIds],
|
|
908
|
+
compressed,
|
|
909
|
+
model: ev.model,
|
|
910
|
+
responsesComposition: info.responsesComposition,
|
|
911
|
+
responsesUnexplainedTokens: info.responsesComposition
|
|
912
|
+
? Math.max(0, rawBaseline - info.responsesComposition.totalLocal)
|
|
913
|
+
: undefined,
|
|
914
|
+
});
|
|
915
|
+
// Keep in lockstep with RECENT_CAP so every "view" link in the recent
|
|
916
|
+
// table resolves to a real breakdown (was 30 < 50, so older visible rows
|
|
917
|
+
// silently fell back to the latest request's data).
|
|
918
|
+
if (this.contextHistory.length > RECENT_CAP) {
|
|
919
|
+
this.contextHistory.splice(0, this.contextHistory.length - RECENT_CAP);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
const imageCount = info?.imageCount ?? 0;
|
|
923
|
+
const hygieneTok = info?.textHygieneSavedTokens ?? 0;
|
|
924
|
+
const hygieneChars = info?.textHygieneSavedChars ?? 0;
|
|
925
|
+
const hygieneStages = info?.textHygieneStages;
|
|
926
|
+
const { opticalCompressed, textOnlyCompressed, compressionMode } = this.classifyCompressionMode(compressed, imageCount, hygieneTok, hygieneStages, info?.reason);
|
|
927
|
+
const dollarEligible = !google || priceMode() === 'kosha';
|
|
928
|
+
this.recordAccumulators({
|
|
929
|
+
model: ev.model,
|
|
930
|
+
eventMs,
|
|
931
|
+
compressed,
|
|
932
|
+
opticalCompressed,
|
|
933
|
+
textOnlyCompressed,
|
|
934
|
+
haveUsage,
|
|
935
|
+
creditSaving,
|
|
936
|
+
dollarEligible,
|
|
937
|
+
actualInputEff,
|
|
938
|
+
baselineInputEff,
|
|
939
|
+
outputEquiv,
|
|
940
|
+
rawActual,
|
|
941
|
+
rawBaseline,
|
|
942
|
+
inp,
|
|
943
|
+
out,
|
|
944
|
+
cc,
|
|
945
|
+
cr,
|
|
946
|
+
cc1h,
|
|
947
|
+
cachedTok: u?.cached_tokens ?? 0,
|
|
948
|
+
writeTok: u?.cache_write_tokens ?? 0,
|
|
949
|
+
googleOrGpt: google || gpt,
|
|
950
|
+
sid: info?.firstUserSha8,
|
|
951
|
+
hygieneTok,
|
|
952
|
+
hygieneChars,
|
|
953
|
+
cliffAvoided: Boolean(info?.cliffAvoided),
|
|
954
|
+
cliffUsd: info?.cliffAvoided?.savedUsd ?? 0,
|
|
955
|
+
measurement: ev.measurement,
|
|
956
|
+
});
|
|
957
|
+
const row = {
|
|
958
|
+
ts: eventMs / 1000,
|
|
959
|
+
method: ev.method,
|
|
960
|
+
path: ev.path,
|
|
961
|
+
model: ev.model,
|
|
962
|
+
status: ev.status,
|
|
963
|
+
compressed,
|
|
964
|
+
cc_added: opticalCompressed ? 1 : undefined,
|
|
965
|
+
image_count: imageCount,
|
|
966
|
+
compression_mode: compressionMode,
|
|
967
|
+
...(hygieneStages && hygieneStages.length > 0 ? { text_hygiene_stages: [...hygieneStages] } : {}),
|
|
968
|
+
input_tokens: haveUsage ? inp : undefined,
|
|
969
|
+
output_tokens: haveUsage ? out : undefined,
|
|
970
|
+
cache_create: haveUsage ? cc : undefined,
|
|
971
|
+
cache_read: haveUsage ? cacheReadForRow : undefined,
|
|
972
|
+
actual_input: haveUsage ? round1(actualInputEff) : undefined,
|
|
973
|
+
baseline_input: creditSaving ? round1(baselineInputEff) : undefined,
|
|
974
|
+
session_saved_so_far_delta: creditSaving ? round1(baselineInputEff - actualInputEff) : undefined,
|
|
975
|
+
img_id: imgId,
|
|
976
|
+
img_ids: imgIds,
|
|
977
|
+
};
|
|
978
|
+
this.recent.push(row);
|
|
979
|
+
if (this.recent.length > RECENT_CAP)
|
|
980
|
+
this.recent.splice(0, this.recent.length - RECENT_CAP);
|
|
981
|
+
}
|
|
982
|
+
/** On startup, stream historical JSONL logs (`${filePath}.1` then `filePath`)
|
|
983
|
+
* line-by-line to restore full lifetime, per-model, daily, and active-session
|
|
984
|
+
* accumulators across restarts while keeping `recent` & `contextHistory`
|
|
985
|
+
* bounded to `RECENT_CAP`. */
|
|
986
|
+
async replay(filePath) {
|
|
987
|
+
const candidates = [`${filePath}.1`, filePath];
|
|
988
|
+
let anyReadable = false;
|
|
989
|
+
const finiteNum = (v, fallback = 0) => typeof v === 'number' && Number.isFinite(v) ? v : fallback;
|
|
990
|
+
const finiteOptNum = (v) => typeof v === 'number' && Number.isFinite(v) ? v : undefined;
|
|
991
|
+
const tailBuffer = [];
|
|
992
|
+
for (const candidate of candidates) {
|
|
993
|
+
try {
|
|
994
|
+
await fs.promises.access(candidate, fs.constants.R_OK);
|
|
995
|
+
anyReadable = true;
|
|
996
|
+
}
|
|
997
|
+
catch {
|
|
998
|
+
continue;
|
|
999
|
+
}
|
|
1000
|
+
try {
|
|
1001
|
+
const stream = fs.createReadStream(candidate, { encoding: 'utf8' });
|
|
1002
|
+
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
1003
|
+
for await (const line of rl) {
|
|
1004
|
+
if (!line)
|
|
1005
|
+
continue;
|
|
1006
|
+
let parsed;
|
|
1007
|
+
try {
|
|
1008
|
+
parsed = JSON.parse(line);
|
|
1009
|
+
}
|
|
1010
|
+
catch {
|
|
1011
|
+
continue; // skip malformed line
|
|
1012
|
+
}
|
|
1013
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
1014
|
+
continue;
|
|
1015
|
+
const t = parsed;
|
|
1016
|
+
if (typeof t.path !== 'string' || typeof t.ts !== 'string')
|
|
1017
|
+
continue;
|
|
1018
|
+
const parsedMs = Date.parse(t.ts);
|
|
1019
|
+
if (!Number.isFinite(parsedMs))
|
|
1020
|
+
continue;
|
|
1021
|
+
const eventMs = parsedMs;
|
|
1022
|
+
const inp = finiteNum(t.input_tokens);
|
|
1023
|
+
const out = finiteNum(t.output_tokens);
|
|
1024
|
+
const cc = finiteNum(t.cache_create_tokens);
|
|
1025
|
+
const cc5m = finiteOptNum(t.cache_create_5m_tokens);
|
|
1026
|
+
const cc1h = finiteNum(t.cache_create_1h_tokens);
|
|
1027
|
+
const cr = finiteNum(t.cache_read_tokens);
|
|
1028
|
+
const compressed = t.compressed === true;
|
|
1029
|
+
const gpt = isOpenAIEvent(t.path, t.accounting_provider);
|
|
1030
|
+
const google = t.accounting_provider === 'google'
|
|
1031
|
+
|| t.path.includes('google-ai-studio') || t.path.toLowerCase().includes('generatecontent');
|
|
1032
|
+
// Same unified accounting as update(); see the branch comments there.
|
|
1033
|
+
let haveUsage;
|
|
1034
|
+
let haveBaseline;
|
|
1035
|
+
let creditSaving;
|
|
1036
|
+
let actualInputEff;
|
|
1037
|
+
let baselineInputEff;
|
|
1038
|
+
let outputEquiv;
|
|
1039
|
+
let rawActual;
|
|
1040
|
+
let rawBaseline;
|
|
1041
|
+
let baselineForRow;
|
|
1042
|
+
let cacheReadForRow;
|
|
1043
|
+
let warmForRow; // text-baseline warmth for the Context Map narration
|
|
1044
|
+
const cachedTok = finiteNum(t.cached_tokens);
|
|
1045
|
+
const baselineTok = finiteNum(t.baseline_tokens);
|
|
1046
|
+
const imageTok = finiteNum(t.image_tokens);
|
|
1047
|
+
const baselineImagedTok = finiteNum(t.baseline_imaged_tokens);
|
|
1048
|
+
const nativeInjectedTok = finiteNum(t.native_injected_tokens);
|
|
1049
|
+
const hygieneTok = finiteNum(t.text_hygiene_saved_tokens);
|
|
1050
|
+
const hygieneChars = finiteNum(t.text_hygiene_saved_chars);
|
|
1051
|
+
const writeTok = finiteNum(t.cache_write_tokens);
|
|
1052
|
+
const imageCount = finiteNum(t.image_count);
|
|
1053
|
+
const durationMs = Math.max(0, finiteNum(t.duration_ms));
|
|
1054
|
+
if (google) {
|
|
1055
|
+
const sidGoogleR = t.first_user_sha8;
|
|
1056
|
+
const completionSecGoogleR = eventMs / 1000;
|
|
1057
|
+
const requestStartSecGoogleR = completionSecGoogleR - durationMs / 1000;
|
|
1058
|
+
const googlePrevR = typeof sidGoogleR === 'string' && sidGoogleR.length > 0
|
|
1059
|
+
? this.lruGet(this.googleWarmth, sidGoogleR)
|
|
1060
|
+
: undefined;
|
|
1061
|
+
const pxShaGoogleR = t.cache_prefix_sha8 ?? t.history_image_sha8;
|
|
1062
|
+
const warmthGoogleR = deriveOpenAIBaselineWarmth(googlePrevR, requestStartSecGoogleR, cachedTok, t.system_sha8, t.model, DashboardState.CACHE_TTL_SEC, pxShaGoogleR);
|
|
1063
|
+
const e = googleEff({
|
|
1064
|
+
model: t.model,
|
|
1065
|
+
inputTokens: inp,
|
|
1066
|
+
outputTokens: out,
|
|
1067
|
+
cachedTokens: cachedTok,
|
|
1068
|
+
compressed,
|
|
1069
|
+
baselineTokens: baselineTok,
|
|
1070
|
+
baselineProbeStatus: t.baseline_probe_status,
|
|
1071
|
+
imageTokens: imageTok,
|
|
1072
|
+
baselineImagedTokens: baselineImagedTok,
|
|
1073
|
+
nativeInjectedTokens: nativeInjectedTok,
|
|
1074
|
+
textHygieneSavedTokens: hygieneTok,
|
|
1075
|
+
warmth: warmthGoogleR,
|
|
1076
|
+
});
|
|
1077
|
+
if (typeof sidGoogleR === 'string' && sidGoogleR.length > 0 && e.haveUsage) {
|
|
1078
|
+
this.lruSet(this.googleWarmth, sidGoogleR, {
|
|
1079
|
+
ts: completionSecGoogleR,
|
|
1080
|
+
cachedOrPrefixTokens: cachedTok > 0 ? cachedTok : Math.max(googlePrevR?.cachedOrPrefixTokens ?? 0, inp),
|
|
1081
|
+
prefixSha: t.system_sha8 ?? googlePrevR?.prefixSha,
|
|
1082
|
+
pxPrefixSha: pxShaGoogleR ?? googlePrevR?.pxPrefixSha,
|
|
1083
|
+
model: t.model ?? googlePrevR?.model,
|
|
1084
|
+
}, DashboardState.SESSION_CAP);
|
|
1085
|
+
}
|
|
1086
|
+
haveUsage = e.haveUsage;
|
|
1087
|
+
haveBaseline = e.haveBaseline;
|
|
1088
|
+
creditSaving = e.creditSaving;
|
|
1089
|
+
actualInputEff = e.actualInputEff;
|
|
1090
|
+
baselineInputEff = e.baselineInputEff;
|
|
1091
|
+
outputEquiv = e.outputEquiv;
|
|
1092
|
+
rawActual = inp;
|
|
1093
|
+
rawBaseline = e.rawBaseline;
|
|
1094
|
+
baselineForRow = creditSaving ? e.rawBaseline : 0;
|
|
1095
|
+
cacheReadForRow = cachedTok;
|
|
1096
|
+
warmForRow = e.warmForRow;
|
|
1097
|
+
}
|
|
1098
|
+
else if (gpt) {
|
|
1099
|
+
const sidGptR = t.first_user_sha8;
|
|
1100
|
+
const completionSecGptR = eventMs / 1000;
|
|
1101
|
+
const requestStartSecGptR = completionSecGptR - durationMs / 1000;
|
|
1102
|
+
const gptPrevR = typeof sidGptR === 'string' && sidGptR.length > 0
|
|
1103
|
+
? this.lruGet(this.openaiWarmth, sidGptR)
|
|
1104
|
+
: undefined;
|
|
1105
|
+
const pxShaGptR = t.cache_prefix_sha8 ?? t.history_image_sha8;
|
|
1106
|
+
const warmthGptR = deriveOpenAIBaselineWarmth(gptPrevR, requestStartSecGptR, cachedTok, t.system_sha8, t.model, OPENAI_CACHE_TTL_SEC, pxShaGptR);
|
|
1107
|
+
const e = gptEff({
|
|
1108
|
+
model: t.model,
|
|
1109
|
+
inputTokens: inp,
|
|
1110
|
+
outputTokens: out,
|
|
1111
|
+
cachedTokens: cachedTok,
|
|
1112
|
+
cacheWriteTokens: writeTok,
|
|
1113
|
+
imageTokens: imageTok,
|
|
1114
|
+
baselineImagedTokens: baselineImagedTok,
|
|
1115
|
+
nativeInjectedTokens: nativeInjectedTok,
|
|
1116
|
+
textHygieneSavedTokens: hygieneTok,
|
|
1117
|
+
warmth: warmthGptR,
|
|
1118
|
+
compressed,
|
|
1119
|
+
});
|
|
1120
|
+
if (typeof sidGptR === 'string' && sidGptR.length > 0 && e.haveUsage) {
|
|
1121
|
+
this.lruSet(this.openaiWarmth, sidGptR, {
|
|
1122
|
+
ts: completionSecGptR,
|
|
1123
|
+
cachedOrPrefixTokens: cachedTok > 0 ? cachedTok : Math.max(gptPrevR?.cachedOrPrefixTokens ?? 0, inp),
|
|
1124
|
+
prefixSha: t.system_sha8 ?? gptPrevR?.prefixSha,
|
|
1125
|
+
pxPrefixSha: pxShaGptR ?? gptPrevR?.pxPrefixSha,
|
|
1126
|
+
model: t.model ?? gptPrevR?.model,
|
|
1127
|
+
}, DashboardState.SESSION_CAP);
|
|
1128
|
+
}
|
|
1129
|
+
haveUsage = e.haveUsage;
|
|
1130
|
+
haveBaseline = e.haveBaseline;
|
|
1131
|
+
creditSaving = e.creditSaving;
|
|
1132
|
+
actualInputEff = e.actualInputEff;
|
|
1133
|
+
baselineInputEff = e.baselineInputEff;
|
|
1134
|
+
outputEquiv = e.outputEquiv;
|
|
1135
|
+
rawActual = e.rawActual;
|
|
1136
|
+
rawBaseline = e.rawBaseline;
|
|
1137
|
+
baselineForRow = e.rawBaseline;
|
|
1138
|
+
cacheReadForRow = cachedTok;
|
|
1139
|
+
warmForRow = warmthGptR.warm;
|
|
1140
|
+
}
|
|
1141
|
+
else {
|
|
1142
|
+
haveUsage = inp > 0 || out > 0 || cc > 0 || cr > 0;
|
|
1143
|
+
const baselineOpt = finiteOptNum(t.baseline_tokens);
|
|
1144
|
+
const cacheable = finiteNum(t.baseline_cacheable_tokens);
|
|
1145
|
+
const probeStatus = t.baseline_probe_status;
|
|
1146
|
+
// Same gating rule as update(): require an explicit 'ok' status when
|
|
1147
|
+
// present; fall back to "have a baseline number" for legacy JSONL.
|
|
1148
|
+
const probeOk = isUsableAnthropicBaselineProbe({
|
|
1149
|
+
baselineTokens: baselineOpt,
|
|
1150
|
+
probeStatus,
|
|
1151
|
+
threadContinue: t.thread_continue,
|
|
1152
|
+
cacheReadTokens: cr,
|
|
1153
|
+
});
|
|
1154
|
+
haveBaseline = baselineOpt !== undefined && baselineOpt > 0 && probeOk;
|
|
1155
|
+
actualInputEff = haveUsage
|
|
1156
|
+
? computeActualInputEffWithCacheTier(inp, cc, cr, cc1h, cc5m, anthropicReadRate(t.model, { at: eventMs }))
|
|
1157
|
+
: 0;
|
|
1158
|
+
// Mirror update(): only credit the cache-modeled counterfactual on
|
|
1159
|
+
// compressed rows. Uncompressed/passthrough rows fall back to the
|
|
1160
|
+
// actual cost so they show zero saved (no fabricated savings).
|
|
1161
|
+
creditSaving = haveBaseline && haveUsage && compressed;
|
|
1162
|
+
// Warmth is reconstructed from persisted completion ts + duration_ms
|
|
1163
|
+
// exactly as update() saw it live.
|
|
1164
|
+
const sidR = t.first_user_sha8;
|
|
1165
|
+
const prefixShaR = t.system_sha8;
|
|
1166
|
+
const completionSecR = eventMs / 1000;
|
|
1167
|
+
const requestStartSecR = completionSecR - durationMs / 1000;
|
|
1168
|
+
const warmthPrevR = typeof sidR === 'string' && sidR.length > 0 ? this.lruGet(this.baselineWarmth, sidR) : undefined;
|
|
1169
|
+
const toolsShaR = t.cache_prefix_tools_sha8;
|
|
1170
|
+
const { warm: warmR, prevCacheable: prevCacheableR } = deriveBaselineWarmth(warmthPrevR, requestStartSecR, cacheable, cr, DashboardState.CACHE_TTL_SEC, prefixShaR, toolsShaR, { pxPrefixSha: t.cache_prefix_sha8, model: t.model });
|
|
1171
|
+
const readRateR = anthropicReadRate(t.model, { at: eventMs });
|
|
1172
|
+
baselineInputEff = creditSaving
|
|
1173
|
+
? computeBaselineInputEffWithCacheTier(baselineOpt, cacheable, inp, cc, cr, warmR, prevCacheableR, cc1h, cc5m, readRateR)
|
|
1174
|
+
: actualInputEff;
|
|
1175
|
+
if (!haveBaseline && compressed && haveUsage && hygieneTok > 0 && imageCount === 0) {
|
|
1176
|
+
haveBaseline = true;
|
|
1177
|
+
creditSaving = true;
|
|
1178
|
+
if (warmR && cr === 0) {
|
|
1179
|
+
const unproxiedRawR = inp + cc + hygieneTok;
|
|
1180
|
+
const reusedTargetR = prevCacheableR > 0 ? prevCacheableR : (warmthPrevR?.observedCachedTokens ?? 0);
|
|
1181
|
+
if (reusedTargetR > 0) {
|
|
1182
|
+
const reusedR = Math.min(unproxiedRawR, reusedTargetR);
|
|
1183
|
+
const createRateR = cc > 0 ? (cc1h > 0 && cc1h >= cc ? 2.0 : 1.25) : 1.0;
|
|
1184
|
+
baselineInputEff = reusedR * readRateR + (unproxiedRawR - reusedR) * createRateR;
|
|
1185
|
+
}
|
|
1186
|
+
else {
|
|
1187
|
+
baselineInputEff = actualInputEff + hygieneTok * readRateR;
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
else {
|
|
1191
|
+
const deltaWeightR = cr > 0
|
|
1192
|
+
? readRateR
|
|
1193
|
+
: cc > 0 ? (cc1h > 0 && cc1h >= cc ? 2.0 : 1.25) : 1.0;
|
|
1194
|
+
baselineInputEff = actualInputEff + hygieneTok * deltaWeightR;
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
if (typeof sidR === 'string' && sidR.length > 0 && haveUsage) {
|
|
1198
|
+
this.lruSet(this.baselineWarmth, sidR, {
|
|
1199
|
+
ts: completionSecR,
|
|
1200
|
+
cacheable: cacheable > 0 ? cacheable : (warmthPrevR?.cacheable ?? 0),
|
|
1201
|
+
prefixSha: prefixShaR ?? warmthPrevR?.prefixSha,
|
|
1202
|
+
toolsSha: toolsShaR ?? warmthPrevR?.toolsSha,
|
|
1203
|
+
pxPrefixSha: t.cache_prefix_sha8 ?? warmthPrevR?.pxPrefixSha,
|
|
1204
|
+
model: t.model ?? warmthPrevR?.model,
|
|
1205
|
+
ttlSec: observedCacheTtlSec(cc1h, warmthPrevR?.ttlSec),
|
|
1206
|
+
observedCachedTokens: cr > 0 || cc > 0 ? cr + cc : warmthPrevR?.observedCachedTokens,
|
|
1207
|
+
}, DashboardState.SESSION_CAP);
|
|
1208
|
+
}
|
|
1209
|
+
outputEquiv = haveUsage
|
|
1210
|
+
? out * resolvePriceRates(t.model, { promptTokens: inp + cc + cr, at: eventMs }).output
|
|
1211
|
+
: 0;
|
|
1212
|
+
rawActual = inp + cc + cr;
|
|
1213
|
+
rawBaseline = probeOk && baselineOpt !== undefined
|
|
1214
|
+
? baselineOpt
|
|
1215
|
+
: (creditSaving && hygieneTok > 0 ? rawActual + hygieneTok : 0);
|
|
1216
|
+
baselineForRow = rawBaseline;
|
|
1217
|
+
cacheReadForRow = cr;
|
|
1218
|
+
warmForRow = warmR;
|
|
1219
|
+
}
|
|
1220
|
+
const hygieneStages = Array.isArray(t.text_hygiene_stages)
|
|
1221
|
+
? t.text_hygiene_stages.filter((s) => typeof s === 'string')
|
|
1222
|
+
: undefined;
|
|
1223
|
+
const { opticalCompressed, textOnlyCompressed, compressionMode } = this.classifyCompressionMode(compressed, imageCount, hygieneTok, hygieneStages, t.reason);
|
|
1224
|
+
const dollarEligible = !google || priceMode() === 'kosha';
|
|
1225
|
+
const textMeas = finiteOptNum(t.text_chars_measured);
|
|
1226
|
+
const thinkMeas = finiteOptNum(t.thinking_chars_measured);
|
|
1227
|
+
const toolMeas = finiteOptNum(t.tool_use_chars_measured);
|
|
1228
|
+
const redactMeas = finiteOptNum(t.redacted_block_count_measured);
|
|
1229
|
+
const hasMeas = textMeas !== undefined ||
|
|
1230
|
+
thinkMeas !== undefined ||
|
|
1231
|
+
toolMeas !== undefined ||
|
|
1232
|
+
redactMeas !== undefined;
|
|
1233
|
+
const measurement = hasMeas
|
|
1234
|
+
? {
|
|
1235
|
+
textChars: textMeas ?? 0,
|
|
1236
|
+
thinkingChars: thinkMeas ?? 0,
|
|
1237
|
+
toolUseChars: toolMeas ?? 0,
|
|
1238
|
+
redactedBlockCount: redactMeas ?? 0,
|
|
1239
|
+
}
|
|
1240
|
+
: undefined;
|
|
1241
|
+
const cliffUsd = finiteNum(t.cliff_saved_usd);
|
|
1242
|
+
const cliffAvoided = cliffUsd > 0 || t.cliff_avoided_at !== undefined;
|
|
1243
|
+
this.recordAccumulators({
|
|
1244
|
+
model: t.model,
|
|
1245
|
+
eventMs,
|
|
1246
|
+
compressed,
|
|
1247
|
+
opticalCompressed,
|
|
1248
|
+
textOnlyCompressed,
|
|
1249
|
+
haveUsage,
|
|
1250
|
+
creditSaving,
|
|
1251
|
+
dollarEligible,
|
|
1252
|
+
actualInputEff,
|
|
1253
|
+
baselineInputEff,
|
|
1254
|
+
outputEquiv,
|
|
1255
|
+
rawActual,
|
|
1256
|
+
rawBaseline,
|
|
1257
|
+
inp,
|
|
1258
|
+
out,
|
|
1259
|
+
cc,
|
|
1260
|
+
cr,
|
|
1261
|
+
cc1h,
|
|
1262
|
+
cachedTok,
|
|
1263
|
+
writeTok,
|
|
1264
|
+
googleOrGpt: google || gpt,
|
|
1265
|
+
sid: t.first_user_sha8,
|
|
1266
|
+
hygieneTok,
|
|
1267
|
+
hygieneChars,
|
|
1268
|
+
cliffAvoided,
|
|
1269
|
+
cliffUsd,
|
|
1270
|
+
measurement,
|
|
1271
|
+
});
|
|
1272
|
+
if (tailBuffer.length >= RECENT_CAP)
|
|
1273
|
+
tailBuffer.shift();
|
|
1274
|
+
tailBuffer.push({
|
|
1275
|
+
t,
|
|
1276
|
+
eventMs,
|
|
1277
|
+
compressed,
|
|
1278
|
+
haveUsage,
|
|
1279
|
+
haveBaseline,
|
|
1280
|
+
creditSaving,
|
|
1281
|
+
actualInputEff,
|
|
1282
|
+
baselineInputEff,
|
|
1283
|
+
rawActual,
|
|
1284
|
+
rawBaseline,
|
|
1285
|
+
baselineForRow,
|
|
1286
|
+
cacheReadForRow,
|
|
1287
|
+
warmForRow,
|
|
1288
|
+
out,
|
|
1289
|
+
imageCount,
|
|
1290
|
+
opticalCompressed,
|
|
1291
|
+
compressionMode,
|
|
1292
|
+
hygieneStages,
|
|
1293
|
+
gpt,
|
|
1294
|
+
google,
|
|
1295
|
+
});
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
catch {
|
|
1299
|
+
// One unreadable/corrupt rotated file must never prevent replaying newer candidates.
|
|
1300
|
+
continue;
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
if (!anyReadable)
|
|
1304
|
+
return;
|
|
1305
|
+
// Construct RecentRow / ContextMapData only for the trailing RECENT_CAP entries.
|
|
1306
|
+
for (const item of tailBuffer) {
|
|
1307
|
+
const { t, eventMs, compressed, haveUsage, haveBaseline, creditSaving, actualInputEff, baselineInputEff, rawActual, rawBaseline, baselineForRow, cacheReadForRow, warmForRow, out, imageCount, opticalCompressed, compressionMode, hygieneStages, gpt, google, } = item;
|
|
1308
|
+
let imgId;
|
|
1309
|
+
if (compressed && haveUsage && imageCount > 0) {
|
|
1310
|
+
imgId = this.nextImageId++;
|
|
1311
|
+
const rawBuckets = t.bucket_chars;
|
|
1312
|
+
const safeBuckets = {};
|
|
1313
|
+
if (rawBuckets && typeof rawBuckets === 'object' && !Array.isArray(rawBuckets)) {
|
|
1314
|
+
for (const [k, v] of Object.entries(rawBuckets)) {
|
|
1315
|
+
if (typeof v === 'number' && Number.isFinite(v))
|
|
1316
|
+
safeBuckets[k] = v;
|
|
1317
|
+
}
|
|
1318
|
+
}
|
|
1319
|
+
const rawRc = t.responses_composition;
|
|
1320
|
+
const rc = rawRc && typeof rawRc === 'object' && !Array.isArray(rawRc) ? rawRc : undefined;
|
|
1321
|
+
this.contextHistory.push({
|
|
1322
|
+
id: imgId,
|
|
1323
|
+
baselineTokens: baselineForRow,
|
|
1324
|
+
realInput: rawActual,
|
|
1325
|
+
baselineInputEff,
|
|
1326
|
+
actualInputEff,
|
|
1327
|
+
haveBaseline,
|
|
1328
|
+
cacheRead: cacheReadForRow,
|
|
1329
|
+
warm: warmForRow,
|
|
1330
|
+
output: out,
|
|
1331
|
+
imageCount,
|
|
1332
|
+
nativeImages: finiteOptNum(t.native_images),
|
|
1333
|
+
wireImages: finiteOptNum(t.wire_images),
|
|
1334
|
+
imageBudgetSkips: finiteOptNum(t.image_budget_skips),
|
|
1335
|
+
baselineImagedTokens: finiteOptNum(t.baseline_imaged_tokens),
|
|
1336
|
+
buckets: safeBuckets,
|
|
1337
|
+
imageIds: [],
|
|
1338
|
+
compressed,
|
|
1339
|
+
model: t.model,
|
|
1340
|
+
responsesComposition: rc,
|
|
1341
|
+
responsesUnexplainedTokens: rc
|
|
1342
|
+
? Math.max(0, rawBaseline - finiteNum(rc.totalLocal))
|
|
1343
|
+
: undefined,
|
|
1344
|
+
restored: true,
|
|
1345
|
+
});
|
|
1346
|
+
if (this.contextHistory.length > RECENT_CAP) {
|
|
1347
|
+
this.contextHistory.splice(0, this.contextHistory.length - RECENT_CAP);
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
const statusNum = finiteOptNum(t.status);
|
|
1351
|
+
const row = {
|
|
1352
|
+
ts: eventMs / 1000,
|
|
1353
|
+
method: typeof t.method === 'string' ? t.method : 'POST',
|
|
1354
|
+
path: t.path,
|
|
1355
|
+
model: typeof t.model === 'string' ? t.model : undefined,
|
|
1356
|
+
status: statusNum !== undefined ? Math.trunc(statusNum) : 0,
|
|
1357
|
+
compressed,
|
|
1358
|
+
cc_added: opticalCompressed ? 1 : undefined,
|
|
1359
|
+
image_count: imageCount,
|
|
1360
|
+
compression_mode: compressionMode,
|
|
1361
|
+
...(hygieneStages && hygieneStages.length > 0 ? { text_hygiene_stages: [...hygieneStages] } : {}),
|
|
1362
|
+
input_tokens: finiteOptNum(t.input_tokens),
|
|
1363
|
+
output_tokens: finiteOptNum(t.output_tokens),
|
|
1364
|
+
cache_create: finiteOptNum(t.cache_create_tokens),
|
|
1365
|
+
cache_read: gpt || google ? cacheReadForRow : finiteOptNum(t.cache_read_tokens),
|
|
1366
|
+
actual_input: haveUsage ? round1(actualInputEff) : undefined,
|
|
1367
|
+
baseline_input: creditSaving ? round1(baselineInputEff) : undefined,
|
|
1368
|
+
session_saved_so_far_delta: creditSaving ? round1(baselineInputEff - actualInputEff) : undefined,
|
|
1369
|
+
img_id: imgId,
|
|
1370
|
+
img_ids: imgId !== undefined ? [imgId] : undefined,
|
|
1371
|
+
};
|
|
1372
|
+
this.recent.push(row);
|
|
1373
|
+
if (this.recent.length > RECENT_CAP)
|
|
1374
|
+
this.recent.shift();
|
|
1375
|
+
}
|
|
1376
|
+
}
|
|
1377
|
+
// ---- HTTP handlers ------------------------------------------------------
|
|
1378
|
+
/**
|
|
1379
|
+
* Per-session "what's happening right now" payload backing the
|
|
1380
|
+
* `SessionSummary` panel. Scopes the dollar-weighted savings ratio + the
|
|
1381
|
+
* per-bucket char attribution + the passthrough-reason histogram to the
|
|
1382
|
+
* most-recently-active session (tracked via `info.firstUserSha8`) so the
|
|
1383
|
+
* top-of-dashboard headline reflects the live session rather than stale
|
|
1384
|
+
* lifetime aggregates from a previous run.
|
|
1385
|
+
*
|
|
1386
|
+
* Returns `{ sessionId: null, message: 'no active session yet' }` when no
|
|
1387
|
+
* events have been received yet (or the first events were all untagged —
|
|
1388
|
+
* cold start, probe failures) — `update()` only sets `currentSessionId`
|
|
1389
|
+
* when a `firstUserSha8`-tagged event lands. The client renders a stale
|
|
1390
|
+
* panel rather than zeroes when a session goes idle (NO `lastSeen >
|
|
1391
|
+
* threshold` check here; see comment in `update()` for the rationale).
|
|
1392
|
+
*/
|
|
1393
|
+
serveCurrentSessionJson() {
|
|
1394
|
+
if (!this.currentSessionId) {
|
|
1395
|
+
return jsonResponse({
|
|
1396
|
+
sessionId: null,
|
|
1397
|
+
message: 'no active session yet',
|
|
1398
|
+
});
|
|
1399
|
+
}
|
|
1400
|
+
const s = this.lruGet(this.sessions, this.currentSessionId);
|
|
1401
|
+
if (!s) {
|
|
1402
|
+
return jsonResponse({ sessionId: null, message: 'no active session yet' });
|
|
1403
|
+
}
|
|
1404
|
+
// Headline payload: the same dollar-weighted baseline/actual input
|
|
1405
|
+
// accumulators the global Totals block exposes, plus the honest
|
|
1406
|
+
// denominator (`baselineMeasuredCount` — only requests that carried a
|
|
1407
|
+
// baseline measurement). We ALSO ship the ALL-rows session bill
|
|
1408
|
+
// (`allActualInputWeighted` + `allOutputWeighted`) so the Svelte panel
|
|
1409
|
+
// can compute saved-% against the full session bill instead of just
|
|
1410
|
+
// the measured slice — matching the global `saved_pct_of_all_spend`
|
|
1411
|
+
// math but scoped to one session. The Svelte panel does the dollar
|
|
1412
|
+
// conversion itself so we don't round-trip pricing through the wire.
|
|
1413
|
+
return jsonResponse({
|
|
1414
|
+
sessionId: s.sessionId,
|
|
1415
|
+
baselineInputWeighted: s.baselineInputWeighted,
|
|
1416
|
+
actualInputWeighted: s.actualInputWeighted,
|
|
1417
|
+
baselineMeasuredCount: s.baselineMeasuredCount,
|
|
1418
|
+
allActualInputWeighted: s.allActualInputWeighted,
|
|
1419
|
+
allOutputWeighted: s.allOutputWeighted,
|
|
1420
|
+
rawActualTokens: s.rawActualTokens,
|
|
1421
|
+
rawBaselineTokens: s.rawBaselineTokens,
|
|
1422
|
+
rawOutputTokens: s.rawOutputTokens,
|
|
1423
|
+
});
|
|
1424
|
+
}
|
|
1425
|
+
serveStats() {
|
|
1426
|
+
// Two headline numbers, derived from the same per-event accumulators:
|
|
1427
|
+
//
|
|
1428
|
+
// saved_pct_input_only = Σ saved / Σ baseline_input_eff × 100
|
|
1429
|
+
// What the proxy actually saved on the slice it can move (input).
|
|
1430
|
+
// Numerator = input tokens we didn't pay for (cache-aware).
|
|
1431
|
+
// Denominator = input tokens we WOULD have paid (cache-aware).
|
|
1432
|
+
// Output is excluded because the proxy doesn't touch it.
|
|
1433
|
+
//
|
|
1434
|
+
// saved_pct_of_total_bill = Σ saved / Σ (baseline_input + output × 5) × 100
|
|
1435
|
+
// What share of the TOTAL bill the proxy saved. Honest counter to the
|
|
1436
|
+
// input-only number: on output-heavy sessions (long thinking blocks,
|
|
1437
|
+
// big edits) the percentage shrinks because output dominates.
|
|
1438
|
+
//
|
|
1439
|
+
// token_equivalent_total = Σ (actual_input + output × 5)
|
|
1440
|
+
// What Anthropic's weekly limit actually meters — input × 1.0 +
|
|
1441
|
+
// output × 5.0 (the same ratio as the per-MTok price card). This is
|
|
1442
|
+
// the number that moves your "%% used this week" indicator.
|
|
1443
|
+
const totals = this.enabledTotals();
|
|
1444
|
+
const baseline = totals.baselineInputWeighted;
|
|
1445
|
+
const actual = totals.actualInputWeighted;
|
|
1446
|
+
const output = totals.outputWeighted; // already × OUTPUT_TOKEN_RATE
|
|
1447
|
+
const saved = baseline - actual;
|
|
1448
|
+
const pricedBaseline = totals.pricedBaselineInputWeighted;
|
|
1449
|
+
const pricedActual = totals.pricedActualInputWeighted;
|
|
1450
|
+
const pricedOutput = totals.pricedOutputWeighted;
|
|
1451
|
+
const pricedSaved = pricedBaseline - pricedActual;
|
|
1452
|
+
const pctInput = baseline > 0 ? (saved / baseline) * 100 : 0;
|
|
1453
|
+
const baselineTotal = baseline + output;
|
|
1454
|
+
const actualTotal = actual + output;
|
|
1455
|
+
const pricedBaselineTotal = pricedBaseline + pricedOutput;
|
|
1456
|
+
const pctTotal = pricedBaselineTotal > 0 ? (pricedSaved / pricedBaselineTotal) * 100 : 0;
|
|
1457
|
+
// Share-of-all-spend: honest denominator. The numerator can only credit
|
|
1458
|
+
// savings against rows where we have a probe baseline (otherwise it's
|
|
1459
|
+
// estimation), but the denominator MUST include every request the user
|
|
1460
|
+
// actually paid for — including passthrough rows, probe-failed rows,
|
|
1461
|
+
// and untransformed turns the gate said no to. Otherwise the headline
|
|
1462
|
+
// answers "did inkling help on the rows where it ran" instead of
|
|
1463
|
+
// "did inkling move my real bill". The first is a cherry-pick.
|
|
1464
|
+
const allBaselineEquiv = totals.allBaselineEquivalentWeighted;
|
|
1465
|
+
const allActual = totals.allActualInputWeighted;
|
|
1466
|
+
const allOutput = totals.allOutputWeighted;
|
|
1467
|
+
// Denominator = counterfactual all-rows bill: what the user would have
|
|
1468
|
+
// paid with no inkling. Bounded ratio at 100%; a single cold-miss
|
|
1469
|
+
// compressed request on an otherwise empty session shows ~99% saved,
|
|
1470
|
+
// not 280%.
|
|
1471
|
+
const allCounterfactualBill = allBaselineEquiv + allOutput;
|
|
1472
|
+
const pctAllSpend = allCounterfactualBill > 0 ? (pricedSaved / allCounterfactualBill) * 100 : 0;
|
|
1473
|
+
// Direct observed split — actual $ per request, partitioned by which
|
|
1474
|
+
// path ran. Token-equivalent (input × 1.0 + cache_create × 1.25 +
|
|
1475
|
+
// cache_read × 0.10 + output × 5) → $ at the assumed Opus 4.7 input
|
|
1476
|
+
// rate. Same $/Mtok rate is applied to both buckets, so the bias from
|
|
1477
|
+
// the rate assumption cancels in the delta. Selection bias from the
|
|
1478
|
+
// gate is NOT cancelled — the operator interprets that via the
|
|
1479
|
+
// sample-count caveat below.
|
|
1480
|
+
const compressedTokenEquiv = totals.compressedActualInputWeighted +
|
|
1481
|
+
totals.compressedOutputWeighted;
|
|
1482
|
+
const passthroughTokenEquiv = totals.passthroughActualInputWeighted +
|
|
1483
|
+
totals.passthroughOutputWeighted;
|
|
1484
|
+
const compressedActualUsd = priceMode() === 'kosha'
|
|
1485
|
+
? totals.compressedActualUsdKosha
|
|
1486
|
+
: (compressedTokenEquiv * ASSUMED_INPUT_USD_PER_MTOK) / 1e6;
|
|
1487
|
+
const passthroughActualUsd = priceMode() === 'kosha'
|
|
1488
|
+
? totals.passthroughActualUsdKosha
|
|
1489
|
+
: (passthroughTokenEquiv * ASSUMED_INPUT_USD_PER_MTOK) / 1e6;
|
|
1490
|
+
const compressedAvgUsd = totals.compressedPaidRequests > 0
|
|
1491
|
+
? compressedActualUsd / totals.compressedPaidRequests
|
|
1492
|
+
: 0;
|
|
1493
|
+
const passthroughAvgUsd = totals.passthroughPaidRequests > 0
|
|
1494
|
+
? passthroughActualUsd / totals.passthroughPaidRequests
|
|
1495
|
+
: 0;
|
|
1496
|
+
// Sufficient-sample threshold is a soft heuristic. 20 paid requests per
|
|
1497
|
+
// bucket is enough to see a real effect on Opus 4.7 traffic (a single
|
|
1498
|
+
// big cold-miss can dominate at lower n). Below this, the UI shows the
|
|
1499
|
+
// bucket numbers but hides the delta and surfaces "small sample".
|
|
1500
|
+
const SUFFICIENT = 20;
|
|
1501
|
+
const splitSufficient = totals.compressedPaidRequests >= SUFFICIENT &&
|
|
1502
|
+
totals.passthroughPaidRequests >= SUFFICIENT;
|
|
1503
|
+
const splitDeltaUsd = compressedAvgUsd - passthroughAvgUsd;
|
|
1504
|
+
const nowMs = Date.now();
|
|
1505
|
+
const todayDate = new Date(nowMs);
|
|
1506
|
+
const todayKey = localDateKey(nowMs);
|
|
1507
|
+
const daily = [];
|
|
1508
|
+
for (let offset = DAILY_CHART_DAYS - 1; offset >= 0; offset--) {
|
|
1509
|
+
const d = new Date(todayDate.getFullYear(), todayDate.getMonth(), todayDate.getDate() - offset);
|
|
1510
|
+
const dateKey = localDateKey(d.getTime());
|
|
1511
|
+
const byModelMap = this.dailyByDateModel.get(dateKey);
|
|
1512
|
+
const dayOtherSupported = this.dailyOtherSupported.get(dateKey) === true;
|
|
1513
|
+
const sum = emptyDailyBucket();
|
|
1514
|
+
if (byModelMap) {
|
|
1515
|
+
for (const [model, b] of byModelMap) {
|
|
1516
|
+
if (!this.isModelIncludedInStats(model, b.textHygieneSavedTokens, dayOtherSupported)) {
|
|
1517
|
+
continue;
|
|
1518
|
+
}
|
|
1519
|
+
sum.requests += b.requests;
|
|
1520
|
+
sum.compressed += b.compressed;
|
|
1521
|
+
sum.imaged += b.imaged;
|
|
1522
|
+
sum.textCompressed += b.textCompressed;
|
|
1523
|
+
sum.baselineInputWeighted += b.baselineInputWeighted;
|
|
1524
|
+
sum.actualInputWeighted += b.actualInputWeighted;
|
|
1525
|
+
sum.rawSavedTokens += b.rawSavedTokens;
|
|
1526
|
+
sum.pricedBaselineInputWeighted += b.pricedBaselineInputWeighted;
|
|
1527
|
+
sum.pricedActualInputWeighted += b.pricedActualInputWeighted;
|
|
1528
|
+
sum.pricedSavedUsd += b.pricedSavedUsd;
|
|
1529
|
+
sum.cliffSavedUsd += b.cliffSavedUsd;
|
|
1530
|
+
}
|
|
1531
|
+
}
|
|
1532
|
+
const daySaved = sum.baselineInputWeighted - sum.actualInputWeighted;
|
|
1533
|
+
const dayPricedSaved = sum.pricedBaselineInputWeighted - sum.pricedActualInputWeighted;
|
|
1534
|
+
const dayUsd = priceMode() === 'kosha'
|
|
1535
|
+
? sum.pricedSavedUsd
|
|
1536
|
+
: (dayPricedSaved * ASSUMED_INPUT_USD_PER_MTOK) / 1e6;
|
|
1537
|
+
daily.push({
|
|
1538
|
+
date: dateKey,
|
|
1539
|
+
requests: sum.requests,
|
|
1540
|
+
compressed: sum.compressed,
|
|
1541
|
+
imaged: sum.imaged,
|
|
1542
|
+
text_compressed: sum.textCompressed,
|
|
1543
|
+
baseline_input_weighted: Math.round(sum.baselineInputWeighted),
|
|
1544
|
+
actual_input_weighted: Math.round(sum.actualInputWeighted),
|
|
1545
|
+
saved_tokens: Math.round(daySaved),
|
|
1546
|
+
raw_saved_tokens: Math.round(sum.rawSavedTokens),
|
|
1547
|
+
saved_pct: sum.baselineInputWeighted > 0 ? round1((daySaved / sum.baselineInputWeighted) * 100) : 0,
|
|
1548
|
+
saved_usd: round4(dayUsd),
|
|
1549
|
+
cliff_saved_usd: round4(sum.cliffSavedUsd),
|
|
1550
|
+
is_today: dateKey === todayKey,
|
|
1551
|
+
});
|
|
1552
|
+
}
|
|
1553
|
+
const uptimeSec = nowMs / 1000 - totals.startedAt;
|
|
1554
|
+
const payload = {
|
|
1555
|
+
requests: totals.requests,
|
|
1556
|
+
compressed_requests: totals.compressedRequests,
|
|
1557
|
+
imaged_requests: totals.imagedRequests,
|
|
1558
|
+
text_compressed_requests: totals.textCompressedRequests,
|
|
1559
|
+
baseline_input_weighted: Math.round(baseline),
|
|
1560
|
+
actual_input_weighted: Math.round(actual),
|
|
1561
|
+
saved_input_tokens: Math.round(saved),
|
|
1562
|
+
raw_saved_tokens: Math.round(totals.rawSavedTokens),
|
|
1563
|
+
// saved_pct kept for back-compat with existing dashboard HTML; it is
|
|
1564
|
+
// the input-only number. New code should read saved_pct_input_only.
|
|
1565
|
+
saved_pct: round1(pctInput),
|
|
1566
|
+
saved_pct_input_only: round1(pctInput),
|
|
1567
|
+
saved_pct_of_total_bill: round1(pctTotal),
|
|
1568
|
+
// Honest "share of total bill saved" — measured-rows numerator over
|
|
1569
|
+
// ALL paid requests in the denominator (compressed + passthrough +
|
|
1570
|
+
// probe-failed). This is the number users actually want when they
|
|
1571
|
+
// ask "is inkling helping". Negative when flap-pollution from
|
|
1572
|
+
// passthrough turns exceeds the collapse win on measured turns.
|
|
1573
|
+
saved_pct_of_all_spend: round1(pctAllSpend),
|
|
1574
|
+
all_baseline_equivalent_weighted: Math.round(allBaselineEquiv),
|
|
1575
|
+
all_actual_input_weighted: Math.round(allActual),
|
|
1576
|
+
all_output_weighted: Math.round(allOutput),
|
|
1577
|
+
all_usage_requests: totals.allUsageRequests,
|
|
1578
|
+
// Direct observed split — replaces "share of spend saved" as the
|
|
1579
|
+
// headline. Total actual $ and average $/req per path, plus a delta
|
|
1580
|
+
// gated on `split_sufficient_sample`. No counterfactual: each
|
|
1581
|
+
// bucket is what each path actually billed.
|
|
1582
|
+
compressed_paid_requests: totals.compressedPaidRequests,
|
|
1583
|
+
passthrough_paid_requests: totals.passthroughPaidRequests,
|
|
1584
|
+
compressed_actual_usd: round4(compressedActualUsd),
|
|
1585
|
+
passthrough_actual_usd: round4(passthroughActualUsd),
|
|
1586
|
+
compressed_avg_usd_per_request: round4(compressedAvgUsd),
|
|
1587
|
+
passthrough_avg_usd_per_request: round4(passthroughAvgUsd),
|
|
1588
|
+
compressed_minus_passthrough_avg_usd: round4(splitDeltaUsd),
|
|
1589
|
+
split_sufficient_sample: splitSufficient,
|
|
1590
|
+
split_min_sample_per_bucket: SUFFICIENT,
|
|
1591
|
+
// Legacy: every saved token at the assumed $10/MTok. Kosha: each row at
|
|
1592
|
+
// its own model's input price; unpriced rows are left out and counted.
|
|
1593
|
+
saved_usd: round4(priceMode() === 'kosha'
|
|
1594
|
+
? totals.pricedSavedUsd
|
|
1595
|
+
: (pricedSaved * ASSUMED_INPUT_USD_PER_MTOK) / 1e6),
|
|
1596
|
+
output_weighted: Math.round(output),
|
|
1597
|
+
baseline_token_equivalent: Math.round(baselineTotal),
|
|
1598
|
+
actual_token_equivalent: Math.round(actualTotal),
|
|
1599
|
+
pricing_assumptions: {
|
|
1600
|
+
input_per_mtok: ASSUMED_INPUT_USD_PER_MTOK,
|
|
1601
|
+
output_multiplier: OUTPUT_TOKEN_RATE,
|
|
1602
|
+
cache_write_5m_multiplier: 1.25,
|
|
1603
|
+
cache_write_1h_multiplier: 2.0,
|
|
1604
|
+
cache_read_multiplier: 0.1,
|
|
1605
|
+
source: 'docs.anthropic.com/en/docs/about-claude/pricing (verified 2026-05-19)',
|
|
1606
|
+
price_mode: priceMode(),
|
|
1607
|
+
price_snapshot: PRICE_SNAPSHOT,
|
|
1608
|
+
usd_priced_requests: totals.usdPricedRequests,
|
|
1609
|
+
usd_unpriced_requests: totals.usdUnpricedRequests,
|
|
1610
|
+
},
|
|
1611
|
+
// Honest output measurement — char counts from the SSE/JSON scanner,
|
|
1612
|
+
// independent of Anthropic's `usage.output_tokens`. Surfaces the gap
|
|
1613
|
+
// the May-2026 weekly-meter audit hypothesized (redacted_thinking adds
|
|
1614
|
+
// billed tokens that we can't see). `events_with_measurement` lets the
|
|
1615
|
+
// operator weigh how representative the numbers are; when it's near
|
|
1616
|
+
// `requests`, the gap is real. When it's 0, the scanner never landed
|
|
1617
|
+
// (5xx-heavy session, no /v1/messages traffic).
|
|
1618
|
+
measured_text_chars: totals.textCharsMeasured,
|
|
1619
|
+
measured_thinking_chars: totals.thinkingCharsMeasured,
|
|
1620
|
+
measured_tool_use_chars: totals.toolUseCharsMeasured,
|
|
1621
|
+
measured_redacted_block_count: totals.redactedBlockCountMeasured,
|
|
1622
|
+
events_with_measurement: totals.eventsWithMeasurement,
|
|
1623
|
+
text_hygiene_saved_tokens: totals.textHygieneSavedTokens,
|
|
1624
|
+
text_hygiene_saved_chars: totals.textHygieneSavedChars,
|
|
1625
|
+
cliff_avoided_events: totals.cliffAvoidedEvents,
|
|
1626
|
+
cliff_saved_usd: round4(totals.cliffSavedUsd),
|
|
1627
|
+
uptime_sec: uptimeSec,
|
|
1628
|
+
compression_enabled: this.compressionEnabled,
|
|
1629
|
+
allowed_models: getAllowedModelBases(),
|
|
1630
|
+
enabled_providers: getEnabledProviders(),
|
|
1631
|
+
by_model: (() => {
|
|
1632
|
+
const byModel = {};
|
|
1633
|
+
for (const [model, t] of this.totalsByModel) {
|
|
1634
|
+
if (!this.isModelIncludedInStats(model, t.textHygieneSavedTokens, this.otherHasSupportedModel)) {
|
|
1635
|
+
continue;
|
|
1636
|
+
}
|
|
1637
|
+
const key = model || 'unknown';
|
|
1638
|
+
const baseline = Math.round(t.baselineInputWeighted);
|
|
1639
|
+
const actual = Math.round(t.actualInputWeighted);
|
|
1640
|
+
const savedTokens = Math.round(t.baselineInputWeighted - t.actualInputWeighted);
|
|
1641
|
+
const rawSaved = Math.round(t.rawSavedTokens);
|
|
1642
|
+
const savedUsd = round4(priceMode() === 'kosha'
|
|
1643
|
+
? t.pricedSavedUsd
|
|
1644
|
+
: ((t.pricedBaselineInputWeighted - t.pricedActualInputWeighted) * ASSUMED_INPUT_USD_PER_MTOK) / 1e6);
|
|
1645
|
+
const prev = byModel[key];
|
|
1646
|
+
if (prev) {
|
|
1647
|
+
const nextBaseline = prev.baseline_input_weighted + baseline;
|
|
1648
|
+
const nextSaved = prev.saved_tokens + savedTokens;
|
|
1649
|
+
byModel[key] = {
|
|
1650
|
+
requests: prev.requests + t.requests,
|
|
1651
|
+
compressed: prev.compressed + t.compressedRequests,
|
|
1652
|
+
imaged: prev.imaged + t.imagedRequests,
|
|
1653
|
+
text_compressed: prev.text_compressed + t.textCompressedRequests,
|
|
1654
|
+
baseline_input_weighted: nextBaseline,
|
|
1655
|
+
actual_input_weighted: prev.actual_input_weighted + actual,
|
|
1656
|
+
saved_tokens: nextSaved,
|
|
1657
|
+
raw_saved_tokens: prev.raw_saved_tokens + rawSaved,
|
|
1658
|
+
saved_pct: nextBaseline > 0 ? Math.round((nextSaved / nextBaseline) * 1000) / 10 : 0,
|
|
1659
|
+
saved_usd: round4(prev.saved_usd + savedUsd),
|
|
1660
|
+
cliff_avoided_events: prev.cliff_avoided_events + t.cliffAvoidedEvents,
|
|
1661
|
+
cliff_saved_usd: round4(prev.cliff_saved_usd + t.cliffSavedUsd),
|
|
1662
|
+
};
|
|
1663
|
+
}
|
|
1664
|
+
else {
|
|
1665
|
+
byModel[key] = {
|
|
1666
|
+
requests: t.requests,
|
|
1667
|
+
compressed: t.compressedRequests,
|
|
1668
|
+
imaged: t.imagedRequests,
|
|
1669
|
+
text_compressed: t.textCompressedRequests,
|
|
1670
|
+
baseline_input_weighted: baseline,
|
|
1671
|
+
actual_input_weighted: actual,
|
|
1672
|
+
saved_tokens: savedTokens,
|
|
1673
|
+
raw_saved_tokens: rawSaved,
|
|
1674
|
+
saved_pct: baseline > 0 ? Math.round((savedTokens / baseline) * 1000) / 10 : 0,
|
|
1675
|
+
saved_usd: savedUsd,
|
|
1676
|
+
cliff_avoided_events: t.cliffAvoidedEvents,
|
|
1677
|
+
cliff_saved_usd: round4(t.cliffSavedUsd),
|
|
1678
|
+
};
|
|
1679
|
+
}
|
|
1680
|
+
}
|
|
1681
|
+
return byModel;
|
|
1682
|
+
})(),
|
|
1683
|
+
today: daily[daily.length - 1],
|
|
1684
|
+
daily,
|
|
1685
|
+
// Rendered-page cache — a live process gauge, not a fold over the event
|
|
1686
|
+
// ring, so it is the one number here that survives no traffic at all.
|
|
1687
|
+
// `max_bytes` ships alongside `bytes` because utilisation is the actionable
|
|
1688
|
+
// reading: a hit rate near zero means something different when the budget is
|
|
1689
|
+
// full (working set too big) than when `oversized` is climbing (a single
|
|
1690
|
+
// render exceeds the whole budget and is never stored).
|
|
1691
|
+
render_cache: {
|
|
1692
|
+
...renderCacheStats(),
|
|
1693
|
+
max_bytes: renderCacheMaxBytes(),
|
|
1694
|
+
},
|
|
1695
|
+
};
|
|
1696
|
+
return new Response(JSON.stringify(payload, null, 2), {
|
|
1697
|
+
headers: {
|
|
1698
|
+
'content-type': 'application/json',
|
|
1699
|
+
'cache-control': 'no-store',
|
|
1700
|
+
'x-content-type-options': 'nosniff',
|
|
1701
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
1702
|
+
},
|
|
1703
|
+
});
|
|
1704
|
+
}
|
|
1705
|
+
serveRecent() {
|
|
1706
|
+
const latest = this.images[this.images.length - 1];
|
|
1707
|
+
const payload = {
|
|
1708
|
+
recent: this.recent,
|
|
1709
|
+
has_preview: latest !== undefined,
|
|
1710
|
+
preview_meta: latest?.meta ?? '',
|
|
1711
|
+
// Image ids currently resident in the ring. The dashboard uses this to
|
|
1712
|
+
// tell which RecentRow.img_id values still resolve — older ones have
|
|
1713
|
+
// been evicted and their "view" button should be disabled.
|
|
1714
|
+
image_ids: this.images.map((im) => im.id),
|
|
1715
|
+
};
|
|
1716
|
+
return jsonResponse(payload);
|
|
1717
|
+
}
|
|
1718
|
+
/** GET /proxy-latest-png[?id=N] — raw PNG from the image ring. With no id
|
|
1719
|
+
* (or an unknown id) the latest render is returned; ?id=N pulls that
|
|
1720
|
+
* specific image while it's still in the ring. 404 once evicted. */
|
|
1721
|
+
servePng(id) {
|
|
1722
|
+
// Cropping is done client-side via CSS (object-position + overflow:hidden).
|
|
1723
|
+
// Python decoded the PNG to crop server-side; we skip that to avoid
|
|
1724
|
+
// pulling a PNG decoder back in — the CSS approach renders identically.
|
|
1725
|
+
const entry = id !== undefined
|
|
1726
|
+
? this.images.find((im) => im.id === id)
|
|
1727
|
+
: this.images[this.images.length - 1];
|
|
1728
|
+
if (!entry) {
|
|
1729
|
+
return new Response('no image yet', {
|
|
1730
|
+
status: 404,
|
|
1731
|
+
headers: {
|
|
1732
|
+
'cache-control': 'no-store',
|
|
1733
|
+
'x-content-type-options': 'nosniff',
|
|
1734
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
1735
|
+
},
|
|
1736
|
+
});
|
|
1737
|
+
}
|
|
1738
|
+
return new Response(entry.png, {
|
|
1739
|
+
headers: {
|
|
1740
|
+
'content-type': 'image/png',
|
|
1741
|
+
'cache-control': 'no-store',
|
|
1742
|
+
'x-content-type-options': 'nosniff',
|
|
1743
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
1744
|
+
},
|
|
1745
|
+
});
|
|
1746
|
+
}
|
|
1747
|
+
/** GET /api/image-source[?id=N] — the source text the PNG was rendered
|
|
1748
|
+
* from, so the operator can see the text → image conversion side by side.
|
|
1749
|
+
* Falls back to the latest image; 404 if evicted or text wasn't captured. */
|
|
1750
|
+
serveImageSource(id) {
|
|
1751
|
+
const entry = id !== undefined
|
|
1752
|
+
? this.images.find((im) => im.id === id)
|
|
1753
|
+
: this.images[this.images.length - 1];
|
|
1754
|
+
if (!entry || entry.sourceText === undefined) {
|
|
1755
|
+
return jsonResponse({ error: 'no source text' }, 404);
|
|
1756
|
+
}
|
|
1757
|
+
return jsonResponse({ id: entry.id, meta: entry.meta, source_text: entry.sourceText });
|
|
1758
|
+
}
|
|
1759
|
+
serveHtml(port) {
|
|
1760
|
+
return htmlResponse(renderPage(port, dashboardHostLabel()));
|
|
1761
|
+
}
|
|
1762
|
+
/** GET /fragments/<name> — server-rendered htmx fragments. Each one reuses
|
|
1763
|
+
* the corresponding JSON endpoint's payload (via Response.json()) so the
|
|
1764
|
+
* HTML and JSON surfaces can't drift apart. */
|
|
1765
|
+
async serveFragment(name, url, port) {
|
|
1766
|
+
switch (name) {
|
|
1767
|
+
case 'toggle':
|
|
1768
|
+
return htmlResponse(renderToggleFragment(this.compressionEnabled));
|
|
1769
|
+
case 'models':
|
|
1770
|
+
return htmlResponse(renderModelsFragment(getAllowedModelBases(), getConfiguredModelBases(), this.compressionEnabled, listProviderStatuses()));
|
|
1771
|
+
case 'plugins': {
|
|
1772
|
+
const plugins = this.hooks.listPlugins
|
|
1773
|
+
? this.hooks.listPlugins()
|
|
1774
|
+
: mergeStagePlugins([], this.pluginOverrides);
|
|
1775
|
+
return htmlResponse(renderPluginsFragment(plugins));
|
|
1776
|
+
}
|
|
1777
|
+
case 'context-map': {
|
|
1778
|
+
const reqParam = url.searchParams.get('req');
|
|
1779
|
+
if (reqParam) {
|
|
1780
|
+
// Explicit request: show ONLY that one. If its breakdown was evicted
|
|
1781
|
+
// or never recorded (no usage on that completion), say so — don't
|
|
1782
|
+
// silently fall back to the latest request's data under its label.
|
|
1783
|
+
const found = this.contextHistory.find((h) => h.id === Number(reqParam));
|
|
1784
|
+
return htmlResponse(renderContextMapFragment(found, this.contextHistory, !found));
|
|
1785
|
+
}
|
|
1786
|
+
// No specific request → default to the latest.
|
|
1787
|
+
return htmlResponse(renderContextMapFragment(this.contextHistory[this.contextHistory.length - 1], this.contextHistory));
|
|
1788
|
+
}
|
|
1789
|
+
case 'session-summary': {
|
|
1790
|
+
// Lifetime hero — same cumulative payload as the header strip so the
|
|
1791
|
+
// headline and the "$ saved" tiles never disagree and it stops jumping.
|
|
1792
|
+
const s = (await this.serveStats().json());
|
|
1793
|
+
return htmlResponse(renderSessionSummaryFragment(s));
|
|
1794
|
+
}
|
|
1795
|
+
case 'header': {
|
|
1796
|
+
const s = (await this.serveStats().json());
|
|
1797
|
+
return htmlResponse(renderHeaderFragment(s, port));
|
|
1798
|
+
}
|
|
1799
|
+
case 'analytics': {
|
|
1800
|
+
const s = (await this.serveStats().json());
|
|
1801
|
+
return htmlResponse(renderAnalyticsFragment(s));
|
|
1802
|
+
}
|
|
1803
|
+
case 'recent': {
|
|
1804
|
+
const r = (await this.serveRecent().json());
|
|
1805
|
+
return htmlResponse(renderRecentFragment(r));
|
|
1806
|
+
}
|
|
1807
|
+
case 'latest': {
|
|
1808
|
+
const r = (await this.serveRecent().json());
|
|
1809
|
+
const pinRaw = url.searchParams.get('pin');
|
|
1810
|
+
const pinNum = pinRaw != null && pinRaw !== '' ? Number(pinRaw) : NaN;
|
|
1811
|
+
const pin = Number.isFinite(pinNum) ? pinNum : null;
|
|
1812
|
+
const showSource = url.searchParams.get('source') === '1';
|
|
1813
|
+
let sourceText = null;
|
|
1814
|
+
if (showSource) {
|
|
1815
|
+
const entry = pin != null
|
|
1816
|
+
? this.images.find((im) => im.id === pin)
|
|
1817
|
+
: this.images[this.images.length - 1];
|
|
1818
|
+
sourceText = entry?.sourceText ?? null;
|
|
1819
|
+
}
|
|
1820
|
+
return htmlResponse(renderLatestFragment({ payload: r, pin, showSource, sourceText }));
|
|
1821
|
+
}
|
|
1822
|
+
case 'sessions': {
|
|
1823
|
+
const res = await this.serveSessionsJson();
|
|
1824
|
+
if (!res.ok)
|
|
1825
|
+
return htmlResponse(`<div class="status">sessions unavailable</div>`);
|
|
1826
|
+
const p = (await res.json());
|
|
1827
|
+
return htmlResponse(renderSessionsFragment(p));
|
|
1828
|
+
}
|
|
1829
|
+
case 'stats': {
|
|
1830
|
+
const res = await this.serveApiStats();
|
|
1831
|
+
const p = (await res.json());
|
|
1832
|
+
return htmlResponse(renderStatsTableFragment(p));
|
|
1833
|
+
}
|
|
1834
|
+
default:
|
|
1835
|
+
return new Response('unknown fragment', { status: 404 });
|
|
1836
|
+
}
|
|
1837
|
+
}
|
|
1838
|
+
// ---- session / cleanup endpoints --------------------------------------
|
|
1839
|
+
//
|
|
1840
|
+
// Every endpoint below recomputes from disk on demand. The dashboard polls
|
|
1841
|
+
// these on a 5s cadence, which is fine for a single-user dev tool — even at
|
|
1842
|
+
// ~3k events / 1.5 MB the round-trip is <100ms on a warm SSD.
|
|
1843
|
+
statSig(filePath) {
|
|
1844
|
+
try {
|
|
1845
|
+
const st = fs.statSync(filePath);
|
|
1846
|
+
return `${st.ino}:${st.size}:${st.mtimeMs}`;
|
|
1847
|
+
}
|
|
1848
|
+
catch {
|
|
1849
|
+
return null;
|
|
1850
|
+
}
|
|
1851
|
+
}
|
|
1852
|
+
async loadSessionsAggregate() {
|
|
1853
|
+
if (!this.paths) {
|
|
1854
|
+
return { sessions: new Map(), sidecarsBySession: new Map() };
|
|
1855
|
+
}
|
|
1856
|
+
const evSig = this.statSig(this.paths.eventsFile) ?? 'missing';
|
|
1857
|
+
const scSig = this.statSig(this.paths.sidecarDir) ?? 'missing';
|
|
1858
|
+
const sig = `${evSig}|${scSig}`;
|
|
1859
|
+
if (this.apiSessionsCache && this.apiSessionsCache.sig === sig) {
|
|
1860
|
+
return this.apiSessionsCache.result;
|
|
1861
|
+
}
|
|
1862
|
+
if (this.apiSessionsInFlight && this.apiSessionsInFlight.sig === sig) {
|
|
1863
|
+
return this.apiSessionsInFlight.promise;
|
|
1864
|
+
}
|
|
1865
|
+
const p = aggregateSessions(this.paths);
|
|
1866
|
+
this.apiSessionsInFlight = { sig, promise: p };
|
|
1867
|
+
try {
|
|
1868
|
+
const result = await p;
|
|
1869
|
+
const afterEvSig = this.statSig(this.paths.eventsFile) ?? 'missing';
|
|
1870
|
+
const afterScSig = this.statSig(this.paths.sidecarDir) ?? 'missing';
|
|
1871
|
+
if (`${afterEvSig}|${afterScSig}` === sig && evSig !== 'missing') {
|
|
1872
|
+
this.apiSessionsCache = { sig, result };
|
|
1873
|
+
}
|
|
1874
|
+
return result;
|
|
1875
|
+
}
|
|
1876
|
+
finally {
|
|
1877
|
+
if (this.apiSessionsInFlight?.promise === p) {
|
|
1878
|
+
this.apiSessionsInFlight = null;
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
}
|
|
1882
|
+
/** GET /api/sessions.json — grouped sessions enriched with the Claude Code
|
|
1883
|
+
* cross-reference. The body is the top-level `sessions` array; the client
|
|
1884
|
+
* renders a bar chart of the top savers. */
|
|
1885
|
+
async serveSessionsJson(opts = {}) {
|
|
1886
|
+
if (!this.paths)
|
|
1887
|
+
return notConfigured('sessions');
|
|
1888
|
+
const [{ sessions }, ccMap] = await Promise.all([
|
|
1889
|
+
this.loadSessionsAggregate(),
|
|
1890
|
+
this.ccMapFn(),
|
|
1891
|
+
]);
|
|
1892
|
+
const rows = filterSessions(sessions, opts);
|
|
1893
|
+
const enriched = rows.map((s) => ({
|
|
1894
|
+
...s,
|
|
1895
|
+
claudeCode: ccMap.get(s.id) ?? null,
|
|
1896
|
+
}));
|
|
1897
|
+
return jsonResponse({ sessions: enriched, count: enriched.length });
|
|
1898
|
+
}
|
|
1899
|
+
/** GET /api/stats.json — full-history aggregate. Migrated from the
|
|
1900
|
+
* former `inkling stats` CLI. */
|
|
1901
|
+
async serveApiStats() {
|
|
1902
|
+
if (!this.paths)
|
|
1903
|
+
return notConfigured('stats');
|
|
1904
|
+
const sig = this.statSig(this.paths.eventsFile);
|
|
1905
|
+
if (!sig) {
|
|
1906
|
+
this.apiStatsCache = null;
|
|
1907
|
+
return jsonResponse({
|
|
1908
|
+
error: 'no events file yet',
|
|
1909
|
+
path: this.paths.eventsFile,
|
|
1910
|
+
}, 404);
|
|
1911
|
+
}
|
|
1912
|
+
if (this.apiStatsCache && this.apiStatsCache.sig === sig) {
|
|
1913
|
+
return jsonResponse(this.apiStatsCache.body);
|
|
1914
|
+
}
|
|
1915
|
+
if (this.apiStatsInFlight && this.apiStatsInFlight.sig === sig) {
|
|
1916
|
+
const shared = await this.apiStatsInFlight.promise;
|
|
1917
|
+
if (!shared) {
|
|
1918
|
+
return jsonResponse({
|
|
1919
|
+
error: 'no events file yet',
|
|
1920
|
+
path: this.paths.eventsFile,
|
|
1921
|
+
}, 404);
|
|
1922
|
+
}
|
|
1923
|
+
return jsonResponse(shared);
|
|
1924
|
+
}
|
|
1925
|
+
const p = aggregateEventsFile(this.paths.eventsFile).then((result) => {
|
|
1926
|
+
if (!result)
|
|
1927
|
+
return null;
|
|
1928
|
+
return {
|
|
1929
|
+
parsed: result.parsed,
|
|
1930
|
+
dropped: result.dropped,
|
|
1931
|
+
summary: summaryToJson(result.summary),
|
|
1932
|
+
};
|
|
1933
|
+
});
|
|
1934
|
+
this.apiStatsInFlight = { sig, promise: p };
|
|
1935
|
+
try {
|
|
1936
|
+
const body = await p;
|
|
1937
|
+
if (!body) {
|
|
1938
|
+
this.apiStatsCache = null;
|
|
1939
|
+
return jsonResponse({
|
|
1940
|
+
error: 'no events file yet',
|
|
1941
|
+
path: this.paths.eventsFile,
|
|
1942
|
+
}, 404);
|
|
1943
|
+
}
|
|
1944
|
+
if (this.statSig(this.paths.eventsFile) === sig) {
|
|
1945
|
+
this.apiStatsCache = { sig, body };
|
|
1946
|
+
}
|
|
1947
|
+
return jsonResponse(body);
|
|
1948
|
+
}
|
|
1949
|
+
finally {
|
|
1950
|
+
if (this.apiStatsInFlight?.promise === p) {
|
|
1951
|
+
this.apiStatsInFlight = null;
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
/** GET /api/last-turn.json — latest turn & active session savings summary. */
|
|
1956
|
+
serveApiLastTurn() {
|
|
1957
|
+
if (!this.paths)
|
|
1958
|
+
return notConfigured('last-turn');
|
|
1959
|
+
return jsonResponse(readTurnReport(this.paths.eventsFile));
|
|
1960
|
+
}
|
|
1961
|
+
/** GET /api/health — live daemon status & runtime metadata. */
|
|
1962
|
+
serveHealth(port = 47821) {
|
|
1963
|
+
return jsonResponse({
|
|
1964
|
+
ok: true,
|
|
1965
|
+
name: 'fiche',
|
|
1966
|
+
version: this.hooks.version ?? defaultDashboardVersion(),
|
|
1967
|
+
pid: process.pid,
|
|
1968
|
+
host: this.hooks.host ?? '127.0.0.1',
|
|
1969
|
+
port,
|
|
1970
|
+
uptime_sec: round1(Math.max(0, Date.now() / 1000 - this.startedAt)),
|
|
1971
|
+
active_requests: Math.max(0, this.hooks.getActiveRequests?.() ?? 0),
|
|
1972
|
+
compression_enabled: this.compressionEnabled,
|
|
1973
|
+
price_mode: priceMode(),
|
|
1974
|
+
allowed_models: getAllowedModelBases(),
|
|
1975
|
+
enabled_providers: getEnabledProviders(),
|
|
1976
|
+
events_file: this.paths?.eventsFile ?? null,
|
|
1977
|
+
});
|
|
1978
|
+
}
|
|
1979
|
+
/** GET /api/compression — inspect runtime kill switch. */
|
|
1980
|
+
serveCompression() {
|
|
1981
|
+
return jsonResponse({ compression_enabled: this.compressionEnabled });
|
|
1982
|
+
}
|
|
1983
|
+
/** POST /api/compression — flip the runtime kill switch.
|
|
1984
|
+
* Body: { enabled: boolean }. Returns the new state. In-memory only;
|
|
1985
|
+
* restart resets to the default (on). */
|
|
1986
|
+
handleCompressionToggle(body) {
|
|
1987
|
+
if (!body || typeof body !== 'object' || Array.isArray(body) || typeof body.enabled !== 'boolean') {
|
|
1988
|
+
return jsonResponse({ error: 'enabled must be a boolean' }, 400);
|
|
1989
|
+
}
|
|
1990
|
+
this.compressionEnabled = body.enabled;
|
|
1991
|
+
return jsonResponse({ compression_enabled: body.enabled });
|
|
1992
|
+
}
|
|
1993
|
+
/** GET /api/models — current allowed model bases + canonical engine catalog. */
|
|
1994
|
+
serveModels() {
|
|
1995
|
+
const allowed = getAllowedModelBases();
|
|
1996
|
+
const configured = getConfiguredModelBases();
|
|
1997
|
+
const hygieneActive = isTextHygieneActive();
|
|
1998
|
+
const curatedMap = new Map(CURATED_MODEL_CATALOG.map((m) => [m.id, m]));
|
|
1999
|
+
const ids = [];
|
|
2000
|
+
const seen = new Set();
|
|
2001
|
+
for (const id of [
|
|
2002
|
+
...CURATED_MODEL_CATALOG.map((m) => m.id),
|
|
2003
|
+
...configured,
|
|
2004
|
+
...allowed,
|
|
2005
|
+
...listCalibratedProfiles().map((p) => p.model),
|
|
2006
|
+
]) {
|
|
2007
|
+
if (id && !seen.has(id)) {
|
|
2008
|
+
seen.add(id);
|
|
2009
|
+
ids.push(id);
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
const catalog = ids.map((id) => {
|
|
2013
|
+
const curated = curatedMap.get(id);
|
|
2014
|
+
const cal = getCalibratedProfile(id);
|
|
2015
|
+
const tier = readerTier(id);
|
|
2016
|
+
let engineMode;
|
|
2017
|
+
if (tier === 'text' || cal?.band === 'text-only') {
|
|
2018
|
+
engineMode = 'text';
|
|
2019
|
+
}
|
|
2020
|
+
else {
|
|
2021
|
+
const policy = resolveOpticalHistoryPolicy({
|
|
2022
|
+
model: id,
|
|
2023
|
+
textHygieneActive: hygieneActive,
|
|
2024
|
+
});
|
|
2025
|
+
engineMode = policy === 'hybrid' ? 'hybrid' : 'optical';
|
|
2026
|
+
}
|
|
2027
|
+
const hint = engineMode === 'hybrid'
|
|
2028
|
+
? 'Hybrid optical + Text-MMU'
|
|
2029
|
+
: engineMode === 'optical'
|
|
2030
|
+
? 'Optical + 4-layer'
|
|
2031
|
+
: '4-layer text';
|
|
2032
|
+
return {
|
|
2033
|
+
id,
|
|
2034
|
+
label: curated?.label ?? id,
|
|
2035
|
+
family: curated?.family ?? inferModelFamily(id),
|
|
2036
|
+
hint,
|
|
2037
|
+
engine_mode: engineMode,
|
|
2038
|
+
};
|
|
2039
|
+
});
|
|
2040
|
+
return jsonResponse({
|
|
2041
|
+
models: allowed,
|
|
2042
|
+
allowed_models: allowed,
|
|
2043
|
+
configured_models: configured,
|
|
2044
|
+
compression_enabled: this.compressionEnabled,
|
|
2045
|
+
catalog,
|
|
2046
|
+
});
|
|
2047
|
+
}
|
|
2048
|
+
/** POST /api/models — update runtime model scope (`{ model, on }` or `{ models: string[] }`). */
|
|
2049
|
+
handleModelsApiPost(body) {
|
|
2050
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
2051
|
+
return jsonResponse({ error: 'request body must be a JSON object' }, 400);
|
|
2052
|
+
}
|
|
2053
|
+
const obj = body;
|
|
2054
|
+
if ('models' in obj) {
|
|
2055
|
+
if (!Array.isArray(obj.models) || !obj.models.every((m) => typeof m === 'string')) {
|
|
2056
|
+
return jsonResponse({ error: 'models must be an array of strings' }, 400);
|
|
2057
|
+
}
|
|
2058
|
+
const cleaned = obj.models.map((s) => s.trim()).filter(Boolean);
|
|
2059
|
+
this.applyModelBases(cleaned);
|
|
2060
|
+
return this.serveModels();
|
|
2061
|
+
}
|
|
2062
|
+
if (typeof obj.model === 'string' && obj.model.trim().length > 0 && typeof obj.on === 'boolean') {
|
|
2063
|
+
this.handleModelsToggle(obj.model.trim(), obj.on);
|
|
2064
|
+
return this.serveModels();
|
|
2065
|
+
}
|
|
2066
|
+
return jsonResponse({ error: 'body must specify { model: string, on: boolean } or { models: string[] }' }, 400);
|
|
2067
|
+
}
|
|
2068
|
+
/** GET /api/providers — catalog with enabled flags and active provider IDs. */
|
|
2069
|
+
serveProviders() {
|
|
2070
|
+
return jsonResponse({
|
|
2071
|
+
providers: listProviderStatuses(),
|
|
2072
|
+
enabled: getEnabledProviders(),
|
|
2073
|
+
});
|
|
2074
|
+
}
|
|
2075
|
+
/** POST /api/providers — toggle one provider (`{ provider, on }`) or set the list (`{ providers: string[] }`). */
|
|
2076
|
+
handleProvidersApiPost(body) {
|
|
2077
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
2078
|
+
return jsonResponse({ error: 'request body must be a JSON object' }, 400);
|
|
2079
|
+
}
|
|
2080
|
+
const obj = body;
|
|
2081
|
+
if ('providers' in obj) {
|
|
2082
|
+
if (!Array.isArray(obj.providers) || !obj.providers.every((p) => typeof p === 'string')) {
|
|
2083
|
+
return jsonResponse({ error: 'providers must be an array of strings' }, 400);
|
|
2084
|
+
}
|
|
2085
|
+
const parsed = parseProvidersSpec(obj.providers);
|
|
2086
|
+
if (parsed.unknown.length > 0 || parsed.providers === null) {
|
|
2087
|
+
return jsonResponse({ error: `unknown provider(s): ${parsed.unknown.join(', ')}` }, 400);
|
|
2088
|
+
}
|
|
2089
|
+
this.applyEnabledProviders(parsed.providers);
|
|
2090
|
+
return this.serveProviders();
|
|
2091
|
+
}
|
|
2092
|
+
if (typeof obj.provider === 'string' && obj.provider.trim().length > 0 && typeof obj.on === 'boolean') {
|
|
2093
|
+
const id = normalizeProviderId(obj.provider);
|
|
2094
|
+
if (!id) {
|
|
2095
|
+
return jsonResponse({ error: `unknown provider: ${obj.provider.trim()}` }, 400);
|
|
2096
|
+
}
|
|
2097
|
+
this.handleProvidersToggle(id, obj.on);
|
|
2098
|
+
return this.serveProviders();
|
|
2099
|
+
}
|
|
2100
|
+
return jsonResponse({ error: 'body must specify { provider: string, on: boolean } or { providers: string[] }' }, 400);
|
|
2101
|
+
}
|
|
2102
|
+
/** GET /api/plugins — list built-in pipeline stages, custom plugins, and discovered skills. */
|
|
2103
|
+
servePlugins() {
|
|
2104
|
+
const plugins = this.hooks.listPlugins
|
|
2105
|
+
? this.hooks.listPlugins()
|
|
2106
|
+
: mergeStagePlugins([], this.pluginOverrides);
|
|
2107
|
+
return jsonResponse({ plugins });
|
|
2108
|
+
}
|
|
2109
|
+
/** POST /api/plugins — toggle one plugin/skill (`{ id, enabled }`) or all 3rd-party extensions (`{ scope: 'third-party', enabled }`). */
|
|
2110
|
+
handlePluginsApiPost(body) {
|
|
2111
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
2112
|
+
return jsonResponse({ error: 'request body must be a JSON object' }, 400);
|
|
2113
|
+
}
|
|
2114
|
+
const obj = body;
|
|
2115
|
+
if (obj.scope === 'third-party') {
|
|
2116
|
+
if (typeof obj.enabled !== 'boolean') {
|
|
2117
|
+
return jsonResponse({ error: 'enabled must be a boolean' }, 400);
|
|
2118
|
+
}
|
|
2119
|
+
if (this.hooks.setThirdPartyPluginsEnabled) {
|
|
2120
|
+
return jsonResponse(this.hooks.setThirdPartyPluginsEnabled(obj.enabled));
|
|
2121
|
+
}
|
|
2122
|
+
const known = mergeStagePlugins([], this.pluginOverrides);
|
|
2123
|
+
let updatedCount = 0;
|
|
2124
|
+
for (const p of known) {
|
|
2125
|
+
if (!isThirdPartyPlugin(p))
|
|
2126
|
+
continue;
|
|
2127
|
+
this.pluginOverrides[p.id] = obj.enabled;
|
|
2128
|
+
updatedCount += 1;
|
|
2129
|
+
}
|
|
2130
|
+
const plugins = mergeStagePlugins([], this.pluginOverrides);
|
|
2131
|
+
return jsonResponse({ updatedCount, enabled: obj.enabled, plugins });
|
|
2132
|
+
}
|
|
2133
|
+
if (typeof obj.id !== 'string' || !obj.id.trim() || typeof obj.enabled !== 'boolean') {
|
|
2134
|
+
return jsonResponse({ error: 'id must be a non-empty string and enabled must be a boolean' }, 400);
|
|
2135
|
+
}
|
|
2136
|
+
const id = obj.id.trim();
|
|
2137
|
+
const enabled = obj.enabled;
|
|
2138
|
+
if (this.hooks.setPluginEnabled) {
|
|
2139
|
+
const updated = this.hooks.setPluginEnabled(id, enabled);
|
|
2140
|
+
if (!updated)
|
|
2141
|
+
return jsonResponse({ error: `unknown plugin: ${id}` }, 404);
|
|
2142
|
+
return jsonResponse(updated);
|
|
2143
|
+
}
|
|
2144
|
+
const known = mergeStagePlugins([], this.pluginOverrides);
|
|
2145
|
+
if (!known.some((p) => p.id === id)) {
|
|
2146
|
+
return jsonResponse({ error: `unknown plugin: ${id}` }, 404);
|
|
2147
|
+
}
|
|
2148
|
+
this.pluginOverrides[id] = enabled;
|
|
2149
|
+
const plugins = mergeStagePlugins([], this.pluginOverrides);
|
|
2150
|
+
const plugin = plugins.find((p) => p.id === id);
|
|
2151
|
+
return jsonResponse({ plugin, plugins });
|
|
2152
|
+
}
|
|
2153
|
+
/** POST /api/shutdown — initiate graceful daemon shutdown. */
|
|
2154
|
+
handleShutdown() {
|
|
2155
|
+
if (this.hooks.onShutdown) {
|
|
2156
|
+
setImmediate(() => this.hooks.onShutdown?.());
|
|
2157
|
+
}
|
|
2158
|
+
return jsonResponse({ shutting_down: true });
|
|
2159
|
+
}
|
|
2160
|
+
/** GET /api/mmu/stats — Context-MMU counters & bounded page summaries. */
|
|
2161
|
+
serveMmuStats(sessionKey) {
|
|
2162
|
+
if (sessionKey !== undefined && !sessionKey.trim()) {
|
|
2163
|
+
return mmuJsonResponse({ error: 'sessionKey must be a non-empty string' }, 400);
|
|
2164
|
+
}
|
|
2165
|
+
const store = getGlobalMmuStore();
|
|
2166
|
+
const sk = sessionKey?.trim();
|
|
2167
|
+
const pages = store.listPages(sk);
|
|
2168
|
+
const safePages = pages.slice(0, 50).map((p) => {
|
|
2169
|
+
if (sk)
|
|
2170
|
+
return p;
|
|
2171
|
+
const { factTokens: _omitted, ...rest } = p;
|
|
2172
|
+
return rest;
|
|
2173
|
+
});
|
|
2174
|
+
return mmuJsonResponse({
|
|
2175
|
+
stats: store.getStats(),
|
|
2176
|
+
pageCount: pages.length,
|
|
2177
|
+
pages: safePages,
|
|
2178
|
+
limits: store.getLimits(),
|
|
2179
|
+
prefixTape: getGlobalPrefixTape().getStats(),
|
|
2180
|
+
});
|
|
2181
|
+
}
|
|
2182
|
+
/** GET /api/mmu/page — retrieve exact slice by `id`/`pageId` or search by `query`. */
|
|
2183
|
+
serveMmuPage(params) {
|
|
2184
|
+
const pageId = (params.get('id') ?? params.get('pageId'))?.trim() || undefined;
|
|
2185
|
+
const query = params.get('query')?.trim() || undefined;
|
|
2186
|
+
if (params.has('sessionKey') && !params.get('sessionKey').trim()) {
|
|
2187
|
+
return mmuJsonResponse({ error: 'sessionKey must be a non-empty string' }, 400);
|
|
2188
|
+
}
|
|
2189
|
+
const sessionKey = params.get('sessionKey')?.trim() || undefined;
|
|
2190
|
+
if (!pageId && !query) {
|
|
2191
|
+
return mmuJsonResponse({ error: 'id/pageId or query parameter is required' }, 400);
|
|
2192
|
+
}
|
|
2193
|
+
if (query && query.length > 512) {
|
|
2194
|
+
return mmuJsonResponse({ error: 'query must be <= 512 chars' }, 400);
|
|
2195
|
+
}
|
|
2196
|
+
const parseOptPosInt = (name) => {
|
|
2197
|
+
const raw = params.get(name);
|
|
2198
|
+
if (raw === null || raw.trim() === '')
|
|
2199
|
+
return undefined;
|
|
2200
|
+
const n = Number(raw);
|
|
2201
|
+
return Number.isSafeInteger(n) && n >= 1 ? n : NaN;
|
|
2202
|
+
};
|
|
2203
|
+
const startLine = parseOptPosInt('startLine');
|
|
2204
|
+
const endLine = parseOptPosInt('endLine');
|
|
2205
|
+
const maxLinesRaw = parseOptPosInt('maxLines');
|
|
2206
|
+
if (Number.isNaN(startLine) || Number.isNaN(endLine) || Number.isNaN(maxLinesRaw)) {
|
|
2207
|
+
return mmuJsonResponse({ error: 'startLine, endLine, and maxLines must be positive integers' }, 400);
|
|
2208
|
+
}
|
|
2209
|
+
const maxLines = maxLinesRaw !== undefined ? Math.min(500, maxLinesRaw) : 120;
|
|
2210
|
+
const store = getGlobalMmuStore();
|
|
2211
|
+
if (pageId) {
|
|
2212
|
+
const hit = store.derefPage(pageId, { sessionKey, startLine, endLine, query, maxLines });
|
|
2213
|
+
if (!hit)
|
|
2214
|
+
return mmuJsonResponse({ error: `MMU page not found: ${pageId}` }, 404);
|
|
2215
|
+
return mmuJsonResponse({
|
|
2216
|
+
pageId: hit.page.id,
|
|
2217
|
+
refId: hit.page.refId,
|
|
2218
|
+
sessionKey: hit.page.sessionKey,
|
|
2219
|
+
filePath: hit.page.filePath,
|
|
2220
|
+
lineCount: hit.page.lineCount,
|
|
2221
|
+
startLine: hit.startLine,
|
|
2222
|
+
endLine: hit.endLine,
|
|
2223
|
+
text: hit.text,
|
|
2224
|
+
symbols: hit.page.symbols,
|
|
2225
|
+
});
|
|
2226
|
+
}
|
|
2227
|
+
const matches = store.searchPages(query, sessionKey);
|
|
2228
|
+
if (matches.length === 0) {
|
|
2229
|
+
return mmuJsonResponse({ error: `no MMU pages matching query: ${query}`, matches: [] }, 404);
|
|
2230
|
+
}
|
|
2231
|
+
const top = matches[0];
|
|
2232
|
+
const hit = store.derefPage(top.page.id, {
|
|
2233
|
+
sessionKey: top.page.sessionKey,
|
|
2234
|
+
startLine,
|
|
2235
|
+
endLine,
|
|
2236
|
+
query,
|
|
2237
|
+
maxLines,
|
|
2238
|
+
});
|
|
2239
|
+
return mmuJsonResponse({
|
|
2240
|
+
pageId: top.page.id,
|
|
2241
|
+
refId: top.page.refId,
|
|
2242
|
+
sessionKey: top.page.sessionKey,
|
|
2243
|
+
filePath: top.page.filePath,
|
|
2244
|
+
lineCount: top.page.lineCount,
|
|
2245
|
+
startLine: hit?.startLine ?? 1,
|
|
2246
|
+
endLine: hit?.endLine ?? 0,
|
|
2247
|
+
text: hit?.text ?? '',
|
|
2248
|
+
symbols: top.page.symbols,
|
|
2249
|
+
matches: matches.slice(0, 5).map((m) => ({
|
|
2250
|
+
pageId: m.page.id,
|
|
2251
|
+
refId: m.page.refId,
|
|
2252
|
+
filePath: m.page.filePath,
|
|
2253
|
+
score: m.score,
|
|
2254
|
+
matchedLine: m.matchedLine,
|
|
2255
|
+
})),
|
|
2256
|
+
});
|
|
2257
|
+
}
|
|
2258
|
+
/** GET /api/calibration — Auto-Canary calibrated visual model profiles. */
|
|
2259
|
+
serveCalibration() {
|
|
2260
|
+
return mmuJsonResponse({ profiles: listCalibratedProfiles() });
|
|
2261
|
+
}
|
|
2262
|
+
/** POST /fragments/models — add/remove ONE model (Claude or GPT) from the
|
|
2263
|
+
* runtime compress scope. The model checks read this live. Persisted via
|
|
2264
|
+
* the host's `persistModelBases` hook when provided (Node writes the
|
|
2265
|
+
* config file); otherwise in-memory only and restart resets to the
|
|
2266
|
+
* INKLING_MODELS env / built-in default. */
|
|
2267
|
+
handleModelsToggle(model, on) {
|
|
2268
|
+
const next = new Set(getAllowedModelBases());
|
|
2269
|
+
if (on)
|
|
2270
|
+
next.add(model);
|
|
2271
|
+
else
|
|
2272
|
+
next.delete(model);
|
|
2273
|
+
this.applyModelBases([...next]);
|
|
2274
|
+
}
|
|
2275
|
+
/** POST /fragments/models with {list} — replace the WHOLE runtime compress
|
|
2276
|
+
* scope from the INKLING_MODELS textbox. Same CSV shape as the env var;
|
|
2277
|
+
* empty or off/false/0/no/none = compress nothing. Persistence as above. */
|
|
2278
|
+
handleModelsSet(csv) {
|
|
2279
|
+
const trimmed = csv.trim();
|
|
2280
|
+
const bases = !trimmed || /^(0|false|no|off|none)$/i.test(trimmed)
|
|
2281
|
+
? []
|
|
2282
|
+
: trimmed.split(',').map((s) => s.trim()).filter(Boolean);
|
|
2283
|
+
this.applyModelBases(bases);
|
|
2284
|
+
}
|
|
2285
|
+
applyModelBases(bases) {
|
|
2286
|
+
setAllowedModelBases(bases);
|
|
2287
|
+
try {
|
|
2288
|
+
this.persistModelBases?.(bases);
|
|
2289
|
+
}
|
|
2290
|
+
catch {
|
|
2291
|
+
// Persistence is best-effort; the live flip already took effect.
|
|
2292
|
+
}
|
|
2293
|
+
}
|
|
2294
|
+
/** Toggle one provider in runtime scope and persist when configured. */
|
|
2295
|
+
handleProvidersToggle(provider, on) {
|
|
2296
|
+
const next = new Set(getEnabledProviders());
|
|
2297
|
+
if (on)
|
|
2298
|
+
next.add(provider);
|
|
2299
|
+
else
|
|
2300
|
+
next.delete(provider);
|
|
2301
|
+
this.applyEnabledProviders([...next]);
|
|
2302
|
+
}
|
|
2303
|
+
applyEnabledProviders(providers) {
|
|
2304
|
+
setEnabledProviders(providers);
|
|
2305
|
+
try {
|
|
2306
|
+
this.hooks.onProvidersPersist?.(providers);
|
|
2307
|
+
}
|
|
2308
|
+
catch {
|
|
2309
|
+
// Persistence is best-effort; the live flip already took effect.
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
/** GET /favicon.svg, /favicon.ico, /apple-touch-icon*.png */
|
|
2313
|
+
serveFavicon(sub, headOnly = false) {
|
|
2314
|
+
return serveFavicon(sub, headOnly);
|
|
2315
|
+
}
|
|
2316
|
+
}
|
|
2317
|
+
export function serveFavicon(sub, headOnly = false) {
|
|
2318
|
+
if (sub === 'empty') {
|
|
2319
|
+
return new Response(null, { status: 204 });
|
|
2320
|
+
}
|
|
2321
|
+
return new Response(headOnly ? null : FICHE_ICON_SVG, {
|
|
2322
|
+
status: 200,
|
|
2323
|
+
headers: {
|
|
2324
|
+
'content-type': 'image/svg+xml; charset=utf-8',
|
|
2325
|
+
'cache-control': 'public, max-age=3600',
|
|
2326
|
+
},
|
|
2327
|
+
});
|
|
2328
|
+
}
|
|
2329
|
+
const CURATED_MODEL_CATALOG = [
|
|
2330
|
+
{ id: 'claude-fable-5', label: 'Claude Fable 5', family: 'Anthropic' },
|
|
2331
|
+
{ id: 'claude-opus-5', label: 'Opus 5', family: 'Anthropic' },
|
|
2332
|
+
{ id: 'claude-opus-5-5', label: 'Claude Opus 5.5', family: 'Anthropic' },
|
|
2333
|
+
{ id: 'claude-sonnet-5-5', label: 'Sonnet 5.5', family: 'Anthropic' },
|
|
2334
|
+
{ id: 'gemini', label: 'Gemini (all versions)', family: 'Google' },
|
|
2335
|
+
{ id: 'gemini-3.6-flash', label: 'Gemini 3.6 Flash', family: 'Google' },
|
|
2336
|
+
{ id: 'gemini-3.7-flash', label: 'Gemini 3.7 Flash', family: 'Google' },
|
|
2337
|
+
{ id: 'gemini-3.8-flash', label: 'Gemini 3.8 Flash', family: 'Google' },
|
|
2338
|
+
{ id: 'gemini-4', label: 'Gemini 4', family: 'Google' },
|
|
2339
|
+
{ id: 'gpt-5.6-sol', label: 'GPT 5.6 Sol', family: 'OpenAI' },
|
|
2340
|
+
{ id: 'gpt-6-sol', label: 'GPT-6 Sol', family: 'OpenAI' },
|
|
2341
|
+
{ id: 'gpt-6.1-sol', label: 'GPT-6.1 Sol', family: 'OpenAI' },
|
|
2342
|
+
{ id: 'gpt-6.2-sol', label: 'GPT-6.2 Sol', family: 'OpenAI' },
|
|
2343
|
+
{ id: 'gpt-5.5', label: 'GPT 5.5', family: 'OpenAI' },
|
|
2344
|
+
{ id: 'gpt-6-astra', label: 'GPT-6 Astra', family: 'OpenAI' },
|
|
2345
|
+
{ id: 'gpt-6.2-astra', label: 'GPT-6.2 Astra', family: 'OpenAI' },
|
|
2346
|
+
{ id: 'gpt-6.1-terra', label: 'GPT-6.1 Terra', family: 'OpenAI' },
|
|
2347
|
+
{ id: 'gpt-6-luna', label: 'GPT-6 Luna', family: 'OpenAI' },
|
|
2348
|
+
{ id: 'grok-4.6', label: 'Grok 4.6', family: 'xAI' },
|
|
2349
|
+
{ id: 'grok-4.5', label: 'Grok 4.5', family: 'xAI' },
|
|
2350
|
+
{ id: 'deepseek', label: 'DeepSeek', family: 'DeepSeek' },
|
|
2351
|
+
{ id: 'kimi', label: 'Kimi', family: 'Moonshot' },
|
|
2352
|
+
{ id: 'glm', label: 'GLM', family: 'Zhipu' },
|
|
2353
|
+
];
|
|
2354
|
+
function inferModelFamily(id) {
|
|
2355
|
+
const lower = id.toLowerCase();
|
|
2356
|
+
const base = lower.split('/').pop() ?? lower;
|
|
2357
|
+
if (base.startsWith('claude'))
|
|
2358
|
+
return 'Anthropic';
|
|
2359
|
+
if (base.includes('gemini') || base.startsWith('gemma'))
|
|
2360
|
+
return 'Google';
|
|
2361
|
+
if (base.startsWith('gpt') || base.startsWith('o1') || base.startsWith('o3') || base.startsWith('o4')) {
|
|
2362
|
+
return 'OpenAI';
|
|
2363
|
+
}
|
|
2364
|
+
if (base.startsWith('grok'))
|
|
2365
|
+
return 'xAI';
|
|
2366
|
+
if (base.startsWith('deepseek'))
|
|
2367
|
+
return 'DeepSeek';
|
|
2368
|
+
if (base.startsWith('kimi') || base.includes('moonshot'))
|
|
2369
|
+
return 'Moonshot';
|
|
2370
|
+
if (base.startsWith('glm') || base.startsWith('zai-glm'))
|
|
2371
|
+
return 'Zhipu';
|
|
2372
|
+
if (base.startsWith('qwen'))
|
|
2373
|
+
return 'Alibaba';
|
|
2374
|
+
if (/^(?:mistral|mixtral|codestral|devstral|ministral|magistral|pixtral)/.test(base)) {
|
|
2375
|
+
return 'Mistral';
|
|
2376
|
+
}
|
|
2377
|
+
if (base.includes('llama') || base.startsWith('codellama'))
|
|
2378
|
+
return 'Meta';
|
|
2379
|
+
if (base.startsWith('minimax'))
|
|
2380
|
+
return 'MiniMax';
|
|
2381
|
+
if (base.startsWith('command-') || base.startsWith('c4ai-aya'))
|
|
2382
|
+
return 'Cohere';
|
|
2383
|
+
return 'Custom';
|
|
2384
|
+
}
|
|
2385
|
+
function jsonResponse(body, status = 200) {
|
|
2386
|
+
return new Response(JSON.stringify(body), {
|
|
2387
|
+
status,
|
|
2388
|
+
headers: {
|
|
2389
|
+
'content-type': 'application/json',
|
|
2390
|
+
'cache-control': 'no-store',
|
|
2391
|
+
'x-content-type-options': 'nosniff',
|
|
2392
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
2393
|
+
},
|
|
2394
|
+
});
|
|
2395
|
+
}
|
|
2396
|
+
function mmuJsonResponse(body, status = 200) {
|
|
2397
|
+
return new Response(JSON.stringify(body), {
|
|
2398
|
+
status,
|
|
2399
|
+
headers: {
|
|
2400
|
+
'content-type': 'application/json',
|
|
2401
|
+
'cache-control': 'no-store',
|
|
2402
|
+
'x-content-type-options': 'nosniff',
|
|
2403
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
2404
|
+
},
|
|
2405
|
+
});
|
|
2406
|
+
}
|
|
2407
|
+
function notConfigured(what) {
|
|
2408
|
+
// The dashboard was constructed without SessionsPaths (e.g. a legacy host
|
|
2409
|
+
// that doesn't track to disk). Return 503 so the client can surface a
|
|
2410
|
+
// helpful error rather than failing silently.
|
|
2411
|
+
return jsonResponse({ error: `${what} unavailable: dashboard not configured with event paths` }, 503);
|
|
2412
|
+
}
|
|
2413
|
+
function round1(n) {
|
|
2414
|
+
return Math.round(n * 10) / 10;
|
|
2415
|
+
}
|
|
2416
|
+
function round4(n) {
|
|
2417
|
+
return Math.round(n * 10000) / 10000;
|
|
2418
|
+
}
|
|
2419
|
+
/** Match dashboard paths (handle query strings on /proxy-latest-png). */
|
|
2420
|
+
export function dashboardPath(pathname) {
|
|
2421
|
+
if (pathname === '/' || pathname === '/dashboard')
|
|
2422
|
+
return { kind: 'html' };
|
|
2423
|
+
if (pathname === '/favicon.svg' || pathname === '/favicon.ico')
|
|
2424
|
+
return { kind: 'favicon', sub: 'svg' };
|
|
2425
|
+
if (pathname === '/apple-touch-icon.png' || pathname === '/apple-touch-icon-precomposed.png') {
|
|
2426
|
+
return { kind: 'favicon', sub: 'empty' };
|
|
2427
|
+
}
|
|
2428
|
+
if (pathname === '/proxy-stats')
|
|
2429
|
+
return { kind: 'stats' };
|
|
2430
|
+
if (pathname === '/proxy-recent')
|
|
2431
|
+
return { kind: 'recent' };
|
|
2432
|
+
if (pathname === '/proxy-latest-png')
|
|
2433
|
+
return { kind: 'png' };
|
|
2434
|
+
if (pathname === '/api/sessions.json')
|
|
2435
|
+
return { kind: 'api-sessions' };
|
|
2436
|
+
if (pathname === '/api/stats.json')
|
|
2437
|
+
return { kind: 'api-stats' };
|
|
2438
|
+
if (pathname === '/api/last-turn.json')
|
|
2439
|
+
return { kind: 'api-last-turn' };
|
|
2440
|
+
if (pathname === '/api/current-session.json')
|
|
2441
|
+
return { kind: 'current-session' };
|
|
2442
|
+
if (pathname === '/api/health')
|
|
2443
|
+
return { kind: 'api-health' };
|
|
2444
|
+
if (pathname === '/api/compression')
|
|
2445
|
+
return { kind: 'api-compression' };
|
|
2446
|
+
if (pathname === '/api/models')
|
|
2447
|
+
return { kind: 'api-models' };
|
|
2448
|
+
if (pathname === '/api/providers')
|
|
2449
|
+
return { kind: 'api-providers' };
|
|
2450
|
+
if (pathname === '/api/plugins')
|
|
2451
|
+
return { kind: 'api-plugins' };
|
|
2452
|
+
if (pathname === '/api/shutdown')
|
|
2453
|
+
return { kind: 'api-shutdown' };
|
|
2454
|
+
if (pathname === '/api/image-source')
|
|
2455
|
+
return { kind: 'api-image-source' };
|
|
2456
|
+
if (pathname === '/api/mmu/stats')
|
|
2457
|
+
return { kind: 'api-mmu-stats' };
|
|
2458
|
+
if (pathname === '/api/mmu/page')
|
|
2459
|
+
return { kind: 'api-mmu-page' };
|
|
2460
|
+
if (pathname === '/api/calibration')
|
|
2461
|
+
return { kind: 'api-calibration' };
|
|
2462
|
+
if (pathname.startsWith('/fragments/')) {
|
|
2463
|
+
return { kind: 'fragment', name: pathname.slice('/fragments/'.length) };
|
|
2464
|
+
}
|
|
2465
|
+
return null;
|
|
2466
|
+
}
|
|
2467
|
+
export function isDashboardMutation(route, method) {
|
|
2468
|
+
return method === 'POST' && (route.kind === 'api-compression'
|
|
2469
|
+
|| route.kind === 'api-models'
|
|
2470
|
+
|| route.kind === 'api-providers'
|
|
2471
|
+
|| route.kind === 'api-plugins'
|
|
2472
|
+
|| route.kind === 'api-shutdown'
|
|
2473
|
+
|| (route.kind === 'fragment' && (route.name === 'toggle' || route.name === 'models' || route.name === 'plugins')));
|
|
2474
|
+
}
|
|
2475
|
+
function methodNotAllowed(allow) {
|
|
2476
|
+
return new Response(JSON.stringify({ error: `method not allowed; use ${allow}` }), {
|
|
2477
|
+
status: 405,
|
|
2478
|
+
headers: { allow, 'content-type': 'application/json' },
|
|
2479
|
+
});
|
|
2480
|
+
}
|
|
2481
|
+
async function parseJsonRequestBody(readBody) {
|
|
2482
|
+
let raw;
|
|
2483
|
+
try {
|
|
2484
|
+
raw = await readBody();
|
|
2485
|
+
}
|
|
2486
|
+
catch {
|
|
2487
|
+
return { ok: false, response: jsonResponse({ error: 'bad request body' }, 400) };
|
|
2488
|
+
}
|
|
2489
|
+
if (!raw.trim())
|
|
2490
|
+
return { ok: true, value: {} };
|
|
2491
|
+
try {
|
|
2492
|
+
return { ok: true, value: JSON.parse(raw) };
|
|
2493
|
+
}
|
|
2494
|
+
catch (e) {
|
|
2495
|
+
return {
|
|
2496
|
+
ok: false,
|
|
2497
|
+
response: jsonResponse({ error: 'bad request body', detail: e.message }, 400),
|
|
2498
|
+
};
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
/** Dispatch a matched DashboardRoute to its handler. Returns `405` on `/api/*`
|
|
2502
|
+
* and `/proxy-*` method mismatches so non-GET calls never leak to upstream. */
|
|
2503
|
+
export async function dispatchDashboard(dashboard, route, method, url, port, readBody) {
|
|
2504
|
+
switch (route.kind) {
|
|
2505
|
+
case 'html':
|
|
2506
|
+
if (method !== 'GET')
|
|
2507
|
+
return undefined;
|
|
2508
|
+
return dashboard.serveHtml(port);
|
|
2509
|
+
case 'favicon':
|
|
2510
|
+
if (method !== 'GET' && method !== 'HEAD')
|
|
2511
|
+
return methodNotAllowed('GET, HEAD');
|
|
2512
|
+
return dashboard.serveFavicon(route.sub, method === 'HEAD');
|
|
2513
|
+
case 'stats':
|
|
2514
|
+
if (method !== 'GET')
|
|
2515
|
+
return methodNotAllowed('GET');
|
|
2516
|
+
return dashboard.serveStats();
|
|
2517
|
+
case 'recent':
|
|
2518
|
+
if (method !== 'GET')
|
|
2519
|
+
return methodNotAllowed('GET');
|
|
2520
|
+
return dashboard.serveRecent();
|
|
2521
|
+
case 'png': {
|
|
2522
|
+
if (method !== 'GET')
|
|
2523
|
+
return methodNotAllowed('GET');
|
|
2524
|
+
const idRaw = url.searchParams.get('id');
|
|
2525
|
+
const idNum = idRaw != null ? Number(idRaw) : NaN;
|
|
2526
|
+
return dashboard.servePng(Number.isFinite(idNum) ? idNum : undefined);
|
|
2527
|
+
}
|
|
2528
|
+
case 'api-image-source': {
|
|
2529
|
+
if (method !== 'GET')
|
|
2530
|
+
return methodNotAllowed('GET');
|
|
2531
|
+
const idRaw = url.searchParams.get('id');
|
|
2532
|
+
const idNum = idRaw != null ? Number(idRaw) : NaN;
|
|
2533
|
+
return dashboard.serveImageSource(Number.isFinite(idNum) ? idNum : undefined);
|
|
2534
|
+
}
|
|
2535
|
+
case 'api-sessions':
|
|
2536
|
+
if (method !== 'GET')
|
|
2537
|
+
return methodNotAllowed('GET');
|
|
2538
|
+
return dashboard.serveSessionsJson({
|
|
2539
|
+
project: url.searchParams.get('project') ?? undefined,
|
|
2540
|
+
since: url.searchParams.get('since') ?? undefined,
|
|
2541
|
+
});
|
|
2542
|
+
case 'api-stats':
|
|
2543
|
+
if (method !== 'GET')
|
|
2544
|
+
return methodNotAllowed('GET');
|
|
2545
|
+
return dashboard.serveApiStats();
|
|
2546
|
+
case 'api-last-turn':
|
|
2547
|
+
if (method !== 'GET')
|
|
2548
|
+
return methodNotAllowed('GET');
|
|
2549
|
+
return dashboard.serveApiLastTurn();
|
|
2550
|
+
case 'current-session':
|
|
2551
|
+
if (method !== 'GET')
|
|
2552
|
+
return methodNotAllowed('GET');
|
|
2553
|
+
return dashboard.serveCurrentSessionJson();
|
|
2554
|
+
case 'api-health':
|
|
2555
|
+
if (method !== 'GET')
|
|
2556
|
+
return methodNotAllowed('GET');
|
|
2557
|
+
return dashboard.serveHealth(port);
|
|
2558
|
+
case 'api-compression': {
|
|
2559
|
+
if (method === 'GET')
|
|
2560
|
+
return dashboard.serveCompression();
|
|
2561
|
+
if (method !== 'POST')
|
|
2562
|
+
return methodNotAllowed('GET, POST');
|
|
2563
|
+
const parsed = await parseJsonRequestBody(readBody);
|
|
2564
|
+
if (!parsed.ok)
|
|
2565
|
+
return parsed.response;
|
|
2566
|
+
if (!parsed.value || typeof parsed.value !== 'object' || Array.isArray(parsed.value)) {
|
|
2567
|
+
return jsonResponse({ error: 'enabled must be a boolean' }, 400);
|
|
2568
|
+
}
|
|
2569
|
+
return dashboard.handleCompressionToggle(parsed.value);
|
|
2570
|
+
}
|
|
2571
|
+
case 'api-models': {
|
|
2572
|
+
if (method === 'GET')
|
|
2573
|
+
return dashboard.serveModels();
|
|
2574
|
+
if (method !== 'POST')
|
|
2575
|
+
return methodNotAllowed('GET, POST');
|
|
2576
|
+
const parsed = await parseJsonRequestBody(readBody);
|
|
2577
|
+
if (!parsed.ok)
|
|
2578
|
+
return parsed.response;
|
|
2579
|
+
return dashboard.handleModelsApiPost(parsed.value);
|
|
2580
|
+
}
|
|
2581
|
+
case 'api-providers': {
|
|
2582
|
+
if (method === 'GET')
|
|
2583
|
+
return dashboard.serveProviders();
|
|
2584
|
+
if (method !== 'POST')
|
|
2585
|
+
return methodNotAllowed('GET, POST');
|
|
2586
|
+
const parsed = await parseJsonRequestBody(readBody);
|
|
2587
|
+
if (!parsed.ok)
|
|
2588
|
+
return parsed.response;
|
|
2589
|
+
return dashboard.handleProvidersApiPost(parsed.value);
|
|
2590
|
+
}
|
|
2591
|
+
case 'api-plugins': {
|
|
2592
|
+
if (method === 'GET')
|
|
2593
|
+
return dashboard.servePlugins();
|
|
2594
|
+
if (method !== 'POST')
|
|
2595
|
+
return methodNotAllowed('GET, POST');
|
|
2596
|
+
const parsed = await parseJsonRequestBody(readBody);
|
|
2597
|
+
if (!parsed.ok)
|
|
2598
|
+
return parsed.response;
|
|
2599
|
+
return dashboard.handlePluginsApiPost(parsed.value);
|
|
2600
|
+
}
|
|
2601
|
+
case 'api-shutdown':
|
|
2602
|
+
if (method !== 'POST')
|
|
2603
|
+
return methodNotAllowed('POST');
|
|
2604
|
+
return dashboard.handleShutdown();
|
|
2605
|
+
case 'api-mmu-stats':
|
|
2606
|
+
if (method !== 'GET')
|
|
2607
|
+
return methodNotAllowed('GET');
|
|
2608
|
+
return dashboard.serveMmuStats(url.searchParams.has('sessionKey') ? url.searchParams.get('sessionKey') : undefined);
|
|
2609
|
+
case 'api-mmu-page':
|
|
2610
|
+
if (method !== 'GET')
|
|
2611
|
+
return methodNotAllowed('GET');
|
|
2612
|
+
return dashboard.serveMmuPage(url.searchParams);
|
|
2613
|
+
case 'api-calibration':
|
|
2614
|
+
if (method !== 'GET')
|
|
2615
|
+
return methodNotAllowed('GET');
|
|
2616
|
+
return dashboard.serveCalibration();
|
|
2617
|
+
case 'fragment': {
|
|
2618
|
+
if (route.name === 'toggle' && method === 'POST') {
|
|
2619
|
+
let enabled = false;
|
|
2620
|
+
try {
|
|
2621
|
+
const raw = await readBody();
|
|
2622
|
+
try {
|
|
2623
|
+
enabled = JSON.parse(raw).enabled === true;
|
|
2624
|
+
}
|
|
2625
|
+
catch {
|
|
2626
|
+
enabled = new URLSearchParams(raw).get('enabled') === 'true';
|
|
2627
|
+
}
|
|
2628
|
+
}
|
|
2629
|
+
catch {
|
|
2630
|
+
return new Response('bad request body', { status: 400 });
|
|
2631
|
+
}
|
|
2632
|
+
dashboard.handleCompressionToggle({ enabled });
|
|
2633
|
+
return dashboard.serveFragment('toggle', url, port);
|
|
2634
|
+
}
|
|
2635
|
+
if (route.name === 'models' && method === 'POST') {
|
|
2636
|
+
let model = '';
|
|
2637
|
+
let provider = '';
|
|
2638
|
+
let on = false;
|
|
2639
|
+
let list = null;
|
|
2640
|
+
try {
|
|
2641
|
+
const raw = await readBody();
|
|
2642
|
+
try {
|
|
2643
|
+
const j = JSON.parse(raw);
|
|
2644
|
+
model = typeof j.model === 'string' ? j.model : '';
|
|
2645
|
+
provider = typeof j.provider === 'string' ? j.provider : '';
|
|
2646
|
+
on = j.on === true;
|
|
2647
|
+
if (typeof j.list === 'string')
|
|
2648
|
+
list = j.list;
|
|
2649
|
+
}
|
|
2650
|
+
catch {
|
|
2651
|
+
const p = new URLSearchParams(raw);
|
|
2652
|
+
model = p.get('model') ?? '';
|
|
2653
|
+
provider = p.get('provider') ?? '';
|
|
2654
|
+
on = p.get('on') === 'true';
|
|
2655
|
+
list = p.get('list');
|
|
2656
|
+
}
|
|
2657
|
+
}
|
|
2658
|
+
catch {
|
|
2659
|
+
return new Response('bad request body', { status: 400 });
|
|
2660
|
+
}
|
|
2661
|
+
if (provider) {
|
|
2662
|
+
const id = normalizeProviderId(provider);
|
|
2663
|
+
if (!id)
|
|
2664
|
+
return new Response('unknown provider', { status: 400 });
|
|
2665
|
+
dashboard.handleProvidersToggle(id, on);
|
|
2666
|
+
}
|
|
2667
|
+
else if (list !== null)
|
|
2668
|
+
dashboard.handleModelsSet(list);
|
|
2669
|
+
else if (model)
|
|
2670
|
+
dashboard.handleModelsToggle(model, on);
|
|
2671
|
+
return dashboard.serveFragment('models', url, port);
|
|
2672
|
+
}
|
|
2673
|
+
if (route.name === 'plugins' && method === 'POST') {
|
|
2674
|
+
let payload;
|
|
2675
|
+
try {
|
|
2676
|
+
const raw = await readBody();
|
|
2677
|
+
try {
|
|
2678
|
+
payload = JSON.parse(raw);
|
|
2679
|
+
}
|
|
2680
|
+
catch {
|
|
2681
|
+
const p = new URLSearchParams(raw);
|
|
2682
|
+
const scope = p.get('scope');
|
|
2683
|
+
const id = p.get('id');
|
|
2684
|
+
const enabledRaw = p.get('enabled');
|
|
2685
|
+
const enabled = enabledRaw === 'true' ? true : enabledRaw === 'false' ? false : undefined;
|
|
2686
|
+
payload = scope ? { scope, enabled } : { id, enabled };
|
|
2687
|
+
}
|
|
2688
|
+
}
|
|
2689
|
+
catch {
|
|
2690
|
+
return new Response('bad request body', { status: 400 });
|
|
2691
|
+
}
|
|
2692
|
+
const mutationRes = dashboard.handlePluginsApiPost(payload);
|
|
2693
|
+
if (!mutationRes.ok)
|
|
2694
|
+
return mutationRes;
|
|
2695
|
+
return dashboard.serveFragment('plugins', url, port);
|
|
2696
|
+
}
|
|
2697
|
+
if (method !== 'GET')
|
|
2698
|
+
return methodNotAllowed('GET');
|
|
2699
|
+
return dashboard.serveFragment(route.name, url, port);
|
|
2700
|
+
}
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
/** Name of the machine serving this dashboard, shown in the title and topbar.
|
|
2704
|
+
* INKLING_DASH_LABEL overrides it for hosts whose system hostname says nothing
|
|
2705
|
+
* useful (containers, "localhost"); an explicitly empty label opts out and
|
|
2706
|
+
* renders the unlabelled page. */
|
|
2707
|
+
export function dashboardHostLabel() {
|
|
2708
|
+
const override = readBrandEnv('DASH_LABEL');
|
|
2709
|
+
if (override !== undefined)
|
|
2710
|
+
return override.trim();
|
|
2711
|
+
try {
|
|
2712
|
+
const h = os.hostname().trim();
|
|
2713
|
+
// Keep it short: FQDNs push the chip past the wordmark for no added meaning.
|
|
2714
|
+
return h.split('.')[0] || '';
|
|
2715
|
+
}
|
|
2716
|
+
catch {
|
|
2717
|
+
return '';
|
|
2718
|
+
}
|
|
2719
|
+
}
|
|
2720
|
+
function htmlResponse(body) {
|
|
2721
|
+
return new Response(body, {
|
|
2722
|
+
headers: {
|
|
2723
|
+
'content-type': 'text/html; charset=utf-8',
|
|
2724
|
+
'x-frame-options': 'DENY',
|
|
2725
|
+
'x-content-type-options': 'nosniff',
|
|
2726
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
2727
|
+
'content-security-policy': "frame-ancestors 'none'; object-src 'none'; base-uri 'self'",
|
|
2728
|
+
},
|
|
2729
|
+
});
|
|
2730
|
+
}
|
|
2731
|
+
//# sourceMappingURL=dashboard.js.map
|