@sriinnu/fiche 0.18.0-bootstrap.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +22 -0
  3. package/NOTICE +13 -0
  4. package/PRIVACY.md +41 -0
  5. package/README.md +289 -0
  6. package/SECURITY.md +53 -0
  7. package/assets/JETBRAINS_MONO_LICENSE.txt +89 -0
  8. package/assets/SPLEEN_LICENSE.txt +24 -0
  9. package/assets/UNIFONT_LICENSE.txt +476 -0
  10. package/assets/fiche-logo-dark.svg +61 -0
  11. package/assets/fiche-logo-light.svg +61 -0
  12. package/assets/fiche-logo.svg +71 -0
  13. package/assets/fiche-mark.svg +48 -0
  14. package/bin/cli.js +7 -0
  15. package/bin/mcp.js +8 -0
  16. package/dist/calibrate.d.ts +30 -0
  17. package/dist/calibrate.js +588 -0
  18. package/dist/core/anthropic-vision.d.ts +28 -0
  19. package/dist/core/anthropic-vision.js +34 -0
  20. package/dist/core/applicability.d.ts +63 -0
  21. package/dist/core/applicability.js +151 -0
  22. package/dist/core/atlas-gray-jbmono10.d.ts +26 -0
  23. package/dist/core/atlas-gray-jbmono10.js +64 -0
  24. package/dist/core/atlas-gray-jbmono12.d.ts +26 -0
  25. package/dist/core/atlas-gray-jbmono12.js +64 -0
  26. package/dist/core/atlas-gray-jbmono14.d.ts +26 -0
  27. package/dist/core/atlas-gray-jbmono14.js +64 -0
  28. package/dist/core/atlas-gray.d.ts +26 -0
  29. package/dist/core/atlas-gray.js +64 -0
  30. package/dist/core/atlas-jbmono10.d.ts +34 -0
  31. package/dist/core/atlas-jbmono10.js +71 -0
  32. package/dist/core/atlas-jbmono12.d.ts +34 -0
  33. package/dist/core/atlas-jbmono12.js +71 -0
  34. package/dist/core/atlas-jbmono14.d.ts +34 -0
  35. package/dist/core/atlas-jbmono14.js +71 -0
  36. package/dist/core/atlas.d.ts +34 -0
  37. package/dist/core/atlas.js +71 -0
  38. package/dist/core/baseline.d.ts +121 -0
  39. package/dist/core/baseline.js +200 -0
  40. package/dist/core/calibration.d.ts +86 -0
  41. package/dist/core/calibration.js +547 -0
  42. package/dist/core/casi-delta.d.ts +63 -0
  43. package/dist/core/casi-delta.js +1271 -0
  44. package/dist/core/claude-model-profiles.d.ts +53 -0
  45. package/dist/core/claude-model-profiles.js +160 -0
  46. package/dist/core/client-tool-round.d.ts +31 -0
  47. package/dist/core/client-tool-round.js +58 -0
  48. package/dist/core/codex-cache.d.ts +20 -0
  49. package/dist/core/codex-cache.js +59 -0
  50. package/dist/core/context-mmu.d.ts +350 -0
  51. package/dist/core/context-mmu.js +3028 -0
  52. package/dist/core/cpt-fit.d.ts +70 -0
  53. package/dist/core/cpt-fit.js +197 -0
  54. package/dist/core/env.d.ts +8 -0
  55. package/dist/core/env.js +15 -0
  56. package/dist/core/export.d.ts +127 -0
  57. package/dist/core/export.js +385 -0
  58. package/dist/core/factsheet.d.ts +77 -0
  59. package/dist/core/factsheet.js +494 -0
  60. package/dist/core/gemini-model-profiles.d.ts +20 -0
  61. package/dist/core/gemini-model-profiles.js +134 -0
  62. package/dist/core/google.d.ts +76 -0
  63. package/dist/core/google.js +1380 -0
  64. package/dist/core/gpt-model-profiles.d.ts +218 -0
  65. package/dist/core/gpt-model-profiles.js +570 -0
  66. package/dist/core/gpt-tokens.d.ts +14 -0
  67. package/dist/core/gpt-tokens.js +165 -0
  68. package/dist/core/history.d.ts +197 -0
  69. package/dist/core/history.js +1003 -0
  70. package/dist/core/index.d.ts +16 -0
  71. package/dist/core/index.js +16 -0
  72. package/dist/core/library.d.ts +80 -0
  73. package/dist/core/library.js +131 -0
  74. package/dist/core/measurement.d.ts +34 -0
  75. package/dist/core/measurement.js +280 -0
  76. package/dist/core/messages-chat-bridge.d.ts +23 -0
  77. package/dist/core/messages-chat-bridge.js +747 -0
  78. package/dist/core/messages-responses-bridge.d.ts +11 -0
  79. package/dist/core/messages-responses-bridge.js +893 -0
  80. package/dist/core/openai-history.d.ts +184 -0
  81. package/dist/core/openai-history.js +1279 -0
  82. package/dist/core/openai-savings.d.ts +57 -0
  83. package/dist/core/openai-savings.js +116 -0
  84. package/dist/core/openai.d.ts +68 -0
  85. package/dist/core/openai.js +2523 -0
  86. package/dist/core/pin.d.ts +199 -0
  87. package/dist/core/pin.js +1353 -0
  88. package/dist/core/png.d.ts +14 -0
  89. package/dist/core/png.js +188 -0
  90. package/dist/core/prefix-tape.d.ts +102 -0
  91. package/dist/core/prefix-tape.js +315 -0
  92. package/dist/core/price-id.d.ts +10 -0
  93. package/dist/core/price-id.js +26 -0
  94. package/dist/core/prices.generated.d.ts +36 -0
  95. package/dist/core/prices.generated.js +369 -0
  96. package/dist/core/pricing.d.ts +134 -0
  97. package/dist/core/pricing.js +335 -0
  98. package/dist/core/profile-base.d.ts +30 -0
  99. package/dist/core/profile-base.js +67 -0
  100. package/dist/core/provider-router.d.ts +51 -0
  101. package/dist/core/provider-router.js +121 -0
  102. package/dist/core/proxy.d.ts +252 -0
  103. package/dist/core/proxy.js +2929 -0
  104. package/dist/core/reader-tier.d.ts +24 -0
  105. package/dist/core/reader-tier.js +118 -0
  106. package/dist/core/render.d.ts +280 -0
  107. package/dist/core/render.js +1302 -0
  108. package/dist/core/request-guard.d.ts +31 -0
  109. package/dist/core/request-guard.js +126 -0
  110. package/dist/core/request-transform.d.ts +43 -0
  111. package/dist/core/request-transform.js +173 -0
  112. package/dist/core/schema-compiler.d.ts +64 -0
  113. package/dist/core/schema-compiler.js +1696 -0
  114. package/dist/core/schema-strip.d.ts +29 -0
  115. package/dist/core/schema-strip.js +173 -0
  116. package/dist/core/session-state.d.ts +219 -0
  117. package/dist/core/session-state.js +929 -0
  118. package/dist/core/stage-plugins.d.ts +45 -0
  119. package/dist/core/stage-plugins.js +205 -0
  120. package/dist/core/text-history.d.ts +74 -0
  121. package/dist/core/text-history.js +612 -0
  122. package/dist/core/text-hygiene.d.ts +160 -0
  123. package/dist/core/text-hygiene.js +2259 -0
  124. package/dist/core/toon.d.ts +29 -0
  125. package/dist/core/toon.js +425 -0
  126. package/dist/core/tracker.d.ts +223 -0
  127. package/dist/core/tracker.js +290 -0
  128. package/dist/core/transform.d.ts +589 -0
  129. package/dist/core/transform.js +3153 -0
  130. package/dist/core/types.d.ts +87 -0
  131. package/dist/core/types.js +8 -0
  132. package/dist/core/upstream-hosts.d.ts +127 -0
  133. package/dist/core/upstream-hosts.js +398 -0
  134. package/dist/core/vision-cost.d.ts +63 -0
  135. package/dist/core/vision-cost.js +137 -0
  136. package/dist/dashboard/fragments.d.ts +87 -0
  137. package/dist/dashboard/fragments.js +1515 -0
  138. package/dist/dashboard/types.d.ts +217 -0
  139. package/dist/dashboard/types.js +3 -0
  140. package/dist/dashboard/vendor.d.ts +3 -0
  141. package/dist/dashboard/vendor.js +6 -0
  142. package/dist/dashboard.d.ts +372 -0
  143. package/dist/dashboard.js +2731 -0
  144. package/dist/export-collect.d.ts +36 -0
  145. package/dist/export-collect.js +59 -0
  146. package/dist/file-tracker.d.ts +42 -0
  147. package/dist/file-tracker.js +234 -0
  148. package/dist/kosha-sync.d.ts +74 -0
  149. package/dist/kosha-sync.js +272 -0
  150. package/dist/launchd-socket.d.ts +22 -0
  151. package/dist/launchd-socket.js +210 -0
  152. package/dist/mcp/cli.d.ts +2 -0
  153. package/dist/mcp/cli.js +55 -0
  154. package/dist/mcp/server.d.ts +48 -0
  155. package/dist/mcp/server.js +987 -0
  156. package/dist/mmu-store.d.ts +31 -0
  157. package/dist/mmu-store.js +179 -0
  158. package/dist/node-fetch.d.ts +22 -0
  159. package/dist/node-fetch.js +489 -0
  160. package/dist/node.d.ts +9 -0
  161. package/dist/node.js +244396 -0
  162. package/dist/request-decoding.d.ts +30 -0
  163. package/dist/request-decoding.js +85 -0
  164. package/dist/sessions.d.ts +179 -0
  165. package/dist/sessions.js +837 -0
  166. package/dist/stats.d.ts +114 -0
  167. package/dist/stats.js +439 -0
  168. package/dist/turn-report.d.ts +65 -0
  169. package/dist/turn-report.js +724 -0
  170. package/dist/warp/app-launch.d.ts +26 -0
  171. package/dist/warp/app-launch.js +155 -0
  172. package/dist/warp/ca.d.ts +74 -0
  173. package/dist/warp/ca.js +416 -0
  174. package/dist/warp/connect.d.ts +42 -0
  175. package/dist/warp/connect.js +686 -0
  176. package/dist/warp/der.d.ts +57 -0
  177. package/dist/warp/der.js +151 -0
  178. package/dist/warp/index.d.ts +79 -0
  179. package/dist/warp/index.js +650 -0
  180. package/dist/warp/resolve.d.ts +12 -0
  181. package/dist/warp/resolve.js +49 -0
  182. package/dist/warp/route.d.ts +71 -0
  183. package/dist/warp/route.js +134 -0
  184. package/dist/worker.d.ts +71 -0
  185. package/dist/worker.js +174 -0
  186. package/docs/SECURITY_MODEL.md +84 -0
  187. package/package.json +115 -3
  188. package/plugins/fiche-companion/README.md +42 -0
  189. package/plugins/fiche-companion/assets/logo.svg +48 -0
  190. package/plugins/fiche-companion/hooks.json +11 -0
  191. package/plugins/fiche-companion/mcp_config.json +8 -0
  192. package/plugins/fiche-companion/plugin.json +18 -0
  193. package/plugins/fiche-companion/scripts/claude-statusline.mjs +35 -0
  194. package/plugins/fiche-companion/scripts/post-invocation.mjs +122 -0
  195. package/plugins/fiche-companion/scripts/resolve-turn-report.mjs +132 -0
  196. package/plugins/fiche-companion/skills/fiche/SKILL.md +61 -0
