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,1268 @@
1
+ /**
2
+ * @file src/config/catalogLoader.mjs
3
+ * Unified Anthropic Model Catalog loader, rate card resolver, Haiku 5.5 100k 5x cliff calculator,
4
+ * and customCeilings.json override merger.
5
+ */
6
+
7
+ import {
8
+ path,
9
+ getCwd,
10
+ getHomeDir,
11
+ getNodeIo,
12
+ fileUrlToPathPure,
13
+ readJsonSafe
14
+ } from '../utils/runtime.mjs';
15
+
16
+ export const BUILTIN_CATALOG = {
17
+ schemaVersion: '2026.11.15',
18
+ catalogVersion: '2026-11-15',
19
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models, 2026-11-15) & Claude Code 2.1.325 bakedCatalog',
20
+ dateRead: '2026-11-15',
21
+ defaultModel: 'claude-sonnet-5-5',
22
+ cacheWriteMultipliers: {
23
+ '5m': 1.25,
24
+ '1h': 2.0
25
+ },
26
+ effortExpectedOutputTokens: {
27
+ low: 800,
28
+ medium: 1500,
29
+ high: 3500,
30
+ max: 6000
31
+ },
32
+ models: {
33
+ 'claude-fable-5-2': {
34
+ id: 'claude-fable-5-2',
35
+ label: 'Claude Fable 5.2',
36
+ shortLabel: 'Fable 5.2',
37
+ family: 'fable',
38
+ generation: '5.2',
39
+ contextCeiling: 1000000,
40
+ operationalSoftCeiling: 180000,
41
+ ratesPer1M: { input: 8.0, output: 40.0, write5m: 10.0, write1h: 16.0, read: 0.2 },
42
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.025 },
43
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
44
+ dateRead: '2026-11-15',
45
+ pricingCliff: null
46
+ },
47
+ 'claude-fable-5-1': {
48
+ id: 'claude-fable-5-1',
49
+ label: 'Claude Fable 5.1',
50
+ shortLabel: 'Fable 5.1',
51
+ family: 'fable',
52
+ generation: '5.1',
53
+ contextCeiling: 1000000,
54
+ operationalSoftCeiling: 180000,
55
+ ratesPer1M: { input: 10.0, output: 50.0, write5m: 12.5, write1h: 20.0, read: 0.25 },
56
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.025 },
57
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
58
+ dateRead: '2026-11-15',
59
+ pricingCliff: null
60
+ },
61
+ 'claude-fable-5': {
62
+ id: 'claude-fable-5',
63
+ label: 'Claude Fable 5',
64
+ shortLabel: 'Fable 5',
65
+ family: 'fable',
66
+ generation: '5',
67
+ contextCeiling: 1000000,
68
+ operationalSoftCeiling: 180000,
69
+ ratesPer1M: { input: 10.0, output: 50.0, write5m: 12.5, write1h: 20.0, read: 1.0 },
70
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
71
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models) & Claude Code 2.1.325 bakedCatalog (tier_10_50)',
72
+ dateRead: '2026-11-15',
73
+ pricingCliff: null
74
+ },
75
+ 'claude-opus-5-5': {
76
+ id: 'claude-opus-5-5',
77
+ label: 'Claude Opus 5.5',
78
+ shortLabel: 'Opus 5.5',
79
+ family: 'opus',
80
+ generation: '5.5',
81
+ contextCeiling: 1000000,
82
+ operationalSoftCeiling: 180000,
83
+ ratesPer1M: { input: 4.0, output: 20.0, write5m: 5.0, write1h: 8.0, read: 0.2 },
84
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.05 },
85
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
86
+ dateRead: '2026-11-15',
87
+ pricingCliff: null
88
+ },
89
+ 'claude-sonnet-5-5': {
90
+ id: 'claude-sonnet-5-5',
91
+ label: 'Claude Sonnet 5.5',
92
+ shortLabel: 'Sonnet 5.5',
93
+ family: 'sonnet',
94
+ generation: '5.5',
95
+ contextCeiling: 1000000,
96
+ operationalSoftCeiling: 180000,
97
+ ratesPer1M: { input: 2.0, output: 10.0, write5m: 2.5, write1h: 4.0, read: 0.1 },
98
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.05 },
99
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
100
+ dateRead: '2026-11-15',
101
+ pricingCliff: null
102
+ },
103
+ 'claude-haiku-5-5': {
104
+ id: 'claude-haiku-5-5',
105
+ label: 'Claude Haiku 5.5',
106
+ shortLabel: 'Haiku 5.5',
107
+ family: 'haiku',
108
+ generation: '5.5',
109
+ contextCeiling: 1000000,
110
+ operationalSoftCeiling: 90000,
111
+ ratesPer1M: { input: 0.1, output: 0.5, write5m: 0.125, write1h: 0.2, read: 0.01 },
112
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
113
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models) & Claude Code 2.1.325 bakedCatalog (haiku_55)',
114
+ dateRead: '2026-11-15',
115
+ pricingCliff: {
116
+ thresholdTokens: 100000,
117
+ preCliffWarningTokens: 90000,
118
+ multiplier: 5.0,
119
+ ratesPer1MAboveCliff: {
120
+ input: 0.5,
121
+ output: 2.5,
122
+ write5m: 0.625,
123
+ write1h: 1.0,
124
+ read: 0.05
125
+ }
126
+ }
127
+ },
128
+ 'claude-opus-5': {
129
+ id: 'claude-opus-5',
130
+ label: 'Claude Opus 5',
131
+ shortLabel: 'Opus 5',
132
+ family: 'opus',
133
+ generation: '5',
134
+ contextCeiling: 1000000,
135
+ operationalSoftCeiling: 180000,
136
+ ratesPer1M: { input: 5.0, output: 25.0, write5m: 6.25, write1h: 10.0, read: 0.5 },
137
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
138
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
139
+ dateRead: '2026-11-15',
140
+ pricingCliff: null
141
+ },
142
+ 'claude-sonnet-5': {
143
+ id: 'claude-sonnet-5',
144
+ label: 'Claude Sonnet 5',
145
+ shortLabel: 'Sonnet 5',
146
+ family: 'sonnet',
147
+ generation: '5',
148
+ contextCeiling: 1000000,
149
+ operationalSoftCeiling: 180000,
150
+ ratesPer1M: { input: 2.0, output: 10.0, write5m: 2.5, write1h: 4.0, read: 0.2 },
151
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
152
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
153
+ dateRead: '2026-11-15',
154
+ pricingCliff: null
155
+ },
156
+ 'claude-opus-4-8': {
157
+ id: 'claude-opus-4-8',
158
+ label: 'Claude Opus 4.8',
159
+ shortLabel: 'Opus 4.8',
160
+ family: 'opus',
161
+ generation: '4.8',
162
+ contextCeiling: 1000000,
163
+ operationalSoftCeiling: 180000,
164
+ ratesPer1M: { input: 5.0, output: 25.0, write5m: 6.25, write1h: 10.0, read: 0.5 },
165
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
166
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
167
+ dateRead: '2026-11-15',
168
+ pricingCliff: null
169
+ },
170
+ 'claude-opus-4-7': {
171
+ id: 'claude-opus-4-7',
172
+ label: 'Claude Opus 4.7',
173
+ shortLabel: 'Opus 4.7',
174
+ family: 'opus',
175
+ generation: '4.7',
176
+ contextCeiling: 1000000,
177
+ operationalSoftCeiling: 180000,
178
+ ratesPer1M: { input: 5.0, output: 25.0, write5m: 6.25, write1h: 10.0, read: 0.5 },
179
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
180
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
181
+ dateRead: '2026-11-15',
182
+ pricingCliff: null
183
+ },
184
+ 'claude-opus-4-6': {
185
+ id: 'claude-opus-4-6',
186
+ label: 'Claude Opus 4.6',
187
+ shortLabel: 'Opus 4.6',
188
+ family: 'opus',
189
+ generation: '4.6',
190
+ contextCeiling: 200000,
191
+ operationalSoftCeiling: 160000,
192
+ ratesPer1M: { input: 5.0, output: 25.0, write5m: 6.25, write1h: 10.0, read: 0.5 },
193
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
194
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
195
+ dateRead: '2026-11-15',
196
+ pricingCliff: null
197
+ },
198
+ 'claude-opus-4-5': {
199
+ id: 'claude-opus-4-5',
200
+ label: 'Claude Opus 4.5',
201
+ shortLabel: 'Opus 4.5',
202
+ family: 'opus',
203
+ generation: '4.5',
204
+ contextCeiling: 200000,
205
+ operationalSoftCeiling: 160000,
206
+ ratesPer1M: { input: 5.0, output: 25.0, write5m: 6.25, write1h: 10.0, read: 0.5 },
207
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
208
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
209
+ dateRead: '2026-11-15',
210
+ pricingCliff: null
211
+ },
212
+ 'claude-opus-4-1': {
213
+ id: 'claude-opus-4-1',
214
+ label: 'Claude Opus 4.1',
215
+ shortLabel: 'Opus 4.1',
216
+ family: 'opus',
217
+ generation: '4.1',
218
+ contextCeiling: 200000,
219
+ operationalSoftCeiling: 160000,
220
+ ratesPer1M: { input: 15.0, output: 75.0, write5m: 18.75, write1h: 30.0, read: 1.5 },
221
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
222
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
223
+ dateRead: '2026-11-15',
224
+ pricingCliff: null
225
+ },
226
+ 'claude-opus-4-0': {
227
+ id: 'claude-opus-4-0',
228
+ label: 'Claude Opus 4',
229
+ shortLabel: 'Opus 4',
230
+ family: 'opus',
231
+ generation: '4.0',
232
+ contextCeiling: 200000,
233
+ operationalSoftCeiling: 160000,
234
+ ratesPer1M: { input: 15.0, output: 75.0, write5m: 18.75, write1h: 30.0, read: 1.5 },
235
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
236
+ source: 'Claude Code 2.1.325 bakedCatalog (tier_15_75) & OpenRouter /api/v1/models (anthropic/claude-opus-4)',
237
+ dateRead: '2026-11-15',
238
+ pricingCliff: null
239
+ },
240
+ 'claude-sonnet-4-6': {
241
+ id: 'claude-sonnet-4-6',
242
+ label: 'Claude Sonnet 4.6',
243
+ shortLabel: 'Sonnet 4.6',
244
+ family: 'sonnet',
245
+ generation: '4.6',
246
+ contextCeiling: 200000,
247
+ operationalSoftCeiling: 160000,
248
+ ratesPer1M: { input: 3.0, output: 15.0, write5m: 3.75, write1h: 6.0, read: 0.3 },
249
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
250
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
251
+ dateRead: '2026-11-15',
252
+ pricingCliff: null
253
+ },
254
+ 'claude-sonnet-4-5': {
255
+ id: 'claude-sonnet-4-5',
256
+ label: 'Claude Sonnet 4.5',
257
+ shortLabel: 'Sonnet 4.5',
258
+ family: 'sonnet',
259
+ generation: '4.5',
260
+ contextCeiling: 200000,
261
+ operationalSoftCeiling: 160000,
262
+ ratesPer1M: { input: 3.0, output: 15.0, write5m: 3.75, write1h: 6.0, read: 0.3 },
263
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
264
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
265
+ dateRead: '2026-11-15',
266
+ pricingCliff: null
267
+ },
268
+ 'claude-sonnet-4-0': {
269
+ id: 'claude-sonnet-4-0',
270
+ label: 'Claude Sonnet 4',
271
+ shortLabel: 'Sonnet 4',
272
+ family: 'sonnet',
273
+ generation: '4.0',
274
+ contextCeiling: 200000,
275
+ operationalSoftCeiling: 160000,
276
+ ratesPer1M: { input: 3.0, output: 15.0, write5m: 3.75, write1h: 6.0, read: 0.3 },
277
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
278
+ source: 'Claude Code 2.1.325 bakedCatalog (tier_3_15) & OpenRouter /api/v1/models (anthropic/claude-sonnet-4)',
279
+ dateRead: '2026-11-15',
280
+ pricingCliff: null
281
+ },
282
+ 'claude-haiku-4-5': {
283
+ id: 'claude-haiku-4-5',
284
+ label: 'Claude Haiku 4.5',
285
+ shortLabel: 'Haiku 4.5',
286
+ family: 'haiku',
287
+ generation: '4.5',
288
+ contextCeiling: 200000,
289
+ operationalSoftCeiling: 160000,
290
+ ratesPer1M: { input: 1.0, output: 5.0, write5m: 1.25, write1h: 2.0, read: 0.1 },
291
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
292
+ source: 'phase0_capabilities_and_cost_gate.md (OpenRouter /api/v1/models)',
293
+ dateRead: '2026-11-15',
294
+ pricingCliff: null
295
+ },
296
+ 'claude-3-7-sonnet': {
297
+ id: 'claude-3-7-sonnet',
298
+ label: 'Claude Sonnet 3.7',
299
+ shortLabel: 'Sonnet 3.7',
300
+ family: 'sonnet',
301
+ generation: '3.7',
302
+ contextCeiling: 200000,
303
+ operationalSoftCeiling: 160000,
304
+ ratesPer1M: { input: 3.0, output: 15.0, write5m: 3.75, write1h: 6.0, read: 0.3 },
305
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
306
+ source: 'Claude Code 2.1.325 bakedCatalog (tier_3_15) & OpenRouter /api/v1/models (anthropic/claude-3.7-sonnet)',
307
+ dateRead: '2026-11-15',
308
+ pricingCliff: null
309
+ },
310
+ 'claude-3-5-sonnet': {
311
+ id: 'claude-3-5-sonnet',
312
+ label: 'Claude Sonnet 3.5',
313
+ shortLabel: 'Sonnet 3.5',
314
+ family: 'sonnet',
315
+ generation: '3.5',
316
+ contextCeiling: 200000,
317
+ operationalSoftCeiling: 160000,
318
+ ratesPer1M: { input: 3.0, output: 15.0, write5m: 3.75, write1h: 6.0, read: 0.3 },
319
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
320
+ source: 'Claude Code 2.1.325 bakedCatalog (tier_3_15) & OpenRouter /api/v1/models',
321
+ dateRead: '2026-11-15',
322
+ pricingCliff: null
323
+ },
324
+ 'claude-3-5-haiku': {
325
+ id: 'claude-3-5-haiku',
326
+ label: 'Claude Haiku 3.5',
327
+ shortLabel: 'Haiku 3.5',
328
+ family: 'haiku',
329
+ generation: '3.5',
330
+ contextCeiling: 200000,
331
+ operationalSoftCeiling: 160000,
332
+ ratesPer1M: { input: 0.8, output: 4.0, write5m: 1.0, write1h: 1.6, read: 0.08 },
333
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
334
+ source: 'Claude Code 2.1.325 bakedCatalog (haiku_35) & OpenRouter /api/v1/models (anthropic/claude-3.5-haiku)',
335
+ dateRead: '2026-11-15',
336
+ pricingCliff: null
337
+ },
338
+ 'claude-mythos-5': {
339
+ id: 'claude-mythos-5',
340
+ label: 'Claude Mythos 5',
341
+ shortLabel: 'Mythos 5',
342
+ family: 'mythos',
343
+ generation: '5',
344
+ contextCeiling: 1000000,
345
+ operationalSoftCeiling: 180000,
346
+ ratesPer1M: { input: 10.0, output: 50.0, write5m: 12.5, write1h: 20.0, read: 1.0 },
347
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.1 },
348
+ source: 'Claude Code 2.1.325 bakedCatalog (tier_10_50; OpenRouter price unverified)',
349
+ dateRead: '2026-11-15',
350
+ pricingCliff: null
351
+ },
352
+ 'claude-mythos-5-1': {
353
+ id: 'claude-mythos-5-1',
354
+ label: 'Claude Mythos 5.1',
355
+ shortLabel: 'Mythos 5.1',
356
+ family: 'mythos',
357
+ generation: '5.1',
358
+ contextCeiling: 1000000,
359
+ operationalSoftCeiling: 180000,
360
+ ratesPer1M: { input: 10.0, output: 50.0, write5m: 12.5, write1h: 20.0, read: 0.25 },
361
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.025 },
362
+ source: 'Claude Code 2.1.325 bakedCatalog (tier_10_50_cache_read_0_25; OpenRouter price unverified)',
363
+ dateRead: '2026-11-15',
364
+ pricingCliff: null
365
+ },
366
+ 'claude-mythos-5-2': {
367
+ id: 'claude-mythos-5-2',
368
+ label: 'Claude Mythos 5.2',
369
+ shortLabel: 'Mythos 5.2',
370
+ family: 'mythos',
371
+ generation: '5.2',
372
+ contextCeiling: 1000000,
373
+ operationalSoftCeiling: 180000,
374
+ ratesPer1M: { input: 8.0, output: 40.0, write5m: 10.0, write1h: 16.0, read: 0.2 },
375
+ multipliers: { write5m: 1.25, write1h: 2.0, read: 0.025 },
376
+ source: 'Claude Code 2.1.325 bakedCatalog (tier_8_40_cache_read_0_20; OpenRouter price unverified)',
377
+ dateRead: '2026-11-15',
378
+ pricingCliff: null
379
+ }
380
+ }
381
+ };
382
+
383
+ /**
384
+ * Resolves the directory containing this module when Tier-2 Node I/O is active.
385
+ * @param {object} [options={}]
386
+ * @returns {string | null}
387
+ */
388
+ function getModuleDir(options = {}) {
389
+ if (!getNodeIo(options)) return null;
390
+ try {
391
+ const filePath = fileUrlToPathPure(import.meta.url, options);
392
+ return filePath ? path.dirname(filePath) : null;
393
+ } catch (_err) {
394
+ return null;
395
+ }
396
+ }
397
+
398
+ /**
399
+ * Detects whether a raw model identifier or options flag requests a 1,000,000-token
400
+ * extended context window (`[1m]`, `-1m`, `_1m`, or `options.extendedContext1M === true`).
401
+ *
402
+ * @param {string} [rawModelId='']
403
+ * @param {object} [options={}]
404
+ * @returns {boolean}
405
+ */
406
+ export function hasExtended1MHint(rawModelId = '', options = {}) {
407
+ if (options?.extendedContext1M === true) return true;
408
+ const raw = String(rawModelId || '').toLowerCase().trim();
409
+ return /\[1m\]|(?:^|[-_:\s])1m(?:$|[-_:\s\]])/.test(raw);
410
+ }
411
+
412
+ export const UNKNOWN_MODEL_ID = 'unknown';
413
+
414
+ /**
415
+ * Formats a concise, zero-USD advisory for models absent from the price catalog (Item 1.2).
416
+ *
417
+ * @param {string} [rawModelId='']
418
+ * @returns {string}
419
+ */
420
+ export function formatUnknownModelAdvisory(rawModelId = '') {
421
+ const displayId = String(rawModelId || '').trim() || UNKNOWN_MODEL_ID;
422
+ return `Prices for model "${displayId}" are unknown (not in price catalog); dollar figures and price-based holds are disabled.`;
423
+ }
424
+
425
+ const SHORT_MODEL_ALIASES = Object.freeze({
426
+ opus: 'claude-opus-5-5',
427
+ best: 'claude-opus-5-5',
428
+ opusplan: 'claude-opus-5-5',
429
+ sonnet: 'claude-sonnet-5-5',
430
+ haiku: 'claude-haiku-5-5',
431
+ fable: 'claude-fable-5-2',
432
+ mythos: 'claude-mythos-5-2',
433
+ 'claude-opus-4': 'claude-opus-4-0',
434
+ 'claude-sonnet-4': 'claude-sonnet-4-0',
435
+ 'claude-3-5-sonnet-v2': 'claude-3-5-sonnet'
436
+ });
437
+
438
+ /**
439
+ * Canonicalizes a raw model identifier syntax (provider prefixes, `[1m]`, dates, version dots)
440
+ * without guessing unknown model families or falling back to a default model.
441
+ *
442
+ * @param {string} [rawModelId='']
443
+ * @returns {string}
444
+ */
445
+ function canonicalizeModelToken(rawModelId = '') {
446
+ let s = String(rawModelId || '')
447
+ .toLowerCase()
448
+ .trim()
449
+ .replace(/\[[12]m\]/gi, '')
450
+ .replace(/[-_:\s]+1m$/g, '')
451
+ .replace(/\s+/g, '-');
452
+
453
+ if (!s) return '';
454
+
455
+ // Strip provider prefixes (e.g. openrouter/anthropic/, anthropic/, us.anthropic.)
456
+ const slashIdx = s.lastIndexOf('/');
457
+ if (slashIdx !== -1) {
458
+ const providerPart = s.slice(0, slashIdx);
459
+ const tail = s.slice(slashIdx + 1);
460
+ if (providerPart === 'anthropic' || providerPart.endsWith('/anthropic')) {
461
+ s = tail;
462
+ } else {
463
+ // Non-Anthropic provider prefix (e.g. google/gemini-2.5-pro, openai/gpt-5) stays intact
464
+ return s.replace(/\./g, '-');
465
+ }
466
+ }
467
+
468
+ const bedrockMatch = s.match(/^(?:[a-z-]+\.)?anthropic\.(claude-.*)$/);
469
+ if (bedrockMatch) {
470
+ s = bedrockMatch[1];
471
+ }
472
+
473
+ s = s.replace(/\./g, '-');
474
+ // Strip Bedrock version tag (-v1:0 / -v2), date trailer (-20251001 / @20251001), or tier tag (:batch is NOT stripped as base rate)
475
+ s = s
476
+ .replace(/-v\d+(?::\d+)?$/i, '')
477
+ .replace(/[@-]\d{8}$/i, '')
478
+ .replace(/-(?:thinking|fast|latest)$/i, '');
479
+
480
+ // Handle alternate ordering like claude-4-6-sonnet -> claude-sonnet-4-6 (4.x+ only; 3.x is claude-3-x-family)
481
+ const altOrder = s.match(/^claude-([4-9]\d*-\d+)-(opus|sonnet|haiku|fable|mythos)$/);
482
+ if (altOrder) {
483
+ s = `claude-${altOrder[2]}-${altOrder[1]}`;
484
+ }
485
+ const threeXOrder = s.match(/^claude-(haiku|sonnet)-(3-[57])$/);
486
+ if (threeXOrder) {
487
+ s = `claude-${threeXOrder[2]}-${threeXOrder[1]}`;
488
+ }
489
+
490
+ if (Object.prototype.hasOwnProperty.call(SHORT_MODEL_ALIASES, s)) {
491
+ return SHORT_MODEL_ALIASES[s];
492
+ }
493
+ if (/^(?:opus|sonnet|haiku|fable)-/.test(s) && !s.startsWith('claude-')) {
494
+ return `claude-${s}`;
495
+ }
496
+
497
+ return s;
498
+ }
499
+
500
+ /**
501
+ * Checks whether a raw model identifier resolves to a known Anthropic catalog model
502
+ * (or an explicit custom rate card in `customCeilings.json`), returning `false` for
503
+ * unrecognized model IDs (including uncatalogued Claude or third-party slugs).
504
+ *
505
+ * @param {string} [rawModelId='']
506
+ * @param {object} [options={}]
507
+ * @returns {boolean}
508
+ */
509
+ export function isKnownCatalogModel(rawModelId = '', options = {}) {
510
+ const raw = String(rawModelId || '').trim();
511
+ if (!raw || raw.toLowerCase() === UNKNOWN_MODEL_ID) return false;
512
+
513
+ const cleaned = canonicalizeModelToken(raw);
514
+ if (!cleaned) return false;
515
+
516
+ const catalog = options.catalog || loadModelCatalog(options);
517
+ if (catalog?.models && Object.prototype.hasOwnProperty.call(catalog.models, cleaned)) {
518
+ return true;
519
+ }
520
+
521
+ const customCeilings = options.customCeilings !== undefined ? options.customCeilings : loadCustomCeilings(options);
522
+ if (customCeilings && typeof customCeilings === 'object') {
523
+ const sourceMap =
524
+ customCeilings.models && typeof customCeilings.models === 'object'
525
+ ? customCeilings.models
526
+ : customCeilings.ceilings && typeof customCeilings.ceilings === 'object'
527
+ ? customCeilings.ceilings
528
+ : customCeilings;
529
+ for (const [key, val] of Object.entries(sourceMap)) {
530
+ if (
531
+ (key === raw || canonicalizeModelToken(key) === cleaned) &&
532
+ val &&
533
+ typeof val === 'object' &&
534
+ val.ratesPer1M &&
535
+ typeof val.ratesPer1M === 'object'
536
+ ) {
537
+ return true;
538
+ }
539
+ }
540
+ }
541
+
542
+ return false;
543
+ }
544
+
545
+ /**
546
+ * Normalizes a raw Anthropic model string or official Claude Code alias to its canonical catalog ID.
547
+ * Returns `BUILTIN_CATALOG.defaultModel` (`'claude-sonnet-5-5'`) only when `rawModelId` is empty/omitted;
548
+ * returns `'unknown'` (`UNKNOWN_MODEL_ID`) for any unrecognized non-empty model identifier.
549
+ *
550
+ * @param {string} [rawModelId='']
551
+ * @param {object} [options={}]
552
+ * @returns {string}
553
+ */
554
+ export function normalizeModelId(rawModelId = '', options = {}) {
555
+ const raw = String(rawModelId || '').trim();
556
+ if (!raw) return BUILTIN_CATALOG.defaultModel;
557
+
558
+ const cleaned = canonicalizeModelToken(raw);
559
+ if (!cleaned) return BUILTIN_CATALOG.defaultModel;
560
+
561
+ const catalog = options.catalog || BUILTIN_CATALOG;
562
+ if (catalog?.models && Object.prototype.hasOwnProperty.call(catalog.models, cleaned)) {
563
+ return cleaned;
564
+ }
565
+
566
+ if (options.customCeilings && isKnownCatalogModel(raw, options)) {
567
+ return cleaned;
568
+ }
569
+
570
+ return UNKNOWN_MODEL_ID;
571
+ }
572
+
573
+ /**
574
+ * Discovers and reads customCeilings.json from options or standard workspace/user paths.
575
+ * @param {object} [options={}]
576
+ * @returns {object | null}
577
+ */
578
+ export function loadCustomCeilings(options = {}) {
579
+ if (options.customCeilings && typeof options.customCeilings === 'object') {
580
+ return options.customCeilings;
581
+ }
582
+
583
+ if (!getNodeIo(options)) return null;
584
+
585
+ const candidatePaths = [];
586
+ if (typeof options.customCeilingsPath === 'string' && options.customCeilingsPath.trim()) {
587
+ candidatePaths.push(options.customCeilingsPath.trim());
588
+ }
589
+
590
+ const cwd = options.cwd || getCwd(options);
591
+ if (cwd && cwd !== '.') {
592
+ candidatePaths.push(path.join(cwd, '.claude', 'attention-horizon', 'customCeilings.json'));
593
+ candidatePaths.push(path.join(cwd, 'customCeilings.json'));
594
+ candidatePaths.push(path.join(cwd, '.claude', 'customCeilings.json'));
595
+ }
596
+
597
+ const modDir = getModuleDir(options);
598
+ if (modDir) {
599
+ candidatePaths.push(path.join(modDir, 'customCeilings.json'));
600
+ }
601
+
602
+ const homeDir = getHomeDir(options);
603
+ if (homeDir) {
604
+ candidatePaths.push(path.join(homeDir, '.claude', 'attention-horizon', 'customCeilings.json'));
605
+ candidatePaths.push(path.join(homeDir, '.claude', 'customCeilings.json'));
606
+ }
607
+
608
+ for (const candidate of candidatePaths) {
609
+ const parsed = readJsonSafe(candidate, null, options);
610
+ if (parsed && typeof parsed === 'object') {
611
+ return parsed;
612
+ }
613
+ }
614
+
615
+ return null;
616
+ }
617
+
618
+ /**
619
+ * Resolves an explicit user ceiling override (in tokens) for `modelId` from `customCeilings.json`
620
+ * or `options.customCeilings`, returning `null` when no custom ceiling override applies (`ISS-005`).
621
+ *
622
+ * @param {string} [modelId='']
623
+ * @param {object} [options={}]
624
+ * @returns {number | null}
625
+ */
626
+ export function resolveCustomCeilingForModel(modelId = '', options = {}) {
627
+ const customCeilings = loadCustomCeilings(options);
628
+ if (!customCeilings || typeof customCeilings !== 'object') {
629
+ return null;
630
+ }
631
+
632
+ const sourceMap =
633
+ customCeilings.models && typeof customCeilings.models === 'object'
634
+ ? customCeilings.models
635
+ : customCeilings.ceilings && typeof customCeilings.ceilings === 'object'
636
+ ? customCeilings.ceilings
637
+ : customCeilings;
638
+
639
+ const extractCeilingNumber = (val) => {
640
+ if (typeof val === 'number' && val > 0) return val;
641
+ if (val && typeof val === 'object') {
642
+ if (typeof val.contextCeiling === 'number' && val.contextCeiling > 0) {
643
+ return val.contextCeiling;
644
+ }
645
+ if (typeof val.ceiling === 'number' && val.ceiling > 0) {
646
+ return val.ceiling;
647
+ }
648
+ }
649
+ return null;
650
+ };
651
+
652
+ const normId = normalizeModelId(modelId, options);
653
+ const cleanedRaw = canonicalizeModelToken(modelId);
654
+ if (modelId && Object.prototype.hasOwnProperty.call(sourceMap, modelId)) {
655
+ const direct = extractCeilingNumber(sourceMap[modelId]);
656
+ if (direct !== null) return direct;
657
+ }
658
+
659
+ for (const [rawKey, overrideVal] of Object.entries(sourceMap)) {
660
+ if (rawKey === '*' || rawKey === 'schemaVersion') continue;
661
+ const keyMatched =
662
+ (cleanedRaw && (rawKey === cleanedRaw || canonicalizeModelToken(rawKey) === cleanedRaw)) ||
663
+ (normId !== UNKNOWN_MODEL_ID && (rawKey === normId || normalizeModelId(rawKey, options) === normId));
664
+ if (keyMatched) {
665
+ const matched = extractCeilingNumber(overrideVal);
666
+ if (matched !== null) return matched;
667
+ }
668
+ }
669
+
670
+ if (Object.prototype.hasOwnProperty.call(sourceMap, '*')) {
671
+ return extractCeilingNumber(sourceMap['*']);
672
+ }
673
+
674
+ return null;
675
+ }
676
+
677
+ /**
678
+ * Applies custom ceiling overrides to a cloned catalog object.
679
+ * @param {object} catalog
680
+ * @param {object | null} customCeilings
681
+ * @returns {object}
682
+ */
683
+ function applyCeilingOverrides(catalog, customCeilings) {
684
+ if (!customCeilings || typeof customCeilings !== 'object') {
685
+ return catalog;
686
+ }
687
+
688
+ const sourceMap =
689
+ customCeilings.models && typeof customCeilings.models === 'object'
690
+ ? customCeilings.models
691
+ : customCeilings.ceilings && typeof customCeilings.ceilings === 'object'
692
+ ? customCeilings.ceilings
693
+ : customCeilings;
694
+
695
+ // Global wildcard override if present
696
+ if (typeof sourceMap['*'] === 'number' && sourceMap['*'] > 0) {
697
+ for (const modelSpec of Object.values(catalog.models)) {
698
+ modelSpec.contextCeiling = sourceMap['*'];
699
+ }
700
+ } else if (sourceMap['*'] && typeof sourceMap['*'] === 'object') {
701
+ for (const modelSpec of Object.values(catalog.models)) {
702
+ if (typeof sourceMap['*'].contextCeiling === 'number') {
703
+ modelSpec.contextCeiling = sourceMap['*'].contextCeiling;
704
+ }
705
+ if (typeof sourceMap['*'].operationalSoftCeiling === 'number') {
706
+ modelSpec.operationalSoftCeiling = sourceMap['*'].operationalSoftCeiling;
707
+ }
708
+ }
709
+ }
710
+
711
+ for (const [rawKey, overrideVal] of Object.entries(sourceMap)) {
712
+ if (rawKey === '*' || rawKey === 'schemaVersion') continue;
713
+ const cleanedKey = canonicalizeModelToken(rawKey);
714
+ const normId = catalog.models[rawKey]
715
+ ? rawKey
716
+ : catalog.models[cleanedKey]
717
+ ? cleanedKey
718
+ : normalizeModelId(rawKey, { catalog });
719
+ let target = normId !== UNKNOWN_MODEL_ID ? catalog.models[normId] : null;
720
+ if (!target && overrideVal && typeof overrideVal === 'object' && overrideVal.ratesPer1M) {
721
+ const customId = cleanedKey || rawKey;
722
+ target = {
723
+ id: customId,
724
+ label: overrideVal.label || customId,
725
+ shortLabel: overrideVal.shortLabel || overrideVal.label || customId,
726
+ family: overrideVal.family || 'custom',
727
+ generation: overrideVal.generation || null,
728
+ contextCeiling: Number(overrideVal.contextCeiling || overrideVal.ceiling || 200000),
729
+ operationalSoftCeiling: Number(overrideVal.operationalSoftCeiling || 160000),
730
+ ratesPer1M: { ...overrideVal.ratesPer1M },
731
+ multipliers: overrideVal.multipliers || { write5m: 1.25, write1h: 2.0, read: 0.1 },
732
+ source: overrideVal.source || 'customCeilings.json',
733
+ dateRead: overrideVal.dateRead || null,
734
+ pricingCliff: overrideVal.pricingCliff || null
735
+ };
736
+ catalog.models[customId] = target;
737
+ continue;
738
+ }
739
+ if (!target) continue;
740
+
741
+ if (typeof overrideVal === 'number' && overrideVal > 0) {
742
+ target.contextCeiling = overrideVal;
743
+ } else if (overrideVal && typeof overrideVal === 'object') {
744
+ if (typeof overrideVal.contextCeiling === 'number' && overrideVal.contextCeiling > 0) {
745
+ target.contextCeiling = overrideVal.contextCeiling;
746
+ }
747
+ if (typeof overrideVal.ceiling === 'number' && overrideVal.ceiling > 0) {
748
+ target.contextCeiling = overrideVal.ceiling;
749
+ }
750
+ if (typeof overrideVal.operationalSoftCeiling === 'number' && overrideVal.operationalSoftCeiling > 0) {
751
+ target.operationalSoftCeiling = overrideVal.operationalSoftCeiling;
752
+ }
753
+ if (overrideVal.ratesPer1M && typeof overrideVal.ratesPer1M === 'object') {
754
+ target.ratesPer1M = { ...target.ratesPer1M, ...overrideVal.ratesPer1M };
755
+ }
756
+ }
757
+ }
758
+
759
+ return catalog;
760
+ }
761
+
762
+ /**
763
+ * Loads the unified Anthropic Model Catalog and merges any user `customCeilings.json` overrides.
764
+ * @param {object} [options={}]
765
+ * @returns {object}
766
+ */
767
+ export function loadModelCatalog(options = {}) {
768
+ let baseCatalog = BUILTIN_CATALOG;
769
+ const modDir = getModuleDir(options);
770
+ if (modDir) {
771
+ const jsonPath = path.join(modDir, 'anthropicModelCatalog.json');
772
+ const diskCatalog = readJsonSafe(jsonPath, null, options);
773
+ if (diskCatalog && diskCatalog.models) {
774
+ baseCatalog = diskCatalog;
775
+ }
776
+ }
777
+
778
+ const cloned = JSON.parse(JSON.stringify(baseCatalog));
779
+ const customCeilings = loadCustomCeilings(options);
780
+ return applyCeilingOverrides(cloned, customCeilings);
781
+ }
782
+
783
+ /**
784
+ * Retrieves the model specification for a given model ID.
785
+ * Empty/omitted `modelId` uses `catalog.defaultModel` (`claude-sonnet-5-5`).
786
+ * Any non-empty unrecognized model ID returns an explicit `{ id: 'unknown', unknownModel: true, ratesPer1M: null }`
787
+ * state rather than silently falling back to `claude-sonnet-5-5` (Item 1.2).
788
+ * Honors `[1m]` / `-1m` / `options.extendedContext1M` 1M context windows on Claude 4.x models (`ISS-002`).
789
+ *
790
+ * @param {string} [modelId='']
791
+ * @param {object} [options={}]
792
+ * @returns {object}
793
+ */
794
+ export function getModelSpec(modelId = '', options = {}) {
795
+ const catalog = options.catalog || loadModelCatalog(options);
796
+ const rawTrimmed = String(modelId || '').trim();
797
+ if (!rawTrimmed) {
798
+ const fallbackSpec =
799
+ catalog.models[catalog.defaultModel] || BUILTIN_CATALOG.models['claude-sonnet-5-5'];
800
+ if (
801
+ hasExtended1MHint(modelId, options) &&
802
+ resolveCustomCeilingForModel(fallbackSpec.id, options) === null &&
803
+ fallbackSpec.contextCeiling < 1000000
804
+ ) {
805
+ return {
806
+ ...fallbackSpec,
807
+ contextCeiling: 1000000,
808
+ operationalSoftCeiling: 800000,
809
+ unknownModel: false
810
+ };
811
+ }
812
+ return { ...fallbackSpec, unknownModel: false };
813
+ }
814
+
815
+ const cleaned = canonicalizeModelToken(rawTrimmed);
816
+ const normId = normalizeModelId(rawTrimmed, { ...options, catalog });
817
+ const directCustomSpec =
818
+ catalog.models[cleaned] ||
819
+ (normId !== UNKNOWN_MODEL_ID ? catalog.models[normId] : null);
820
+
821
+ if (!directCustomSpec || normId === UNKNOWN_MODEL_ID) {
822
+ const customCeiling = resolveCustomCeilingForModel(rawTrimmed, options);
823
+ const defaultCeiling = hasExtended1MHint(rawTrimmed, options) ? 1000000 : 200000;
824
+ const contextCeiling = Number(customCeiling || defaultCeiling);
825
+ return {
826
+ id: UNKNOWN_MODEL_ID,
827
+ rawModelId: rawTrimmed,
828
+ unknownModel: true,
829
+ label: `Unknown Model (${rawTrimmed})`,
830
+ shortLabel: 'Unknown Model',
831
+ family: 'unknown',
832
+ generation: null,
833
+ contextCeiling,
834
+ operationalSoftCeiling: Math.round(contextCeiling * 0.8),
835
+ ratesPer1M: null,
836
+ multipliers: null,
837
+ source: null,
838
+ dateRead: null,
839
+ pricingCliff: null,
840
+ advisory: formatUnknownModelAdvisory(rawTrimmed)
841
+ };
842
+ }
843
+
844
+ if (
845
+ (normId === 'claude-opus-4-6' ||
846
+ normId === 'claude-sonnet-4-6' ||
847
+ normId === 'claude-opus-4-5' ||
848
+ normId === 'claude-sonnet-4-5') &&
849
+ hasExtended1MHint(modelId, options) &&
850
+ resolveCustomCeilingForModel(modelId, options) === null
851
+ ) {
852
+ return {
853
+ ...directCustomSpec,
854
+ contextCeiling: 1000000,
855
+ operationalSoftCeiling: 800000,
856
+ unknownModel: false
857
+ };
858
+ }
859
+
860
+ return { ...directCustomSpec, unknownModel: false };
861
+ }
862
+
863
+ /**
864
+ * Extracts normalized prompt & output token counts across all flat, camelCase, snake_case,
865
+ * and nested Anthropic `cache_creation.ephemeral_*` usage formats without double-counting (`ISS-003`, `ISS-004`).
866
+ *
867
+ * @param {object} [usage={}]
868
+ * @returns {{
869
+ * uncachedInputTokens: number,
870
+ * cacheReadTokens: number,
871
+ * write5mTokens: number,
872
+ * write1hTokens: number,
873
+ * remainingGenericWriteTokens: number,
874
+ * effectiveWrite5mTokens: number,
875
+ * effectiveWrite1hTokens: number,
876
+ * totalCacheWriteTokens: number,
877
+ * outputTokens: number,
878
+ * thinkingTokens: number
879
+ * }}
880
+ */
881
+ export function extractNormalizedTokenBreakdown(usage = {}) {
882
+ if (!usage || typeof usage !== 'object') {
883
+ return {
884
+ uncachedInputTokens: 0,
885
+ cacheReadTokens: 0,
886
+ write5mTokens: 0,
887
+ write1hTokens: 0,
888
+ remainingGenericWriteTokens: 0,
889
+ effectiveWrite5mTokens: 0,
890
+ effectiveWrite1hTokens: 0,
891
+ totalCacheWriteTokens: 0,
892
+ outputTokens: 0,
893
+ thinkingTokens: 0
894
+ };
895
+ }
896
+
897
+ const uncachedInputTokens = Math.max(
898
+ 0,
899
+ Number(
900
+ usage.uncachedInputTokens ??
901
+ usage.freshInputTokens ??
902
+ usage.inputTokens ??
903
+ usage.input_tokens ??
904
+ 0
905
+ )
906
+ );
907
+ const cacheReadTokens = Math.max(
908
+ 0,
909
+ Number(
910
+ usage.cacheReadTokens ??
911
+ usage.cacheReadInputTokens ??
912
+ usage.cache_read_input_tokens ??
913
+ 0
914
+ )
915
+ );
916
+
917
+ const nestedCreation =
918
+ usage.cache_creation && typeof usage.cache_creation === 'object'
919
+ ? usage.cache_creation
920
+ : null;
921
+
922
+ const write5mTokens = Math.max(
923
+ 0,
924
+ Number(
925
+ usage.cacheWrite5mTokens ??
926
+ usage.cache_write_5m_tokens ??
927
+ nestedCreation?.ephemeral_5m_input_tokens ??
928
+ 0
929
+ )
930
+ );
931
+ const write1hTokens = Math.max(
932
+ 0,
933
+ Number(
934
+ usage.cacheWrite1hTokens ??
935
+ usage.cache_write_1h_tokens ??
936
+ nestedCreation?.ephemeral_1h_input_tokens ??
937
+ 0
938
+ )
939
+ );
940
+ const genericWriteTokens = Math.max(
941
+ 0,
942
+ Number(
943
+ usage.cacheWriteTokens ??
944
+ usage.cacheCreationInputTokens ??
945
+ usage.cache_creation_input_tokens ??
946
+ usage.lastWriteTokens ??
947
+ 0
948
+ )
949
+ );
950
+
951
+ const remainingGenericWriteTokens = Math.max(
952
+ 0,
953
+ genericWriteTokens - (write5mTokens + write1hTokens)
954
+ );
955
+
956
+ const defaultTier =
957
+ usage.cacheTtlTier === '1h' || usage.ttlTier === '1h' ? '1h' : '5m';
958
+ const effectiveWrite5mTokens =
959
+ write5mTokens + (defaultTier === '5m' ? remainingGenericWriteTokens : 0);
960
+ const effectiveWrite1hTokens =
961
+ write1hTokens + (defaultTier === '1h' ? remainingGenericWriteTokens : 0);
962
+ const totalCacheWriteTokens = effectiveWrite5mTokens + effectiveWrite1hTokens;
963
+
964
+ const outputTokens = Math.max(
965
+ 0,
966
+ Number(usage.outputTokens ?? usage.output_tokens ?? usage.lastOutputTokens ?? 0)
967
+ );
968
+ const thinkingTokens = Math.max(
969
+ 0,
970
+ Number(
971
+ usage.thinkingTokens ??
972
+ usage.thinking_tokens ??
973
+ usage.reasoning_tokens ??
974
+ nestedCreation?.thinking_tokens ??
975
+ usage.lastThinkingTokens ??
976
+ 0
977
+ )
978
+ );
979
+
980
+ return {
981
+ uncachedInputTokens,
982
+ cacheReadTokens,
983
+ write5mTokens,
984
+ write1hTokens,
985
+ remainingGenericWriteTokens,
986
+ effectiveWrite5mTokens,
987
+ effectiveWrite1hTokens,
988
+ totalCacheWriteTokens,
989
+ outputTokens,
990
+ thinkingTokens
991
+ };
992
+ }
993
+
994
+ /**
995
+ * Computes the exact single-turn total prompt token envelope
996
+ * (`uncachedInputTokens + cacheReadTokens + write5mTokens + write1hTokens + remainingGenericWriteTokens`),
997
+ * honoring an optional explicit single-turn `usage.turnPromptTokens` override while never inflating
998
+ * a single turn with multi-turn cumulative sums (`ISS-003`, `ISS-004`).
999
+ *
1000
+ * @param {object} [usage={}]
1001
+ * @returns {number}
1002
+ */
1003
+ export function computeTotalPromptTokens(usage = {}) {
1004
+ if (!usage || typeof usage !== 'object') return 0;
1005
+
1006
+ if (usage.turnPromptTokens !== undefined && usage.turnPromptTokens !== null) {
1007
+ const breakdown = extractNormalizedTokenBreakdown(usage);
1008
+ const splitSum =
1009
+ breakdown.uncachedInputTokens +
1010
+ breakdown.cacheReadTokens +
1011
+ breakdown.totalCacheWriteTokens;
1012
+ return Math.max(splitSum, Math.max(0, Number(usage.turnPromptTokens)));
1013
+ }
1014
+
1015
+ const breakdown = extractNormalizedTokenBreakdown(usage);
1016
+ const hasExplicitCacheRead =
1017
+ usage.cacheReadTokens !== undefined ||
1018
+ usage.cacheReadInputTokens !== undefined ||
1019
+ usage.cache_read_input_tokens !== undefined;
1020
+ const unattributedCached = !hasExplicitCacheRead
1021
+ ? Math.max(
1022
+ 0,
1023
+ Number(usage.cachedTokens ?? usage.cached_tokens ?? 0) - breakdown.totalCacheWriteTokens
1024
+ )
1025
+ : 0;
1026
+
1027
+ const computedPromptTokens =
1028
+ breakdown.uncachedInputTokens +
1029
+ breakdown.cacheReadTokens +
1030
+ breakdown.totalCacheWriteTokens +
1031
+ unattributedCached;
1032
+
1033
+ const hasExplicitUncached =
1034
+ usage.uncachedInputTokens !== undefined ||
1035
+ usage.freshInputTokens !== undefined ||
1036
+ usage.inputTokens !== undefined ||
1037
+ usage.input_tokens !== undefined;
1038
+
1039
+ if (hasExplicitUncached && (hasExplicitCacheRead || breakdown.totalCacheWriteTokens > 0)) {
1040
+ return computedPromptTokens;
1041
+ }
1042
+
1043
+ const explicitSingleTurnTotal = Math.max(
1044
+ 0,
1045
+ Number(
1046
+ usage.totalPromptTokens ?? usage.totalInputTokens ?? usage.total_input_tokens ?? 0
1047
+ )
1048
+ );
1049
+
1050
+ return Math.max(computedPromptTokens, explicitSingleTurnTotal);
1051
+ }
1052
+
1053
+ /**
1054
+ * Resolves the effective USD per 1M token rate card for a model at a given prompt token volume.
1055
+ * Enforces the Claude Haiku 5.5 100,000-token 5x price cliff across all token categories.
1056
+ *
1057
+ * @param {string} [modelId='claude-sonnet-5-5']
1058
+ * @param {number} [totalPromptTokens=0]
1059
+ * @param {object} [options={}]
1060
+ * @returns {{
1061
+ * modelId: string,
1062
+ * label: string,
1063
+ * shortLabel: string,
1064
+ * family: string,
1065
+ * contextCeiling: number,
1066
+ * operationalSoftCeiling: number,
1067
+ * inputPer1M: number,
1068
+ * outputPer1M: number,
1069
+ * write5mPer1M: number,
1070
+ * write1hPer1M: number,
1071
+ * readPer1M: number,
1072
+ * multipliers: { write5m: number, write1h: number, read: number },
1073
+ * cliffTriggered: boolean,
1074
+ * preCliffWarningTriggered: boolean,
1075
+ * cliffThresholdTokens: number | null,
1076
+ * cliffMultiplier: number
1077
+ * }}
1078
+ */
1079
+ export function resolveEffectiveRates(modelId = 'claude-sonnet-5-5', totalPromptTokens = 0, options = {}) {
1080
+ const spec = getModelSpec(modelId, options);
1081
+ const promptTokens = Math.max(0, Number(totalPromptTokens || 0));
1082
+
1083
+ if (spec.unknownModel) {
1084
+ return {
1085
+ modelId: UNKNOWN_MODEL_ID,
1086
+ rawModelId: spec.rawModelId || String(modelId || '').trim(),
1087
+ unknownModel: true,
1088
+ label: spec.label,
1089
+ shortLabel: spec.shortLabel || 'Unknown Model',
1090
+ family: 'unknown',
1091
+ contextCeiling: spec.contextCeiling,
1092
+ operationalSoftCeiling: spec.operationalSoftCeiling,
1093
+ inputPer1M: null,
1094
+ outputPer1M: null,
1095
+ write5mPer1M: null,
1096
+ write1hPer1M: null,
1097
+ readPer1M: null,
1098
+ multipliers: null,
1099
+ source: null,
1100
+ dateRead: null,
1101
+ cliffTriggered: false,
1102
+ preCliffWarningTriggered: false,
1103
+ cliffThresholdTokens: null,
1104
+ cliffMultiplier: 1.0,
1105
+ advisory: spec.advisory || formatUnknownModelAdvisory(modelId)
1106
+ };
1107
+ }
1108
+
1109
+ const cliff = spec.pricingCliff || null;
1110
+ const cliffTriggered = Boolean(cliff && promptTokens > cliff.thresholdTokens);
1111
+ const preCliffWarningTriggered = Boolean(
1112
+ cliff && promptTokens >= (cliff.preCliffWarningTokens || cliff.thresholdTokens * 0.9)
1113
+ );
1114
+
1115
+ const activeRates = cliffTriggered && cliff.ratesPer1MAboveCliff
1116
+ ? cliff.ratesPer1MAboveCliff
1117
+ : spec.ratesPer1M;
1118
+
1119
+ return {
1120
+ modelId: spec.id,
1121
+ unknownModel: false,
1122
+ label: spec.label,
1123
+ shortLabel: spec.shortLabel || spec.label,
1124
+ family: spec.family,
1125
+ contextCeiling: spec.contextCeiling,
1126
+ operationalSoftCeiling: spec.operationalSoftCeiling,
1127
+ inputPer1M: activeRates.input,
1128
+ outputPer1M: activeRates.output,
1129
+ write5mPer1M: activeRates.write5m,
1130
+ write1hPer1M: activeRates.write1h,
1131
+ readPer1M: activeRates.read,
1132
+ multipliers: { ...spec.multipliers },
1133
+ source: spec.source || null,
1134
+ dateRead: spec.dateRead || null,
1135
+ cliffTriggered,
1136
+ preCliffWarningTriggered,
1137
+ cliffThresholdTokens: cliff ? cliff.thresholdTokens : null,
1138
+ cliffMultiplier: cliffTriggered ? cliff.multiplier : 1.0
1139
+ };
1140
+ }
1141
+
1142
+ /**
1143
+ * Computes exact USD turn cost and uncached equivalent baseline for a single turn.
1144
+ *
1145
+ * @param {object} [usage={}]
1146
+ * @param {string} [usage.model='claude-sonnet-5-5']
1147
+ * @param {number} [usage.inputTokens=0] - Uncached input tokens
1148
+ * @param {number} [usage.outputTokens=0] - Output tokens
1149
+ * @param {number} [usage.thinkingTokens=0] - Extended thinking tokens (billed at output rate)
1150
+ * @param {number} [usage.cacheWriteTokens=0] - Cache write tokens (uses cacheTtlTier if 5m/1h not split)
1151
+ * @param {number} [usage.cacheWrite5mTokens=0] - Explicit 5-minute cache write tokens
1152
+ * @param {number} [usage.cacheWrite1hTokens=0] - Explicit 1-hour cache write tokens
1153
+ * @param {number} [usage.cacheReadTokens=0] - Cache read tokens
1154
+ * @param {number} [usage.turnPromptTokens] - Optional explicit single-turn prompt size for cliff evaluation
1155
+ * @param {number} [usage.totalPromptTokens] - Optional explicit single-turn prompt size for cliff evaluation
1156
+ * @param {'5m'|'1h'} [usage.cacheTtlTier='5m'] - Default TTL tier when cacheWriteTokens is unsplit
1157
+ * @param {object} [options={}]
1158
+ */
1159
+ export function calculateTurnCostUSD(usage = {}, options = {}) {
1160
+ const breakdown = extractNormalizedTokenBreakdown(usage);
1161
+ const uncachedInput = breakdown.uncachedInputTokens;
1162
+ const outputTokens = breakdown.outputTokens;
1163
+ const thinkingTokens = breakdown.thinkingTokens;
1164
+ const cacheReadTokens = breakdown.cacheReadTokens;
1165
+ const write5mTokens = breakdown.effectiveWrite5mTokens;
1166
+ const write1hTokens = breakdown.effectiveWrite1hTokens;
1167
+ const totalCacheWriteTokens = breakdown.totalCacheWriteTokens;
1168
+ const totalPromptTokens = computeTotalPromptTokens(usage);
1169
+
1170
+ const rawModel = usage.model || usage.modelId || 'claude-sonnet-5-5';
1171
+ const rates = resolveEffectiveRates(rawModel, totalPromptTokens, options);
1172
+
1173
+ if (rates.unknownModel) {
1174
+ return {
1175
+ modelId: UNKNOWN_MODEL_ID,
1176
+ rawModelId: rates.rawModelId || String(rawModel),
1177
+ unknownModel: true,
1178
+ advisory: rates.advisory,
1179
+ rates,
1180
+ tokens: {
1181
+ uncachedInput,
1182
+ cacheWrite5m: write5mTokens,
1183
+ cacheWrite1h: write1hTokens,
1184
+ totalCacheWrite: totalCacheWriteTokens,
1185
+ cacheRead: cacheReadTokens,
1186
+ totalPrompt: totalPromptTokens,
1187
+ output: outputTokens,
1188
+ thinking: thinkingTokens,
1189
+ totalOutput: outputTokens + thinkingTokens
1190
+ },
1191
+ costsUSD: {
1192
+ uncachedInput: null,
1193
+ write5m: null,
1194
+ write1h: null,
1195
+ cacheRead: null,
1196
+ output: null,
1197
+ actualCacheSpendUSD: null,
1198
+ uncachedCacheEquivalentUSD: null,
1199
+ totalActualSpendUSD: null,
1200
+ totalUncachedEquivalentUSD: null,
1201
+ netCacheSavingsUSD: null
1202
+ },
1203
+ cliffTriggered: false,
1204
+ preCliffWarningTriggered: false
1205
+ };
1206
+ }
1207
+
1208
+ const inputCostUSD = (uncachedInput / 1_000_000) * rates.inputPer1M;
1209
+ const write5mCostUSD = (write5mTokens / 1_000_000) * rates.write5mPer1M;
1210
+ const write1hCostUSD = (write1hTokens / 1_000_000) * rates.write1hPer1M;
1211
+ const readCostUSD = (cacheReadTokens / 1_000_000) * rates.readPer1M;
1212
+ const outputCostUSD = ((outputTokens + thinkingTokens) / 1_000_000) * rates.outputPer1M;
1213
+
1214
+ const actualCacheSpendUSD = write5mCostUSD + write1hCostUSD + readCostUSD;
1215
+ const uncachedCacheEquivalentUSD = ((totalCacheWriteTokens + cacheReadTokens) / 1_000_000) * rates.inputPer1M;
1216
+
1217
+ const totalActualSpendUSD = inputCostUSD + actualCacheSpendUSD + outputCostUSD;
1218
+ const totalUncachedEquivalentUSD = inputCostUSD + uncachedCacheEquivalentUSD + outputCostUSD;
1219
+ const netCacheSavingsUSD = totalUncachedEquivalentUSD - totalActualSpendUSD;
1220
+
1221
+ return {
1222
+ modelId: rates.modelId,
1223
+ unknownModel: false,
1224
+ rates,
1225
+ tokens: {
1226
+ uncachedInput,
1227
+ cacheWrite5m: write5mTokens,
1228
+ cacheWrite1h: write1hTokens,
1229
+ totalCacheWrite: totalCacheWriteTokens,
1230
+ cacheRead: cacheReadTokens,
1231
+ totalPrompt: totalPromptTokens,
1232
+ output: outputTokens,
1233
+ thinking: thinkingTokens,
1234
+ totalOutput: outputTokens + thinkingTokens
1235
+ },
1236
+ costsUSD: {
1237
+ uncachedInput: Number(inputCostUSD.toFixed(6)),
1238
+ write5m: Number(write5mCostUSD.toFixed(6)),
1239
+ write1h: Number(write1hCostUSD.toFixed(6)),
1240
+ cacheRead: Number(readCostUSD.toFixed(6)),
1241
+ output: Number(outputCostUSD.toFixed(6)),
1242
+ actualCacheSpendUSD: Number(actualCacheSpendUSD.toFixed(6)),
1243
+ uncachedCacheEquivalentUSD: Number(uncachedCacheEquivalentUSD.toFixed(6)),
1244
+ totalActualSpendUSD: Number(totalActualSpendUSD.toFixed(6)),
1245
+ totalUncachedEquivalentUSD: Number(totalUncachedEquivalentUSD.toFixed(6)),
1246
+ netCacheSavingsUSD: Number(netCacheSavingsUSD.toFixed(6))
1247
+ },
1248
+ cliffTriggered: rates.cliffTriggered,
1249
+ preCliffWarningTriggered: rates.preCliffWarningTriggered
1250
+ };
1251
+ }
1252
+
1253
+ export default {
1254
+ BUILTIN_CATALOG,
1255
+ UNKNOWN_MODEL_ID,
1256
+ formatUnknownModelAdvisory,
1257
+ hasExtended1MHint,
1258
+ isKnownCatalogModel,
1259
+ normalizeModelId,
1260
+ loadCustomCeilings,
1261
+ resolveCustomCeilingForModel,
1262
+ loadModelCatalog,
1263
+ getModelSpec,
1264
+ extractNormalizedTokenBreakdown,
1265
+ computeTotalPromptTokens,
1266
+ resolveEffectiveRates,
1267
+ calculateTurnCostUSD
1268
+ };