@chroxy/server 0.10.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 (275) hide show
  1. package/CONFIG.md +695 -0
  2. package/README.md +105 -0
  3. package/hooks/permission-hook.sh +285 -0
  4. package/package.json +69 -0
  5. package/scripts/fix-node-pty-helper.js +44 -0
  6. package/sidecar/Dockerfile +40 -0
  7. package/sidecar/PROTOCOL.md +691 -0
  8. package/sidecar/agent.js +1290 -0
  9. package/sidecar/package-lock.json +43 -0
  10. package/sidecar/package.json +17 -0
  11. package/src/activity-registry.js +491 -0
  12. package/src/anthropic-compatible-config.js +534 -0
  13. package/src/anthropic-compatible-session.js +579 -0
  14. package/src/anthropic-openai-shim.js +109 -0
  15. package/src/anthropic-openai-translate.js +377 -0
  16. package/src/auth-probes.js +296 -0
  17. package/src/background-shell-tracker.js +320 -0
  18. package/src/background-shells.js +125 -0
  19. package/src/base-session.js +1518 -0
  20. package/src/billing-budget.js +191 -0
  21. package/src/billing-canary-monitor.js +203 -0
  22. package/src/billing-class.js +149 -0
  23. package/src/bind-host.js +82 -0
  24. package/src/built-in-tools/bash-exec.js +167 -0
  25. package/src/built-in-tools/file-ops.js +198 -0
  26. package/src/built-in-tools/tool-transforms.js +179 -0
  27. package/src/builtin-commands.js +107 -0
  28. package/src/byok-compose-state-shared.js +31 -0
  29. package/src/byok-compose-state.js +234 -0
  30. package/src/byok-credentials.js +127 -0
  31. package/src/byok-event-translator.js +136 -0
  32. package/src/byok-mcp-client.js +404 -0
  33. package/src/byok-mcp-config.js +159 -0
  34. package/src/byok-mcp-fleet.js +214 -0
  35. package/src/byok-mcp-trust.js +175 -0
  36. package/src/byok-session.js +2019 -0
  37. package/src/byok-subagent-profiles.js +101 -0
  38. package/src/byok-tool-executor.js +813 -0
  39. package/src/byok-tools.js +271 -0
  40. package/src/channels/PACKAGING.md +181 -0
  41. package/src/channels/README.md +99 -0
  42. package/src/channels/chroxy-channel-server.js +248 -0
  43. package/src/checkpoint-manager.js +515 -0
  44. package/src/child-stream-guard.js +38 -0
  45. package/src/claude-channel-session.js +185 -0
  46. package/src/claude-model-catalog.js +266 -0
  47. package/src/claude-stream-parser.js +106 -0
  48. package/src/claude-tui/form-driver.js +874 -0
  49. package/src/claude-tui/pty-driver.js +520 -0
  50. package/src/claude-tui/tested-cli-version.js +22 -0
  51. package/src/claude-tui-attachments.js +342 -0
  52. package/src/claude-tui-session.js +4029 -0
  53. package/src/cli/config-cmd.js +34 -0
  54. package/src/cli/credentials-cmd.js +59 -0
  55. package/src/cli/deploy-cmd.js +167 -0
  56. package/src/cli/doctor-cmd.js +52 -0
  57. package/src/cli/identity-cmd.js +82 -0
  58. package/src/cli/init-cmd.js +209 -0
  59. package/src/cli/pages-cmd.js +167 -0
  60. package/src/cli/pair-code-cmd.js +108 -0
  61. package/src/cli/pair-discord-cmd.js +100 -0
  62. package/src/cli/providers-cmd.js +168 -0
  63. package/src/cli/server-cmd.js +94 -0
  64. package/src/cli/service-cmd.js +237 -0
  65. package/src/cli/session-cmd.js +143 -0
  66. package/src/cli/shared.js +194 -0
  67. package/src/cli/shell-cmd.js +130 -0
  68. package/src/cli/status-cmd.js +204 -0
  69. package/src/cli/tunnel-cmd.js +101 -0
  70. package/src/cli/update-cmd.js +45 -0
  71. package/src/cli/worktree-gc-cmd.js +195 -0
  72. package/src/cli-session.js +1820 -0
  73. package/src/cli.js +60 -0
  74. package/src/codex-app-server-client.js +156 -0
  75. package/src/codex-app-server-session.js +572 -0
  76. package/src/codex-session.js +604 -0
  77. package/src/config.js +1757 -0
  78. package/src/connection-info.js +42 -0
  79. package/src/connection-locality.js +55 -0
  80. package/src/content-blocks.js +42 -0
  81. package/src/control-room/byok-pool.js +130 -0
  82. package/src/control-room/constants.js +26 -0
  83. package/src/control-room/containers.js +258 -0
  84. package/src/control-room/emulators.js +279 -0
  85. package/src/control-room/handler-factory.js +142 -0
  86. package/src/control-room/host-prune.js +387 -0
  87. package/src/control-room/integrations.js +929 -0
  88. package/src/control-room/repo-runtime-config.js +239 -0
  89. package/src/control-room/repo-set.js +162 -0
  90. package/src/control-room/runners.js +479 -0
  91. package/src/control-room/simulators.js +223 -0
  92. package/src/control-room/skills-inventory.js +303 -0
  93. package/src/control-room/survey.js +685 -0
  94. package/src/control-room/wsl.js +182 -0
  95. package/src/conversation-scanner.js +270 -0
  96. package/src/conversation-scope.js +52 -0
  97. package/src/conversation-search.js +216 -0
  98. package/src/cost-budget-manager.js +190 -0
  99. package/src/credential-cipher.js +179 -0
  100. package/src/credential-store.js +786 -0
  101. package/src/credential-test.js +145 -0
  102. package/src/credentials-file.js +58 -0
  103. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
  104. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
  105. package/src/dashboard-next/dist/index.html +13 -0
  106. package/src/deepseek-credentials.js +58 -0
  107. package/src/deepseek-session.js +192 -0
  108. package/src/detect-thinking-keyword.js +67 -0
  109. package/src/dev-preview.js +227 -0
  110. package/src/devcontainer-config.js +269 -0
  111. package/src/device-preferences.js +267 -0
  112. package/src/diagnostics.js +187 -0
  113. package/src/diff-parser.js +157 -0
  114. package/src/discord-credentials.js +188 -0
  115. package/src/discord-pair-delivery.js +113 -0
  116. package/src/docker-byok-pool-stats.js +221 -0
  117. package/src/docker-byok-pool.js +841 -0
  118. package/src/docker-byok-session.js +2172 -0
  119. package/src/docker-image-allowlist.js +99 -0
  120. package/src/docker-sdk-session.js +396 -0
  121. package/src/docker-session.js +382 -0
  122. package/src/doctor-billing.js +179 -0
  123. package/src/doctor.js +667 -0
  124. package/src/duration.js +77 -0
  125. package/src/environment-manager.js +753 -0
  126. package/src/environment-statuses.js +20 -0
  127. package/src/environments/backends/docker.js +931 -0
  128. package/src/environments/backends/k8s.js +3030 -0
  129. package/src/environments/backends/rancher.js +326 -0
  130. package/src/environments/backends/types.js +332 -0
  131. package/src/event-ingest.js +546 -0
  132. package/src/event-normalizer.js +1083 -0
  133. package/src/external-session-registry.js +0 -0
  134. package/src/file-store.js +52 -0
  135. package/src/gemini-session.js +498 -0
  136. package/src/get-public-ip.js +52 -0
  137. package/src/git.js +15 -0
  138. package/src/github-webhook.js +256 -0
  139. package/src/handler-utils.js +663 -0
  140. package/src/handlers/checkpoint-handlers.js +202 -0
  141. package/src/handlers/control-room-handlers.js +1945 -0
  142. package/src/handlers/conversation-handlers.js +201 -0
  143. package/src/handlers/credential-handlers.js +247 -0
  144. package/src/handlers/evaluator-handlers.js +94 -0
  145. package/src/handlers/feature-handlers.js +332 -0
  146. package/src/handlers/file-handlers.js +142 -0
  147. package/src/handlers/ide-handlers.js +238 -0
  148. package/src/handlers/input-handlers.js +1048 -0
  149. package/src/handlers/pairing-handlers.js +94 -0
  150. package/src/handlers/repo-handlers.js +295 -0
  151. package/src/handlers/session-handlers.js +660 -0
  152. package/src/handlers/settings-handlers.js +818 -0
  153. package/src/handlers/skills-handlers.js +682 -0
  154. package/src/handlers/summarize-handlers.js +172 -0
  155. package/src/handlers/token-handlers.js +57 -0
  156. package/src/http-oversize.js +51 -0
  157. package/src/http-routes.js +1158 -0
  158. package/src/ide/search.js +268 -0
  159. package/src/ide/symbols.js +423 -0
  160. package/src/ip-utils.js +85 -0
  161. package/src/json-state-file.js +169 -0
  162. package/src/jsonl-reader.js +187 -0
  163. package/src/jsonl-subprocess-session.js +441 -0
  164. package/src/keychain.js +458 -0
  165. package/src/lan-ip.js +38 -0
  166. package/src/logger.js +388 -0
  167. package/src/mailbox-route.js +252 -0
  168. package/src/mcp-tools.js +46 -0
  169. package/src/message-transform.js +102 -0
  170. package/src/metrics.js +67 -0
  171. package/src/model-discovery.js +288 -0
  172. package/src/models.js +1426 -0
  173. package/src/notification-prefs.js +544 -0
  174. package/src/notifications/discord-billing-sink.js +323 -0
  175. package/src/notifications/discord-webhook-client.js +187 -0
  176. package/src/notifications/discord-webhook-sink.js +768 -0
  177. package/src/notifications/expo-push-sink.js +414 -0
  178. package/src/notifications/ready-body.js +177 -0
  179. package/src/notifications/sink-registry.js +98 -0
  180. package/src/notifications/sink.js +82 -0
  181. package/src/ollama-session.js +221 -0
  182. package/src/ollama-tags.js +238 -0
  183. package/src/openai-compatible-session.js +118 -0
  184. package/src/pages-store.js +255 -0
  185. package/src/pairing.js +836 -0
  186. package/src/path-hash-trust-ledger.js +311 -0
  187. package/src/per-session-settings.js +366 -0
  188. package/src/permission-audit.js +120 -0
  189. package/src/permission-hook.js +257 -0
  190. package/src/permission-manager.js +829 -0
  191. package/src/permission-resolver.js +144 -0
  192. package/src/platform.js +139 -0
  193. package/src/prompt-evaluator.js +386 -0
  194. package/src/providers.js +436 -0
  195. package/src/push.js +565 -0
  196. package/src/rate-limiter.js +433 -0
  197. package/src/redaction.js +206 -0
  198. package/src/sdk-session.js +1773 -0
  199. package/src/semver.js +92 -0
  200. package/src/server-cli/push-notification-handler.js +240 -0
  201. package/src/server-cli/server-orchestrator.js +168 -0
  202. package/src/server-cli/startup-display.js +146 -0
  203. package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
  204. package/src/server-cli-child.js +207 -0
  205. package/src/server-cli.js +1223 -0
  206. package/src/server-identity.js +383 -0
  207. package/src/service.js +835 -0
  208. package/src/session-context.js +49 -0
  209. package/src/session-lock.js +60 -0
  210. package/src/session-manager.js +3257 -0
  211. package/src/session-message-history.js +511 -0
  212. package/src/session-preset-trust.js +78 -0
  213. package/src/session-preset.js +458 -0
  214. package/src/session-state-persistence.js +307 -0
  215. package/src/session-timeout-manager.js +166 -0
  216. package/src/session-token-store.js +83 -0
  217. package/src/shell-approval-info.js +45 -0
  218. package/src/shell-approval-store.js +163 -0
  219. package/src/shell-audit.js +63 -0
  220. package/src/skills-budget.js +181 -0
  221. package/src/skills-content-validator.js +106 -0
  222. package/src/skills-frontmatter.js +422 -0
  223. package/src/skills-loader.js +1893 -0
  224. package/src/skills-manager.js +256 -0
  225. package/src/skills-trust.js +532 -0
  226. package/src/skills-usage.js +335 -0
  227. package/src/snapshots-store.js +345 -0
  228. package/src/ssrf-guard.js +130 -0
  229. package/src/subagent-counter.js +149 -0
  230. package/src/summarize-session.js +268 -0
  231. package/src/supervisor.js +929 -0
  232. package/src/test-client.js +131 -0
  233. package/src/token-compare.js +28 -0
  234. package/src/token-manager.js +220 -0
  235. package/src/tool-result.js +87 -0
  236. package/src/transcript-tasks.js +334 -0
  237. package/src/tunnel/base.js +294 -0
  238. package/src/tunnel/cloudflare.js +281 -0
  239. package/src/tunnel/index.js +54 -0
  240. package/src/tunnel-check.js +84 -0
  241. package/src/turn-tracker.js +0 -0
  242. package/src/user-shell-registry.js +218 -0
  243. package/src/user-shell-session.js +411 -0
  244. package/src/utils/check-dependencies.js +70 -0
  245. package/src/utils/concurrency.js +24 -0
  246. package/src/utils/context-window-learn.js +148 -0
  247. package/src/utils/error-message.js +25 -0
  248. package/src/utils/format-bytes.js +35 -0
  249. package/src/utils/preflight.js +143 -0
  250. package/src/utils/resolve-binary.js +91 -0
  251. package/src/utils/respawn-rate-limiter.js +59 -0
  252. package/src/utils/sleep.js +58 -0
  253. package/src/utils/spawn-env.js +193 -0
  254. package/src/utils/validation-patterns.js +23 -0
  255. package/src/utils/win-spawn.js +98 -0
  256. package/src/version-check.js +16 -0
  257. package/src/web-task-manager.js +383 -0
  258. package/src/worktree-gc.js +418 -0
  259. package/src/worktree-reaper.js +168 -0
  260. package/src/ws-auth.js +645 -0
  261. package/src/ws-broadcaster.js +385 -0
  262. package/src/ws-client-manager.js +476 -0
  263. package/src/ws-client-sender.js +115 -0
  264. package/src/ws-file-ops/browser.js +594 -0
  265. package/src/ws-file-ops/common.js +163 -0
  266. package/src/ws-file-ops/git.js +298 -0
  267. package/src/ws-file-ops/index.js +52 -0
  268. package/src/ws-file-ops/reader.js +595 -0
  269. package/src/ws-forwarding.js +543 -0
  270. package/src/ws-handler-context.js +196 -0
  271. package/src/ws-history.js +1251 -0
  272. package/src/ws-message-handlers.js +165 -0
  273. package/src/ws-permissions.js +676 -0
  274. package/src/ws-schemas.js +119 -0
  275. package/src/ws-server.js +2866 -0
