ctxtop 4.1.0 → 4.1.1

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 (318) hide show
  1. package/.antigravity-plugin/plugin.json +1 -1
  2. package/.claude-plugin/plugin.json +21 -18
  3. package/CHECKSUMS.sha256 +51 -44
  4. package/LICENSE +27 -27
  5. package/README.md +90 -56
  6. package/SECURITY.md +7 -1
  7. package/assets/hero-demo.svg +1 -1
  8. package/bin/ctxtop.mjs +267 -54
  9. package/config/modelCatalog.json +847 -273
  10. package/hooks/handlers/hookIpcClient.mjs +8 -4
  11. package/hooks/handlers/post-model-switch.mjs +39 -2
  12. package/hooks/handlers/post-tool-use-core.mjs +394 -0
  13. package/hooks/handlers/post-tool-use.mjs +54 -321
  14. package/hooks/handlers/pre-model-switch.mjs +115 -5
  15. package/hooks/handlers/pre-tool-use-core.mjs +680 -0
  16. package/hooks/handlers/pre-tool-use.mjs +61 -571
  17. package/hooks/handlers/stop-gate.mjs +20 -8
  18. package/hooks/handlers/user-prompt-submit.mjs +111 -2
  19. package/hooks/post_tool_use.mjs +17 -4
  20. package/hooks/pre_tool_use.mjs +84 -54
  21. package/hooks.json +56 -56
  22. package/package.json +4 -3
  23. package/packages/antigravity/package.json +10 -3
  24. package/packages/antigravity/src/adapter.mjs +109 -0
  25. package/packages/antigravity/src/index.mjs +7 -1
  26. package/packages/claude-code/package.json +10 -3
  27. package/packages/claude-code/src/adapter.mjs +194 -0
  28. package/packages/claude-code/src/index.mjs +8 -2
  29. package/packages/claude-code/src/register.js +726 -0
  30. package/packages/core/package.json +6 -2
  31. package/packages/core/src/catalog/detectorCatalog.mjs +558 -0
  32. package/packages/core/src/catalog/index.mjs +1 -0
  33. package/packages/core/src/catalog/safeguardGuide.mjs +412 -0
  34. package/packages/core/src/coach/cacheGravityRouter.mjs +1547 -0
  35. package/packages/core/src/coach/effortShiftDetector.mjs +316 -0
  36. package/packages/core/src/coach/microSkills.mjs +1 -0
  37. package/packages/core/src/coach/promptHygieneGovernor.mjs +1 -0
  38. package/packages/core/src/coach/repoCalibration.mjs +254 -0
  39. package/packages/core/src/coach/resumeToolsetAuditor.mjs +321 -0
  40. package/packages/core/src/coach/savedQuotaLedger.mjs +527 -0
  41. package/packages/core/src/coach/smartCompactAdvisor.mjs +339 -0
  42. package/packages/core/src/coach/stateBatonHydrator.mjs +810 -0
  43. package/packages/core/src/coach/ttlWatchdog.mjs +464 -0
  44. package/packages/core/src/config/anthropicModelCatalog.json +607 -0
  45. package/packages/core/src/config/catalogLoader.mjs +1271 -0
  46. package/packages/core/src/config/horizonConfig.mjs +1055 -0
  47. package/packages/core/src/control/callTree.mjs +338 -0
  48. package/packages/core/src/control/coachLatches.mjs +126 -0
  49. package/packages/core/src/control/controlStateMachine.mjs +205 -0
  50. package/packages/core/src/control/index.mjs +49 -0
  51. package/packages/core/src/control/swarmWorktree.mjs +109 -0
  52. package/packages/core/src/control/toolSuspension.mjs +197 -0
  53. package/packages/core/src/diagnostics/drift_guard.mjs +382 -0
  54. package/packages/core/src/diagnostics/index.mjs +9 -0
  55. package/packages/core/src/diagnostics/micro_skills.mjs +471 -0
  56. package/packages/core/src/diagnostics/prompt_hygiene_governor.mjs +888 -0
  57. package/packages/core/src/economics/billingBlocks.mjs +251 -0
  58. package/packages/core/src/economics/cacheGravity.mjs +371 -0
  59. package/packages/core/src/economics/cliffBreaker.mjs +256 -0
  60. package/packages/core/src/economics/driftLatency.mjs +433 -0
  61. package/packages/core/src/economics/dualTtl.mjs +198 -0
  62. package/packages/core/src/economics/index.mjs +47 -0
  63. package/packages/core/src/economics/retentionRadar.mjs +348 -0
  64. package/packages/core/src/economics/shadowAutoModel.mjs +228 -0
  65. package/packages/core/src/guards/bucketBAlphaBeta.mjs +860 -0
  66. package/packages/core/src/guards/bucketBGamma.mjs +442 -0
  67. package/packages/core/src/guards/bucketBHeuristics.mjs +37 -0
  68. package/packages/core/src/guards/circuitBreakers.mjs +1202 -0
  69. package/packages/core/src/guards/det01_03_shell_secret.mjs +1184 -0
  70. package/packages/core/src/guards/det04_12_thrash_rot.mjs +572 -0
  71. package/packages/core/src/guards/det13_20_mcp_scope.mjs +913 -0
  72. package/packages/core/src/guards/docIndexCore.mjs +446 -0
  73. package/packages/core/src/guards/losslessPostSanitizer.mjs +317 -0
  74. package/packages/core/src/guards/slopsquatGate.mjs +551 -0
  75. package/packages/core/src/index.js +27 -0
  76. package/packages/core/src/index.mjs +25 -1
  77. package/packages/core/src/telemetry/otelExporter.mjs +187 -0
  78. package/packages/core/src/telemetry/scopeLockRegistry.mjs +522 -0
  79. package/packages/core/src/telemetry/sprintMetrics.mjs +327 -0
  80. package/packages/core/src/telemetry/swarmTopology.mjs +152 -0
  81. package/packages/core/src/telemetry/telemetryBridge.mjs +1232 -0
  82. package/packages/core/src/ui/brailleSparkline.mjs +142 -0
  83. package/packages/core/src/ui/costRadarSvg.mjs +276 -0
  84. package/packages/core/src/ui/horizonGrid.mjs +475 -0
  85. package/packages/core/src/ui/horizonPanelHtml.mjs +1502 -0
  86. package/packages/core/src/ui/modViews.mjs +1558 -0
  87. package/packages/core/src/ui/pdfReceiptGenerator.mjs +329 -0
  88. package/packages/core/src/ustf/index.mjs +7 -0
  89. package/packages/core/src/ustf/normalizer.mjs +512 -0
  90. package/packages/core/src/ustf/schema.mjs +186 -0
  91. package/packages/core/src/utils/runtime.mjs +962 -0
  92. package/packages/engine-node/package.json +6 -2
  93. package/packages/engine-node/src/db/index.mjs +58 -0
  94. package/packages/engine-node/src/db/jsonl_fallback.mjs +184 -0
  95. package/packages/engine-node/src/db/probe.mjs +342 -0
  96. package/packages/engine-node/src/db/sqlite_wrapper.mjs +122 -0
  97. package/packages/engine-node/src/index.mjs +11 -1
  98. package/packages/engine-node/src/ipc/client.mjs +447 -0
  99. package/packages/engine-node/src/ipc/fast_client.mjs +191 -0
  100. package/packages/engine-node/src/ipc/index.mjs +24 -0
  101. package/packages/engine-node/src/ipc/protocol.mjs +177 -0
  102. package/packages/engine-node/src/ipc/server.mjs +445 -0
  103. package/packages/engine-node/src/multi_host_mcp.mjs +168 -0
  104. package/packages/engine-node/src/offloader/index.mjs +6 -0
  105. package/packages/engine-node/src/offloader/tool_offloader.mjs +241 -0
  106. package/packages/engine-node/src/rsl/index.mjs +3 -0
  107. package/packages/engine-node/src/sensors/blindspots.mjs +376 -0
  108. package/packages/engine-node/src/sensors/git_merge_tree.mjs +223 -0
  109. package/packages/engine-node/src/sensors/index.mjs +7 -0
  110. package/packages/engine-node/src/vendor/config/default_flightcheck.json +133 -0
  111. package/packages/engine-node/src/vendor/config/modelCatalog.json +1359 -0
  112. package/packages/engine-node/src/vendor/config/platformQuirks.json +19 -0
  113. package/packages/engine-node/src/vendor/core/atomic_io.mjs +124 -0
  114. package/packages/engine-node/src/vendor/core/constants.mjs +2150 -0
  115. package/packages/engine-node/src/vendor/core/doc_indexer.mjs +338 -0
  116. package/packages/engine-node/src/vendor/core/rsl_clash_auditor.mjs +423 -0
  117. package/packages/engine-node/src/vendor/core/rsl_distiller.mjs +394 -0
  118. package/packages/engine-node/src/vendor/core/rsl_ledger.mjs +1029 -0
  119. package/packages/engine-node/src/vendor/core/rsl_triage.mjs +1051 -0
  120. package/packages/engine-node/src/vendor/core/shield_manager.mjs +1417 -0
  121. package/packages/engine-node/src/vendor/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  122. package/packages/engine-node/src/vendor/core-isomorphic/catalog/index.mjs +1 -0
  123. package/packages/engine-node/src/vendor/core-isomorphic/catalog/safeguardGuide.mjs +412 -0
  124. package/packages/engine-node/src/vendor/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
  125. package/packages/engine-node/src/vendor/core-isomorphic/coach/effortShiftDetector.mjs +316 -0
  126. package/packages/engine-node/src/vendor/core-isomorphic/coach/microSkills.mjs +1 -0
  127. package/packages/engine-node/src/vendor/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  128. package/packages/engine-node/src/vendor/core-isomorphic/coach/repoCalibration.mjs +254 -0
  129. package/packages/engine-node/src/vendor/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  130. package/packages/engine-node/src/vendor/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  131. package/packages/engine-node/src/vendor/core-isomorphic/coach/smartCompactAdvisor.mjs +339 -0
  132. package/packages/engine-node/src/vendor/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  133. package/packages/engine-node/src/vendor/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
  134. package/packages/engine-node/src/vendor/core-isomorphic/config/anthropicModelCatalog.json +607 -0
  135. package/packages/engine-node/src/vendor/core-isomorphic/config/catalogLoader.mjs +1271 -0
  136. package/packages/engine-node/src/vendor/core-isomorphic/config/horizonConfig.mjs +1055 -0
  137. package/packages/engine-node/src/vendor/core-isomorphic/control/callTree.mjs +338 -0
  138. package/packages/engine-node/src/vendor/core-isomorphic/control/coachLatches.mjs +126 -0
  139. package/packages/engine-node/src/vendor/core-isomorphic/control/controlStateMachine.mjs +205 -0
  140. package/packages/engine-node/src/vendor/core-isomorphic/control/index.mjs +49 -0
  141. package/packages/engine-node/src/vendor/core-isomorphic/control/swarmWorktree.mjs +109 -0
  142. package/packages/engine-node/src/vendor/core-isomorphic/control/toolSuspension.mjs +197 -0
  143. package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  144. package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/index.mjs +9 -0
  145. package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  146. package/packages/engine-node/src/vendor/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
  147. package/packages/engine-node/src/vendor/core-isomorphic/economics/billingBlocks.mjs +251 -0
  148. package/packages/engine-node/src/vendor/core-isomorphic/economics/cacheGravity.mjs +371 -0
  149. package/packages/engine-node/src/vendor/core-isomorphic/economics/cliffBreaker.mjs +256 -0
  150. package/packages/engine-node/src/vendor/core-isomorphic/economics/driftLatency.mjs +433 -0
  151. package/packages/engine-node/src/vendor/core-isomorphic/economics/dualTtl.mjs +198 -0
  152. package/packages/engine-node/src/vendor/core-isomorphic/economics/index.mjs +47 -0
  153. package/packages/engine-node/src/vendor/core-isomorphic/economics/retentionRadar.mjs +348 -0
  154. package/packages/engine-node/src/vendor/core-isomorphic/economics/shadowAutoModel.mjs +228 -0
  155. package/packages/engine-node/src/vendor/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  156. package/packages/engine-node/src/vendor/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  157. package/packages/engine-node/src/vendor/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  158. package/packages/engine-node/src/vendor/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  159. package/packages/engine-node/src/vendor/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
  160. package/packages/engine-node/src/vendor/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
  161. package/packages/engine-node/src/vendor/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
  162. package/packages/engine-node/src/vendor/core-isomorphic/guards/docIndexCore.mjs +446 -0
  163. package/packages/engine-node/src/vendor/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
  164. package/packages/engine-node/src/vendor/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  165. package/packages/engine-node/src/vendor/core-isomorphic/index.js +27 -0
  166. package/packages/engine-node/src/vendor/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  167. package/packages/engine-node/src/vendor/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  168. package/packages/engine-node/src/vendor/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  169. package/packages/engine-node/src/vendor/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  170. package/packages/engine-node/src/vendor/core-isomorphic/telemetry/telemetryBridge.mjs +1232 -0
  171. package/packages/engine-node/src/vendor/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  172. package/packages/engine-node/src/vendor/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  173. package/packages/engine-node/src/vendor/core-isomorphic/ui/horizonGrid.mjs +475 -0
  174. package/packages/engine-node/src/vendor/core-isomorphic/ui/horizonPanelHtml.mjs +1502 -0
  175. package/packages/engine-node/src/vendor/core-isomorphic/ui/modViews.mjs +1558 -0
  176. package/packages/engine-node/src/vendor/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  177. package/packages/engine-node/src/vendor/core-isomorphic/ustf/index.mjs +7 -0
  178. package/packages/engine-node/src/vendor/core-isomorphic/ustf/normalizer.mjs +512 -0
  179. package/packages/engine-node/src/vendor/core-isomorphic/ustf/schema.mjs +186 -0
  180. package/packages/engine-node/src/vendor/core-isomorphic/utils/runtime.mjs +962 -0
  181. package/packages/mcp/package.json +7 -3
  182. package/packages/mcp/src/server.mjs +115 -14
  183. package/packages/mcp/src/vendor/config/default_flightcheck.json +133 -0
  184. package/packages/mcp/src/vendor/config/modelCatalog.json +1359 -0
  185. package/packages/mcp/src/vendor/config/platformQuirks.json +19 -0
  186. package/packages/mcp/src/vendor/core/atomic_io.mjs +124 -0
  187. package/packages/mcp/src/vendor/core/coach/saved_quota_ledger.mjs +615 -0
  188. package/packages/mcp/src/vendor/core/constants.mjs +2150 -0
  189. package/packages/mcp/src/vendor/core/doc_indexer.mjs +338 -0
  190. package/packages/mcp/src/vendor/core/fts5_output_compressor.mjs +596 -0
  191. package/packages/mcp/src/vendor/core/hook_diagnostics.mjs +158 -0
  192. package/packages/mcp/src/vendor/core/paths.mjs +311 -0
  193. package/packages/mcp/src/vendor/core/session_auditor.mjs +1109 -0
  194. package/packages/mcp/src/vendor/core/sqlite_client.mjs +289 -0
  195. package/packages/mcp/src/vendor/core/telemetry/scope_lock_registry.mjs +578 -0
  196. package/packages/mcp/src/vendor/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  197. package/packages/mcp/src/vendor/core-isomorphic/catalog/index.mjs +1 -0
  198. package/packages/mcp/src/vendor/core-isomorphic/catalog/safeguardGuide.mjs +412 -0
  199. package/packages/mcp/src/vendor/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
  200. package/packages/mcp/src/vendor/core-isomorphic/coach/effortShiftDetector.mjs +316 -0
  201. package/packages/mcp/src/vendor/core-isomorphic/coach/microSkills.mjs +1 -0
  202. package/packages/mcp/src/vendor/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  203. package/packages/mcp/src/vendor/core-isomorphic/coach/repoCalibration.mjs +254 -0
  204. package/packages/mcp/src/vendor/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  205. package/packages/mcp/src/vendor/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  206. package/packages/mcp/src/vendor/core-isomorphic/coach/smartCompactAdvisor.mjs +339 -0
  207. package/packages/mcp/src/vendor/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  208. package/packages/mcp/src/vendor/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
  209. package/packages/mcp/src/vendor/core-isomorphic/config/anthropicModelCatalog.json +607 -0
  210. package/packages/mcp/src/vendor/core-isomorphic/config/catalogLoader.mjs +1271 -0
  211. package/packages/mcp/src/vendor/core-isomorphic/config/horizonConfig.mjs +1055 -0
  212. package/packages/mcp/src/vendor/core-isomorphic/control/callTree.mjs +338 -0
  213. package/packages/mcp/src/vendor/core-isomorphic/control/coachLatches.mjs +126 -0
  214. package/packages/mcp/src/vendor/core-isomorphic/control/controlStateMachine.mjs +205 -0
  215. package/packages/mcp/src/vendor/core-isomorphic/control/index.mjs +49 -0
  216. package/packages/mcp/src/vendor/core-isomorphic/control/swarmWorktree.mjs +109 -0
  217. package/packages/mcp/src/vendor/core-isomorphic/control/toolSuspension.mjs +197 -0
  218. package/packages/mcp/src/vendor/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  219. package/packages/mcp/src/vendor/core-isomorphic/diagnostics/index.mjs +9 -0
  220. package/packages/mcp/src/vendor/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  221. package/packages/mcp/src/vendor/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
  222. package/packages/mcp/src/vendor/core-isomorphic/economics/billingBlocks.mjs +251 -0
  223. package/packages/mcp/src/vendor/core-isomorphic/economics/cacheGravity.mjs +371 -0
  224. package/packages/mcp/src/vendor/core-isomorphic/economics/cliffBreaker.mjs +256 -0
  225. package/packages/mcp/src/vendor/core-isomorphic/economics/driftLatency.mjs +433 -0
  226. package/packages/mcp/src/vendor/core-isomorphic/economics/dualTtl.mjs +198 -0
  227. package/packages/mcp/src/vendor/core-isomorphic/economics/index.mjs +47 -0
  228. package/packages/mcp/src/vendor/core-isomorphic/economics/retentionRadar.mjs +348 -0
  229. package/packages/mcp/src/vendor/core-isomorphic/economics/shadowAutoModel.mjs +228 -0
  230. package/packages/mcp/src/vendor/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  231. package/packages/mcp/src/vendor/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  232. package/packages/mcp/src/vendor/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  233. package/packages/mcp/src/vendor/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  234. package/packages/mcp/src/vendor/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
  235. package/packages/mcp/src/vendor/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
  236. package/packages/mcp/src/vendor/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
  237. package/packages/mcp/src/vendor/core-isomorphic/guards/docIndexCore.mjs +446 -0
  238. package/packages/mcp/src/vendor/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
  239. package/packages/mcp/src/vendor/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  240. package/packages/mcp/src/vendor/core-isomorphic/index.js +27 -0
  241. package/packages/mcp/src/vendor/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  242. package/packages/mcp/src/vendor/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  243. package/packages/mcp/src/vendor/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  244. package/packages/mcp/src/vendor/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  245. package/packages/mcp/src/vendor/core-isomorphic/telemetry/telemetryBridge.mjs +1232 -0
  246. package/packages/mcp/src/vendor/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  247. package/packages/mcp/src/vendor/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  248. package/packages/mcp/src/vendor/core-isomorphic/ui/horizonGrid.mjs +475 -0
  249. package/packages/mcp/src/vendor/core-isomorphic/ui/horizonPanelHtml.mjs +1502 -0
  250. package/packages/mcp/src/vendor/core-isomorphic/ui/modViews.mjs +1558 -0
  251. package/packages/mcp/src/vendor/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  252. package/packages/mcp/src/vendor/core-isomorphic/ustf/index.mjs +7 -0
  253. package/packages/mcp/src/vendor/core-isomorphic/ustf/normalizer.mjs +512 -0
  254. package/packages/mcp/src/vendor/core-isomorphic/ustf/schema.mjs +186 -0
  255. package/packages/mcp/src/vendor/core-isomorphic/utils/runtime.mjs +962 -0
  256. package/packages/mcp/src/vendor/engine-node/db/probe.mjs +342 -0
  257. package/packages/mcp/src/vendor/pro/pro_license.mjs +547 -0
  258. package/packages/pro/package.json +23 -16
  259. package/packages/pro/src/index.mjs +9 -3
  260. package/packages/pro/src/pro_license.mjs +547 -0
  261. package/packages/pro/src/team_finops_pack.mjs +241 -241
  262. package/packages/pro/workers/polar_webhook_worker.mjs +219 -215
  263. package/plugin.json +1 -1
  264. package/sidecars/horizon-daemon/server.mjs +482 -44
  265. package/src/cli/doctor.mjs +11 -2
  266. package/src/cli/horizon_hud.mjs +31 -15
  267. package/src/cli/init.mjs +46 -13
  268. package/src/config/modelCatalog.json +886 -231
  269. package/src/core/classifier.mjs +25 -11
  270. package/src/core/coach/circuit_breakers.mjs +84 -6
  271. package/src/core/coach/task_quota_router.mjs +8 -0
  272. package/src/core/code_fold_lite.mjs +169 -0
  273. package/src/core/config.mjs +44 -0
  274. package/src/core/constants.mjs +175 -12
  275. package/src/core/detectors_det01_to_16.mjs +44 -3
  276. package/src/core/fts5_output_compressor.mjs +272 -35
  277. package/src/core/horizon_config.mjs +42 -0
  278. package/src/core/parser.mjs +86 -11
  279. package/src/core/pro_license.mjs +174 -12
  280. package/src/core/pruner.mjs +7 -146
  281. package/src/core/quota.mjs +14 -2
  282. package/src/core/rsl_distiller.mjs +31 -9
  283. package/src/core/rsl_ledger.mjs +66 -6
  284. package/src/core/rsl_triage.mjs +159 -17
  285. package/src/core/session_auditor.mjs +476 -25
  286. package/src/core/shadow_auto_ledger.mjs +205 -0
  287. package/src/core/sqlite_client.mjs +10 -4
  288. package/src/core/subagents.mjs +18 -2
  289. package/src/core/task_quota_router.mjs +61 -4
  290. package/src/core-isomorphic/catalog/safeguardGuide.mjs +412 -0
  291. package/src/core-isomorphic/coach/effortShiftDetector.mjs +316 -0
  292. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +54 -20
  293. package/src/core-isomorphic/config/anthropicModelCatalog.json +1 -0
  294. package/src/core-isomorphic/config/catalogLoader.mjs +6 -3
  295. package/src/core-isomorphic/config/horizonConfig.mjs +1 -1
  296. package/src/core-isomorphic/economics/cacheGravity.mjs +3 -1
  297. package/src/core-isomorphic/economics/shadowAutoModel.mjs +228 -0
  298. package/src/core-isomorphic/guards/bucketBGamma.mjs +1 -1
  299. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +77 -1
  300. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +395 -130
  301. package/src/core-isomorphic/ui/modViews.mjs +62 -8
  302. package/src/diagnostics/claudeHookCapabilities.mjs +32 -2
  303. package/src/diagnostics/doctorEngine.mjs +28 -2
  304. package/src/engine-node/ipc/fast_client.mjs +191 -0
  305. package/src/engine-node/ipc/index.mjs +2 -0
  306. package/src/engine-node/multi_host_mcp.mjs +168 -0
  307. package/src/hooks/antigravity_rsl_hook.mjs +24 -2
  308. package/src/hooks/claude_rsl_hook.mjs +22 -2
  309. package/src/hooks/daemon_hook_bridge.mjs +256 -0
  310. package/src/hooks/fast_hook_ipc.mjs +295 -0
  311. package/src/hooks/post_invocation.mjs +37 -597
  312. package/src/hooks/post_invocation_core.mjs +623 -0
  313. package/src/hooks/pre_invocation.mjs +103 -1668
  314. package/src/hooks/pre_invocation_core.mjs +1830 -0
  315. package/src/utils/sessionCalibration.mjs +52 -5
  316. package/src/webview/advanced_view.html +34 -18
  317. package/src/webview/horizon_panel.html +3233 -675
  318. package/src/webview/simple_view.html +1 -1