@@ -0,0 +1,1515 @@
1
+ // Server-rendered HTML dashboard — htmx polls fragments, Alpine drives the toast tray.
2
+ import { HTMX_JS, ALPINE_JS } from './vendor.js';
3
+ import { CACHE_CREATE_RATE, CACHE_READ_RATE } from '../core/baseline.js';
4
+ import { listProviderStatuses } from '../core/upstream-hosts.js';
5
+ // ---- helpers --------------------------------------------------------
6
+ export function escapeHtml(s) {
7
+ if (s == null)
8
+ return '';
9
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
10
+ }
11
+ function numFmt(n) {
12
+ const v = Math.round(Number(n) || 0);
13
+ return v.toLocaleString('en-US');
14
+ }
15
+ function fmtSignedUsd(v, decimals = 2) {
16
+ const n = Number(v);
17
+ if (!Number.isFinite(n) || n === 0)
18
+ return `$${(0).toFixed(decimals)}`;
19
+ return n < 0 ? `-$${Math.abs(n).toFixed(decimals)}` : `$${n.toFixed(decimals)}`;
20
+ }
21
+ /** "12.3k" / "1.2M" compact formatter for headline numbers. */
22
+ function kFmt(n) {
23
+ const v = Number(n) || 0;
24
+ const a = Math.abs(v);
25
+ if (a >= 1_000_000)
26
+ return (v / 1_000_000).toFixed(a >= 10_000_000 ? 0 : 1) + 'M';
27
+ if (a >= 1000)
28
+ return (v / 1000).toFixed(a >= 100_000 ? 0 : 1) + 'k';
29
+ return String(Math.round(v));
30
+ }
31
+ function formatDuration(s) {
32
+ s = Math.floor(s);
33
+ const h = Math.floor(s / 3600);
34
+ const m = Math.floor((s % 3600) / 60);
35
+ const sec = s % 60;
36
+ return (h ? h + 'h ' : '') + (m || h ? m + 'm ' : '') + sec + 's';
37
+ }
38
+ function shortPath(p) {
39
+ if (!p)
40
+ return '-';
41
+ const parts = String(p).split('/');
42
+ return parts[parts.length - 1] || p;
43
+ }
44
+ // ---- compression toggle (kill switch) ------------------------------------
45
+ export function renderToggleFragment(enabled) {
46
+ // NOTE: "PASSTHROUGH MODE", "Disable compression", "Enable compression" are asserted by tests.
47
+ const banner = enabled
48
+ ? ''
49
+ : `<div class="banner"><strong>PASSTHROUGH MODE</strong> — compression is off. Every request goes to Claude unchanged: no images, no savings. Use this to A/B test, or if the upstream API is having problems.</div>`;
50
+ // Button POSTs the OPPOSITE of current state; 2s poll keeps it fresh.
51
+ const confirm = enabled
52
+ ? ` hx-confirm="Turn compression off?\n\nRequests will pass straight through to Claude, unchanged. Restarting the proxy turns it back on."`
53
+ : '';
54
+ return (`<div class="switch">` +
55
+ `<span class="switch-state ${enabled ? 'on' : 'off'}" title="Kill switch — resets to on when you restart"><span class="switch-dot"></span>${enabled ? 'Compression on' : 'Compression off'}</span>` +
56
+ `<button class="switch-btn" type="button" hx-post="/fragments/toggle" hx-target="#frag-toggle" hx-vals='{"enabled": ${!enabled}}'${confirm}>` +
57
+ (enabled ? 'Disable compression' : 'Enable compression') +
58
+ `</button>` +
59
+ `</div>` +
60
+ banner);
61
+ }
62
+ // ---- compress scope (which models get imaged) ----------------------------
63
+ /** Chip catalog — UNION with env scope + active set, so env-var models stay toggleable. Labels are cosmetic. */
64
+ const MODEL_CATALOG = [
65
+ { id: 'claude-fable-5', label: 'Fable 5 (all versions)' },
66
+ { id: 'claude-opus-5', label: 'Opus 5' },
67
+ { id: 'claude-opus-5-5', label: 'Opus 5.5' },
68
+ { id: 'claude-sonnet-5-5', label: 'Sonnet 5.5' },
69
+ ];
70
+ const GPT_MODEL_CATALOG = [
71
+ { id: 'gpt-5.6-sol', label: 'GPT 5.6 Sol' },
72
+ { id: 'gpt-5.5', label: 'GPT 5.5' },
73
+ ];
74
+ const GROK_MODEL_CATALOG = [
75
+ { id: 'grok-4.6', label: 'Grok 4.6' },
76
+ { id: 'grok-4.5', label: 'Grok 4.5' },
77
+ ];
78
+ const GEMINI_MODEL_CATALOG = [
79
+ // `gemini` is the family base (default on): covers 3.6/3.7/3.8, Pro, 4, 5 and
80
+ // whatever ships next. The per-version chips are for narrowing scope after
81
+ // opting the family off.
82
+ { id: 'gemini', label: 'Gemini (all versions)' },
83
+ { id: 'gemini-3.6-flash', label: 'Gemini 3.6 Flash' },
84
+ { id: 'gemini-3.7-flash', label: 'Gemini 3.7 Flash' },
85
+ { id: 'gemini-3.8-flash', label: 'Gemini 3.8 Flash' },
86
+ { id: 'gemini-4', label: 'Gemini 4' },
87
+ ];
88
+ export function renderModelsFragment(active, configured, enabled, providers = listProviderStatuses()) {
89
+ const on = new Set(active);
90
+ const labelOf = new Map([...MODEL_CATALOG, ...GPT_MODEL_CATALOG, ...GROK_MODEL_CATALOG, ...GEMINI_MODEL_CATALOG].map((m) => [m.id, m.label]));
91
+ // Union the catalog with env-configured + active ids so INKLING_MODELS-enabled
92
+ // families always show as toggles, then split into chip rows (Claude /
93
+ // OpenAI Responses / Gemini) plus the INKLING_MODELS CSV textbox that mirrors the scope.
94
+ const ids = [];
95
+ const seen = new Set();
96
+ for (const id of [
97
+ ...MODEL_CATALOG.map((m) => m.id),
98
+ ...GPT_MODEL_CATALOG.map((m) => m.id),
99
+ ...GROK_MODEL_CATALOG.map((m) => m.id),
100
+ ...GEMINI_MODEL_CATALOG.map((m) => m.id),
101
+ ...configured,
102
+ ...active,
103
+ ]) {
104
+ if (id && !seen.has(id)) {
105
+ seen.add(id);
106
+ ids.push(id);
107
+ }
108
+ }
109
+ const providerChipFor = (p) => {
110
+ const lit = p.enabled;
111
+ return (`<button class="chip${lit ? ' on' : ''}" type="button" ` +
112
+ `title="${escapeHtml(p.hosts.join(', '))}" ` +
113
+ `hx-post="/fragments/models" hx-target="#frag-models" ` +
114
+ `hx-vals='${escapeHtml(`{"provider":${JSON.stringify(p.id)},"on":${!lit}}`)}'>${escapeHtml(p.label)}${lit ? ' ✓' : ''}</button>`);
115
+ };
116
+ const primaryProviders = providers.filter((p) => p.tier === 'first-party' || p.enabled);
117
+ const disabledThirdPartyProviders = providers.filter((p) => p.tier === 'third-party' && !p.enabled);
118
+ const enabledThirdPartyCount = providers.filter((p) => p.tier === 'third-party' && p.enabled).length;
119
+ const totalThirdPartyCount = providers.filter((p) => p.tier === 'third-party').length;
120
+ const moreProvidersHtml = disabledThirdPartyProviders.length > 0
121
+ ? `<details class="models-more" style="display:inline-block;margin-left:4px">` +
122
+ `<summary class="mini-btn" style="cursor:pointer;list-style:none;display:inline-block">More providers (${enabledThirdPartyCount}/${totalThirdPartyCount} on)</summary>` +
123
+ `<div style="margin-top:6px;display:flex;flex-wrap:wrap;gap:6px">${disabledThirdPartyProviders.map(providerChipFor).join('')}</div>` +
124
+ `</details>`
125
+ : '';
126
+ const providersSection = `<div class="models">` +
127
+ `<span class="models-label">My Providers (Warp &amp; Proxy)</span>` +
128
+ primaryProviders.map(providerChipFor).join('') +
129
+ moreProvidersHtml +
130
+ `<span class="hint">only enabled providers are intercepted by warp &amp; /to/</span>` +
131
+ `</div>`;
132
+ const chipFor = (id) => {
133
+ const lit = on.has(id);
134
+ const label = labelOf.get(id) ?? id;
135
+ return (`<button class="chip${lit ? ' on' : ''}" type="button" ` +
136
+ `hx-post="/fragments/models" hx-target="#frag-models" ` +
137
+ `hx-vals='${escapeHtml(`{"model":${JSON.stringify(id)},"on":${!lit}}`)}'>${escapeHtml(label)}${lit ? ' ✓' : ''}</button>`);
138
+ };
139
+ const isFirstPartyModel = (id) => {
140
+ const base = id.toLowerCase().replace(/\[[^\]]*\]/g, '').split('/').pop() ?? '';
141
+ return (base.startsWith('claude') ||
142
+ id.toLowerCase().includes('gemini') ||
143
+ /^(?:gpt|o[134])(?:[-.]|$)/.test(base));
144
+ };
145
+ const claudeChips = ids.filter((id) => id.startsWith('claude')).map(chipFor).join('');
146
+ const geminiChips = ids.filter((id) => id.includes('gemini')).map(chipFor).join('');
147
+ const gptChips = ids.filter((id) => isFirstPartyModel(id) && !id.startsWith('claude') && !id.includes('gemini')).map(chipFor).join('');
148
+ const thirdPartyIds = ids.filter((id) => !isFirstPartyModel(id));
149
+ const thirdPartyChips = thirdPartyIds.map(chipFor).join('');
150
+ const activeThirdParty = thirdPartyIds.filter((id) => on.has(id));
151
+ const firstPartyActive = active.filter((id) => isFirstPartyModel(id));
152
+ const thirdPartyBulkButton = activeThirdParty.length > 0
153
+ ? `<button class="mini-btn" type="button" ` +
154
+ `hx-post="/fragments/models" hx-target="#frag-models" ` +
155
+ `hx-vals='${escapeHtml(JSON.stringify({ list: firstPartyActive.join(',') || 'off' }))}'>Disable all third-party (${activeThirdParty.length})</button>`
156
+ : thirdPartyIds.length > 0
157
+ ? `<button class="mini-btn" type="button" ` +
158
+ `hx-post="/fragments/models" hx-target="#frag-models" ` +
159
+ `hx-vals='${escapeHtml(JSON.stringify({ list: [...new Set([...active, ...thirdPartyIds])].join(',') }))}'>Enable third-party</button>`
160
+ : '';
161
+ const moot = enabled
162
+ ? ''
163
+ : `<div class="models"><span class="hint">compression is off — these settings have no effect right now</span></div>`;
164
+ return (moot +
165
+ providersSection +
166
+ `<div class="models">` +
167
+ `<span class="models-label">Image Claude models</span>` +
168
+ claudeChips +
169
+ `<span class="hint">unlisted models get plain text</span>` +
170
+ `</div>` +
171
+ `<div class="models">` +
172
+ `<span class="models-label">Image Gemini models</span>` +
173
+ geminiChips +
174
+ `<span class="hint">on by default · toggle off to opt out · 100/100 vision reader</span>` +
175
+ `</div>` +
176
+ `<div class="models">` +
177
+ `<span class="models-label">Image OpenAI Responses models</span>` +
178
+ gptChips +
179
+ `<span class="hint">opt-in · no Anthropic cache_control</span>` +
180
+ `</div>` +
181
+ `<div class="models">` +
182
+ `<span class="models-label">Third-party models</span>` +
183
+ thirdPartyChips +
184
+ thirdPartyBulkButton +
185
+ `<span class="hint">4-layer deterministic text hygiene · DeepSeek, Kimi, GLM, Grok</span>` +
186
+ `</div>` +
187
+ `<div class="models">` +
188
+ `<span class="models-label">FICHE_MODELS</span>` +
189
+ `<input class="models-csv" id="models-csv" type="text" name="list" ` +
190
+ `value="${escapeHtml(active.join(','))}" spellcheck="false" autocomplete="off" ` +
191
+ `hx-post="/fragments/models" hx-target="#frag-models" hx-trigger="change">` +
192
+ `<span class="hint">CSV of bases, or off · applies on enter/blur · export to persist</span>` +
193
+ `</div>`);
194
+ }
195
+ /** Render server-driven 1-click controls for 3rd-party plugins, skills & extensions. */
196
+ export function renderPluginsFragment(plugins) {
197
+ const thirdParty = plugins.filter((p) => p.kind !== 'builtin' && p.id !== 'skill:fiche');
198
+ if (thirdParty.length === 0) {
199
+ return `<div class="models"><span class="hint">No 3rd-party plugins or skills discovered in ~/.fiche/plugins or ~/.agents/skills.</span></div>`;
200
+ }
201
+ const activeCount = thirdParty.filter((p) => p.enabled).length;
202
+ const anyOn = activeCount > 0;
203
+ const bulkBtn = `<button class="mini-btn" type="button" ` +
204
+ `hx-post="/fragments/plugins" hx-target="#frag-plugins" ` +
205
+ `hx-vals='${escapeHtml(JSON.stringify({ scope: 'third-party', enabled: !anyOn }))}'>` +
206
+ `${anyOn ? `Disable all 3rd-party (${activeCount})` : `Enable all 3rd-party (${thirdParty.length})`}</button>`;
207
+ const chips = thirdParty
208
+ .map((p) => {
209
+ const lit = p.enabled;
210
+ return (`<button class="chip${lit ? ' on' : ''}" type="button" ` +
211
+ `hx-post="/fragments/plugins" hx-target="#frag-plugins" ` +
212
+ `hx-vals='${escapeHtml(JSON.stringify({ id: p.id, enabled: !lit }))}'>${escapeHtml(p.name)}${lit ? ' ✓' : ''}</button>`);
213
+ })
214
+ .join('');
215
+ return (`<div class="models">` +
216
+ `<span class="models-label">3rd-party toggle</span>` +
217
+ bulkBtn +
218
+ `<span class="hint">${activeCount}/${thirdParty.length} active · built-in stages &amp; fiche skill stay on</span>` +
219
+ `</div>` +
220
+ `<div class="models">` +
221
+ `<span class="models-label">Extensions</span>` +
222
+ chips +
223
+ `</div>`);
224
+ }
225
+ // ---- session hero --------------------------------------------------------
226
+ // Must stay in lockstep with ASSUMED_INPUT_USD_PER_MTOK in src/dashboard.ts.
227
+ const INPUT_USD_PER_MTOK = 10.0;
228
+ void INPUT_USD_PER_MTOK; // suppress unused-var; renderHeaderFragment uses the server's pricing block.
229
+ // Lifetime hero. Reads the SAME cumulative weighted totals as the header strip
230
+ // (serveStats), so the headline and the "$ saved" tiles can never disagree, and
231
+ // the number stops swinging on tiny per-session samples. Cache-weighted on
232
+ // purpose ("lifeweight"): it answers "did inkling move my real, cache-discounted
233
+ // bill since this proxy started", not a raw token count.
234
+ export function renderSessionSummaryFragment(s) {
235
+ const measured = s.compressed_requests ?? 0;
236
+ if (measured <= 0) {
237
+ return (`<div class="hero hero-empty">` +
238
+ `<div class="hero-eyebrow">Since start</div>` +
239
+ `<div class="hero-headline">Warming up…</div>` +
240
+ `<div class="hero-sub">Point Claude Code at this proxy with <code>ANTHROPIC_BASE_URL</code>, or launch any CLI/app with <code>fiche warp -- claude</code> (or enable <code>fiche shell-init --wrap</code> in your shell) to route all coding agents transparently. Send a message and your running savings show up right here.</div>` +
241
+ `</div>`);
242
+ }
243
+ // Cache-aware reduction — same basis as the Details panel + Saved column.
244
+ // Raw count_tokens would over-claim: most of the text baseline would have been
245
+ // cheap cache-reads (~0.1×), not full-price tokens. Weighting both sides at their
246
+ // real cache rate is the only comparison that can't contradict the Saved column.
247
+ // Input-only: inkling never touches output, so lumping it in just dampened the %.
248
+ const baselineW = s.baseline_input_weighted ?? 0; // same context as text, cache-aware
249
+ const actualW = s.actual_input_weighted ?? 0; // what we actually sent, cache-aware
250
+ const outMult = s.pricing_assumptions?.output_multiplier || 5;
251
+ const rawOutput = (s.output_weighted ?? 0) / outMult; // reply — never compressed
252
+ const inputPct = baselineW > 0 ? (1 - actualW / baselineW) * 100 : 0;
253
+ const positive = inputPct >= 0;
254
+ const bigNum = `${Math.abs(inputPct).toFixed(0)}%`;
255
+ const word = positive ? 'fewer tokens' : 'more tokens';
256
+ const imaged = s.imaged_requests ?? 0;
257
+ const textComp = s.text_compressed_requests ?? 0;
258
+ const modeSummary = imaged > 0 && textComp > 0
259
+ ? `${numFmt(imaged)} imaged · ${numFmt(textComp)} text-compacted`
260
+ : textComp > 0
261
+ ? `${numFmt(textComp)} text-compacted`
262
+ : `${numFmt(measured)} request${measured === 1 ? '' : 's'} imaged`;
263
+ const todayStr = s.today && s.today.requests > 0
264
+ ? ` · Today: ${s.today.saved_tokens >= 0 ? '-' : '+'}${kFmt(Math.abs(s.today.saved_tokens))} wtd${s.today.saved_usd > 0 ? ` ($${s.today.saved_usd.toFixed(2)})` : ''}`
265
+ : '';
266
+ const rawSavedNote = (s.raw_saved_tokens ?? 0) > 0 ? `${kFmt(s.raw_saved_tokens)} raw tokens stripped · ` : '';
267
+ return (`<div class="hero${positive ? '' : ' hero-neg'}">` +
268
+ `<div class="hero-eyebrow">Lifetime · ${modeSummary}${todayStr}</div>` +
269
+ `<div class="hero-headline"><span class="hero-num">${bigNum}</span> ${word}</div>` +
270
+ `<div class="hero-sub">` +
271
+ `<strong>${kFmt(actualW)}</strong> provider-accounted input tokens vs <strong>${kFmt(baselineW)}</strong> if this same context ` +
272
+ `stayed plain text. Your latest messages and model output are never compressed.` +
273
+ `</div>` +
274
+ `<div class="hero-meta">` +
275
+ rawSavedNote +
276
+ `Provider-token basis; cache discounts applied where measurable · ` +
277
+ `output untouched (${kFmt(rawOutput)}) · no $ assumptions` +
278
+ `</div>` +
279
+ `</div>`);
280
+ }
281
+ // ---- stat strip + "Show the math" drawer ----------------------------------
282
+ function mathRow(key, val, note = '') {
283
+ const v = typeof val === 'number' ? numFmt(val) : String(val ?? '-');
284
+ return `<div><span class="k">${key}:</span> <span class="v">${escapeHtml(v)}</span> <span class="k">${note}</span></div>`;
285
+ }
286
+ function mathBlock(title, body) {
287
+ return `<section class="math-block"><h4>${title}</h4><div class="formula">${body}</div></section>`;
288
+ }
289
+ /** Stat tile; `tip` adds a hover "?" explainer. */
290
+ function statTile(label, value, sub, cls = '', tip = '') {
291
+ const q = tip
292
+ ? `<span class="q" tabindex="0" aria-label="${escapeHtml(tip)}" data-tip="${escapeHtml(tip)}">?</span>`
293
+ : '';
294
+ return (`<div class="tile">` +
295
+ `<div class="tile-label">${label}${q}</div>` +
296
+ `<div class="tile-value ${cls}">${value}</div>` +
297
+ `<div class="tile-sub">${sub}</div>` +
298
+ `</div>`);
299
+ }
300
+ export function renderHeaderFragment(s, port) {
301
+ const pa = s.pricing_assumptions;
302
+ const unpricedImaged = Math.max(0, (s.compressed_requests ?? 0) - (s.compressed_paid_requests ?? 0));
303
+ const onlyUnpriced = unpricedImaged > 0 && (s.compressed_paid_requests ?? 0) === 0;
304
+ // Compare the same imaged requests on both sides. Passthrough requests are
305
+ // generally smaller because the profitability gate selected them, so their
306
+ // average is not a valid "without inkling" counterfactual.
307
+ const cAvg = s.compressed_avg_usd_per_request ?? 0;
308
+ const paidImaged = s.compressed_paid_requests ?? 0;
309
+ const withoutAvg = paidImaged > 0 ? cAvg + (s.saved_usd ?? 0) / paidImaged : 0;
310
+ const costTile = paidImaged > 0
311
+ ? statTile('Cost per request', `$${cAvg.toFixed(4)}`, `vs $${withoutAvg.toFixed(4)} without fiche`, cAvg <= withoutAvg ? 'pos' : 'neg', 'Average cost of paid imaged requests versus the cache-aware text counterfactual for those same requests. Unmeasured requests are assigned zero savings.')
312
+ : onlyUnpriced
313
+ ? statTile('Cost per request', '—', 'provider pricing not configured', 'muted-val', 'Token savings are available, but this provider is excluded from Claude-priced dollar estimates.')
314
+ : statTile('Cost per request', 'collecting…', 'waiting for a paid imaged request', 'muted-val', 'The comparison appears after an imaged request returns provider usage.');
315
+ const savedUsdTile = onlyUnpriced
316
+ ? statTile('Estimated saved', '—', 'provider pricing not configured', 'muted-val', 'Token savings are shown separately. Dollar estimates require provider-specific pricing and are not inferred from Claude rates.')
317
+ : statTile('Estimated saved', `$${(s.saved_usd ?? 0).toFixed(2)}`, unpricedImaged > 0
318
+ ? `${numFmt(unpricedImaged)} provider-priced request${unpricedImaged === 1 ? '' : 's'} excluded`
319
+ : `at $${pa.input_per_mtok}/M base input price`, '', 'Cache-aware estimate for requests covered by the configured pricing assumptions. Other providers remain excluded.');
320
+ const imagedCount = s.imaged_requests ?? 0;
321
+ const textCompCount = s.text_compressed_requests ?? 0;
322
+ const requestsSub = imagedCount > 0 && textCompCount > 0
323
+ ? `${numFmt(imagedCount)} imaged · ${numFmt(textCompCount)} text-compacted`
324
+ : textCompCount > 0
325
+ ? `${numFmt(textCompCount)} text-compacted`
326
+ : `${numFmt(s.compressed_requests)} turned into images`;
327
+ const strip = `<div class="strip">` +
328
+ statTile('Requests', numFmt(s.requests), requestsSub) +
329
+ statTile('Input tokens saved', numFmt(s.saved_input_tokens), 'vs sending the same context as text', 'pos', 'Bulky context sent as compact images instead of text. Uses provider-reported input tokens and a measured or model-profile text counterfactual; recent turns and output stay text.') +
330
+ savedUsdTile +
331
+ costTile +
332
+ `</div>`;
333
+ // math drawer
334
+ const savedMath = `<div><span class="k">formula:</span> <span class="v">saved = baseline − actual</span></div>` +
335
+ `<div><span class="k">weights:</span> <span class="v">input×1.0, cache_write_5m×1.25, cache_write_1h×2.0, cache_read×0.10</span></div>` +
336
+ `<div class="sp"></div>` +
337
+ mathRow('baseline', s.baseline_input_weighted, '(cache-aware: cacheable×weight + cold_tail)') +
338
+ mathRow('actual', s.actual_input_weighted, '(input + cc_5m×1.25 + cc_1h×2.0 + cr×0.10)') +
339
+ mathRow('saved', s.saved_input_tokens, `<span class="op">=</span> baseline − actual`) +
340
+ `<span class="src">output excluded — identical with/without compression</span>`;
341
+ const usdMath = onlyUnpriced
342
+ ? `<div><span class="v">Unavailable for this provider.</span></div>` +
343
+ `<span class="src">Token savings are still reported; Claude pricing is not applied across providers.</span>`
344
+ :
345
+ `<div><span class="k">formula:</span> <span class="v">$ saved = saved_tokens × $${pa.input_per_mtok}/Mtok</span></div>` +
346
+ `<div class="sp"></div>` +
347
+ mathRow('saved_tokens', s.saved_input_tokens, '(cache-aware, input-side)') +
348
+ mathRow('saved_usd', `$${(s.saved_usd || 0).toFixed(4)} `, `<span class="op">=</span> saved_tokens × input_rate / 1e6`) +
349
+ `<span class="src">source: ${escapeHtml(pa.source || 'docs.anthropic.com pricing')}</span>`;
350
+ const costPerRequestMath = `<div><span class="k">formula:</span> <span class="v">without_fiche = actual_imaged + measured_savings</span></div>` +
351
+ `<div><span class="k">why:</span> <span class="v">both averages cover the same paid imaged requests. Passthrough requests are not used because the profitability gate selects a different, generally smaller population.</span></div>` +
352
+ `<div class="sp"></div>` +
353
+ mathRow(`actual imaged (n=${paidImaged})`, `$${(s.compressed_actual_usd || 0).toFixed(4)}`, `total · avg $${cAvg.toFixed(4)}/req`) +
354
+ mathRow('measured savings', `$${(s.saved_usd || 0).toFixed(4)}`, 'cache-aware input-side total') +
355
+ mathRow('without fiche', `$${withoutAvg.toFixed(4)}/req`, '<span class="op">=</span> (actual imaged + measured savings) / n') +
356
+ `<span class="src">unmeasured imaged rows remain in n and actual cost, with zero assumed savings</span>`;
357
+ const pctMath = `<div><span class="k">formula:</span> <span class="v">share_of_spend = saved / (all_baseline_equivalent + all_output × ${pa.output_multiplier})</span></div>` +
358
+ `<div><span class="k">diagnostic, not the headline:</span> <span class="v">this is a counterfactual ("what you WOULD have paid"). It leans on the count_tokens probe, the cache-aware split, and an input-rate assumption. Useful as a sanity check; the real-traffic answer is the compressed-vs-passthrough split above.</span></div>` +
359
+ `<div class="sp"></div>` +
360
+ mathRow('saved', s.saved_input_tokens, '(measured-rows numerator; cache-aware)') +
361
+ mathRow('all_baseline_equivalent', s.all_baseline_equivalent_weighted, '(every paid request; baseline on measured + actual on the rest)') +
362
+ mathRow(`all_output × ${pa.output_multiplier}`, s.all_output_weighted, '(every paid request)') +
363
+ mathRow('share_of_spend', (s.saved_pct_of_all_spend || 0).toFixed(1) + '%', `<span class="op">=</span> saved / counterfactual_total × 100`) +
364
+ mathRow('all_usage_requests', s.all_usage_requests, '(denominator request count — compressed + passthrough + probe-failed)') +
365
+ `<span class="src">measured numerator, all-rows counterfactual denominator — bounded at 100%</span>`;
366
+ const tokeqMath = `<div><span class="k">formula:</span> <span class="v">token_equivalent = input + output × ${pa.output_multiplier}</span></div>` +
367
+ `<div><span class="k">why:</span> <span class="v">matches Anthropic's per-Mtok price ratio ($${pa.input_per_mtok} input vs $${pa.input_per_mtok * pa.output_multiplier} output) — this is what the weekly-limit meter counts.</span></div>` +
368
+ `<div class="sp"></div>` +
369
+ mathRow('actual_token_equivalent', s.actual_token_equivalent) +
370
+ mathRow('baseline_token_equivalent', s.baseline_token_equivalent, `(unproxied counterfactual, same ×${pa.output_multiplier} on output)`) +
371
+ `<div class="sp"></div>` +
372
+ mathRow('events_with_measurement', s.events_with_measurement, '(events where the SSE/JSON scanner produced char counts)') +
373
+ mathRow('measured_text_chars', s.measured_text_chars, '') +
374
+ mathRow('measured_thinking_chars', s.measured_thinking_chars, '') +
375
+ mathRow('measured_tool_use_chars', s.measured_tool_use_chars, '') +
376
+ mathRow('measured_redacted_blocks', s.measured_redacted_block_count, '(opaque encrypted blocks — billed but unmeasurable)') +
377
+ `<span class="src">measured — no estimation</span>`;
378
+ const drawer = `<details class="drawer" id="math-drawer">` +
379
+ `<summary>Show the math &amp; honesty receipts</summary>` +
380
+ `<div class="drawer-intro">Every number above, derived from the same per-event log. The proxy only moves <em>input</em> tokens; output is shown on both sides so percentages stay honest.</div>` +
381
+ `<div class="math-grid">` +
382
+ mathBlock('Input tokens saved', savedMath) +
383
+ mathBlock('Dollars saved', usdMath) +
384
+ mathBlock('Cost per imaged request', costPerRequestMath) +
385
+ mathBlock('Share of total spend (diagnostic)', pctMath) +
386
+ mathBlock('Token-equivalent (what the weekly cap counts)', tokeqMath) +
387
+ `</div></details>`;
388
+ // NOTE: tests assert the header fragment contains the port number.
389
+ const updated = `<div class="updated"><span class="live-dot"></span>live · port ${port} · uptime ${formatDuration(s.uptime_sec)}</div>`;
390
+ return strip + drawer + updated;
391
+ }
392
+ const CTXMAP_BUCKETS = [
393
+ ['static_slab', 'System prompt + tool docs'],
394
+ ['reminder', 'System-reminder blocks'],
395
+ ['tool_result_prose', 'Tool results — prose'],
396
+ ['tool_result_log', 'Tool results — logs'],
397
+ ['tool_result_json', 'Tool results — JSON'],
398
+ ['history', 'Older conversation turns'],
399
+ ];
400
+ /** Image-vs-text breakdown for one request. */
401
+ export function renderContextMapFragment(c, history = [], notFound = false) {
402
+ const isLatest = c !== undefined && c.id === (history.at(-1)?.id ?? -1);
403
+ if (notFound) {
404
+ return `<div class="ctxmap"><div class="empty-note">That request's breakdown isn't kept anymore — only the most recent requests are. Pick <strong>Details</strong> on a newer row.</div></div>`;
405
+ }
406
+ if (!c || (c.baselineTokens <= 0 && c.imageCount <= 0)) {
407
+ return `<div class="ctxmap"><div class="empty-note">Pick <strong>Details</strong> on a request to see exactly which parts became images and which stayed as text.</div></div>`;
408
+ }
409
+ // Cache-aware billing-equivalent basis — identical to the recent row's
410
+ // As-text / Sent / Saved/lost columns. These are not raw token counts; they apply
411
+ // Anthropic's cache rates so create/read misses are visible in the comparison.
412
+ // The two panels can never contradict each other. The raw
413
+ // count_tokens ratio is cache-blind: it over-states savings whenever the
414
+ // prefix would have been a cheap cache-read, so it must NOT drive the
415
+ // headline. It survives only as a clarifying sub-line below.
416
+ const showCompare = c.haveBaseline && c.baselineInputEff > 0;
417
+ const base = c.baselineInputEff;
418
+ const real = c.actualInputEff;
419
+ const pct = showCompare ? Math.round((1 - real / base) * 100) : 0;
420
+ const rawShrink = c.baselineTokens > 0 ? Math.round((1 - c.realInput / c.baselineTokens) * 100) : 0;
421
+ const totalImagedChars = CTXMAP_BUCKETS.reduce((a, [key]) => a + (c.buckets[key] ?? 0), 0);
422
+ const imgRows = CTXMAP_BUCKETS.map(([key, label]) => [label, c.buckets[key] ?? 0])
423
+ .filter(([, ch]) => ch > 0)
424
+ .map(([label, ch]) => `<div class="ctx-row"><span class="ctx-lbl">${label}</span><span class="ctx-val">${kFmt(ch)} chars</span></div>`)
425
+ .join('');
426
+ const rc = c.responsesComposition;
427
+ const responseRows = rc
428
+ ? [
429
+ ['Instructions', rc.instructions],
430
+ ['System / developer items', rc.systemDeveloper],
431
+ ['User / assistant text kept native', rc.userAssistant],
432
+ ['Native tool JSON', rc.toolsJson],
433
+ ['Tool calls (function + custom)', rc.functionCalls],
434
+ ['Tool outputs (function + custom)', rc.functionOutputs],
435
+ ['Tool outputs eligible in old closed pairs', rc.imageableFunctionOutputs ?? 0],
436
+ ['Tool outputs actually imaged this request', rc.collapsedFunctionOutputs ?? 0],
437
+ ['Reasoning / encrypted items', rc.reasoningEncrypted],
438
+ ['Compaction / opaque items', rc.compactionOpaque],
439
+ ['Other Responses items', rc.other],
440
+ ]
441
+ : [];
442
+ const responseBreakdown = rc
443
+ ? `<div class="split-note" style="margin-top:12px"><strong>Original Responses composition (local o200k estimate)</strong></div>` +
444
+ responseRows.filter(([, n]) => n > 0).map(([label, n]) => `<div class="ctx-row"><span class="ctx-lbl">${label}</span><span class="ctx-val">${kFmt(n)} tok</span></div>`).join('') +
445
+ `<div class="ctx-row"><span class="ctx-lbl">Imageable text baseline</span><span class="ctx-val">${kFmt(c.baselineImagedTokens ?? 0)} tok</span></div>` +
446
+ `<div class="ctx-row"><span class="ctx-lbl">Completed tool pairs (old / recent native / imaged)</span><span class="ctx-val">${Math.trunc(Number(rc.completedFunctionPairs) || 0)} (${Math.trunc(Number(rc.oldFunctionPairs) || 0)} / ${Math.trunc(Number(rc.recentNativeFunctionPairs) || 0)} / ${Math.trunc(Number(rc.collapsedFunctionPairs) || 0)})</span></div>` +
447
+ `<div class="ctx-row"><span class="ctx-lbl">Open calls kept native</span><span class="ctx-val">${Math.trunc(Number(rc.openFunctionCalls) || 0)}</span></div>` +
448
+ `<div class="ctx-row"><span class="ctx-lbl">Native image parts</span><span class="ctx-val">${Math.trunc(Number(rc.imageParts) || 0)}</span></div>` +
449
+ `<div class="ctx-row"><span class="ctx-lbl">Provider tokens not explained locally</span><span class="ctx-val">${kFmt(c.responsesUnexplainedTokens ?? 0)} tok</span></div>` +
450
+ `<div class="split-note">This diagnostic uses local o200k counts only; it never calls Anthropic /count_tokens.</div>`
451
+ : '';
452
+ const ids = c.imageIds ?? [];
453
+ const modelLabel = c.model ? escapeHtml(c.model) : 'the model';
454
+ const gallery = ids.length
455
+ ? `<div class="pages-title">${ids.length} image page${ids.length === 1 ? '' : 's'} sent to ${modelLabel} — click one to read the exact text behind it:</div>` +
456
+ `<div class="pages">` +
457
+ ids
458
+ .map((id) => `<img class="page" src="/proxy-latest-png?id=${id}" alt="page ${id}" loading="lazy" title="Click to read the source text behind page ${id}" onclick="ppPin(${id});ppSource(true)" onerror="this.classList.add('page-gone'); this.alt='page ${id} expired from buffer';" />`)
459
+ .join('') +
460
+ `</div>`
461
+ : c.restored && c.imageCount > 0
462
+ ? `<div class="pages-title">${Math.trunc(Number(c.imageCount) || 0)} image page${c.imageCount === 1 ? '' : 's'} were sent — thumbnails expired when the proxy restarted. The breakdown above is reconstructed from the saved log.</div>`
463
+ : '';
464
+ // Did the TEXT baseline's prefix read warm this turn? This follows the actual
465
+ // request's observed cache state: cache_read > 0 means warm, cache_read === 0
466
+ // means cold. No wall-clock-only counterfactual is credited.
467
+ const warm = showCompare && c.warm;
468
+ const google = c.model?.startsWith('gemini-') === true;
469
+ const textNoun = warm ? 'cached text' : 'text';
470
+ // Raw count_tokens can grow (imaging bloated a short prompt), so say so rather
471
+ // than rendering a nonsensical "shrank -36%".
472
+ const rawPhrase = rawShrink >= 0 ? `Raw content shrank ${rawShrink}%.` : `Raw content grew ${-rawShrink}%.`;
473
+ const headline = !showCompare
474
+ ? `<strong>${kFmt(c.actualInputEff || c.realInput)}</strong> billing-equivalent input tokens sent`
475
+ : pct >= 0
476
+ ? google
477
+ ? `<span class="ctx-big">${pct}%</span> smaller — text would account as <strong>${kFmt(base)}</strong> input tokens; images account as <strong>${kFmt(real)}</strong>`
478
+ : `<span class="ctx-big">${pct}%</span> smaller — ${textNoun} would bill as <strong>${kFmt(base)}</strong> input tokens; images billed as <strong>${kFmt(real)}</strong>`
479
+ : google
480
+ ? `<span class="ctx-big">${-pct}%</span> bigger — images account as <strong>${kFmt(real)}</strong> input tokens vs <strong>${kFmt(base)}</strong> for text`
481
+ : `<span class="ctx-big">${-pct}%</span> bigger — images billed as <strong>${kFmt(real)}</strong> input tokens vs <strong>${kFmt(base)}</strong> for ${textNoun}`;
482
+ // Clarifying sub-line. It must match the actual request's cache state: claiming
483
+ // a 0.1× read discount when cache_read===0 would count hypothetical cache as a
484
+ // inkling effect, so cold rows price both paths cold.
485
+ const subnote = !showCompare
486
+ ? 'Billed tokens count cache discounts (reads at 0.1×) — no trustworthy text baseline for this request yet.'
487
+ : google
488
+ ? `Same provider-token basis as the Saved column. The gap is token count. ${rawPhrase}`
489
+ : !warm
490
+ ? `No warm text cache this turn — the text counterfactual's prefix is priced at the 1.25× create rate (the same event the imaged path pays), identical basis to the Saved column. The gap is purely token count. ${rawPhrase}`
491
+ : pct < 0 && rawShrink > 0
492
+ ? `Billed = after cache discounts (reads at 0.1×), same basis as the Saved column. The raw text is ${rawShrink}% smaller, but most of it would have been a cheap cache-read — so imaging it cost more.`
493
+ : `Billed = after cache discounts (reads at 0.1×), same basis as the Saved column. ${rawPhrase}`;
494
+ const title = isLatest ? 'Latest request' : 'Selected request';
495
+ // The provider caps a request at 100 image blocks and counts the CLIENT's
496
+ // images against the same limit. Three facts are worth showing, and only when
497
+ // they are true — a quiet turn should stay quiet:
498
+ // - the client brought its own images (they shrank our room),
499
+ // - we rendered more pages than we shipped (the collapse ate some),
500
+ // - we gave up on imaging something because the cap was full.
501
+ const capBits = [];
502
+ if ((c.nativeImages ?? 0) > 0) {
503
+ capBits.push(`${c.nativeImages} image${c.nativeImages === 1 ? '' : 's'} came from your side and count against the same 100-image request cap`);
504
+ }
505
+ if (c.wireImages !== undefined && c.wireImages < c.imageCount + (c.nativeImages ?? 0)) {
506
+ const absorbed = c.imageCount + (c.nativeImages ?? 0) - c.wireImages;
507
+ capBits.push(`${absorbed} rendered page${absorbed === 1 ? '' : 's'} never went out — the history collapse absorbed those messages (${c.wireImages} on the wire)`);
508
+ }
509
+ if ((c.imageBudgetSkips ?? 0) > 0) {
510
+ capBits.push(`${c.imageBudgetSkips} block${c.imageBudgetSkips === 1 ? '' : 's'} stayed as text because the image cap was full`);
511
+ }
512
+ const capNote = capBits.length
513
+ ? `<div class="split-note cap-note">${capBits.map(escapeHtml).join(' · ')}</div>`
514
+ : '';
515
+ return (`<div class="ctxmap">` +
516
+ `<div class="ctx-headline"><span class="ctx-title">${title}</span> ${headline}</div>` +
517
+ `<div class="split-note ctx-subnote">${subnote}</div>` +
518
+ `<div class="legend"><span class="tag tag-img">Became an image</span><span class="tag tag-txt">Stayed as text</span></div>` +
519
+ `<div class="split">` +
520
+ `<div class="split-col split-img">` +
521
+ `<div class="split-head">Compressed into images <span class="split-sum">${kFmt(totalImagedChars)} chars · ${Math.trunc(Number(c.imageCount) || 0)} page${c.imageCount === 1 ? '' : 's'}</span></div>` +
522
+ (imgRows || `<div class="ctx-row muted-row">nothing imaged this request</div>`) +
523
+ capNote +
524
+ `<div class="split-note">fiche can misread exact values inside images — treat these as gist, not byte-exact.</div>` +
525
+ `</div>` +
526
+ `<div class="split-col split-txt">` +
527
+ `<div class="split-head">Kept as plain text <span class="split-sum">byte-exact</span></div>` +
528
+ `<div class="ctx-row"><span class="ctx-lbl">Your latest messages</span><span class="ctx-val">verbatim</span></div>` +
529
+ `<div class="ctx-row"><span class="ctx-lbl">Model reply (output)</span><span class="ctx-val">${kFmt(c.output)} tok</span></div>` +
530
+ `<div class="split-note">never imaged — safe for IDs, hashes and exact numbers.</div>` +
531
+ `</div>` +
532
+ `</div>` +
533
+ responseBreakdown +
534
+ gallery +
535
+ `</div>`);
536
+ }
537
+ // ---- recent requests table -----------------------------------------------
538
+ function statusCls(status) {
539
+ if (status >= 500)
540
+ return 'bad';
541
+ if (status >= 400)
542
+ return 'warn';
543
+ return 'good';
544
+ }
545
+ export function renderRecentFragment(p) {
546
+ const rows = (p.recent ?? []).slice().reverse();
547
+ const body = rows.length === 0
548
+ ? `<tr><td colspan="10" class="empty-cell">No requests yet — they stream in here live.</td></tr>`
549
+ : rows
550
+ .map((e, i) => {
551
+ const viewId = (e.img_ids ?? (e.img_id != null ? [e.img_id] : []))[0];
552
+ const viewLink = viewId != null
553
+ ? `<a class="row-view" href="#" hx-get="/fragments/context-map?req=${viewId}" hx-target="#frag-context-map" hx-swap="innerHTML">Details →</a>`
554
+ : `<span class="muted">—</span>`;
555
+ const saved = e.session_saved_so_far_delta;
556
+ // A loss that disappears when the newly written prefix is repriced at
557
+ // the read rate is just the one-time cache-create premium — the
558
+ // purchase price of the cheap cache reads on the turns that follow.
559
+ // Mark it so create turns don't read as gate failures.
560
+ const cc = e.cache_create ?? 0;
561
+ const createLoss = saved != null &&
562
+ saved < 0 &&
563
+ cc > 0 &&
564
+ saved + cc * (CACHE_CREATE_RATE - CACHE_READ_RATE) > 0;
565
+ const createNote = createLoss
566
+ ? ` <span class="mk-create" title="Cache-create turn: this loss is the one-time ${CACHE_CREATE_RATE}× premium for writing ${numFmt(cc)} tokens to cache. Later turns re-read that prefix at ${CACHE_READ_RATE}×, which typically recoups it.">create</span>`
567
+ : '';
568
+ const savedCell = saved == null
569
+ ? `<td class="num muted">—</td>`
570
+ : saved > 0
571
+ ? `<td class="num pos">${numFmt(saved)}</td>`
572
+ : saved < 0
573
+ ? `<td class="num neg">${numFmt(saved)}${createNote}</td>`
574
+ : `<td class="num">0</td>`;
575
+ const imaged = e.compression_mode === 'optical' || (!e.compression_mode && e.cc_added)
576
+ ? `<span class="badge badge-img">image</span>`
577
+ : e.compression_mode === 'text'
578
+ ? `<span class="badge badge-hyg" title="${escapeHtml((e.text_hygiene_stages ?? []).join(', ') || '4-layer deterministic text hygiene')}">text-hygiene</span>`
579
+ : `<span class="badge badge-txt">text</span>`;
580
+ return (`<tr>` +
581
+ `<td class="muted">${i + 1}</td>` +
582
+ `<td><span class="pill pill-${statusCls(e.status)}">${escapeHtml(String(e.status))}</span></td>` +
583
+ `<td class="endp">${escapeHtml(shortPath(e.path))}</td>` +
584
+ `<td>${e.model ? `<code>${escapeHtml(e.model)}</code>` : '<span class="muted">—</span>'}</td>` +
585
+ `<td>${imaged}</td>` +
586
+ `<td class="num">${e.cache_read != null ? numFmt(e.cache_read) : '—'}</td>` +
587
+ `<td class="num">${e.baseline_input != null ? numFmt(e.baseline_input) : '—'}</td>` +
588
+ `<td class="num">${e.actual_input != null ? numFmt(e.actual_input) : '—'}</td>` +
589
+ savedCell +
590
+ `<td class="num">${viewLink}</td>` +
591
+ `</tr>`);
592
+ })
593
+ .join('');
594
+ return (`<table class="rtable"><thead><tr>` +
595
+ `<th>#</th>` +
596
+ `<th>Result</th>` +
597
+ `<th>Endpoint</th>` +
598
+ `<th>Model</th>` +
599
+ `<th title="Was this request's context compressed into an image?">Sent as</th>` +
600
+ `<th class="num" title="Tokens the provider reported as served from cache">Cache hits</th>` +
601
+ `<th class="num" title="Billing-equivalent input if kept as plain text, after cache create/read rates">As text</th>` +
602
+ `<th class="num" title="Actual billing-equivalent input after imaging, after cache create/read rates">Sent</th>` +
603
+ `<th class="num" title="As-text minus Sent; negative means imaging cost more">Saved/lost</th>` +
604
+ `<th></th>` +
605
+ `</tr></thead><tbody>${body}</tbody></table>`);
606
+ }
607
+ export function renderLatestFragment(inp) {
608
+ const { payload, pin, showSource, sourceText } = inp;
609
+ const hasPreview = payload.has_preview === true;
610
+ const meta = payload.preview_meta ?? '';
611
+ const imageIds = payload.image_ids ?? [];
612
+ const pinnedEvicted = pin != null && !imageIds.includes(pin);
613
+ // Pinned id, or latest (cache-busted by meta).
614
+ const imgSrc = pin != null
615
+ ? `/proxy-latest-png?id=${pin}`
616
+ : `/proxy-latest-png?t=${encodeURIComponent(meta)}`;
617
+ const pinBar = pin != null
618
+ ? `<div class="viewer-bar"><button class="mini-btn" type="button" onclick="ppPin(null)">← back to latest</button><span class="mini-label">image #${pin}</span></div>`
619
+ : '';
620
+ let main;
621
+ if (pin != null && pinnedEvicted) {
622
+ main = `<div class="evicted">image #${pin} is no longer in the buffer</div>`;
623
+ }
624
+ else if (pin != null || hasPreview) {
625
+ // When source pane is open the image appears inside the pairing — don't duplicate it.
626
+ main = showSource ? '' : `<div class="frame"><img src="${imgSrc}" alt="rendered page" /></div>`;
627
+ }
628
+ else {
629
+ main = `<div class="empty-note">No images yet — they appear the instant fiche compresses a request.</div>`;
630
+ }
631
+ const showBtn = pin != null ? !pinnedEvicted : hasPreview;
632
+ const caption = pin != null ? `image #${pin}` : meta ? `${escapeHtml(meta)} · top-left at native size` : '';
633
+ const srcBtn = showBtn
634
+ ? `<button class="mini-btn" type="button" onclick="ppSource(${showSource ? 'false' : 'true'})">${showSource ? 'hide source text' : 'show the text behind this image'}</button>`
635
+ : '';
636
+ let pane = '';
637
+ if (showSource) {
638
+ pane =
639
+ sourceText == null
640
+ ? `<div class="evicted">source text wasn't captured for this image</div>`
641
+ : `<div class="pairing">` +
642
+ `<div class="pair-col"><div class="pair-head pair-img">What the model sees · image</div><div class="frame frame-sm"><img src="${imgSrc}" alt="rendered page" /></div></div>` +
643
+ `<div class="pair-mid">made from ↓</div>` +
644
+ `<div class="pair-col"><div class="pair-head pair-txt">The original text · byte-exact</div><pre class="src-pane">${escapeHtml(sourceText)}</pre></div>` +
645
+ `</div>`;
646
+ }
647
+ return pinBar + main + `<div class="viewer-caption">${caption} ${srcBtn}</div>` + pane;
648
+ }
649
+ export function renderAnalyticsFragment(s) {
650
+ const days = s.daily ?? [];
651
+ const today = s.today;
652
+ const hasToday = Boolean(today && today.requests > 0);
653
+ const rawSaved = s.raw_saved_tokens ?? 0;
654
+ const imagedCount = s.imaged_requests ?? 0;
655
+ const textCount = s.text_compressed_requests ?? 0;
656
+ const summaryKpis = `<div class="analytics-kpis">` +
657
+ `<div class="akpi">` +
658
+ `<div class="akpi-lbl">Today</div>` +
659
+ `<div class="akpi-val">${today ? `${kFmt(today.saved_tokens)} <span class="akpi-unit">wtd</span>` : '0 <span class="akpi-unit">wtd</span>'}</div>` +
660
+ `<div class="akpi-sub">${hasToday && today ? `${kFmt(today.raw_saved_tokens)} raw · ${fmtSignedUsd(today.saved_usd)} · ${numFmt(today.requests)} req` : 'no requests today yet'}</div>` +
661
+ `</div>` +
662
+ `<div class="akpi">` +
663
+ `<div class="akpi-lbl">Lifetime</div>` +
664
+ `<div class="akpi-val">${kFmt(s.saved_input_tokens)} <span class="akpi-unit">wtd</span></div>` +
665
+ `<div class="akpi-sub">${kFmt(rawSaved)} raw · ${fmtSignedUsd(s.saved_usd ?? 0)} · ${numFmt(imagedCount)} img / ${numFmt(textCount)} txt</div>` +
666
+ `</div>` +
667
+ `</div>`;
668
+ const buildDailySvg = (metric) => {
669
+ const W = 640;
670
+ const H = 156;
671
+ const padL = 10;
672
+ const padR = 54;
673
+ const padT = 14;
674
+ const padB = 24;
675
+ const plotW = W - padL - padR;
676
+ const plotH = H - padT - padB;
677
+ const vals = days.map((d) => Math.max(0, metric === 'usd' ? d.saved_usd : d.saved_tokens));
678
+ const maxVal = Math.max(metric === 'usd' ? 0.01 : 1, ...vals);
679
+ const fmtTick = (v) => metric === 'usd' ? `$${v >= 10 ? v.toFixed(1) : v.toFixed(2)}` : kFmt(v);
680
+ const gridLines = [0, 0.5, 1]
681
+ .map((frac) => {
682
+ const y = padT + plotH * (1 - frac);
683
+ const label = fmtTick(maxVal * frac);
684
+ return (`<line x1="${padL}" y1="${y.toFixed(1)}" x2="${padL + plotW}" y2="${y.toFixed(1)}" ` +
685
+ `stroke="var(--border)" stroke-dasharray="${frac === 0 ? '' : '3 3'}" stroke-width="1"/>` +
686
+ `<text x="${padL + plotW + 6}" y="${(y + 3).toFixed(1)}" font-size="9.5" fill="var(--muted)" font-family="var(--mono)">${escapeHtml(label)}</text>`);
687
+ })
688
+ .join('');
689
+ const count = Math.max(1, days.length);
690
+ const slotW = plotW / count;
691
+ const barW = Math.max(8, Math.min(28, slotW * 0.64));
692
+ const bars = days
693
+ .map((d, i) => {
694
+ const v = vals[i] ?? 0;
695
+ const barH = v > 0 ? Math.max(3, (v / maxVal) * plotH) : 2;
696
+ const x = padL + i * slotW + (slotW - barW) / 2;
697
+ const y = padT + plotH - barH;
698
+ const tip = `${d.date}: ${kFmt(d.saved_tokens)} wtd · ${kFmt(d.raw_saved_tokens)} raw · ${fmtSignedUsd(d.saved_usd)} · ${d.requests} req${d.is_today ? ' (Live today)' : ''}`;
699
+ const fill = v > 0 ? 'var(--good)' : 'var(--border-strong)';
700
+ const extra = d.is_today
701
+ ? ` opacity="0.58" stroke="var(--good)" stroke-dasharray="3 2" stroke-width="1.2"`
702
+ : '';
703
+ return (`<g>` +
704
+ `<title>${escapeHtml(tip)}</title>` +
705
+ `<rect x="${x.toFixed(1)}" y="${y.toFixed(1)}" width="${barW.toFixed(1)}" height="${barH.toFixed(1)}" rx="3" fill="${fill}"${extra}/>` +
706
+ `</g>`);
707
+ })
708
+ .join('');
709
+ const xLabelIdxs = days.length > 0 ? [...new Set([0, Math.floor((days.length - 1) / 2), days.length - 1])] : [];
710
+ const xLabels = xLabelIdxs
711
+ .map((idx) => {
712
+ const d = days[idx];
713
+ const cx = padL + idx * slotW + slotW / 2;
714
+ const txt = d.is_today ? 'Today' : d.date.slice(5);
715
+ return `<text x="${cx.toFixed(1)}" y="${H - 6}" text-anchor="middle" font-size="9.5" fill="var(--muted)" font-family="var(--mono)">${escapeHtml(txt)}</text>`;
716
+ })
717
+ .join('');
718
+ const cls = metric === 'usd' ? 'daily-svg daily-svg-usd' : 'daily-svg daily-svg-tokens';
719
+ const dataAttr = metric === 'usd' ? 'daily-usd' : 'daily';
720
+ return (`<svg class="${cls}" data-chart="${dataAttr}" viewBox="0 0 ${W} ${H}" role="img" aria-label="14-day daily savings (${metric})">` +
721
+ gridLines +
722
+ bars +
723
+ xLabels +
724
+ `</svg>`);
725
+ };
726
+ const dailyPanel = `<div class="card">` +
727
+ `<div class="chart-head">` +
728
+ `<h3 class="card-head" style="margin:0">Daily savings (14d)</h3>` +
729
+ `<div class="metric-tabs">` +
730
+ `<button type="button" class="mini-btn metric-btn metric-btn-tokens on" onclick="ppSetMetric('tokens')">Tokens</button>` +
731
+ `<button type="button" class="mini-btn metric-btn metric-btn-usd" onclick="ppSetMetric('usd')">USD</button>` +
732
+ `</div>` +
733
+ `</div>` +
734
+ (days.length > 0
735
+ ? buildDailySvg('tokens') + buildDailySvg('usd')
736
+ : `<div class="empty-note">Daily chart populates automatically as requests arrive.</div>`) +
737
+ `<div class="axis">Solid: sealed day · Dashed (58%): Live today (unsealed)</div>` +
738
+ `</div>`;
739
+ const modelEntries = Object.entries(s.by_model ?? {}).sort((a, b) => {
740
+ const diffTok = b[1].saved_tokens - a[1].saved_tokens;
741
+ if (diffTok !== 0)
742
+ return diffTok;
743
+ const diffReq = b[1].requests - a[1].requests;
744
+ if (diffReq !== 0)
745
+ return diffReq;
746
+ return a[0].localeCompare(b[0]);
747
+ });
748
+ const maxModelTok = Math.max(1, ...modelEntries.map(([, m]) => Math.max(0, m.saved_tokens)));
749
+ const modelBars = modelEntries.length === 0
750
+ ? `<div class="empty-note">No per-model traffic recorded yet.</div>`
751
+ : `<div class="bars">` +
752
+ modelEntries
753
+ .map(([model, m]) => {
754
+ const pctW = m.saved_tokens > 0 ? Math.max(2, (m.saved_tokens / maxModelTok) * 100) : 0;
755
+ const fill = pctW > 0 ? `<div class="bar-fill" style="width:${pctW.toFixed(1)}%"></div>` : '';
756
+ const modeDetail = `${numFmt(m.requests)} req · ${numFmt(m.imaged)} img · ${numFmt(m.text_compressed)} txt`;
757
+ const valLabel = `${kFmt(m.saved_tokens)} wtd · ${kFmt(m.raw_saved_tokens)} raw · ${fmtSignedUsd(m.saved_usd)}`;
758
+ const valCls = m.saved_tokens < 0 ? 'mbar-val neg' : m.saved_tokens === 0 ? 'mbar-val muted' : 'mbar-val';
759
+ return (`<div class="mbar-row">` +
760
+ `<div class="mbar-top">` +
761
+ `<span class="mbar-name" title="${escapeHtml(model)}">${escapeHtml(model)}</span>` +
762
+ `<span class="${valCls}">${valLabel}</span>` +
763
+ `</div>` +
764
+ `<div class="bar-track">${fill}</div>` +
765
+ `<div class="mbar-sub">${modeDetail}</div>` +
766
+ `</div>`);
767
+ })
768
+ .join('') +
769
+ `</div>`;
770
+ const modelsPanel = `<div class="card">` +
771
+ `<h3 class="card-head">By model (tokens saved &amp; USD)</h3>` +
772
+ modelBars +
773
+ `</div>`;
774
+ return (`<div class="analytics-wrap" data-metric="tokens">` +
775
+ summaryKpis +
776
+ `<div class="analytics-grid">${dailyPanel}${modelsPanel}</div>` +
777
+ `</div>`);
778
+ }
779
+ // ---- sessions bar chart --------------------------------------------------
780
+ const TOP_N = 8;
781
+ export function renderSessionsFragment(p) {
782
+ const all = p.sessions ?? [];
783
+ const rows = [...all]
784
+ .sort((a, b) => (b.tokensSavedEst ?? 0) - (a.tokensSavedEst ?? 0))
785
+ .slice(0, TOP_N);
786
+ const max = rows.reduce((m, s) => Math.max(m, s.tokensSavedEst ?? 0), 0);
787
+ const label = (s) => {
788
+ const proj = s.claudeCode?.projectPath || s.project;
789
+ return proj ? shortPath(proj) : s.id.slice(0, 8);
790
+ };
791
+ const barPct = (v) => (max <= 0 || v <= 0 ? 0 : (v / max) * 100);
792
+ const status = `<div class="status">${all.length} session${all.length === 1 ? '' : 's'} tracked</div>`;
793
+ if (rows.length === 0)
794
+ return status + `<div class="empty">No sessions yet.</div>`;
795
+ const chart = rows
796
+ .map((s) => {
797
+ const v = s.tokensSavedEst ?? 0;
798
+ const pct = barPct(v);
799
+ const fill = pct > 0 ? `<div class="bar-fill" style="width:max(3px,${pct}%)"></div>` : '';
800
+ return (`<div class="bar-row">` +
801
+ `<div class="bar-label" title="${escapeHtml(s.claudeCode?.projectPath || s.project || s.id)}">${escapeHtml(label(s))}</div>` +
802
+ `<div class="bar-track">${fill}</div>` +
803
+ `<div class="bar-val${v < 0 ? ' neg' : ''}">${numFmt(v)}</div>` +
804
+ `</div>`);
805
+ })
806
+ .join('');
807
+ return (status +
808
+ `<div class="bars">${chart}</div>` +
809
+ `<div class="axis">tokens saved per session (cache-aware) · top ${rows.length} of ${all.length}</div>`);
810
+ }
811
+ // ---- full-history stats table --------------------------------------------
812
+ export function renderStatsTableFragment(p) {
813
+ if (p.error || !p.summary) {
814
+ return `<div class="status">${escapeHtml(p.error || 'no data')}</div><table class="dtable"><tbody></tbody></table>`;
815
+ }
816
+ const s = p.summary;
817
+ const totalIn = Math.max(0, (s.inputTokensTotal || 0) +
818
+ (s.cacheCreateTokensTotal || 0) +
819
+ (s.cacheReadTokensTotal || 0) -
820
+ (s.inclusiveCacheReadTotal || 0));
821
+ const hitRateTok = totalIn > 0 ? ((s.cacheReadTokensTotal / totalIn) * 100).toFixed(1) + '%' : '-';
822
+ const hitRateEv = s.eventsWithUsage > 0 ? ((s.cacheHitEvents / s.eventsWithUsage) * 100).toFixed(1) + '%' : '-';
823
+ const charRatio = s.origCharsTotal > 0 ? (s.imageBytesTotal / s.origCharsTotal).toFixed(3) : '-';
824
+ // NOTE: the literal word "requests" is asserted by tests.
825
+ const tr = (k, v) => `<tr><td>${k}</td><td class="num">${v}</td></tr>`;
826
+ return (`<div class="status">${numFmt(p.parsed)} events parsed from disk</div>` +
827
+ `<table class="dtable"><tbody>` +
828
+ tr('requests', numFmt(s.total)) +
829
+ tr('2xx / 4xx / 5xx', `${numFmt(s.ok2xx)} / ${numFmt(s.err4xx)} / ${numFmt(s.err5xx)}`) +
830
+ tr('compressed', numFmt(s.compressed)) +
831
+ tr('passthrough', numFmt(s.passthrough)) +
832
+ tr('input tokens', numFmt(s.inputTokensTotal)) +
833
+ tr('cache create', numFmt(s.cacheCreateTokensTotal)) +
834
+ tr('cache read', numFmt(s.cacheReadTokensTotal)) +
835
+ tr('cache hit (by tokens)', hitRateTok) +
836
+ tr('cache hit (by events)', hitRateEv) +
837
+ tr('original chars', numFmt(s.origCharsTotal)) +
838
+ tr('image bytes', numFmt(s.imageBytesTotal)) +
839
+ tr('bytes / char', charRatio) +
840
+ (s.pinEvents
841
+ ? tr('pin footer (uncached)', `${numFmt(s.pinCharsTotal ?? 0)} chars / ${numFmt(s.pinEvents)} req`)
842
+ : '') +
843
+ tr('latency p50 / p95', `${numFmt(s.durationP50)} / ${numFmt(s.durationP95)} ms`) +
844
+ tr('first-byte p50 / p95', `${numFmt(s.firstByteP50)} / ${numFmt(s.firstByteP95)} ms`) +
845
+ `</tbody></table>`);
846
+ }
847
+ // ---- page shell -------------------------------------------------------------
848
+ // Concept A prismatic optical compression funnel & faceted crystal frame.
849
+ // Exported so both the inlined data-URI favicon and /favicon.svg share one source.
850
+ export const FICHE_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" role="img" aria-label="fiche">` +
851
+ `<defs>` +
852
+ `<linearGradient id="fa-top" x1="0" y1="0" x2="1" y2="0"><stop offset="0%" stop-color="#FF4D5A"/><stop offset="52%" stop-color="#FF6B2B"/><stop offset="100%" stop-color="#FFB020"/></linearGradient>` +
853
+ `<linearGradient id="fa-mid" x1="0" y1="0" x2="1" y2="0"><stop offset="0%" stop-color="#9333EA"/><stop offset="52%" stop-color="#C026D3"/><stop offset="100%" stop-color="#F43F8E"/></linearGradient>` +
854
+ `<linearGradient id="fa-bot" x1="0" y1="0" x2="1" y2="0"><stop offset="0%" stop-color="#06E3F5"/><stop offset="52%" stop-color="#0EA5E9"/><stop offset="100%" stop-color="#3B82F6"/></linearGradient>` +
855
+ `<linearGradient id="fa-gem-top" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stop-color="#FFD166"/><stop offset="100%" stop-color="#FF70A6"/></linearGradient>` +
856
+ `<linearGradient id="fa-gem-bot" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stop-color="#C084FC"/><stop offset="100%" stop-color="#9333EA"/></linearGradient>` +
857
+ `</defs>` +
858
+ `<rect x="8" y="8" width="240" height="240" rx="52" fill="#0B0D14" stroke="#1E293B" stroke-width="3"/>` +
859
+ `<g transform="translate(22 22) scale(0.828)">` +
860
+ `<path d="M14 74H62C88 74 96 109 127 109V119C90 119 82 102 62 102H14Z" fill="url(#fa-top)"/>` +
861
+ `<path d="M14 114H62C88 114 96 123 127 123V133C96 133 88 142 62 142H14Z" fill="url(#fa-mid)"/>` +
862
+ `<path d="M14 154H62C82 154 90 137 127 137V147C96 147 88 182 62 182H14Z" fill="url(#fa-bot)"/>` +
863
+ `<path d="M129 104V79H227V177H129V152H114V192H242V64H114V104Z" fill="#FFFFFF"/>` +
864
+ `<polygon points="178,102 165,128 152,128" fill="#FF5447"/>` +
865
+ `<polygon points="178,102 191,128 165,128" fill="url(#fa-gem-top)"/>` +
866
+ `<polygon points="178,102 204,128 191,128" fill="#22D3EE"/>` +
867
+ `<polygon points="152,128 165,128 178,154" fill="#F43F5E"/>` +
868
+ `<polygon points="165,128 191,128 178,154" fill="url(#fa-gem-bot)"/>` +
869
+ `<polygon points="191,128 204,128 178,154" fill="#3B82F6"/>` +
870
+ `</g>` +
871
+ `</svg>`;
872
+ const FAVICON = `data:image/svg+xml,${encodeURIComponent(FICHE_ICON_SVG)}`;
873
+ const CSS = `
874
+ :root {
875
+ --bg: #f8f9fb; --surface: #ffffff; --surface-2: #f1f3f6;
876
+ --border: #e5e7eb; --border-strong: #d1d5db;
877
+ --ink: #0f172a; --ink-2: #475569; --muted: #64748b;
878
+ --accent: #0f172a; --accent-soft: #f1f5f9;
879
+ --good: #15803d; --good-tint: #ecfdf5;
880
+ --bad: #dc2626; --bad-tint: #fef2f2;
881
+ --warn: #b45309; --warn-tint: #fffbeb;
882
+ --img: #4f46e5; --img-ink: #3730a3; --img-tint: #eef2ff;
883
+ --txt: #0369a1; --txt-ink: #075985; --txt-tint: #f0f9ff;
884
+ --hyg: #0f766e; --hyg-ink: #115e59; --hyg-tint: #ccfbf1;
885
+ --radius: 12px;
886
+ --shadow: 0 1px 2px rgba(15,23,42,0.04);
887
+ --font: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
888
+ --mono: 'JetBrains Mono', 'SF Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
889
+ color-scheme: light;
890
+ }
891
+ /* Dark theme: true graphite obsidian, set before first paint via localStorage 'pp-theme' else system pref. */
892
+ :root[data-theme="dark"] {
893
+ --bg: #0b0d12; --surface: #11141b; --surface-2: #171b24;
894
+ --border: rgba(255,255,255,0.08); --border-strong: rgba(255,255,255,0.14);
895
+ --ink: #f1f5f9; --ink-2: #94a3b8; --muted: #64748b;
896
+ --accent: #e2e8f0; --accent-soft: rgba(255,255,255,0.06);
897
+ --good: #34d399; --good-tint: rgba(52,211,153,0.10);
898
+ --bad: #f87171; --bad-tint: rgba(248,113,113,0.10);
899
+ --warn: #fbbf24; --warn-tint: rgba(251,191,36,0.10);
900
+ --img: #818cf8; --img-ink: #c7d2fe; --img-tint: rgba(129,140,248,0.12);
901
+ --txt: #38bdf8; --txt-ink: #bae6fd; --txt-tint: rgba(56,189,248,0.10);
902
+ --hyg: #2dd4bf; --hyg-ink: #99f6e4; --hyg-tint: rgba(45,212,191,0.12);
903
+ --shadow: 0 1px 2px rgba(0,0,0,0.3);
904
+ color-scheme: dark;
905
+ }
906
+ :root[data-theme="dark"] .banner { border-color: rgba(248,113,113,0.28); color: #fecaca; }
907
+ :root[data-theme="dark"] .banner strong { color: #fee2e2; }
908
+ :root[data-theme="dark"] .toast { border-color: rgba(248,113,113,0.28); box-shadow: 0 8px 24px rgba(0,0,0,0.5); }
909
+ :root[data-theme="dark"] #routing-help::backdrop { background: rgba(0,0,0,0.65); }
910
+ * { box-sizing: border-box; }
911
+ body { margin: 0; padding: 24px 28px 64px; background: var(--bg); color: var(--ink-2);
912
+ font: 14px/1.5 var(--font); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
913
+ .shell { max-width: 1180px; margin: 0 auto; }
914
+ b, strong { color: var(--ink); }
915
+ code { font-family: var(--mono); font-size: 0.9em; background: var(--surface-2);
916
+ border: 1px solid var(--border); border-radius: 5px; padding: 1px 5px; color: var(--ink); }
917
+ .good { color: var(--good); } .bad { color: var(--bad); }
918
+ .muted { color: var(--muted); }
919
+
920
+ /* topbar */
921
+ .topbar { display: flex; align-items: center; justify-content: space-between;
922
+ gap: 16px; flex-wrap: wrap; margin-bottom: 22px; padding-bottom: 16px;
923
+ border-bottom: 1px solid var(--border); }
924
+ .brand { display: flex; align-items: center; gap: 12px; min-width: 0; }
925
+ .brand-mark { width: 34px; height: 34px; flex: none; display: block; }
926
+ .wordmark { font-size: 21px; font-weight: 700; color: var(--ink); letter-spacing: -0.03em; line-height: 1.1; }
927
+ .wordmark-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
928
+ /* Which machine is this? Two dashboards from two hosts look identical otherwise. */
929
+ .hostchip { font-size: 11px; font-weight: 600; color: var(--muted); padding: 1px 8px;
930
+ background: var(--surface); border: 1px solid var(--border-strong); border-radius: 999px; white-space: nowrap; }
931
+ .tagline { font-size: 12.5px; color: var(--muted); margin-top: 2px; max-width: 520px; }
932
+ .controls { display: flex; align-items: center; justify-content: flex-end; gap: 8px; flex-wrap: wrap; }
933
+ @media (max-width: 720px) { .controls { justify-content: flex-start; } }
934
+ #frag-toggle { display: contents; }
935
+
936
+ /* kill switch */
937
+ .banner { order: 3; flex: 0 0 100%; margin: 4px 0 0; padding: 9px 13px; background: var(--bad-tint);
938
+ border: 1px solid rgba(220,38,38,0.22); border-radius: 8px; color: #991b1b; font-size: 12px; }
939
+ .banner strong { color: #7f1d1d; }
940
+ .switch { order: 2; display: inline-flex; align-items: center; gap: 8px; flex-wrap: wrap; }
941
+ .switch-state { display: inline-flex; align-items: center; gap: 6px; height: 30px; font-size: 12px; font-weight: 600;
942
+ padding: 0 10px; border-radius: 999px; white-space: nowrap; }
943
+ .switch-state.on { color: var(--good); background: var(--good-tint); }
944
+ .switch-state.off { color: var(--bad); background: var(--bad-tint); }
945
+ .switch-dot { width: 6px; height: 6px; border-radius: 50%; background: currentColor; }
946
+ .switch-btn { background: var(--surface); color: var(--ink); border: 1px solid var(--border-strong);
947
+ height: 30px; padding: 0 11px; cursor: pointer; border-radius: 8px; font: inherit; font-size: 12px; font-weight: 500;
948
+ box-shadow: var(--shadow); display: inline-flex; align-items: center; line-height: 1; white-space: nowrap; }
949
+ .switch-btn:hover { border-color: var(--accent); background: var(--accent-soft); }
950
+ .hint { color: var(--muted); font-size: 11px; font-weight: 400; }
951
+ .theme-btn { order: 1; background: var(--surface); color: var(--ink-2); border: 1px solid var(--border-strong);
952
+ height: 30px; padding: 0 11px; cursor: pointer; border-radius: 8px; font: inherit; font-size: 12px; font-weight: 500;
953
+ box-shadow: var(--shadow); display: inline-flex; align-items: center; gap: 6px; line-height: 1; white-space: nowrap; }
954
+ .theme-btn:hover { border-color: var(--accent); color: var(--ink); background: var(--accent-soft); }
955
+
956
+ /* model chips & config dock */
957
+ .config-dock { margin: 16px 0 24px; background: var(--surface); border: 1px solid var(--border);
958
+ border-radius: var(--radius); overflow: hidden; box-shadow: var(--shadow); }
959
+ .models { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 0 0 18px; }
960
+ .models-label { color: var(--ink-2); font-size: 12px; font-weight: 600; min-width: 170px; }
961
+ .models-csv { flex: 1 1 260px; min-width: 220px; color: var(--ink); background: var(--surface);
962
+ border: 1px solid var(--border-strong); border-radius: 6px; padding: 5px 9px;
963
+ font: 12px/1.4 var(--mono); }
964
+ .models-csv:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 2px var(--accent-soft); }
965
+ .models-routing { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 12px 0 0;
966
+ padding-top: 10px; border-top: 1px solid var(--border); }
967
+ #routing-help { border: 1px solid var(--border-strong); border-radius: var(--radius); background: var(--surface);
968
+ color: var(--ink); max-width: 600px; padding: 18px 22px; box-shadow: 0 16px 40px rgba(15,23,42,0.18); }
969
+ #routing-help::backdrop { background: rgba(15, 23, 42, 0.45); }
970
+ #routing-help h3 { margin: 0 0 8px; font-size: 14px; color: var(--ink); }
971
+ #routing-help p, #routing-help li { font-size: 12px; line-height: 1.55; color: var(--ink-2); margin: 6px 0; }
972
+ #routing-help ul { margin: 6px 0; padding-left: 18px; }
973
+ #routing-help code { font: 11px var(--mono); color: var(--ink); }
974
+ #routing-help pre { background: var(--surface-2); border: 1px solid var(--border); border-radius: 8px;
975
+ padding: 9px 11px; margin: 8px 0; overflow-x: auto;
976
+ font: 11px/1.5 var(--mono); color: var(--ink); }
977
+ .chip { background: var(--surface); color: var(--ink-2); border: 1px solid var(--border-strong);
978
+ border-radius: 999px; padding: 4px 11px; cursor: pointer; font: inherit; font-size: 12px; font-weight: 500;
979
+ transition: border-color .12s, background .12s, color .12s; }
980
+ .chip:hover { border-color: var(--border-strong); color: var(--ink); background: var(--accent-soft); }
981
+ .chip.on { background: var(--accent); color: var(--surface); border-color: var(--accent);
982
+ font-weight: 600; }
983
+ .chip.on:hover { background: var(--accent); color: var(--surface); border-color: var(--accent); opacity: 0.9; }
984
+
985
+ /* collapsed config drawers (#116): <details> lives in the static shell — NOT
986
+ inside #frag-models — so the 2s poll never resets open state. */
987
+ .models-collapse { margin: 0; border-bottom: 1px solid var(--border); }
988
+ .models-collapse:last-child { border-bottom: none; }
989
+ .models-collapse .models { margin: 0 0 10px; }
990
+ .models-collapse .models:last-child { margin-bottom: 0; }
991
+ .models-summary { cursor: pointer; list-style: none; padding: 11px 16px; color: var(--ink);
992
+ font-size: 12.5px; font-weight: 600; margin: 0; user-select: none;
993
+ display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
994
+ .models-summary::-webkit-details-marker { display: none; }
995
+ .models-summary::before { content: '▸'; color: var(--muted); font-size: 10px; }
996
+ .models-collapse[open] > .models-summary::before { content: '▾'; }
997
+ .models-summary:hover { background: var(--surface-2); color: var(--ink); }
998
+ .dock-body { padding: 12px 16px 16px; border-top: 1px solid var(--border); font-size: 12.5px; color: var(--ink-2); }
999
+ .dock-body p { margin: 0 0 10px; }
1000
+ .dock-body p:last-child { margin-bottom: 0; }
1001
+ .dock-body pre { background: var(--surface-2); border: 1px solid var(--border); border-radius: 8px;
1002
+ padding: 9px 12px; margin: 0 0 12px; overflow-x: auto; font: 12px/1.5 var(--mono); color: var(--ink); }
1003
+ .models-warning { color: var(--ink-2); background: var(--warn-tint); border: 1px solid var(--border);
1004
+ border-left: 2px solid var(--warn); border-radius: 8px; padding: 8px 12px; font-size: 12px;
1005
+ margin: 0 0 12px; }
1006
+
1007
+ /* session hero */
1008
+ #frag-session { display: block; margin-bottom: 14px; }
1009
+ .hero { background: var(--surface); border: 1px solid var(--border);
1010
+ border-top: 2px solid var(--good); border-radius: var(--radius); padding: 22px 26px; box-shadow: var(--shadow); }
1011
+ .hero-neg { border-top-color: var(--bad); }
1012
+ .hero-empty { border-top-color: var(--border-strong); }
1013
+ .hero-eyebrow { font-size: 11px; font-weight: 600; letter-spacing: 0.08em; text-transform: uppercase;
1014
+ color: var(--muted); margin-bottom: 8px; }
1015
+ .hero-headline { font-size: 24px; font-weight: 600; color: var(--ink); letter-spacing: -0.025em; line-height: 1.15; }
1016
+ .hero-num { font-size: 46px; font-weight: 700; letter-spacing: -0.04em; line-height: 1; margin-right: 8px;
1017
+ color: var(--good); font-variant-numeric: tabular-nums; }
1018
+ .hero-neg .hero-num { color: var(--bad); }
1019
+ .hero-sub { font-size: 14px; color: var(--ink-2); margin-top: 10px; max-width: 740px; }
1020
+ .hero-meta { font-size: 12px; color: var(--muted); margin-top: 12px; padding-top: 10px;
1021
+ border-top: 1px solid var(--border); }
1022
+ .hero-empty .hero-headline { color: var(--muted); font-size: 22px; }
1023
+
1024
+ /* stat strip */
1025
+ .strip { display: grid; grid-template-columns: repeat(4, 1fr); gap: 12px; margin-bottom: 12px; }
1026
+ @media (max-width: 1000px) { .strip { grid-template-columns: repeat(2, 1fr); } }
1027
+ @media (max-width: 560px) { .strip { grid-template-columns: 1fr; } }
1028
+ .tile { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
1029
+ padding: 15px 18px; box-shadow: var(--shadow); }
1030
+ .tile-label { font-size: 11px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase;
1031
+ color: var(--muted); margin-bottom: 8px; display: flex; align-items: center; gap: 5px; }
1032
+ .tile-value { font-size: 24px; font-weight: 700; color: var(--ink); font-variant-numeric: tabular-nums;
1033
+ letter-spacing: -0.02em; line-height: 1.15; }
1034
+ .tile-value.pos { color: var(--good); } .tile-value.neg { color: var(--bad); }
1035
+ .tile-value.muted-val { color: var(--muted); font-size: 18px; font-weight: 600; }
1036
+ .tile-sub { font-size: 11.5px; color: var(--muted); margin-top: 6px; }
1037
+ .q { display: inline-flex; align-items: center; justify-content: center; width: 14px; height: 14px; flex: none;
1038
+ border-radius: 50%; background: var(--surface-2); border: 1px solid var(--border-strong);
1039
+ color: var(--muted); font-size: 9px; font-weight: 700; cursor: help; position: relative; outline: none;
1040
+ text-transform: none; letter-spacing: normal; }
1041
+ .q:hover, .q:focus-visible { color: var(--ink); border-color: var(--border-strong); background: var(--accent-soft); }
1042
+ .q::after { content: attr(data-tip); position: absolute; z-index: 50; left: 50%; bottom: calc(100% + 8px);
1043
+ width: min(280px, 75vw); transform: translate(-50%, 4px); padding: 8px 10px; border-radius: 7px;
1044
+ background: var(--ink); color: var(--surface); box-shadow: var(--shadow); font-family: var(--font);
1045
+ font-size: 11px; font-weight: 500; text-transform: none; letter-spacing: normal;
1046
+ line-height: 1.4; text-align: left; pointer-events: none; opacity: 0; visibility: hidden;
1047
+ transition: opacity .12s, transform .12s, visibility .12s; }
1048
+ .q::before { content: ''; position: absolute; z-index: 51; left: 50%; bottom: calc(100% + 3px);
1049
+ transform: translateX(-50%); border: 5px solid transparent; border-top-color: var(--ink);
1050
+ pointer-events: none; opacity: 0; visibility: hidden; transition: opacity .12s, visibility .12s; }
1051
+ .q:hover::after, .q:focus-visible::after { opacity: 1; visibility: visible; transform: translate(-50%, 0); }
1052
+ .q:hover::before, .q:focus-visible::before { opacity: 1; visibility: visible; }
1053
+
1054
+ /* drawer */
1055
+ .drawer { margin: 0 0 12px; background: var(--surface); border: 1px solid var(--border);
1056
+ border-radius: var(--radius); box-shadow: var(--shadow); overflow: hidden; }
1057
+ .drawer > summary { cursor: pointer; user-select: none; list-style: none; padding: 11px 16px;
1058
+ font-size: 12.5px; font-weight: 600; color: var(--ink); display: flex; align-items: center; gap: 8px; }
1059
+ .drawer > summary::-webkit-details-marker { display: none; }
1060
+ .drawer > summary::before { content: '▸'; color: var(--muted); font-size: 10px; }
1061
+ .drawer[open] > summary::before { content: '▾'; }
1062
+ .drawer > summary:hover { background: var(--surface-2); }
1063
+ .drawer-intro { padding: 10px 16px; border-top: 1px solid var(--border); font-size: 12px; color: var(--ink-2); }
1064
+ .drawer-intro em { color: var(--ink); font-style: normal; font-weight: 600; }
1065
+ .math-grid { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; padding: 0 16px 16px; }
1066
+ @media (max-width: 860px) { .math-grid { grid-template-columns: 1fr; } }
1067
+ .math-block h4 { margin: 0 0 6px; font-size: 12px; font-weight: 600; color: var(--ink); }
1068
+ .formula { background: var(--surface-2); border: 1px solid var(--border); border-radius: 8px;
1069
+ padding: 9px 11px; font: 11px/1.55 var(--mono); color: var(--ink-2); white-space: pre-wrap;
1070
+ word-break: break-word; }
1071
+ .formula .k { color: var(--muted); } .formula .v { color: var(--ink); } .formula .op { color: var(--good); font-weight: 600; }
1072
+ .formula .sp { height: 6px; }
1073
+ .formula .src { color: var(--muted); font-size: 10px; display: block; margin-top: 7px;
1074
+ border-top: 1px solid var(--border); padding-top: 6px; }
1075
+ .updated { font-size: 11.5px; color: var(--muted); display: flex; align-items: center; gap: 6px; }
1076
+ .live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--good); animation: pulse 2s infinite; }
1077
+ @keyframes pulse { 50% { opacity: 0.35; } }
1078
+
1079
+ /* sections */
1080
+ .section { margin-top: 28px; }
1081
+ .section-head { font-size: 13.5px; font-weight: 600; letter-spacing: -0.01em; color: var(--ink); margin: 0 0 12px;
1082
+ display: flex; align-items: baseline; gap: 10px; }
1083
+ .section-sub { font-size: 12px; font-weight: 400; color: var(--muted); }
1084
+ .card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
1085
+ padding: 18px 20px; box-shadow: var(--shadow); min-width: 0; }
1086
+ .card-head { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em;
1087
+ color: var(--muted); margin: 0 0 12px; }
1088
+ .card-head.spaced { margin-top: 22px; padding-top: 16px; border-top: 1px solid var(--border); }
1089
+
1090
+ /* x-ray */
1091
+ .xray { display: grid; grid-template-columns: 1.15fr 1fr; gap: 16px; align-items: start; }
1092
+ @media (max-width: 1000px) { .xray { grid-template-columns: 1fr; } }
1093
+
1094
+ /* context map */
1095
+ .ctxmap { font-size: 13px; }
1096
+ .empty-note { color: var(--muted); font-size: 12.5px; padding: 14px; background: var(--surface-2);
1097
+ border: 1px dashed var(--border-strong); border-radius: 10px; }
1098
+ .ctx-headline { font-size: 13px; color: var(--ink-2); margin-bottom: 10px; }
1099
+ .ctx-title { display: inline-block; font-weight: 600; color: var(--ink); margin-right: 6px; }
1100
+ .ctx-big { font-size: 22px; font-weight: 700; color: var(--ink); font-variant-numeric: tabular-nums; letter-spacing: -0.02em; }
1101
+ .legend { display: flex; gap: 8px; margin-bottom: 10px; }
1102
+ .tag { font-size: 11px; font-weight: 600; padding: 3px 9px 3px 22px; border-radius: 999px; position: relative; }
1103
+ .tag::before { content: ''; position: absolute; left: 9px; top: 50%; transform: translateY(-50%);
1104
+ width: 8px; height: 8px; border-radius: 2px; }
1105
+ .tag-img { background: var(--img-tint); color: var(--img-ink); }
1106
+ .tag-img::before { background: var(--img); }
1107
+ .tag-txt { background: var(--txt-tint); color: var(--txt-ink); }
1108
+ .tag-txt::before { background: var(--txt); }
1109
+ .split { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
1110
+ @media (max-width: 560px) { .split { grid-template-columns: 1fr; } }
1111
+ .split-col { border: 1px solid var(--border); border-radius: 10px; padding: 12px 14px; background: var(--surface); }
1112
+ .split-img { border-top: 2px solid var(--img); }
1113
+ .split-txt { border-top: 2px solid var(--txt); }
1114
+ .split-head { font-size: 12px; font-weight: 600; color: var(--ink); margin-bottom: 8px; display: flex;
1115
+ flex-direction: column; gap: 2px; }
1116
+ .split-sum { font-size: 10.5px; font-weight: 500; color: var(--muted); }
1117
+ .ctx-row { display: flex; justify-content: space-between; gap: 10px; font-size: 12px; padding: 4px 0;
1118
+ border-bottom: 1px solid var(--border); }
1119
+ .ctx-row:last-of-type { border-bottom: none; }
1120
+ .ctx-lbl { color: var(--ink-2); } .ctx-val { color: var(--ink); font-variant-numeric: tabular-nums; white-space: nowrap; }
1121
+ .muted-row { color: var(--muted); font-style: italic; }
1122
+ .split-note { font-size: 10.5px; color: var(--muted); margin-top: 7px; }
1123
+ .cap-note { color: var(--ink); border-left: 2px solid var(--warn); padding-left: 8px; }
1124
+ .pages-title { font-size: 11px; color: var(--ink-2); margin: 12px 0 6px; }
1125
+ .pages { display: flex; flex-wrap: wrap; gap: 6px; max-height: 320px; overflow: auto;
1126
+ background: var(--surface-2); padding: 6px; border: 1px solid var(--border); border-radius: 8px; }
1127
+ .page { height: 130px; width: auto; max-width: 230px; object-fit: contain; object-position: top left;
1128
+ image-rendering: pixelated; background: #fff; border: 1px solid var(--border-strong); border-radius: 4px;
1129
+ cursor: pointer; transition: border-color .12s, transform .12s; }
1130
+ .page:hover { border-color: var(--accent); transform: translateY(-1px); }
1131
+ .page.page-gone { width: 150px; height: 56px; background: var(--surface-2); border: 1px dashed var(--border-strong);
1132
+ color: var(--muted); font-size: 10px; cursor: default; }
1133
+
1134
+ /* recent requests */
1135
+ .row-view { color: var(--ink); font-weight: 600; text-decoration: none; cursor: pointer; white-space: nowrap; }
1136
+ .row-view:hover { text-decoration: underline; }
1137
+ table.rtable, table.dtable { width: 100%; border-collapse: collapse; font-size: 12px; }
1138
+ .rtable th, .dtable th { text-align: left; color: var(--muted); font-size: 11px; font-weight: 600;
1139
+ text-transform: uppercase; letter-spacing: 0.04em; padding: 8px 8px;
1140
+ border-bottom: 1px solid var(--border-strong); white-space: nowrap; }
1141
+ .rtable td, .dtable td { padding: 8px 8px; border-bottom: 1px solid var(--border);
1142
+ font-variant-numeric: tabular-nums; vertical-align: middle; color: var(--ink-2); }
1143
+ .rtable td code { background: transparent; border: none; padding: 0; font-size: 11.5px; }
1144
+ .rtable tr:last-child td, .dtable tr:last-child td { border-bottom: none; }
1145
+ .rtable tbody tr:hover, .dtable tbody tr:hover { background: var(--surface-2); }
1146
+ #frag-recent, #frag-stats { overflow-x: auto; overflow-y: hidden; scrollbar-width: thin; }
1147
+ #frag-recent table, #frag-stats table { min-width: max-content; }
1148
+ #frag-latest { overflow: auto; scrollbar-width: thin; }
1149
+ th.num, td.num { text-align: right; }
1150
+ td.pos { color: var(--good); font-weight: 600; }
1151
+ td.neg { color: var(--bad); font-weight: 600; }
1152
+ .endp { color: var(--ink); font-family: var(--mono); font-size: 11px; }
1153
+ .empty-cell { color: var(--muted); text-align: center; padding: 18px; }
1154
+ .pill { display: inline-block; min-width: 38px; text-align: center; font-size: 11px; font-weight: 600;
1155
+ padding: 2px 8px; border-radius: 999px; font-variant-numeric: tabular-nums; }
1156
+ .pill-good { background: var(--good-tint); color: var(--good); }
1157
+ .pill-warn { background: var(--warn-tint); color: var(--warn); }
1158
+ .pill-bad { background: var(--bad-tint); color: var(--bad); }
1159
+ .badge { font-size: 10.5px; font-weight: 600; padding: 2px 8px; border-radius: 999px; }
1160
+ .mk-create { font-size: 9.5px; font-weight: 600; color: var(--muted); border: 1px solid var(--border-strong);
1161
+ border-radius: 999px; padding: 0 5px; margin-left: 4px; vertical-align: 1px; cursor: help; white-space: nowrap; }
1162
+ .badge-img { background: var(--img-tint); color: var(--img-ink); }
1163
+ .badge-hyg { background: var(--hyg-tint); color: var(--hyg-ink); }
1164
+ .badge-txt { background: var(--txt-tint); color: var(--txt-ink); }
1165
+
1166
+ /* analytics (daily + per-model) */
1167
+ .analytics-wrap { display: flex; flex-direction: column; gap: 12px; }
1168
+ .analytics-kpis { display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px; }
1169
+ @media (max-width: 640px) { .analytics-kpis { grid-template-columns: 1fr; } }
1170
+ .akpi { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius);
1171
+ padding: 14px 18px; box-shadow: var(--shadow); }
1172
+ .akpi-lbl { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); }
1173
+ .akpi-val { font-size: 22px; font-weight: 700; color: var(--ink); font-variant-numeric: tabular-nums; margin-top: 4px; }
1174
+ .akpi-unit { font-size: 12px; font-weight: 500; color: var(--muted); }
1175
+ .akpi-sub { font-size: 11.5px; color: var(--muted); margin-top: 4px; font-variant-numeric: tabular-nums; }
1176
+ .analytics-grid { display: grid; grid-template-columns: 1.2fr 1fr; gap: 16px; align-items: start; }
1177
+ @media (max-width: 960px) { .analytics-grid { grid-template-columns: 1fr; } }
1178
+ .chart-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }
1179
+ .metric-tabs { display: inline-flex; gap: 4px; }
1180
+ .metric-btn.on { background: var(--accent); color: var(--surface); border-color: var(--accent); font-weight: 600; }
1181
+ .daily-svg { display: block; width: 100%; height: auto; }
1182
+ .analytics-wrap[data-metric="tokens"] .daily-svg-usd { display: none; }
1183
+ .analytics-wrap[data-metric="usd"] .daily-svg-tokens { display: none; }
1184
+ .mbar-row { display: flex; flex-direction: column; gap: 4px; padding-bottom: 8px; border-bottom: 1px solid var(--border); }
1185
+ .mbar-row:last-child { border-bottom: none; padding-bottom: 0; }
1186
+ .mbar-top { display: flex; justify-content: space-between; gap: 8px; align-items: baseline; font-size: 12px; }
1187
+ .mbar-name { font-family: var(--mono); font-size: 11.5px; font-weight: 600; color: var(--ink); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1188
+ .mbar-val { font-variant-numeric: tabular-nums; color: var(--good); font-weight: 600; font-size: 11.5px; white-space: nowrap; }
1189
+ .mbar-val.neg { color: var(--bad, #b42318); }
1190
+ .mbar-val.muted { color: var(--muted); }
1191
+ .mbar-sub { font-size: 10.5px; color: var(--muted); font-variant-numeric: tabular-nums; }
1192
+
1193
+ /* inspector */
1194
+ .viewer-bar { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; }
1195
+ .mini-btn { font-size: 11px; background: var(--surface); color: var(--ink); border: 1px solid var(--border-strong);
1196
+ border-radius: 7px; padding: 4px 10px; cursor: pointer; font-weight: 500; }
1197
+ .mini-btn:hover { border-color: var(--accent); background: var(--accent-soft); }
1198
+ .metric-btn.on:hover { background: var(--accent); color: var(--surface); border-color: var(--accent); opacity: 0.9; }
1199
+ .mini-label { font-size: 11px; color: var(--muted); }
1200
+ .frame { background: #fff; border: 1px solid var(--border-strong); border-radius: 8px; padding: 5px;
1201
+ overflow: auto; max-height: 360px; scrollbar-width: thin; }
1202
+ .frame img { display: block; width: auto; height: auto; max-width: none; image-rendering: pixelated; }
1203
+ .frame-sm { max-height: 260px; }
1204
+ .viewer-caption { font-size: 11px; color: var(--muted); margin-top: 8px; display: flex; align-items: center;
1205
+ gap: 10px; flex-wrap: wrap; }
1206
+ .pairing { display: grid; grid-template-columns: 1fr; gap: 10px; margin-top: 10px; }
1207
+ .pair-head { font-size: 11px; font-weight: 600; padding: 3px 9px; border-radius: 6px; display: inline-block;
1208
+ margin-bottom: 6px; }
1209
+ .pair-img { background: var(--img-tint); color: var(--img-ink); }
1210
+ .pair-txt { background: var(--txt-tint); color: var(--txt-ink); }
1211
+ .pair-mid { font-size: 11px; font-weight: 600; color: var(--muted); text-align: center; }
1212
+ .src-pane { margin: 0; max-height: 280px; overflow: auto; background: var(--surface-2);
1213
+ border: 1px solid var(--border); border-radius: 8px; padding: 9px; font: 11px/1.45 var(--mono);
1214
+ white-space: pre-wrap; word-break: break-word; color: var(--ink-2); }
1215
+ .evicted { font-size: 11.5px; color: var(--muted); padding: 12px; background: var(--surface-2);
1216
+ border: 1px dashed var(--border-strong); border-radius: 8px; }
1217
+
1218
+ /* sessions bars */
1219
+ .status { margin-bottom: 12px; color: var(--muted); font-size: 12px; }
1220
+ .bars { display: flex; flex-direction: column; gap: 8px; }
1221
+ .bar-row { display: flex; align-items: center; gap: 12px; font-size: 12px; }
1222
+ .bar-label { width: 150px; flex: none; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
1223
+ color: var(--ink); font-family: var(--mono); font-size: 11px; }
1224
+ .bar-track { flex: 1; min-width: 0; height: 14px; background: var(--surface-2); border-radius: 4px;
1225
+ overflow: hidden; border: 1px solid var(--border); }
1226
+ .bar-fill { height: 100%; border-radius: 4px 0 0 4px; background: var(--good); }
1227
+ .bar-val { width: 78px; flex: none; text-align: right; font-variant-numeric: tabular-nums;
1228
+ color: var(--good); font-weight: 600; }
1229
+ .bar-val.neg { color: var(--bad); }
1230
+ .axis { margin-top: 12px; color: var(--muted); font-size: 11px; }
1231
+ .empty { text-align: center; color: var(--muted); padding: 22px; font-size: 12px; }
1232
+
1233
+ /* toast tray */
1234
+ .tray { position: fixed; bottom: 16px; right: 16px; display: flex; flex-direction: column; gap: 8px;
1235
+ z-index: 1000; pointer-events: none; }
1236
+ .toast { background: var(--surface); color: var(--bad); border: 1px solid rgba(220,38,38,0.25); border-radius: 9px;
1237
+ padding: 10px 14px; font-size: 12px; box-shadow: 0 8px 24px rgba(15,23,42,0.10); display: flex;
1238
+ align-items: center; gap: 12px; pointer-events: auto; max-width: 360px; }
1239
+ .toast button { background: transparent; color: inherit; border: 0; cursor: pointer; font-size: 16px;
1240
+ line-height: 1; padding: 0; }
1241
+ `;
1242
+ // Client glue: window.pp (pin+source state) → hx-vals; preserves <details> open state across swaps; routes htmx errors to toast tray.
1243
+ const GLUE_JS = `
1244
+ window.pp = { pin: null, src: false, chartMetric: 'tokens' };
1245
+ function ppApplyMetric() {
1246
+ var m = window.pp.chartMetric === 'usd' ? 'usd' : 'tokens';
1247
+ var wrap = document.querySelector('#frag-analytics .analytics-wrap');
1248
+ if (wrap) {
1249
+ wrap.setAttribute('data-metric', m);
1250
+ wrap.querySelectorAll('.metric-btn-tokens').forEach(function (b) { b.classList.toggle('on', m === 'tokens'); });
1251
+ wrap.querySelectorAll('.metric-btn-usd').forEach(function (b) { b.classList.toggle('on', m === 'usd'); });
1252
+ }
1253
+ }
1254
+ function ppSetMetric(m) {
1255
+ window.pp.chartMetric = m === 'usd' ? 'usd' : 'tokens';
1256
+ ppApplyMetric();
1257
+ }
1258
+ function ppPin(id) {
1259
+ window.pp.pin = id;
1260
+ htmx.trigger('#frag-latest', 'pp-refresh');
1261
+ }
1262
+ function ppSource(on) {
1263
+ window.pp.src = on;
1264
+ htmx.trigger('#frag-latest', 'pp-refresh');
1265
+ }
1266
+ document.body.addEventListener('htmx:beforeSwap', function (ev) {
1267
+ const open = [];
1268
+ ev.detail.target.querySelectorAll('details[open][id]').forEach(function (d) { open.push(d.id); });
1269
+ ev.detail.target.__ppOpen = open;
1270
+ });
1271
+ document.body.addEventListener('htmx:afterSwap', function (ev) {
1272
+ (ev.detail.target.__ppOpen || []).forEach(function (id) {
1273
+ const d = document.getElementById(id);
1274
+ if (d) d.setAttribute('open', '');
1275
+ });
1276
+ if (ev.detail.target && ev.detail.target.id === 'frag-analytics') {
1277
+ ppApplyMetric();
1278
+ }
1279
+ });
1280
+ document.body.addEventListener('htmx:responseError', function (ev) {
1281
+ window.dispatchEvent(new CustomEvent('pp-toast', {
1282
+ detail: { text: ev.detail.xhr.status + ' ' + ev.detail.requestConfig.path }
1283
+ }));
1284
+ });
1285
+ document.body.addEventListener('htmx:sendError', function (ev) {
1286
+ window.dispatchEvent(new CustomEvent('pp-toast', {
1287
+ detail: { text: 'proxy unreachable: ' + ev.detail.requestConfig.path }
1288
+ }));
1289
+ });
1290
+ `;
1291
+ // Theme: light/dark via data-theme on <html>; saved in localStorage, defaults to system pref.
1292
+ const THEME_JS = `
1293
+ (function () {
1294
+ function apply(t) {
1295
+ document.documentElement.dataset.theme = t;
1296
+ var b = document.getElementById('theme-btn');
1297
+ if (b) {
1298
+ b.textContent = t === 'dark' ? '☀ Light' : '☾ Dark';
1299
+ b.setAttribute('aria-label', t === 'dark' ? 'Switch to light mode' : 'Switch to dark mode');
1300
+ }
1301
+ }
1302
+ window.ppTheme = function () {
1303
+ var next = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
1304
+ try { localStorage.setItem('pp-theme', next); } catch (e) {}
1305
+ apply(next);
1306
+ };
1307
+ apply(document.documentElement.dataset.theme === 'dark' ? 'dark' : 'light');
1308
+ })();
1309
+ `;
1310
+ /** `hostLabel` names the machine this proxy runs on. The dashboard is otherwise
1311
+ * byte-identical across hosts, so a tab opened against a remote host through
1312
+ * the tailnet front is indistinguishable from the local one - which is how a
1313
+ * session gets read on the wrong box. Empty label = render as before. */
1314
+ export function renderPage(port, hostLabel = '') {
1315
+ const host = escapeHtml(hostLabel.trim());
1316
+ // hx-trigger="load, every Ns": paint on load then poll (2s live, 5s aggregates).
1317
+ return `<!doctype html>
1318
+ <html lang="en">
1319
+ <head>
1320
+ <meta charset="utf-8" />
1321
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
1322
+ <title>${host ? `${host} · fiche dashboard` : 'fiche — live dashboard'}</title>
1323
+ <link rel="icon" href="${FAVICON}" />
1324
+ <style>${CSS}</style>
1325
+ <script>
1326
+ // Set theme before first paint (no flash): saved choice wins, else system preference.
1327
+ (function () {
1328
+ try {
1329
+ var s = localStorage.getItem('pp-theme');
1330
+ var dark = s ? s === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches;
1331
+ document.documentElement.dataset.theme = dark ? 'dark' : 'light';
1332
+ } catch (e) { document.documentElement.dataset.theme = 'light'; }
1333
+ })();
1334
+ </script>
1335
+ </head>
1336
+ <body>
1337
+ <main class="shell">
1338
+
1339
+ <header class="topbar">
1340
+ <div class="brand">
1341
+ <svg class="brand-mark" viewBox="0 0 256 256" width="34" height="34" fill="none" aria-hidden="true">
1342
+ <defs>
1343
+ <linearGradient id="dash-fa-top" x1="0" y1="0" x2="1" y2="0">
1344
+ <stop offset="0%" stop-color="#FF4D5A"/>
1345
+ <stop offset="52%" stop-color="#FF6B2B"/>
1346
+ <stop offset="100%" stop-color="#FFB020"/>
1347
+ </linearGradient>
1348
+ <linearGradient id="dash-fa-mid" x1="0" y1="0" x2="1" y2="0">
1349
+ <stop offset="0%" stop-color="#9333EA"/>
1350
+ <stop offset="52%" stop-color="#C026D3"/>
1351
+ <stop offset="100%" stop-color="#F43F8E"/>
1352
+ </linearGradient>
1353
+ <linearGradient id="dash-fa-bot" x1="0" y1="0" x2="1" y2="0">
1354
+ <stop offset="0%" stop-color="#06E3F5"/>
1355
+ <stop offset="52%" stop-color="#0EA5E9"/>
1356
+ <stop offset="100%" stop-color="#3B82F6"/>
1357
+ </linearGradient>
1358
+ <linearGradient id="dash-fa-gt" x1="0" y1="0" x2="1" y2="1">
1359
+ <stop offset="0%" stop-color="#FFD166"/>
1360
+ <stop offset="100%" stop-color="#FF70A6"/>
1361
+ </linearGradient>
1362
+ <linearGradient id="dash-fa-gb" x1="0" y1="0" x2="1" y2="1">
1363
+ <stop offset="0%" stop-color="#C084FC"/>
1364
+ <stop offset="100%" stop-color="#9333EA"/>
1365
+ </linearGradient>
1366
+ </defs>
1367
+ <rect x="8" y="8" width="240" height="240" rx="52" fill="#0B0D14" stroke="#1E293B" stroke-width="3"/>
1368
+ <g transform="translate(22, 22) scale(0.828)">
1369
+ <path d="M 14 74 H 62 C 88 74, 96 109, 127 109 V 119 C 90 119, 82 102, 62 102 H 14 Z" fill="url(#dash-fa-top)"/>
1370
+ <path d="M 14 114 H 62 C 88 114, 96 123, 127 123 V 133 C 96 133, 88 142, 62 142 H 14 Z" fill="url(#dash-fa-mid)"/>
1371
+ <path d="M 14 154 H 62 C 82 154, 90 137, 127 137 V 147 C 96 147, 88 182, 62 182 H 14 Z" fill="url(#dash-fa-bot)"/>
1372
+ <path d="M 129 104 V 79 H 227 V 177 H 129 V 152 H 114 V 192 H 242 V 64 H 114 V 104 Z" fill="#FFFFFF"/>
1373
+ <polygon points="178,102 165,128 152,128" fill="#FF5447"/>
1374
+ <polygon points="178,102 191,128 165,128" fill="url(#dash-fa-gt)"/>
1375
+ <polygon points="178,102 204,128 191,128" fill="#22D3EE"/>
1376
+ <polygon points="152,128 165,128 178,154" fill="#F43F5E"/>
1377
+ <polygon points="165,128 191,128 178,154" fill="url(#dash-fa-gb)"/>
1378
+ <polygon points="191,128 204,128 178,154" fill="#3B82F6"/>
1379
+ </g>
1380
+ </svg>
1381
+ <div>
1382
+ <div class="wordmark-row">
1383
+ <div class="wordmark">fiche</div>
1384
+ ${host ? `<span class="hostchip" title="proxy host">${host}</span>` : ''}
1385
+ </div>
1386
+ <div class="tagline">Microfiche for coding agents — cache-safe optical &amp; text compilation.</div>
1387
+ </div>
1388
+ </div>
1389
+ <div class="controls">
1390
+ <button type="button" id="theme-btn" class="theme-btn" onclick="ppTheme()" aria-label="Toggle dark mode" title="Toggle dark / light mode">☾ Dark</button>
1391
+ <div id="frag-toggle" hx-get="/fragments/toggle" hx-trigger="load, every 2s" hx-swap="innerHTML"></div>
1392
+ </div>
1393
+ </header>
1394
+
1395
+ <div id="frag-session" hx-get="/fragments/session-summary" hx-trigger="load, every 2s" hx-swap="innerHTML">
1396
+ <div class="hero hero-empty"><div class="hero-headline">Connecting…</div></div>
1397
+ </div>
1398
+
1399
+ <div id="frag-header" hx-get="/fragments/header" hx-trigger="load, every 2s" hx-swap="innerHTML"></div>
1400
+
1401
+ <section class="section" id="analytics-section">
1402
+ <h2 class="section-head">Daily &amp; per-model savings <span class="section-sub">lifetime &amp; daily tokens + kosha USD</span></h2>
1403
+ <div id="frag-analytics" hx-get="/fragments/analytics" hx-trigger="load, every 5s" hx-swap="innerHTML"></div>
1404
+ </section>
1405
+
1406
+ <div class="config-dock">
1407
+ <details class="models-collapse">
1408
+ <summary class="models-summary">Connect an agent <span class="hint">auto-wrap every CLI or launch any desktop app · instant FICHE_BYPASS=1 · @fiche pin</span></summary>
1409
+ <div class="dock-body">
1410
+ <p><strong>Option 1 — One-time automatic shell setup</strong> (recommended; routes <code>claude</code>, <code>codex</code>, <code>ribhu</code>, <code>agy</code>, <code>gemini</code>, <code>opencode</code>, <code>cursor-agent</code>, <code>amp</code>, <code>pi</code>, <code>aider</code> through Fiche automatically):</p>
1411
+ <pre>eval "$(fiche shell-init --wrap)" # add to ~/.zshrc or ~/.bashrc</pre>
1412
+ <p><strong>Option 2 — Wrap any CLI or Desktop app explicitly</strong> (with zero config edits):</p>
1413
+ <pre>fiche warp -- claude
1414
+ fiche warp -- codex
1415
+ fiche warp -- agy
1416
+ fiche warp -- gemini
1417
+ fiche warp -- opencode
1418
+ fiche warp -- aider
1419
+ fiche warp --app Antigravity</pre>
1420
+ <p>Desktop apps (Antigravity, Cursor, Claude, Windsurf, Zed, OpenCode, ChatGPT) and CLIs can also be launched with 1 click from the <strong>Agents</strong> tab in <code>FicheBar.app</code>. Already-running apps/terminals must be restarted once after wiring so they inherit the local proxy and TLS trust. Use <code>FICHE_BYPASS=1 claude</code> or the top pause switch for instant passthrough.</p>
1421
+ <p>Custom upstream routes use <code>--route PATTERN=http://host:port</code> (e.g. <code>--route '127.0.0.1:9090/v1/*=http://127.0.0.1:${port}'</code>). Without warp, point HTTP-capable clients at <code>ANTHROPIC_BASE_URL=http://127.0.0.1:${port}</code>.</p>
1422
+ <p>Pin instructions from inside the session — they get moved to the end of every request, where the model actually reads them:</p>
1423
+ <pre>@fiche pin be concise, no walls of text
1424
+ @fiche unpin 2
1425
+ @fiche unpin all</pre>
1426
+ <p><code>@fiche pin</code> with no text lists what is pinned.</p>
1427
+ <p>A <code>@fiche pin …</code> line in your global or project <code>CLAUDE.md</code> (<code>AGENTS.md</code> under Codex / OpenCode) is relocated the same way, on every session, with no typing. Those are file-backed, so <code>unpin</code> and <code>unpin all</code> never touch them — edit the file to remove one.</p>
1428
+ </div>
1429
+ </details>
1430
+
1431
+ <details class="models-collapse">
1432
+ <summary class="models-summary">Image model scope <span class="hint">Fable 5 &amp; Gemini optical by default; 4-layer text compiler runs across text-tier models</span></summary>
1433
+ <div class="dock-body">
1434
+ <div class="models-warning">Optical image compression is active by default for Fable 5 and Gemini; the 4-layer text compiler runs automatically across text-tier models. Other families can use <strong>more</strong> tokens when imaged — opt in only for deliberate experiments.</div>
1435
+ <div id="frag-models" hx-get="/fragments/models" hx-trigger="load, every 2s [!document.activeElement || document.activeElement.id !== 'models-csv']" hx-swap="innerHTML"></div>
1436
+ <div class="models-routing"><span class="hint">imaging scope ≠ provider routing — non-Anthropic IDs also need routing env on the proxy</span> <button class="mini-btn" type="button" onclick="document.getElementById('routing-help').showModal()">routing help</button></div>
1437
+ </div>
1438
+ </details>
1439
+
1440
+ <details class="models-collapse">
1441
+ <summary class="models-summary">3rd-party plugins &amp; extensions <span class="hint">one click toggles all external skills and plugins while keeping core compiler stages on</span></summary>
1442
+ <div class="dock-body">
1443
+ <div id="frag-plugins" hx-get="/fragments/plugins" hx-trigger="load, every 5s" hx-swap="innerHTML"></div>
1444
+ </div>
1445
+ </details>
1446
+ </div>
1447
+
1448
+ <section class="section">
1449
+ <h2 class="section-head">What happened to your context <span class="section-sub">click a request to see image vs text</span></h2>
1450
+ <div class="xray">
1451
+ <div class="card">
1452
+ <h3 class="card-head">Recent requests</h3>
1453
+ <div id="frag-recent" hx-get="/fragments/recent" hx-trigger="load, every 2s" hx-swap="innerHTML"></div>
1454
+ </div>
1455
+ <div class="card">
1456
+ <h3 class="card-head">Image vs text breakdown</h3>
1457
+ <div id="frag-context-map" hx-get="/fragments/context-map" hx-trigger="load" hx-swap="innerHTML"></div>
1458
+ <h3 class="card-head spaced">Image ↔ source inspector</h3>
1459
+ <div id="frag-latest" hx-get="/fragments/latest" hx-trigger="load, every 2s, pp-refresh" hx-swap="innerHTML"
1460
+ hx-vals='js:{pin: window.pp.pin == null ? "" : window.pp.pin, source: window.pp.src ? "1" : ""}'></div>
1461
+ </div>
1462
+ </div>
1463
+ </section>
1464
+
1465
+ <section class="section">
1466
+ <h2 class="section-head">Top sessions <span class="section-sub">by tokens saved</span></h2>
1467
+ <div class="card">
1468
+ <div id="frag-sessions" hx-get="/fragments/sessions" hx-trigger="load, every 5s" hx-swap="innerHTML"></div>
1469
+ </div>
1470
+ </section>
1471
+
1472
+ <section class="section">
1473
+ <h2 class="section-head">Full history <span class="section-sub">every event on disk</span></h2>
1474
+ <div class="card">
1475
+ <div id="frag-stats" hx-get="/fragments/stats" hx-trigger="load, every 5s" hx-swap="innerHTML"></div>
1476
+ </div>
1477
+ </section>
1478
+
1479
+ </main>
1480
+
1481
+ <dialog id="routing-help" onclick="if (event.target === this) this.close()">
1482
+ <h3>Routing Claude Code to OpenAI / Cloudflare models</h3>
1483
+ <p>Claude models use Anthropic by default. Two optional routes can run together — set on the <strong>fiche process</strong> (keep provider credentials out of Claude Code):</p>
1484
+ <ul>
1485
+ <li><code>OPENAI_MODELS</code> — exact model IDs routed to OpenAI Responses (<code>OPENAI_UPSTREAM</code> + <code>OPENAI_API_KEY</code>)</li>
1486
+ <li><code>CLOUDFLARE_MODELS</code> — exact model IDs routed to Cloudflare's OpenAI-compatible endpoint (<code>CLOUDFLARE_ACCOUNT_ID</code> + <code>CLOUDFLARE_API_TOKEN</code>)</li>
1487
+ </ul>
1488
+ <p>If a model appears in both lists: <code>CLOUDFLARE_MODELS &gt; OPENAI_MODELS &gt; default routing</code>.</p>
1489
+ <pre>OPENAI_UPSTREAM=https://api.openai.com \\
1490
+ OPENAI_API_KEY=your-openai-key \\
1491
+ OPENAI_MODELS=gpt-5.6-sol \\
1492
+ CLOUDFLARE_ACCOUNT_ID=your-account-id \\
1493
+ CLOUDFLARE_API_TOKEN=your-cloudflare-token \\
1494
+ CLOUDFLARE_MODELS=moonshotai/kimi-k3 \\
1495
+ npx @sriinnu/fiche</pre>
1496
+ <p>Non-Anthropic IDs are advertised with a <code>claude-</code> prefix because Claude Code needs a Claude-shaped ID; fiche strips it before forwarding. Switch to one inside Claude Code with <code>/model claude-&lt;model&gt;</code> — e.g. <code>/model claude-moonshotai/kimi-k3</code> — or launch with <code>claude --model claude-moonshotai/kimi-k3</code>. Verify discovery with <code>curl …/v1/models</code>.</p>
1497
+ <p><code>FICHE_MODELS</code> above is separate: it controls image compression, not routing. Kimi K3 on Cloudflare is the only non-Anthropic model tested end to end — see <code>docs/CLAUDE_CODE_PROVIDER_ROUTING.md</code>.</p>
1498
+ <button class="mini-btn" type="button" onclick="this.closest('dialog').close()">close</button>
1499
+ </dialog>
1500
+
1501
+ <div class="tray" x-data="{ toasts: [], next: 1 }"
1502
+ @pp-toast.window="const id = next++; toasts.push({ id, text: $event.detail.text }); setTimeout(() => toasts = toasts.filter(t => t.id !== id), 5000)">
1503
+ <template x-for="t in toasts" :key="t.id">
1504
+ <div class="toast"><span x-text="t.text"></span><button type="button" @click="toasts = toasts.filter(x => x.id !== t.id)" aria-label="dismiss">&times;</button></div>
1505
+ </template>
1506
+ </div>
1507
+
1508
+ <script>${HTMX_JS}</script>
1509
+ <script>${GLUE_JS}</script>
1510
+ <script>${THEME_JS}</script>
1511
+ <script>${ALPINE_JS}</script>
1512
+ </body>
1513
+ </html>`;
1514
+ }
1515
+ //# sourceMappingURL=fragments.js.map