package/src/models.js ADDED
@@ -0,0 +1,1426 @@
1
+ import { readFileSync, mkdirSync, watch as fsWatch } from 'fs'
2
+ import { homedir } from 'os'
3
+ import { basename, dirname, join } from 'path'
4
+ import { writeFileRestricted } from './platform.js'
5
+ import { createLogger } from './logger.js'
6
+ import {
7
+ DEFAULT_CONTEXT_WINDOW,
8
+ ONE_M_SUFFIX,
9
+ resolveClaudeContextWindow,
10
+ claudeDeriveId,
11
+ CLAUDE_FALLBACK_MODELS as FALLBACK_MODELS,
12
+ CLAUDE_PRICING_USD_PER_MTOK,
13
+ resolvePricingKey,
14
+ } from './claude-model-catalog.js'
15
+
16
+ const log = createLogger('models')
17
+
18
+ // Claude model catalog (roster, pricing, context-window heuristic) moved to
19
+ // claude-model-catalog.js (#6201 OCP) so this generic registry/overlay/cost
20
+ // module no longer OWNS the Claude data — it consumes it. Re-exported under the
21
+ // original names so every existing importer + test is unaffected. The
22
+ // module-level pricing path (resolveModelPricing) and the createModelsRegistry
23
+ // drift-guard read the imported CLAUDE_PRICING_USD_PER_MTOK / resolvePricingKey.
24
+ export { DEFAULT_CONTEXT_WINDOW, ONE_M_SUFFIX, resolveClaudeContextWindow, claudeDeriveId, FALLBACK_MODELS }
25
+
26
+ // #6219 — fullIds chroxy disallows regardless of source: the CLI fallback (gone
27
+ // already, removed from MODEL_METADATA), the Agent SDK's supportedModels() push,
28
+ // the disk cache, AND a user models-overlay.json. Fable (claude-fable-5) is
29
+ // currently the only one. Keyed on the FULL id (not the short `fable` alias) so
30
+ // the precise disallowed model is dropped without false-positiving an unrelated
31
+ // overlay/SDK entry that merely uses `fable` as a short label. The short alias
32
+ // can't resurface anyway — it only ever resolved to claude-fable-5, now removed.
33
+ // The `[1m]` variant is also matched. Exported for tests + future enforcement.
34
+ export const DISALLOWED_MODEL_IDS = Object.freeze(new Set(['claude-fable-5']))
35
+
36
+ /**
37
+ * True when a model id resolves to a disallowed fullId, normalising the same id
38
+ * shapes the rest of this module supports: a trailing `[1m]` long-context suffix
39
+ * and/or a trailing `-YYYYMMDD` date stamp (the SDK's `Model` enum surfaces dated
40
+ * forms like `claude-fable-5-20251201`). So `claude-fable-5`, `claude-fable-5[1m]`,
41
+ * `claude-fable-5-20251201`, and `claude-fable-5-20251201[1m]` all match.
42
+ */
43
+ export function isDisallowedModelId(id) {
44
+ if (typeof id !== 'string') return false
45
+ let base = id.endsWith('[1m]') ? id.slice(0, -'[1m]'.length) : id
46
+ base = base.replace(/-\d{8}$/, '') // strip a trailing YYYYMMDD date stamp
47
+ return DISALLOWED_MODEL_IDS.has(base)
48
+ }
49
+
50
+ // deepFreezePricing, FALLBACK_MODELS, CLAUDE_PRICING_USD_PER_MTOK and
51
+ // resolvePricingKey now live in claude-model-catalog.js (#6201 OCP) — imported
52
+ // above. resolveModelPricing() below layers the operator overlay + registry
53
+ // resolution on top of the catalog's static base lookup.
54
+
55
+ /**
56
+ * Returns the pricing rates for a model (USD per million tokens), or null
57
+ * if pricing is unknown. Callers that can't compute cost should still
58
+ * function — emit `cost: 0` and log a warn so the gap is visible without
59
+ * blocking the turn.
60
+ *
61
+ * Accepts short ids ('sonnet'), full ids ('claude-sonnet-4-6'), and the
62
+ * `[1m]` long-context suffix. The returned entry's top-level rates are
63
+ * the base (≤200K input) tier. `[1m]` variants additionally carry a
64
+ * `longContext` block with premium rates that `computePromptCostUsd`
65
+ * selects when the turn's total input exceeds the threshold (#4087).
66
+ * The selection happens inside computePromptCostUsd — callers should
67
+ * pass usage to that helper rather than reaching into `.longContext`
68
+ * directly.
69
+ */
70
+ export function getModelPricing(modelId) {
71
+ return resolveModelPricing(modelId, defaultOverlay)
72
+ }
73
+
74
+ /**
75
+ * Resolve pricing for a model id with an optional overlay consulted first.
76
+ * Precedence: overlay pricing (matched on the resolved full id) > static
77
+ * CLAUDE_PRICING_USD_PER_MTOK > null. A missing overlay pricing block does
78
+ * NOT shadow the static table (we only short-circuit when the overlay
79
+ * actually carries a `pricing` object), and an absent match everywhere
80
+ * yields null — never 0.
81
+ *
82
+ * @param {string} modelId
83
+ * @param {Map} [overlay] - fullId → overlay entry map (see loadModelsOverlayResult)
84
+ * @returns {object|null}
85
+ */
86
+ // #6381 — pure overlay-pricing lookup against a fullId-keyed overlay map. Tries
87
+ // the id verbatim, then the `resolveId`-resolved full id (so an operator can key
88
+ // the overlay on a short alias OR a full id). Returns the matched entry's pricing
89
+ // or null. Reused by resolveModelPricing (Claude path, with the static fallback)
90
+ // and the per-provider registry's getOverlayPricing (overlay only) so non-Claude
91
+ // providers can be re-priced via the overlay with no release.
92
+ function lookupOverlayPricing(modelId, overlay, resolveId) {
93
+ if (!(overlay instanceof Map) || overlay.size === 0 || typeof modelId !== 'string' || modelId.length === 0) return null
94
+ const candidates = new Set([modelId])
95
+ const resolved = typeof resolveId === 'function' ? resolveId(modelId) : null
96
+ if (typeof resolved === 'string' && resolved.length > 0) candidates.add(resolved)
97
+ for (const candidate of candidates) {
98
+ const entry = overlay.get(candidate)
99
+ if (entry && entry.pricing) return entry.pricing
100
+ }
101
+ return null
102
+ }
103
+
104
+ function resolveModelPricing(modelId, overlay) {
105
+ const fromOverlay = lookupOverlayPricing(modelId, overlay, (id) => defaultRegistry.resolveModelId(id))
106
+ if (fromOverlay) return fromOverlay
107
+ const key = resolvePricingKey(modelId)
108
+ // Coalesce a resolved-but-absent key (e.g. a short alias that resolves to a
109
+ // full id with no pricing row because we don't ship unverified pricing) to null, not
110
+ // undefined, so the documented "rates or null" contract holds and callers
111
+ // that branch on `=== null` work.
112
+ return (key && CLAUDE_PRICING_USD_PER_MTOK[key]) || null
113
+ }
114
+
115
+ // DeepSeek pricing now lives on its provider class (#6201 OCP) —
116
+ // see DEEPSEEK_PRICING_USD_PER_MTOK + _getPricing in deepseek-session.js.
117
+
118
+ /**
119
+ * Compute USD cost for a single turn's usage object as returned by the
120
+ * Anthropic SDK (`{ input_tokens, output_tokens, cache_creation_input_tokens,
121
+ * cache_read_input_tokens }`).
122
+ *
123
+ * Returns `null` — NOT 0 — when pricing is unknown OR usage is missing OR the
124
+ * computed cost isn't finite (#5630). A `null` means "cost unknown", which is
125
+ * semantically distinct from a genuine `$0.00` turn — it lets the per-turn
126
+ * wire `cost` carry an honest "unknown" instead of a misleading `0`. Callers
127
+ * that accumulate a turn total MUST skip a `null` (it is not addable) — see
128
+ * byok-session.js's `turnCostKnown` guard. Never throws, never returns NaN.
129
+ * Cache-read tokens are NOT also billed at the input rate; the SDK already
130
+ * excludes them from `input_tokens`.
131
+ *
132
+ * #4087 — long-context premium: when the pricing entry has a
133
+ * `longContext` block AND the turn's total input (input + cache reads +
134
+ * cache writes) exceeds the threshold, ALL tokens in the turn are
135
+ * charged at the premium rate. The threshold-crossing applies to the
136
+ * whole turn, not just over-threshold tokens — matches Anthropic's
137
+ * public pricing-table format.
138
+ *
139
+ * @returns {number|null} Finite USD cost, or `null` when cost is unknown.
140
+ */
141
+ export function computePromptCostUsd(usage, pricing) {
142
+ if (!pricing || !usage) return null
143
+ const inputTokens = Number(usage.input_tokens) || 0
144
+ const outputTokens = Number(usage.output_tokens) || 0
145
+ const cacheReadTokens = Number(usage.cache_read_input_tokens) || 0
146
+ const cacheWriteTokens = Number(usage.cache_creation_input_tokens) || 0
147
+ // Select base or long-context rates. Only `[1m]`-variant entries carry
148
+ // a `longContext` block, so default-window models always use the
149
+ // top-level rates.
150
+ let rates = pricing
151
+ if (pricing.longContext) {
152
+ const totalInput = inputTokens + cacheReadTokens + cacheWriteTokens
153
+ if (totalInput > pricing.longContext.thresholdInputTokens) {
154
+ rates = pricing.longContext
155
+ }
156
+ }
157
+ const cost =
158
+ inputTokens * rates.input / 1_000_000
159
+ + outputTokens * rates.output / 1_000_000
160
+ + cacheReadTokens * rates.cacheRead / 1_000_000
161
+ + cacheWriteTokens * rates.cacheWrite / 1_000_000
162
+ return Number.isFinite(cost) ? cost : null
163
+ }
164
+
165
+ function getDefaultCachePath() {
166
+ const configDir = process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
167
+ return join(configDir, 'models-cache.json')
168
+ }
169
+
170
+ /**
171
+ * User-extensible overlay path. Mirrors getDefaultCachePath's config-dir
172
+ * resolution EXACTLY (CHROXY_CONFIG_DIR || ~/.chroxy) so the overlay file
173
+ * lives next to the cache. The overlay lets operators surface a brand-new
174
+ * model id, override a label/contextWindow, or supply pricing for a model
175
+ * the static table doesn't carry — all without a code change.
176
+ */
177
+ function getDefaultOverlayPath() {
178
+ const configDir = process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
179
+ return join(configDir, 'models.json')
180
+ }
181
+
182
+ /**
183
+ * Load and normalise the user overlay from disk (boot-only — not hot-reload;
184
+ * that's a deferred follow-up). The file is an object keyed by full model id:
185
+ *
186
+ * {
187
+ * "claude-fable-5": {
188
+ * "shortId": "fable", // optional
189
+ * "label": "Fable", // optional
190
+ * "fullId": "claude-fable-5", // optional (defaults to the key)
191
+ * "contextWindow": 200000, // optional
192
+ * "pricing": { // optional
193
+ * "input": 10, "output": 50, "cacheRead": 1, "cacheWrite": 12.5
194
+ * }
195
+ * }
196
+ * }
197
+ *
198
+ * Parses defensively: a missing file yields an empty overlay; malformed JSON
199
+ * (or a non-object root) logs a warn and yields an empty overlay. NEVER throws
200
+ * on boot. Returns a Map keyed by fullId for O(1) lookup; each value carries a
201
+ * normalised `{ fullId, shortId, label, contextWindow, pricing }` where any
202
+ * absent field is left undefined (NOT defaulted to 0/null) so downstream
203
+ * precedence can distinguish "overlay said nothing" from "overlay said X".
204
+ *
205
+ * @param {string} [path]
206
+ * @returns {Map<string, {fullId:string, shortId?:string, label?:string, contextWindow?:number, pricing?:object}>}
207
+ */
208
+ /**
209
+ * #5932 — load the overlay with an explicit MALFORMED-vs-EMPTY signal so a
210
+ * hot-reload can keep the last-good set when the file becomes malformed
211
+ * (rather than silently dropping every overlaid model). Returns
212
+ * `{ ok, overlay }`:
213
+ * - absent file → `{ ok: true, overlay: <empty> }` (legit "no overrides";
214
+ * a reload of an absent/deleted file CLEARS the overlay — an explicit
215
+ * operator action, distinct from a parse failure)
216
+ * - malformed JSON → `{ ok: false, overlay: <empty> }` (keep last-good on reload)
217
+ * - non-object JSON root → `{ ok: false, overlay: <empty> }`
218
+ * - valid object → `{ ok: true, overlay: <normalised> }`
219
+ *
220
+ * NEVER throws. Boot + reload call this directly to get both the default
221
+ * (Claude) overlay and the per-provider slices (#6377).
222
+ *
223
+ * @param {string} [path]
224
+ * @returns {{ ok: boolean, overlay: Map<string, object>, byProvider: Map<string, Map<string, object>> }}
225
+ */
226
+ function loadModelsOverlayResult(path = getDefaultOverlayPath()) {
227
+ // `overlay` is the DEFAULT (Claude) registry overlay — entries with no
228
+ // `provider` field (or a Claude provider name), for backward compatibility.
229
+ // `byProvider` (#6377) routes entries that carry `provider: "<name>"` to that
230
+ // non-Claude provider's own registry: Map<providerName, Map<fullId, entry>>.
231
+ const overlay = new Map()
232
+ const byProvider = new Map()
233
+ let raw
234
+ try {
235
+ raw = readFileSync(path, 'utf-8')
236
+ } catch (err) {
237
+ // A genuinely-absent file (ENOENT) is the common case AND a legitimate
238
+ // operator action — empty overlay, `ok: true` so a reload of a deleted file
239
+ // clears the overlay (no log; absence is normal). Any OTHER read error
240
+ // (EACCES, EBUSY, EISDIR, transient IO) is NOT an intentional clear — return
241
+ // `ok: false` + warn so a hot-reload keeps the LAST-GOOD set instead of
242
+ // silently wiping the operator's overlay on a transient fault (Copilot #5945).
243
+ if (err?.code === 'ENOENT') return { ok: true, overlay, byProvider }
244
+ log.warn(`loadModelsOverlay: cannot read ${path}: ${err?.code || ''} ${err?.message || err} — keeping last-good overlay`.replace(/\s+/g, ' ').trim())
245
+ return { ok: false, overlay, byProvider }
246
+ }
247
+ let parsed
248
+ try {
249
+ parsed = JSON.parse(raw)
250
+ } catch (err) {
251
+ log.warn(`loadModelsOverlay: malformed JSON in ${path}: ${err?.message || err} — ignoring overlay`)
252
+ return { ok: false, overlay, byProvider }
253
+ }
254
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
255
+ log.warn(`loadModelsOverlay: ${path} is not a JSON object keyed by model id — ignoring overlay`)
256
+ return { ok: false, overlay, byProvider }
257
+ }
258
+ for (const [key, value] of Object.entries(parsed)) {
259
+ if (typeof key !== 'string' || key.length === 0) continue
260
+ if (!value || typeof value !== 'object' || Array.isArray(value)) continue
261
+ const fullId = typeof value.fullId === 'string' && value.fullId.length > 0 ? value.fullId : key
262
+ const entry = { fullId }
263
+ if (typeof value.shortId === 'string' && value.shortId.length > 0) entry.shortId = value.shortId
264
+ if (typeof value.label === 'string' && value.label.length > 0) entry.label = value.label
265
+ if (typeof value.contextWindow === 'number' && value.contextWindow > 0) entry.contextWindow = value.contextWindow
266
+ if (value.pricing && typeof value.pricing === 'object' && !Array.isArray(value.pricing)) {
267
+ entry.pricing = value.pricing
268
+ }
269
+ // #6377: route by an optional `provider` field. Routing is by PRESENCE, not
270
+ // by classifying the name — this runs at module-init (before providers may
271
+ // have registered), so a registry lookup here would be unreliable. Absent
272
+ // `provider` → the default Claude registry overlay (backward-compatible, the
273
+ // common case). A `provider` name → that provider's own registry overlay,
274
+ // applied by getRegistryForProvider (which returns the default registry for
275
+ // Claude names, so tagging a Claude model is a documented no-op — omit it).
276
+ // The routing field is NOT copied into the entry.
277
+ const provider = typeof value.provider === 'string' && value.provider.length > 0 ? value.provider : null
278
+ if (provider) {
279
+ let providerMap = byProvider.get(provider)
280
+ if (!providerMap) { providerMap = new Map(); byProvider.set(provider, providerMap) }
281
+ providerMap.set(fullId, entry)
282
+ } else {
283
+ overlay.set(fullId, entry)
284
+ }
285
+ }
286
+ return { ok: true, overlay, byProvider }
287
+ }
288
+
289
+ // Module-level overlay, loaded at boot and HOT-RELOADABLE (#5932). The default
290
+ // Claude registry and the module-level getModelPricing() consult this; both
291
+ // read it dynamically (getModelPricing at call time; the registry via
292
+ // applyOverlay), so reassigning it in reloadModelsOverlay() takes effect without
293
+ // a restart. Per-provider registries take their own overlay via the
294
+ // createModelsRegistry hook.
295
+ const _bootOverlayResult = loadModelsOverlayResult()
296
+ let defaultOverlay = _bootOverlayResult.overlay
297
+ // #6377: per-provider overlays — entries tagged `provider: "<name>"` keyed by
298
+ // provider name. Threaded into each non-Claude registry by
299
+ // getRegistryForProvider and re-folded across cached registries on hot-reload.
300
+ let providerOverlays = _bootOverlayResult.byProvider
301
+
302
+ /**
303
+ * Per-provider cache path resolver (#4413). Non-Claude providers
304
+ * (codex, gemini, …) persist learned context-window ratchets to their own
305
+ * disk file so a server restart doesn't lose state and the default Claude
306
+ * cache (`models-cache.json`) stays untouched.
307
+ *
308
+ * The provider name is sanitised to a filename-safe slug so an unexpected
309
+ * `providerName` value can't escape the config dir via path metacharacters.
310
+ *
311
+ * @param {string} providerName
312
+ * @returns {string}
313
+ */
314
+ function getProviderCachePath(providerName) {
315
+ const configDir = process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
316
+ const safe = String(providerName).replace(/[^a-zA-Z0-9_-]/g, '_')
317
+ return join(configDir, `models-cache.${safe}.json`)
318
+ }
319
+
320
+ /**
321
+ * Canonical JSON stringifier — sorts object keys recursively so equivalent
322
+ * data produces an identical string regardless of construction order.
323
+ *
324
+ * Used by the registry's snapshotString() to dedupe saveCache() writes. The
325
+ * JS spec guarantees insertion-order key iteration, but relying on that to
326
+ * compare payloads is fragile: any future refactor that builds model objects
327
+ * via `{...m, contextWindow}` spreads or object-rest patterns could silently
328
+ * shuffle keys and defeat the snapshot equality check. Sorting keys makes
329
+ * the snapshot invariant to construction order.
330
+ *
331
+ * Semantics match `JSON.stringify` for the cases that matter:
332
+ * - undefined / function / symbol values: dropped from objects,
333
+ * coerced to null inside arrays (same as JSON.stringify)
334
+ * - sparse array holes: serialized as null (same as JSON.stringify)
335
+ * - `toJSON()`: honored on any object that defines it
336
+ * - circular structures: throw (same as JSON.stringify)
337
+ *
338
+ * Implementation: normalize to a key-sorted plain-object/array tree first,
339
+ * then hand to `JSON.stringify`. This avoids emitting invalid JSON like
340
+ * `{"k":undefined}` while still guaranteeing canonical ordering.
341
+ *
342
+ * Exported for tests.
343
+ */
344
+ export function canonicalStringify(value) {
345
+ const seen = new Set()
346
+
347
+ function normalize(current, key, inArray) {
348
+ if (current && typeof current === 'object' && typeof current.toJSON === 'function') {
349
+ current = current.toJSON(key)
350
+ }
351
+ if (current === undefined || typeof current === 'function' || typeof current === 'symbol') {
352
+ return inArray ? null : undefined
353
+ }
354
+ if (!current || typeof current !== 'object') {
355
+ return current
356
+ }
357
+ if (seen.has(current)) {
358
+ throw new TypeError('Converting circular structure to JSON')
359
+ }
360
+ seen.add(current)
361
+ try {
362
+ if (Array.isArray(current)) {
363
+ const out = new Array(current.length)
364
+ for (let i = 0; i < current.length; i += 1) {
365
+ out[i] = normalize(current[i], String(i), true)
366
+ }
367
+ return out
368
+ }
369
+ const out = {}
370
+ const keys = Object.keys(current).sort()
371
+ for (const childKey of keys) {
372
+ const childValue = normalize(current[childKey], childKey, false)
373
+ if (childValue !== undefined) {
374
+ out[childKey] = childValue
375
+ }
376
+ }
377
+ return out
378
+ } finally {
379
+ seen.delete(current)
380
+ }
381
+ }
382
+
383
+ return JSON.stringify(normalize(value, '', false))
384
+ }
385
+
386
+ /**
387
+ * Decompose a Claude model fullId into its `family` (e.g. `claude-opus-4`)
388
+ * and optional numeric `minor` (e.g. `7` for `claude-opus-4-7`). Used by
389
+ * `loadCache()` to detect retired model versions in the disk cache (#3162):
390
+ *
391
+ * `claude-opus-4-7` → { family: 'claude-opus-4', minor: 7 }
392
+ * `claude-opus-4-7[1m]` → { family: 'claude-opus-4', minor: 7 }
393
+ * `claude-opus-4-7-20251201` → { family: 'claude-opus-4', minor: 7 }
394
+ * `claude-sonnet-4-20250514` → { family: 'claude-sonnet-4', minor: null }
395
+ * `claude-sonnet-4-6` → { family: 'claude-sonnet-4', minor: 6 }
396
+ *
397
+ * `loadCache()` keeps cached entries whose family is present in
398
+ * `FALLBACK_MODELS` and (when minor is known) whose minor matches a fallback
399
+ * minor for the same family. SDK-reported dated ids like
400
+ * `claude-sonnet-4-20250514` carry no minor and pass through on family
401
+ * match — the API still accepts them. Family/major-only retirement (e.g.
402
+ * sonnet 3 family removed entirely) is caught by the family-not-in-fallback
403
+ * branch.
404
+ */
405
+ function modelFamilyAndMinor(fullId) {
406
+ if (typeof fullId !== 'string') return { family: '', minor: null }
407
+ let stripped = fullId.endsWith(ONE_M_SUFFIX) ? fullId.slice(0, -ONE_M_SUFFIX.length) : fullId
408
+ stripped = stripped.replace(/-\d{8,}$/, '')
409
+ const m = stripped.match(/^(claude-[a-z]+-\d+)(?:-(\d+))?$/)
410
+ if (m) {
411
+ return { family: m[1], minor: m[2] ? parseInt(m[2], 10) : null }
412
+ }
413
+ return { family: stripped, minor: null }
414
+ }
415
+
416
+ /**
417
+ * Derive a human-readable label from a stripped model ID.
418
+ * E.g. "opus-4-5-20251101" → "Opus 4.5", "sonnet-4-20250514" → "Sonnet 4",
419
+ * "opus-4-7[1m]" → "Opus 4.7 (1M)"
420
+ */
421
+ function humanizeModelId(id) {
422
+ const oneM = id.endsWith(ONE_M_SUFFIX)
423
+ let clean = oneM ? id.slice(0, -ONE_M_SUFFIX.length) : id
424
+ clean = clean.replace(/-\d{8,}$/, '')
425
+ const parts = clean.split('-')
426
+ if (parts.length === 0) return id
427
+ const family = parts[0].charAt(0).toUpperCase() + parts[0].slice(1)
428
+ const version = parts.slice(1).join('.')
429
+ const base = version ? `${family} ${version}` : family
430
+ return oneM ? `${base} (1M)` : base
431
+ }
432
+
433
+ /**
434
+ * Factory function that creates an isolated models registry.
435
+ * Each instance has its own mutable state, preventing test pollution.
436
+ *
437
+ * Accepts optional provider-specific hooks so non-Claude providers (Codex,
438
+ * Gemini, …) can drive their own fallback list, ID derivation and context-
439
+ * window heuristic without the registry hard-coding Claude conventions. When
440
+ * no hooks are supplied the registry defaults to the Claude behaviour so all
441
+ * existing callers (sdk-session, server-cli, test suites) keep working.
442
+ *
443
+ * @param {Object} [hooks]
444
+ * @param {ReadonlyArray<Object>} [hooks.fallbackModels] - Provider's minimal
445
+ * fallback list. Defaults to Claude's `FALLBACK_MODELS`.
446
+ * @param {(fullId:string) => string} [hooks.deriveId] - Maps an SDK `fullId`
447
+ * to the registry's short id. Defaults to Claude's `claude-` strip.
448
+ * @param {(fullId:string) => number} [hooks.resolveContextWindow] -
449
+ * Heuristic context-window resolver. Defaults to the Claude one.
450
+ * @param {(fullId:string) => (Object|null)} [hooks.getModelMetadata] -
451
+ * Optional provider lookup that can return `{id,label,fullId,contextWindow}`
452
+ * for a known model fullId. When present it is consulted first during
453
+ * `updateModels()` to reuse provider-authoritative metadata.
454
+ * @param {() => string} [hooks.cachePath] - Resolver for the disk cache path
455
+ * used by `loadCache()` / `saveCache()` when no explicit path is passed.
456
+ * Lazy so the path is re-read from `CHROXY_CONFIG_DIR` after env edits in
457
+ * tests. Defaults to the shared Claude cache at
458
+ * `~/.chroxy/models-cache.json`. Non-Claude providers should supply a
459
+ * provider-scoped path (e.g. `~/.chroxy/models-cache.codex.json`) so the
460
+ * default Claude cache stays untouched by per-provider learn-loops (#4413).
461
+ * @param {Map} [hooks.overlay] - User-extensible overlay (fullId → entry; see
462
+ * loadModelsOverlayResult). Overlay entries SEED the registry like a
463
+ * FALLBACK_MODELS row, so a brand-new model id appears with no code change
464
+ * and survives loadCache()'s family prune. The default Claude registry gets
465
+ * the module-level `defaultOverlay`; pass `new Map()` to opt out.
466
+ */
467
+ export function createModelsRegistry(hooks = {}) {
468
+ const baseFallbackModels = hooks.fallbackModels ?? FALLBACK_MODELS
469
+ const deriveIdFn = typeof hooks.deriveId === 'function' ? hooks.deriveId : claudeDeriveId
470
+ const resolveContextWindowFn = typeof hooks.resolveContextWindow === 'function'
471
+ ? hooks.resolveContextWindow
472
+ : resolveClaudeContextWindow
473
+ const cachePathFn = typeof hooks.cachePath === 'function' ? hooks.cachePath : getDefaultCachePath
474
+ const getModelMetadataFn = typeof hooks.getModelMetadata === 'function' ? hooks.getModelMetadata : null
475
+ const overlay = hooks.overlay instanceof Map ? hooks.overlay : new Map()
476
+ // #6381: the CURRENT overlay (swapped by applyOverlay on hot-reload), retained
477
+ // so getOverlayPricing() reflects live edits. The fallback rows don't carry
478
+ // pricing, so pricing is read from this map directly.
479
+ let currentOverlay = overlay
480
+
481
+ // Fold overlay entries into the fallback set. An overlay entry for a fullId
482
+ // NOT already in the base fallbacks seeds the registry exactly like a
483
+ // FALLBACK_MODELS row would — so it appears in getModels(), resolves both
484
+ // ways, lands in the allowlist, and is unioned into the loadCache prune
485
+ // allowlist (its family survives boot). For an id already present in the
486
+ // base fallbacks, the overlay's label/contextWindow override the static
487
+ // heuristic (overlay > heuristic). Pricing is handled separately by
488
+ // resolveModelPricing. SDK live values still win over both at
489
+ // updateModels() time (the contextWindowOverrides / providerMeta lookups
490
+ // are consulted ahead of the fallback row's contextWindow).
491
+ //
492
+ // #5932 — extracted so applyOverlay() can RE-fold a hot-reloaded overlay
493
+ // without rebuilding the whole registry (which would discard SDK-learned
494
+ // models + contextWindow overrides).
495
+ function computeFallbackModels(overlayMap) {
496
+ const overlayRows = []
497
+ const overriddenBase = []
498
+ const baseByFullId = new Map(baseFallbackModels.map((m) => [m.fullId, m]))
499
+ for (const entry of overlayMap.values()) {
500
+ // #6219 — an overlay must not reintroduce a disallowed model (e.g. fable).
501
+ if (isDisallowedModelId(entry.shortId) || isDisallowedModelId(entry.fullId)) continue
502
+ const baseRow = baseByFullId.get(entry.fullId)
503
+ if (baseRow) {
504
+ // Override the base row's label/window from the overlay when supplied.
505
+ if (entry.label !== undefined || entry.contextWindow !== undefined || entry.shortId !== undefined) {
506
+ baseByFullId.set(entry.fullId, Object.freeze({
507
+ id: entry.shortId ?? baseRow.id,
508
+ label: entry.label ?? baseRow.label,
509
+ fullId: baseRow.fullId,
510
+ contextWindow: entry.contextWindow ?? baseRow.contextWindow,
511
+ }))
512
+ }
513
+ continue
514
+ }
515
+ const shortId = entry.shortId ?? deriveIdFn(entry.fullId)
516
+ overlayRows.push(Object.freeze({
517
+ id: shortId,
518
+ label: entry.label ?? humanizeModelId(shortId),
519
+ fullId: entry.fullId,
520
+ contextWindow: entry.contextWindow ?? resolveContextWindowFn(entry.fullId),
521
+ }))
522
+ }
523
+ // Preserve base order, then append overlay-only rows.
524
+ for (const m of baseFallbackModels) overriddenBase.push(baseByFullId.get(m.fullId))
525
+ return overlayRows.length > 0 || overriddenBase.some((m, i) => m !== baseFallbackModels[i])
526
+ ? Object.freeze([...overriddenBase, ...overlayRows])
527
+ : baseFallbackModels
528
+ }
529
+
530
+ // #5932: `let` (was const) so applyOverlay() can swap in a re-folded set.
531
+ let fallbackModels = computeFallbackModels(overlay)
532
+
533
+ let activeModels = fallbackModels
534
+ let defaultModelId = null
535
+ let allowedModelIds = new Set()
536
+ let toFullIdMap = new Map()
537
+ let toShortIdMap = new Map()
538
+ // #5932: the last SDK model list applied via updateModels(), retained so
539
+ // applyOverlay() can RE-merge a hot-reloaded overlay with the live SDK data
540
+ // (AC2) instead of reverting to the bare fallback view. Null until the first
541
+ // SDK refresh (CLI-only / pre-init).
542
+ let lastSdkModels = null
543
+ // #5932 (PR #5945 review): the last list applied via loadCache(), retained so
544
+ // an overlay reload in the CLI-only window (cache warmed, no SDK refresh yet)
545
+ // preserves cache-warmed entries the new fallback doesn't cover (date-suffixed
546
+ // ids past the family filter) — WITHOUT resurrecting overlay-only rows the
547
+ // operator removed (those only ever live in fallbackModels, never here).
548
+ let lastCacheModels = null
549
+ // Snapshot of the last saved cache payload so saveCache() can skip
550
+ // redundant writes. `null` forces the first save to always run.
551
+ let lastSavedSnapshot = null
552
+ // Authoritative contextWindow values observed from SDK `modelUsage`,
553
+ // keyed by fullId. These override the static resolveContextWindow()
554
+ // heuristic and must survive subsequent updateModels() refreshes
555
+ // (which otherwise rebuild every entry from the heuristic on every
556
+ // SDK session init). Cleared on resetModels().
557
+ const contextWindowOverrides = new Map()
558
+
559
+ // #4106: warn-once set for synthesized 1M variants that lack a matching
560
+ // pricing entry. updateModels() can be called repeatedly across the
561
+ // server lifetime (every SDK session init); without this guard, an
562
+ // operator running with a new model family would see the same warn line
563
+ // for every session. Cleared on resetModels().
564
+ const pricingDriftWarned = new Set()
565
+
566
+ // Seed lookups with FALLBACK_MODELS aliases so legacy short ids
567
+ // (`sonnet`/`opus`/`haiku`) remain valid even after the SDK returns a
568
+ // dynamic list whose derived short ids look different
569
+ // (e.g. `sonnet-4-6`). Dynamic entries override on collision.
570
+ function rebuildLookups(models) {
571
+ allowedModelIds = new Set()
572
+ toFullIdMap = new Map()
573
+ toShortIdMap = new Map()
574
+
575
+ const seed = (list) => {
576
+ for (const m of list) {
577
+ allowedModelIds.add(m.id)
578
+ allowedModelIds.add(m.fullId)
579
+ toFullIdMap.set(m.id, m.fullId)
580
+ toFullIdMap.set(m.fullId, m.fullId)
581
+ toShortIdMap.set(m.fullId, m.id)
582
+ toShortIdMap.set(m.id, m.id)
583
+ }
584
+ }
585
+
586
+ seed(fallbackModels)
587
+ if (models !== fallbackModels) seed(models)
588
+ }
589
+
590
+ function applyModels(models, nextDefault) {
591
+ // #6219 — strip disallowed models (fable) from ANY source funnelled through
592
+ // here (SDK updateModels(), disk loadCache()), so they can't appear in
593
+ // SDK/TUI modes. Skip the allocation when nothing is disallowed (the common
594
+ // case). The CLI fallback is already clean (removed from MODEL_METADATA).
595
+ const filtered = models.some((m) => isDisallowedModelId(m.id) || isDisallowedModelId(m.fullId))
596
+ ? models.filter((m) => !isDisallowedModelId(m.id) && !isDisallowedModelId(m.fullId))
597
+ : models
598
+ activeModels = filtered
599
+ // #6219 review (#6232): never leave defaultModelId pointing at a model that
600
+ // isn't in the active list — e.g. the SDK marked the now-filtered disallowed
601
+ // model (fable) as "Default", so nextDefault is its short id which isn't in
602
+ // `filtered`. A dangling default can't be resolved by the picker. When
603
+ // nextDefault is absent from the filtered list, re-pick a stable family head
604
+ // (opus → sonnet) else the first model (mirrors updateModels' fallback). Only
605
+ // fires when filtering actually dropped the chosen default — a present
606
+ // nextDefault (the common case + loadCache's own discard result) is kept.
607
+ const defaultPresent =
608
+ nextDefault != null && filtered.some((m) => m.id === nextDefault || m.fullId === nextDefault)
609
+ if (nextDefault != null && !defaultPresent) {
610
+ const preferred = filtered.find((m) => m.id === 'opus' || m.id === 'sonnet')
611
+ defaultModelId = preferred?.id ?? filtered[0]?.id ?? null
612
+ } else {
613
+ defaultModelId = nextDefault
614
+ }
615
+ rebuildLookups(filtered)
616
+ }
617
+
618
+ function snapshotString() {
619
+ return canonicalStringify({ models: activeModels, defaultModelId })
620
+ }
621
+
622
+ // Hoisted out of the returned method so loadCache() can heal the disk
623
+ // file in the same pass when stale entries are pruned (#3162).
624
+ function saveCacheImpl(path) {
625
+ const snapshot = snapshotString()
626
+ if (snapshot === lastSavedSnapshot) return true
627
+
628
+ try {
629
+ mkdirSync(dirname(path), { recursive: true })
630
+ // Pass a per-pid `tmpSuffix` so two concurrent processes
631
+ // (test runner + main daemon, or two test workers) writing the
632
+ // same cache do not race on the same intermediate `.tmp` file
633
+ // (#4874). The suffix is honoured on both POSIX and Windows since
634
+ // #4913 — writeFileRestricted now uses the same temp+rename
635
+ // pattern on both platforms, so the per-pid hint protects every
636
+ // host. writeFileRestricted handles atomic rename + cleanup
637
+ // internally; no manual rename/unlink wrapper is needed here.
638
+ writeFileRestricted(path, JSON.stringify({
639
+ models: activeModels,
640
+ defaultModelId,
641
+ savedAt: Date.now(),
642
+ }, null, 2), { tmpSuffix: `.tmp-${process.pid}` })
643
+ lastSavedSnapshot = snapshot
644
+ return true
645
+ } catch (err) {
646
+ // Persisting the cache failed (permission denied, disk full, read-only
647
+ // parent). The in-memory list stays live for this process, but will be
648
+ // lost on restart — surface at warn level so operators can diagnose
649
+ // from ~/.chroxy/logs/chroxy.log.
650
+ log.warn(`saveCache: failed to persist models cache to ${path}: ${err?.code || ''} ${err?.message || err}`.trim())
651
+ return false
652
+ }
653
+ }
654
+
655
+ rebuildLookups(fallbackModels)
656
+
657
+ // #5932: captured in a const so applyOverlay() can re-run the full
658
+ // updateModels() pipeline against a re-folded fallback set. Methods reference
659
+ // `registry` only at call time (by which point it's assigned), so there is no
660
+ // temporal-dead-zone hazard.
661
+ const registry = {
662
+ getModels() {
663
+ return activeModels
664
+ },
665
+
666
+ /**
667
+ * #5932 — apply a hot-reloaded overlay WITHOUT rebuilding the registry
668
+ * (which would discard SDK-learned models + contextWindow overrides). Re-fold
669
+ * the new overlay into the fallback set, then:
670
+ * - if SDK data was applied (lastSdkModels) → re-run updateModels() so the
671
+ * overlay (overlay-only rows + label/window overrides) re-merges with the
672
+ * live SDK list exactly as it did originally (AC2);
673
+ * - otherwise (CLI-only / pre-init) → the re-folded fallback IS the active
674
+ * list; re-apply it and rebuild lookups, preserving the current default.
675
+ * Returns the new active model list.
676
+ */
677
+ applyOverlay(newOverlay) {
678
+ const map = newOverlay instanceof Map ? newOverlay : new Map()
679
+ currentOverlay = map // #6381: keep getOverlayPricing in sync with reloads
680
+ fallbackModels = computeFallbackModels(map)
681
+ if (lastSdkModels) {
682
+ registry.updateModels(lastSdkModels)
683
+ } else if (lastCacheModels) {
684
+ // Cache-warmed (loadCache) but no SDK refresh yet — apply the new
685
+ // fallback (base + overlay overrides + overlay-only rows) while
686
+ // PRESERVING the cache entries it doesn't cover (date-suffixed ids past
687
+ // the family filter, e.g. `claude-sonnet-4-20250514`). Preserve from the
688
+ // CACHE list, not `activeModels`, so an overlay-only row the operator
689
+ // REMOVED still drops (it lives in fallbackModels, never lastCacheModels)
690
+ // — matched on fullId so an overlay override of a cached/fallback row
691
+ // still wins (it's in fallbackModels → the cache copy is skipped).
692
+ const byFullId = new Set(fallbackModels.map((m) => m.fullId))
693
+ const preserved = lastCacheModels.filter((m) => !byFullId.has(m.fullId))
694
+ const next = preserved.length > 0 ? Object.freeze([...fallbackModels, ...preserved]) : fallbackModels
695
+ applyModels(next, defaultModelId)
696
+ } else {
697
+ applyModels(fallbackModels, defaultModelId)
698
+ }
699
+ return activeModels
700
+ },
701
+
702
+ updateModels(sdkModels) {
703
+ if (!Array.isArray(sdkModels)) {
704
+ log.debug(`updateModels: ignoring non-array input (got ${sdkModels === null ? 'null' : typeof sdkModels})`)
705
+ return null
706
+ }
707
+
708
+ let nextDefault = null
709
+ // Track total dropped count separately from the key-sample buffer so
710
+ // the log reports "dropped N/M" correctly when more than 3 entries
711
+ // are invalid (the sample is capped to avoid log bloat).
712
+ let droppedCount = 0
713
+ const droppedSample = []
714
+ const converted = sdkModels
715
+ .filter(m => {
716
+ const ok = m && typeof m.value === 'string' && m.value.length > 0
717
+ if (!ok) {
718
+ droppedCount++
719
+ if (droppedSample.length < 3) droppedSample.push(m)
720
+ }
721
+ return ok
722
+ })
723
+ .map(m => {
724
+ const fullId = m.value
725
+ // Prefer the provider's own metadata lookup when it recognises
726
+ // the id — that keeps the short id / label / context window in
727
+ // sync with whatever the provider exposes via `getAllowedModels()`
728
+ // and `getFallbackModels()`. When the provider has no entry for
729
+ // this id (new release, custom deploy, …) fall back to the
730
+ // registry's deriveId/resolveContextWindow hooks.
731
+ const providerMeta = getModelMetadataFn ? getModelMetadataFn(fullId) : null
732
+ const derivedId = providerMeta?.id ?? deriveIdFn(fullId)
733
+ let label = m.displayName || ''
734
+ if (typeof m.displayName === 'string' && /^default\b/i.test(m.displayName)) {
735
+ nextDefault = derivedId
736
+ const match = label.match(/^Default\s*\((.+)\)$/)
737
+ if (match) label = match[1]
738
+ }
739
+ if (!label || /^recommended$/i.test(label)) {
740
+ label = providerMeta?.label || humanizeModelId(derivedId)
741
+ }
742
+ // Prefer an authoritative value observed from SDK modelUsage
743
+ // over the static heuristic, so a learned contextWindow isn't
744
+ // lost when _fetchSupportedModels() fires on every init.
745
+ const contextWindow = contextWindowOverrides.get(fullId)
746
+ ?? providerMeta?.contextWindow
747
+ ?? resolveContextWindowFn(fullId)
748
+ return { id: derivedId, label, fullId, contextWindow }
749
+ })
750
+
751
+ if (droppedCount > 0) {
752
+ // Contract drift: SDK returned entries whose `value` was missing,
753
+ // non-string, or empty. Log the accurate total count, plus a
754
+ // keys-only sample of the first N offenders — entries may carry
755
+ // provider metadata we don't want to leak to disk logs.
756
+ const sample = droppedSample.map(m => {
757
+ if (m === null) return 'null'
758
+ if (typeof m !== 'object') return typeof m
759
+ return `{${Object.keys(m).join(',')}}`
760
+ }).join(', ')
761
+ log.warn(`updateModels: dropped ${droppedCount}/${sdkModels.length} SDK entries with missing or invalid 'value' key (sample: ${sample})`)
762
+ }
763
+
764
+ if (converted.length === 0) {
765
+ if (sdkModels.length > 0) {
766
+ log.warn(`updateModels: SDK returned ${sdkModels.length} entries but none matched the expected {value,displayName,description} shape — keeping existing models`)
767
+ }
768
+ return converted
769
+ }
770
+
771
+ // Merge fallback entries that the SDK omitted so the picker stays
772
+ // useful when the CLI under-reports (#3075 — observed on Opus 4.7,
773
+ // where supportedModels() returned only the 4.6 family). Match on
774
+ // fullId — fallback's id is a short alias (e.g. `opus`) that would
775
+ // otherwise collide with a derived id of the same family.
776
+ const seenFullIds = new Set(converted.map(m => m.fullId))
777
+ for (const fb of fallbackModels) {
778
+ if (!seenFullIds.has(fb.fullId)) {
779
+ // Re-derive the short id with the registry's hook so non-Claude
780
+ // providers don't accidentally inherit Claude's `claude-` strip.
781
+ const providerMeta = getModelMetadataFn ? getModelMetadataFn(fb.fullId) : null
782
+ const id = providerMeta?.id ?? deriveIdFn(fb.fullId)
783
+ const label = providerMeta?.label || humanizeModelId(id)
784
+ const contextWindow = contextWindowOverrides.get(fb.fullId)
785
+ ?? providerMeta?.contextWindow
786
+ ?? fb.contextWindow
787
+ ?? resolveContextWindowFn(fb.fullId)
788
+ converted.push({ id, label, fullId: fb.fullId, contextWindow })
789
+ seenFullIds.add(fb.fullId)
790
+ }
791
+ }
792
+
793
+ // Synthesize 1M-context variants for any model with a >=1M context
794
+ // window that doesn't already have an explicit `[1m]` entry. The CLI
795
+ // accepts `claude-*[1m]` as a separate model id (verified against the
796
+ // claude binary), so the picker should surface it as a distinct chip
797
+ // even though `supportedModels()` doesn't list it (#3075).
798
+ //
799
+ // Pricing-table drift guard (#4106): the day Anthropic ships a 1M
800
+ // variant of Sonnet/Haiku/any-future-model, `updateModels` will
801
+ // synthesize the `[1m]` chip here, but if the pricing table at the
802
+ // top of this file doesn't carry a matching entry with a
803
+ // `longContext` block, `resolvePricingKey` falls back to the base
804
+ // family entry and silently undercounts >200K turns by whatever the
805
+ // premium ratio is. Warn-once per variant so an operator notices
806
+ // before the bills lie. Forward-compat only — no current breakage.
807
+ const variants = []
808
+ for (const m of converted) {
809
+ if (!m.fullId || m.fullId.endsWith(ONE_M_SUFFIX)) continue
810
+ if (m.contextWindow < 1_000_000) continue
811
+ const variantFullId = `${m.fullId}${ONE_M_SUFFIX}`
812
+ if (seenFullIds.has(variantFullId)) continue
813
+ const variantId = `${m.id}${ONE_M_SUFFIX}`
814
+ // Consult the provider's metadata hook first so non-Claude registries
815
+ // that eventually ship a >=1M model get their authoritative label
816
+ // instead of the humanizeModelId mangling (#4441 follow-up to #4438).
817
+ // Currently unreachable for codex/gemini (no 1M models today) but
818
+ // keeps the synthesis path consistent with the five other call sites.
819
+ const providerMeta = getModelMetadataFn ? getModelMetadataFn(variantFullId) : null
820
+ variants.push({
821
+ id: variantId,
822
+ label: providerMeta?.label || humanizeModelId(variantId),
823
+ fullId: variantFullId,
824
+ contextWindow: 1_000_000,
825
+ })
826
+ seenFullIds.add(variantFullId)
827
+ // Drift detection (#4106 + #4116). Two failure modes both lose
828
+ // the premium tier in different ways:
829
+ // (1) No `[1m]` entry at all → resolvePricingKey may return null
830
+ // (cost=0) or fall back to the base family entry (no
831
+ // longContext block) depending on the family.
832
+ // (2) `[1m]` entry exists but lacks `longContext` → premium
833
+ // block silently absent; >200K turns billed at base rates.
834
+ // Both produce undercounting; warn for either. Gate to `claude-*`
835
+ // so non-Claude registries don't get a Claude-pricing nag.
836
+ if (variantFullId.startsWith('claude-')) {
837
+ const entry = CLAUDE_PRICING_USD_PER_MTOK[variantFullId]
838
+ if ((!entry || !entry.longContext) && !pricingDriftWarned.has(variantFullId)) {
839
+ const reason = entry
840
+ ? `no longContext premium block; >200K turns will bill at base rates`
841
+ : `no entry in CLAUDE_PRICING_USD_PER_MTOK; cost may be 0 or fall back to base`
842
+ log.warn(`pricing-table drift: synthesized 1M variant ${variantFullId} ${reason}. Add an explicit entry (with longContext) in packages/server/src/claude-model-catalog.js.`)
843
+ pricingDriftWarned.add(variantFullId)
844
+ }
845
+ }
846
+ }
847
+ converted.push(...variants)
848
+
849
+ // #5631 — robustness: the `/^default\b/i` displayName regex is the only
850
+ // path that sets nextDefault. If the SDK ever drops or renames the
851
+ // "Default (…)" marker, nextDefault stays null and the registry has no
852
+ // default model at all. Pick a deterministic fallback so drift is
853
+ // visible and the picker still has a sensible default: prefer a stable
854
+ // family present in FALLBACK_MODELS (opus, then sonnet) — matched by the
855
+ // fallback row's fullId so SDK-derived ids like `opus-4-8` (not the
856
+ // short alias `opus`) still match — else the first converted entry.
857
+ // Warn so the regex miss surfaces in logs.
858
+ if (nextDefault === null && converted.length > 0) {
859
+ let picked = null
860
+ for (const preferredShortId of ['opus', 'sonnet']) {
861
+ const fb = fallbackModels.find((m) => m.id === preferredShortId)
862
+ if (!fb) continue
863
+ const match = converted.find((m) => m.fullId === fb.fullId)
864
+ if (match) { picked = match.id; break }
865
+ }
866
+ if (!picked) picked = converted[0].id
867
+ nextDefault = picked
868
+ log.warn(`updateModels: no SDK entry matched the /^default\\b/i displayName regex — falling back to '${picked}' as the default model. The SDK's "Default (…)" marker may have changed shape.`)
869
+ }
870
+
871
+ // #5932: remember the raw SDK list so a later overlay hot-reload can
872
+ // re-merge against it (AC2). Store the original input, not `converted`,
873
+ // so the re-merge re-derives ids/labels/windows from the new fallback
874
+ // exactly as the original call did.
875
+ lastSdkModels = sdkModels
876
+ applyModels(converted, nextDefault)
877
+ return converted
878
+ },
879
+
880
+ /**
881
+ * Replace the contextWindow for an existing entry when the SDK reports
882
+ * an authoritative value (via `SDKResultSuccess.modelUsage`). Matches
883
+ * on `fullId` or short `id`. No-op if the model isn't in the registry
884
+ * or the reported value already matches.
885
+ */
886
+ updateContextWindow(modelId, contextWindow) {
887
+ if (typeof modelId !== 'string' || typeof contextWindow !== 'number' || contextWindow <= 0) {
888
+ return false
889
+ }
890
+ let changed = false
891
+ activeModels = activeModels.map(m => {
892
+ if ((m.id === modelId || m.fullId === modelId) && m.contextWindow !== contextWindow) {
893
+ changed = true
894
+ // Persist the authoritative value so a later updateModels()
895
+ // refresh doesn't revert us to the static heuristic.
896
+ contextWindowOverrides.set(m.fullId, contextWindow)
897
+ return { ...m, contextWindow }
898
+ }
899
+ return m
900
+ })
901
+ return changed
902
+ },
903
+
904
+ resetModels() {
905
+ contextWindowOverrides.clear()
906
+ pricingDriftWarned.clear()
907
+ // #5932: drop the retained SDK + cache lists too, so a reset truly returns
908
+ // to the bare fallback view (a later applyOverlay won't re-merge stale
909
+ // SDK/cache data).
910
+ lastSdkModels = null
911
+ lastCacheModels = null
912
+ applyModels(fallbackModels, null)
913
+ lastSavedSnapshot = null
914
+ },
915
+
916
+ getDefaultModelId() {
917
+ return defaultModelId
918
+ },
919
+
920
+ resolveModelId(model) {
921
+ return toFullIdMap.get(model) || model
922
+ },
923
+
924
+ // #6381: this registry's overlay pricing for a model id (or null). Lets a
925
+ // non-Claude provider honor `pricing` from a `provider`-tagged ~/.chroxy/
926
+ // models.json entry — re-pricing a model with no release. Overlay only; the
927
+ // provider's own static table is the caller's fallback.
928
+ getOverlayPricing(model) {
929
+ return lookupOverlayPricing(model, currentOverlay, (id) => toFullIdMap.get(id) || id)
930
+ },
931
+
932
+ toShortModelId(model) {
933
+ return toShortIdMap.get(model) || model
934
+ },
935
+
936
+ getAllowedModelIds() {
937
+ return allowedModelIds
938
+ },
939
+
940
+ /**
941
+ * Load a previously cached model list from disk. Returns true on success.
942
+ * Silently returns false if the cache is absent, malformed, or empty.
943
+ * Missing `label` and `contextWindow` fields are re-derived so that
944
+ * older or hand-edited cache files don't leave the picker with empty
945
+ * labels or a default context window.
946
+ */
947
+ loadCache(path = cachePathFn()) {
948
+ try {
949
+ const raw = readFileSync(path, 'utf-8')
950
+ const parsed = JSON.parse(raw)
951
+ if (!Array.isArray(parsed?.models) || parsed.models.length === 0) return false
952
+
953
+ // Filter out cached entries whose family is no longer in
954
+ // FALLBACK_MODELS, OR whose minor version was superseded (#3162).
955
+ // FALLBACK_MODELS is version-pinned per release, so it's the
956
+ // authoritative set of currently-supported families/minors.
957
+ // Date-suffixed SDK ids (e.g. `claude-sonnet-4-20250514`) carry no
958
+ // explicit minor and pass through on family match — the API still
959
+ // accepts them. Family-only retirement (e.g. sonnet 3 dropped
960
+ // entirely) is caught by the family-not-in-fallback branch.
961
+ // CLI-only users never have updateModels() called, so without
962
+ // this filter a stale cache lingers indefinitely.
963
+ const fallbackByFamily = new Map()
964
+ for (const fb of fallbackModels) {
965
+ const { family, minor } = modelFamilyAndMinor(fb.fullId)
966
+ if (!family) continue
967
+ if (!fallbackByFamily.has(family)) fallbackByFamily.set(family, new Set())
968
+ if (minor !== null) fallbackByFamily.get(family).add(minor)
969
+ }
970
+
971
+ const valid = parsed.models.filter(m =>
972
+ m && typeof m.id === 'string' && typeof m.fullId === 'string',
973
+ )
974
+ const models = valid
975
+ .filter(m => {
976
+ const { family, minor } = modelFamilyAndMinor(m.fullId)
977
+ if (!fallbackByFamily.has(family)) return false
978
+ if (minor === null) return true
979
+ return fallbackByFamily.get(family).has(minor)
980
+ })
981
+ .map(m => {
982
+ // #4434: when the cached label is missing/empty (older cache
983
+ // files, or operators hand-editing the on-disk cache that
984
+ // landed in #4413), prefer the provider's own metadata label
985
+ // before falling back to `humanizeModelId`. The humanize
986
+ // helper assumes Claude-style ids ("opus-4-7" → "Opus 4.7")
987
+ // and mangles non-Claude ids ("gpt-5-codex" → "Gpt 5.codex").
988
+ // Mirrors the post-filter merge step below which already
989
+ // consults `getModelMetadataFn` for the same reason.
990
+ const providerMeta = getModelMetadataFn ? getModelMetadataFn(m.fullId) : null
991
+ return {
992
+ id: m.id,
993
+ fullId: m.fullId,
994
+ label: typeof m.label === 'string' && m.label.length > 0
995
+ ? m.label
996
+ : (providerMeta?.label || humanizeModelId(m.id)),
997
+ contextWindow: typeof m.contextWindow === 'number' && m.contextWindow > 0
998
+ ? m.contextWindow
999
+ : resolveContextWindowFn(m.fullId),
1000
+ }
1001
+ })
1002
+
1003
+ const droppedStaleCount = valid.length - models.length
1004
+ if (droppedStaleCount > 0) {
1005
+ log.info(`loadCache: dropped ${droppedStaleCount} stale cache entr${droppedStaleCount === 1 ? 'y' : 'ies'} not in FALLBACK_MODELS`)
1006
+ }
1007
+
1008
+ if (models.length === 0) {
1009
+ if (valid.length > 0) {
1010
+ log.warn(`loadCache: all ${valid.length} cached entries are stale; falling back to FALLBACK_MODELS`)
1011
+ }
1012
+ return false
1013
+ }
1014
+
1015
+ // Merge in any fallback entries the filtered cache doesn't cover
1016
+ // so the picker always has the canonical sonnet/opus/haiku aliases
1017
+ // even when the cache was mostly stale. The `[1m]` variant
1018
+ // synthesis that updateModels() does is intentionally NOT repeated
1019
+ // here — variants are already in the saved cache for SDK users,
1020
+ // and CLI-only users would not have a working SDK call to populate
1021
+ // them anyway.
1022
+ const seenFullIds = new Set(models.map(m => m.fullId))
1023
+ for (const fb of fallbackModels) {
1024
+ if (!seenFullIds.has(fb.fullId)) {
1025
+ const providerMeta = getModelMetadataFn ? getModelMetadataFn(fb.fullId) : null
1026
+ const id = providerMeta?.id ?? deriveIdFn(fb.fullId)
1027
+ const label = providerMeta?.label || humanizeModelId(id)
1028
+ const contextWindow = providerMeta?.contextWindow ?? fb.contextWindow ?? resolveContextWindowFn(fb.fullId)
1029
+ models.push({ id, fullId: fb.fullId, label, contextWindow })
1030
+ seenFullIds.add(fb.fullId)
1031
+ }
1032
+ }
1033
+
1034
+ // Drop the cached default if it points to a filtered-out entry —
1035
+ // otherwise resolveModelId would map a stale short id to the same
1036
+ // retired fullId on the first set_model call.
1037
+ let nextDefault = parsed.defaultModelId || null
1038
+ const defaultDiscarded = nextDefault && !models.some(m => m.id === nextDefault || m.fullId === nextDefault)
1039
+ if (defaultDiscarded) nextDefault = null
1040
+
1041
+ applyModels(models, nextDefault)
1042
+ // #5932: remember the cache-applied list so an overlay reload in the
1043
+ // CLI-only window (no SDK refresh yet) preserves these entries.
1044
+ lastCacheModels = models
1045
+ // Treat the loaded state as the last-saved baseline so subsequent
1046
+ // saveCache() calls only hit disk when the registry actually drifts.
1047
+ lastSavedSnapshot = snapshotString()
1048
+
1049
+ // Heal the disk file when we pruned anything. Without this the
1050
+ // CLI-only/offline path would re-filter the same stale entries on
1051
+ // every startup since updateModels() never runs to overwrite them.
1052
+ if (droppedStaleCount > 0 || defaultDiscarded) {
1053
+ // Force a write by clearing the snapshot baseline (saveCacheImpl
1054
+ // skips when snapshot matches lastSavedSnapshot).
1055
+ lastSavedSnapshot = null
1056
+ saveCacheImpl(path)
1057
+ }
1058
+
1059
+ return true
1060
+ } catch {
1061
+ return false
1062
+ }
1063
+ },
1064
+
1065
+ /**
1066
+ * Persist the current model list to disk. Returns true on success
1067
+ * OR when there was nothing to persist (idempotent no-op); returns
1068
+ * false only if the write was attempted and failed.
1069
+ *
1070
+ * Skips disk IO when the (models, defaultModelId) snapshot matches the
1071
+ * last successful save — `_fetchSupportedModels()` fires on every SDK
1072
+ * session init, which would otherwise write ~2 KB on every user message.
1073
+ *
1074
+ * Writes go through a temp file + rename so a crash mid-write can't
1075
+ * leave a truncated cache, and permissions are locked down via
1076
+ * writeFileRestricted (0600).
1077
+ */
1078
+ saveCache(path = cachePathFn()) {
1079
+ return saveCacheImpl(path)
1080
+ },
1081
+ }
1082
+
1083
+ return registry
1084
+ }
1085
+
1086
+ // Default instance — preserves backward compatibility for all existing imports.
1087
+ // Seeded with the boot-loaded user overlay so an operator-supplied model id
1088
+ // appears in the picker / allowlist and survives the loadCache prune.
1089
+ const defaultRegistry = createModelsRegistry({ overlay: defaultOverlay })
1090
+
1091
+ /**
1092
+ * #5932 — hot-reload the user model overlay (`~/.chroxy/models.json`) into the
1093
+ * DEFAULT (Claude) registry + the module-level pricing path, without a daemon
1094
+ * restart. Re-reads the file, re-folds it into the registry (re-merging with
1095
+ * any live SDK model list — AC2), and swaps the module-level `defaultOverlay`
1096
+ * so `getModelPricing()` picks up new/changed pricing.
1097
+ *
1098
+ * Safety (AC3): a MALFORMED overlay is rejected — the registry + pricing keep
1099
+ * the LAST GOOD set and the call returns `{ reloaded: false, reason }`. A
1100
+ * deleted/absent file legitimately CLEARS the overlay (an explicit operator
1101
+ * action). Never throws.
1102
+ *
1103
+ * @param {string} [path]
1104
+ * @returns {{ reloaded: boolean, reason?: string, models?: object[], defaultModelId?: string|null }}
1105
+ */
1106
+ export function reloadModelsOverlay(path = getDefaultOverlayPath()) {
1107
+ const result = loadModelsOverlayResult(path)
1108
+ if (!result.ok) {
1109
+ // Malformed — keep the last-good registry + pricing untouched.
1110
+ return { reloaded: false, reason: 'malformed' }
1111
+ }
1112
+ defaultOverlay = result.overlay
1113
+ defaultRegistry.applyOverlay(result.overlay)
1114
+ // #6377: re-fold the per-provider slices into every ALREADY-BUILT non-Claude
1115
+ // registry. A provider whose registry hasn't been built yet picks up its slice
1116
+ // lazily on first getRegistryForProvider() (which reads providerOverlays), so
1117
+ // only the cached ones need an explicit re-fold here. A provider that lost all
1118
+ // its overlay entries gets an empty Map → its overlay-only rows drop.
1119
+ providerOverlays = result.byProvider
1120
+ for (const [name, registry] of providerRegistryCache) {
1121
+ registry.applyOverlay(providerOverlays.get(name) ?? new Map())
1122
+ }
1123
+ return {
1124
+ reloaded: true,
1125
+ models: defaultRegistry.getModels(),
1126
+ defaultModelId: defaultRegistry.getDefaultModelId(),
1127
+ }
1128
+ }
1129
+
1130
+ /**
1131
+ * #5932 — watch the overlay file for edits and hot-reload on change. Watches the
1132
+ * containing DIRECTORY (not the file inode) so an editor's atomic
1133
+ * write-temp-then-rename still fires, filters to the overlay filename, and
1134
+ * debounces the burst of events a single save emits. On a successful reload the
1135
+ * `onReload({ models, defaultModelId })` callback fires (the caller broadcasts
1136
+ * `available_models`). A malformed save is ignored (last-good kept, no callback).
1137
+ *
1138
+ * Returns a `{ close() }` handle; call it on daemon shutdown. Never throws — a
1139
+ * watch that can't be established (e.g. unsupported FS) logs a warn and returns
1140
+ * an inert handle (boot-only behavior, unchanged).
1141
+ *
1142
+ * `watchFactory` is injectable for tests (defaults to `fs.watch`); it must
1143
+ * return a watcher with `.close()` and accept `(dir, listener)`.
1144
+ *
1145
+ * @param {{ path?: string, onReload?: (r: object) => void, debounceMs?: number, watchFactory?: Function }} [opts]
1146
+ * @returns {{ close: () => void }}
1147
+ */
1148
+ export function watchModelsOverlay({ path = getDefaultOverlayPath(), onReload, debounceMs = 200, watchFactory } = {}) {
1149
+ const dir = dirname(path)
1150
+ const file = basename(path)
1151
+ let timer = null
1152
+ let closed = false
1153
+
1154
+ const fire = () => {
1155
+ timer = null
1156
+ if (closed) return
1157
+ const result = reloadModelsOverlay(path)
1158
+ if (result.reloaded && typeof onReload === 'function') {
1159
+ try { onReload(result) } catch (err) { log.warn(`watchModelsOverlay: onReload threw: ${err?.message || err}`) }
1160
+ }
1161
+ }
1162
+ const trigger = () => {
1163
+ if (closed) return
1164
+ if (timer) clearTimeout(timer)
1165
+ timer = setTimeout(fire, debounceMs)
1166
+ }
1167
+
1168
+ let watcher
1169
+ try {
1170
+ const factory = typeof watchFactory === 'function' ? watchFactory : (d, listener) => fsWatch(d, listener)
1171
+ watcher = factory(dir, (_eventType, changed) => {
1172
+ // Directory watch fires for every entry; only react to our file. A null
1173
+ // filename (some platforms) is treated as "maybe ours" → reload.
1174
+ if (changed == null || basename(String(changed)) === file) trigger()
1175
+ })
1176
+ if (watcher && typeof watcher.on === 'function') {
1177
+ watcher.on('error', (err) => log.warn(`watchModelsOverlay: watcher error: ${err?.message || err}`))
1178
+ }
1179
+ } catch (err) {
1180
+ log.warn(`watchModelsOverlay: could not watch ${dir}: ${err?.message || err} — overlay edits need a restart`)
1181
+ return { close() {} }
1182
+ }
1183
+
1184
+ return {
1185
+ close() {
1186
+ closed = true
1187
+ if (timer) { clearTimeout(timer); timer = null }
1188
+ try { watcher?.close?.() } catch { /* already closed */ }
1189
+ },
1190
+ }
1191
+ }
1192
+
1193
+ /**
1194
+ * #5932 — test hook: restore the module-level default overlay + registry to a
1195
+ * known state so a test that exercises reloadModelsOverlay() doesn't leak global
1196
+ * mutations into sibling tests. Pass a Map to seed a specific overlay, or omit
1197
+ * for an empty one.
1198
+ */
1199
+ export function _resetModelsOverlayForTests(overlay = new Map(), byProvider = new Map()) {
1200
+ defaultOverlay = overlay instanceof Map ? overlay : new Map()
1201
+ defaultRegistry.applyOverlay(defaultOverlay)
1202
+ // #6377: reset the per-provider overlays + re-fold any cached provider
1203
+ // registries so a test can't leak provider-overlay state into siblings.
1204
+ providerOverlays = byProvider instanceof Map ? byProvider : new Map()
1205
+ for (const [name, registry] of providerRegistryCache) {
1206
+ registry.applyOverlay(providerOverlays.get(name) ?? new Map())
1207
+ }
1208
+ }
1209
+
1210
+ /**
1211
+ * Per-provider registries. Providers that expose static
1212
+ * `getFallbackModels()` and `getModelMetadata(id)` get a dedicated, isolated
1213
+ * registry so a Codex or Gemini session never sees Claude-only models. The
1214
+ * cache is lazy and keyed by provider name.
1215
+ *
1216
+ * The default Claude providers (`claude-sdk`, `claude-cli`, any docker alias
1217
+ * thereof) continue to share the module-level `defaultRegistry` so that the
1218
+ * existing cache-warming path (`loadModelsCache`) and the live
1219
+ * `updateModels()` feed from the Agent SDK still have one source of truth.
1220
+ */
1221
+ const providerRegistryCache = new Map()
1222
+
1223
+ /**
1224
+ * True when the given provider is a Claude-family provider (and so shares the
1225
+ * default models registry, which is fed by the Agent SDK's live
1226
+ * `supportedModels()` push). Non-Claude providers (Codex, Gemini, custom) have
1227
+ * their own static allowlists and should be validated strictly.
1228
+ *
1229
+ * Used by `SessionManager.createSession` (#3403) to decide whether an unknown
1230
+ * initial model should be a hard rejection or a soft fall-back to the provider
1231
+ * default — Claude's allowlist is a moving target driven by a stale dashboard
1232
+ * `defaultModel` (e.g. `opus-4-6` after `opus-4-7` ships) so a hard error breaks
1233
+ * otherwise-valid session creation.
1234
+ *
1235
+ * #5858: membership is the SINGLE `static claudeFamily = true` flag on the
1236
+ * provider class (inherited by docker-* subclasses), not a hand-maintained name
1237
+ * literal that drifted from the registry (#5855). When the class isn't passed,
1238
+ * it is resolved via the `nameToProviderClass` map (populated for every provider
1239
+ * at registration). Docker-* resolve once `registerDockerProvider()` has run —
1240
+ * which is always before a docker session is created; `getRegistryForProvider`
1241
+ * is unaffected pre-registration because its unknown-name branch also returns
1242
+ * the default registry.
1243
+ *
1244
+ * @param {string|undefined|null} providerName
1245
+ * @param {Function} [ProviderClass] - optional provider class for the name
1246
+ * @returns {boolean}
1247
+ */
1248
+ export function isClaudeProvider(providerName, ProviderClass = null) {
1249
+ // A passed class is AUTHORITATIVE: trust its boolean flag, so an explicit
1250
+ // `static claudeFamily = false` opts out even when the name would otherwise
1251
+ // resolve to a Claude class (name/class can only disagree on a caller bug,
1252
+ // but the class the caller handed us is the ground truth).
1253
+ if (ProviderClass && typeof ProviderClass.claudeFamily === 'boolean') {
1254
+ return ProviderClass.claudeFamily
1255
+ }
1256
+ // No class (or no flag on it) — resolve the class by name via the registry.
1257
+ if (typeof providerName === 'string') {
1258
+ const resolved = nameToProviderClass.get(providerName)
1259
+ if (resolved && resolved.claudeFamily === true) {
1260
+ return true
1261
+ }
1262
+ }
1263
+ return false
1264
+ }
1265
+
1266
+ // Populated by providers.js at module load so models.js can resolve a
1267
+ // provider name to its ProviderClass without creating a circular import.
1268
+ // Keeping this module-local + async-free keeps `getRegistryForProvider()`
1269
+ // synchronous for the ws-history.js hot path (post-auth handshake).
1270
+ const nameToProviderClass = new Map()
1271
+
1272
+ /**
1273
+ * Called by providers.js after `registerProvider(name, ProviderClass)` so
1274
+ * models.js can build a per-provider registry on demand. Noop for Claude
1275
+ * providers — they share the default registry.
1276
+ *
1277
+ * @param {string} providerName
1278
+ * @param {Function} ProviderClass
1279
+ */
1280
+ export function registerProviderRegistry(providerName, ProviderClass) {
1281
+ if (!providerName || typeof providerName !== 'string') return
1282
+ if (typeof ProviderClass !== 'function') return
1283
+ nameToProviderClass.set(providerName, ProviderClass)
1284
+ // Purge any previously-cached registry so a re-registration picks up
1285
+ // the new class (useful for tests and hot-reload).
1286
+ providerRegistryCache.delete(providerName)
1287
+ }
1288
+
1289
+ /**
1290
+ * Test helper (#4413). Drops the cached provider registries so the next
1291
+ * `getRegistryForProvider()` call rebuilds — and re-runs `loadCache()` —
1292
+ * from disk. Used by the persistence test suite to simulate "server
1293
+ * restart": save → wipe in-memory state → re-read.
1294
+ *
1295
+ * Not exported via the public API surface beyond tests; the name leads
1296
+ * with an underscore to signal that.
1297
+ *
1298
+ * @param {string} [providerName] - When provided, drop only that provider's
1299
+ * cached registry; when omitted, drop all of them.
1300
+ */
1301
+ export function _resetProviderRegistryCacheForTests(providerName) {
1302
+ if (typeof providerName === 'string' && providerName.length > 0) {
1303
+ providerRegistryCache.delete(providerName)
1304
+ return
1305
+ }
1306
+ providerRegistryCache.clear()
1307
+ }
1308
+
1309
+ /**
1310
+ * Lazily create and cache a provider-scoped registry.
1311
+ *
1312
+ * Claude providers (including docker-based variants) share the module-level
1313
+ * default registry so the live SDK feed keeps updating a single source of
1314
+ * truth. Non-Claude providers get their own registry driven by
1315
+ * `ProviderClass.getFallbackModels()` and `ProviderClass.getModelMetadata()`.
1316
+ *
1317
+ * Unknown or unregistered provider names fall back to the Claude registry
1318
+ * (safe default — matches the legacy global behaviour).
1319
+ *
1320
+ * @param {string} providerName
1321
+ * @returns {ReturnType<typeof createModelsRegistry>}
1322
+ */
1323
+ export function getRegistryForProvider(providerName) {
1324
+ if (!providerName || isClaudeProvider(providerName)) {
1325
+ return defaultRegistry
1326
+ }
1327
+
1328
+ const cached = providerRegistryCache.get(providerName)
1329
+ if (cached) return cached
1330
+
1331
+ const ProviderClass = nameToProviderClass.get(providerName)
1332
+ if (!ProviderClass || typeof ProviderClass.getFallbackModels !== 'function') {
1333
+ return defaultRegistry
1334
+ }
1335
+
1336
+ const registry = createModelsRegistry({
1337
+ fallbackModels: ProviderClass.getFallbackModels(),
1338
+ getModelMetadata: typeof ProviderClass.getModelMetadata === 'function'
1339
+ ? (id) => ProviderClass.getModelMetadata(id)
1340
+ : null,
1341
+ // Non-Claude providers typically use opaque full ids (no prefix to
1342
+ // strip) — identity is the safest default. Providers can override via
1343
+ // `getModelMetadata()` when they want a different short id.
1344
+ deriveId: (fullId) => fullId,
1345
+ resolveContextWindow: (fullId) => {
1346
+ const meta = typeof ProviderClass.getModelMetadata === 'function'
1347
+ ? ProviderClass.getModelMetadata(fullId)
1348
+ : null
1349
+ // #5421: preserve an EXPLICIT null — providers like ollama return
1350
+ // `contextWindow: null` to say "window unknown, never fabricate"
1351
+ // (#5418), and substituting DEFAULT_CONTEXT_WINDOW here would pin a
1352
+ // made-up 200k chip on every discovered local model. Only fall back
1353
+ // to the default when the provider has no metadata entry at all.
1354
+ if (meta && 'contextWindow' in meta) return meta.contextWindow
1355
+ return DEFAULT_CONTEXT_WINDOW
1356
+ },
1357
+ // #4413: provider-scoped cache path. Lazy resolver so tests that mutate
1358
+ // `CHROXY_CONFIG_DIR` after registry creation still hit the temp dir.
1359
+ cachePath: () => getProviderCachePath(providerName),
1360
+ // #6377: this provider's slice of the user overlay (entries tagged
1361
+ // `provider: "<name>"`) — seeds new models + overrides labels/windows just
1362
+ // like the Claude registry's overlay. Empty Map when the operator supplied
1363
+ // none. Re-folded on hot-reload (reloadModelsOverlay).
1364
+ overlay: providerOverlays.get(providerName) ?? new Map(),
1365
+ })
1366
+ // #4413: hydrate the registry from its own cache file before serving the
1367
+ // first getModels() call. A miss (no file, malformed, all-stale) is a
1368
+ // silent no-op so cold-boot semantics are unchanged. This restores any
1369
+ // previously-learned context-window ratchet (gpt-5/gpt-5-codex 400k →
1370
+ // 550k after a series of large turns) so the dashboard meter is honest
1371
+ // immediately, not only after the next over-budget turn.
1372
+ try {
1373
+ registry.loadCache()
1374
+ } catch (err) {
1375
+ log.warn(`getRegistryForProvider(${providerName}): loadCache threw unexpectedly: ${err?.message || err}`)
1376
+ }
1377
+ providerRegistryCache.set(providerName, registry)
1378
+ return registry
1379
+ }
1380
+
1381
+ // Accept both short ids and full model IDs in set_model.
1382
+ // Proxy delegates to the default registry's live Set so mutations
1383
+ // (from updateModels/resetModels) are always reflected.
1384
+ export const ALLOWED_MODEL_IDS = new Proxy(new Set(), {
1385
+ get(_, prop) {
1386
+ const target = defaultRegistry.getAllowedModelIds()
1387
+ const value = Reflect.get(target, prop, target)
1388
+ return typeof value === 'function' ? value.bind(target) : value
1389
+ },
1390
+ })
1391
+
1392
+ export function getModels() {
1393
+ return defaultRegistry.getModels()
1394
+ }
1395
+
1396
+ export function updateModels(sdkModels) {
1397
+ return defaultRegistry.updateModels(sdkModels)
1398
+ }
1399
+
1400
+ export function updateContextWindow(modelId, contextWindow) {
1401
+ return defaultRegistry.updateContextWindow(modelId, contextWindow)
1402
+ }
1403
+
1404
+ export function resetModels() {
1405
+ defaultRegistry.resetModels()
1406
+ }
1407
+
1408
+ export function resolveModelId(model) {
1409
+ return defaultRegistry.resolveModelId(model)
1410
+ }
1411
+
1412
+ export function toShortModelId(model) {
1413
+ return defaultRegistry.toShortModelId(model)
1414
+ }
1415
+
1416
+ export function getDefaultModelId() {
1417
+ return defaultRegistry.getDefaultModelId()
1418
+ }
1419
+
1420
+ export function loadModelsCache(path) {
1421
+ return defaultRegistry.loadCache(path)
1422
+ }
1423
+
1424
+ export function saveModelsCache(path) {
1425
+ return defaultRegistry.saveCache(path)
1426
+ }