@@ -0,0 +1,2150 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { fileURLToPath } from 'node:url';
5
+
6
+ const __constantsDirname = path.dirname(fileURLToPath(import.meta.url));
7
+ const __srcCatalogCandidate = path.resolve(__constantsDirname, '../config/modelCatalog.json');
8
+ const __rootCatalogCandidate = path.resolve(__constantsDirname, '../../config/modelCatalog.json');
9
+ export const DEFAULT_MODEL_CATALOG_PATH = fs.existsSync(__srcCatalogCandidate)
10
+ ? __srcCatalogCandidate
11
+ : __rootCatalogCandidate;
12
+
13
+ export const HORIZON_WINDOW = {
14
+ MAX_TOKENS: 200000,
15
+ TOTAL_CELLS: 40,
16
+ CELL_SIZE_TOKENS: 5000,
17
+ AMPUTATION_THRESHOLD_TOKENS: 140000,
18
+ AMPUTATION_CELL_COUNT: 8, // Earliest 20% = Cells 0..7 (40,000 tokens)
19
+ STALE_STEP_THRESHOLD: 25,
20
+ ACTIVE_SET_STEP_WINDOW: 8
21
+ };
22
+
23
+ export const SESSION_RISK_THRESHOLDS = Object.freeze({
24
+ SAFE_HORIZON_TOKENS: 179000, // 70% of 256k Cortex hard clamp
25
+ CASCADE_SYNC_WATERMARK_TOKENS: 50000, // 50k Cascade checkpointer arming threshold
26
+ WARM_CACHE_LOCK_TOKENS: 50000, // >50k cached tokens triggers prefix-lock warning
27
+ LEAN_SESSION_TOKENS: 25000, // <25k lean session floor for cold cache escalation
28
+ CACHE_TTL_EXPIRED_SECONDS: 0
29
+ });
30
+
31
+ export const SURFACE_TAGS = Object.freeze({
32
+ 'antigravity': '[App]',
33
+ 'antigravity-ide': '[IDE]',
34
+ 'antigravity-cli': '[CLI]',
35
+ 'claude-code': '[Claude]',
36
+ 'claude': '[Claude]',
37
+ 'cursor': '[Cursor]',
38
+ 'app': '[App]',
39
+ 'ide': '[IDE]',
40
+ 'cli': '[CLI]'
41
+ });
42
+
43
+ export const PREFIX_LOCK_WARNING_TEXT =
44
+ 'Active warm cache (>50k tokens). Switching models (within or across families) triggers a full uncached cache rebuild; on Claude, changing reasoning effort also re-bills cached chat history (Gemini thinking-level changes keep the cache).';
45
+
46
+ export const CORTEX_CLAMPED_CEILING_LABEL =
47
+ '256k Host Cap (1M model)';
48
+
49
+ export const PATCHED_CLI_CEILING_TIERS = Object.freeze([512000, 900000]);
50
+
51
+ export const WATERMARK_TOOLTIPS = Object.freeze({
52
+ CASCADE_SYNC_ARMED:
53
+ '50k Cascade Sync Armed: Crossing 50k arms the automatic checkpointer. Completing a task.md item or switching subagents will trigger synchronous auto-compaction.',
54
+ ATTENTION_HORIZON:
55
+ 'Attention Horizon (Safe Limit): Practical recall threshold (70% of ceiling, 179k on 256k).',
56
+ CORTEX_HARD_CLAMP:
57
+ 'Hard assembly limit (cortex/utils.GetCheckpointConfig).'
58
+ });
59
+
60
+ export const STRANDED_SIGNAL_WARNING_TEXT =
61
+ 'Stranded in Low-Attention Trough. Risk of recall decay during multi-file reasoning. Re-reference in active prompt or anchor to task.md.';
62
+
63
+ export const ATTENTION_TROUGH_CONFIG = Object.freeze({
64
+ GAMMA: 0.6,
65
+ TROUGH_START_RATIO: 0.30,
66
+ TROUGH_END_RATIO: 0.70,
67
+ CANONICAL_TROUGH_START_CELL: 6, // 0-indexed (Cell #7 in 1-indexed UI, or Cell index 7..15)
68
+ CANONICAL_TROUGH_END_CELL: 15
69
+ });
70
+
71
+ /**
72
+ * Resolves a human-readable surface badge ('[App]' | '[IDE]' | '[CLI]' | '[Claude]' | '[Cursor]') from a store name or path.
73
+ */
74
+ export function resolveSurfaceTag(surfaceOrPath = 'antigravity') {
75
+ const s = String(surfaceOrPath || '').toLowerCase().trim();
76
+ if (s.includes('claude') || s === '[claude]') return '[Claude]';
77
+ if (s.includes('cursor') || s.endsWith('.vscdb') || s === '[cursor]') return '[Cursor]';
78
+ if (s.includes('antigravity-cli') || s === 'cli' || s === '[cli]') return '[CLI]';
79
+ if (s.includes('antigravity-ide') || s === 'ide' || s === '[ide]') return '[IDE]';
80
+ return '[App]';
81
+ }
82
+
83
+ export const CATEGORIES = {
84
+ ANCHOR: 'ANCHOR',
85
+ MEMORY_KI: 'MEMORY_KI',
86
+ FOREIGN_BLEED: 'FOREIGN_BLEED',
87
+ STALE_DUPLICATE: 'STALE_DUPLICATE',
88
+ DEAD_ERROR: 'DEAD_ERROR',
89
+ ACTIVE_WORKING_SET: 'ACTIVE_WORKING_SET',
90
+ FREE_HEADROOM: 'FREE_HEADROOM'
91
+ };
92
+
93
+ export const CATEGORY_METADATA = {
94
+ ANCHOR: {
95
+ label: 'Anchors (Rules & Plan)',
96
+ ansi256: 51,
97
+ ansiCode: '\x1b[38;5;51m',
98
+ hex: '#00d7ff',
99
+ symbol: '█',
100
+ priority: 1
101
+ },
102
+ MEMORY_KI: {
103
+ label: 'Knowledge Memory',
104
+ ansi256: 135,
105
+ ansiCode: '\x1b[38;5;135m',
106
+ hex: '#af5fff',
107
+ symbol: '▓',
108
+ priority: 2
109
+ },
110
+ FOREIGN_BLEED: {
111
+ label: 'Foreign KI Bleed',
112
+ ansi256: 198,
113
+ ansiCode: '\x1b[38;5;198m',
114
+ hex: '#ff0087',
115
+ symbol: '▓',
116
+ priority: 2
117
+ },
118
+ STALE_DUPLICATE: {
119
+ label: 'Stale / Duplicate Reads',
120
+ ansi256: 214,
121
+ ansiCode: '\x1b[38;5;214m',
122
+ hex: '#ffaf00',
123
+ symbol: '▒',
124
+ priority: 3
125
+ },
126
+ DEAD_ERROR: {
127
+ label: 'Resolved Dead Errors',
128
+ ansi256: 196,
129
+ ansiCode: '\x1b[38;5;196m',
130
+ hex: '#ff0000',
131
+ symbol: '▓',
132
+ priority: 4
133
+ },
134
+ ACTIVE_WORKING_SET: {
135
+ label: 'Active Working Set',
136
+ ansi256: 46,
137
+ ansiCode: '\x1b[38;5;46m',
138
+ hex: '#00ff00',
139
+ symbol: '█',
140
+ priority: 5
141
+ },
142
+ FREE_HEADROOM: {
143
+ label: 'Free Headroom',
144
+ ansi256: 238,
145
+ ansiCode: '\x1b[38;5;238m',
146
+ hex: '#334155',
147
+ symbol: '░',
148
+ priority: 6
149
+ }
150
+ };
151
+
152
+ export const CARBON_RATE_CLIFF_UTC = '2026-12-01T00:00:00Z';
153
+ export const CARBON_RATE_CLIFF_MS = Date.parse(CARBON_RATE_CLIFF_UTC);
154
+ export const LEGACY_MODEL_SUNSET_UTC = '2026-11-18T00:00:00Z';
155
+ export const LEGACY_MODEL_SUNSET_MS = Date.parse(LEGACY_MODEL_SUNSET_UTC);
156
+ export const SHARED_1M_CONTEXT_POOL_TOKENS = 1048576; // 1,048,576 unified context ceiling
157
+
158
+ export const ANTIGRAVITY_ENUM_ALIASES = Object.freeze({
159
+ 'm427': 'gemini-4-carbon',
160
+ 'm437': 'gemini-4-carbon',
161
+ 'm438': 'gemini-4-carbon',
162
+ 'm670': 'gemini-4-carbon-cyber-permissive',
163
+ 'orchestrator': 'gemini-4-carbon',
164
+ 'orchestrator-carbon': 'gemini-4-carbon',
165
+ 'antigravity-orchestrator': 'gemini-4-carbon',
166
+ 'gemini-pro-orchestrator': 'gemini-4-carbon',
167
+ 'gemini-pro-orchestrator-argon': 'gemini-4-argon',
168
+ 'orchestrator-argon': 'gemini-4-argon',
169
+ 'gemini-pro-orchestrator-hydrogen': 'gemini-4-hydrogen',
170
+ 'orchestrator-hydrogen': 'gemini-4-hydrogen'
171
+ });
172
+
173
+ export const PLAN_TIER_RANK = Object.freeze({
174
+ free: 0,
175
+ pro: 1,
176
+ ultra: 2,
177
+ enterprise: 3
178
+ });
179
+
180
+ export const CARBON_RATE_SCHEDULES = Object.freeze([
181
+ Object.freeze({
182
+ id: 'carbon-introductory-pre-2026-12-01',
183
+ window: 'introductory',
184
+ effective_from_utc: null,
185
+ effective_until_utc: '2026-11-30T23:59:59Z',
186
+ standard: Object.freeze({
187
+ input_per_1m: 2.00,
188
+ output_per_1m: 10.00,
189
+ write_5m_per_1m: 2.00,
190
+ write_1h_per_1m: 2.00,
191
+ cached_read_per_1m: 0.10
192
+ }),
193
+ priority: Object.freeze({
194
+ input_per_1m: 3.60,
195
+ output_per_1m: 18.00,
196
+ write_5m_per_1m: 3.60,
197
+ write_1h_per_1m: 3.60,
198
+ cached_read_per_1m: 0.10
199
+ })
200
+ }),
201
+ Object.freeze({
202
+ id: 'carbon-standard-from-2026-12-01',
203
+ window: 'post_introductory',
204
+ effective_from_utc: CARBON_RATE_CLIFF_UTC,
205
+ effective_until_utc: null,
206
+ standard: Object.freeze({
207
+ input_per_1m: 4.00,
208
+ output_per_1m: 20.00,
209
+ write_5m_per_1m: 4.00,
210
+ write_1h_per_1m: 4.00,
211
+ cached_read_per_1m: 0.20
212
+ }),
213
+ priority: Object.freeze({
214
+ input_per_1m: 7.20,
215
+ output_per_1m: 36.00,
216
+ write_5m_per_1m: 7.20,
217
+ write_1h_per_1m: 7.20,
218
+ cached_read_per_1m: 0.20
219
+ })
220
+ })
221
+ ]);
222
+
223
+ export const FLASH_RATE_CLIFF_UTC = '2027-01-01T00:00:00Z';
224
+ export const FLASH_RATE_CLIFF_MS = Date.parse(FLASH_RATE_CLIFF_UTC);
225
+
226
+ export const FLASH_RATE_SCHEDULES = Object.freeze([
227
+ Object.freeze({
228
+ id: 'flash-introductory-pre-2027-01-01',
229
+ window: 'introductory',
230
+ effective_from_utc: null,
231
+ effective_until_utc: '2026-12-31T23:59:59Z',
232
+ standard: Object.freeze({
233
+ input_per_1m: 0.75,
234
+ output_per_1m: 3.75,
235
+ write_5m_per_1m: 0.75,
236
+ write_1h_per_1m: 0.75,
237
+ cached_read_per_1m: 0.075
238
+ }),
239
+ priority: Object.freeze({
240
+ input_per_1m: 1.35,
241
+ output_per_1m: 6.75,
242
+ write_5m_per_1m: 1.35,
243
+ write_1h_per_1m: 1.35,
244
+ cached_read_per_1m: 0.075
245
+ })
246
+ }),
247
+ Object.freeze({
248
+ id: 'flash-standard-from-2027-01-01',
249
+ window: 'post_introductory',
250
+ effective_from_utc: FLASH_RATE_CLIFF_UTC,
251
+ effective_until_utc: null,
252
+ standard: Object.freeze({
253
+ input_per_1m: 1.50,
254
+ output_per_1m: 7.50,
255
+ write_5m_per_1m: 1.50,
256
+ write_1h_per_1m: 1.50,
257
+ cached_read_per_1m: 0.15
258
+ }),
259
+ priority: Object.freeze({
260
+ input_per_1m: 2.70,
261
+ output_per_1m: 13.50,
262
+ write_5m_per_1m: 2.70,
263
+ write_1h_per_1m: 2.70,
264
+ cached_read_per_1m: 0.15
265
+ })
266
+ })
267
+ ]);
268
+
269
+ export const HYDROGEN_RATE_SCHEDULES = Object.freeze([
270
+ Object.freeze({
271
+ id: 'hydrogen-standard-from-2026-11-12',
272
+ window: 'standard',
273
+ effective_from_utc: null,
274
+ effective_until_utc: null,
275
+ standard: Object.freeze({
276
+ input_per_1m: 1.50,
277
+ output_per_1m: 7.50,
278
+ write_5m_per_1m: 1.50,
279
+ write_1h_per_1m: 1.50,
280
+ cached_read_per_1m: 0.075
281
+ }),
282
+ priority: Object.freeze({
283
+ input_per_1m: 2.70,
284
+ output_per_1m: 13.50,
285
+ write_5m_per_1m: 2.70,
286
+ write_1h_per_1m: 2.70,
287
+ cached_read_per_1m: 0.075
288
+ })
289
+ })
290
+ ]);
291
+
292
+ /**
293
+ * Frozen Schema Gate Definitions for Shared Core (`ModelDescriptor`, `RateSchedule`, `AgentCacheKey`, `SwarmAgentState`).
294
+ */
295
+ export const CORE_SCHEMAS = Object.freeze({
296
+ ModelDescriptor: Object.freeze({
297
+ required: ['id', 'family', 'label', 'supported_efforts', 'caching_mode', 'supports_explicit_cache', 'antigravity_min_tier', 'shared_pool_ceiling'],
298
+ properties: {
299
+ id: 'string',
300
+ aliases: 'array',
301
+ family: 'string',
302
+ label: 'string',
303
+ supported_efforts: 'array',
304
+ caching_mode: 'string',
305
+ supports_explicit_cache: 'boolean',
306
+ antigravity_min_tier: 'string',
307
+ shared_pool_ceiling: 'number',
308
+ deprecated_after: 'string|null',
309
+ rate_schedules: 'array'
310
+ }
311
+ }),
312
+ RateSchedule: Object.freeze({
313
+ required: ['standard', 'priority'],
314
+ properties: {
315
+ effective_from_utc: 'string|null',
316
+ effective_until_utc: 'string|null',
317
+ standard: 'object',
318
+ priority: 'object'
319
+ }
320
+ }),
321
+ AgentCacheKey: Object.freeze({
322
+ pattern: /^[^:]+::[^:]+::[^:]+$/,
323
+ delimiter: '::',
324
+ defaultAgentId: 'primary'
325
+ }),
326
+ SwarmAgentState: Object.freeze({
327
+ required: ['agent_id', 'model_id', 'status', 'last_active_timestamp', 'warm_prefix_tokens'],
328
+ validStatuses: Object.freeze(['active', 'idle_zero_token', 'terminated']),
329
+ defaultCacheTtlMs: 300000,
330
+ defaultColdWakeThresholdTokens: 100000
331
+ })
332
+ });
333
+
334
+ function buildAnthropicSchedule({ input, output, write5m, write1h, cachedRead }) {
335
+ const tier = Object.freeze({
336
+ input_per_1m: input,
337
+ output_per_1m: output,
338
+ write_5m_per_1m: write5m,
339
+ write_1h_per_1m: write1h,
340
+ cached_read_per_1m: cachedRead
341
+ });
342
+ return Object.freeze([
343
+ Object.freeze({
344
+ effective_from_utc: null,
345
+ effective_until_utc: null,
346
+ standard: tier,
347
+ priority: tier
348
+ })
349
+ ]);
350
+ }
351
+
352
+ export const MODEL_REGISTRY = Object.freeze({
353
+ 'gemini-4-carbon': Object.freeze({
354
+ id: 'gemini-4-carbon',
355
+ aliases: Object.freeze([
356
+ 'gemini-4-carbon-high',
357
+ 'gemini-4-carbon-medium',
358
+ 'gemini-4-carbon-med',
359
+ 'gemini-4-carbon-low',
360
+ 'M427',
361
+ 'M437',
362
+ 'M438',
363
+ 'gemini-pro-orchestrator',
364
+ 'orchestrator',
365
+ 'orchestrator-carbon',
366
+ 'antigravity-orchestrator'
367
+ ]),
368
+ family: 'carbon',
369
+ label: 'Gemini 4 Carbon',
370
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
371
+ supported_effort_tiers: Object.freeze(['low', 'medium', 'high']),
372
+ caching_mode: 'implicit_only',
373
+ supports_explicit_cache: false,
374
+ antigravity_min_tier: 'ultra',
375
+ shared_pool_ceiling: SHARED_1M_CONTEXT_POOL_TOKENS,
376
+ shared_context_pool_tokens: SHARED_1M_CONTEXT_POOL_TOKENS,
377
+ max_output_tokens: null,
378
+ deprecated_after: null,
379
+ rate_schedules: CARBON_RATE_SCHEDULES
380
+ }),
381
+ 'gemini-4-carbon-cyber-permissive': Object.freeze({
382
+ id: 'gemini-4-carbon-cyber-permissive',
383
+ aliases: Object.freeze(['M670']),
384
+ family: 'carbon',
385
+ label: 'Gemini 4 Carbon (Cyber Permissive)',
386
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
387
+ supported_effort_tiers: Object.freeze(['low', 'medium', 'high']),
388
+ caching_mode: 'implicit_only',
389
+ supports_explicit_cache: false,
390
+ antigravity_min_tier: 'ultra',
391
+ shared_pool_ceiling: SHARED_1M_CONTEXT_POOL_TOKENS,
392
+ shared_context_pool_tokens: SHARED_1M_CONTEXT_POOL_TOKENS,
393
+ max_output_tokens: null,
394
+ deprecated_after: null,
395
+ rate_schedules: CARBON_RATE_SCHEDULES
396
+ }),
397
+ 'gemini-4-argon': Object.freeze({
398
+ id: 'gemini-4-argon',
399
+ aliases: Object.freeze([
400
+ 'gemini-4-argon-high',
401
+ 'gemini-4-argon-medium',
402
+ 'gemini-4-argon-med',
403
+ 'gemini-4-argon-low',
404
+ 'gemini-pro-orchestrator-argon',
405
+ 'orchestrator-argon'
406
+ ]),
407
+ family: 'argon',
408
+ label: 'Gemini 4 Argon',
409
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
410
+ supported_effort_tiers: Object.freeze(['low', 'medium', 'high']),
411
+ caching_mode: 'implicit_only',
412
+ supports_explicit_cache: false,
413
+ antigravity_min_tier: 'pro',
414
+ shared_pool_ceiling: SHARED_1M_CONTEXT_POOL_TOKENS,
415
+ shared_context_pool_tokens: SHARED_1M_CONTEXT_POOL_TOKENS,
416
+ max_output_tokens: null,
417
+ deprecated_after: null,
418
+ rate_schedules: CARBON_RATE_SCHEDULES
419
+ }),
420
+ 'gemini-4-hydrogen': Object.freeze({
421
+ id: 'gemini-4-hydrogen',
422
+ aliases: Object.freeze([
423
+ 'gemini-4-hydrogen-xhigh',
424
+ 'gemini-4-hydrogen-extra-high',
425
+ 'gemini-4-hydrogen-high',
426
+ 'gemini-4-hydrogen-medium',
427
+ 'gemini-4-hydrogen-med',
428
+ 'gemini-4-hydrogen-low',
429
+ 'orchestrator-hydrogen',
430
+ 'gemini-pro-orchestrator-hydrogen'
431
+ ]),
432
+ family: 'hydrogen',
433
+ label: 'Gemini 4 Hydrogen',
434
+ supported_efforts: Object.freeze(['low', 'medium', 'high', 'xhigh']),
435
+ supported_effort_tiers: Object.freeze(['low', 'medium', 'high', 'xhigh']),
436
+ caching_mode: 'implicit_only',
437
+ supports_explicit_cache: false,
438
+ antigravity_min_tier: 'pro',
439
+ shared_pool_ceiling: SHARED_1M_CONTEXT_POOL_TOKENS,
440
+ shared_context_pool_tokens: SHARED_1M_CONTEXT_POOL_TOKENS,
441
+ max_output_tokens: 65536,
442
+ deprecated_after: null,
443
+ rate_schedules: HYDROGEN_RATE_SCHEDULES
444
+ }),
445
+ 'gemini-3.8-flash': Object.freeze({
446
+ id: 'gemini-3.8-flash',
447
+ aliases: Object.freeze([
448
+ 'gemini-3.8-flash-high',
449
+ 'gemini-3.8-flash-medium',
450
+ 'gemini-3.8-flash-med',
451
+ 'gemini-3.8-flash-low'
452
+ ]),
453
+ family: 'flash',
454
+ label: 'Gemini 3.8 Flash',
455
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
456
+ caching_mode: 'implicit_only',
457
+ supports_explicit_cache: false,
458
+ antigravity_min_tier: 'free',
459
+ shared_pool_ceiling: 256000,
460
+ max_output_tokens: null,
461
+ deprecated_after: null,
462
+ rate_schedules: FLASH_RATE_SCHEDULES
463
+ }),
464
+ 'claude-haiku-5-5': Object.freeze({
465
+ id: 'claude-haiku-5-5',
466
+ aliases: Object.freeze(['claude-haiku-5.5', 'haiku-5-5', 'haiku-5.5']),
467
+ family: 'haiku',
468
+ label: 'Claude Haiku 5.5',
469
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
470
+ caching_mode: 'explicit_and_implicit',
471
+ supports_explicit_cache: true,
472
+ antigravity_min_tier: 'pro',
473
+ shared_pool_ceiling: 1000000,
474
+ max_output_tokens: null,
475
+ deprecated_after: null,
476
+ prompt_cliff_tokens: 100000,
477
+ rate_schedules: Object.freeze([
478
+ Object.freeze({
479
+ effective_from_utc: null,
480
+ effective_until_utc: null,
481
+ standard: Object.freeze({
482
+ input_per_1m: 0.10,
483
+ output_per_1m: 0.50,
484
+ write_5m_per_1m: 0.125,
485
+ write_1h_per_1m: 0.20,
486
+ cached_read_per_1m: 0.01
487
+ }),
488
+ cliff_over_100k: Object.freeze({
489
+ input_per_1m: 0.50,
490
+ output_per_1m: 2.50,
491
+ write_5m_per_1m: 0.625,
492
+ write_1h_per_1m: 1.00,
493
+ cached_read_per_1m: 0.05
494
+ }),
495
+ priority: Object.freeze({
496
+ input_per_1m: 0.10,
497
+ output_per_1m: 0.50,
498
+ write_5m_per_1m: 0.125,
499
+ write_1h_per_1m: 0.20,
500
+ cached_read_per_1m: 0.01
501
+ })
502
+ })
503
+ ])
504
+ }),
505
+ 'claude-sonnet-5-5': Object.freeze({
506
+ id: 'claude-sonnet-5-5',
507
+ aliases: Object.freeze(['claude-sonnet-5.5', 'sonnet-5-5', 'sonnet-5.5']),
508
+ family: 'sonnet',
509
+ label: 'Claude Sonnet 5.5',
510
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
511
+ caching_mode: 'explicit_and_implicit',
512
+ supports_explicit_cache: true,
513
+ antigravity_min_tier: 'pro',
514
+ shared_pool_ceiling: 1000000,
515
+ max_output_tokens: null,
516
+ deprecated_after: null,
517
+ rate_schedules: buildAnthropicSchedule({ input: 2.00, output: 10.00, write5m: 2.50, write1h: 4.00, cachedRead: 0.10 })
518
+ }),
519
+ 'claude-opus-5-5': Object.freeze({
520
+ id: 'claude-opus-5-5',
521
+ aliases: Object.freeze(['claude-opus-5.5', 'opus-5-5', 'opus-5.5']),
522
+ family: 'opus',
523
+ label: 'Claude Opus 5.5',
524
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
525
+ caching_mode: 'explicit_and_implicit',
526
+ supports_explicit_cache: true,
527
+ antigravity_min_tier: 'pro',
528
+ shared_pool_ceiling: 1000000,
529
+ max_output_tokens: null,
530
+ deprecated_after: null,
531
+ rate_schedules: buildAnthropicSchedule({ input: 4.00, output: 20.00, write5m: 5.00, write1h: 8.00, cachedRead: 0.20 })
532
+ }),
533
+ 'claude-fable-5-2': Object.freeze({
534
+ id: 'claude-fable-5-2',
535
+ aliases: Object.freeze(['claude-fable-5.2', 'fable-5-2', 'fable-5.2']),
536
+ family: 'fable',
537
+ label: 'Claude Fable 5.2',
538
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
539
+ caching_mode: 'explicit_and_implicit',
540
+ supports_explicit_cache: true,
541
+ antigravity_min_tier: 'ultra',
542
+ shared_pool_ceiling: 1000000,
543
+ max_output_tokens: 128000,
544
+ deprecated_after: null,
545
+ rate_schedules: buildAnthropicSchedule({ input: 8.00, output: 40.00, write5m: 10.00, write1h: 16.00, cachedRead: 0.20 })
546
+ }),
547
+ 'claude-fable-5-1': Object.freeze({
548
+ id: 'claude-fable-5-1',
549
+ aliases: Object.freeze(['claude-fable-5.1', 'fable-5-1', 'fable-5.1']),
550
+ family: 'fable',
551
+ label: 'Claude Fable 5.1',
552
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
553
+ caching_mode: 'explicit_and_implicit',
554
+ supports_explicit_cache: true,
555
+ antigravity_min_tier: 'ultra',
556
+ shared_pool_ceiling: 1000000,
557
+ max_output_tokens: 128000,
558
+ deprecated_after: null,
559
+ rate_schedules: buildAnthropicSchedule({ input: 10.00, output: 50.00, write5m: 12.50, write1h: 20.00, cachedRead: 0.25 })
560
+ }),
561
+ 'claude-fable-5': Object.freeze({
562
+ id: 'claude-fable-5',
563
+ aliases: Object.freeze(['fable-5']),
564
+ family: 'fable',
565
+ label: 'Claude Fable 5',
566
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
567
+ caching_mode: 'explicit_and_implicit',
568
+ supports_explicit_cache: true,
569
+ antigravity_min_tier: 'ultra',
570
+ shared_pool_ceiling: 1000000,
571
+ max_output_tokens: null,
572
+ deprecated_after: null,
573
+ rate_schedules: buildAnthropicSchedule({ input: 10.00, output: 50.00, write5m: 12.50, write1h: 20.00, cachedRead: 1.00 })
574
+ }),
575
+ 'claude-mythos-5-2': Object.freeze({
576
+ id: 'claude-mythos-5-2',
577
+ aliases: Object.freeze(['claude-mythos-5.2', 'mythos-5-2', 'mythos-5.2']),
578
+ family: 'mythos',
579
+ label: 'Claude Mythos 5.2',
580
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
581
+ caching_mode: 'explicit_and_implicit',
582
+ supports_explicit_cache: true,
583
+ antigravity_min_tier: 'ultra',
584
+ shared_pool_ceiling: 1000000,
585
+ max_output_tokens: 128000,
586
+ deprecated_after: null,
587
+ rate_schedules: buildAnthropicSchedule({ input: 8.00, output: 40.00, write5m: 10.00, write1h: 16.00, cachedRead: 0.20 })
588
+ }),
589
+ 'claude-mythos-5-1': Object.freeze({
590
+ id: 'claude-mythos-5-1',
591
+ aliases: Object.freeze(['claude-mythos-5.1', 'mythos-5-1', 'mythos-5.1']),
592
+ family: 'mythos',
593
+ label: 'Claude Mythos 5.1',
594
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
595
+ caching_mode: 'explicit_and_implicit',
596
+ supports_explicit_cache: true,
597
+ antigravity_min_tier: 'ultra',
598
+ shared_pool_ceiling: 1000000,
599
+ max_output_tokens: 128000,
600
+ deprecated_after: null,
601
+ rate_schedules: buildAnthropicSchedule({ input: 10.00, output: 50.00, write5m: 12.50, write1h: 20.00, cachedRead: 0.25 })
602
+ }),
603
+ 'claude-mythos-5': Object.freeze({
604
+ id: 'claude-mythos-5',
605
+ aliases: Object.freeze(['mythos-5']),
606
+ family: 'mythos',
607
+ label: 'Claude Mythos 5',
608
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
609
+ caching_mode: 'explicit_and_implicit',
610
+ supports_explicit_cache: true,
611
+ antigravity_min_tier: 'ultra',
612
+ shared_pool_ceiling: 1000000,
613
+ max_output_tokens: 128000,
614
+ deprecated_after: null,
615
+ rate_schedules: buildAnthropicSchedule({ input: 10.00, output: 50.00, write5m: 12.50, write1h: 20.00, cachedRead: 1.00 })
616
+ }),
617
+ 'claude-opus-5': Object.freeze({
618
+ id: 'claude-opus-5',
619
+ aliases: Object.freeze(['opus-5']),
620
+ family: 'opus',
621
+ label: 'Claude Opus 5',
622
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
623
+ caching_mode: 'explicit_and_implicit',
624
+ supports_explicit_cache: true,
625
+ antigravity_min_tier: 'pro',
626
+ shared_pool_ceiling: 1000000,
627
+ max_output_tokens: null,
628
+ deprecated_after: null,
629
+ rate_schedules: buildAnthropicSchedule({ input: 5.00, output: 25.00, write5m: 6.25, write1h: 10.00, cachedRead: 0.50 })
630
+ }),
631
+ 'claude-sonnet-5': Object.freeze({
632
+ id: 'claude-sonnet-5',
633
+ aliases: Object.freeze(['sonnet-5']),
634
+ family: 'sonnet',
635
+ label: 'Claude Sonnet 5',
636
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
637
+ caching_mode: 'explicit_and_implicit',
638
+ supports_explicit_cache: true,
639
+ antigravity_min_tier: 'pro',
640
+ shared_pool_ceiling: 1000000,
641
+ max_output_tokens: null,
642
+ deprecated_after: null,
643
+ rate_schedules: buildAnthropicSchedule({ input: 2.00, output: 10.00, write5m: 2.50, write1h: 4.00, cachedRead: 0.20 })
644
+ }),
645
+ 'claude-opus-4-8': Object.freeze({
646
+ id: 'claude-opus-4-8',
647
+ aliases: Object.freeze(['claude-opus-4.8', 'opus-4-8', 'opus-4.8']),
648
+ family: 'opus',
649
+ label: 'Claude Opus 4.8',
650
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
651
+ caching_mode: 'explicit_and_implicit',
652
+ supports_explicit_cache: true,
653
+ antigravity_min_tier: 'pro',
654
+ shared_pool_ceiling: 1000000,
655
+ max_output_tokens: null,
656
+ deprecated_after: null,
657
+ rate_schedules: buildAnthropicSchedule({ input: 5.00, output: 25.00, write5m: 6.25, write1h: 10.00, cachedRead: 0.50 })
658
+ }),
659
+ 'claude-opus-4-7': Object.freeze({
660
+ id: 'claude-opus-4-7',
661
+ aliases: Object.freeze(['claude-opus-4.7', 'opus-4-7', 'opus-4.7']),
662
+ family: 'opus',
663
+ label: 'Claude Opus 4.7',
664
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
665
+ caching_mode: 'explicit_and_implicit',
666
+ supports_explicit_cache: true,
667
+ antigravity_min_tier: 'pro',
668
+ shared_pool_ceiling: 1000000,
669
+ max_output_tokens: null,
670
+ deprecated_after: null,
671
+ rate_schedules: buildAnthropicSchedule({ input: 5.00, output: 25.00, write5m: 6.25, write1h: 10.00, cachedRead: 0.50 })
672
+ }),
673
+ 'claude-sonnet-4-6': Object.freeze({
674
+ id: 'claude-sonnet-4-6',
675
+ aliases: Object.freeze(['claude-sonnet-4.6', 'sonnet-4-6', 'sonnet-4.6']),
676
+ family: 'sonnet',
677
+ label: 'Claude Sonnet 4.6',
678
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
679
+ caching_mode: 'explicit_and_implicit',
680
+ supports_explicit_cache: true,
681
+ antigravity_min_tier: 'pro',
682
+ shared_pool_ceiling: 200000,
683
+ max_output_tokens: null,
684
+ deprecated_after: LEGACY_MODEL_SUNSET_UTC,
685
+ rate_schedules: buildAnthropicSchedule({ input: 3.00, output: 15.00, write5m: 3.75, write1h: 6.00, cachedRead: 0.30 })
686
+ }),
687
+ 'claude-sonnet-4-5': Object.freeze({
688
+ id: 'claude-sonnet-4-5',
689
+ aliases: Object.freeze(['claude-sonnet-4.5', 'sonnet-4-5', 'sonnet-4.5']),
690
+ family: 'sonnet',
691
+ label: 'Claude Sonnet 4.5',
692
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
693
+ caching_mode: 'explicit_and_implicit',
694
+ supports_explicit_cache: true,
695
+ antigravity_min_tier: 'pro',
696
+ shared_pool_ceiling: 200000,
697
+ max_output_tokens: null,
698
+ deprecated_after: null,
699
+ rate_schedules: buildAnthropicSchedule({ input: 3.00, output: 15.00, write5m: 3.75, write1h: 6.00, cachedRead: 0.30 })
700
+ }),
701
+ 'claude-opus-4-6': Object.freeze({
702
+ id: 'claude-opus-4-6',
703
+ aliases: Object.freeze(['claude-opus-4.6', 'claude-opus-4-6-thinking', 'opus-4-6', 'opus-4.6']),
704
+ family: 'opus',
705
+ label: 'Claude Opus 4.6',
706
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
707
+ caching_mode: 'explicit_and_implicit',
708
+ supports_explicit_cache: true,
709
+ antigravity_min_tier: 'pro',
710
+ shared_pool_ceiling: 200000,
711
+ max_output_tokens: null,
712
+ deprecated_after: LEGACY_MODEL_SUNSET_UTC,
713
+ rate_schedules: buildAnthropicSchedule({ input: 5.00, output: 25.00, write5m: 6.25, write1h: 10.00, cachedRead: 0.50 })
714
+ }),
715
+ 'claude-opus-4-5': Object.freeze({
716
+ id: 'claude-opus-4-5',
717
+ aliases: Object.freeze(['claude-opus-4.5', 'opus-4-5', 'opus-4.5']),
718
+ family: 'opus',
719
+ label: 'Claude Opus 4.5',
720
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
721
+ caching_mode: 'explicit_and_implicit',
722
+ supports_explicit_cache: true,
723
+ antigravity_min_tier: 'pro',
724
+ shared_pool_ceiling: 200000,
725
+ max_output_tokens: null,
726
+ deprecated_after: null,
727
+ rate_schedules: buildAnthropicSchedule({ input: 5.00, output: 25.00, write5m: 6.25, write1h: 10.00, cachedRead: 0.50 })
728
+ }),
729
+ 'claude-haiku-4-5': Object.freeze({
730
+ id: 'claude-haiku-4-5',
731
+ aliases: Object.freeze(['claude-haiku-4.5', 'haiku-4-5', 'haiku-4.5']),
732
+ family: 'haiku',
733
+ label: 'Claude Haiku 4.5',
734
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
735
+ caching_mode: 'explicit_and_implicit',
736
+ supports_explicit_cache: true,
737
+ antigravity_min_tier: 'pro',
738
+ shared_pool_ceiling: 200000,
739
+ max_output_tokens: null,
740
+ deprecated_after: null,
741
+ rate_schedules: buildAnthropicSchedule({ input: 1.00, output: 5.00, write5m: 1.25, write1h: 2.00, cachedRead: 0.10 })
742
+ }),
743
+ 'gpt-oss-120b': Object.freeze({
744
+ id: 'gpt-oss-120b',
745
+ aliases: Object.freeze(['gpt-oss']),
746
+ family: 'gpt-oss',
747
+ label: 'GPT-OSS 120B',
748
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
749
+ caching_mode: 'implicit_only',
750
+ supports_explicit_cache: false,
751
+ antigravity_min_tier: 'pro',
752
+ shared_pool_ceiling: 128000,
753
+ max_output_tokens: null,
754
+ deprecated_after: LEGACY_MODEL_SUNSET_UTC,
755
+ rate_schedules: Object.freeze([
756
+ Object.freeze({
757
+ effective_from_utc: null,
758
+ effective_until_utc: null,
759
+ standard: Object.freeze({
760
+ input_per_1m: 1.00,
761
+ output_per_1m: 3.00,
762
+ write_5m_per_1m: 1.00,
763
+ write_1h_per_1m: 1.00,
764
+ cached_read_per_1m: 0.10
765
+ }),
766
+ priority: Object.freeze({
767
+ input_per_1m: 1.00,
768
+ output_per_1m: 3.00,
769
+ write_5m_per_1m: 1.00,
770
+ write_1h_per_1m: 1.00,
771
+ cached_read_per_1m: 0.10
772
+ })
773
+ })
774
+ ])
775
+ }),
776
+ 'gemini-3.1-pro': Object.freeze({
777
+ id: 'gemini-3.1-pro',
778
+ aliases: Object.freeze(['gemini-3.1-pro-preview', 'gemini-3-1-pro', 'gemini-3-1-pro-preview']),
779
+ family: 'gemini-pro',
780
+ label: 'Gemini 3.1 Pro',
781
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
782
+ caching_mode: 'explicit_and_implicit',
783
+ supports_explicit_cache: true,
784
+ antigravity_min_tier: 'pro',
785
+ shared_pool_ceiling: 1000000,
786
+ max_output_tokens: null,
787
+ deprecated_after: null,
788
+ prompt_cliff_tokens: 200000,
789
+ rate_schedules: Object.freeze([
790
+ Object.freeze({
791
+ effective_from_utc: null,
792
+ effective_until_utc: null,
793
+ standard: Object.freeze({
794
+ input_per_1m: 1.25,
795
+ output_per_1m: 10.00,
796
+ write_5m_per_1m: 1.25,
797
+ write_1h_per_1m: 1.25,
798
+ cached_read_per_1m: 0.125
799
+ }),
800
+ cliff_over_200k: Object.freeze({
801
+ input_per_1m: 2.50,
802
+ output_per_1m: 15.00,
803
+ write_5m_per_1m: 2.50,
804
+ write_1h_per_1m: 2.50,
805
+ cached_read_per_1m: 0.25
806
+ }),
807
+ priority: Object.freeze({
808
+ input_per_1m: 1.25,
809
+ output_per_1m: 10.00,
810
+ write_5m_per_1m: 1.25,
811
+ write_1h_per_1m: 1.25,
812
+ cached_read_per_1m: 0.125
813
+ })
814
+ })
815
+ ])
816
+ }),
817
+ 'gemini-2.5-pro': Object.freeze({
818
+ id: 'gemini-2.5-pro',
819
+ aliases: Object.freeze(['gemini-2.5-pro-preview', 'gemini-2-5-pro', 'gemini-2.5-pro-1m']),
820
+ family: 'gemini-pro',
821
+ label: 'Gemini 2.5 Pro',
822
+ supported_efforts: Object.freeze(['low', 'medium', 'high']),
823
+ caching_mode: 'explicit_and_implicit',
824
+ supports_explicit_cache: true,
825
+ antigravity_min_tier: 'pro',
826
+ shared_pool_ceiling: 1000000,
827
+ max_output_tokens: null,
828
+ deprecated_after: null,
829
+ prompt_cliff_tokens: 200000,
830
+ rate_schedules: Object.freeze([
831
+ Object.freeze({
832
+ effective_from_utc: null,
833
+ effective_until_utc: null,
834
+ standard: Object.freeze({
835
+ input_per_1m: 1.25,
836
+ output_per_1m: 10.00,
837
+ write_5m_per_1m: 1.25,
838
+ write_1h_per_1m: 1.25,
839
+ cached_read_per_1m: 0.125
840
+ }),
841
+ cliff_over_200k: Object.freeze({
842
+ input_per_1m: 2.50,
843
+ output_per_1m: 15.00,
844
+ write_5m_per_1m: 2.50,
845
+ write_1h_per_1m: 2.50,
846
+ cached_read_per_1m: 0.25
847
+ }),
848
+ priority: Object.freeze({
849
+ input_per_1m: 1.25,
850
+ output_per_1m: 10.00,
851
+ write_5m_per_1m: 1.25,
852
+ write_1h_per_1m: 1.25,
853
+ cached_read_per_1m: 0.125
854
+ })
855
+ })
856
+ ])
857
+ })
858
+ });
859
+
860
+ export const MODEL_PRICING_PER_MILLION = {
861
+ 'claude-haiku-5-5': 0.10,
862
+ 'claude-haiku-5.5': 0.10,
863
+ 'haiku-5-5': 0.10,
864
+ 'haiku-5.5': 0.10,
865
+ 'claude-sonnet-5-5': 2.00,
866
+ 'claude-sonnet-5.5': 2.00,
867
+ 'sonnet-5-5': 2.00,
868
+ 'sonnet-5.5': 2.00,
869
+ 'claude-opus-5-5': 4.00,
870
+ 'claude-opus-5.5': 4.00,
871
+ 'opus-5-5': 4.00,
872
+ 'opus-5.5': 4.00,
873
+ 'claude-fable-5-2': 8.00,
874
+ 'claude-fable-5.2': 8.00,
875
+ 'claude-fable-5-1': 10.00,
876
+ 'claude-fable-5.1': 10.00,
877
+ 'claude-fable-5': 10.00,
878
+ 'claude-mythos-5-2': 8.00,
879
+ 'claude-mythos-5.2': 8.00,
880
+ 'mythos-5-2': 8.00,
881
+ 'mythos-5.2': 8.00,
882
+ 'claude-mythos-5-1': 10.00,
883
+ 'claude-mythos-5.1': 10.00,
884
+ 'mythos-5-1': 10.00,
885
+ 'mythos-5.1': 10.00,
886
+ 'claude-mythos-5': 10.00,
887
+ 'claude-opus-5': 5.00,
888
+ 'claude-sonnet-5': 2.00,
889
+ 'claude-opus-4-8': 5.00,
890
+ 'claude-opus-4.8': 5.00,
891
+ 'claude-opus-4-7': 5.00,
892
+ 'claude-opus-4.7': 5.00,
893
+ 'claude-opus-4-6': 5.00,
894
+ 'claude-opus-4.6': 5.00,
895
+ 'claude-opus-4-6-thinking': 5.00,
896
+ 'claude-opus-4-5': 5.00,
897
+ 'claude-opus-4.5': 5.00,
898
+ 'claude-opus-4-1': 15.00,
899
+ 'claude-opus-4-0': 15.00,
900
+ 'claude-sonnet-4-6': 3.00,
901
+ 'claude-sonnet-4.6': 3.00,
902
+ 'claude-sonnet-4-5': 3.00,
903
+ 'claude-sonnet-4.5': 3.00,
904
+ 'claude-sonnet-4-0': 3.00,
905
+ 'claude-haiku-4-5': 1.00,
906
+ 'claude-haiku-4.5': 1.00,
907
+ 'claude-3-5-sonnet': 3.00,
908
+ 'gemini-2.5-pro': 1.25,
909
+ 'gemini-3.8-flash': 0.75,
910
+ 'gemini-3.8-flash-high': 0.75,
911
+ 'gemini-3.8-flash-medium': 0.75,
912
+ 'gemini-3.8-flash-med': 0.75,
913
+ 'gemini-3.8-flash-low': 0.75,
914
+ 'gemini-2.0-flash': 0.75,
915
+ 'gemini-4-argon': 2.00,
916
+ 'gemini-4-argon-high': 2.00,
917
+ 'gemini-4-argon-medium': 2.00,
918
+ 'gemini-4-argon-med': 2.00,
919
+ 'gemini-4-argon-low': 2.00,
920
+ 'gemini-pro-orchestrator-argon': 2.00,
921
+ 'orchestrator-argon': 2.00,
922
+ 'gemini-4-hydrogen': 1.50,
923
+ 'gemini-4-hydrogen-xhigh': 1.50,
924
+ 'gemini-4-hydrogen-extra-high': 1.50,
925
+ 'gemini-4-hydrogen-high': 1.50,
926
+ 'gemini-4-hydrogen-medium': 1.50,
927
+ 'gemini-4-hydrogen-med': 1.50,
928
+ 'gemini-4-hydrogen-low': 1.50,
929
+ 'gemini-pro-orchestrator-hydrogen': 1.50,
930
+ 'orchestrator-hydrogen': 1.50,
931
+ 'gemini-4-carbon': 2.00,
932
+ 'gemini-4-carbon-high': 2.00,
933
+ 'gemini-4-carbon-medium': 2.00,
934
+ 'gemini-4-carbon-med': 2.00,
935
+ 'gemini-4-carbon-low': 2.00,
936
+ 'gemini-4-carbon-cyber-permissive': 2.00,
937
+ 'gemini-pro-orchestrator': 2.00,
938
+ 'orchestrator': 2.00,
939
+ 'orchestrator-carbon': 2.00,
940
+ 'antigravity-orchestrator': 2.00,
941
+ 'm427': 2.00,
942
+ 'm437': 2.00,
943
+ 'm438': 2.00,
944
+ 'm670': 2.00,
945
+ 'gemini-1.5-pro': 1.25,
946
+ 'gemini-3.1-pro': 1.25,
947
+ 'gemini-pro': 1.25,
948
+ 'gpt-oss-120b': 1.00,
949
+ 'default': 0.75
950
+ };
951
+
952
+ export const MODEL_CEILINGS = Object.freeze({
953
+ 'claude-haiku-5-5': 1000000,
954
+ 'claude-haiku-5.5': 1000000,
955
+ 'haiku-5-5': 1000000,
956
+ 'haiku-5.5': 1000000,
957
+ 'claude-sonnet-5-5': 1000000,
958
+ 'claude-sonnet-5.5': 1000000,
959
+ 'sonnet-5-5': 1000000,
960
+ 'sonnet-5.5': 1000000,
961
+ 'claude-opus-5-5': 1000000,
962
+ 'claude-opus-5.5': 1000000,
963
+ 'opus-5-5': 1000000,
964
+ 'opus-5.5': 1000000,
965
+ 'claude-fable-5-2': 1000000,
966
+ 'claude-fable-5.2': 1000000,
967
+ 'claude-fable-5-1': 1000000,
968
+ 'claude-fable-5.1': 1000000,
969
+ 'claude-fable-5': 1000000,
970
+ 'claude-mythos-5-2': 1000000,
971
+ 'claude-mythos-5.2': 1000000,
972
+ 'mythos-5-2': 1000000,
973
+ 'mythos-5.2': 1000000,
974
+ 'claude-mythos-5-1': 1000000,
975
+ 'claude-mythos-5.1': 1000000,
976
+ 'mythos-5-1': 1000000,
977
+ 'mythos-5.1': 1000000,
978
+ 'claude-mythos-5': 1000000,
979
+ 'claude-opus-5': 1000000,
980
+ 'claude-sonnet-5': 1000000,
981
+ 'claude-opus-4-8': 1000000,
982
+ 'claude-opus-4.8': 1000000,
983
+ 'claude-opus-4-7': 1000000,
984
+ 'claude-opus-4.7': 1000000,
985
+ 'claude-opus-4-6': 200000,
986
+ 'claude-opus-4.6': 200000,
987
+ 'claude-opus-4-6-thinking': 200000,
988
+ 'claude-opus-4-5': 200000,
989
+ 'claude-opus-4.5': 200000,
990
+ 'claude-opus-4-1': 200000,
991
+ 'claude-opus-4-0': 200000,
992
+ 'claude-sonnet-4-6': 200000,
993
+ 'claude-sonnet-4.6': 200000,
994
+ 'claude-sonnet-4-5': 200000,
995
+ 'claude-sonnet-4.5': 200000,
996
+ 'claude-sonnet-4-0': 200000,
997
+ 'claude-haiku-4-5': 200000,
998
+ 'claude-haiku-4.5': 200000,
999
+ 'claude-3-5-sonnet': 200000,
1000
+ 'claude-sonnet': 1000000,
1001
+ 'gemini-2.5-pro': 1000000,
1002
+ 'gemini-3.8-flash': 256000,
1003
+ 'gemini-3.8-flash-high': 256000,
1004
+ 'gemini-3.8-flash-medium': 256000,
1005
+ 'gemini-3.8-flash-med': 256000,
1006
+ 'gemini-3.8-flash-low': 256000,
1007
+ 'gemini-4-argon': SHARED_1M_CONTEXT_POOL_TOKENS,
1008
+ 'gemini-4-argon-high': SHARED_1M_CONTEXT_POOL_TOKENS,
1009
+ 'gemini-4-argon-medium': SHARED_1M_CONTEXT_POOL_TOKENS,
1010
+ 'gemini-4-argon-med': SHARED_1M_CONTEXT_POOL_TOKENS,
1011
+ 'gemini-4-argon-low': SHARED_1M_CONTEXT_POOL_TOKENS,
1012
+ 'gemini-pro-orchestrator-argon': SHARED_1M_CONTEXT_POOL_TOKENS,
1013
+ 'orchestrator-argon': SHARED_1M_CONTEXT_POOL_TOKENS,
1014
+ 'gemini-4-hydrogen': SHARED_1M_CONTEXT_POOL_TOKENS,
1015
+ 'gemini-4-hydrogen-xhigh': SHARED_1M_CONTEXT_POOL_TOKENS,
1016
+ 'gemini-4-hydrogen-extra-high': SHARED_1M_CONTEXT_POOL_TOKENS,
1017
+ 'gemini-4-hydrogen-high': SHARED_1M_CONTEXT_POOL_TOKENS,
1018
+ 'gemini-4-hydrogen-medium': SHARED_1M_CONTEXT_POOL_TOKENS,
1019
+ 'gemini-4-hydrogen-med': SHARED_1M_CONTEXT_POOL_TOKENS,
1020
+ 'gemini-4-hydrogen-low': SHARED_1M_CONTEXT_POOL_TOKENS,
1021
+ 'gemini-pro-orchestrator-hydrogen': SHARED_1M_CONTEXT_POOL_TOKENS,
1022
+ 'orchestrator-hydrogen': SHARED_1M_CONTEXT_POOL_TOKENS,
1023
+ 'gemini-4-carbon': SHARED_1M_CONTEXT_POOL_TOKENS,
1024
+ 'gemini-4-carbon-high': SHARED_1M_CONTEXT_POOL_TOKENS,
1025
+ 'gemini-4-carbon-medium': SHARED_1M_CONTEXT_POOL_TOKENS,
1026
+ 'gemini-4-carbon-med': SHARED_1M_CONTEXT_POOL_TOKENS,
1027
+ 'gemini-4-carbon-low': SHARED_1M_CONTEXT_POOL_TOKENS,
1028
+ 'gemini-4-carbon-cyber-permissive': SHARED_1M_CONTEXT_POOL_TOKENS,
1029
+ 'gemini-pro-orchestrator': SHARED_1M_CONTEXT_POOL_TOKENS,
1030
+ 'orchestrator': SHARED_1M_CONTEXT_POOL_TOKENS,
1031
+ 'orchestrator-carbon': SHARED_1M_CONTEXT_POOL_TOKENS,
1032
+ 'antigravity-orchestrator': SHARED_1M_CONTEXT_POOL_TOKENS,
1033
+ 'm427': SHARED_1M_CONTEXT_POOL_TOKENS,
1034
+ 'm437': SHARED_1M_CONTEXT_POOL_TOKENS,
1035
+ 'm438': SHARED_1M_CONTEXT_POOL_TOKENS,
1036
+ 'm670': SHARED_1M_CONTEXT_POOL_TOKENS,
1037
+ 'gpt-oss-120b': 128000,
1038
+ 'gemini-1.5-pro-1m': 1000000,
1039
+ 'gemini-2.5-pro-1m': 1000000,
1040
+ 'gemini-2.5-pro-preview': 1000000,
1041
+ 'gemini-3.1-pro': 1000000,
1042
+ 'gemini-3.1-pro-preview': 1000000,
1043
+ 'default': 256000
1044
+ });
1045
+
1046
+ let cachedModelCatalog = null;
1047
+ let cachedModelCatalogPath = null;
1048
+
1049
+ /**
1050
+ * Loads the canonical JSON model catalog (`config/modelCatalog.json`), falling back cleanly
1051
+ * to the frozen in-memory `MODEL_REGISTRY` if the file is unavailable.
1052
+ */
1053
+ export function loadModelCatalog(catalogPath = DEFAULT_MODEL_CATALOG_PATH, { forceReload = false } = {}) {
1054
+ const resolved = path.resolve(catalogPath || DEFAULT_MODEL_CATALOG_PATH);
1055
+ if (!forceReload && cachedModelCatalog && cachedModelCatalogPath === resolved) {
1056
+ return cachedModelCatalog;
1057
+ }
1058
+ try {
1059
+ if (fs.existsSync(resolved)) {
1060
+ const parsed = JSON.parse(fs.readFileSync(resolved, 'utf8'));
1061
+ if (parsed && typeof parsed === 'object' && parsed.models && typeof parsed.models === 'object') {
1062
+ cachedModelCatalog = parsed;
1063
+ cachedModelCatalogPath = resolved;
1064
+ return cachedModelCatalog;
1065
+ }
1066
+ }
1067
+ } catch {
1068
+ // Graceful fallback to built-in registry
1069
+ }
1070
+ return {
1071
+ schema_version: '2.0.0',
1072
+ shared_1m_context_pool_tokens: SHARED_1M_CONTEXT_POOL_TOKENS,
1073
+ legacy_model_sunset_utc: LEGACY_MODEL_SUNSET_UTC,
1074
+ models: MODEL_REGISTRY
1075
+ };
1076
+ }
1077
+
1078
+ function readCustomCeilingsFile(filePath) {
1079
+ try {
1080
+ if (!filePath || !fs.existsSync(filePath)) return null;
1081
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
1082
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
1083
+ const rawMap =
1084
+ (parsed.ceilings && typeof parsed.ceilings === 'object' && !Array.isArray(parsed.ceilings) ? parsed.ceilings : null) ||
1085
+ (parsed.model_ceilings && typeof parsed.model_ceilings === 'object' && !Array.isArray(parsed.model_ceilings) ? parsed.model_ceilings : null) ||
1086
+ (parsed.modelCeilings && typeof parsed.modelCeilings === 'object' && !Array.isArray(parsed.modelCeilings) ? parsed.modelCeilings : null) ||
1087
+ parsed;
1088
+ const out = {};
1089
+ for (const [k, v] of Object.entries(rawMap)) {
1090
+ const num = typeof v === 'string' ? Number(v.replace(/[_,\s]/g, '')) : Number(v);
1091
+ if (k && Number.isFinite(num) && num >= 4096) {
1092
+ const normKey = normalizeModelId(k);
1093
+ const rounded = Math.round(num);
1094
+ if (normKey) out[normKey] = rounded;
1095
+ out[String(k).trim().toLowerCase()] = rounded;
1096
+ }
1097
+ }
1098
+ return out;
1099
+ } catch {
1100
+ return null;
1101
+ }
1102
+ }
1103
+
1104
+ /**
1105
+ * Loads and merges user and workspace `customCeilings.json` overrides from lowest to highest priority:
1106
+ * 1. `~/.attention-horizon/customCeilings.json`
1107
+ * 2. `~/.gemini/attention-horizon/customCeilings.json`
1108
+ * 3. `<cwd>/.attention-horizon/customCeilings.json`
1109
+ * 4. `<cwd>/.agents/horizon/customCeilings.json`
1110
+ */
1111
+ export function loadCustomCeilings({ cwd = null, homeDir = null, customPaths = null } = {}) {
1112
+ const effectiveHome = homeDir || process.env.ATTENTION_HORIZON_HOME_DIR || os.homedir();
1113
+ const effectiveCwd = cwd || process.cwd();
1114
+ const candidatePaths = Array.isArray(customPaths) && customPaths.length > 0
1115
+ ? customPaths
1116
+ : [
1117
+ effectiveHome ? path.join(effectiveHome, '.attention-horizon', 'customCeilings.json') : null,
1118
+ effectiveHome ? path.join(effectiveHome, '.gemini', 'attention-horizon', 'customCeilings.json') : null,
1119
+ effectiveCwd ? path.join(effectiveCwd, '.attention-horizon', 'customCeilings.json') : null,
1120
+ effectiveCwd ? path.join(effectiveCwd, '.agents', 'horizon', 'customCeilings.json') : null
1121
+ ].filter(Boolean);
1122
+
1123
+ const merged = {};
1124
+ for (const p of candidatePaths) {
1125
+ const fileMap = readCustomCeilingsFile(p);
1126
+ if (fileMap) {
1127
+ Object.assign(merged, fileMap);
1128
+ }
1129
+ }
1130
+ return merged;
1131
+ }
1132
+
1133
+ /**
1134
+ * Extracts a whitelisted patched CLI ceiling (512,000 or 900,000) from CLI settings or overrides.
1135
+ */
1136
+ export function resolvePatchedCliCeiling(cliSettings = null) {
1137
+ if (!cliSettings || typeof cliSettings !== 'object') return null;
1138
+ const rawCandidate =
1139
+ cliSettings.contextWindow ??
1140
+ cliSettings.context_window ??
1141
+ cliSettings.context_window_limit ??
1142
+ cliSettings.maxContextTokens ??
1143
+ cliSettings.max_tokens ??
1144
+ cliSettings.maxTokens ??
1145
+ cliSettings.cortexCheckpointLimit ??
1146
+ cliSettings.patchedCeilingTokens ??
1147
+ null;
1148
+ if (rawCandidate === null || rawCandidate === undefined) return null;
1149
+ if (typeof rawCandidate === 'string') {
1150
+ const lower = rawCandidate.toLowerCase().trim();
1151
+ if (lower === '512k' || lower === '512000' || lower === '512_000') return 512000;
1152
+ if (lower === '900k' || lower === '900000' || lower === '900_000') return 900000;
1153
+ }
1154
+ const num = Number(rawCandidate);
1155
+ if (PATCHED_CLI_CEILING_TIERS.includes(num)) return num;
1156
+ return null;
1157
+ }
1158
+
1159
+ function buildCeilingDescriptor(ceilingTokens, source, modelKey = '') {
1160
+ const isArgon1M = modelKey.includes('argon') || modelKey.includes('gemini-4');
1161
+ const isClamped1MModel = isArgon1M && ceilingTokens === 256000;
1162
+ const patchedTier = PATCHED_CLI_CEILING_TIERS.includes(ceilingTokens)
1163
+ ? `${Math.round(ceilingTokens / 1000)}k`
1164
+ : null;
1165
+ return {
1166
+ ceilingTokens,
1167
+ source,
1168
+ isClamped1MModel,
1169
+ clampedLabel: isClamped1MModel ? CORTEX_CLAMPED_CEILING_LABEL : '',
1170
+ patchedTier
1171
+ };
1172
+ }
1173
+
1174
+ /**
1175
+ * Normalizes a human-readable or raw model identifier into a canonical lookup key.
1176
+ * "Claude Opus 5.5 (Medium)" -> "claude-opus-5.5"; "gemini-4-argon" -> "gemini-4-argon";
1177
+ * Antigravity enum aliases ("M427", "M437", "M438") -> "gemini-4-carbon", "M670" -> "gemini-4-carbon-cyber-permissive".
1178
+ */
1179
+ const EFFORT_ONLY_PAREN_RE = /\s*\((?:low|medium|med|high|xhigh|extra[\s-]*high|max|minimal|auto|fast|thinking|standard|extended[\s-]*thinking)(?:\s*[,/|]\s*(?:low|medium|med|high|xhigh|extra[\s-]*high|max|minimal|auto|fast|thinking|standard|extended[\s-]*thinking))*\)\s*$/i;
1180
+
1181
+ export function normalizeModelId(modelId = '') {
1182
+ let s = String(modelId ?? '').trim().toLowerCase();
1183
+ // Strip trailing effort/mode suffixes like "(Medium)" or "(High, Thinking)",
1184
+ // while preserving model/codename qualifiers like "(Carbon)" or "(Cyber Permissive)".
1185
+ while (EFFORT_ONLY_PAREN_RE.test(s)) {
1186
+ s = s.replace(EFFORT_ONLY_PAREN_RE, '');
1187
+ }
1188
+ s = s.replace(/[()]+/g, ' ').replace(/\s+/g, '-').replace(/-+/g, '-').replace(/^-|-$/g, '');
1189
+ if (Object.prototype.hasOwnProperty.call(ANTIGRAVITY_ENUM_ALIASES, s)) {
1190
+ return ANTIGRAVITY_ENUM_ALIASES[s];
1191
+ }
1192
+ return s;
1193
+ }
1194
+
1195
+ export const normalizeModelKey = normalizeModelId;
1196
+
1197
+ function stripEffortSuffix(modelKey = '') {
1198
+ return String(modelKey || '').replace(/-(xhigh|extra-high|high|medium|med|low)$/i, '');
1199
+ }
1200
+
1201
+ /**
1202
+ * Resolves a canonical ModelDescriptor from MODEL_REGISTRY for any model ID or alias.
1203
+ */
1204
+ export function resolveModelDescriptor(modelId = 'gemini-4-argon') {
1205
+ const raw = String(modelId ?? '').trim().toLowerCase();
1206
+ const norm = normalizeModelId(modelId);
1207
+ const stripped = stripEffortSuffix(norm);
1208
+ const hyphenated = stripped.replace(/\.(\d+)/g, '-$1');
1209
+
1210
+ if (MODEL_REGISTRY[norm]) return MODEL_REGISTRY[norm];
1211
+ if (MODEL_REGISTRY[stripped]) return MODEL_REGISTRY[stripped];
1212
+ if (MODEL_REGISTRY[hyphenated]) return MODEL_REGISTRY[hyphenated];
1213
+
1214
+ if (ANTIGRAVITY_ENUM_ALIASES[raw] && MODEL_REGISTRY[ANTIGRAVITY_ENUM_ALIASES[raw]]) {
1215
+ return MODEL_REGISTRY[ANTIGRAVITY_ENUM_ALIASES[raw]];
1216
+ }
1217
+ if (ANTIGRAVITY_ENUM_ALIASES[stripped] && MODEL_REGISTRY[ANTIGRAVITY_ENUM_ALIASES[stripped]]) {
1218
+ return MODEL_REGISTRY[ANTIGRAVITY_ENUM_ALIASES[stripped]];
1219
+ }
1220
+
1221
+ for (const desc of Object.values(MODEL_REGISTRY)) {
1222
+ if (
1223
+ desc.aliases &&
1224
+ desc.aliases.some((a) => {
1225
+ const al = a.toLowerCase();
1226
+ return al === raw || al === norm || al === stripped || al === hyphenated;
1227
+ })
1228
+ ) {
1229
+ return desc;
1230
+ }
1231
+ }
1232
+
1233
+ if (hyphenated.includes('carbon-cyber-permissive')) return MODEL_REGISTRY['gemini-4-carbon-cyber-permissive'];
1234
+ if (hyphenated.includes('carbon')) return MODEL_REGISTRY['gemini-4-carbon'];
1235
+ if (hyphenated.includes('argon')) return MODEL_REGISTRY['gemini-4-argon'];
1236
+ if (hyphenated.includes('hydrogen')) return MODEL_REGISTRY['gemini-4-hydrogen'];
1237
+ if (hyphenated.includes('3-8-flash') || hyphenated.includes('flash')) return MODEL_REGISTRY['gemini-3.8-flash'];
1238
+ if (hyphenated.includes('fable-5-2')) return MODEL_REGISTRY['claude-fable-5-2'];
1239
+ if (hyphenated.includes('fable-5-1')) return MODEL_REGISTRY['claude-fable-5-1'];
1240
+ if (hyphenated.includes('fable')) return MODEL_REGISTRY['claude-fable-5-2'];
1241
+ if (hyphenated.includes('mythos-5-2')) return MODEL_REGISTRY['claude-mythos-5-2'];
1242
+ if (hyphenated.includes('mythos-5-1')) return MODEL_REGISTRY['claude-mythos-5-1'];
1243
+ if (hyphenated.includes('mythos-5')) return MODEL_REGISTRY['claude-mythos-5'];
1244
+ if (hyphenated.includes('mythos')) return MODEL_REGISTRY['claude-mythos-5-2'];
1245
+ if (hyphenated.includes('haiku-5-5')) return MODEL_REGISTRY['claude-haiku-5-5'];
1246
+ if (hyphenated.includes('sonnet-5-5')) return MODEL_REGISTRY['claude-sonnet-5-5'];
1247
+ if (hyphenated.includes('opus-5-5')) return MODEL_REGISTRY['claude-opus-5-5'];
1248
+ if (hyphenated.includes('opus-4-8')) return MODEL_REGISTRY['claude-opus-4-8'];
1249
+ if (hyphenated.includes('opus-4-7')) return MODEL_REGISTRY['claude-opus-4-7'];
1250
+ if (hyphenated.includes('sonnet-4-6')) return MODEL_REGISTRY['claude-sonnet-4-6'];
1251
+ if (hyphenated.includes('sonnet-4-5')) return MODEL_REGISTRY['claude-sonnet-4-5'];
1252
+ if (hyphenated.includes('opus-4-6')) return MODEL_REGISTRY['claude-opus-4-6'];
1253
+ if (hyphenated.includes('opus-4-5')) return MODEL_REGISTRY['claude-opus-4-5'];
1254
+ if (hyphenated.includes('haiku-4-5')) return MODEL_REGISTRY['claude-haiku-4-5'];
1255
+ if (hyphenated.includes('gpt-oss')) return MODEL_REGISTRY['gpt-oss-120b'];
1256
+ return null;
1257
+ }
1258
+
1259
+ /**
1260
+ * Validates a ModelDescriptor object against the frozen schema gate.
1261
+ */
1262
+ export function validateModelDescriptor(descriptor) {
1263
+ if (!descriptor || typeof descriptor !== 'object') return { valid: false, error: 'Descriptor must be an object' };
1264
+ for (const reqKey of CORE_SCHEMAS.ModelDescriptor.required) {
1265
+ if (descriptor[reqKey] === undefined) {
1266
+ return { valid: false, error: `Missing required field: ${reqKey}` };
1267
+ }
1268
+ }
1269
+ if (!Array.isArray(descriptor.supported_efforts) || descriptor.supported_efforts.length === 0) {
1270
+ return { valid: false, error: 'supported_efforts must be a non-empty array' };
1271
+ }
1272
+ if (typeof descriptor.supports_explicit_cache !== 'boolean') {
1273
+ return { valid: false, error: 'supports_explicit_cache must be boolean' };
1274
+ }
1275
+ return { valid: true, error: null };
1276
+ }
1277
+
1278
+ /**
1279
+ * Formats a composite AgentCacheKey: `${session_id}::${agent_id}::${model_id}`.
1280
+ * Defaults `agent_id` to `"primary"` when absent in single-agent payloads.
1281
+ */
1282
+ export function formatAgentCacheKey(sessionId = 'default_session', agentId = 'primary', modelId = 'gemini-4-argon') {
1283
+ const sId = String(sessionId || 'default_session').trim() || 'default_session';
1284
+ const aId = String(agentId || 'primary').trim() || 'primary';
1285
+ const mId = normalizeModelId(modelId || 'gemini-4-argon') || 'gemini-4-argon';
1286
+ return `${sId}::${aId}::${mId}`;
1287
+ }
1288
+
1289
+ /**
1290
+ * Formats a composite AgentStreamKey: `${session_id}::${agent_id}` for per-agent thrash/bust scoping.
1291
+ */
1292
+ export function formatAgentStreamKey(sessionId = 'default_session', agentId = 'primary') {
1293
+ const sId = String(sessionId || 'default_session').trim() || 'default_session';
1294
+ const aId = String(agentId || 'primary').trim() || 'primary';
1295
+ return `${sId}::${aId}`;
1296
+ }
1297
+
1298
+ /**
1299
+ * Parses a composite AgentCacheKey `${session_id}::${agent_id}::${model_id}`.
1300
+ */
1301
+ export function parseAgentCacheKey(compositeKey = '') {
1302
+ const parts = String(compositeKey || '').split('::');
1303
+ if (parts.length < 3) {
1304
+ const res = {
1305
+ session_id: parts[0] || 'default_session',
1306
+ agent_id: parts[1] || 'primary',
1307
+ model_id: normalizeModelId(parts[2] || 'gemini-4-argon')
1308
+ };
1309
+ Object.defineProperty(res, 'valid', { value: false, enumerable: false });
1310
+ return res;
1311
+ }
1312
+ const res = {
1313
+ session_id: parts[0],
1314
+ agent_id: parts[1] || 'primary',
1315
+ model_id: normalizeModelId(parts.slice(2).join('::'))
1316
+ };
1317
+ Object.defineProperty(res, 'valid', { value: true, enumerable: false });
1318
+ return res;
1319
+ }
1320
+
1321
+ /**
1322
+ * Creates and validates a SwarmAgentState record.
1323
+ */
1324
+ export function createSwarmAgentState(raw = {}) {
1325
+ const agent_id = String(raw.agent_id || raw.agentId || 'primary').trim() || 'primary';
1326
+ const model_id = normalizeModelId(raw.model_id || raw.modelId || raw.model || 'gemini-4-carbon') || 'gemini-4-carbon';
1327
+ const statusRaw = String(raw.status || 'active').toLowerCase().trim();
1328
+ const status = CORE_SCHEMAS.SwarmAgentState.validStatuses.includes(statusRaw)
1329
+ ? statusRaw
1330
+ : 'active';
1331
+ const last_active_timestamp = Number.isFinite(Number(raw.last_active_timestamp ?? raw.lastActiveTimestamp))
1332
+ ? Number(raw.last_active_timestamp ?? raw.lastActiveTimestamp)
1333
+ : Date.now();
1334
+ const warm_prefix_tokens = Math.max(0, Number(raw.warm_prefix_tokens ?? raw.warmPrefixTokens ?? raw.cachedTokens ?? 0));
1335
+ const cache_ttl_ms = Number(raw.cache_ttl_ms ?? raw.cacheTtlMs ?? CORE_SCHEMAS.SwarmAgentState.defaultCacheTtlMs);
1336
+ return {
1337
+ agent_id,
1338
+ model_id,
1339
+ status,
1340
+ last_active_timestamp,
1341
+ warm_prefix_tokens,
1342
+ cache_ttl_ms,
1343
+ role: raw.role || null
1344
+ };
1345
+ }
1346
+
1347
+ export function validateSwarmAgentState(state = {}) {
1348
+ if (!state || typeof state !== 'object') return { valid: false, error: 'SwarmAgentState must be an object' };
1349
+ for (const k of CORE_SCHEMAS.SwarmAgentState.required) {
1350
+ if (state[k] === undefined || state[k] === null) {
1351
+ return { valid: false, error: `Missing required field: ${k}` };
1352
+ }
1353
+ }
1354
+ if (!CORE_SCHEMAS.SwarmAgentState.validStatuses.includes(state.status)) {
1355
+ return { valid: false, error: `Invalid status: ${state.status}` };
1356
+ }
1357
+ return { valid: true, error: null };
1358
+ }
1359
+
1360
+ function parseTimestampUtcMs(eventTimestampUtc) {
1361
+ if (typeof eventTimestampUtc === 'number' && Number.isFinite(eventTimestampUtc)) {
1362
+ return eventTimestampUtc;
1363
+ }
1364
+ if (eventTimestampUtc instanceof Date) {
1365
+ return eventTimestampUtc.getTime();
1366
+ }
1367
+ if (typeof eventTimestampUtc === 'string' && eventTimestampUtc.trim()) {
1368
+ const parsed = Date.parse(eventTimestampUtc.trim());
1369
+ if (Number.isFinite(parsed)) return parsed;
1370
+ }
1371
+ return Date.now();
1372
+ }
1373
+
1374
+ function isTimestampWithinSchedule(tsMs, sched) {
1375
+ if (!sched || typeof sched !== 'object') return false;
1376
+ if (sched.effective_from_utc) {
1377
+ const fromMs = Date.parse(sched.effective_from_utc);
1378
+ if (Number.isFinite(fromMs) && tsMs < fromMs) return false;
1379
+ }
1380
+ if (sched.effective_until_utc) {
1381
+ const untilStr = String(sched.effective_until_utc).trim();
1382
+ const untilMs = Date.parse(untilStr);
1383
+ if (Number.isFinite(untilMs)) {
1384
+ // Exclusive when specified at 00:00:00Z midnight boundary; inclusive through .999Z when 23:59:59Z
1385
+ if (untilStr.endsWith('00:00:00Z')) {
1386
+ if (tsMs >= untilMs) return false;
1387
+ } else if (tsMs > untilMs + 999) {
1388
+ return false;
1389
+ }
1390
+ }
1391
+ }
1392
+ return true;
1393
+ }
1394
+
1395
+ function extractPromptEnvelopeTokens(contextOptions) {
1396
+ if (typeof contextOptions === 'number' && Number.isFinite(contextOptions)) {
1397
+ return Math.max(0, contextOptions);
1398
+ }
1399
+ if (!contextOptions || typeof contextOptions !== 'object') return 0;
1400
+ if (Number.isFinite(Number(contextOptions.totalPromptTokens)) && Number(contextOptions.totalPromptTokens) > 0) {
1401
+ return Math.max(0, Number(contextOptions.totalPromptTokens));
1402
+ }
1403
+ const fresh = Math.max(0, Number(
1404
+ contextOptions.freshInputTokens ??
1405
+ contextOptions.uncachedInputTokens ??
1406
+ contextOptions.inputTokens ??
1407
+ contextOptions.input_tokens ??
1408
+ 0
1409
+ ));
1410
+ const read = Math.max(0, Number(
1411
+ contextOptions.cacheReadInputTokens ??
1412
+ contextOptions.cacheReadTokens ??
1413
+ contextOptions.cache_read_input_tokens ??
1414
+ contextOptions.cachedTokens ??
1415
+ 0
1416
+ ));
1417
+ const write = Math.max(0, Number(
1418
+ contextOptions.cacheCreationInputTokens ??
1419
+ contextOptions.cacheCreationTokens ??
1420
+ contextOptions.cache_creation_input_tokens ??
1421
+ ((Number(contextOptions.write5mTokens || 0) + Number(contextOptions.write1hTokens || 0)) || 0)
1422
+ ));
1423
+ return fresh + read + write;
1424
+ }
1425
+
1426
+ function formatRateCardResult({
1427
+ modelId,
1428
+ serviceTier,
1429
+ windowName,
1430
+ effectiveFromUtc = null,
1431
+ effectiveUntilUtc = null,
1432
+ input,
1433
+ output,
1434
+ write5m,
1435
+ write1h,
1436
+ cachedRead,
1437
+ cliffTriggered = false
1438
+ }) {
1439
+ const w5m = Number.isFinite(write5m) ? write5m : input;
1440
+ const w1h = Number.isFinite(write1h) ? write1h : input;
1441
+ return {
1442
+ modelId,
1443
+ serviceTier,
1444
+ window: windowName,
1445
+ pricingWindow: windowName,
1446
+ cliffTriggered,
1447
+ effectiveFromUtc,
1448
+ effectiveUntilUtc,
1449
+ input,
1450
+ output,
1451
+ write5m: w5m,
1452
+ write1h: w1h,
1453
+ cachedRead,
1454
+ input_per_1m: input,
1455
+ output_per_1m: output,
1456
+ write_5m_per_1m: w5m,
1457
+ write_1h_per_1m: w1h,
1458
+ cached_read_per_1m: cachedRead,
1459
+ inputPer1M: input,
1460
+ outputPer1M: output,
1461
+ write5mPer1M: w5m,
1462
+ write1hPer1M: w1h,
1463
+ cachedReadPer1M: cachedRead,
1464
+ inputPerMillionUsd: input,
1465
+ outputPerMillionUsd: output,
1466
+ write5mPerMillionUsd: w5m,
1467
+ write1hPerMillionUsd: w1h,
1468
+ cachedReadPerMillionUsd: cachedRead
1469
+ };
1470
+ }
1471
+
1472
+ /**
1473
+ * Date-Gated & Multi-Rate Pricing Resolver (`resolveModelRates(modelId, eventTimestampUtc, serviceTier, contextOptions)`).
1474
+ * Evaluates `effective_from_utc` / `effective_until_utc` across every model in `MODEL_REGISTRY`,
1475
+ * plus prompt-cliff tiers (e.g. `claude-haiku-5-5` > 100,000 prompt tokens 5x cliff).
1476
+ */
1477
+ export function resolveModelRates(modelId = 'gemini-4-carbon', eventTimestampUtc = null, serviceTier = 'standard', contextOptions = null) {
1478
+ let effectiveTsArg = eventTimestampUtc;
1479
+ let effectiveTierArg = serviceTier;
1480
+ let effectiveCtx = contextOptions;
1481
+
1482
+ if (eventTimestampUtc && typeof eventTimestampUtc === 'object' && !(eventTimestampUtc instanceof Date)) {
1483
+ effectiveCtx = eventTimestampUtc;
1484
+ effectiveTsArg = eventTimestampUtc.eventTimestampUtc ?? eventTimestampUtc.timestamp ?? null;
1485
+ effectiveTierArg = eventTimestampUtc.serviceTier || serviceTier || 'standard';
1486
+ }
1487
+
1488
+ const tsMs = parseTimestampUtcMs(effectiveTsArg);
1489
+ const tierKey = String(effectiveTierArg || 'standard').toLowerCase().trim() === 'priority' ? 'priority' : 'standard';
1490
+ const desc = resolveModelDescriptor(modelId);
1491
+
1492
+ if (desc && Array.isArray(desc.rate_schedules) && desc.rate_schedules.length > 0) {
1493
+ const matchedSched =
1494
+ desc.rate_schedules.find((s) => isTimestampWithinSchedule(tsMs, s)) ||
1495
+ desc.rate_schedules[desc.rate_schedules.length - 1];
1496
+
1497
+ const promptEnvelope = extractPromptEnvelopeTokens(effectiveCtx);
1498
+ const cliffSchedule = matchedSched.cliff_over_200k || matchedSched.cliff_over_100k || null;
1499
+ const cliffWindowName = matchedSched.cliff_over_200k ? 'cliff_over_200k' : 'cliff_over_100k';
1500
+ const cliffTriggered = Boolean(
1501
+ desc.prompt_cliff_tokens &&
1502
+ promptEnvelope > desc.prompt_cliff_tokens &&
1503
+ cliffSchedule
1504
+ );
1505
+ const rates = cliffTriggered
1506
+ ? cliffSchedule
1507
+ : (matchedSched[tierKey] || matchedSched.standard);
1508
+
1509
+ let windowName = 'standard';
1510
+ if (cliffTriggered) {
1511
+ windowName = cliffWindowName;
1512
+ } else if (matchedSched.window) {
1513
+ windowName = matchedSched.window;
1514
+ } else if (desc.rate_schedules.length > 1) {
1515
+ windowName = matchedSched.effective_from_utc ? 'post_introductory' : 'introductory';
1516
+ }
1517
+
1518
+ return formatRateCardResult({
1519
+ modelId: desc.id,
1520
+ serviceTier: tierKey,
1521
+ windowName,
1522
+ effectiveFromUtc: matchedSched.effective_from_utc,
1523
+ effectiveUntilUtc: matchedSched.effective_until_utc,
1524
+ input: rates.input_per_1m,
1525
+ output: rates.output_per_1m,
1526
+ write5m: rates.write_5m_per_1m ?? rates.input_per_1m,
1527
+ write1h: rates.write_1h_per_1m ?? rates.input_per_1m,
1528
+ cachedRead: rates.cached_read_per_1m,
1529
+ cliffTriggered
1530
+ });
1531
+ }
1532
+
1533
+ const norm = normalizeModelId(modelId);
1534
+ const fallbackInput = MODEL_PRICING_PER_MILLION[norm] ?? MODEL_PRICING_PER_MILLION.default ?? 0.75;
1535
+ const fallbackOutput = fallbackInput * 5;
1536
+ const fallbackCached = Number((fallbackInput * 0.1).toFixed(4));
1537
+ return formatRateCardResult({
1538
+ modelId: norm || 'default',
1539
+ serviceTier: tierKey,
1540
+ windowName: 'standard',
1541
+ input: fallbackInput,
1542
+ output: fallbackOutput,
1543
+ write5m: fallbackInput,
1544
+ write1h: fallbackInput,
1545
+ cachedRead: fallbackCached
1546
+ });
1547
+ }
1548
+
1549
+ /**
1550
+ * Computes exact USD cost for a turn payload using `resolveModelRates`.
1551
+ * Always sums `(output_tokens + thinking_tokens)` against `output_per_1m`
1552
+ * and evaluates multi-rate cache writes (`write5m`, `write1h`) and prompt-cliff tiers.
1553
+ */
1554
+ export function calculateModelCost(payload = {}, options = {}) {
1555
+ const modelId = options.modelId || payload.modelId || payload.model_id || payload.model || 'gemini-4-carbon';
1556
+ const eventTimestampUtc = options.eventTimestampUtc ?? payload.eventTimestampUtc ?? payload.timestamp ?? payload.createdAt ?? null;
1557
+ const serviceTier = options.serviceTier || payload.serviceTier || payload.service_tier || 'standard';
1558
+
1559
+ const rawInputTokens = Math.max(0, Number(payload.input_tokens ?? payload.inputTokens ?? payload.uncachedInputTokens ?? 0));
1560
+ const outputTokens = Math.max(0, Number(payload.output_tokens ?? payload.outputTokens ?? 0));
1561
+ const thinkingTokens = Math.max(0, Number(payload.thinking_tokens ?? payload.thinkingTokens ?? 0));
1562
+ const cachedReadTokens = Math.max(
1563
+ 0,
1564
+ Number(
1565
+ payload.cached_input_tokens ??
1566
+ payload.cached_read_tokens ??
1567
+ payload.cache_read_input_tokens ??
1568
+ payload.cacheReadTokens ??
1569
+ payload.cachedTokens ??
1570
+ 0
1571
+ )
1572
+ );
1573
+ const inputTokens =
1574
+ payload.cached_input_tokens !== undefined &&
1575
+ payload.uncached_input_tokens === undefined &&
1576
+ payload.uncachedInputTokens === undefined &&
1577
+ rawInputTokens >= cachedReadTokens
1578
+ ? rawInputTokens - cachedReadTokens
1579
+ : rawInputTokens;
1580
+
1581
+ let write5mTokens = Math.max(
1582
+ 0,
1583
+ Number(
1584
+ payload.cache_creation_ephemeral_5m_input_tokens ??
1585
+ payload.cache_creation?.ephemeral_5m_input_tokens ??
1586
+ payload.write5mTokens ??
1587
+ 0
1588
+ )
1589
+ );
1590
+ let write1hTokens = Math.max(
1591
+ 0,
1592
+ Number(
1593
+ payload.cache_creation_ephemeral_1h_input_tokens ??
1594
+ payload.cache_creation?.ephemeral_1h_input_tokens ??
1595
+ payload.write1hTokens ??
1596
+ 0
1597
+ )
1598
+ );
1599
+ const flatCacheCreationTokens = Math.max(
1600
+ 0,
1601
+ Number(payload.cache_creation_input_tokens ?? payload.cacheCreationTokens ?? payload.cacheCreationInputTokens ?? 0)
1602
+ );
1603
+ if (write5mTokens + write1hTokens === 0 && flatCacheCreationTokens > 0) {
1604
+ const ttlHint = String(options.cacheTtl || payload.cacheTtl || payload.cache_ttl || '5m').toLowerCase();
1605
+ if (ttlHint === '1h' || ttlHint === '3600' || ttlHint === '3600s') {
1606
+ write1hTokens = flatCacheCreationTokens;
1607
+ } else {
1608
+ write5mTokens = flatCacheCreationTokens;
1609
+ }
1610
+ }
1611
+
1612
+ const totalPromptTokens = inputTokens + cachedReadTokens + write5mTokens + write1hTokens;
1613
+ const rates = resolveModelRates(modelId, eventTimestampUtc, serviceTier, { totalPromptTokens });
1614
+
1615
+ const billedOutputTokens = outputTokens + thinkingTokens;
1616
+ const inputCostUsd = (inputTokens / 1_000_000) * rates.input_per_1m;
1617
+ const outputCostUsd = (billedOutputTokens / 1_000_000) * rates.output_per_1m;
1618
+ const write5mCostUsd = (write5mTokens / 1_000_000) * rates.write_5m_per_1m;
1619
+ const write1hCostUsd = (write1hTokens / 1_000_000) * rates.write_1h_per_1m;
1620
+ const cachedReadCostUsd = (cachedReadTokens / 1_000_000) * rates.cached_read_per_1m;
1621
+ const totalCostUsd = Number((inputCostUsd + outputCostUsd + write5mCostUsd + write1hCostUsd + cachedReadCostUsd).toFixed(6));
1622
+
1623
+ return {
1624
+ modelId: rates.modelId,
1625
+ serviceTier: rates.serviceTier,
1626
+ pricingWindow: rates.pricingWindow,
1627
+ cliffTriggered: rates.cliffTriggered,
1628
+ rates,
1629
+ inputTokens,
1630
+ outputTokens,
1631
+ thinkingTokens,
1632
+ billedOutputTokens,
1633
+ write5mTokens,
1634
+ write1hTokens,
1635
+ cachedReadTokens,
1636
+ totalPromptTokens,
1637
+ inputCostUsd: Number(inputCostUsd.toFixed(6)),
1638
+ outputCostUsd: Number(outputCostUsd.toFixed(6)),
1639
+ write5mCostUsd: Number(write5mCostUsd.toFixed(6)),
1640
+ write1hCostUsd: Number(write1hCostUsd.toFixed(6)),
1641
+ cachedReadCostUsd: Number(cachedReadCostUsd.toFixed(6)),
1642
+ totalCostUsd
1643
+ };
1644
+ }
1645
+
1646
+ /**
1647
+ * Checks whether a model ID is deprecated at the given timestamp (`deprecated_after: "2026-11-18T00:00:00Z"`).
1648
+ */
1649
+ export function isModelDeprecated(modelId = '', eventTimestampUtc = null) {
1650
+ const desc = resolveModelDescriptor(modelId);
1651
+ if (!desc || !desc.deprecated_after) return false;
1652
+ const tsMs = parseTimestampUtcMs(eventTimestampUtc);
1653
+ const sunsetMs = Date.parse(desc.deprecated_after);
1654
+ return Number.isFinite(sunsetMs) && tsMs >= sunsetMs;
1655
+ }
1656
+
1657
+ /**
1658
+ * Returns a migration notice if a session is pinned to a retired model ID on or after its sunset date.
1659
+ */
1660
+ export function getDeprecatedModelMigrationNotice(modelId = '', eventTimestampUtc = null, userTier = 'pro') {
1661
+ if (!isModelDeprecated(modelId, eventTimestampUtc)) return null;
1662
+ const desc = resolveModelDescriptor(modelId);
1663
+ const replacement = isPlanTierEligible(userTier, 'ultra') ? 'gemini-4-carbon' : 'gemini-4-argon';
1664
+ const noticeText = `Model "${desc.label}" (${desc.id}) was retired on ${desc.deprecated_after}. Migrate session to ${replacement} to restore active support and implicit caching.`;
1665
+ return {
1666
+ deprecated: true,
1667
+ modelId: desc.id,
1668
+ deprecatedAfterUtc: desc.deprecated_after,
1669
+ recommendedReplacement: replacement,
1670
+ notice: noticeText,
1671
+ includes(substr) {
1672
+ return noticeText.includes(substr);
1673
+ },
1674
+ toString() {
1675
+ return noticeText;
1676
+ }
1677
+ };
1678
+ }
1679
+
1680
+ /**
1681
+ * Checks whether a user's Antigravity plan tier satisfies a model's `antigravity_min_tier`.
1682
+ * Supports both `isPlanTierEligible(userTier, requiredMinTier)` and `isPlanTierEligible(modelId, userTier)`.
1683
+ */
1684
+ export function isPlanTierEligible(firstArg = 'pro', secondArg = 'free') {
1685
+ const fKey = String(firstArg || 'pro').toLowerCase().trim();
1686
+ const sKey = String(secondArg || 'free').toLowerCase().trim();
1687
+ if (!Object.prototype.hasOwnProperty.call(PLAN_TIER_RANK, fKey)) {
1688
+ const desc = resolveModelDescriptor(fKey);
1689
+ if (desc) {
1690
+ const reqRank = PLAN_TIER_RANK[desc.antigravity_min_tier] ?? PLAN_TIER_RANK.free;
1691
+ const usrRank = PLAN_TIER_RANK[sKey] ?? PLAN_TIER_RANK.pro;
1692
+ return usrRank >= reqRank;
1693
+ }
1694
+ }
1695
+ const uRank = PLAN_TIER_RANK[fKey] ?? PLAN_TIER_RANK.pro;
1696
+ const rRank = PLAN_TIER_RANK[sKey] ?? PLAN_TIER_RANK.free;
1697
+ return uRank >= rRank;
1698
+ }
1699
+
1700
+ /**
1701
+ * Phase 2.1: Unified 1,048,576-Token Context Pool Calculator for `gemini-4-carbon` and `gemini-4-argon`.
1702
+ *
1703
+ * `pool_used = input_tokens + thinking_tokens + output_tokens`
1704
+ * `remaining_decode_headroom = 1_048_576 - input_tokens`
1705
+ */
1706
+ export function computeUnifiedContextPool(usage = {}, modelId = 'gemini-4-carbon') {
1707
+ const desc = resolveModelDescriptor(modelId);
1708
+ const norm = normalizeModelId(modelId);
1709
+ const isUnified1M = Boolean(
1710
+ (desc && (desc.family === 'carbon' || desc.family === 'argon')) ||
1711
+ norm.includes('carbon') ||
1712
+ norm.includes('argon')
1713
+ );
1714
+ const ceiling = isUnified1M
1715
+ ? SHARED_1M_CONTEXT_POOL_TOKENS
1716
+ : (desc?.shared_pool_ceiling || MODEL_CEILINGS[norm] || MODEL_CEILINGS.default);
1717
+
1718
+ const input_tokens = Math.max(0, Number(usage.input_tokens ?? usage.inputTokens ?? usage.totalInputTokens ?? 0));
1719
+ const thinking_tokens = Math.max(0, Number(usage.thinking_tokens ?? usage.thinkingTokens ?? 0));
1720
+ const output_tokens = Math.max(0, Number(usage.output_tokens ?? usage.outputTokens ?? 0));
1721
+
1722
+ const pool_used = input_tokens + thinking_tokens + output_tokens;
1723
+ const remaining_decode_headroom = Math.max(0, ceiling - input_tokens);
1724
+ const remaining_pool_tokens = Math.max(0, ceiling - pool_used);
1725
+ const utilization_ratio = ceiling > 0 ? pool_used / ceiling : 0;
1726
+ const utilization_pct = Number((utilization_ratio * 100).toFixed(2));
1727
+
1728
+ return {
1729
+ modelId: desc?.id || norm,
1730
+ ceiling,
1731
+ pool_ceiling: ceiling,
1732
+ ceilingTokens: ceiling,
1733
+ input_tokens,
1734
+ thinking_tokens,
1735
+ output_tokens,
1736
+ pool_used,
1737
+ poolUsedTokens: pool_used,
1738
+ remaining_decode_headroom,
1739
+ remainingDecodeHeadroom: remaining_decode_headroom,
1740
+ remaining_pool_tokens,
1741
+ utilization_ratio: Number(utilization_ratio.toFixed(6)),
1742
+ utilization_pct,
1743
+ utilizationPct: utilization_pct,
1744
+ is_overflow: pool_used > ceiling,
1745
+ isOverflow: pool_used > ceiling
1746
+ };
1747
+ }
1748
+
1749
+ /**
1750
+ * Phase 2.2: Carbon High-Effort Verbosity Detector.
1751
+ *
1752
+ * Tracks `(thinking_tokens + output_tokens) / input_tokens` and absolute reasoning spend per turn.
1753
+ * When `gemini-4-carbon` runs at `high` effort across >= 2 consecutive routine turns
1754
+ * (single-file edits, simple shell checks, no error recovery) and exceeds the configured
1755
+ * reasoning-token budget, emits an actionable prescription to step down via `/effort medium`
1756
+ * or delegate routine edits to `gemini-3.8-flash`.
1757
+ */
1758
+ export function evaluateCarbonVerbosityGuardrail(turns = [], options = {}) {
1759
+ const reasoningTokenBudget = Number(options.reasoningTokenBudget ?? options.reasoning_token_budget ?? 16000);
1760
+ const ratioThreshold = Number(options.ratioThreshold ?? 0.25);
1761
+ const eventTimestampUtc = options.eventTimestampUtc ?? null;
1762
+ const serviceTier = options.serviceTier || 'standard';
1763
+
1764
+ let consecutiveRoutineHighTurns = 0;
1765
+ const turnEvaluations = [];
1766
+
1767
+ for (const turn of (Array.isArray(turns) ? turns : [])) {
1768
+ const modelId = turn.modelId || turn.model_id || turn.model || options.modelId || 'gemini-4-carbon';
1769
+ const desc = resolveModelDescriptor(modelId);
1770
+ const isCarbon = Boolean(desc?.family === 'carbon' || normalizeModelId(modelId).includes('carbon'));
1771
+ const effort = String(turn.effort || turn.reasoningEffort || options.effort || 'high').toLowerCase().trim();
1772
+ const isHighEffort = effort === 'high' || effort === 'max';
1773
+
1774
+ const inputTokens = Math.max(1, Number(turn.input_tokens ?? turn.inputTokens ?? 1));
1775
+ const thinkingTokens = Math.max(0, Number(turn.thinking_tokens ?? turn.thinkingTokens ?? 0));
1776
+ const outputTokens = Math.max(0, Number(turn.output_tokens ?? turn.outputTokens ?? 0));
1777
+ const reasoningTokens = thinkingTokens + outputTokens;
1778
+ const reasoningToInputRatio = Number((reasoningTokens / inputTokens).toFixed(4));
1779
+
1780
+ const hasError = Boolean(
1781
+ turn.errorRecovery ||
1782
+ turn.hasError ||
1783
+ turn.status === 'ERROR' ||
1784
+ (typeof turn.exitCode === 'number' && turn.exitCode !== 0)
1785
+ );
1786
+ const editedFilesCount = Number(
1787
+ turn.editedFilesCount ??
1788
+ (Array.isArray(turn.editedFiles) ? turn.editedFiles.length : (turn.multiFileEdit ? 2 : 1))
1789
+ );
1790
+ const isRoutine = Boolean(
1791
+ turn.isRoutine !== undefined
1792
+ ? turn.isRoutine
1793
+ : (!hasError && editedFilesCount <= 1)
1794
+ );
1795
+
1796
+ const cost = calculateModelCost(
1797
+ { input_tokens: 0, output_tokens: outputTokens, thinking_tokens: thinkingTokens },
1798
+ { modelId, eventTimestampUtc: turn.timestamp || turn.createdAt || eventTimestampUtc, serviceTier }
1799
+ );
1800
+
1801
+ const exceedsBudget = reasoningTokens > reasoningTokenBudget || reasoningToInputRatio >= ratioThreshold;
1802
+ if (isCarbon && isHighEffort && isRoutine && exceedsBudget) {
1803
+ consecutiveRoutineHighTurns++;
1804
+ } else {
1805
+ consecutiveRoutineHighTurns = 0;
1806
+ }
1807
+
1808
+ turnEvaluations.push({
1809
+ modelId: desc?.id || normalizeModelId(modelId),
1810
+ effort,
1811
+ isCarbon,
1812
+ isHighEffort,
1813
+ isRoutine,
1814
+ inputTokens,
1815
+ thinkingTokens,
1816
+ outputTokens,
1817
+ reasoningTokens,
1818
+ reasoningToInputRatio,
1819
+ reasoningSpendUsd: cost.outputCostUsd,
1820
+ exceedsBudget,
1821
+ consecutiveRoutineHighTurns
1822
+ });
1823
+ }
1824
+
1825
+ const latest = turnEvaluations[turnEvaluations.length - 1] || null;
1826
+ const triggered = consecutiveRoutineHighTurns >= 2;
1827
+
1828
+ return {
1829
+ triggered,
1830
+ consecutiveRoutineHighTurns,
1831
+ reasoningTokenBudget,
1832
+ latestTurn: latest,
1833
+ turnEvaluations,
1834
+ recommendedAction: triggered ? '/effort medium' : null,
1835
+ delegateModel: triggered ? 'gemini-3.8-flash' : null,
1836
+ prescription: triggered
1837
+ ? `Gemini 4 Carbon ran at HIGH effort across ${consecutiveRoutineHighTurns} consecutive routine turns (${latest.reasoningTokens.toLocaleString('en-US')} decode tokens, ratio ${latest.reasoningToInputRatio}x, $${latest.reasoningSpendUsd.toFixed(4)} reasoning spend). Step down via /effort medium or delegate routine edits to gemini-3.8-flash.`
1838
+ : ''
1839
+ };
1840
+ }
1841
+
1842
+
1843
+ /**
1844
+ * Resolves ceiling with explicit source origin tracking ('patched_cli' | 'host' | 'custom' | 'config' | 'family' | 'hint' | 'legacy_default' | 'fallback').
1845
+ */
1846
+ export function resolveModelCeilingDetailed(
1847
+ modelId = 'default',
1848
+ stdinContextWindow = null,
1849
+ { useLegacyDefault = false, config = null, cliSettings = null, cwd = null, homeDir = null, customCeilings = null } = {}
1850
+ ) {
1851
+ const key = normalizeModelId(modelId);
1852
+ const strippedKey = stripEffortSuffix(key);
1853
+
1854
+ // 0. Patched CLI binary override (~/.gemini/antigravity-cli/settings.json or config.cliSettings)
1855
+ const patchedCliTokens = resolvePatchedCliCeiling(cliSettings || config?.cliSettings || stdinContextWindow?.cliSettings);
1856
+ if (patchedCliTokens) {
1857
+ return buildCeilingDescriptor(patchedCliTokens, 'patched_cli', key);
1858
+ }
1859
+
1860
+ const explicitMax = Number(
1861
+ stdinContextWindow?.max_tokens ||
1862
+ stdinContextWindow?.maxTokens ||
1863
+ stdinContextWindow?.context_window_limit ||
1864
+ 0
1865
+ );
1866
+ if (explicitMax >= 20000) {
1867
+ const src = PATCHED_CLI_CEILING_TIERS.includes(explicitMax) ? 'patched_cli' : 'host';
1868
+ return buildCeilingDescriptor(explicitMax, src, key);
1869
+ }
1870
+
1871
+ // 0b. User & workspace customCeilings.json overrides (merged ahead of config & built-in defaults)
1872
+ const customMap =
1873
+ (customCeilings && typeof customCeilings === 'object' ? customCeilings : null) ||
1874
+ (config?.customCeilings && typeof config.customCeilings === 'object' ? config.customCeilings : null) ||
1875
+ loadCustomCeilings({ cwd: cwd || config?.cwd || null, homeDir: homeDir || config?.homeDir || null });
1876
+
1877
+ if (customMap && Object.keys(customMap).length > 0) {
1878
+ if (Object.prototype.hasOwnProperty.call(customMap, key)) {
1879
+ const val = Number(customMap[key]);
1880
+ if (val >= 4096) return buildCeilingDescriptor(val, 'custom', key);
1881
+ }
1882
+ if (strippedKey && Object.prototype.hasOwnProperty.call(customMap, strippedKey)) {
1883
+ const val = Number(customMap[strippedKey]);
1884
+ if (val >= 4096) return buildCeilingDescriptor(val, 'custom', key);
1885
+ }
1886
+ const customFamilyKeys = Object.keys(customMap).filter(k => k !== 'default').sort((a, b) => b.length - a.length);
1887
+ for (const candidate of customFamilyKeys) {
1888
+ if (key.startsWith(candidate) || key.includes(candidate)) {
1889
+ const val = Number(customMap[candidate]);
1890
+ if (val >= 4096) return buildCeilingDescriptor(val, 'custom', key);
1891
+ }
1892
+ }
1893
+ if (key === 'default' && Object.prototype.hasOwnProperty.call(customMap, 'default')) {
1894
+ const val = Number(customMap.default);
1895
+ if (val >= 4096) return buildCeilingDescriptor(val, 'custom', key);
1896
+ }
1897
+ }
1898
+
1899
+ // 1. Exact match in config.model_ceilings (non-'default' explicit model keys)
1900
+ if (key !== 'default' && config?.model_ceilings && Object.prototype.hasOwnProperty.call(config.model_ceilings, key)) {
1901
+ const val = Number(config.model_ceilings[key]);
1902
+ if (val >= 20000) return buildCeilingDescriptor(val, 'config', key);
1903
+ }
1904
+
1905
+ // 2. Exact match in built-in table or canonical catalog/registry
1906
+ if (key !== 'default' && Object.prototype.hasOwnProperty.call(MODEL_CEILINGS, key)) {
1907
+ return buildCeilingDescriptor(MODEL_CEILINGS[key], 'config', key);
1908
+ }
1909
+ const catalog = loadModelCatalog();
1910
+ if (catalog?.models?.[key]?.shared_pool_ceiling >= 20000) {
1911
+ return buildCeilingDescriptor(Number(catalog.models[key].shared_pool_ceiling), 'config', key);
1912
+ }
1913
+
1914
+ // 3. Prefix / mergedCeilings lookup BEFORE generic family fallbacks
1915
+ const mergedCeilings = { ...MODEL_CEILINGS, ...(config?.model_ceilings || {}), ...(customMap || {}) };
1916
+ const familyKeys = Object.keys(mergedCeilings).filter(k => k !== 'default').sort((a, b) => b.length - a.length);
1917
+ for (const candidate of familyKeys) {
1918
+ if (key.startsWith(candidate) || key.includes(candidate)) {
1919
+ return buildCeilingDescriptor(mergedCeilings[candidate], 'family', key);
1920
+ }
1921
+ }
1922
+
1923
+ const desc = resolveModelDescriptor(key);
1924
+ if (desc && Number(desc.shared_pool_ceiling) >= 20000) {
1925
+ return buildCeilingDescriptor(Number(desc.shared_pool_ceiling), 'family', key);
1926
+ }
1927
+
1928
+ // 4. Size hints in model name
1929
+ if (/\b900k\b|900_000/.test(key)) return buildCeilingDescriptor(900000, 'patched_cli', key);
1930
+ if (/\b512k\b|512_000/.test(key)) return buildCeilingDescriptor(512000, 'patched_cli', key);
1931
+ if (/\b1m\b|1000k|1_000_000/.test(key)) return buildCeilingDescriptor(1000000, 'hint', key);
1932
+ if (/\b200k\b/.test(key)) return buildCeilingDescriptor(200000, 'hint', key);
1933
+ if (/\b256k\b/.test(key)) return buildCeilingDescriptor(256000, 'hint', key);
1934
+
1935
+ // 5. Residual legacy Claude 3.5 / 4.x family -> 200,000 ceiling
1936
+ if (key.includes('claude-sonnet-4') || key.includes('claude-opus-4') || key.includes('claude-haiku-4') || key.includes('claude-3-5-sonnet') || key.includes('claude-3.5-sonnet')) {
1937
+ return buildCeilingDescriptor(200000, 'family', key);
1938
+ }
1939
+
1940
+ if (useLegacyDefault) {
1941
+ return buildCeilingDescriptor(HORIZON_WINDOW.MAX_TOKENS, 'legacy_default', key);
1942
+ }
1943
+
1944
+ const fallback =
1945
+ (customMap && Number(customMap.default) >= 4096 ? Number(customMap.default) : null) ||
1946
+ (config?.model_ceilings && config.model_ceilings.default) ||
1947
+ MODEL_CEILINGS.default;
1948
+ return buildCeilingDescriptor(fallback, 'fallback', key);
1949
+ }
1950
+
1951
+ /**
1952
+ * Resolves the native context window ceiling for a given model or host telemetry payload.
1953
+ * Preserves 200,000 when useLegacyDefault is true and no explicit ceiling is supplied.
1954
+ */
1955
+ export function resolveModelCeiling(
1956
+ modelId = 'default',
1957
+ stdinContextWindow = null,
1958
+ { useLegacyDefault = false, config = null, cliSettings = null, cwd = null, homeDir = null, customCeilings = null } = {}
1959
+ ) {
1960
+ return resolveModelCeilingDetailed(modelId, stdinContextWindow, {
1961
+ useLegacyDefault,
1962
+ config,
1963
+ cliSettings,
1964
+ cwd,
1965
+ homeDir,
1966
+ customCeilings
1967
+ }).ceilingTokens;
1968
+ }
1969
+
1970
+ /**
1971
+ * Resolves pricing per million tokens with date-gated `MODEL_REGISTRY` schedule evaluation
1972
+ * (defaulting timestamp to `Date.now()`) and family fallback.
1973
+ */
1974
+ export function resolvePricePerM(modelId = 'default', config = null) {
1975
+ const key = normalizeModelId(modelId);
1976
+ const hasTemporalOrCliffContext = Boolean(
1977
+ config?.eventTimestampUtc ||
1978
+ config?.timestamp ||
1979
+ config?.serviceTier ||
1980
+ config?.totalPromptTokens ||
1981
+ config?.freshInputTokens ||
1982
+ config?.cacheReadInputTokens ||
1983
+ config?.cacheCreationInputTokens
1984
+ );
1985
+ const customMap = config?.model_pricing_per_1m_input || null;
1986
+ const hasExplicitCustomOverride = Boolean(
1987
+ customMap &&
1988
+ Object.prototype.hasOwnProperty.call(customMap, key) &&
1989
+ Number.isFinite(Number(customMap[key])) &&
1990
+ Number(customMap[key]) !== MODEL_PRICING_PER_MILLION[key] &&
1991
+ !hasTemporalOrCliffContext
1992
+ );
1993
+
1994
+ if (hasExplicitCustomOverride) {
1995
+ return Number(customMap[key]);
1996
+ }
1997
+
1998
+ const desc = key && key !== 'default' ? resolveModelDescriptor(key) : null;
1999
+ if (desc) {
2000
+ const ts = config?.eventTimestampUtc ?? config?.timestamp ?? Date.now();
2001
+ const tier = config?.serviceTier || 'standard';
2002
+ return resolveModelRates(key, ts, tier, config).input_per_1m;
2003
+ }
2004
+
2005
+ const pricingMap = { ...MODEL_PRICING_PER_MILLION, ...(customMap || {}) };
2006
+
2007
+ if (Object.prototype.hasOwnProperty.call(pricingMap, key)) {
2008
+ return pricingMap[key];
2009
+ }
2010
+
2011
+ const familyKeys = Object.keys(pricingMap).filter(k => k !== 'default').sort((a, b) => b.length - a.length);
2012
+ for (const candidate of familyKeys) {
2013
+ if (key.startsWith(candidate) || key.includes(candidate)) {
2014
+ return pricingMap[candidate];
2015
+ }
2016
+ }
2017
+
2018
+ return pricingMap.default || 0.75;
2019
+ }
2020
+
2021
+ /**
2022
+ * Scales an effort profile's safeLimit and thinkingReserve proportionally when maxTokens
2023
+ * differs from the 200,000 baseline (e.g. 256,000 -> 120k Fast / 147k High / 180k Auto).
2024
+ */
2025
+ export function scaleEffortProfileForCeiling(profile, maxTokens = HORIZON_WINDOW.MAX_TOKENS) {
2026
+ const raw = profile || EFFORT_PROFILES.STANDARD;
2027
+ const canonicalTier = raw.tier && EFFORT_PROFILES[raw.tier] ? EFFORT_PROFILES[raw.tier] : null;
2028
+ // Prevent double-scaling if an already-scaled profile (with maxTokens set) is passed in again
2029
+ const base = (raw.maxTokens && canonicalTier) ? { ...canonicalTier, ...raw, safeLimit: canonicalTier.safeLimit, thinkingReserve: canonicalTier.thinkingReserve } : raw;
2030
+ if (!maxTokens || maxTokens === HORIZON_WINDOW.MAX_TOKENS) {
2031
+ return {
2032
+ ...base,
2033
+ maxTokens: HORIZON_WINDOW.MAX_TOKENS,
2034
+ limitReason: base.tier === 'HIGH'
2035
+ ? `${Math.round(base.thinkingReserve / 1000)}k reserved for deep reasoning`
2036
+ : (base.tier === 'STANDARD'
2037
+ ? `${Math.round(base.safeLimit / 1000)}k recall ceiling`
2038
+ : base.limitReason)
2039
+ };
2040
+ }
2041
+ if (raw.maxTokens === maxTokens && typeof raw.safeLimit === 'number' && !canonicalTier) {
2042
+ return { ...raw };
2043
+ }
2044
+ const ratio = maxTokens / HORIZON_WINDOW.MAX_TOKENS;
2045
+ const scaledSafe = Math.round((base.safeLimit * ratio) / 1000) * 1000;
2046
+ const scaledReserve = Math.round((base.thinkingReserve * ratio) / 1000) * 1000;
2047
+ return {
2048
+ ...base,
2049
+ safeLimit: scaledSafe,
2050
+ thinkingReserve: scaledReserve,
2051
+ maxTokens,
2052
+ limitReason: base.tier === 'HIGH'
2053
+ ? `${Math.round(scaledReserve / 1000)}k reserved for deep reasoning`
2054
+ : (base.tier === 'STANDARD'
2055
+ ? `${Math.round(scaledSafe / 1000)}k recall ceiling`
2056
+ : base.limitReason)
2057
+ };
2058
+ }
2059
+
2060
+ export const EFFORT_PROFILES = Object.freeze({
2061
+ HIGH: Object.freeze({
2062
+ tier: 'HIGH',
2063
+ safeLimit: 115000,
2064
+ thinkingReserve: 25000,
2065
+ label: 'High Effort',
2066
+ shortLabel: 'High',
2067
+ limitReason: '25k reserved for deep reasoning'
2068
+ }),
2069
+ STANDARD: Object.freeze({
2070
+ tier: 'STANDARD',
2071
+ safeLimit: 140000,
2072
+ thinkingReserve: 0,
2073
+ label: 'Standard / Auto',
2074
+ shortLabel: 'Auto',
2075
+ limitReason: '140k recall ceiling'
2076
+ }),
2077
+ FAST: Object.freeze({
2078
+ tier: 'FAST',
2079
+ safeLimit: 95000,
2080
+ thinkingReserve: 0,
2081
+ label: 'Fast / Low Effort',
2082
+ shortLabel: 'Fast',
2083
+ limitReason: 'Earlier middle-window dilution on fast tiers'
2084
+ })
2085
+ });
2086
+
2087
+ /**
2088
+ * Inspects a turn's model/effort metadata (or string) and resolves the active effort profile.
2089
+ * Falls back to STANDARD (140k) when Auto or unspecified.
2090
+ */
2091
+ export function resolveEffortProfile(turnMetadata) {
2092
+ if (!turnMetadata) return { ...EFFORT_PROFILES.STANDARD };
2093
+
2094
+ let effortStr = '';
2095
+ let modelStr = '';
2096
+
2097
+ if (typeof turnMetadata === 'string') {
2098
+ const paren = turnMetadata.match(/\(([^)]+)\)/);
2099
+ if (paren) {
2100
+ effortStr = paren[1].trim();
2101
+ modelStr = turnMetadata.replace(paren[0], '').trim();
2102
+ } else {
2103
+ effortStr = turnMetadata.trim();
2104
+ modelStr = turnMetadata.trim();
2105
+ }
2106
+ } else if (typeof turnMetadata === 'object') {
2107
+ const rawTier = turnMetadata.tier || turnMetadata.effortTier || '';
2108
+ const rawEffort = turnMetadata.effort || turnMetadata.reasoningEffort || turnMetadata.reasoning_effort || '';
2109
+ const rawModel = typeof turnMetadata.model === 'string'
2110
+ ? turnMetadata.model
2111
+ : (turnMetadata.model?.id || turnMetadata.modelId || turnMetadata.model_id || turnMetadata.modelName || turnMetadata.rawLabel || '');
2112
+ const paren = String(rawModel).match(/\(([^)]+)\)/);
2113
+ effortStr = String(rawTier || rawEffort || (paren ? paren[1] : '')).trim();
2114
+ modelStr = String(rawModel).trim();
2115
+ }
2116
+
2117
+ if (effortStr) {
2118
+ if (/\b(xhigh|extra[\s-]*high|high|max|thinking|deep)\b/i.test(effortStr)) {
2119
+ return { ...EFFORT_PROFILES.HIGH };
2120
+ }
2121
+ if (/\b(low|fast|lite)\b/i.test(effortStr)) {
2122
+ return { ...EFFORT_PROFILES.FAST };
2123
+ }
2124
+ if (/\b(medium|standard|normal|auto|default|none)\b/i.test(effortStr)) {
2125
+ return { ...EFFORT_PROFILES.STANDARD };
2126
+ }
2127
+ }
2128
+
2129
+ const combined = `${effortStr} ${modelStr}`.trim();
2130
+ if (/\b(xhigh|extra[\s-]*high|high|max|thinking|deep)\b|-(?:xhigh|extra-high|high)\b/i.test(combined)) {
2131
+ return { ...EFFORT_PROFILES.HIGH };
2132
+ }
2133
+ if (/\b(low|fast|flash|lite)\b/i.test(combined)) {
2134
+ return { ...EFFORT_PROFILES.FAST };
2135
+ }
2136
+
2137
+ return { ...EFFORT_PROFILES.STANDARD };
2138
+ }
2139
+
2140
+ export const RSL_CONSTANTS = Object.freeze({
2141
+ MAX_RULE_FILE_BYTES: 24_000,
2142
+ AGGREGATE_RULE_TOKEN_BUDGET: 20_000,
2143
+ CLAUDE_MEMORY_MAX_LINES: 200,
2144
+ CLAUDE_MEMORY_MAX_BYTES: 25_000,
2145
+ INITIAL_IMPORTANCE: 2,
2146
+ PROMOTE_HOOK_IMPORTANCE: 5,
2147
+ REPEAT_VIOLATION_THRESHOLD: 2,
2148
+ CONTRASTIVE_WINDOW_STEPS: 4,
2149
+ MAX_DIGEST_CHARS: 10_000
2150
+ });