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