@alexgreensh/token-optimizer 5.13.62 → 5.13.63

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.
@@ -287,6 +287,9 @@ th, td { padding: 10px !important; }
287
287
  }
288
288
  .fold__body p { margin: 0 0 var(--s-3); }
289
289
  .fold__body p:last-child { margin-bottom: 0; }
290
+ .fold__body ul { margin: 0 0 var(--s-3); padding-left: 1.3em; }
291
+ .fold__body li { margin: 0 0 var(--s-2); }
292
+ .fold__body li:last-child { margin-bottom: 0; }
290
293
  .fold__body strong, .fold__body b { color: var(--c-text-main); font-weight: 600; }
291
294
 
292
295
  /* Visible lead sentence above a fold: sized to read, capped near 62ch so lines
@@ -301,6 +304,12 @@ th, td { padding: 10px !important; }
301
304
  }
302
305
  .lede + .lede { margin-top: var(--s-3); }
303
306
  .lede strong, .lede b { color: var(--c-text-main); font-weight: 500; }
307
+ /* One short readable line under a number: normal text colour, never grey fine print.
308
+ Anything longer belongs in a .fold. */
309
+ .plain-line {
310
+ font-size: 15px; line-height: 1.6; color: var(--c-text-main);
311
+ max-width: 62ch; text-wrap: pretty; margin: var(--s-2) 0 0;
312
+ }
304
313
  /* Plain inline note (methodology one-liners under bars/cards). */
