ctxtop 0.0.0-stage → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +166 -0
- package/LICENSE +27 -0
- package/README.md +350 -2
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +175 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1799 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +133 -0
- package/config/modelCatalog.json +785 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +577 -0
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +311 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +366 -0
- package/hooks/handlers/pre-model-switch.mjs +1048 -0
- package/hooks/handlers/pre-tool-use.mjs +632 -0
- package/hooks/handlers/stop-gate.mjs +526 -0
- package/hooks/handlers/user-prompt-submit.mjs +367 -0
- package/hooks/hooks.json +131 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +25 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +726 -0
- package/hooks/session_start.mjs +24 -0
- package/hooks/stop.mjs +23 -0
- package/hooks.json +56 -0
- package/package.json +110 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2038 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +50 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +109 -0
- package/src/adapters/claude-code/index.mjs +194 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +888 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +704 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/bucket_b_runtime.mjs +1200 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1987 -0
- package/src/core/detectors_det01_to_16.mjs +1523 -0
- package/src/core/doc_indexer.mjs +338 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +1084 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1997 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +311 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/rsl_clash_auditor.mjs +423 -0
- package/src/core/rsl_distiller.mjs +372 -0
- package/src/core/rsl_ledger.mjs +969 -0
- package/src/core/rsl_triage.mjs +909 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_auditor.mjs +658 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/shield_manager.mjs +1417 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
- package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +27 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
- package/src/core-isomorphic/ui/modViews.mjs +1504 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +295 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +342 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +12 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +376 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +611 -0
- package/src/hooks/pre_invocation.mjs +1725 -0
- package/src/hooks/session_start.mjs +199 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +12397 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,615 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { getHomeDir } from '../paths.mjs';
|
|
4
|
+
import { openLocalHorizonDb } from '../sqlite_client.mjs';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Phase 4.3: Deterministic "Saved-Quota Receipt" Ledger (`src/core/coach/saved_quota_ledger.mjs`)
|
|
8
|
+
*
|
|
9
|
+
* - Initializes strictly at `$0.00` and `0` tokens (zero mock constants).
|
|
10
|
+
* - Stores byte-verified deterministic savings events in SQLite:
|
|
11
|
+
* `EFFORT_DOWNSHIFT`, `COLD_PREFILL_AVOIDED`, `CLI_DUMP_COMPRESSED`, `LOOP_TURN_PREVENTED`
|
|
12
|
+
* - Updates the VS Code Status Bar item and Horizon Footer from live SQLite rows only.
|
|
13
|
+
* - Implements `[Copy Savings Receipt]` to export a clean Markdown telemetry table to the clipboard.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export const INITIAL_LEDGER_STATE = Object.freeze({
|
|
17
|
+
totalTokensSaved: 0,
|
|
18
|
+
totalArgonEquivTokensSaved: 0,
|
|
19
|
+
totalDollarsSaved: 0,
|
|
20
|
+
formattedDollarsSaved: '$0.00',
|
|
21
|
+
formattedSavedK: '0.0k'
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
export const SAVINGS_EVENT_TYPES = Object.freeze({
|
|
25
|
+
EFFORT_DOWNSHIFT: 'EFFORT_DOWNSHIFT',
|
|
26
|
+
COLD_PREFILL_AVOIDED: 'COLD_PREFILL_AVOIDED',
|
|
27
|
+
CLI_DUMP_COMPRESSED: 'CLI_DUMP_COMPRESSED',
|
|
28
|
+
LOOP_TURN_PREVENTED: 'LOOP_TURN_PREVENTED',
|
|
29
|
+
SUBAGENT_ISOLATED: 'SUBAGENT_ISOLATED',
|
|
30
|
+
CACHE_HIT_PRESERVED: 'CACHE_HIT_PRESERVED',
|
|
31
|
+
COMPACTION_RECLAIMED: 'COMPACTION_RECLAIMED',
|
|
32
|
+
PROMPT_HYGIENE_STEERED: 'PROMPT_HYGIENE_STEERED',
|
|
33
|
+
PROMPT_HYGIENE_BLOCKED: 'PROMPT_HYGIENE_BLOCKED',
|
|
34
|
+
SIGHTSEEING_TOOL_PREVENTED: 'SIGHTSEEING_TOOL_PREVENTED'
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
/** Plain-English labels for the Simple View Auto-fix log. */
|
|
38
|
+
export const AUTO_FIX_LABELS = Object.freeze({
|
|
39
|
+
EFFORT_DOWNSHIFT: 'Effort downshifted',
|
|
40
|
+
COLD_PREFILL_AVOIDED: 'Cold prefill avoided',
|
|
41
|
+
CLI_DUMP_COMPRESSED: 'CLI output compressed',
|
|
42
|
+
LOOP_TURN_PREVENTED: 'Loop turn prevented',
|
|
43
|
+
SUBAGENT_ISOLATED: 'Subagent isolated',
|
|
44
|
+
COMPACTION_RECLAIMED: 'Compaction reclaimed',
|
|
45
|
+
PROMPT_HYGIENE_STEERED: 'Prompt steered',
|
|
46
|
+
PROMPT_HYGIENE_BLOCKED: 'Prompt blocked',
|
|
47
|
+
SIGHTSEEING_TOOL_PREVENTED: 'Sightseeing read prevented'
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
export function getDefaultSavingsLedgerDbPath(homeDir = getHomeDir()) {
|
|
51
|
+
return path.join(homeDir, '.gemini', 'antigravity', 'agy-horizon', 'saved_quota_ledger.sqlite');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function formatTokensCompactK(tokens = 0) {
|
|
55
|
+
const n = Math.max(0, Number(tokens) || 0);
|
|
56
|
+
return `${(n / 1000).toFixed(1)}k`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function formatTokensHuman(tokens = 0) {
|
|
60
|
+
const n = Math.max(0, Number(tokens) || 0);
|
|
61
|
+
if (n >= 1_000_000) {
|
|
62
|
+
return `${(n / 1_000_000).toFixed(1)}M`;
|
|
63
|
+
}
|
|
64
|
+
return `${(n / 1000).toFixed(1)}k`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export class SavedQuotaReceiptLedger {
|
|
68
|
+
constructor(options = {}) {
|
|
69
|
+
this.homeDir = options.homeDir || getHomeDir();
|
|
70
|
+
this.dbPath = options.dbPath !== undefined && options.dbPath !== null
|
|
71
|
+
? String(options.dbPath)
|
|
72
|
+
: getDefaultSavingsLedgerDbPath(this.homeDir);
|
|
73
|
+
this.clipboardWriter = typeof options.clipboardWriter === 'function'
|
|
74
|
+
? options.clipboardWriter
|
|
75
|
+
: (text) => { this.lastClipboardMarkdown = String(text || ''); return true; };
|
|
76
|
+
this.lastClipboardMarkdown = '';
|
|
77
|
+
if (this.dbPath) {
|
|
78
|
+
this._initDb();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
_initDb() {
|
|
83
|
+
if (!this.dbPath) return;
|
|
84
|
+
fs.mkdirSync(path.dirname(this.dbPath), { recursive: true });
|
|
85
|
+
const db = openLocalHorizonDb(this.dbPath, { readOnly: false });
|
|
86
|
+
try {
|
|
87
|
+
db.exec(`
|
|
88
|
+
CREATE TABLE IF NOT EXISTS savings_events (
|
|
89
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
90
|
+
session_id TEXT NOT NULL,
|
|
91
|
+
event_type TEXT NOT NULL,
|
|
92
|
+
argon_equiv_tokens_saved INTEGER NOT NULL DEFAULT 0,
|
|
93
|
+
raw_bytes_saved INTEGER NOT NULL DEFAULT 0,
|
|
94
|
+
dollars_saved REAL NOT NULL DEFAULT 0,
|
|
95
|
+
detail TEXT,
|
|
96
|
+
created_at TEXT NOT NULL
|
|
97
|
+
);
|
|
98
|
+
`);
|
|
99
|
+
try { db.exec('ALTER TABLE savings_events ADD COLUMN raw_bytes_saved INTEGER NOT NULL DEFAULT 0;'); } catch {}
|
|
100
|
+
try { db.exec('ALTER TABLE savings_events ADD COLUMN dollars_saved REAL NOT NULL DEFAULT 0;'); } catch {}
|
|
101
|
+
} finally {
|
|
102
|
+
db.close();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Records a verified deterministic savings event into SQLite.
|
|
108
|
+
*/
|
|
109
|
+
recordSaving({
|
|
110
|
+
sessionId = 'default-session',
|
|
111
|
+
eventType = SAVINGS_EVENT_TYPES.EFFORT_DOWNSHIFT,
|
|
112
|
+
argonEquivTokensSaved = undefined,
|
|
113
|
+
tokensSaved = undefined,
|
|
114
|
+
rawBytesSaved = 0,
|
|
115
|
+
dollarsSaved = undefined,
|
|
116
|
+
inputPricePer1M = 2.0,
|
|
117
|
+
detail = '',
|
|
118
|
+
dedupeKey = '',
|
|
119
|
+
createdAt = new Date().toISOString()
|
|
120
|
+
} = {}) {
|
|
121
|
+
const type = String(eventType || SAVINGS_EVENT_TYPES.EFFORT_DOWNSHIFT).toUpperCase();
|
|
122
|
+
const bytes = Math.max(0, Math.round(Number(rawBytesSaved) || 0));
|
|
123
|
+
const derivedTokens = bytes > 0 ? Math.floor(bytes / 4) : 0;
|
|
124
|
+
const saved = Math.max(0, Math.round(Number(argonEquivTokensSaved ?? tokensSaved ?? derivedTokens) || 0));
|
|
125
|
+
const usd = dollarsSaved !== undefined
|
|
126
|
+
? Math.max(0, Number(dollarsSaved) || 0)
|
|
127
|
+
: Number(((saved / 1_000_000) * Math.max(0, Number(inputPricePer1M) || 0)).toFixed(6));
|
|
128
|
+
const detailStr = dedupeKey
|
|
129
|
+
? `[key:${dedupeKey}] ${String(detail || '')}`.trim()
|
|
130
|
+
: String(detail || '');
|
|
131
|
+
if (!this.dbPath) {
|
|
132
|
+
return this.getSummary(sessionId);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const db = openLocalHorizonDb(this.dbPath, { readOnly: false });
|
|
136
|
+
try {
|
|
137
|
+
if (dedupeKey) {
|
|
138
|
+
const existing = db.prepare(`
|
|
139
|
+
SELECT id FROM savings_events
|
|
140
|
+
WHERE session_id = ? AND event_type = ? AND detail LIKE ?
|
|
141
|
+
LIMIT 1
|
|
142
|
+
`).get(String(sessionId), type, `[key:${dedupeKey}]%`);
|
|
143
|
+
if (existing) {
|
|
144
|
+
return this.getSummary(sessionId);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
db.prepare(`
|
|
148
|
+
INSERT INTO savings_events (session_id, event_type, argon_equiv_tokens_saved, raw_bytes_saved, dollars_saved, detail, created_at)
|
|
149
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
150
|
+
`).run(String(sessionId), type, saved, bytes, usd, detailStr, String(createdAt));
|
|
151
|
+
} finally {
|
|
152
|
+
db.close();
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return this.getSummary(sessionId);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Lists the most recent verified auto-fix events for a session (strictly read-only SQLite).
|
|
160
|
+
* Passive `CACHE_HIT_PRESERVED` rows are excluded: they are tracked in the KPI bar, not the fix log.
|
|
161
|
+
* @returns {{ total: number, items: Array<object> }}
|
|
162
|
+
*/
|
|
163
|
+
listRecentEvents(sessionId = null, limit = 20) {
|
|
164
|
+
if (!this.dbPath || !fs.existsSync(this.dbPath)) return { total: 0, items: [] };
|
|
165
|
+
const cap = Math.max(1, Math.min(200, Math.round(Number(limit) || 20)));
|
|
166
|
+
let rows = [];
|
|
167
|
+
let total = 0;
|
|
168
|
+
const db = openLocalHorizonDb(this.dbPath, { readOnly: true });
|
|
169
|
+
try {
|
|
170
|
+
const where = sessionId ? 'WHERE session_id = ? AND event_type != ?' : 'WHERE event_type != ?';
|
|
171
|
+
const args = sessionId
|
|
172
|
+
? [String(sessionId), SAVINGS_EVENT_TYPES.CACHE_HIT_PRESERVED]
|
|
173
|
+
: [SAVINGS_EVENT_TYPES.CACHE_HIT_PRESERVED];
|
|
174
|
+
total = Number(db.prepare(`SELECT COUNT(*) AS n FROM savings_events ${where}`).get(...args)?.n || 0);
|
|
175
|
+
rows = db.prepare(`
|
|
176
|
+
SELECT id, event_type AS eventType, argon_equiv_tokens_saved AS tokensSaved, raw_bytes_saved AS rawBytesSaved, dollars_saved AS usd, detail, created_at AS at
|
|
177
|
+
FROM savings_events ${where}
|
|
178
|
+
ORDER BY id DESC
|
|
179
|
+
LIMIT ${cap}
|
|
180
|
+
`).all(...args);
|
|
181
|
+
} finally {
|
|
182
|
+
db.close();
|
|
183
|
+
}
|
|
184
|
+
return {
|
|
185
|
+
total,
|
|
186
|
+
items: rows.map((r) => ({
|
|
187
|
+
id: r.id,
|
|
188
|
+
type: r.eventType,
|
|
189
|
+
label: AUTO_FIX_LABELS[r.eventType] || String(r.eventType || '').toLowerCase().replace(/_/g, ' ').replace(/^\w/, (c) => c.toUpperCase()),
|
|
190
|
+
tokensSaved: Math.max(0, Number(r.tokensSaved) || 0),
|
|
191
|
+
usd: Math.max(0, Number(r.usd) || 0),
|
|
192
|
+
detail: String(r.detail || '').replace(/^\[key:[^\]]*\]\s*/, '').slice(0, 160),
|
|
193
|
+
at: r.at,
|
|
194
|
+
turn: null
|
|
195
|
+
}))
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Computes aggregated savings and formats the VS Code Status Bar and Horizon Footer string.
|
|
201
|
+
*/
|
|
202
|
+
getSummary(sessionId = null) {
|
|
203
|
+
let rows = [];
|
|
204
|
+
if (this.dbPath && fs.existsSync(this.dbPath)) {
|
|
205
|
+
const db = openLocalHorizonDb(this.dbPath, { readOnly: true });
|
|
206
|
+
try {
|
|
207
|
+
if (sessionId) {
|
|
208
|
+
rows = db.prepare(`
|
|
209
|
+
SELECT id, session_id AS sessionId, event_type AS eventType, argon_equiv_tokens_saved AS argonEquivTokensSaved, raw_bytes_saved AS rawBytesSaved, dollars_saved AS dollarsSaved, detail, created_at AS createdAt
|
|
210
|
+
FROM savings_events
|
|
211
|
+
WHERE session_id = ?
|
|
212
|
+
ORDER BY id ASC
|
|
213
|
+
`).all(String(sessionId));
|
|
214
|
+
} else {
|
|
215
|
+
rows = db.prepare(`
|
|
216
|
+
SELECT id, session_id AS sessionId, event_type AS eventType, argon_equiv_tokens_saved AS argonEquivTokensSaved, raw_bytes_saved AS rawBytesSaved, dollars_saved AS dollarsSaved, detail, created_at AS createdAt
|
|
217
|
+
FROM savings_events
|
|
218
|
+
ORDER BY id ASC
|
|
219
|
+
`).all();
|
|
220
|
+
}
|
|
221
|
+
} finally {
|
|
222
|
+
db.close();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const counts = {
|
|
227
|
+
[SAVINGS_EVENT_TYPES.COLD_PREFILL_AVOIDED]: 0,
|
|
228
|
+
[SAVINGS_EVENT_TYPES.EFFORT_DOWNSHIFT]: 0,
|
|
229
|
+
[SAVINGS_EVENT_TYPES.CLI_DUMP_COMPRESSED]: 0,
|
|
230
|
+
[SAVINGS_EVENT_TYPES.LOOP_TURN_PREVENTED]: 0,
|
|
231
|
+
[SAVINGS_EVENT_TYPES.SUBAGENT_ISOLATED]: 0,
|
|
232
|
+
[SAVINGS_EVENT_TYPES.CACHE_HIT_PRESERVED]: 0,
|
|
233
|
+
[SAVINGS_EVENT_TYPES.COMPACTION_RECLAIMED]: 0,
|
|
234
|
+
[SAVINGS_EVENT_TYPES.PROMPT_HYGIENE_STEERED]: 0,
|
|
235
|
+
[SAVINGS_EVENT_TYPES.PROMPT_HYGIENE_BLOCKED]: 0,
|
|
236
|
+
[SAVINGS_EVENT_TYPES.SIGHTSEEING_TOOL_PREVENTED]: 0
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
const totalsByType = {
|
|
240
|
+
[SAVINGS_EVENT_TYPES.COLD_PREFILL_AVOIDED]: 0,
|
|
241
|
+
[SAVINGS_EVENT_TYPES.EFFORT_DOWNSHIFT]: 0,
|
|
242
|
+
[SAVINGS_EVENT_TYPES.CLI_DUMP_COMPRESSED]: 0,
|
|
243
|
+
[SAVINGS_EVENT_TYPES.LOOP_TURN_PREVENTED]: 0,
|
|
244
|
+
[SAVINGS_EVENT_TYPES.SUBAGENT_ISOLATED]: 0,
|
|
245
|
+
[SAVINGS_EVENT_TYPES.CACHE_HIT_PRESERVED]: 0,
|
|
246
|
+
[SAVINGS_EVENT_TYPES.COMPACTION_RECLAIMED]: 0,
|
|
247
|
+
[SAVINGS_EVENT_TYPES.PROMPT_HYGIENE_STEERED]: 0,
|
|
248
|
+
[SAVINGS_EVENT_TYPES.PROMPT_HYGIENE_BLOCKED]: 0,
|
|
249
|
+
[SAVINGS_EVENT_TYPES.SIGHTSEEING_TOOL_PREVENTED]: 0
|
|
250
|
+
};
|
|
251
|
+
|
|
252
|
+
let totalArgonEquivTokensSaved = 0;
|
|
253
|
+
let totalRawBytesSaved = 0;
|
|
254
|
+
let totalDollarsSaved = 0;
|
|
255
|
+
const distinctSessions = new Set();
|
|
256
|
+
|
|
257
|
+
for (const row of rows) {
|
|
258
|
+
const t = String(row.eventType || '');
|
|
259
|
+
const tok = Math.max(0, Number(row.argonEquivTokensSaved || 0));
|
|
260
|
+
const b = Math.max(0, Number(row.rawBytesSaved || 0));
|
|
261
|
+
const usd = Math.max(0, Number(row.dollarsSaved || 0));
|
|
262
|
+
totalArgonEquivTokensSaved += tok;
|
|
263
|
+
totalRawBytesSaved += b;
|
|
264
|
+
totalDollarsSaved += usd;
|
|
265
|
+
if (row.sessionId) distinctSessions.add(String(row.sessionId));
|
|
266
|
+
if (counts[t] !== undefined) {
|
|
267
|
+
counts[t]++;
|
|
268
|
+
totalsByType[t] += tok;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const coldCount = counts[SAVINGS_EVENT_TYPES.COLD_PREFILL_AVOIDED];
|
|
273
|
+
const downshiftCount = counts[SAVINGS_EVENT_TYPES.EFFORT_DOWNSHIFT];
|
|
274
|
+
const cliCount = counts[SAVINGS_EVENT_TYPES.CLI_DUMP_COMPRESSED];
|
|
275
|
+
const loopCount = counts[SAVINGS_EVENT_TYPES.LOOP_TURN_PREVENTED];
|
|
276
|
+
const steeredPrompts = counts[SAVINGS_EVENT_TYPES.PROMPT_HYGIENE_STEERED];
|
|
277
|
+
const blockedPrompts = counts[SAVINGS_EVENT_TYPES.PROMPT_HYGIENE_BLOCKED];
|
|
278
|
+
const sightseeingToolsPrevented = counts[SAVINGS_EVENT_TYPES.SIGHTSEEING_TOOL_PREVENTED];
|
|
279
|
+
const modeledEstimateTokensSaved =
|
|
280
|
+
totalsByType[SAVINGS_EVENT_TYPES.PROMPT_HYGIENE_STEERED] +
|
|
281
|
+
totalsByType[SAVINGS_EVENT_TYPES.PROMPT_HYGIENE_BLOCKED] +
|
|
282
|
+
totalsByType[SAVINGS_EVENT_TYPES.SIGHTSEEING_TOOL_PREVENTED];
|
|
283
|
+
|
|
284
|
+
const parts = [
|
|
285
|
+
`${coldCount} Cold Prefill${coldCount === 1 ? '' : 's'}`,
|
|
286
|
+
`${downshiftCount} Downshift${downshiftCount === 1 ? '' : 's'}`,
|
|
287
|
+
`${cliCount} CLI Compress`
|
|
288
|
+
];
|
|
289
|
+
if (loopCount > 0) {
|
|
290
|
+
parts.push(`${loopCount} Loop${loopCount === 1 ? '' : 's'} Prevented`);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
const formattedSavedK = formatTokensCompactK(totalArgonEquivTokensSaved);
|
|
294
|
+
const formattedSavedHuman = formatTokensHuman(totalArgonEquivTokensSaved);
|
|
295
|
+
const formattedDollarsSaved = totalDollarsSaved === 0 ? '$0.00' : `$${totalDollarsSaved.toFixed(2)}`;
|
|
296
|
+
const statusBarText = `$(shield) Horizon: +${formattedSavedK} Argon-equiv tokens saved (${parts.join(' • ')})`;
|
|
297
|
+
const footerText = `🛡️ Horizon: +${formattedSavedK} Argon-equiv tokens saved (${parts.join(' • ')})`;
|
|
298
|
+
const displayFooterText = `🛡️ Tokens Saved: +${formattedSavedHuman} (${parts.join(' · ')})`;
|
|
299
|
+
|
|
300
|
+
return {
|
|
301
|
+
totalTokensSaved: totalArgonEquivTokensSaved,
|
|
302
|
+
totalArgonEquivTokensSaved,
|
|
303
|
+
totalRawBytesSaved,
|
|
304
|
+
totalDollarsSaved: Number(totalDollarsSaved.toFixed(6)),
|
|
305
|
+
formattedDollarsSaved,
|
|
306
|
+
formattedSavedK,
|
|
307
|
+
formattedSavedHuman,
|
|
308
|
+
sessionsCount: distinctSessions.size,
|
|
309
|
+
counts,
|
|
310
|
+
totalsByType,
|
|
311
|
+
measuredPromptHygiene: {
|
|
312
|
+
steeredPrompts,
|
|
313
|
+
blockedPrompts,
|
|
314
|
+
sightseeingToolsPrevented,
|
|
315
|
+
modeledEstimateTokensSaved,
|
|
316
|
+
provenanceTag: '[modeled-estimate]'
|
|
317
|
+
},
|
|
318
|
+
events: rows,
|
|
319
|
+
statusBarText,
|
|
320
|
+
footerText,
|
|
321
|
+
displayFooterText
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Returns both session-scoped and 30-day workspace/global ledger summaries.
|
|
327
|
+
*/
|
|
328
|
+
getWorkspaceSummary({ sessionId = null, days = 30 } = {}) {
|
|
329
|
+
const sessionSummary = sessionId ? this.getSummary(sessionId) : this.getSummary(null);
|
|
330
|
+
const allSummary = this.getSummary(null);
|
|
331
|
+
const cutoffMs = Date.now() - Math.max(1, Number(days) || 30) * 86_400_000;
|
|
332
|
+
|
|
333
|
+
let totalTokens = 0;
|
|
334
|
+
let totalDollarsSaved = 0;
|
|
335
|
+
const sessions = new Set();
|
|
336
|
+
const counts = {
|
|
337
|
+
[SAVINGS_EVENT_TYPES.COLD_PREFILL_AVOIDED]: 0,
|
|
338
|
+
[SAVINGS_EVENT_TYPES.EFFORT_DOWNSHIFT]: 0,
|
|
339
|
+
[SAVINGS_EVENT_TYPES.CLI_DUMP_COMPRESSED]: 0,
|
|
340
|
+
[SAVINGS_EVENT_TYPES.LOOP_TURN_PREVENTED]: 0,
|
|
341
|
+
[SAVINGS_EVENT_TYPES.SUBAGENT_ISOLATED]: 0,
|
|
342
|
+
[SAVINGS_EVENT_TYPES.CACHE_HIT_PRESERVED]: 0,
|
|
343
|
+
[SAVINGS_EVENT_TYPES.COMPACTION_RECLAIMED]: 0,
|
|
344
|
+
[SAVINGS_EVENT_TYPES.PROMPT_HYGIENE_STEERED]: 0,
|
|
345
|
+
[SAVINGS_EVENT_TYPES.PROMPT_HYGIENE_BLOCKED]: 0,
|
|
346
|
+
[SAVINGS_EVENT_TYPES.SIGHTSEEING_TOOL_PREVENTED]: 0
|
|
347
|
+
};
|
|
348
|
+
const totalsByType = { ...counts };
|
|
349
|
+
|
|
350
|
+
for (const ev of allSummary.events) {
|
|
351
|
+
const ts = Date.parse(ev.createdAt || '');
|
|
352
|
+
if (Number.isFinite(ts) && ts < cutoffMs) continue;
|
|
353
|
+
const tok = Math.max(0, Number(ev.argonEquivTokensSaved || 0));
|
|
354
|
+
const usd = Math.max(0, Number(ev.dollarsSaved || 0));
|
|
355
|
+
const t = String(ev.eventType || '');
|
|
356
|
+
totalTokens += tok;
|
|
357
|
+
totalDollarsSaved += usd;
|
|
358
|
+
if (ev.sessionId) sessions.add(String(ev.sessionId));
|
|
359
|
+
if (counts[t] !== undefined) {
|
|
360
|
+
counts[t]++;
|
|
361
|
+
totalsByType[t] += tok;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
return {
|
|
366
|
+
session: sessionSummary,
|
|
367
|
+
workspace30d: {
|
|
368
|
+
totalTokens,
|
|
369
|
+
totalDollarsSaved: Number(totalDollarsSaved.toFixed(6)),
|
|
370
|
+
formattedTokens: formatTokensHuman(totalTokens),
|
|
371
|
+
formattedDollarsSaved: totalDollarsSaved === 0 ? '$0.00' : `$${totalDollarsSaved.toFixed(2)}`,
|
|
372
|
+
sessionsCount: sessions.size,
|
|
373
|
+
counts,
|
|
374
|
+
totalsByType
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Exports a plain-English Markdown receipt of verified token savings.
|
|
381
|
+
*/
|
|
382
|
+
copyPlainSavingsReceipt(arg = {}) {
|
|
383
|
+
const opts = typeof arg === 'string' ? { sessionId: arg } : (arg || {});
|
|
384
|
+
const sessionId = opts.sessionId || null;
|
|
385
|
+
const liveSavings = opts.liveSavings || null;
|
|
386
|
+
const ws = this.getWorkspaceSummary({ sessionId });
|
|
387
|
+
const s = liveSavings?.session || {
|
|
388
|
+
totalTokens: ws.session.totalTokensSaved,
|
|
389
|
+
estimatedUsd: ws.session.totalDollarsSaved,
|
|
390
|
+
bySource: {
|
|
391
|
+
subagentIsolated: ws.session.totalsByType.SUBAGENT_ISOLATED || 0,
|
|
392
|
+
cachePreserved: (ws.session.totalsByType.COLD_PREFILL_AVOIDED || 0) + (ws.session.totalsByType.CACHE_HIT_PRESERVED || 0),
|
|
393
|
+
cliCompressed: ws.session.totalsByType.CLI_DUMP_COMPRESSED || 0,
|
|
394
|
+
compactionReclaimed: ws.session.totalsByType.COMPACTION_RECLAIMED || 0,
|
|
395
|
+
guardsPrevented:
|
|
396
|
+
(ws.session.totalsByType.LOOP_TURN_PREVENTED || 0) +
|
|
397
|
+
(ws.session.totalsByType.EFFORT_DOWNSHIFT || 0) +
|
|
398
|
+
(ws.session.totalsByType.PROMPT_HYGIENE_STEERED || 0) +
|
|
399
|
+
(ws.session.totalsByType.PROMPT_HYGIENE_BLOCKED || 0) +
|
|
400
|
+
(ws.session.totalsByType.SIGHTSEEING_TOOL_PREVENTED || 0)
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
const w30 = liveSavings?.workspace30d || {
|
|
404
|
+
totalTokens: ws.workspace30d.totalTokens,
|
|
405
|
+
estimatedUsd: ws.workspace30d.totalDollarsSaved
|
|
406
|
+
};
|
|
407
|
+
const lines = [
|
|
408
|
+
`### 🛡️ Highbeam — Verified Tokens Saved Receipt`,
|
|
409
|
+
``,
|
|
410
|
+
`**This Chat:** \`+${formatTokensHuman(s.totalTokens)}\` (\`~$${Number(s.estimatedUsd || 0).toFixed(2)}\` est.) · **30-Day Workspace:** \`+${formatTokensHuman(w30.totalTokens)}\``,
|
|
411
|
+
``,
|
|
412
|
+
`| Source | Tokens Saved |`,
|
|
413
|
+
`| :--- | :---: |`,
|
|
414
|
+
`| Subagent context isolation | +${formatTokensHuman(s.bySource?.subagentIsolated || 0)} |`,
|
|
415
|
+
`| Warm prompt cache preserved (95% off) | +${formatTokensHuman(s.bySource?.cachePreserved || 0)} |`,
|
|
416
|
+
`| CLI & log output compressed | +${formatTokensHuman(s.bySource?.cliCompressed || 0)} |`,
|
|
417
|
+
`| Loops, re-reads & tail trims avoided | +${formatTokensHuman((s.bySource?.guardsPrevented || 0) + (s.bySource?.compactionReclaimed || 0))} |`
|
|
418
|
+
];
|
|
419
|
+
const markdown = lines.join('\n');
|
|
420
|
+
this.clipboardWriter(markdown);
|
|
421
|
+
return { ok: true, markdown, summary: ws.session };
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Exports a clean Markdown telemetry table receipt and copies it to the clipboard.
|
|
426
|
+
*/
|
|
427
|
+
copySavingsReceipt(sessionId = null) {
|
|
428
|
+
const summary = this.getSummary(sessionId);
|
|
429
|
+
const lines = [
|
|
430
|
+
`### 🛡️ Highbeam — Saved-Quota Receipt`,
|
|
431
|
+
``,
|
|
432
|
+
`**Total Saved:** \`+${summary.formattedSavedK}\` Argon-equiv tokens`,
|
|
433
|
+
``,
|
|
434
|
+
`| Category | Event Count | Argon-Equiv Tokens Saved |`,
|
|
435
|
+
`| :--- | :---: | :---: |`,
|
|
436
|
+
`| Cold Prefills Avoided (\`COLD_PREFILL_AVOIDED\`) | ${summary.counts.COLD_PREFILL_AVOIDED} | +${formatTokensCompactK(summary.totalsByType.COLD_PREFILL_AVOIDED)} |`,
|
|
437
|
+
`| Effort Downshifts (\`EFFORT_DOWNSHIFT\`) | ${summary.counts.EFFORT_DOWNSHIFT} | +${formatTokensCompactK(summary.totalsByType.EFFORT_DOWNSHIFT)} |`,
|
|
438
|
+
`| CLI Dumps Compressed (\`CLI_DUMP_COMPRESSED\`) | ${summary.counts.CLI_DUMP_COMPRESSED} | +${formatTokensCompactK(summary.totalsByType.CLI_DUMP_COMPRESSED)} |`,
|
|
439
|
+
`| Loop Turns Prevented (\`LOOP_TURN_PREVENTED\`) | ${summary.counts.LOOP_TURN_PREVENTED} | +${formatTokensCompactK(summary.totalsByType.LOOP_TURN_PREVENTED)} |`
|
|
440
|
+
];
|
|
441
|
+
|
|
442
|
+
const markdown = lines.join('\n');
|
|
443
|
+
this.clipboardWriter(markdown);
|
|
444
|
+
return {
|
|
445
|
+
ok: true,
|
|
446
|
+
markdown,
|
|
447
|
+
summary
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Computes the unified multi-source "Tokens Saved" payload (`state.savings`) combining
|
|
454
|
+
* deduplicated subagent isolation, warm prompt cache 95% discount, FTS5 CLI compression,
|
|
455
|
+
* compaction/tail-trim reclaims, and prevented loop/re-read guards.
|
|
456
|
+
*/
|
|
457
|
+
export function computeUnifiedSavings(state = {}, {
|
|
458
|
+
ledger = null,
|
|
459
|
+
sessionId = null,
|
|
460
|
+
fts5SavedTokens = 0
|
|
461
|
+
} = {}) {
|
|
462
|
+
const sessionKey = String(sessionId || state?.sessionId || 'default');
|
|
463
|
+
const ws = ledger && typeof ledger.getWorkspaceSummary === 'function'
|
|
464
|
+
? ledger.getWorkspaceSummary({ sessionId: sessionKey, days: 30 })
|
|
465
|
+
: null;
|
|
466
|
+
const sessionLedger = ws?.session || null;
|
|
467
|
+
const workspaceLedger = ws?.workspace30d || null;
|
|
468
|
+
|
|
469
|
+
// 1. Deduplicated subagent context isolation
|
|
470
|
+
const rawInvocations = Array.isArray(state?.subagents?.invocations) ? state.subagents.invocations : [];
|
|
471
|
+
const seenSubIds = new Set();
|
|
472
|
+
let dedupedSubagentSaved = 0;
|
|
473
|
+
for (const inv of rawInvocations) {
|
|
474
|
+
const id = String(inv?.conversationId || inv?.id || '');
|
|
475
|
+
if (id && seenSubIds.has(id)) continue;
|
|
476
|
+
if (id) seenSubIds.add(id);
|
|
477
|
+
dedupedSubagentSaved += Math.max(0, Number(inv?.tokensSaved || 0));
|
|
478
|
+
}
|
|
479
|
+
if (dedupedSubagentSaved === 0 && rawInvocations.length === 0) {
|
|
480
|
+
dedupedSubagentSaved = Math.max(
|
|
481
|
+
0,
|
|
482
|
+
Number(state?.subagents?.totalSavedTokens ?? state?.subagents?.tokensSaved ?? 0)
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
const subagentIsolated = Math.max(
|
|
486
|
+
dedupedSubagentSaved,
|
|
487
|
+
Number(sessionLedger?.totalsByType?.SUBAGENT_ISOLATED || 0)
|
|
488
|
+
);
|
|
489
|
+
|
|
490
|
+
// 2. Warm KV prompt cache discount (defaults to 95% for Argon/Sonnet 5.5, or model-specific ratio) + avoided cold prefills
|
|
491
|
+
const cacheBlock = state?.quota?.cache || state?.cache || {};
|
|
492
|
+
const cacheReadTokens = Math.max(0, Number(cacheBlock.cacheReadTokens || 0));
|
|
493
|
+
const pricing = state?.model?.pricing || {};
|
|
494
|
+
const explicitDiscountRatio = Number(pricing.cacheReadDiscountRatio);
|
|
495
|
+
const derivedDiscountRatio =
|
|
496
|
+
Number(pricing.inputPer1M) > 0 && pricing.readPer1M !== undefined
|
|
497
|
+
? Math.max(0, Math.min(0.99, 1 - Number(pricing.readPer1M) / Number(pricing.inputPer1M)))
|
|
498
|
+
: NaN;
|
|
499
|
+
const discountRatio = Number.isFinite(explicitDiscountRatio) && explicitDiscountRatio > 0 && explicitDiscountRatio < 1
|
|
500
|
+
? explicitDiscountRatio
|
|
501
|
+
: (Number.isFinite(derivedDiscountRatio) ? derivedDiscountRatio : 0.95);
|
|
502
|
+
const cacheDiscountSaved = Math.round(cacheReadTokens * discountRatio);
|
|
503
|
+
const ledgerCacheHits = Math.max(0, Number(sessionLedger?.totalsByType?.CACHE_HIT_PRESERVED || 0));
|
|
504
|
+
const coldPrefillsSaved = Math.max(0, Number(sessionLedger?.totalsByType?.COLD_PREFILL_AVOIDED || 0));
|
|
505
|
+
const billingEquivalentCacheTokens = Math.max(cacheDiscountSaved, ledgerCacheHits);
|
|
506
|
+
const cachePreserved = billingEquivalentCacheTokens + coldPrefillsSaved;
|
|
507
|
+
|
|
508
|
+
// 3. CLI & log compression
|
|
509
|
+
const cliCompressed = Math.max(
|
|
510
|
+
0,
|
|
511
|
+
Number(state?.coachState?.fts5Compressor?.savedTokens || 0),
|
|
512
|
+
Number(sessionLedger?.totalsByType?.CLI_DUMP_COMPRESSED || 0)
|
|
513
|
+
);
|
|
514
|
+
|
|
515
|
+
// 4. Compaction & uncached tail trims
|
|
516
|
+
const liveCompactedDelta = state?.delta?.compacted && Number(state?.delta?.tokens) < 0
|
|
517
|
+
? Math.abs(Math.round(Number(state.delta.tokens)))
|
|
518
|
+
: 0;
|
|
519
|
+
const compactionReclaimed = Math.max(
|
|
520
|
+
liveCompactedDelta,
|
|
521
|
+
Number(sessionLedger?.totalsByType?.COMPACTION_RECLAIMED || 0)
|
|
522
|
+
);
|
|
523
|
+
|
|
524
|
+
// 5. Blocked retry loops, unmodified re-reads, effort downshifts & prompt hygiene interventions
|
|
525
|
+
const guardsPrevented =
|
|
526
|
+
Math.max(0, Number(sessionLedger?.totalsByType?.LOOP_TURN_PREVENTED || 0)) +
|
|
527
|
+
Math.max(0, Number(sessionLedger?.totalsByType?.EFFORT_DOWNSHIFT || 0)) +
|
|
528
|
+
Math.max(0, Number(sessionLedger?.totalsByType?.PROMPT_HYGIENE_STEERED || 0)) +
|
|
529
|
+
Math.max(0, Number(sessionLedger?.totalsByType?.PROMPT_HYGIENE_BLOCKED || 0)) +
|
|
530
|
+
Math.max(0, Number(sessionLedger?.totalsByType?.SIGHTSEEING_TOOL_PREVENTED || 0));
|
|
531
|
+
const avoidedBloat = compactionReclaimed + guardsPrevented;
|
|
532
|
+
|
|
533
|
+
const physicalTokensAvoided =
|
|
534
|
+
subagentIsolated +
|
|
535
|
+
coldPrefillsSaved +
|
|
536
|
+
cliCompressed +
|
|
537
|
+
compactionReclaimed +
|
|
538
|
+
guardsPrevented;
|
|
539
|
+
|
|
540
|
+
const sessionTotalTokens =
|
|
541
|
+
subagentIsolated +
|
|
542
|
+
cachePreserved +
|
|
543
|
+
cliCompressed +
|
|
544
|
+
compactionReclaimed +
|
|
545
|
+
guardsPrevented;
|
|
546
|
+
|
|
547
|
+
const inputRatePer1M = Math.max(0.1, Number(state?.model?.pricing?.inputPer1M || 2.0));
|
|
548
|
+
const sessionEstimatedUsd = Number(((sessionTotalTokens / 1_000_000) * inputRatePer1M).toFixed(4));
|
|
549
|
+
|
|
550
|
+
const nonSessionLedgerTokens = Math.max(
|
|
551
|
+
0,
|
|
552
|
+
Number(workspaceLedger?.totalTokens || 0) - Number(sessionLedger?.totalTokensSaved || 0)
|
|
553
|
+
);
|
|
554
|
+
const nonSessionLedgerDollars = Math.max(
|
|
555
|
+
0,
|
|
556
|
+
Number(workspaceLedger?.totalDollarsSaved || 0) - Number(sessionLedger?.totalDollarsSaved || 0)
|
|
557
|
+
);
|
|
558
|
+
const extraFts5Tokens = Math.max(
|
|
559
|
+
0,
|
|
560
|
+
Number(fts5SavedTokens || 0) - Number(workspaceLedger?.totalsByType?.CLI_DUMP_COMPRESSED || 0)
|
|
561
|
+
);
|
|
562
|
+
const extraFts5Usd = (extraFts5Tokens / 1_000_000) * inputRatePer1M;
|
|
563
|
+
const workspaceTotalTokens = Math.max(
|
|
564
|
+
sessionTotalTokens,
|
|
565
|
+
sessionTotalTokens + nonSessionLedgerTokens + extraFts5Tokens
|
|
566
|
+
);
|
|
567
|
+
const workspaceEstimatedUsd = Number(
|
|
568
|
+
Math.max(
|
|
569
|
+
(workspaceTotalTokens / 1_000_000) * inputRatePer1M,
|
|
570
|
+
sessionEstimatedUsd + nonSessionLedgerDollars + extraFts5Usd
|
|
571
|
+
).toFixed(4)
|
|
572
|
+
);
|
|
573
|
+
const baseSessionsCount = Number(workspaceLedger?.sessionsCount || 0);
|
|
574
|
+
const hasCurrentInLedger = Number(sessionLedger?.sessionsCount || 0) > 0;
|
|
575
|
+
const sessionsCount = Math.max(
|
|
576
|
+
sessionTotalTokens > 0 ? 1 : 0,
|
|
577
|
+
baseSessionsCount + (sessionTotalTokens > 0 && !hasCurrentInLedger ? 1 : 0)
|
|
578
|
+
);
|
|
579
|
+
|
|
580
|
+
return {
|
|
581
|
+
session: {
|
|
582
|
+
totalTokens: sessionTotalTokens,
|
|
583
|
+
totalPhysicalTokens: sessionTotalTokens,
|
|
584
|
+
physicalTokensAvoided,
|
|
585
|
+
billingEquivalentCacheTokens,
|
|
586
|
+
cacheDiscountRatio: discountRatio,
|
|
587
|
+
formattedTokens: formatTokensHuman(sessionTotalTokens),
|
|
588
|
+
estimatedUsd: sessionEstimatedUsd,
|
|
589
|
+
estimatedInputValueUsd: sessionEstimatedUsd,
|
|
590
|
+
formattedUsd: sessionEstimatedUsd === 0 ? '$0.00' : `$${sessionEstimatedUsd.toFixed(2)}`,
|
|
591
|
+
bySource: {
|
|
592
|
+
subagentIsolated,
|
|
593
|
+
subagentIsolation: subagentIsolated,
|
|
594
|
+
cachePreserved,
|
|
595
|
+
cachePreservation: cachePreserved,
|
|
596
|
+
cliCompressed,
|
|
597
|
+
cliCompression: cliCompressed,
|
|
598
|
+
compactionReclaimed,
|
|
599
|
+
guardsPrevented,
|
|
600
|
+
avoidedBloat
|
|
601
|
+
}
|
|
602
|
+
},
|
|
603
|
+
workspace30d: {
|
|
604
|
+
totalTokens: workspaceTotalTokens,
|
|
605
|
+
totalPhysicalTokens: workspaceTotalTokens,
|
|
606
|
+
formattedTokens: formatTokensHuman(workspaceTotalTokens),
|
|
607
|
+
estimatedUsd: workspaceEstimatedUsd,
|
|
608
|
+
estimatedInputValueUsd: workspaceEstimatedUsd,
|
|
609
|
+
formattedUsd: workspaceEstimatedUsd === 0 ? '$0.00' : `$${workspaceEstimatedUsd.toFixed(2)}`,
|
|
610
|
+
sessionsCount
|
|
611
|
+
}
|
|
612
|
+
};
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
export default SavedQuotaReceiptLedger;
|