ctxtop 0.0.0-stage → 4.0.0

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