ctxtop 0.0.0-stage → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +149 -0
  4. package/LICENSE +27 -0
  5. package/README.md +330 -3
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +145 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1474 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +114 -0
  25. package/config/modelCatalog.json +620 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +262 -0
  28. package/hooks/handlers/hookIo.mjs +255 -0
  29. package/hooks/handlers/hookIpcClient.mjs +83 -0
  30. package/hooks/handlers/post-tool-use.mjs +265 -0
  31. package/hooks/handlers/pre-model-switch.mjs +249 -0
  32. package/hooks/handlers/pre-tool-use.mjs +365 -0
  33. package/hooks/handlers/stop-gate.mjs +240 -0
  34. package/hooks/handlers/user-prompt-submit.mjs +143 -0
  35. package/hooks/hooks.json +81 -0
  36. package/hooks/post_invocation.mjs +13 -0
  37. package/hooks/post_tool_use.mjs +17 -0
  38. package/hooks/pre_invocation.mjs +14 -0
  39. package/hooks/pre_tool_use.mjs +97 -0
  40. package/hooks/register.js +687 -0
  41. package/hooks/session_start.mjs +14 -0
  42. package/hooks/stop.mjs +13 -0
  43. package/hooks.json +56 -0
  44. package/package.json +103 -4
  45. package/packages/antigravity/package.json +14 -0
  46. package/packages/antigravity/src/index.mjs +1 -0
  47. package/packages/claude-code/package.json +14 -0
  48. package/packages/claude-code/src/index.mjs +2 -0
  49. package/packages/core/package.json +14 -0
  50. package/packages/core/src/index.mjs +1 -0
  51. package/packages/engine-node/package.json +14 -0
  52. package/packages/engine-node/src/index.mjs +1 -0
  53. package/packages/mcp/package.json +17 -0
  54. package/packages/mcp/src/server.mjs +396 -0
  55. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  56. package/packages/pro/README-SIGNING.md +30 -0
  57. package/packages/pro/package.json +16 -0
  58. package/packages/pro/src/index.mjs +3 -0
  59. package/packages/pro/src/team_finops_pack.mjs +241 -0
  60. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  61. package/plugin.json +36 -0
  62. package/rules/AGENTS.md +10 -0
  63. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  64. package/sidecars/horizon-daemon/server.mjs +2002 -0
  65. package/sidecars/horizon-daemon/sidecar.json +19 -0
  66. package/skills/cost-radar/SKILL.md +21 -0
  67. package/skills/evolve/SKILL.md +21 -0
  68. package/skills/handoff/SKILL.md +42 -0
  69. package/skills/horizon/SKILL.md +17 -0
  70. package/skills/inspect/SKILL.md +18 -0
  71. package/skills/precheck/SKILL.md +44 -0
  72. package/src/adapters/antigravity/index.mjs +79 -0
  73. package/src/adapters/claude-code/index.mjs +155 -0
  74. package/src/cli/cost_radar.mjs +70 -0
  75. package/src/cli/doctor.mjs +351 -0
  76. package/src/cli/horizon_hud.mjs +686 -0
  77. package/src/cli/init.mjs +425 -0
  78. package/src/cli/postmortem.mjs +515 -0
  79. package/src/coach/cacheGravityRouter.mjs +12 -0
  80. package/src/config/modelCatalog.json +620 -0
  81. package/src/config/platformQuirks.json +19 -0
  82. package/src/core/action_queue.mjs +264 -0
  83. package/src/core/ag_bridge.mjs +346 -0
  84. package/src/core/atomic_io.mjs +124 -0
  85. package/src/core/baseline.mjs +607 -0
  86. package/src/core/blindspot_sensors.mjs +399 -0
  87. package/src/core/classifier.mjs +1757 -0
  88. package/src/core/coach/circuit_breakers.mjs +650 -0
  89. package/src/core/coach/contradiction_auditor.mjs +239 -0
  90. package/src/core/coach/effort_advisor.mjs +143 -0
  91. package/src/core/coach/handoff_hydrator.mjs +483 -0
  92. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  93. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  94. package/src/core/coach/reflector_queue.mjs +505 -0
  95. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  96. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  97. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  98. package/src/core/coach/task_quota_router.mjs +955 -0
  99. package/src/core/coach/turn_zero_gate.mjs +574 -0
  100. package/src/core/compaction_coach.mjs +1126 -0
  101. package/src/core/config.mjs +214 -0
  102. package/src/core/constants.mjs +1800 -0
  103. package/src/core/detectors_det01_to_16.mjs +1474 -0
  104. package/src/core/episodic_memory.mjs +135 -0
  105. package/src/core/fts5_output_compressor.mjs +359 -0
  106. package/src/core/git_ledger.mjs +189 -0
  107. package/src/core/handoff_audit.mjs +558 -0
  108. package/src/core/history.mjs +221 -0
  109. package/src/core/hook_diagnostics.mjs +158 -0
  110. package/src/core/horizon_classifier.mjs +326 -0
  111. package/src/core/horizon_config.mjs +802 -0
  112. package/src/core/host_watchdog.mjs +200 -0
  113. package/src/core/layer5_hygiene.mjs +966 -0
  114. package/src/core/log_resolver.mjs +231 -0
  115. package/src/core/mcp_auditor.mjs +138 -0
  116. package/src/core/micro_skills_store.mjs +91 -0
  117. package/src/core/offenders.mjs +161 -0
  118. package/src/core/parser.mjs +1996 -0
  119. package/src/core/path_canonicalizer.mjs +73 -0
  120. package/src/core/paths.mjs +310 -0
  121. package/src/core/prefix_cache_shield.mjs +386 -0
  122. package/src/core/pro_license.mjs +385 -0
  123. package/src/core/prompt_rubric.mjs +518 -0
  124. package/src/core/pruner.mjs +433 -0
  125. package/src/core/quota.mjs +1860 -0
  126. package/src/core/rsi_instinct_engine.mjs +1197 -0
  127. package/src/core/sanitizer.mjs +121 -0
  128. package/src/core/session_forensics.mjs +303 -0
  129. package/src/core/session_timeline.mjs +358 -0
  130. package/src/core/settings.mjs +99 -0
  131. package/src/core/shared/detectors.mjs +1342 -0
  132. package/src/core/shared/fnv1a64.mjs +85 -0
  133. package/src/core/shared/handoff_schema.mjs +123 -0
  134. package/src/core/shared/index.mjs +5 -0
  135. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  136. package/src/core/shared/micro_skills.mjs +1 -0
  137. package/src/core/shared/plugin_validator.mjs +202 -0
  138. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  139. package/src/core/sidecar_store.mjs +302 -0
  140. package/src/core/sprint_metrics.mjs +366 -0
  141. package/src/core/sqlite_client.mjs +283 -0
  142. package/src/core/storage_doctor.mjs +358 -0
  143. package/src/core/subagents.mjs +609 -0
  144. package/src/core/swarm_topology.mjs +360 -0
  145. package/src/core/task_quota_router.mjs +1656 -0
  146. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  147. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  148. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  149. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  150. package/src/core/timeline_svg.mjs +236 -0
  151. package/src/core/tool_surgeon.mjs +305 -0
  152. package/src/core/trajectory_stitcher.mjs +645 -0
  153. package/src/core/u_shaped_optimizer.mjs +789 -0
  154. package/src/core/wal_hygiene.mjs +233 -0
  155. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  156. package/src/core-isomorphic/catalog/index.mjs +1 -0
  157. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
  158. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  159. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  160. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  161. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  162. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  163. package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
  164. package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
  165. package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
  166. package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
  167. package/src/core-isomorphic/control/callTree.mjs +338 -0
  168. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  169. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  170. package/src/core-isomorphic/control/index.mjs +49 -0
  171. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  172. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  173. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  174. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  175. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  176. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
  177. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  178. package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
  179. package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
  180. package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
  181. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  182. package/src/core-isomorphic/economics/index.mjs +47 -0
  183. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  184. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  185. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
  186. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
  187. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
  188. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
  189. package/src/core-isomorphic/index.js +26 -0
  190. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  191. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  192. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  193. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  194. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
  195. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  196. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  197. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  198. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
  199. package/src/core-isomorphic/ui/modViews.mjs +1478 -0
  200. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  201. package/src/core-isomorphic/ustf/index.mjs +7 -0
  202. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  203. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  204. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  205. package/src/demo/synthetic_states.mjs +661 -0
  206. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  207. package/src/diagnostics/doctorEngine.mjs +203 -0
  208. package/src/engine-node/db/index.mjs +58 -0
  209. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  210. package/src/engine-node/db/probe.mjs +110 -0
  211. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  212. package/src/engine-node/index.mjs +9 -0
  213. package/src/engine-node/ipc/client.mjs +447 -0
  214. package/src/engine-node/ipc/index.mjs +22 -0
  215. package/src/engine-node/ipc/protocol.mjs +177 -0
  216. package/src/engine-node/ipc/server.mjs +445 -0
  217. package/src/engine-node/offloader/index.mjs +6 -0
  218. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  219. package/src/engine-node/sensors/blindspots.mjs +369 -0
  220. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  221. package/src/engine-node/sensors/index.mjs +7 -0
  222. package/src/hooks/portfolio_runtime.mjs +858 -0
  223. package/src/hooks/post_invocation.mjs +419 -0
  224. package/src/hooks/pre_invocation.mjs +1015 -0
  225. package/src/hooks/session_start.mjs +161 -0
  226. package/src/shims/agy_cli_compressor.mjs +705 -0
  227. package/src/shims/agy_git_guard.mjs +749 -0
  228. package/src/shims/ah_log_query.mjs +39 -0
  229. package/src/ui/costRadarSvg.mjs +6 -0
  230. package/src/ui/horizonGrid.mjs +1 -0
  231. package/src/ui/horizonPanelHtml.mjs +1 -0
  232. package/src/ui/horizon_panel.css +167 -0
  233. package/src/ui/horizon_panel.js +212 -0
  234. package/src/ui/modViews.mjs +1 -0
  235. package/src/utils/nodeIo.mjs +59 -0
  236. package/src/utils/runtime.mjs +1 -0
  237. package/src/webview/advanced_view.html +1808 -0
  238. package/src/webview/horizon_panel.html +11389 -0
  239. package/src/webview/registry.mjs +80 -0
  240. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,1132 @@