305
314
  .note {
306
315
  font-size: 14px; line-height: 1.75; color: var(--c-text-dim);
@@ -2389,10 +2398,41 @@ function codexMemCardHtml(mr, fn) { return '<div class="card"><div class="card-h
2389
2398
  '<div style="text-align:center;padding:0 0 var(--s-3);font-size:12px;color:var(--c-text-dim);">Measured from Codex state; no file structure audit</div>' +
2390
2399
  '</div>'; }
2391
2400
  function memCountSuffix(mr) { return mr && mr.scan_partial ? '+' : ''; }
2401
+ function hermesComponentDetails(c) {
2402
+ function fileSub(x, missing) {
2403
+ return (x && x.exists) ? (x.lines || 0) + ' lines loaded every session' : missing;
2404
+ }
2405
+ var sk = c.skills || {}, mcp = c.mcp_tools || {};
2406
+ return [
2407
+ { key: 'hermes_soul', name: 'SOUL.md', tokens: c.hermes_soul ? c.hermes_soul.tokens : 0,
2408
+ sub: fileSub(c.hermes_soul, 'No SOUL.md in your Hermes home'),
2409
+ what: 'Hermes loads SOUL.md from its home folder into every session as the agent identity.',
2410
+ top: [], issues: [], related: [] },
2411
+ { key: 'hermes_memory', name: 'Memory', tokens: c.hermes_memory ? c.hermes_memory.tokens : 0,
2412
+ sub: fileSub(c.hermes_memory, 'No MEMORY.md or USER.md yet'),
2413
+ what: 'MEMORY.md and USER.md from memories/ are added to the system prompt as a snapshot when a session starts.',
2414
+ top: [], issues: [], related: [] },
2415
+ { key: 'skills', name: 'Skills', tokens: sk.tokens || 0,
2416
+ sub: (sk.count || 0) + ' skills listed' + (sk.archived_count ? ', ' + sk.archived_count + ' archived' : '') +
2417
+ (sk.disabled_count ? ', ' + sk.disabled_count + ' disabled' : ''),
2418
+ what: 'Hermes lists each skill name and description in the system prompt and loads the full skill only when it is used. Short descriptions keep the list small.',
2419
+ top: [], issues: [], related: [] },
2420
+ { key: 'mcp_tools', name: 'MCP Servers', tokens: mcp.tokens || 0,
2421
+ sub: (mcp.server_count || 0) + ' servers enabled' + (mcp.disabled_count ? ', ' + mcp.disabled_count + ' disabled' : ''),
2422
+ what: 'Servers from mcp_servers in config.yaml. With tool search on (the Hermes default), their tools are listed briefly and full schemas load on demand.',
2423
+ top: [], issues: [], related: [] },
2424
+ { key: 'core_system', name: 'Core System', tokens: c.core_system ? c.core_system.tokens : 0,
2425
+ sub: 'Not exposed for measurement',
2426
+ what: "Hermes's built-in instructions and tools. Hermes does not expose their size, so it is not counted here.",
2427
+ top: [], issues: [], related: [] }
2428
+ ];
2429
+ }
2430
+
2392
2431
  function getComponentDetails(data) {
2393
2432
  var c = data.snapshot.components;
2394
2433
  var cd = data.snapshot.component_details || {};
2395
2434
  var isCodex = data.runtime === 'codex';
2435
+ if (data.runtime === 'hermes') return hermesComponentDetails(c);
2396
2436
 
2397
2437
  var ct = 0;
2398
2438
  for (var k in c) {
@@ -2504,6 +2544,8 @@ function getComponentDetails(data) {
2504
2544
  sub: 'Fixed overhead, not optimizable',
2505
2545
  what: isCodex
2506
2546
  ? "Codex's built-in instructions and tool definitions. This is fixed by the runtime and cannot be reduced by project configuration."
2547
+ : data.runtime && data.runtime !== 'claude'
2548
+ ? (data.runtime_label || 'The runtime') + "'s built-in instructions and tool definitions. Fixed by the runtime; not reducible through configuration."
2507
2549
  : "Claude Code's built-in system prompt, tool definitions, safety instructions, and MCP protocol overhead. This is fixed by Anthropic and cannot be reduced by user configuration changes.",
2508
2550
  top: [], issues: [], related: []
2509
2551
  }
@@ -3012,6 +3054,7 @@ var DB = (function() {
3012
3054
  // Generate bar chart from components
3013
3055
  var c = data.snapshot.components;
3014
3056
  var isCodexOverview = data.runtime === 'codex';
3057
+ var isHermesOverview = data.runtime === 'hermes';
3015
3058
  var vals = [];
3016
3059
  var ct = 0; for (var k in c) {
3017
3060
  if (!c[k] || !c[k].tokens) continue;
@@ -3042,6 +3085,13 @@ var DB = (function() {
3042
3085
  barLabels.push('MCP Tools');
3043
3086
  barLabels.push('Core System');
3044
3087
  var memoryExists = c.memory_md && c.memory_md.exists !== false;
3088
+ if (isHermesOverview) {
3089
+ // Hermes: SOUL.md, memory snapshot, skills index, MCP servers, core.
3090
+ var hc = hermesComponentDetails(c);
3091
+ vals = hc.map(function(x) { return x.tokens || 0; });
3092
+ barLabels = hc.map(function(x) { return x.name; });
3093
+ memoryExists = !!(c.hermes_memory && c.hermes_memory.exists);
3094
+ }
3045
3095
  var barsHtml = vals.map(function(v, i) {
3046
3096
  var w = logBar(v);
3047
3097
  var fixedClass = i === vals.length - 1 ? ' fixed' : '';
@@ -3057,7 +3107,7 @@ var DB = (function() {
3057
3107
  document.getElementById('sat-desc').textContent =
3058
3108
  isCodexOverview
3059
3109
  ? 'Bars show % of the logged Codex context window each component uses. Core System is fixed by Codex. AGENTS.md, memories, skills/plugins, MCP, and hooks are yours to tune.'
3060
- : 'Bars show % of context window each component uses. Core System is fixed by Claude Code. Everything else is yours to trim.';
3110
+ : 'Bars show % of context window each component uses. Core System is fixed by ' + (data.runtime_label || 'Claude Code') + '. Everything else is yours to trim.';
3061
3111
  var caveatEl = document.getElementById('sat-caveat');
3062
3112
  if (!caveatEl) {
3063
3113
  caveatEl = document.createElement('div');
@@ -4195,11 +4245,19 @@ var DB = (function() {
4195
4245
  : ((isFinite(Number(rw.extra_work_pct)) && Number(rw.extra_work_pct) > 0)
4196
4246
  ? '<div class="metric-large" style="text-wrap:balance;text-shadow:none;"><em style="font-style:normal;color:var(--c-accent-cyan);">&asymp;' + rw.extra_work_pct + '%</em> more work per token</div>'
4197
4247
  : '<div class="metric-large" style="text-wrap:balance;text-shadow:none;">' + (usdHeadline || '<em style="font-style:normal;color:var(--c-accent-cyan);">more work</em>') + '</div>');
4248
+ // Visible: one short plain line. The technical explanation of how each
4249
+ // figure is built goes to the fold at the bottom of the card.
4198
4250
  var rwEfficiencyDetail = rwHasCostEfficiency
4199
- ? 'A comparable session fell from <strong>' + rwMoney(rwBeforeCost) + '</strong> to <strong>' + rwMoney(rwAfterCost) + '</strong>' + (rwCostCutDisplay !== null ? ' &middot; ~' + rwCostCutDisplay + '% cheaper/session' : '') + '. This cost-efficiency lens combines lighter context, the cache re-read cascade, and model routing.'
4200
- : 'lighter context &times;' + rw.context_multiplier + ' &middot; lighter models &times;' + rw.routing_multiplier + '. A per-token throughput multiplier, shown separately from the window headroom and dollar figures below.';
4251
+ ? 'A comparable session fell from <strong>' + rwMoney(rwBeforeCost) + '</strong> to <strong>' + rwMoney(rwAfterCost) + '</strong>' + (rwCostCutDisplay !== null ? ' (about ' + rwCostCutDisplay + '% cheaper)' : '') + '.'
4252
+ : 'Lighter context (&times;' + rw.context_multiplier + ') and lighter models (&times;' + rw.routing_multiplier + ') let each token do more.';
4253
+ var rwEfficiencyMethod = rwHasCostEfficiency
4254
+ ? 'This cost-efficiency lens combines lighter context, the cache re-read cascade, and model routing.'
4255
+ : 'Lighter context &times;' + rw.context_multiplier + ' and lighter models &times;' + rw.routing_multiplier + ' give a per-token throughput multiplier, shown separately from the window headroom and dollar figures.';
4201
4256
  var rwTokenFloorDetail = (rwTokenFloorPct !== null)
4202
- ? '<div style="margin-top:var(--s-2);font-size:15px;color:var(--c-text-dim);line-height:1.5;text-wrap:pretty;">Separate measured token floor: <strong>' + fn(rwSavedTokens) + '</strong> never sent on <strong>' + fn(rwSpentTokens) + '</strong> <code>/stats</code>-compatible spent &middot; &asymp;' + rwTokenFloorPct + '% of the would-be token load.</div>'
4257
+ ? '<div class="plain-line">About <strong>' + fn(rwSavedTokens) + '</strong> tokens never had to be sent, roughly ' + rwTokenFloorPct + '% of what would have been.</div>'
4258
+ : '';
4259
+ var rwTokenFloorMethod = (rwTokenFloorPct !== null)
4260
+ ? 'Separate measured token floor: ' + fn(rwSavedTokens) + ' never sent on ' + fn(rwSpentTokens) + ' <code>/stats</code>-compatible spent, &asymp;' + rwTokenFloorPct + '% of the would-be token load.'
4203
4261
  : '';
4204
4262
  // Tier chip reflects the USD spine's measured-vs-estimated boundary:
4205
4263
  // context $ is metered, routing $ is an estimated counterfactual.
@@ -4221,13 +4279,13 @@ var DB = (function() {
4221
4279
  // Cost efficiency is the transformation lens; the token floor remains a
4222
4280
  // separate measured line so neither percentage is forced to equal the other.
4223
4281
  rwEfficiencyHeadline +
4224
- '<div style="margin-top:var(--s-2);font-size:15px;color:var(--c-text-dim);line-height:1.5;text-wrap:pretty;">' + rwEfficiencyDetail + '</div>' +
4282
+ '<div class="plain-line">' + rwEfficiencyDetail + '</div>' +
4225
4283
  rwTokenFloorDetail +
4226
4284
  // Stands alone. An earlier revision opened with "before you hit your usage
4227
4285
  // limits.", a continuation of the headline that reads as a truncated
4228
4286
  // fragment once it wraps to its own line, and the limit panels below
4229
4287
  // already establish which limits are meant.
4230
- '<p style="margin:0 0 var(--s-4);color:var(--c-text-dim);font-size:17px;line-height:1.6;text-wrap:pretty;">Token Optimizer keeps junk out of context and runs routine turns on lighter models, so more of your plan goes to real work instead of waste.</p>' +
4288
+ '<p style="margin:var(--s-3) 0 var(--s-4);color:var(--c-text-main);font-size:17px;line-height:1.6;text-wrap:pretty;">Token Optimizer keeps junk out of context and runs routine turns on lighter models, so more of your plan goes to real work instead of waste.</p>' +
4231
4289
  // Per-window bars when the meter is fresh enough; otherwise a note so the
4232
4290
  // card degrades instead of vanishing (the multiplier + savings above still
4233
4291
  // stand without the live meter).
@@ -4268,7 +4326,7 @@ var DB = (function() {
4268
4326
  // report. Keep the button (it rebuilds savings/the rest), just stop
4269
4327
  // implying it refreshes the window.
4270
4328
  var staleNote = stale
4271
- ? ' The window figure updates only while Claude Code is actively running; Regenerate rebuilds the page but will not refresh a stale reading.'
4329
+ ? ' It updates only while ' + esc(data.runtime_label || 'Claude Code') + ' is running; Regenerate will not refresh it.'
4272
4330
  : '';
4273
4331
  return '<div style="margin-top:var(--s-3);font-size:13px;color:' + col + ';">' +
4274
4332
  (stale ? '⚠ ' : '') + 'Window reading as of ' + esc(whenStr) + ' (' + ageStr + ').' + staleNote +
@@ -4284,16 +4342,20 @@ var DB = (function() {
4284
4342
  // block makes "clicked but nothing happened" impossible to miss.
4285
4343
  '<div id="to-regen-error" hidden style="margin-top:10px;padding:10px 14px;font-size:15px;font-weight:500;color:var(--c-waste);background:rgba(255,95,95,.08);border:1px solid rgba(255,95,95,.35);border-radius:8px;line-height:1.5;text-wrap:pretty;"></div></div>';
4286
4344
  })() +
4287
- '<div style="margin-top:var(--s-4);padding-top:var(--s-3);border-top:1px solid var(--c-border);font-size:14px;color:var(--c-text-dim);line-height:1.7;text-wrap:pretty;">' +
4288
- // rw.proxy is now the single source of the measured-vs-estimated boundary
4289
- // AND the ledger detail (deduped: this used to repeat the ledger sentence
4290
- // and re-state "usage is measured"). We add only the one fact proxy can't
4291
- // carry -- the throughput-% is its own unit, not a sum of the dollars --
4292
- // because it needs the live JS value.
4293
- esc(rw.proxy) + ' ' +
4294
- (rwHasCostEfficiency
4295
- ? 'The &asymp;' + rwEfficiencyMult.toFixed(1) + '&times; figure is the before/after per-session cost ratio, not a sum of the token floor or per-window dollar figures.'
4296
- : 'The &asymp;' + rw.extra_work_pct + '% is a separate per-token throughput multiplier, not a sum of the per-window dollar figures.') +
4345
+ '<div style="margin-top:var(--s-4);padding-top:var(--s-3);border-top:1px solid var(--c-border);font-size:15px;color:var(--c-text-main);line-height:1.6;text-wrap:pretty;">' +
4346
+ 'Your window usage is measured. The savings comparison is an estimate.' +
4347
+ // Technical method lives in a fold. rw.proxy is the single source of the
4348
+ // measured-vs-estimated boundary AND the ledger detail; we add only the
4349
+ // one fact proxy can't carry -- the headline figure is its own unit, not
4350
+ // a sum of the dollars -- because it needs the live JS value.
4351
+ '<details class="fold"><summary>How these numbers are measured</summary><div class="fold__body">' +
4352
+ '<p>' + esc(rw.proxy) + '</p>' +
4353
+ '<p>' + rwEfficiencyMethod + '</p>' +
4354
+ (rwTokenFloorMethod ? '<p>' + rwTokenFloorMethod + '</p>' : '') +
4355
+ '<p>' + (rwHasCostEfficiency
4356
+ ? 'The &asymp;' + rwEfficiencyMult.toFixed(1) + '&times; figure is the before/after per-session cost ratio, not a sum of the token floor or per-window dollar figures.'
4357
+ : 'The &asymp;' + rw.extra_work_pct + '% is a separate per-token throughput multiplier, not a sum of the per-window dollar figures.') + '</p>' +
4358
+ '</div></details>' +
4297
4359
  '</div>' +
4298
4360
  '</div>';
4299
4361
  }
@@ -4312,6 +4374,7 @@ var DB = (function() {
4312
4374
  var days = Number(s.period_days) || 30;
4313
4375
  var mr = s.model_routing || {};
4314
4376
  var cd = s.cache_drop || {};
4377
+ var op = s.oneshot_pricing || {};
4315
4378
  var ow = s.output_waste || {};
4316
4379
  var beh = s.behavioral_estimate || {};
4317
4380
  var sd = s.structural_detail || {};
@@ -4349,6 +4412,7 @@ var DB = (function() {
4349
4412
  }
4350
4413
  function fmtTok(n) {
4351
4414
  var v = Number(n) || 0;
4415
+ if (v >= 1e9) return (v / 1e9).toFixed(1) + 'B';
4352
4416
  if (v >= 1e6) return (v / 1e6).toFixed(1) + 'M';
4353
4417
  if (v >= 1e3) return Math.round(v / 1e3) + 'K';
4354
4418
  return String(Math.round(v));
@@ -4361,6 +4425,13 @@ var DB = (function() {
4361
4425
  return '<details class="fold"><summary>' + esc(summary) + '</summary>' +
4362
4426
  '<div class="fold__body">' + bodyHtml + '</div></details>';
4363
4427
  }
4428
+ // "How this is counted" bullets for a fold. Items are ready HTML (esc()'d by the
4429
+ // caller); falsy items are skipped so callers can pass conditionals inline.
4430
+ function countedList(items) {
4431
+ var li = items.filter(Boolean);
4432
+ return li.length ? '<p><strong>How this is counted</strong></p><ul>' +
4433
+ li.map(function(x) { return '<li>' + x + '</li>'; }).join('') + '</ul>' : '';
4434
+ }
4364
4435
 
4365
4436
  // ---- mechanism pillars (structural / runtime / behavioral). Behavioral holds only
4366
4437
  // what you're actually getting (realized routing + estimated loop prevention); cache-drop
@@ -4389,30 +4460,91 @@ var DB = (function() {
4389
4460
  var behavMo = mo(mr.realized_cost_usd) + mo(beh.cost_saved_usd) + mo(ce.cost_saved_usd) + mo(hr.cost_saved_usd) + avoidedSearchMo + mo(rle.cost_saved_usd) + mo(vs.cost_saved_usd);
4390
4461
  // ---- trust tiers: measured / estimated / opportunity. Opportunity NEVER folds into the headline. ----
4391
4462
  // Measured = billable events we metered (runtime compression + realized model routing).
4392
- var measuredMo = mo(s.total_cost_usd) + mo(mr.realized_cost_usd);
4463
+ // Routing joins the measured tier only when its valuation is measured; the
4464
+ // standardized newest-card schedule makes it an estimate (Other estimates).
4465
+ var routingEstimated = mr.evidence === 'estimated';
4466
+ var measuredMo = mo(s.total_cost_usd) + (routingEstimated ? 0 : mo(mr.realized_cost_usd));
4393
4467
  // Estimated = genuine TO-realized counterfactuals grounded in YOUR behavior; each carries a sample size.
4394
4468
  // (Pillars + estimated reconcile to gettingMo: mcp_cap folds into runtime.)
4395
4469
  var estItems = [
4396
- { label: 'loops prevented', amt: mo(beh.cost_saved_usd), n: Number(beh.loop_events) || 0, unit: 'events' },
4397
- { label: 'sub-agent runtime', amt: mo(unc.cost_saved_usd), n: Number(unc.subagent_dispatches) || 0, unit: 'dispatches' },
4398
- { label: 'MCP output cap', amt: mo(mce.cost_saved_usd), n: Number(mce.events) || 0, unit: 'capped results' },
4399
- { label: 'avoided rework (heeded nudges)', amt: mo(ce.cost_saved_usd), n: Number(ce.heeded_sessions) || 0, unit: 'heeded', conf: ce.confidence },
4400
- { label: 'continuity handover', amt: mo(hr.cost_saved_usd), n: Number(hr.restored_sessions) || 0, unit: 'restored', conf: hr.confidence },
4401
- { label: 'avoided search (hints)', amt: avoidedSearchMo, n: avoidedSearchN, unit: avoidedSearchUnit, conf: hfHasData ? 'observed' : rs.confidence },
4402
- { label: 'lean resumes (cold reload avoided)', amt: mo(rle.cost_saved_usd), n: Number(rle.events) || 0, unit: 'resumes' },
4403
- { label: 'concise output nudges', amt: mo(vs.cost_saved_usd), n: Number(vs.events) || 0, unit: 'nudges' }
4470
+ { key: 'routing_estimated', label: 'model routing', amt: routingEstimated ? mo(mr.realized_cost_usd) : 0, n: (mr.baseline_reference_priced || []).length, unit: 'model families on one newest-card price list' },
4471
+ { key: 'behavioral_estimate', label: 'loops prevented', amt: mo(beh.cost_saved_usd), n: Number(beh.loop_events) || 0, unit: 'events' },
4472
+ { key: 'uncaptured_runtime', label: 'sub-agent runtime', amt: mo(unc.cost_saved_usd), n: Number(unc.subagent_dispatches) || 0, unit: 'dispatches' },
4473
+ { key: 'mcp_cap_estimated', label: 'MCP output cap', amt: mo(mce.cost_saved_usd), n: Number(mce.events) || 0, unit: 'capped results' },
4474
+ { key: 'contamination_exit', label: 'avoided rework (heeded nudges)', amt: mo(ce.cost_saved_usd), n: Number(ce.heeded_sessions) || 0, unit: 'heeded', conf: ce.confidence },
4475
+ { key: 'handover_rerun', label: 'continuity handover', amt: mo(hr.cost_saved_usd), n: Number(hr.restored_sessions) || 0, unit: 'restored', conf: hr.confidence },
4476
+ { key: 'avoided_search', label: 'avoided search (hints)', amt: avoidedSearchMo, n: avoidedSearchN, unit: avoidedSearchUnit, conf: hfHasData ? 'observed' : rs.confidence },
4477
+ { key: 'resume_lean_estimated', label: 'lean resumes (cold reload avoided)', amt: mo(rle.cost_saved_usd), n: Number(rle.events) || 0, unit: 'resumes' },
4478
+ { key: 'verbosity_steer', label: 'concise output nudges', amt: mo(vs.cost_saved_usd), n: Number(vs.events) || 0, unit: 'nudges' }
4404
4479
  ].filter(function(it){ return it.amt > 0 || it.conf; });
4405
4480
  var estimatedMo = estItems.reduce(function(a, b){ return a + b.amt; }, 0);
4406
4481
  // What you're getting = measured + estimated (both real value; estimated shown split-out, never hidden).
4407
4482
  var gettingMo = measuredMo + rereadMo + estimatedMo;
4483
+ // New payloads share the CLI's complete action total. Older saved dashboards
4484
+ // retain the component calculation above until their next regeneration.
4485
+ var actionSavings = s.action_savings;
4486
+ if (actionSavings) {
4487
+ measuredMo = mo(actionSavings.logged_usd) + mo(actionSavings.routing_measured_usd);
4488
+ rereadMo = mo(actionSavings.reread_usd);
4489
+ estimatedMo = mo(actionSavings.estimated_usd) + mo(actionSavings.routing_estimated_usd);
4490
+ gettingMo = mo(actionSavings.total_usd);
4491
+ }
4492
+ // Whole-cent display values from the payload: the parts shown on the card
4493
+ // add up to the total shown, with the exact amounts kept in the payload.
4494
+ var exactCents = null;
4495
+ var dispCents = actionSavings && actionSavings.display;
4496
+ if (dispCents && dispCents.components_cents && dispCents.estimates_cents) {
4497
+ var dc = dispCents.components_cents, de = dispCents.estimates_cents;
4498
+ var estSumCents = Object.keys(de).reduce(function(a, k) { return a + de[k]; }, 0);
4499
+ exactCents = {
4500
+ total: dispCents.total_cents,
4501
+ logged: dc.logged + dc.routing_measured,
4502
+ reread: dc.reread,
4503
+ other: estSumCents + dc.routing_estimated,
4504
+ est: de,
4505
+ routingEstimated: dc.routing_estimated,
4506
+ avoidedKey: actionSavings.avoided_search_source
4507
+ };
4508
+ }
4509
+ function moneyCents(c) {
4510
+ return (c < 0 ? '-$' : '$') + (Math.abs(c) / 100).toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2});
4511
+ }
4512
+ function estCents(item) {
4513
+ var key = item.key === 'avoided_search' ? exactCents.avoidedKey : item.key;
4514
+ return key === 'routing_estimated' ? exactCents.routingEstimated : exactCents.est[key];
4515
+ }
4408
4516
  // Opportunity = realizable if you act; never realized, never summed into "getting".
4409
4517
  // output-waste is $ here; cache-drop is shown separately in TOKENS (re-written prefix) —
4410
4518
  // its $ is Anthropic-specific (OpenAI/OpenCode cache writes are free), but the token count
4411
4519
  // is a provider-neutral fact, matching Claude Code's own token-denominated display.
4412
4520
  var recl = s.stale_reads_reclaimable || {};
4413
4521
  var cdTokensMo = Math.round((Number(cd.est_drops) || 0) * (Number(cd.prefix_tokens) || 0) / Math.max(days, 1) * 30);
4414
- var addnlMo = mo(sp.cost_saved_usd) + mo(mr.potential_cost_usd);
4415
- var opportunityMo = addnlMo + mo(recl.cost_usd) + mo(ow.cost_saved_usd);
4522
+ // The big opportunity number holds only evidence-backed items (unused skills,
4523
+ // stale re-reads, full-file Writes). Routing rests on an assumed share of your
4524
+ // Opus work, so it gets its own line below the number and is never added in.
4525
+ var opportunityMo = mo(sp.cost_saved_usd) + mo(recl.cost_usd) + mo(ow.cost_saved_usd);
4526
+ // Round once: each item gets its floor in cents and the missing cents go to
4527
+ // the largest remainders, so the items shown add up to the number shown.
4528
+ var oppCents = (function(values) {
4529
+ // Snap to a millionth of a cent first so float noise from the monthly
4530
+ // scaling (32.625 becoming 32.62499...) rounds the same way as the text report.
4531
+ var exact = values.map(function(v) { var n = Math.round(Number(v) * 1e8) / 1e6; return isFinite(n) ? n : 0; });
4532
+ var floors = exact.map(function(x) { return Math.floor(x); });
4533
+ var total = Math.round(Math.round(exact.reduce(function(a, b) { return a + b; }, 0) * 1e6) / 1e6);
4534
+ var left = total - floors.reduce(function(a, b) { return a + b; }, 0);
4535
+ exact.map(function(x, i) { return i; })
4536
+ .sort(function(a, b) { return (exact[b] - floors[b]) - (exact[a] - floors[a]) || a - b; })
4537
+ .slice(0, Math.max(0, Math.min(left, exact.length)))
4538
+ .forEach(function(i) { floors[i] += 1; });
4539
+ return { structural: floors[0], output: floors[1], reclaimable: floors[2], total: total };
4540
+ })([mo(sp.cost_saved_usd), mo(ow.cost_saved_usd), mo(recl.cost_usd)]);
4541
+ var routingPotentialMo = mo(mr.potential_cost_usd);
4542
+ var cdCostMo = mo(cd.cost_saved_usd);
4543
+ var routingTokensMo = Number(mr.potential_tokens_monthly) > 0
4544
+ ? Number(mr.potential_tokens_monthly)
4545
+ : mo(mr.potential_tokens);
4546
+ var routingFracPct = Math.round((mr.routable_fraction == null ? 0.2 : Number(mr.routable_fraction)) * 10000) / 100;
4547
+ var routingTarget = mr.target_model || "Sonnet";
4416
4548
  var unusedSkills = Number(sp.unused_skills) || 0;
4417
4549
  var currOpus = Math.round((Number(mr.current_opus_share) || 0) * 100);
4418
4550
  var ts = data.generated_at ? new Date(data.generated_at).toLocaleString() : 'unknown';
@@ -4445,11 +4577,9 @@ var DB = (function() {
4445
4577
  '<p class="lede">Your recent workload compared with your earlier way of working, at the same token prices.</p>' +
4446
4578
  '<div class="savings-split"><span>Now <strong>' + money(nowCost) + '</strong></span>' +
4447
4579
  '<span>Earlier workflow <strong>' + money(oldCost) + '</strong></span></div>' +
4448
- '<div class="note">Overlaps with the action savings below. Do not add the two totals.</div>' +
4449
- (ba.savings_capped && ba.savings_cap_note
4450
- ? '<div class="note" style="margin-top:var(--s-2);">' + esc(ba.savings_cap_note) + '</div>'
4451
- : '') +
4580
+ '<div class="plain-line">Overlaps with the action savings below. Do not add the two totals.</div>' +
4452
4581
  fold('How this is estimated',
4582
+ countedList([ba.savings_capped && ba.savings_cap_note ? esc(ba.savings_cap_note) : '']) +
4453
4583
  (wp
4454
4584
  ? '<p>Baseline: <strong>' + esc(wp.anchor_month) + '</strong>. We compare cost per ' + wpUnit +
4455
4585
  ' at constant prices, then apply the difference to the <strong>' +
@@ -4490,6 +4620,34 @@ var DB = (function() {
4490
4620
  '<div class="label" style="margin-bottom:var(--s-2);">At or above your baseline this period</div>' +
4491
4621
  '<div class="lede">Your recent sessions cost about what your frozen baseline would have — est. <strong>' + money(ba.actual_monthly_usd) + '/mo</strong> now vs <strong>' + money(ba.counterfactual_monthly_usd) + '/mo</strong> the old way. There is no net saving to headline this period, so we are not showing one. The figure below is what Token Optimizer counted directly, action by action.</div>' +
4492
4622
  '</div>';
4623
+ } else if (ba.reason === 'flat') {
4624
+ // Both work-unit methods sit within a few percent of spend: no
4625
+ // measurable whole-workload change, so no headline and no scary number.
4626
+ html += '<div class="card wide" style="padding:var(--s-5) var(--s-4);margin-bottom:var(--s-3);">' +
4627
+ '<div class="label" style="margin-bottom:var(--s-2);">No measurable change in cost per unit of work</div>' +
4628
+ '<div class="plain-line">Your recent work costs about the same per request as before install (' + money(ba.actual_monthly_usd) + '/mo now vs ' + money(ba.counterfactual_monthly_usd) + '/mo the old way). The savings below are counted action by action.</div>' +
4629
+ '</div>';
4630
+ } else if (ba.reason === 'methods_disagree') {
4631
+ // The two independent work-unit methods (per-API-call and per-message)
4632
+ // landed more than 10% apart, so neither figure is trustworthy enough to
4633
+ // headline. Show both, headline nothing; the metered floor card below
4634
+ // still reports realized savings. Same neutral-card shape as
4635
+ // net_negative, with signed money for the cross-check figure.
4636
+ var swp = ba.session_weight_pool || {};
4637
+ var swpCross = swp.crosscheck || {};
4638
+ var mainUsd = Number(swp.transformation_usd) || 0;
4639
+ var crossUsd = Number(swpCross.transformation_usd) || 0;
4640
+ var mainUnit = swp.work_unit === 'message' ? 'per-message' : 'per-API-call';
4641
+ var crossUnit = swpCross.unit === 'api_call' ? 'per-API-call' : 'per-message';
4642
+ var signedMoney = function (n) {
4643
+ var v = Number(n) || 0;
4644
+ return (v < 0 ? '-' : '') + money(Math.abs(v));
4645
+ };
4646
+ html += '<div class="card wide" style="padding:var(--s-5) var(--s-4);margin-bottom:var(--s-3);">' +
4647
+ '<div class="label" style="margin-bottom:var(--s-2);">Two estimates disagree this period</div>' +
4648
+ '<div class="lede">The ' + mainUnit + ' estimate is <strong>' + signedMoney(mainUsd) + '/mo</strong> and the ' + crossUnit +
4649
+ ' estimate is <strong>' + signedMoney(crossUsd) + '/mo</strong>. They are too far apart to headline either one. The figure below is what Token Optimizer counted directly, action by action.</div>' +
4650
+ '</div>';
4493
4651
  }
4494
4652
 
4495
4653
  // ---- Tokens Saved card: the full card (hero + spent-vs-saved + model-
@@ -4505,22 +4663,74 @@ var DB = (function() {
4505
4663
  html += '<div style="display:flex;gap:var(--s-3);flex-wrap:wrap;margin-bottom:var(--s-3);">';
4506
4664
  var periodLabel = runRate ? 'last ' + days + ' days' : trackedDays + ' days tracked';
4507
4665
  var heroAmt = gettingMo;
4666
+ // One plain visible line only when some of the total could not be priced; every
4667
+ // other counting note lives in the card's "Breakdown and method" fold.
4668
+ var actionPricingIncomplete = !!(cp.reread_pricing_note ||
4669
+ (actionSavings && actionSavings.reread_prices_available === false) || cp.reread_prices_available === false ||
4670
+ Number(s.compression_unpriced_tokens) > 0 ||
4671
+ (s.reprice_detail && Number(s.reprice_detail.unpriced_tokens) > 0));
4508
4672
  html += '<div class="card savings-actions" style="flex:2;min-width:min(100%,320px);padding:var(--s-4);">' +
4509
4673
  '<div class="label">Action savings &middot; ' + periodLabel + '</div>' +
4510
- '<div class="savings-amount">' + money(periodValue(heroAmt)) + '<span class="savings-unit"> logged + estimated</span></div>' +
4511
- '<div class="savings-split"><span>Logged actions <strong>' + money(periodValue(measuredMo)) + '</strong></span>' +
4512
- '<span>Repeat reads avoided <strong>~' + money(periodValue(rereadMo)) + '</strong></span>' +
4513
- '<span>Other estimates <strong>~' + money(periodValue(estimatedMo)) + '</strong></span></div>' +
4514
- '<p class="note">Includes the later benefit of context removed during this period. Initial removals are counted once.</p>' +
4515
- (!cp.available ? '<p class="note">Repeat-read coverage is unavailable here; logged actions are still included.</p>' : '') +
4674
+ '<div class="savings-amount">' + (exactCents ? moneyCents(exactCents.total) : money(periodValue(heroAmt))) + '<span class="savings-unit"> logged + estimated</span></div>' +
4675
+ '<div class="savings-split"><span>Logged actions <strong>' + (exactCents ? moneyCents(exactCents.logged) : money(periodValue(measuredMo))) + '</strong></span>' +
4676
+ '<span>Repeat reads avoided <strong>' +
4677
+ (actionSavings && actionSavings.reread_available === false ? 'Unavailable' :
4678
+ ((actionSavings && actionSavings.reread_prices_available === false) || cp.reread_prices_available === false ?
4679
+ 'Unpriced' : '~' + (exactCents ? moneyCents(exactCents.reread) : money(periodValue(rereadMo))))) + '</strong></span>' +
4680
+ '<span>Other estimates <strong>~' + (exactCents ? moneyCents(exactCents.other) : money(periodValue(estimatedMo))) + '</strong></span></div>' +
4681
+ (actionPricingIncomplete
4682
+ ? '<p class="plain-line">Some older history has no exact price, so this is a priced subtotal.</p>'
4683
+ : (!cp.available ? '<p class="plain-line">Repeat reads are not available here. Logged actions are still counted.</p>' : '')) +
4684
+ (mr.evidence === 'pending'
4685
+ ? '<p class="plain-line routing-pending">Model routing: re-measuring (' + Number(mr.pending_sessions || 0).toLocaleString() +
4686
+ ' session' + (Number(mr.pending_sessions) === 1 ? '' : 's') + ' left). It is added to this total when the re-measurement finishes.</p>' : '') +
4516
4687
  fold('Breakdown and method',
4517
- '<p>Logged actions include output trims, context reductions, setup changes and routing savings. ' +
4688
+ countedList([
4689
+ 'Includes the later benefit of context removed during this period. Initial removals are counted once.',
4690
+ cp.reread_pricing_note ? esc(cp.reread_pricing_note) : '',
4691
+ actionSavings && actionSavings.total_clamped ? 'Signed adjustments give a net total of ' +
4692
+ money(actionSavings.net_total_usd) + '; the headline has a $0 floor.' : '',
4693
+ Number(s.compression_unpriced_tokens) > 0 ?
4694
+ Math.round(Number(s.compression_unpriced_tokens)).toLocaleString() +
4695
+ ' compression tokens are counted without a dollar value because their model rate is unavailable' +
4696
+ ((Number(s.compression_unpriced_credit_tokens) > 0 || Number(s.compression_unpriced_debit_tokens) > 0)
4697
+ ? ' (' + Math.round(Number(s.compression_unpriced_credit_tokens) || 0).toLocaleString() + ' credits, ' +
4698
+ Math.round(Number(s.compression_unpriced_debit_tokens) || 0).toLocaleString() + ' debits)' : '') + '.' : '',
4699
+ s.reprice_detail && Number(s.reprice_detail.unpriced_tokens) > 0 ?
4700
+ Math.round(Number(s.reprice_detail.unpriced_tokens)).toLocaleString() +
4701
+ ' logged tokens ran on models with no known rate; their dollar value is not included.' : '',
4702
+ op.removal_events > 0 ? 'Initial removals above are priced at the input rate, a minimum.' +
4703
+ (Number(op.class_premium_usd) >= 0.005
4704
+ ? ' The next call billed new context at a cache-write rate for ' +
4705
+ Math.round(Number(op.class_events) || 0).toLocaleString() + ' removals: about ' +
4706
+ money(Number(op.class_premium_usd)) + ' more, not in the total.' : '') : '',
4707
+ !cp.available ? 'Repeat-read coverage is unavailable here; logged actions are still included.' : ''
4708
+ ]) +
4709
+ '<p>Logged actions include output trims, context reductions, setup changes and, when your earlier model mix is priced from your own usage, routing savings. ' +
4518
4710
  'Prices may be allocated from each session’s recorded model mix.</p>' +
4519
4711
  '<p>Repeat reads use recorded later turns up to each session’s next compaction. ' +
4520
4712
  'This assumes the removed context would otherwise have stayed until that compaction. ' +
4521
- 'The value belongs to the date of removal, not the date of each later read. Missing transcripts receive no repeat-read estimate.</p>' +
4522
- '<p>Stored repeat-read values use the rates recorded when they were computed.' +
4713
+ 'The value belongs to the date of removal, not the date of each later read. Missing transcripts add no new repeat-read estimate; previously verified history is retained.</p>' +
4714
+ '<p>Stored repeat-read values include only verified per-turn rates. Unpriced contributions retain their token counts.' +
4523
4715
  (cp.computed_at ? ' Last counted: ' + esc(new Date(cp.computed_at).toLocaleString()) + '.' : '') + '</p>' +
4716
+ (Number(mr.premium_share) > 0
4717
+ ? '<p>Routing compares your current model mix with your earlier mix. Premium models you chose (' +
4718
+ esc((mr.premium_models || []).map(function(f) { return f.charAt(0).toUpperCase() + f.slice(1); }).join(', ')) + ', ' +
4719
+ Math.round(Number(mr.premium_share) * 100) + '% of tokens, about ' + money(mo(mr.premium_cost_usd)) + per +
4720
+ ' at API rates) are left out, so they do not offset the shift toward lighter models.</p>' : '') +
4721
+ ((mr.baseline_reference_priced || []).length
4722
+ ? '<p>Routing compares your earlier and current mix on one price list, the newest card of each family (' +
4723
+ esc(mr.baseline_reference_priced.map(function(f) { return f.charAt(0).toUpperCase() + f.slice(1); }).join(', ')) +
4724
+ '), because your earlier mix records no model generations. The figure is listed under estimates.</p>' : '') +
4725
+ (Math.abs(mo(mr.generation_price_delta_usd)) >= 0.01
4726
+ ? '<p>At the exact cards you ran, the same work cost about ' + money(Math.abs(mo(mr.generation_price_delta_usd))) +
4727
+ (Number(mr.generation_price_delta_usd) > 0 ? ' more' : ' less') +
4728
+ ' than on that price list. That gap is model generation pricing, not routing.</p>' : '') +
4729
+ ((Number(mr.unpriced_tokens) > 0 || Number(mr.free_tokens) > 0)
4730
+ ? '<p>Models without a known price (' +
4731
+ esc((mr.unpriced_models || []).concat(mr.free_models || []).slice(0, 3).join(', ')) + ', ' +
4732
+ (Number(mr.unpriced_tokens || 0) + Number(mr.free_tokens || 0)).toLocaleString() +
4733
+ ' tokens) are left out of the routing comparison, not counted as free.</p>' : '') +
4524
4734
  ((s.reprice_detail && Number(s.reprice_detail.delta_usd) !== 0)
4525
4735
  ? '<p>Model-rate allocation: ' + money(Number(s.reprice_detail.delta_usd)) +
4526
4736
  ' across ' + Number(s.reprice_detail.repriced_tokens || 0).toLocaleString() +
@@ -4529,21 +4739,60 @@ var DB = (function() {
4529
4739
  '<span>Runtime <strong>' + money(periodValue(runtimeMo + rereadMo)) + '</strong></span>' +
4530
4740
  '<span>Habits <strong>' + money(periodValue(behavMo)) + '</strong></span></div>' +
4531
4741
  (estItems.length ? '<p>Other estimates:</p>' + estItems.map(function(it) {
4532
- return '<p>' + esc(it.label) + ': <strong>' + money(periodValue(it.amt)) + '</strong> (' +
4742
+ var shown = exactCents && estCents(it) != null ? moneyCents(estCents(it)) : money(periodValue(it.amt));
4743
+ return '<p>' + esc(it.label) + ': <strong>' + shown + '</strong> (' +
4533
4744
  it.n.toLocaleString() + ' ' + esc(it.unit) + (it.conf ? ', ' + esc(String(it.conf)) : '') + ').</p>';
4534
4745
  }).join('') : '') +
4535
4746
  '<p>' + billingCaption + '</p>') +
4536
4747
  '</div>';
4537
4748
  var cc = s.counted_cumulative || {};
4538
- if (Number(cc.total_usd) > 0) {
4749
+ var sia = (si && si.all_in) || null;
4750
+ if (sia && Number(sia.total_usd) > 0) {
4751
+ var siaParts = sia.components_usd || {};
4752
+ var siaRouting = (Number(siaParts.routing_measured) || 0) + (Number(siaParts.routing_estimated) || 0);
4753
+ var siaPending = sia.routing_pending || sia.remeasuring;
4754
+ var siaLeft = Math.max(Number(sia.routing_pending_sessions) || 0, Number(sia.remeasuring_sessions) || 0);
4755
+ html += '<div class="card savings-history" style="flex:1;min-width:min(100%,260px);padding:var(--s-4);">' +
4756
+ '<div class="label">Saved since ' + esc(prettyDate(si.install_date)) + '</div>' +
4757
+ '<div class="savings-amount">' + money(sia.total_usd) +
4758
+ (siaPending ? ' <span class="remeasuring-tag" style="font-size:0.45em;color:var(--c-text-dim);">so far</span>' : '') + '</div>' +
4759
+ (siaPending ? '<p class="plain-line remeasuring">Re-measuring older history (' + siaLeft.toLocaleString() +
4760
+ ' session' + (siaLeft === 1 ? '' : 's') + ' left). This total will grow when they finish.</p>' : '') +
4761
+ '<p class="plain-line">Same four parts as the monthly total, added up since install.</p>' +
4762
+ fold('Breakdown and history',
4763
+ '<p>Model routing: <strong>' + money(siaRouting) + '</strong> (estimated).</p>' +
4764
+ '<p>Repeat reads avoided: <strong>' + money(siaParts.reread) + '</strong> (modeled).</p>' +
4765
+ '<p>Logged actions: <strong>' + money(siaParts.logged) + '</strong>.</p>' +
4766
+ '<p>Other estimates: <strong>' + money(sia.estimated_usd) + '</strong>.</p>' +
4767
+ ((Number(cc.total_usd) > 0 || cc.available) ?
4768
+ '<p>Context trimming on its own (initial removals + repeat reads): ' +
4769
+ (cc.prices_available === false ? 'Unpriced' : money(Math.max(0, Number(cc.total_usd) || 0))) + '.</p>' : '') +
4770
+ countedList([
4771
+ cc.pricing_note ? esc(cc.pricing_note) : '',
4772
+ cc.media_note ? esc(cc.media_note) : ''
4773
+ ]) +
4774
+ '<p>Tracked over ' + Number(si.days || 0).toLocaleString() + ' days. Historical entries remain after their source transcripts rotate.</p>' +
4775
+ '<p>' + billingCaption + '</p>') +
4776
+ '</div>';
4777
+ } else if (Number(cc.total_usd) > 0 || (cc.available && Number(cc.events) > 0)) {
4539
4778
  html += '<div class="card savings-history" style="flex:1;min-width:min(100%,260px);padding:var(--s-4);">' +
4540
4779
  '<div class="label">Context savings &middot; all time</div>' +
4541
- '<div class="savings-amount">' + money(cc.total_usd) + '</div>' +
4542
- '<p class="note">Initial removals + modeled repeat reads.</p>' +
4543
- (cp.available ? '<p class="note"><strong>' + money(cp.total_usd) + '</strong> from removals in the last ' + days + ' days.</p>' : '') +
4544
- '<p class="note">Overlaps with action savings. Excludes routing, setup and other estimates.</p>' +
4780
+ '<div class="savings-amount">' + (cc.prices_available === false ? 'Unpriced' : money(Math.max(0, Number(cc.total_usd) || 0))) +
4781
+ (cc.remeasuring ? ' <span class="remeasuring-tag" style="font-size:0.45em;color:var(--c-text-dim);">so far</span>' : '') + '</div>' +
4782
+ (cc.remeasuring ? '<p class="plain-line remeasuring">Re-measuring (' + Number(cc.remeasuring_sessions || 0).toLocaleString() +
4783
+ ' session' + (Number(cc.remeasuring_sessions) === 1 ? '' : 's') + ' left). This subtotal is in progress and will change when they finish.</p>' : '') +
4784
+ '<p class="plain-line">' + (cp.available ? '<strong>' + (cp.prices_available === false ? 'Unpriced' : money(cp.total_usd)) + '</strong> from removals in the last ' + days + ' days. ' : '') +
4785
+ 'Overlaps with action savings.</p>' +
4545
4786
  fold('History and coverage',
4546
- '<p>' + money(cc.oneshot_usd) + ' initial removals + ' + money(cc.reread_usd) + ' modeled repeat reads.</p>' +
4787
+ countedList([
4788
+ 'Initial removals + modeled repeat reads.',
4789
+ cc.pricing_note ? esc(cc.pricing_note) : '',
4790
+ cc.media_note ? esc(cc.media_note) : '',
4791
+ Number(cc.total_usd) < 0 ? 'Signed net: ' + money(cc.total_usd) + '. Savings headline is floored at zero.' : '',
4792
+ 'Excludes routing, setup and other estimates.'
4793
+ ]) +
4794
+ '<p>' + (cc.oneshot_prices_available === false ? 'Unpriced' : money(cc.oneshot_usd)) + ' initial removals + ' +
4795
+ (cc.reread_prices_available === false ? 'Unpriced' : money(cc.reread_usd)) + ' modeled repeat reads.</p>' +
4547
4796
  '<p>Stored history since ' + esc(prettyDate(cc.window_start)) + '. ' +
4548
4797
  'Same removal-date method as the period total. Historical entries remain after their source transcripts rotate.</p>' +
4549
4798
  '<p>Repeat reads assume the removed context would otherwise have stayed until the session’s next compaction. ' +
@@ -4564,26 +4813,66 @@ var DB = (function() {
4564
4813
  // ---- SAVE MORE: suggestions, promoted right under the hero ----
4565
4814
  var parts = [];
4566
4815
  if ((Number(sp.cost_saved_usd) || 0) > 0 && unusedSkills > 0) {
4567
- parts.push('Review ' + unusedSkills + ' skill' + (unusedSkills === 1 ? '' : 's') + ' not invoked in this window. Archiving what you no longer need is worth about ' + money(mo(sp.cost_saved_usd)) + per + ', automatically, from then on.');
4816
+ parts.push('Review ' + unusedSkills + ' skill' + (unusedSkills === 1 ? '' : 's') + ' not invoked in this window. Archiving what you no longer need is worth about ' + moneyCents(oppCents.structural) + per + ', automatically, from then on.');
4817
+ }
4818
+ if ((Number(recl.cost_usd) || 0) > 0) {
4819
+ parts.push('Avoid re-reading files that have not changed, or add them to .contextignore. ' + (Number(recl.tokens) || 0).toLocaleString() + ' tokens of stale re-reads across ' + (Number(recl.sessions) || 0).toLocaleString() + ' sessions are worth about ' + moneyCents(oppCents.reclaimable) + per + '.');
4568
4820
  }
4569
4821
  if ((Number(mr.potential_cost_usd) || 0) > 0) {
4570
- parts.push('Let Token Optimizer route more of your routine work to lighter models. Recovers about ' + money(mo(mr.potential_cost_usd)) + per + '.');
4822
+ parts.push('Route routine work to lighter models and keep Opus for the work that needs it. The routing line above shows the size of that assumption.');
4571
4823
  }
4572
4824
  if (cdTokensMo > 0) {
4573
- parts.push('Resume within the hour, or batch related work before stepping away. ' + (Number(cd.drop_sessions) || 0) + ' of your sessions idled past the cache window and re-wrote the prefix — about ' + cdTokensMo.toLocaleString() + ' tokens' + per + '.');
4825
+ parts.push('Resume within the hour, or batch related work before stepping away. ' + (Number(cd.drop_sessions) || 0) + ' of your sessions idled past the cache window and re-wrote the prefix, about ' + cdTokensMo.toLocaleString() + ' tokens' + per + (cdCostMo > 0 ? ', worth about ' + money(cdCostMo) + per + ' at API rates' : '') + '.');
4574
4826
  }
4575
4827
  if ((Number(ow.cost_saved_usd) || 0) > 0) {
4576
- parts.push('Favor targeted Edits over full-file Writes. About ' + (Number(ow.avoidable_writes) || 0) + ' of your Writes could have been Edits, worth about ' + money(mo(ow.cost_saved_usd)) + per + ' in output.');
4828
+ parts.push('Favor targeted Edits over full-file Writes. About ' + (Number(ow.avoidable_writes) || 0) + ' of your Writes could have been Edits, worth about ' + moneyCents(oppCents.output) + per + ' in output.');
4577
4829
  }
4578
4830
  if (parts.length > 0) {
4579
4831
  html += '<div class="card wide" style="padding:var(--s-5) var(--s-4);margin-bottom:var(--s-3);border:1px solid var(--c-amber);box-shadow:0 0 0 1px rgba(217,164,65,0.18), 0 0 44px rgba(217,164,65,0.12);">';
4580
4832
  html += '<div class="label" style="margin-bottom:var(--s-2);color:var(--c-amber);letter-spacing:0.08em;">Money on the table &middot; opportunity</div>';
4581
- html += '<div style="display:flex;align-items:baseline;gap:var(--s-2);flex-wrap:wrap;">' +
4582
- '<span style="font-family:var(--font-mono);font-weight:300;font-size:76px;line-height:0.9;color:var(--c-amber);text-shadow:0 0 30px rgba(217,164,65,0.5);letter-spacing:-0.02em;">' + money(opportunityMo) + '</span>' +
4583
- '<span style="font-size:23px;color:var(--c-text-dim);font-family:var(--font-mono);">' + per + ' still on the table</span>' +
4584
- '</div>';
4585
- html += '<div class="lede" style="margin-top:var(--s-2);">Potential savings if you change your setup or habits. Excluded from the totals above.</div>';
4833
+ if (opportunityMo > 0) {
4834
+ html += '<div style="display:flex;align-items:baseline;gap:var(--s-2);flex-wrap:wrap;">' +
4835
+ '<span style="font-family:var(--font-mono);font-weight:300;font-size:76px;line-height:0.9;color:var(--c-amber);text-shadow:0 0 30px rgba(217,164,65,0.5);letter-spacing:-0.02em;">' + moneyCents(oppCents.total) + '</span>' +
4836
+ '<span style="font-size:23px;color:var(--c-text-dim);font-family:var(--font-mono);">' + per + ' still on the table</span>' +
4837
+ '</div>';
4838
+ html += '<div class="lede" style="margin-top:var(--s-2);">Potential savings if you change your setup or habits. Excluded from the totals above.</div>';
4839
+ } else {
4840
+ html += '<div class="lede">Potential savings if you change your setup or habits. Excluded from the totals above.</div>';
4841
+ }
4842
+ if (cdTokensMo > 0) {
4843
+ html += '<div class="cache-drop-opportunity" style="margin-top:var(--s-3);font-family:var(--font-mono);font-size:17px;line-height:1.6;color:var(--c-text-main);max-width:820px;">' +
4844
+ 'Cache drops (an opportunity, not a measurement): ' + (Number(cd.drop_sessions) || 0) + ' sessions idled past the cache window and re-wrote ~' + fmtTok(cdTokensMo) + ' tokens' + esc(per) + ' of prefix' +
4845
+ (cdCostMo > 0 ? ', about <span style="color:var(--c-amber);">' + money(cdCostMo) + esc(per) + '</span> at API rates' : '') + '.' +
4846
+ '</div>';
4847
+ html += '<div class="plain-line">Not part of the savings number above.</div>';
4848
+ html += fold('How the cache drop figure is priced', '<p>Cache write rate minus the cache read it would have cost, at the models you ran. It is not part of the number above.</p>');
4849
+ }
4850
+ if (routingPotentialMo > 0) {
4851
+ html += '<div class="routing-assumption" style="margin-top:var(--s-3);font-family:var(--font-mono);font-size:17px;line-height:1.6;color:var(--c-text-main);max-width:820px;">' +
4852
+ 'Routing (an assumption, not a measurement): if about ' + routingFracPct + '% of your Opus work (grunt tasks) ran on ' + esc(routingTarget) + ': new input and output only' +
4853
+ (mo(mr.potential_unsplit_excluded_tokens) > 0 ? ' (~' + fmtTok(mo(mr.potential_unsplit_excluded_tokens)) + ' Opus tokens' + esc(per) + ' without a class split are left out)' : '') + ', about <span style="color:var(--c-amber);">' + money(routingPotentialMo) + esc(per) + '</span> at API rates.' +
4854
+ (routingTokensMo > 0 ? ' ~' + fmtTok(routingTokensMo) + ' tokens' + esc(per) + '.' : '') +
4855
+ '</div>';
4856
+ html += '<div class="plain-line">An assumption about your own work, not a measured saving, and not part of the number above.</div>';
4857
+ var classLabels = { fresh_input: 'Fresh input', cache_create_5m: 'Cache writes (5 min)', cache_create_1h: 'Cache writes (1 hour)',
4858
+ cache_read: 'Cache reads', output: 'Output' };
4859
+ var byClass = mr.potential_by_class || {};
4860
+ var classRows = Object.keys(byClass).filter(function(k) { return classLabels[k]; })
4861
+ .sort(function(a, b) { return (Number(byClass[b].usd) || 0) - (Number(byClass[a].usd) || 0); });
4862
+ if (classRows.length) {
4863
+ html += fold('How the routing figure is priced',
4864
+ '<p>Some Opus work is worth keeping on Opus.</p>' +
4865
+ '<p>Each kind of token is priced at the rate of the model you ran, and the lighter model at the newest Sonnet rates. ' +
4866
+ 'The figure is the rate difference on about ' + routingFracPct + '% of your remaining Opus tokens.</p>' +
4867
+ classRows.map(function(k) {
4868
+ return '<p>' + esc(classLabels[k]) + ': ~' + fmtTok(mo(byClass[k].tokens)) + ' tokens' + esc(per) + ', about ' + money(mo(byClass[k].usd)) + ' at API rates.</p>';
4869
+ }).join(''));
4870
+ } else {
4871
+ html += fold('About this assumption', '<p>Some Opus work is worth keeping on Opus.</p>');
4872
+ }
4873
+ }
4586
4874
  html += '<details class="fold"><summary>Ways to save more</summary><div class="fold__body">';
4875
+ html += '<p>' + billingCaption + '</p>';
4587
4876
  parts.forEach(function(p, i){
4588
4877
  html += '<div style="display:flex;gap:var(--s-3);align-items:flex-start;">' +
4589
4878
  '<div style="flex-shrink:0;width:34px;height:34px;border-radius:50%;border:1.5px solid var(--c-amber);background:rgba(217,164,65,0.08);display:flex;align-items:center;justify-content:center;font-family:var(--font-mono);font-size:16px;color:var(--c-amber);margin-top:2px;">' + (i+1) + '</div>' +
@@ -4625,7 +4914,8 @@ var DB = (function() {
4625
4914
  '<div style="font-family:var(--font-mono);font-weight:300;font-size:48px;line-height:1;color:var(--c-accent-cyan);">' + avgQ + '<span style="font-size:18px;color:var(--c-text-dim);">/100</span></div>' +
4626
4915
  '<div style="flex:1;min-width:220px;">' +
4627
4916
  '<div style="height:8px;border-radius:5px;background:rgba(255,255,255,0.06);overflow:hidden;"><div style="height:100%;width:' + barPct + '%;background:linear-gradient(90deg,var(--c-accent-blue),var(--c-accent-cyan));"></div></div>' +
4628
- '<div style="margin-top:var(--s-2);font-size:14px;color:var(--c-text-dim);line-height:1.6;">Savings are only half the story. Across your last ' + sessionsCounted + ' sessions, Token Optimizer kept your context averaging ' + avgQ + '/100. Tighter context means sharper answers and fewer compaction interruptions. <em>This is the average across sessions; the Health tab scores your single latest session.</em></div>' +
4917
+ '<div class="plain-line">Across your last ' + sessionsCounted + ' sessions, Token Optimizer kept your context averaging ' + avgQ + '/100.</div>' +
4918
+ fold('What this means', '<p>Savings are only half the story. Tighter context means sharper answers and fewer compaction interruptions.</p><p>This is the average across sessions; the Health tab scores your single latest session.</p>') +
4629
4919
  '</div>' +
4630
4920
  '</div></div>';
4631
4921
  }
@@ -4667,13 +4957,15 @@ var DB = (function() {
4667
4957
  var ready = pr.promotion_ready;
4668
4958
  ccHtml += '<div style="margin-top:var(--s-3);padding-top:var(--s-2);border-top:1px solid rgba(255,255,255,0.08);">' +
4669
4959
  '<div style="font-weight:500;">First-read skeleton — safety check</div>' +
4670
- '<div style="font-size:13px;color:var(--c-text-dim);line-height:1.6;margin-top:2px;">' +
4960
+ '<div class="plain-line">' + (Number(pr.edits_after_read) || 0) + ' of ' + (Number(pr.shadow_reads) || 0) +
4961
+ ' large files were edited soon after the read (' + (Number(pr.edit_rate_pct) || 0).toFixed(1) + '%). ' +
4962
+ 'Currently <strong>' + (ready ? 'ready to promote' : 'still measuring') + '</strong>.</div>' +
4963
+ fold('How this check works', '<p>' +
4671
4964
  'Of ' + (Number(pr.shadow_reads) || 0) + ' large files where a skeleton would have saved tokens, ' +
4672
4965
  (Number(pr.edits_after_read) || 0) + ' were edited soon after the read &mdash; an edit rate of ' +
4673
4966
  '<span style="font-family:var(--font-mono);color:' + (ready ? 'var(--c-accent-cyan)' : 'var(--c-text-main)') + ';">' + (Number(pr.edit_rate_pct) || 0).toFixed(1) + '%</span>. ' +
4674
- 'Skeletons turn on automatically only once this stays under ' + (Number(pr.promotion_gate_pct) || 15) + '% (the model rarely needed the full file). ' +
4675
- 'Currently <strong>' + (ready ? 'ready to promote' : 'still measuring') + '</strong>.' +
4676
- '</div></div>';
4967
+ 'Skeletons turn on automatically only once this stays under ' + (Number(pr.promotion_gate_pct) || 15) + '% (the model rarely needed the full file).</p>') +
4968
+ '</div>';
4677
4969
  }
4678
4970
  // Runtime tripwire: per-cohort LIVE edit-rate + any auto-demotions.
4679
4971
  var tw = cc.cohort_tripwire || {};
@@ -4682,9 +4974,7 @@ var DB = (function() {
4682
4974
  if (twCohorts.length || twDemoted.length) {
4683
4975
  ccHtml += '<div style="margin-top:var(--s-3);padding-top:var(--s-2);border-top:1px solid rgba(255,255,255,0.08);">' +
4684
4976
  '<div style="font-weight:500;">Active cohort tripwire &mdash; live quality guard</div>' +
4685
- '<div style="font-size:13px;color:var(--c-text-dim);margin-top:2px;margin-bottom:4px;">' +
4686
- 'Each promoted cohort’s live edit-after-skeleton rate. A cohort auto-demotes to measure-only if it crosses 15% (no flapping &mdash; re-promote is manual or by the next backfill).' +
4687
- '</div>';
4977
+ fold('How the tripwire works', '<p>Each promoted cohort’s live edit-after-skeleton rate. A cohort auto-demotes to measure-only if it crosses 15% (no flapping &mdash; re-promote is manual or by the next backfill).</p>');
4688
4978
  twCohorts.forEach(function(c) {
4689
4979
  var dem = !!c.demoted;
4690
4980
  // T9: interpolated cohorts (promoted on a thin sample via an adjacent
@@ -4736,10 +5026,10 @@ var DB = (function() {
4736
5026
  '<div><div style="font-size:12px;color:var(--c-text-dim);">Affected sessions</div>' +
4737
5027
  '<div style="font-family:var(--font-mono);font-size:20px;">' + (Number(ch.affected_sessions) || 0) + '<span style="font-size:13px;color:var(--c-text-dim);"> / ' + (Number(ch.scanned_sessions) || 0) + '</span></div></div>' +
4738
5028
  (Number(ch.would_be_savings_1h_usd) > 0 ?
4739
- '<div><div style="font-size:12px;color:var(--c-text-dim);" title="API/SDK sessions only: a 1-hour cache_control would avoid the repeat writes. Does not apply to Claude Code, which already holds a 1h cache.">Recoverable via 1h cache (API/SDK)</div>' +
5029
+ '<div><div style="font-size:12px;color:var(--c-text-dim);" title="' + ((!data.runtime || data.runtime === 'claude') ? 'API/SDK sessions only: a 1-hour cache_control would avoid the repeat writes. Does not apply to Claude Code, which already holds a 1h cache.' : 'Where the provider offers a 1-hour cache, using it would avoid these repeat writes.') + '">Recoverable via 1h cache (API/SDK)</div>' +
4740
5030
  '<div style="font-family:var(--font-mono);font-size:20px;color:var(--c-text-dim);">$' + (Number(ch.would_be_savings_1h_usd) || 0).toFixed(2) + '</div></div>' : '') +
4741
5031
  (Number(ch.avoidable_behavioral_usd) > 0 ?
4742
- '<div><div style="font-size:12px;color:var(--c-text-dim);" title="Claude Code already holds a 1-hour cache. This is avoidable only behaviorally — by resuming within the hour or batching related work. No setting extends it.">Avoidable by resuming in-hour</div>' +
5032
+ '<div><div style="font-size:12px;color:var(--c-text-dim);" title="' + ((!data.runtime || data.runtime === 'claude') ? 'Claude Code already holds a 1-hour cache. This is avoidable only behaviorally, by resuming within the hour or batching related work. No setting extends it.' : 'Avoidable by resuming before the cache expires or batching related work.') + '">Avoidable by resuming in-hour</div>' +
4743
5033
  '<div style="font-family:var(--font-mono);font-size:20px;color:var(--c-text-dim);">$' + (Number(ch.avoidable_behavioral_usd) || 0).toFixed(2) + '</div></div>' : '') +
4744
5034
  '</div>';
4745
5035
  if (Number(ch.no_cache_economics_sessions) > 0) {
@@ -5646,6 +5936,8 @@ var DB = (function() {
5646
5936
  '<p id="manage-mode-desc">' +
5647
5937
  (isCodex
5648
5938
  ? 'Codex setup uses real local logs plus project hooks. Balanced hooks are on by default; noisy per-tool hooks stay opt-in so Desktop users are not spammed.'
5939
+ : m && m.read_only
5940
+ ? 'Your ' + esc(data.runtime_label || 'runtime') + ' skills and MCP servers, read from its own files. Token Optimizer feature toggles are below.'
5649
5941
  : window.__TOKEN_API_LIVE
5650
5942
  ? '<span style="color:var(--c-accent-cyan);font-weight:600;">Live mode</span> — toggles apply instantly to settings. <strong>Restart ' + (isCodex ? 'Codex' : 'Claude') + '</strong> to activate changes.'
5651
5943
  : tcliHtml('Open in serve mode for live toggles: <code style="background:var(--c-bg);padding:2px 5px;border-radius:4px;">python3 measure.py dashboard --serve</code>')) +
@@ -5835,8 +6127,45 @@ var DB = (function() {
5835
6127
  html += '</div></div></div>';
5836
6128
  }
5837
6129
 
6130
+ // --- READ-ONLY INVENTORY (Hermes) ---
6131
+ // Listed only: the toggles below manage Claude Code folders, so they must
6132
+ // never act on another runtime's skills or servers.
6133
+ if (!isCodex && m.read_only) {
6134
+ var roLabel = data.runtime_label || 'This runtime';
6135
+ var roRow = function(name, desc, meta) {
6136
+ return '<div class="hook-row" style="padding:8px var(--s-3);">' +
6137
+ '<div class="hook-info">' +
6138
+ '<div class="hook-label" style="font-size:14px;font-family:var(--font-mono);">' + esc(name) + '</div>' +
6139
+ (desc ? '<div class="hook-desc">' + esc(desc) + '</div>' : '') +
6140
+ '<div style="font-size:11px;color:var(--c-text-dim);margin-top:2px;">' + esc(meta) + '</div>' +
6141
+ '</div></div>';
6142
+ };
6143
+ var roList = function(title, items, label, empty, rowFn) {
6144
+ var out = '<div class="card wide"><div class="card-header"><span>' + esc(title) + ' (' + items.length + ')</span>' +
6145
+ (label ? '<span class="label">' + esc(label) + '</span>' : '') + '</div>';
6146
+ if (items.length === 0) return out + '<div class="empty-state" style="font-size:13px;">' + esc(empty) + '</div></div>';
6147
+ return out + '<div style="max-height:500px;overflow-y:auto;">' + items.map(rowFn).join('') + '</div></div>';
6148
+ };
6149
+ var roSkills = (m.skills && m.skills.active) || [];
6150
+ var roSkillTokens = roSkills.reduce(function(s, sk) { return s + (sk.tokens || 0); }, 0);
6151
+ var skillRow = function(sk) {
6152
+ return roRow(sk.name, sk.description || '', (sk.category ? sk.category + ' · ' : '') + (sk.tokens || 0) + ' tokens in the skill list');
6153
+ };
6154
+ html += roList('Skills', roSkills, fn(roSkillTokens) + ' tokens/session', 'No skills found in your ' + roLabel + ' skills folder.', skillRow);
6155
+ var roArchived = ((m.skills && m.skills.archived) || []).concat((m.skills && m.skills.disabled) || []);
6156
+ if (roArchived.length) html += roList('Archived or disabled skills', roArchived, 'not in the skill list', '', function(sk) {
6157
+ return roRow(sk.name, sk.description || '', sk.path || '');
6158
+ });
6159
+ var roMcp = ((m.mcp_servers && m.mcp_servers.active) || []).concat((m.mcp_servers && m.mcp_servers.disabled) || []);
6160
+ html += roList('MCP servers', roMcp, '', 'No mcp_servers in your ' + roLabel + ' config.yaml.', function(srv) {
6161
+ return roRow(srv.name, '', (srv.enabled ? '' : 'disabled · ') + srv.transport + (srv.command ? ' · ' + srv.command : ''));
6162
+ });
6163
+ html += '<p style="font-size:13px;color:var(--c-text-dim);padding:0 var(--s-3);">Read from ' + esc(roLabel) +
6164
+ '\'s own skills folder and config.yaml. Change them in ' + esc(roLabel) + '; this list updates on the next refresh.</p>';
6165
+ }
6166
+
5838
6167
  // --- SKILLS SECTION ---
5839
- if (!isCodex) {
6168
+ if (!isCodex && !m.read_only) {
5840
6169
  var activeSkills = (m.skills && m.skills.active) || [];
5841
6170
  var archivedSkills = (m.skills && m.skills.archived) || [];
5842
6171
  var totalTokens = activeSkills.reduce(function(s, sk) { return s + (sk.tokens || 100); }, 0);