1
+ /**
2
+ * @file src/telemetry/telemetryBridge.mjs
3
+ * Dual-Source Telemetry Engine for Claude Code Highbeam.
4
+ * Ingests live token/cache telemetry from:
5
+ * 1. In-process Mod `turn.step` / `turn.complete` (`result.usage` + `e.agentId`)
6
+ * 2. CLI `statusLine` stdin JSON (`context_window`, `prompt_cache`, `rate_limits`)
7
+ * Never sums raw JSONL `usage.input_tokens` placeholders.
8
+ * Computes exact USD Cache ROI and persists atomic bridge snapshots to
9
+ * `.claude/cache/ah_live_state_<sessionId>.json`.
10
+ */
11
+
12
+ import { path, getCwd, writeJsonAtomic, readJsonSafe } from '../utils/runtime.mjs';
13
+ import {
14
+ normalizeModelId,
15
+ resolveCustomCeilingForModel,
16
+ extractNormalizedTokenBreakdown,
17
+ computeTotalPromptTokens,
18
+ resolveEffectiveRates,
19
+ calculateTurnCostUSD
20
+ } from '../config/catalogLoader.mjs';
21
+ import { exportOtelTelemetry } from './otelExporter.mjs';
22
+ import { applySubagentLifecycle } from './swarmTopology.mjs';
23
+ import {
24
+ createInitialPrefixRetention,
25
+ createInitialThinkingDrift,
26
+ applyPrefixRetentionRequest,
27
+ applyThinkingDriftEvent
28
+ } from './sprintMetrics.mjs';
29
+
30
+ export const SESSION_FIVE_MIN_ROI_TARGET = 1.39;
31
+
32
+ /**
33
+ * Computes dynamic single-write USD break-even read/write ratio `(mWrite - 1) / (1 - mRead)`
34
+ * from model rate multipliers, weighting 5m and 1h writes when both are present (`ISS-006`).
35
+ *
36
+ * @param {object} rates
37
+ * @param {number} [write5mTokens=0]
38
+ * @param {number} [write1hTokens=0]
39
+ * @param {'5m'|'1h'} [ttlTier='5m']
40
+ * @returns {number}
41
+ */
42
+ function computeBreakEvenRatioFromRates(
43
+ rates,
44
+ write5mTokens = 0,
45
+ write1hTokens = 0,
46
+ ttlTier = '5m'
47
+ ) {
48
+ const mults = rates?.multipliers || { write5m: 1.25, write1h: 2.0, read: 0.05 };
49
+ const w5 = Math.max(0, Number(write5mTokens || 0));
50
+ const w1 = Math.max(0, Number(write1hTokens || 0));
51
+ const totalW = w5 + w1;
52
+ const mWrite =
53
+ totalW > 0
54
+ ? (w5 * mults.write5m + w1 * mults.write1h) / totalW
55
+ : ttlTier === '1h'
56
+ ? mults.write1h
57
+ : mults.write5m;
58
+ const mRead = Number(mults.read ?? 0.05);
59
+ const denom = 1 - mRead;
60
+ if (denom <= 0) return Infinity;
61
+ return Number((Math.max(0, mWrite - 1) / denom).toFixed(3));
62
+ }
63
+
64
+ /**
65
+ * Sanitizes a session ID for safe filesystem paths.
66
+ * @param {string} [sessionId='default']
67
+ * @returns {string}
68
+ */
69
+ export function sanitizeSessionId(sessionId = 'default') {
70
+ const cleaned = String(sessionId || 'default')
71
+ .trim()
72
+ .replace(/[^a-zA-Z0-9_-]/g, '_');
73
+ return cleaned || 'default';
74
+ }
75
+
76
+ /**
77
+ * Resolves the atomic bridge file path `.claude/cache/ah_live_state_<sessionId>.json`.
78
+ * @param {string} [sessionId='default']
79
+ * @param {object} [options={}]
80
+ * @returns {string}
81
+ */
82
+ export function getLiveStateBridgePath(sessionId = 'default', options = {}) {
83
+ const cwd = getCwd(options);
84
+ const safeId = sanitizeSessionId(sessionId);
85
+ return path.join(cwd, '.claude', 'cache', `ah_live_state_${safeId}.json`);
86
+ }
87
+
88
+ /**
89
+ * Computes exact USD Cache ROI and break-even read/write ratio for a model and token distribution.
90
+ * Flags Negative Cache ROI strictly when `ActualCacheSpendUSD > UncachedEquivalentUSD`
91
+ * (i.e. `reads / write < (M_write - 1) / (1 - M_read)`, which is `0.263` for 5m Opus/Sonnet 5.5
92
+ * and `1.053` for 1h writes).
93
+ *
94
+ * @param {object} [params={}]
95
+ * @param {string} [params.model='claude-sonnet-5-5']
96
+ * @param {number} [params.cacheWriteTokens=0]
97
+ * @param {number} [params.cacheWrite5mTokens=0]
98
+ * @param {number} [params.cacheWrite1hTokens=0]
99
+ * @param {number} [params.cacheReadTokens=0]
100
+ * @param {number} [params.uncachedInputTokens=0]
101
+ * @param {number} [params.outputTokens=0]
102
+ * @param {number} [params.thinkingTokens=0]
103
+ * @param {number} [params.totalPromptTokens]
104
+ * @param {'5m'|'1h'} [params.cacheTtlTier='5m']
105
+ * @param {object} [options={}]
106
+ */
107
+ export function computeCacheRoi(params = {}, options = {}) {
108
+ const ttlTier = params.cacheTtlTier === '1h' ? '1h' : '5m';
109
+ const turnCalc = calculateTurnCostUSD(
110
+ {
111
+ ...params,
112
+ model: params.model || 'claude-sonnet-5-5',
113
+ inputTokens:
114
+ params.uncachedInputTokens ?? params.freshInputTokens ?? params.inputTokens ?? params.input_tokens ?? 0,
115
+ outputTokens: params.outputTokens ?? params.output_tokens ?? 0,
116
+ thinkingTokens: params.thinkingTokens ?? params.thinking_tokens ?? 0,
117
+ cacheWriteTokens:
118
+ params.cacheWriteTokens ?? params.cacheCreationInputTokens ?? params.cache_creation_input_tokens ?? 0,
119
+ cacheWrite5mTokens: params.cacheWrite5mTokens ?? params.cache_write_5m_tokens ?? 0,
120
+ cacheWrite1hTokens: params.cacheWrite1hTokens ?? params.cache_write_1h_tokens ?? 0,
121
+ cacheReadTokens:
122
+ params.cacheReadTokens ?? params.cacheReadInputTokens ?? params.cache_read_input_tokens ?? 0,
123
+ totalPromptTokens: params.totalPromptTokens,
124
+ cacheTtlTier: ttlTier
125
+ },
126
+ options
127
+ );
128
+
129
+ const rates = turnCalc.rates;
130
+ const { cacheWrite5m, cacheWrite1h, totalCacheWrite, cacheRead, uncachedInput, totalPrompt } =
131
+ turnCalc.tokens;
132
+ const {
133
+ actualCacheSpendUSD,
134
+ uncachedCacheEquivalentUSD,
135
+ totalActualSpendUSD,
136
+ totalUncachedEquivalentUSD,
137
+ netCacheSavingsUSD
138
+ } = turnCalc.costsUSD;
139
+
140
+ const breakEvenReadsPerWrite = computeBreakEvenRatioFromRates(
141
+ rates,
142
+ cacheWrite5m,
143
+ cacheWrite1h,
144
+ ttlTier
145
+ );
146
+
147
+ const readsPerWriteRatio =
148
+ totalCacheWrite > 0
149
+ ? Number((cacheRead / totalCacheWrite).toFixed(4))
150
+ : cacheRead > 0
151
+ ? Infinity
152
+ : 0;
153
+
154
+ const negativeCacheRoi = Boolean(
155
+ totalCacheWrite > 0 && actualCacheSpendUSD > uncachedCacheEquivalentUSD + 1e-9
156
+ );
157
+
158
+ const cacheHitRatio =
159
+ totalPrompt > 0 ? Number((cacheRead / totalPrompt).toFixed(4)) : 0;
160
+
161
+ return {
162
+ modelId: rates.modelId,
163
+ cacheTtlTier: ttlTier,
164
+ actualCacheSpendUSD,
165
+ actualSpendUSD: actualCacheSpendUSD,
166
+ uncachedEquivalentUSD: uncachedCacheEquivalentUSD,
167
+ uncachedBaselineUSD: uncachedCacheEquivalentUSD,
168
+ totalActualSpendUSD,
169
+ totalUncachedEquivalentUSD,
170
+ netCacheSavingsUSD,
171
+ negativeCacheRoi,
172
+ readsPerWriteRatio,
173
+ breakEvenReadsPerWrite,
174
+ sessionFiveMinRoiTarget: SESSION_FIVE_MIN_ROI_TARGET,
175
+ cacheHitRatio,
176
+ cliffTriggered: rates.cliffTriggered,
177
+ preCliffWarningTriggered: rates.preCliffWarningTriggered,
178
+ tokens: {
179
+ uncachedInput,
180
+ cacheWrite: totalCacheWrite,
181
+ cacheRead,
182
+ totalPrompt
183
+ }
184
+ };
185
+ }
186
+
187
+ /**
188
+ * Computes session-wide Cache ROI directly from accumulated per-turn USD spend in `state.cumulative`,
189
+ * never retroactively re-pricing multi-turn cumulative token sums against single-turn 5x cliffs (`ISS-003`).
190
+ *
191
+ * @param {object} state
192
+ * @param {object} currentRates
193
+ * @returns {object}
194
+ */
195
+ function buildCumulativeCacheRoi(state, currentRates) {
196
+ const ttlTier = state.promptCache?.ttlTier === '1h' ? '1h' : '5m';
197
+ const cum = state.cumulative || {};
198
+ const write5m = Math.max(0, Number(cum.cacheWrite5mTokens || 0));
199
+ const write1h = Math.max(0, Number(cum.cacheWrite1hTokens || 0));
200
+ const totalCacheWrite = write5m + write1h;
201
+ const cacheRead = Math.max(0, Number(cum.cacheReadTokens || 0));
202
+ const uncachedInput = Math.max(0, Number(cum.uncachedInputTokens || 0));
203
+ const totalPrompt = uncachedInput + totalCacheWrite + cacheRead;
204
+
205
+ const actualCacheSpendUSD = Number((cum.actualCacheSpendUSD || 0).toFixed(6));
206
+ const uncachedEquivalentUSD = Number(
207
+ (cum.uncachedEquivalentUSD ?? cum.uncachedBaselineUSD ?? 0).toFixed(6)
208
+ );
209
+ const totalActualSpendUSD = Number((cum.totalActualSpendUSD || 0).toFixed(6));
210
+ const totalUncachedEquivalentUSD = Number((cum.totalUncachedEquivalentUSD || 0).toFixed(6));
211
+ const netCacheSavingsUSD = Number((uncachedEquivalentUSD - actualCacheSpendUSD).toFixed(6));
212
+
213
+ const breakEvenReadsPerWrite = computeBreakEvenRatioFromRates(
214
+ currentRates,
215
+ write5m,
216
+ write1h,
217
+ ttlTier
218
+ );
219
+ const readsPerWriteRatio =
220
+ totalCacheWrite > 0
221
+ ? Number((cacheRead / totalCacheWrite).toFixed(4))
222
+ : cacheRead > 0
223
+ ? Infinity
224
+ : 0;
225
+ const negativeCacheRoi = Boolean(
226
+ totalCacheWrite > 0 && actualCacheSpendUSD > uncachedEquivalentUSD + 1e-9
227
+ );
228
+ const cacheHitRatio =
229
+ totalPrompt > 0 ? Number((cacheRead / totalPrompt).toFixed(4)) : 0;
230
+
231
+ return {
232
+ modelId: currentRates.modelId,
233
+ cacheTtlTier: ttlTier,
234
+ actualCacheSpendUSD,
235
+ actualSpendUSD: actualCacheSpendUSD,
236
+ uncachedEquivalentUSD,
237
+ uncachedBaselineUSD: uncachedEquivalentUSD,
238
+ totalActualSpendUSD,
239
+ totalUncachedEquivalentUSD,
240
+ netCacheSavingsUSD,
241
+ negativeCacheRoi,
242
+ readsPerWriteRatio,
243
+ breakEvenReadsPerWrite,
244
+ sessionFiveMinRoiTarget: SESSION_FIVE_MIN_ROI_TARGET,
245
+ cacheHitRatio,
246
+ cliffTriggered: Boolean(currentRates.cliffTriggered),
247
+ preCliffWarningTriggered: Boolean(currentRates.preCliffWarningTriggered),
248
+ tokens: {
249
+ uncachedInput,
250
+ cacheWrite: totalCacheWrite,
251
+ cacheRead,
252
+ totalPrompt
253
+ }
254
+ };
255
+ }
256
+
257
+ /**
258
+ * Adds a single turn's (or positive step delta's) priced token & USD breakdown into `state.cumulative`.
259
+ * @param {object} cumulative
260
+ * @param {object} turnCost
261
+ */
262
+ function addTurnCostToCumulative(cumulative, turnCost) {
263
+ const { uncachedInput, cacheWrite5m, cacheWrite1h, cacheRead, output, thinking } =
264
+ turnCost.tokens;
265
+ const {
266
+ actualCacheSpendUSD,
267
+ uncachedCacheEquivalentUSD,
268
+ totalActualSpendUSD,
269
+ totalUncachedEquivalentUSD
270
+ } = turnCost.costsUSD;
271
+
272
+ cumulative.uncachedInputTokens += uncachedInput;
273
+ cumulative.cacheWrite5mTokens += cacheWrite5m;
274
+ cumulative.cacheWrite1hTokens += cacheWrite1h;
275
+ cumulative.cacheReadTokens += cacheRead;
276
+ cumulative.outputTokens += output;
277
+ cumulative.thinkingTokens += thinking;
278
+ cumulative.actualCacheSpendUSD = Number(
279
+ (cumulative.actualCacheSpendUSD + actualCacheSpendUSD).toFixed(6)
280
+ );
281
+ cumulative.uncachedEquivalentUSD = Number(
282
+ (cumulative.uncachedEquivalentUSD + uncachedCacheEquivalentUSD).toFixed(6)
283
+ );
284
+ cumulative.uncachedBaselineUSD = cumulative.uncachedEquivalentUSD;
285
+ cumulative.totalActualSpendUSD = Number(
286
+ (cumulative.totalActualSpendUSD + totalActualSpendUSD).toFixed(6)
287
+ );
288
+ cumulative.totalUncachedEquivalentUSD = Number(
289
+ (cumulative.totalUncachedEquivalentUSD + totalUncachedEquivalentUSD).toFixed(6)
290
+ );
291
+ cumulative.netCacheSavingsUSD = Number(
292
+ (cumulative.uncachedEquivalentUSD - cumulative.actualCacheSpendUSD).toFixed(6)
293
+ );
294
+ }
295
+
296
+ /**
297
+ * Creates a clean initial session telemetry state object.
298
+ * @param {string} [sessionId='default']
299
+ * @param {string} [model='claude-sonnet-5-5']
300
+ * @returns {object}
301
+ */
302
+ export function createInitialTelemetryState(sessionId = 'default', model = 'claude-sonnet-5-5') {
303
+ const normModel = normalizeModelId(model);
304
+ const rates = resolveEffectiveRates(model, 0);
305
+ const initialBreakEven = computeBreakEvenRatioFromRates(rates, 0, 0, '5m');
306
+ return {
307
+ schemaVersion: '2026.11.1',
308
+ sessionId: sanitizeSessionId(sessionId),
309
+ modelId: normModel,
310
+ rawModelId: String(model || normModel),
311
+ modelLabel: rates.label,
312
+ contextCeiling: rates.contextCeiling,
313
+ steps: 0,
314
+ turnsCompleted: 0,
315
+ lastUpdatedAt: Date.now(),
316
+ lastSource: 'init',
317
+ lastAgentId: null,
318
+ contextWindow: {
319
+ totalInputTokens: 0,
320
+ uncachedInputTokens: 0,
321
+ cachedTokens: 0,
322
+ cacheReadTokens: 0,
323
+ cacheWriteTokens: 0,
324
+ warmPrefixTokens: 0,
325
+ lastWriteTokens: 0,
326
+ lastOutputTokens: 0,
327
+ lastThinkingTokens: 0,
328
+ systemAndMcpTokens: 0,
329
+ distractorTokens: 0,
330
+ customCeiling: null,
331
+ contextCeiling: rates.contextCeiling
332
+ },
333
+ cumulative: {
334
+ uncachedInputTokens: 0,
335
+ cacheWrite5mTokens: 0,
336
+ cacheWrite1hTokens: 0,
337
+ cacheReadTokens: 0,
338
+ outputTokens: 0,
339
+ thinkingTokens: 0,
340
+ actualCacheSpendUSD: 0,
341
+ uncachedEquivalentUSD: 0,
342
+ uncachedBaselineUSD: 0,
343
+ totalActualSpendUSD: 0,
344
+ totalUncachedEquivalentUSD: 0,
345
+ netCacheSavingsUSD: 0
346
+ },
347
+ promptCache: {
348
+ warm: false,
349
+ ttlTier: '5m',
350
+ ttlSeconds: 300,
351
+ expiresAt: null,
352
+ lastMissCause: null
353
+ },
354
+ cacheRoi: {
355
+ actualCacheSpendUSD: 0,
356
+ actualSpendUSD: 0,
357
+ uncachedEquivalentUSD: 0,
358
+ uncachedBaselineUSD: 0,
359
+ netCacheSavingsUSD: 0,
360
+ negativeCacheRoi: false,
361
+ readsPerWriteRatio: 0,
362
+ breakEvenReadsPerWrite: initialBreakEven,
363
+ sessionFiveMinRoiTarget: SESSION_FIVE_MIN_ROI_TARGET,
364
+ cacheHitRatio: 0
365
+ },
366
+ rateLimits: {
367
+ fiveHour: null,
368
+ sevenDay: null,
369
+ spendLimit: null
370
+ },
371
+ subagents: {},
372
+ inFlightTurn: null,
373
+ subagentInFlightTurns: {},
374
+ lastCompletedTurnId: null,
375
+ lastStatusTurnId: null,
376
+ lastReportedStatusCostUSD: null,
377
+ lastStatusLineEnvelopeSig: null,
378
+ cliffTriggered: false,
379
+ preCliffWarningTriggered: false,
380
+ prefixRetention: createInitialPrefixRetention(),
381
+ thinkingDrift: createInitialThinkingDrift(),
382
+ lastTurn: null
383
+ };
384
+ }
385
+
386
+ /**
387
+ * Normalizes a TTL value from `statusLine` or Mod payload into `{ ttlTier: '5m'|'1h', ttlSeconds: number }`.
388
+ * Explicit `0` / `'0s'` / negative values return `ttlSeconds: 0` (`ISS-027`).
389
+ * @param {string|number|undefined} rawTtl
390
+ * @returns {{ ttlTier: '5m'|'1h', ttlSeconds: number }}
391
+ */
392
+ function parseTtlInfo(rawTtl) {
393
+ if (rawTtl === 0 || rawTtl === '0' || rawTtl === '0s' || (typeof rawTtl === 'number' && rawTtl <= 0)) {
394
+ return { ttlTier: '5m', ttlSeconds: 0 };
395
+ }
396
+ if (typeof rawTtl === 'string') {
397
+ const trimmed = rawTtl.trim().toLowerCase();
398
+ if (trimmed === '1h') return { ttlTier: '1h', ttlSeconds: 3600 };
399
+ if (trimmed === '5m') return { ttlTier: '5m', ttlSeconds: 300 };
400
+ const secMatch = trimmed.match(/^(-?\d+(?:\.\d+)?)s?$/);
401
+ if (secMatch) {
402
+ const parsedSec = Number(secMatch[1]);
403
+ if (parsedSec <= 0) return { ttlTier: '5m', ttlSeconds: 0 };
404
+ if (parsedSec > 300) return { ttlTier: '1h', ttlSeconds: parsedSec };
405
+ return { ttlTier: '5m', ttlSeconds: parsedSec };
406
+ }
407
+ }
408
+ if (Number(rawTtl) > 300) {
409
+ return {
410
+ ttlTier: '1h',
411
+ ttlSeconds: typeof rawTtl === 'number' ? rawTtl : 3600
412
+ };
413
+ }
414
+ return {
415
+ ttlTier: '5m',
416
+ ttlSeconds: typeof rawTtl === 'number' && rawTtl > 0 ? rawTtl : 300
417
+ };
418
+ }
419
+
420
+ /**
421
+ * Normalizes `expires_at` (ISO string or epoch ms/seconds) to epoch milliseconds.
422
+ * @param {string|number|null|undefined} rawExpiresAt
423
+ * @param {number} fallbackNowMs
424
+ * @param {number} ttlSeconds
425
+ * @param {boolean} isWarm
426
+ * @returns {number | null}
427
+ */
428
+ function normalizeExpiresAtMs(rawExpiresAt, fallbackNowMs, ttlSeconds, isWarm) {
429
+ if (typeof rawExpiresAt === 'number' && Number.isFinite(rawExpiresAt)) {
430
+ return rawExpiresAt < 1e11 ? rawExpiresAt * 1000 : rawExpiresAt;
431
+ }
432
+ if (typeof rawExpiresAt === 'string' && rawExpiresAt.trim()) {
433
+ const parsed = Date.parse(rawExpiresAt);
434
+ if (!Number.isNaN(parsed)) return parsed;
435
+ }
436
+ if (isWarm && ttlSeconds > 0) {
437
+ return fallbackNowMs + ttlSeconds * 1000;
438
+ }
439
+ return null;
440
+ }
441
+
442
+ /**
443
+ * Computes strictly non-negative token delta between two token breakdown snapshots (`ISS-027`).
444
+ * @param {object} current
445
+ * @param {object} baseline
446
+ */
447
+ function computePositiveTokenDelta(current, baseline) {
448
+ if (!baseline) return { ...current };
449
+ return {
450
+ uncachedInputTokens: Math.max(
451
+ 0,
452
+ current.uncachedInputTokens - (baseline.uncachedInputTokens || 0)
453
+ ),
454
+ effectiveWrite5mTokens: Math.max(
455
+ 0,
456
+ current.effectiveWrite5mTokens - (baseline.effectiveWrite5mTokens || 0)
457
+ ),
458
+ effectiveWrite1hTokens: Math.max(
459
+ 0,
460
+ current.effectiveWrite1hTokens - (baseline.effectiveWrite1hTokens || 0)
461
+ ),
462
+ cacheReadTokens: Math.max(0, current.cacheReadTokens - (baseline.cacheReadTokens || 0)),
463
+ outputTokens: Math.max(0, current.outputTokens - (baseline.outputTokens || 0)),
464
+ thinkingTokens: Math.max(0, current.thinkingTokens - (baseline.thinkingTokens || 0))
465
+ };
466
+ }
467
+
468
+ function hasAnyPositiveTokens(delta) {
469
+ return (
470
+ delta.uncachedInputTokens +
471
+ delta.effectiveWrite5mTokens +
472
+ delta.effectiveWrite1hTokens +
473
+ delta.cacheReadTokens +
474
+ delta.outputTokens +
475
+ delta.thinkingTokens >
476
+ 0
477
+ );
478
+ }
479
+
480
+ /**
481
+ * Ingests a Mod `turn.step` or `turn.complete` event into the session telemetry state.
482
+ * Deduplicates `turn.step` + `turn.complete` per turn so `state.cumulative` commits 1x,
483
+ * and isolates subagent turns from overwriting the main `state.contextWindow` (`ISS-027`).
484
+ *
485
+ * @param {object} currentState
486
+ * @param {object} event
487
+ * @param {object} [options={}]
488
+ * @returns {object} Updated state
489
+ */
490
+ export function ingestModTurnEvent(currentState, event = {}, options = {}) {
491
+ const nowMs = options.nowMs || Date.now();
492
+ const sessionId = event.sessionId || event.session_id || currentState?.sessionId || 'default';
493
+ const rawEventModel = event.model || event.result?.model || null;
494
+ const fallbackModel = currentState?.rawModelId || currentState?.modelId || 'claude-sonnet-5-5';
495
+ const state = currentState
496
+ ? JSON.parse(JSON.stringify(currentState))
497
+ : createInitialTelemetryState(sessionId, rawEventModel || fallbackModel);
498
+
499
+ state.sessionId = sanitizeSessionId(sessionId);
500
+ state.lastUpdatedAt = nowMs;
501
+ state.lastSource = event.type === 'turn.complete' ? 'mod.turn.complete' : 'mod.turn.step';
502
+ if (!state.subagentInFlightTurns || typeof state.subagentInFlightTurns !== 'object') {
503
+ state.subagentInFlightTurns = {};
504
+ }
505
+
506
+ const subagentId =
507
+ event.subagentId ||
508
+ event.subagent_id ||
509
+ (event.agentId && event.agentId !== 'main' ? event.agentId : null) ||
510
+ (event.agent_id && event.agent_id !== 'main' ? event.agent_id : null) ||
511
+ null;
512
+ const isSubagent = Boolean(
513
+ event.isSubagent || subagentId || event.parentSessionId || event.parent_session_id
514
+ );
515
+ const agentKey = isSubagent
516
+ ? subagentId || String(event.parentSessionId || event.parent_session_id || 'subagent')
517
+ : null;
518
+ state.lastAgentId = agentKey;
519
+
520
+ const turnId = event.turnId || event.turn_id || event.result?.turn_id || null;
521
+ const messageId =
522
+ event.messageId ||
523
+ event.message_id ||
524
+ event.message?.id ||
525
+ event.result?.id ||
526
+ event.result?.message?.id ||
527
+ null;
528
+
529
+ if (!isSubagent && event.type === 'turn.complete' && turnId && state.lastCompletedTurnId === turnId) {
530
+ return state;
531
+ }
532
+
533
+ const effectiveTurnModelRaw = isSubagent
534
+ ? rawEventModel || fallbackModel
535
+ : rawEventModel || fallbackModel;
536
+
537
+ if (!isSubagent && rawEventModel) {
538
+ state.rawModelId = String(rawEventModel);
539
+ state.modelId = normalizeModelId(rawEventModel);
540
+ }
541
+
542
+ const usage = event.result?.usage || event.usage || null;
543
+ if (!usage) {
544
+ if (event.type === 'turn.complete') {
545
+ if (!isSubagent) {
546
+ state.turnsCompleted += 1;
547
+ state.inFlightTurn = null;
548
+ if (turnId) state.lastCompletedTurnId = turnId;
549
+ } else if (agentKey) {
550
+ delete state.subagentInFlightTurns[agentKey];
551
+ if (state.subagents && state.subagents[agentKey]) {
552
+ applySubagentLifecycle(state.subagents[agentKey], event, { nowMs, eventType: 'turn.complete' });
553
+ }
554
+ }
555
+ }
556
+ return state;
557
+ }
558
+
559
+ const ttlTier = state.promptCache?.ttlTier === '1h' ? '1h' : '5m';
560
+ const breakdown = extractNormalizedTokenBreakdown({ ...usage, cacheTtlTier: ttlTier });
561
+ const uncachedInput = breakdown.uncachedInputTokens;
562
+ const write5mTokens = breakdown.effectiveWrite5mTokens;
563
+ const write1hTokens = breakdown.effectiveWrite1hTokens;
564
+ const totalWriteTokens = breakdown.totalCacheWriteTokens;
565
+ const cacheReadTokens = breakdown.cacheReadTokens;
566
+ const outputTokens = breakdown.outputTokens;
567
+ const thinkingTokens = breakdown.thinkingTokens;
568
+ const totalPromptTokens = uncachedInput + totalWriteTokens + cacheReadTokens;
569
+
570
+ // Determine in-flight turn tracker (main vs isolated subagent) to prevent 2x double-counting
571
+ const activeTracker = isSubagent
572
+ ? state.subagentInFlightTurns[agentKey] || null
573
+ : state.inFlightTurn || null;
574
+
575
+ const sameTurn =
576
+ activeTracker &&
577
+ (!turnId || !activeTracker.turnId || turnId === activeTracker.turnId);
578
+
579
+ let deltaBreakdown = breakdown;
580
+ if (event.type === 'turn.complete') {
581
+ if (sameTurn) {
582
+ const compareBaseline =
583
+ messageId && activeTracker.lastMessageId && messageId === activeTracker.lastMessageId
584
+ ? activeTracker.lastStepTokens
585
+ : activeTracker.committedTokens;
586
+ deltaBreakdown = computePositiveTokenDelta(breakdown, compareBaseline);
587
+ }
588
+ if (isSubagent) {
589
+ delete state.subagentInFlightTurns[agentKey];
590
+ } else {
591
+ state.inFlightTurn = null;
592
+ if (turnId) state.lastCompletedTurnId = turnId;
593
+ }
594
+ } else {
595
+ // turn.step
596
+ state.steps += 1;
597
+ let updatedTracker;
598
+ if (sameTurn) {
599
+ if (messageId && activeTracker.lastMessageId && messageId === activeTracker.lastMessageId) {
600
+ // Streaming chunk update for the same message.id
601
+ deltaBreakdown = computePositiveTokenDelta(breakdown, activeTracker.lastStepTokens);
602
+ updatedTracker = {
603
+ turnId: turnId || activeTracker.turnId || null,
604
+ lastMessageId: messageId,
605
+ lastStepTokens: { ...breakdown },
606
+ committedTokens: {
607
+ uncachedInputTokens:
608
+ activeTracker.committedTokens.uncachedInputTokens + deltaBreakdown.uncachedInputTokens,
609
+ effectiveWrite5mTokens:
610
+ activeTracker.committedTokens.effectiveWrite5mTokens +
611
+ deltaBreakdown.effectiveWrite5mTokens,
612
+ effectiveWrite1hTokens:
613
+ activeTracker.committedTokens.effectiveWrite1hTokens +
614
+ deltaBreakdown.effectiveWrite1hTokens,
615
+ cacheReadTokens:
616
+ activeTracker.committedTokens.cacheReadTokens + deltaBreakdown.cacheReadTokens,
617
+ outputTokens: activeTracker.committedTokens.outputTokens + deltaBreakdown.outputTokens,
618
+ thinkingTokens:
619
+ activeTracker.committedTokens.thinkingTokens + deltaBreakdown.thinkingTokens
620
+ }
621
+ };
622
+ } else {
623
+ // Distinct step within the same open turn
624
+ deltaBreakdown = { ...breakdown };
625
+ updatedTracker = {
626
+ turnId: turnId || activeTracker.turnId || null,
627
+ lastMessageId: messageId || activeTracker.lastMessageId || null,
628
+ lastStepTokens: { ...breakdown },
629
+ committedTokens: {
630
+ uncachedInputTokens:
631
+ activeTracker.committedTokens.uncachedInputTokens + breakdown.uncachedInputTokens,
632
+ effectiveWrite5mTokens:
633
+ activeTracker.committedTokens.effectiveWrite5mTokens + breakdown.effectiveWrite5mTokens,
634
+ effectiveWrite1hTokens:
635
+ activeTracker.committedTokens.effectiveWrite1hTokens + breakdown.effectiveWrite1hTokens,
636
+ cacheReadTokens:
637
+ activeTracker.committedTokens.cacheReadTokens + breakdown.cacheReadTokens,
638
+ outputTokens: activeTracker.committedTokens.outputTokens + breakdown.outputTokens,
639
+ thinkingTokens: activeTracker.committedTokens.thinkingTokens + breakdown.thinkingTokens
640
+ }
641
+ };
642
+ }
643
+ } else {
644
+ deltaBreakdown = { ...breakdown };
645
+ updatedTracker = {
646
+ turnId: turnId || null,
647
+ lastMessageId: messageId || null,
648
+ lastStepTokens: { ...breakdown },
649
+ committedTokens: { ...breakdown }
650
+ };
651
+ }
652
+
653
+ if (isSubagent) {
654
+ state.subagentInFlightTurns[agentKey] = updatedTracker;
655
+ } else {
656
+ state.inFlightTurn = updatedTracker;
657
+ }
658
+ }
659
+
660
+ // Subagent attribution (`ISS-027`: never overwrite main contextWindow, even if main is 0!)
661
+ if (isSubagent && agentKey) {
662
+ const existingSub = state.subagents[agentKey] || {
663
+ agentId: agentKey,
664
+ turns: 0,
665
+ totalInputTokens: 0,
666
+ totalOutputTokens: 0,
667
+ totalTokens: 0,
668
+ lastActiveAt: nowMs
669
+ };
670
+ const deltaSubPrompt =
671
+ deltaBreakdown.uncachedInputTokens +
672
+ deltaBreakdown.effectiveWrite5mTokens +
673
+ deltaBreakdown.effectiveWrite1hTokens +
674
+ deltaBreakdown.cacheReadTokens;
675
+ const deltaSubOut = deltaBreakdown.outputTokens + deltaBreakdown.thinkingTokens;
676
+ if (!sameTurn || event.type !== 'turn.complete') {
677
+ existingSub.turns += 1;
678
+ }
679
+ existingSub.totalInputTokens += deltaSubPrompt;
680
+ existingSub.totalOutputTokens += deltaSubOut;
681
+ existingSub.totalTokens = existingSub.totalInputTokens + existingSub.totalOutputTokens;
682
+ existingSub.lastActiveAt = nowMs;
683
+ applySubagentLifecycle(existingSub, event, { nowMs, eventType: event.type });
684
+ state.subagents[agentKey] = existingSub;
685
+ }
686
+
687
+ // Full single-turn cost snapshot for `lastTurn` and main window metadata
688
+ const fullTurnCost = calculateTurnCostUSD(
689
+ {
690
+ model: effectiveTurnModelRaw,
691
+ inputTokens: uncachedInput,
692
+ outputTokens,
693
+ thinkingTokens,
694
+ cacheWrite5mTokens: write5mTokens,
695
+ cacheWrite1hTokens: write1hTokens,
696
+ cacheReadTokens,
697
+ turnPromptTokens: totalPromptTokens,
698
+ cacheTtlTier: ttlTier
699
+ },
700
+ options
701
+ );
702
+
703
+ // Delta cost committed to `state.cumulative` (priced at this turn's `totalPromptTokens` cliff tier)
704
+ if (hasAnyPositiveTokens(deltaBreakdown)) {
705
+ const deltaTurnCost = calculateTurnCostUSD(
706
+ {
707
+ model: effectiveTurnModelRaw,
708
+ inputTokens: deltaBreakdown.uncachedInputTokens,
709
+ outputTokens: deltaBreakdown.outputTokens,
710
+ thinkingTokens: deltaBreakdown.thinkingTokens,
711
+ cacheWrite5mTokens: deltaBreakdown.effectiveWrite5mTokens,
712
+ cacheWrite1hTokens: deltaBreakdown.effectiveWrite1hTokens,
713
+ cacheReadTokens: deltaBreakdown.cacheReadTokens,
714
+ turnPromptTokens: totalPromptTokens,
715
+ cacheTtlTier: ttlTier
716
+ },
717
+ options
718
+ );
719
+ addTurnCostToCumulative(state.cumulative, deltaTurnCost);
720
+ }
721
+
722
+ if (event.type === 'turn.complete' && !isSubagent) {
723
+ state.turnsCompleted += 1;
724
+ if (!sameTurn) {
725
+ state.steps += 1;
726
+ }
727
+ }
728
+
729
+ if (!isSubagent) {
730
+ const customCeiling = resolveCustomCeilingForModel(effectiveTurnModelRaw, options);
731
+ const resolvedCeiling = Number(customCeiling || fullTurnCost.rates.contextCeiling);
732
+ state.modelLabel = fullTurnCost.rates.label;
733
+ state.contextCeiling = resolvedCeiling;
734
+ state.cliffTriggered = fullTurnCost.cliffTriggered;
735
+ state.preCliffWarningTriggered = fullTurnCost.preCliffWarningTriggered;
736
+
737
+ state.contextWindow.totalInputTokens = totalPromptTokens;
738
+ state.contextWindow.uncachedInputTokens = uncachedInput;
739
+ state.contextWindow.cacheReadTokens = cacheReadTokens;
740
+ state.contextWindow.cacheWriteTokens = totalWriteTokens;
741
+ state.contextWindow.warmPrefixTokens = cacheReadTokens + totalWriteTokens;
742
+ state.contextWindow.cachedTokens = cacheReadTokens + totalWriteTokens;
743
+ state.contextWindow.lastWriteTokens = totalWriteTokens;
744
+ state.contextWindow.lastOutputTokens = outputTokens;
745
+ state.contextWindow.lastThinkingTokens = thinkingTokens;
746
+ state.contextWindow.customCeiling = customCeiling || null;
747
+ state.contextWindow.contextCeiling = resolvedCeiling;
748
+
749
+ const isWarm = cacheReadTokens > 0 || totalWriteTokens > 0;
750
+ if (isWarm) {
751
+ state.promptCache.warm = true;
752
+ const ttlSeconds = state.promptCache.ttlTier === '1h' ? 3600 : 300;
753
+ state.promptCache.ttlSeconds = ttlSeconds;
754
+ state.promptCache.expiresAt = nowMs + ttlSeconds * 1000;
755
+ }
756
+ }
757
+
758
+ const activeMainRates = resolveEffectiveRates(
759
+ state.rawModelId || state.modelId,
760
+ state.contextWindow.totalInputTokens,
761
+ options
762
+ );
763
+ state.cacheRoi = buildCumulativeCacheRoi(state, activeMainRates);
764
+ state.lastTurn = fullTurnCost;
765
+
766
+ // Sprint 1 Metrics Wedge. Retention is scored once per distinct API request (prompt-side
767
+ // usage is final on the first chunk of a message); streaming re-sends of the same
768
+ // message.id and turn.complete re-reports of an already-tracked turn are skipped.
769
+ const isNewRequest =
770
+ event.type === 'turn.complete'
771
+ ? !sameTurn
772
+ : !(sameTurn && messageId && activeTracker.lastMessageId && messageId === activeTracker.lastMessageId);
773
+ if (isNewRequest) {
774
+ state.prefixRetention = applyPrefixRetentionRequest(state.prefixRetention, {
775
+ streamKey: isSubagent ? agentKey || 'subagent' : 'main',
776
+ modelId: normalizeModelId(effectiveTurnModelRaw),
777
+ uncachedInputTokens: uncachedInput,
778
+ cacheReadTokens,
779
+ cacheWriteTokens: totalWriteTokens,
780
+ nowMs,
781
+ ttlSeconds: ttlTier === '1h' ? 3600 : 300,
782
+ inputPer1M: fullTurnCost.rates.inputPer1M,
783
+ readPer1M: fullTurnCost.rates.readPer1M
784
+ });
785
+ }
786
+ if (!isSubagent) {
787
+ state.thinkingDrift = applyThinkingDriftEvent(state.thinkingDrift, {
788
+ eventType: event.type === 'turn.complete' ? 'turn.complete' : 'turn.step',
789
+ thinkingTokens: deltaBreakdown.thinkingTokens,
790
+ outputTokens: deltaBreakdown.outputTokens,
791
+ nowMs,
792
+ turnStartedAtMs: normalizeEventTimestampMs(
793
+ event.turnStartedAt ?? event.turn_started_at ?? event.result?.started_at ?? null
794
+ ),
795
+ ttftMs: Number(event.ttftMs ?? event.ttft_ms ?? event.result?.ttft_ms ?? 0) || null,
796
+ turnMutations: Number(event.turnMutations ?? 0) || 0
797
+ });
798
+ }
799
+
800
+ exportOtelTelemetry(state, options);
801
+
802
+ return state;
803
+ }
804
+
805
+ /**
806
+ * Normalizes an ISO string or epoch (s/ms) timestamp to epoch milliseconds, or `null`.
807
+ * @param {string|number|null|undefined} raw
808
+ * @returns {number|null}
809
+ */
810
+ function normalizeEventTimestampMs(raw) {
811
+ if (typeof raw === 'number' && Number.isFinite(raw) && raw > 0) {
812
+ return raw < 1e11 ? raw * 1000 : raw;
813
+ }
814
+ if (typeof raw === 'string' && raw.trim()) {
815
+ const parsed = Date.parse(raw);
816
+ return Number.isNaN(parsed) ? null : parsed;
817
+ }
818
+ return null;
819
+ }
820
+
821
+ /**
822
+ * Ingests a `statusLine` stdin JSON payload into the session telemetry state.
823
+ * Honors `customCeilings.json` ahead of `context_window_size` (`ISS-005`), tracks Turn-1 cold
824
+ * `cacheReadTokens` separately from `cacheWriteTokens` (`ISS-006`), increments `state.steps`
825
+ * on distinct turn envelopes (`ISS-003`), and prevents `WARM | 00:00 (0s)` (`ISS-027`).
826
+ *
827
+ * @param {object} currentState
828
+ * @param {object} statusPayload
829
+ * @param {object} [options={}]
830
+ * @returns {object} Updated state
831
+ */
832
+ export function ingestStatusLinePayload(currentState, statusPayload = {}, options = {}) {
833
+ const nowMs = options.nowMs || Date.now();
834
+ const sessionId =
835
+ statusPayload.session_id ||
836
+ statusPayload.sessionId ||
837
+ currentState?.sessionId ||
838
+ 'default';
839
+ const rawPayloadModel =
840
+ statusPayload.model?.id ||
841
+ (typeof statusPayload.model === 'string' ? statusPayload.model : null);
842
+ const rawModel =
843
+ rawPayloadModel ||
844
+ currentState?.rawModelId ||
845
+ currentState?.modelId ||
846
+ 'claude-sonnet-5-5';
847
+
848
+ const prevSource = currentState?.lastSource || 'init';
849
+ const state = currentState
850
+ ? JSON.parse(JSON.stringify(currentState))
851
+ : createInitialTelemetryState(sessionId, rawModel);
852
+
853
+ state.sessionId = sanitizeSessionId(sessionId);
854
+ state.rawModelId = String(rawModel);
855
+ state.modelId = normalizeModelId(rawModel);
856
+ state.lastUpdatedAt = nowMs;
857
+ state.lastSource = 'statusLine';
858
+
859
+ const cw = statusPayload.context_window || {};
860
+ const currentUsage = cw.current_usage || {};
861
+ const pc = statusPayload.prompt_cache || {};
862
+ const rl = statusPayload.rate_limits || {};
863
+
864
+ const ttlInfo = parseTtlInfo(pc.ttl ?? state.promptCache.ttlTier);
865
+ state.promptCache.ttlTier = ttlInfo.ttlTier;
866
+
867
+ const hasCurrentUsage =
868
+ Boolean(currentUsage && typeof currentUsage === 'object') &&
869
+ (currentUsage.input_tokens !== undefined ||
870
+ currentUsage.inputTokens !== undefined ||
871
+ currentUsage.uncachedInputTokens !== undefined ||
872
+ currentUsage.freshInputTokens !== undefined ||
873
+ currentUsage.cache_read_input_tokens !== undefined ||
874
+ currentUsage.cacheReadTokens !== undefined ||
875
+ currentUsage.cacheReadInputTokens !== undefined ||
876
+ currentUsage.cache_creation_input_tokens !== undefined ||
877
+ currentUsage.cacheWriteTokens !== undefined ||
878
+ currentUsage.cacheWrite5mTokens !== undefined ||
879
+ currentUsage.cacheWrite1hTokens !== undefined ||
880
+ currentUsage.cache_creation !== undefined);
881
+
882
+ const breakdown = extractNormalizedTokenBreakdown({
883
+ ...currentUsage,
884
+ cacheTtlTier: state.promptCache.ttlTier
885
+ });
886
+ const uncachedInput = breakdown.uncachedInputTokens;
887
+ const write5mTokens = breakdown.effectiveWrite5mTokens;
888
+ const write1hTokens = breakdown.effectiveWrite1hTokens;
889
+ const cacheWrite = breakdown.totalCacheWriteTokens;
890
+ const cacheRead = breakdown.cacheReadTokens;
891
+ const outputTokens = breakdown.outputTokens;
892
+ const thinkingTokens = breakdown.thinkingTokens;
893
+
894
+ const singleTurnUsagePrompt = uncachedInput + cacheWrite + cacheRead;
895
+ const reportedTotalInput = Math.max(
896
+ 0,
897
+ Number(cw.total_input_tokens ?? singleTurnUsagePrompt)
898
+ );
899
+ // Single-turn prompt token count for cliff check (never inflated by multi-turn cumulative sums)
900
+ const turnCliffPromptTokens = hasCurrentUsage ? singleTurnUsagePrompt : reportedTotalInput;
901
+
902
+ const customCeiling = resolveCustomCeilingForModel(rawModel, options);
903
+ const rates = resolveEffectiveRates(rawModel, turnCliffPromptTokens, options);
904
+ state.modelLabel = statusPayload.model?.display_name || rates.label;
905
+ state.contextCeiling = Number(customCeiling || cw.context_window_size || rates.contextCeiling);
906
+ state.cliffTriggered = rates.cliffTriggered;
907
+ state.preCliffWarningTriggered = rates.preCliffWarningTriggered;
908
+
909
+ state.contextWindow.totalInputTokens = reportedTotalInput;
910
+ state.contextWindow.customCeiling = customCeiling || null;
911
+ state.contextWindow.contextCeiling = state.contextCeiling;
912
+ if (hasCurrentUsage) {
913
+ state.contextWindow.uncachedInputTokens = uncachedInput;
914
+ state.contextWindow.cacheReadTokens = cacheRead;
915
+ state.contextWindow.cacheWriteTokens = cacheWrite;
916
+ state.contextWindow.warmPrefixTokens = cacheRead + cacheWrite;
917
+ state.contextWindow.cachedTokens = cacheRead + cacheWrite;
918
+ state.contextWindow.lastWriteTokens = cacheWrite;
919
+ state.contextWindow.lastOutputTokens = outputTokens;
920
+ state.contextWindow.lastThinkingTokens = thinkingTokens;
921
+ }
922
+
923
+ if (typeof cw.system_tokens === 'number' || typeof cw.mcp_tokens === 'number') {
924
+ state.contextWindow.systemAndMcpTokens =
925
+ Math.max(0, Number(cw.system_tokens || 0)) + Math.max(0, Number(cw.mcp_tokens || 0));
926
+ }
927
+ if (typeof cw.distractor_tokens === 'number') {
928
+ state.contextWindow.distractorTokens = Math.max(0, Number(cw.distractor_tokens || 0));
929
+ }
930
+
931
+ const parsedExpiresAt = normalizeExpiresAtMs(pc.expires_at, nowMs, ttlInfo.ttlSeconds, false);
932
+ const explicitlyExpired =
933
+ (pc.ttl !== undefined && ttlInfo.ttlSeconds <= 0) ||
934
+ (parsedExpiresAt !== null && parsedExpiresAt <= nowMs);
935
+ const rawWarm =
936
+ typeof pc.warm === 'boolean' ? pc.warm : state.contextWindow.cachedTokens > 0;
937
+ const isWarm = explicitlyExpired ? false : Boolean(rawWarm && ttlInfo.ttlSeconds > 0);
938
+ state.promptCache.warm = isWarm;
939
+ state.promptCache.ttlSeconds = isWarm ? ttlInfo.ttlSeconds : explicitlyExpired ? 0 : ttlInfo.ttlSeconds;
940
+ state.promptCache.expiresAt = isWarm
941
+ ? parsedExpiresAt ?? nowMs + ttlInfo.ttlSeconds * 1000
942
+ : null;
943
+
944
+ if (pc.last_miss_cause !== undefined) {
945
+ state.promptCache.lastMissCause = pc.last_miss_cause;
946
+ }
947
+
948
+ if (rl.five_hour) state.rateLimits.fiveHour = { ...rl.five_hour };
949
+ if (rl.seven_day) state.rateLimits.sevenDay = { ...rl.seven_day };
950
+ if (rl.spend_limit) state.rateLimits.spendLimit = { ...rl.spend_limit };
951
+
952
+ // Detect distinct turn envelope / cost delta on standalone statusLine ticks (`ISS-003`)
953
+ const statusTurnId =
954
+ statusPayload.turn_id ||
955
+ statusPayload.turnId ||
956
+ cw.turn_id ||
957
+ currentUsage.message_id ||
958
+ currentUsage.id ||
959
+ null;
960
+ const rawReportedCost = statusPayload.cost?.total_cost_usd;
961
+ const hasReportedCost = typeof rawReportedCost === 'number' && Number.isFinite(rawReportedCost);
962
+ const costChanged =
963
+ hasReportedCost &&
964
+ (state.lastReportedStatusCostUSD === null ||
965
+ Math.abs(rawReportedCost - state.lastReportedStatusCostUSD) > 1e-9);
966
+ const envelopeSig = `${state.modelId}:${uncachedInput}:${write5mTokens}:${write1hTokens}:${cacheRead}:${outputTokens}:${thinkingTokens}`;
967
+
968
+ const alreadyCommittedByMod =
969
+ prevSource.startsWith('mod.turn') &&
970
+ state.lastTurn?.tokens &&
971
+ state.lastTurn.tokens.uncachedInput === uncachedInput &&
972
+ state.lastTurn.tokens.totalCacheWrite === cacheWrite &&
973
+ state.lastTurn.tokens.cacheRead === cacheRead &&
974
+ state.lastTurn.tokens.output === outputTokens;
975
+
976
+ const isDuplicateStatusEnvelope =
977
+ (statusTurnId && state.lastStatusTurnId === statusTurnId) ||
978
+ (hasReportedCost && !costChanged && state.lastStatusLineEnvelopeSig === envelopeSig);
979
+
980
+ if (hasCurrentUsage && !alreadyCommittedByMod && !isDuplicateStatusEnvelope) {
981
+ const turnCost = calculateTurnCostUSD(
982
+ {
983
+ model: rawModel,
984
+ inputTokens: uncachedInput,
985
+ outputTokens,
986
+ thinkingTokens,
987
+ cacheWrite5mTokens: write5mTokens,
988
+ cacheWrite1hTokens: write1hTokens,
989
+ cacheReadTokens: cacheRead,
990
+ turnPromptTokens: turnCliffPromptTokens,
991
+ cacheTtlTier: state.promptCache.ttlTier
992
+ },
993
+ options
994
+ );
995
+ addTurnCostToCumulative(state.cumulative, turnCost);
996
+ state.steps += 1;
997
+ state.lastTurn = turnCost;
998
+ state.lastStatusLineEnvelopeSig = envelopeSig;
999
+ if (statusTurnId) state.lastStatusTurnId = statusTurnId;
1000
+ if (hasReportedCost) state.lastReportedStatusCostUSD = rawReportedCost;
1001
+ } else if (!hasCurrentUsage && costChanged && rawReportedCost > (state.lastReportedStatusCostUSD || 0)) {
1002
+ state.steps += 1;
1003
+ state.lastReportedStatusCostUSD = rawReportedCost;
1004
+ }
1005
+
1006
+ if (
1007
+ state.steps > 0 ||
1008
+ state.cumulative.cacheWrite5mTokens +
1009
+ state.cumulative.cacheWrite1hTokens +
1010
+ state.cumulative.cacheReadTokens >
1011
+ 0
1012
+ ) {
1013
+ state.cacheRoi = buildCumulativeCacheRoi(state, rates);
1014
+ }
1015
+
1016
+ return state;
1017
+ }
1018
+
1019
+ /**
1020
+ * Atomically writes the telemetry state snapshot to `.claude/cache/ah_live_state_<sessionId>.json`
1021
+ * and updates `.claude/cache/ah_live_state.json`.
1022
+ *
1023
+ * @param {string} sessionId
1024
+ * @param {object} state
1025
+ * @param {object} [options={}]
1026
+ * @returns {{ ok: boolean, sessionPath: string }}
1027
+ */
1028
+ export function writeLiveStateSnapshot(sessionId, state, options = {}) {
1029
+ const safeId = sanitizeSessionId(sessionId || state?.sessionId || 'default');
1030
+ const sessionPath = getLiveStateBridgePath(safeId, options);
1031
+ const okSession = writeJsonAtomic(sessionPath, state, options);
1032
+
1033
+ const cwd = getCwd(options);
1034
+ const defaultPath = path.join(cwd, '.claude', 'cache', 'ah_live_state.json');
1035
+ writeJsonAtomic(defaultPath, state, options);
1036
+
1037
+ return { ok: okSession, sessionPath };
1038
+ }
1039
+
1040
+ /**
1041
+ * Reads the live telemetry state snapshot from `.claude/cache/ah_live_state_<sessionId>.json`.
1042
+ * Falls back to `.claude/cache/ah_live_state.json` or a clean initial state.
1043
+ *
1044
+ * @param {string} [sessionId='default']
1045
+ * @param {object} [options={}]
1046
+ * @returns {object}
1047
+ */
1048
+ export function readLiveStateSnapshot(sessionId = 'default', options = {}) {
1049
+ const safeId = sanitizeSessionId(sessionId);
1050
+ const sessionPath = getLiveStateBridgePath(safeId, options);
1051
+ const fromSession = readJsonSafe(sessionPath, null, options);
1052
+ if (fromSession && typeof fromSession === 'object') {
1053
+ return fromSession;
1054
+ }
1055
+
1056
+ const cwd = getCwd(options);
1057
+ const defaultPath = path.join(cwd, '.claude', 'cache', 'ah_live_state.json');
1058
+ const fromDefault = readJsonSafe(defaultPath, null, options);
1059
+ if (fromDefault && typeof fromDefault === 'object') {
1060
+ return fromDefault;
1061
+ }
1062
+
1063
+ return createInitialTelemetryState(safeId, options.defaultModel || 'claude-sonnet-5-5');
1064
+ }
1065
+
1066
+ /**
1067
+ * Stateful Dual-Source Telemetry Bridge controller.
1068
+ */
1069
+ export class TelemetryBridge {
1070
+ /**
1071
+ * @param {object} [options={}]
1072
+ */
1073
+ constructor(options = {}) {
1074
+ this.options = options;
1075
+ this.sessionId = sanitizeSessionId(options.sessionId || 'default');
1076
+ this.state =
1077
+ options.initialState ||
1078
+ createInitialTelemetryState(this.sessionId, options.defaultModel || 'claude-sonnet-5-5');
1079
+ }
1080
+
1081
+ /**
1082
+ * Processes a Mod `turn.step` or `turn.complete` event and optionally persists to disk.
1083
+ * @param {object} event
1084
+ * @param {object} [callOptions={}]
1085
+ * @returns {object}
1086
+ */
1087
+ handleModEvent(event = {}, callOptions = {}) {
1088
+ const mergedOpts = { ...this.options, ...callOptions };
1089
+ this.state = ingestModTurnEvent(this.state, event, mergedOpts);
1090
+ this.sessionId = this.state.sessionId;
1091
+ if (mergedOpts.persist !== false) {
1092
+ writeLiveStateSnapshot(this.sessionId, this.state, mergedOpts);
1093
+ }
1094
+ return this.state;
1095
+ }
1096
+
1097
+ /**
1098
+ * Processes a `statusLine` JSON payload and optionally persists to disk.
1099
+ * @param {object} statusPayload
1100
+ * @param {object} [callOptions={}]
1101
+ * @returns {object}
1102
+ */
1103
+ handleStatusLine(statusPayload = {}, callOptions = {}) {
1104
+ const mergedOpts = { ...this.options, ...callOptions };
1105
+ this.state = ingestStatusLinePayload(this.state, statusPayload, mergedOpts);
1106
+ this.sessionId = this.state.sessionId;
1107
+ if (mergedOpts.persist !== false) {
1108
+ writeLiveStateSnapshot(this.sessionId, this.state, mergedOpts);
1109
+ }
1110
+ return this.state;
1111
+ }
1112
+
1113
+ /**
1114
+ * Returns current session state.
1115
+ * @returns {object}
1116
+ */
1117
+ getState() {
1118
+ return this.state;
1119
+ }
1120
+ }
1121
+
1122
+ export default {
1123
+ sanitizeSessionId,
1124
+ getLiveStateBridgePath,
1125
+ computeCacheRoi,
1126
+ createInitialTelemetryState,
1127
+ ingestModTurnEvent,
1128
+ ingestStatusLinePayload,
1129
+ writeLiveStateSnapshot,
1130
+ readLiveStateSnapshot,
1131
+ TelemetryBridge
1132
+ };