@chroxy/server 0.11.0 → 0.11.10

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 (317) hide show
  1. package/CONFIG.md +204 -18
  2. package/README.md +2 -2
  3. package/hooks/claude-native-route-check.mjs +17 -0
  4. package/hooks/permission-hook.sh +166 -11
  5. package/package.json +16 -12
  6. package/sidecar/Dockerfile +1 -1
  7. package/sidecar/PROTOCOL.md +9 -1
  8. package/sidecar/agent.js +102 -10
  9. package/sidecar/package-lock.json +3 -3
  10. package/src/acp-config.js +206 -0
  11. package/src/acp-session.js +954 -0
  12. package/src/activity-registry.js +110 -5
  13. package/src/agent-connections.js +293 -0
  14. package/src/agent-control/client.js +1616 -0
  15. package/src/agent-control/events.js +547 -0
  16. package/src/agent-control/local-connection.js +275 -0
  17. package/src/agent-control/mcp-server.js +545 -0
  18. package/src/anthropic-compatible-config.js +29 -4
  19. package/src/anthropic-compatible-session.js +15 -6
  20. package/src/anthropic-openai-shim.js +0 -1
  21. package/src/archive-continuation.js +164 -0
  22. package/src/assistant-response.js +24 -0
  23. package/src/auth-probes.js +120 -13
  24. package/src/background-shell-tracker.js +27 -0
  25. package/src/base-session.js +1203 -36
  26. package/src/bearer-recheck.js +49 -0
  27. package/src/billing-budget.js +19 -0
  28. package/src/billing-class.js +40 -7
  29. package/src/binary-provenance-trust.js +11 -5
  30. package/src/bound-client-policy.js +279 -0
  31. package/src/built-in-tools/bash-exec.js +46 -7
  32. package/src/built-in-tools/file-ops.js +69 -5
  33. package/src/built-in-tools/tool-transforms.js +1113 -13
  34. package/src/byok-compose-state.js +6 -9
  35. package/src/byok-credentials.js +2 -3
  36. package/src/byok-mcp-client.js +92 -7
  37. package/src/byok-mcp-config.js +628 -121
  38. package/src/byok-mcp-fleet.js +49 -7
  39. package/src/byok-mcp-oauth-store.js +18 -16
  40. package/src/byok-mcp-trust.js +3 -3
  41. package/src/byok-session.js +650 -175
  42. package/src/byok-tool-executor.js +2662 -26
  43. package/src/byok-tools.js +9 -2
  44. package/src/channels/chroxy-channel-server.js +2 -3
  45. package/src/checkpoint-manager.js +64 -46
  46. package/src/claude-channel-session.js +16 -10
  47. package/src/claude-model-catalog.js +131 -16
  48. package/src/claude-model-refresh.js +385 -0
  49. package/src/claude-model-request.js +103 -0
  50. package/src/claude-stream-parser.js +53 -3
  51. package/src/claude-tui/diagnostic-tail.js +83 -0
  52. package/src/claude-tui/form-driver.js +44 -7
  53. package/src/claude-tui/model-error.js +41 -0
  54. package/src/claude-tui/pty-driver.js +211 -88
  55. package/src/claude-tui/sanitize-question-payload.js +109 -0
  56. package/src/claude-tui/usage-limit.js +239 -0
  57. package/src/claude-tui-session.js +3513 -287
  58. package/src/claude-tui-tool-response.js +300 -0
  59. package/src/cli/agent-control-cmd.js +65 -0
  60. package/src/cli/config-cmd.js +4 -4
  61. package/src/cli/config-dir-cmd.js +234 -0
  62. package/src/cli/deploy-cmd.js +45 -10
  63. package/src/cli/doctor-cmd.js +7 -3
  64. package/src/cli/init-cmd.js +15 -16
  65. package/src/cli/providers-cmd.js +3 -3
  66. package/src/cli/schedule-cmd.js +68 -39
  67. package/src/cli/server-cmd.js +48 -1
  68. package/src/cli/service-cmd.js +33 -10
  69. package/src/cli/session-cmd.js +227 -74
  70. package/src/cli/shared.js +162 -11
  71. package/src/cli/tokens-cmd.js +4 -5
  72. package/src/cli/tunnel-cmd.js +255 -24
  73. package/src/cli/worktree-gc-cmd.js +2 -2
  74. package/src/cli-session.js +1066 -121
  75. package/src/cli.js +4 -0
  76. package/src/codex-app-server-client.js +36 -3
  77. package/src/codex-app-server-session.js +1454 -79
  78. package/src/codex-bundled-client.js +66 -0
  79. package/src/codex-model-catalog.js +548 -0
  80. package/src/codex-model-rejections.js +87 -0
  81. package/src/codex-native-resume.js +104 -0
  82. package/src/codex-protocol-capabilities.js +188 -0
  83. package/src/codex-session.js +450 -27
  84. package/src/config-dir-migration.js +444 -0
  85. package/src/config-dir.js +108 -0
  86. package/src/config.js +286 -26
  87. package/src/connection-authority.js +48 -0
  88. package/src/connection-info.js +5 -9
  89. package/src/connection-locality.js +60 -0
  90. package/src/container-liveness-monitor.js +189 -0
  91. package/src/continuation-metadata-worker.js +17 -0
  92. package/src/continuations.js +114 -0
  93. package/src/control-room/host-prune.js +5 -0
  94. package/src/control-room/integrations.js +7 -20
  95. package/src/control-room/skills-inventory.js +2 -2
  96. package/src/conversation-scanner.js +40 -18
  97. package/src/conversation-scope.js +59 -39
  98. package/src/conversation-search.js +24 -22
  99. package/src/credential-store.js +23 -19
  100. package/src/daemon-commit.js +92 -0
  101. package/src/daemon-idle-state.js +171 -0
  102. package/src/daemon-update-status.js +314 -0
  103. package/src/dashboard-build.js +70 -0
  104. package/src/declared-status.js +90 -0
  105. package/src/deepseek-credentials.js +2 -3
  106. package/src/dev-preview.js +169 -182
  107. package/src/device-preferences.js +2 -2
  108. package/src/diff-parser.js +87 -0
  109. package/src/discord-credentials.js +2 -3
  110. package/src/docker-byok-pool.js +3 -1
  111. package/src/docker-byok-session.js +678 -78
  112. package/src/docker-image-allowlist.js +23 -1
  113. package/src/docker-sdk-session.js +172 -3
  114. package/src/docker-session.js +284 -10
  115. package/src/doctor.js +767 -61
  116. package/src/edited-input.js +264 -0
  117. package/src/environment-manager.js +175 -36
  118. package/src/environments/authority.js +95 -0
  119. package/src/environments/backends/container-claude-spawn.js +94 -0
  120. package/src/environments/backends/docker.js +31 -10
  121. package/src/environments/backends/k8s.js +49 -24
  122. package/src/environments/destroy-with-sessions.js +142 -0
  123. package/src/event-ingest.js +118 -13
  124. package/src/event-normalizer.js +151 -233
  125. package/src/gemini-session.js +81 -5
  126. package/src/handler-utils.js +535 -68
  127. package/src/handlers/checkpoint-handlers.js +39 -4
  128. package/src/handlers/control-room-handlers.js +51 -11
  129. package/src/handlers/conversation-handlers.js +469 -56
  130. package/src/handlers/daemon-update-handlers.js +81 -0
  131. package/src/handlers/evaluator-handlers.js +14 -1
  132. package/src/handlers/feature-handlers.js +186 -69
  133. package/src/handlers/file-handlers.js +57 -13
  134. package/src/handlers/input-handlers.js +685 -48
  135. package/src/handlers/orchestration-handlers.js +3 -3
  136. package/src/handlers/scheduler-handlers.js +88 -14
  137. package/src/handlers/session-handlers.js +542 -20
  138. package/src/handlers/session-pr-status-handlers.js +283 -0
  139. package/src/handlers/session-pr-threads-handlers.js +247 -0
  140. package/src/handlers/settings-handlers.js +330 -42
  141. package/src/handlers/skills-handlers.js +13 -4
  142. package/src/handlers/summarize-handlers.js +32 -1
  143. package/src/handlers/survey-throttle.js +380 -0
  144. package/src/health-proof.js +40 -0
  145. package/src/history-page.js +104 -0
  146. package/src/http-routes.js +127 -8
  147. package/src/ide/search.js +24 -6
  148. package/src/ide/symbols.js +20 -6
  149. package/src/input-context.js +117 -0
  150. package/src/instruction-policy-compiler.js +229 -0
  151. package/src/instruction-policy.js +250 -0
  152. package/src/jsonl-reader.js +289 -82
  153. package/src/jsonl-subprocess-session.js +92 -8
  154. package/src/keychain.js +1 -1
  155. package/src/logger.js +63 -17
  156. package/src/mailbox-route.js +11 -22
  157. package/src/message-wire.js +386 -0
  158. package/src/model-discovery.js +43 -3
  159. package/src/models.js +1276 -174
  160. package/src/notification-prefs.js +12 -4
  161. package/src/notifications/discord-billing-sink.js +22 -5
  162. package/src/notifications/discord-ci-sink.js +243 -0
  163. package/src/notifications/discord-webhook-client.js +71 -0
  164. package/src/notifications/discord-webhook-sink.js +64 -23
  165. package/src/notifications/expo-push-sink.js +85 -6
  166. package/src/notifications/ready-body.js +16 -5
  167. package/src/ollama-session.js +34 -2
  168. package/src/orchestration/build-manager.js +9 -2
  169. package/src/orchestration/git-ops.js +41 -7
  170. package/src/orchestration/orchestration-manager.js +80 -33
  171. package/src/orchestration/permission-gate.js +13 -1
  172. package/src/orchestration/run-model.js +2 -1
  173. package/src/orchestration/turn-driver.js +44 -20
  174. package/src/orphan-reaper.js +413 -0
  175. package/src/outgoing-policy.js +183 -0
  176. package/src/pairing.js +92 -13
  177. package/src/path-hash-trust-ledger.js +642 -25
  178. package/src/permission-deadlines.js +82 -0
  179. package/src/permission-floor.js +1357 -42
  180. package/src/permission-hook.js +180 -69
  181. package/src/permission-manager.js +712 -83
  182. package/src/permission-mode-support.js +35 -0
  183. package/src/permission-resolver.js +122 -8
  184. package/src/permission-scope.js +43 -0
  185. package/src/platform.js +159 -43
  186. package/src/preview-ingress.js +54 -0
  187. package/src/preview-target.js +213 -0
  188. package/src/prompt-evaluator.js +34 -4
  189. package/src/provider-customization.js +180 -0
  190. package/src/providers.js +207 -4
  191. package/src/push.js +30 -4
  192. package/src/question-route-map.js +130 -0
  193. package/src/redaction.js +360 -8
  194. package/src/roster-broadcast.js +186 -0
  195. package/src/scheduled-task-store.js +318 -26
  196. package/src/scheduler.js +73 -3
  197. package/src/sdk-session.js +2060 -187
  198. package/src/server-cli/preview-shutdown.js +22 -0
  199. package/src/server-cli/push-notification-handler.js +11 -2
  200. package/src/server-cli/server-orchestrator.js +28 -5
  201. package/src/server-cli-child.js +33 -18
  202. package/src/server-cli.js +524 -38
  203. package/src/server-identity.js +15 -11
  204. package/src/service.js +396 -25
  205. package/src/session-archive-limits.js +15 -0
  206. package/src/session-archive.js +1029 -0
  207. package/src/session-busy-state.js +72 -0
  208. package/src/session-ci-watcher.js +926 -0
  209. package/src/session-context.js +7 -2
  210. package/src/session-manager.js +3491 -312
  211. package/src/session-message-history.js +722 -16
  212. package/src/session-pr-status.js +654 -0
  213. package/src/session-pr-threads.js +271 -0
  214. package/src/session-preset-trust.js +3 -3
  215. package/src/session-preset.js +10 -5
  216. package/src/session-state-persistence.js +94 -17
  217. package/src/session-timeout-manager.js +20 -0
  218. package/src/session-token-store.js +17 -8
  219. package/src/session-wake.js +240 -0
  220. package/src/shell-approval-info.js +2 -2
  221. package/src/shell-approval-store.js +3 -1
  222. package/src/skills-loader.js +7 -4
  223. package/src/skills-manager.js +2 -2
  224. package/src/skills-trust.js +95 -13
  225. package/src/skills-usage.js +2 -3
  226. package/src/snapshots-store.js +2 -3
  227. package/src/statusline.js +23 -11
  228. package/src/summarize-session.js +51 -4
  229. package/src/supervisor.js +22 -11
  230. package/src/sweep-stale-provider-dirs.js +95 -0
  231. package/src/thinking-level-wire.js +39 -0
  232. package/src/thinking-stream.js +179 -0
  233. package/src/tool-result.js +61 -0
  234. package/src/transcript-sources.js +109 -0
  235. package/src/transcript-tasks.js +372 -25
  236. package/src/trusted-file-read.js +302 -0
  237. package/src/tunnel/base.js +0 -8
  238. package/src/tunnel/cloudflare.js +34 -31
  239. package/src/tunnel/index.js +9 -0
  240. package/src/tunnel/preview.js +64 -0
  241. package/src/turn-outcome.js +137 -0
  242. package/src/usage-normalize.js +9 -5
  243. package/src/user-shell-session.js +59 -5
  244. package/src/utils/agent-sdk-version.js +107 -0
  245. package/src/utils/argv-safety.js +741 -0
  246. package/src/utils/auth-cause.js +60 -0
  247. package/src/utils/binary-package-manifest.js +597 -0
  248. package/src/utils/binary-version.js +224 -0
  249. package/src/utils/bounded-regex-worker.js +25 -0
  250. package/src/utils/bounded-regex.js +153 -0
  251. package/src/utils/claude-binary.js +43 -0
  252. package/src/utils/claude-config-dir.js +245 -0
  253. package/src/utils/claude-login-command.js +16 -0
  254. package/src/utils/claude-native-route.js +81 -0
  255. package/src/utils/componentwise-resolver.js +133 -37
  256. package/src/utils/deploy-control-files.js +87 -0
  257. package/src/utils/exec-failure-reason.js +21 -0
  258. package/src/utils/git-repo.js +42 -0
  259. package/src/utils/is-entry-point.js +137 -0
  260. package/src/utils/node-pty-probe.js +95 -0
  261. package/src/utils/node-pty-support.js +118 -0
  262. package/src/utils/opened-file-path.js +167 -0
  263. package/src/utils/path-containment.js +165 -0
  264. package/src/utils/permission-mode-sidecar.js +51 -0
  265. package/src/utils/preflight.js +360 -16
  266. package/src/utils/read-limiter.js +217 -0
  267. package/src/utils/regular-file.js +375 -0
  268. package/src/utils/safe-regex.js +113 -0
  269. package/src/utils/small-file.js +129 -0
  270. package/src/utils/spawn-env.js +189 -4
  271. package/src/utils/stale-session-dirs.js +182 -0
  272. package/src/utils/stat-identity.js +43 -0
  273. package/src/utils/verify-provenance.js +406 -13
  274. package/src/web-task-manager.js +256 -16
  275. package/src/worktree-gc.js +7 -2
  276. package/src/ws-auth.js +69 -21
  277. package/src/ws-broadcaster.js +14 -2
  278. package/src/ws-client-manager.js +16 -1
  279. package/src/ws-client-sender.js +7 -0
  280. package/src/ws-file-ops/browser.js +331 -58
  281. package/src/ws-file-ops/common.js +320 -14
  282. package/src/ws-file-ops/git.js +395 -42
  283. package/src/ws-file-ops/index.js +2 -0
  284. package/src/ws-file-ops/memory.js +137 -35
  285. package/src/ws-file-ops/open-nofollow.js +354 -0
  286. package/src/ws-file-ops/reader.js +571 -113
  287. package/src/ws-forwarding.js +329 -39
  288. package/src/ws-handler-context.js +70 -2
  289. package/src/ws-history.js +940 -172
  290. package/src/ws-message-handlers.js +17 -1
  291. package/src/ws-permissions.js +307 -37
  292. package/src/ws-schemas.js +5 -0
  293. package/src/ws-server.js +643 -96
  294. package/sidecar/node_modules/.package-lock.json +0 -29
  295. package/sidecar/node_modules/ws/LICENSE +0 -20
  296. package/sidecar/node_modules/ws/README.md +0 -548
  297. package/sidecar/node_modules/ws/browser.js +0 -8
  298. package/sidecar/node_modules/ws/index.js +0 -22
  299. package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
  300. package/sidecar/node_modules/ws/lib/constants.js +0 -19
  301. package/sidecar/node_modules/ws/lib/event-target.js +0 -292
  302. package/sidecar/node_modules/ws/lib/extension.js +0 -203
  303. package/sidecar/node_modules/ws/lib/limiter.js +0 -55
  304. package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
  305. package/sidecar/node_modules/ws/lib/receiver.js +0 -706
  306. package/sidecar/node_modules/ws/lib/sender.js +0 -602
  307. package/sidecar/node_modules/ws/lib/stream.js +0 -161
  308. package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
  309. package/sidecar/node_modules/ws/lib/validation.js +0 -152
  310. package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
  311. package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
  312. package/sidecar/node_modules/ws/package.json +0 -70
  313. package/sidecar/node_modules/ws/wrapper.mjs +0 -21
  314. package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
  315. package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
  316. package/src/dashboard-next/dist/index.html +0 -13
  317. package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
package/src/models.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { readFileSync, mkdirSync, watch as fsWatch } from 'fs'
2
- import { homedir } from 'os'
3
- import { basename, dirname, join } from 'path'
2
+ import { basename, dirname } from 'path'
3
+ import { MODEL_ENTRY_METADATA_KEYS, DEFAULT_PROVIDER } from '@chroxy/protocol'
4
4
  import { writeFileRestricted } from './platform.js'
5
5
  import { createLogger } from './logger.js'
6
+ import { configPath } from './config-dir.js'
6
7
  import {
7
8
  DEFAULT_CONTEXT_WINDOW,
8
9
  ONE_M_SUFFIX,
@@ -15,6 +16,10 @@ import {
15
16
 
16
17
  const log = createLogger('models')
17
18
 
19
+ // Chroxy's default for new Claude sessions; upstream defaults remain explicit
20
+ // picker choices and restored null overrides keep their original semantics.
21
+ export const CLAUDE_NEW_SESSION_DEFAULT_MODEL = 'claude-sonnet-5-5'
22
+
18
23
  // Claude model catalog (roster, pricing, context-window heuristic) moved to
19
24
  // claude-model-catalog.js (#6201 OCP) so this generic registry/overlay/cost
20
25
  // module no longer OWNS the Claude data — it consumes it. Re-exported under the
@@ -23,15 +28,26 @@ const log = createLogger('models')
23
28
  // drift-guard read the imported CLAUDE_PRICING_USD_PER_MTOK / resolvePricingKey.
24
29
  export { DEFAULT_CONTEXT_WINDOW, ONE_M_SUFFIX, resolveClaudeContextWindow, claudeDeriveId, FALLBACK_MODELS }
25
30
 
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']))
31
+ // fullIds chroxy disallows regardless of source (the Agent SDK's supportedModels()
32
+ // push, the disk cache, and a user models-overlay.json). Keyed on the FULL id (not a
33
+ // short alias) so a precise model is dropped without false-positiving an overlay/SDK
34
+ // entry that merely reuses the alias; the `[1m]` variant is matched too.
35
+ //
36
+ // The Set is EMPTY on purpose. #6219 banned claude-fable-5 as a preview; it is now GA
37
+ // (fleet doctrine skill-templates#236 scopes it to HIGH-tier orchestration with a
38
+ // spend ceiling — allowed, not banned), so it was removed from the ban. The plumbing
39
+ // (isDisallowedModelId + its call sites + the #6232 dangling-default guard) is retained
40
+ // for a future disallow — do NOT delete it as dead code.
41
+ export const DISALLOWED_MODEL_IDS = Object.freeze(new Set())
42
+
43
+ // Schema version stamped into every cache payload `saveCache()` writes (#7776
44
+ // re-review). A payload WITHOUT this marker was written by a build that still
45
+ // unioned the static seed into `activeModels` on every registry, so on a
46
+ // registry that REPLACES its seed the file holds rows the picker must no longer
47
+ // offer — see the one-time migration in `loadCache()`. Bump it only for a
48
+ // change that needs another such migration; the loader treats "marker >= this"
49
+ // as current and anything else as legacy.
50
+ export const MODELS_CACHE_SCHEMA_VERSION = 2
35
51
 
36
52
  /**
37
53
  * True when a model id resolves to a disallowed fullId, normalising the same id
@@ -144,9 +160,8 @@ export function computePromptCostUsd(usage, pricing) {
144
160
  const outputTokens = Number(usage.output_tokens) || 0
145
161
  const cacheReadTokens = Number(usage.cache_read_input_tokens) || 0
146
162
  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.
163
+ // Select rates for the whole prompt. A model may tier its base ID too
164
+ // (Haiku 5.5), so the pricing entry, rather than an ID suffix, decides.
150
165
  let rates = pricing
151
166
  if (pricing.longContext) {
152
167
  const totalInput = inputTokens + cacheReadTokens + cacheWriteTokens
@@ -163,8 +178,7 @@ export function computePromptCostUsd(usage, pricing) {
163
178
  }
164
179
 
165
180
  function getDefaultCachePath() {
166
- const configDir = process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
167
- return join(configDir, 'models-cache.json')
181
+ return configPath('models-cache.json')
168
182
  }
169
183
 
170
184
  /**
@@ -175,8 +189,7 @@ function getDefaultCachePath() {
175
189
  * the static table doesn't carry — all without a code change.
176
190
  */
177
191
  function getDefaultOverlayPath() {
178
- const configDir = process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
179
- return join(configDir, 'models.json')
192
+ return configPath('models.json')
180
193
  }
181
194
 
182
195
  /**
@@ -312,9 +325,8 @@ let providerOverlays = _bootOverlayResult.byProvider
312
325
  * @returns {string}
313
326
  */
314
327
  function getProviderCachePath(providerName) {
315
- const configDir = process.env.CHROXY_CONFIG_DIR || join(homedir(), '.chroxy')
316
328
  const safe = String(providerName).replace(/[^a-zA-Z0-9_-]/g, '_')
317
- return join(configDir, `models-cache.${safe}.json`)
329
+ return configPath(`models-cache.${safe}.json`)
318
330
  }
319
331
 
320
332
  /**
@@ -383,36 +395,6 @@ export function canonicalStringify(value) {
383
395
  return JSON.stringify(normalize(value, '', false))
384
396
  }
385
397
 
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
398
  /**
417
399
  * Derive a human-readable label from a stripped model ID.
418
400
  * E.g. "opus-4-5-20251101" → "Opus 4.5", "sonnet-4-20250514" → "Sonnet 4",
@@ -430,6 +412,81 @@ function humanizeModelId(id) {
430
412
  return oneM ? `${base} (1M)` : base
431
413
  }
432
414
 
415
+ /**
416
+ * Copy the optional `available_models` metadata (#7723) onto a registry entry,
417
+ * taking each key from the FIRST source that carries a usable value.
418
+ *
419
+ * The key roster is `MODEL_ENTRY_METADATA_KEYS` from `@chroxy/protocol` — the
420
+ * same list the wire schema declares — so a field added to the entry schema is
421
+ * carried by every construction site THAT CALLS THIS HELPER without a second
422
+ * list to keep in sync. That is not every entry literal in this file:
423
+ * `computeFallbackModels()` builds the overlay and base rows as bare
424
+ * `{id,label,fullId,contextWindow}` literals and does NOT route through here,
425
+ * because an overlay row's metadata (a `provenance: 'manual'` in particular)
426
+ * is a producer decision that belongs with the stamping work, not with this
427
+ * plumbing. Adding a roster key does NOT make those two literals carry it.
428
+ *
429
+ * Nothing is synthesized: a source that never supplies a key leaves the
430
+ * key ABSENT, so an entry with none of these fields stays byte-identical to
431
+ * what it was before this change (and to what older clients already parse).
432
+ *
433
+ * @param {Object} entry - mutated in place and returned
434
+ * @param {...(Object|null|undefined)} sources - highest precedence first
435
+ */
436
+ function withModelMetadata(entry, ...sources) {
437
+ for (const key of MODEL_ENTRY_METADATA_KEYS) {
438
+ for (const source of sources) {
439
+ const value = source?.[key]
440
+ if (value === undefined || value === null) continue
441
+ entry[key] = value
442
+ break
443
+ }
444
+ }
445
+ return entry
446
+ }
447
+
448
+ /**
449
+ * The caller-supplied context window from an `updateModels()` / cache entry,
450
+ * or `undefined` when it is absent or unusable (#7723).
451
+ *
452
+ * `undefined` (not `null`) so the caller can keep chaining with `??` — a
453
+ * provider that means "window unknown, never fabricate" says so through its
454
+ * own `getModelMetadata()`, which is consulted further down the chain.
455
+ */
456
+ function usableContextWindow(source) {
457
+ const cw = source?.contextWindow
458
+ return typeof cw === 'number' && Number.isFinite(cw) && cw > 0 ? cw : undefined
459
+ }
460
+
461
+ /**
462
+ * #7810 — validate the cache file's `learnedContextWindows` field on read.
463
+ * Each value must be the same shape `updateContextWindow` itself is willing
464
+ * to STORE into the map (a finite positive integer): this reader cannot
465
+ * trust that every byte on disk went through a well-behaved write path (a
466
+ * hand-edit, an older/corrupted build, a partial write), so it re-validates
467
+ * independently rather than passing the parsed value straight through — #7771
468
+ * found `updateContextWindow`'s OWN input guard admits NaN (`typeof NaN ===
469
+ * 'number'` and `NaN <= 0` is false, so the existing `contextWindow <= 0`
470
+ * check never fires for it), which is exactly the kind of value this map
471
+ * must not resurrect from disk. A missing/absent field (an old-format cache
472
+ * written before this key existed) and a non-object value both yield an
473
+ * empty map rather than throwing — loadCache() must keep working with the
474
+ * map absent.
475
+ *
476
+ * @param {unknown} raw - `parsed.learnedContextWindows` from a cache file.
477
+ * @returns {Map<string, number>}
478
+ */
479
+ function parseLearnedContextWindows(raw) {
480
+ const out = new Map()
481
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return out
482
+ for (const [fullId, value] of Object.entries(raw)) {
483
+ if (typeof fullId !== 'string' || fullId.length === 0) continue
484
+ if (typeof value !== 'number' || !Number.isInteger(value) || value <= 0) continue
485
+ out.set(fullId, value)
486
+ }
487
+ return out
488
+ }
489
+
433
490
  /**
434
491
  * Factory function that creates an isolated models registry.
435
492
  * Each instance has its own mutable state, preventing test pollution.
@@ -458,10 +515,28 @@ function humanizeModelId(id) {
458
515
  * `~/.chroxy/models-cache.json`. Non-Claude providers should supply a
459
516
  * provider-scoped path (e.g. `~/.chroxy/models-cache.codex.json`) so the
460
517
  * default Claude cache stays untouched by per-provider learn-loops (#4413).
518
+ * @param {boolean} [hooks.unionsStaticFallbacks] - Opt in to the #3075 union
519
+ * of this registry's STATIC seed on a NON-Claude registry: wherever a roster
520
+ * is learned from the provider — `updateModels()`, `loadCache()`, and
521
+ * `applyOverlay()`'s cache-warmed branch, all three via
522
+ * `unionableSeedRows()` (#7776) — seed rows that roster omitted are merged
523
+ * back. Default
524
+ * false off the Claude registry (#7761) — for a provider whose refresh IS
525
+ * its own roster the union means a retired model never disappears. Set it
526
+ * only where the seed is a RECOMMENDATION list rather than a roster claim
527
+ * (ollama: models worth pulling that this machine has not pulled yet).
528
+ * @param {boolean} [hooks.hasDiscoverySeam] - Whether this provider can ever
529
+ * RE-PUBLISH a roster (a static `refreshModels`, or an `updateModels` caller).
530
+ * Defaults to true, which is the #7761 behaviour: the refresh is the roster
531
+ * and it REPLACES the static seed. Pass false for a provider with no such
532
+ * seam (gemini, deepseek) — its cache can only ever be a snapshot of this
533
+ * repo's own static table, so the seed keeps unioning at all three sites and
534
+ * a statically-added row still reaches the picker on an install that already
535
+ * has a cache file.
461
536
  * @param {Map} [hooks.overlay] - User-extensible overlay (fullId → entry; see
462
537
  * loadModelsOverlayResult). Overlay entries SEED the registry like a
463
538
  * 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
539
+ * and survives loadCache(). The default Claude registry gets
465
540
  * the module-level `defaultOverlay`; pass `new Map()` to opt out.
466
541
  */
467
542
  export function createModelsRegistry(hooks = {}) {
@@ -473,6 +548,89 @@ export function createModelsRegistry(hooks = {}) {
473
548
  const cachePathFn = typeof hooks.cachePath === 'function' ? hooks.cachePath : getDefaultCachePath
474
549
  const getModelMetadataFn = typeof hooks.getModelMetadata === 'function' ? hooks.getModelMetadata : null
475
550
  const overlay = hooks.overlay instanceof Map ? hooks.overlay : new Map()
551
+ // ONE discriminator for every rule in this registry whose PREMISE is a fact
552
+ // about Claude rather than about "a model registry". Identity, not a name
553
+ // check — the roster IS the thing each rule was written against, and a
554
+ // provider that passes its own list is by construction not it.
555
+ //
556
+ // Claude partial-discovery reconciliation and `[1m]` synthesis use it.
557
+ // Other providers publish replacement rosters, including on cache load.
558
+ //
559
+ // - #7761 `updateModels()`'s #3075 union re-adds every static fallback row a
560
+ // refresh omitted. Its premise ("`supportedModels()` under-reports") is a
561
+ // Claude-SDK fact; against a provider whose catalogue IS the producer's
562
+ // own roster it silently converts REPLACE into UNION, so a model the
563
+ // provider retired never disappears.
564
+ // - #7747 the `<id>[1m]` variant synthesis mints a CLAUDE-CLI id convention.
565
+ // Nothing strips the suffix on a non-Claude send path, so the chip 400s at
566
+ // the provider the moment someone taps it.
567
+ const isClaudeRegistry = baseFallbackModels === FALLBACK_MODELS
568
+ // #7761 — the union is scoped to the STATIC seed, not to everything in
569
+ // `fallbackModels`: `computeFallbackModels()` also folds in operator OVERLAY
570
+ // rows, and an overlay entry is a deliberate user declaration ("this model
571
+ // exists, offer it") rather than a possibly-stale vendor table. Those keep
572
+ // riding the union on every registry — that is the `applyOverlay` → live-SDK
573
+ // re-merge contract (#5932 AC2).
574
+ const staticFallbackFullIds = new Set(baseFallbackModels.map((m) => m.fullId))
575
+ // #7777 — …and an overlay entry that OVERRIDES a static row is such a
576
+ // declaration too, which the id-set above cannot see on its own:
577
+ // `computeFallbackModels()` merges an override IN PLACE and keeps the base
578
+ // row's `fullId`, so the merged row is indistinguishable from the static it
579
+ // decorates and was dropped with it. That silently disabled the one
580
+ // documented escape hatch (`docs/guides/model-overlay.md`: "An existing id
581
+ // has its label / contextWindow / shortId overridden") for exactly the ids it
582
+ // exists for — an operator keeping a row the provider's refresh no longer
583
+ // reports — and made the row FLICKER for a connected client: present in the
584
+ // boot `applyModels(fallbackModels)` view, gone the moment the first refresh
585
+ // landed.
586
+ //
587
+ // So the declared ids are tracked separately from the static seed. This does
588
+ // NOT reopen #7761: that gate protects a provider-reported roster from THIS
589
+ // REPO'S hand-maintained table (`baseFallbackModels`), and this set is
590
+ // derived only from the operator's `models.json` — empty on every registry
591
+ // whose operator wrote no overlay, which is the whole production surface
592
+ // #7761 was filed about. `gpt-4o` comes back only when someone typed
593
+ // `gpt-4o` into their own overlay. #7747 stays closed the same way: the
594
+ // `[1m]` synthesis is gated on `isClaudeRegistry`, so an overlay-declared
595
+ // `gpt-4.1` cannot mint `gpt-4.1[1m]` on the codex registry.
596
+ //
597
+ // Recomputed by `computeFallbackModels` (construction + every
598
+ // `applyOverlay`), so removing the row from `models.json` removes the union
599
+ // pass with it.
600
+ //
601
+ // A MAP, not a Set (`.has()` reads the same either way), keyed fullId → the
602
+ // operator's own overlay entry. The union pass needs the entry itself: for an
603
+ // id the provider is NOT reporting, `providerMeta` is this repo's static
604
+ // table rather than a live value, and #5932's stated precedence — SDK live >
605
+ // overlay > static heuristic — puts the operator ahead of it. Reading the
606
+ // ENTRY (not the merged fallback row) keeps that precise: only fields the
607
+ // operator actually supplied win, so a bare `{provider: "codex"}`
608
+ // declaration still renders from the provider's metadata exactly as before.
609
+ let overlayDeclaredFullIds = new Map()
610
+ // …and one non-Claude provider OPTS BACK IN, because for it the seed is not
611
+ // a vendor roster at all: ollama's is a list of RECOMMENDED models to pull,
612
+ // so a machine with two models installed should still be offered the other
613
+ // three (#5421, pinned in ollama-tags.test.js). Explicit, because #7761's
614
+ // whole complaint is that the union was applied to registries whose premise
615
+ // it did not fit — and a silent default is how that happened.
616
+ //
617
+ // …and so does every provider that has NO DISCOVERY SEAM at all (#7776
618
+ // re-review). The gate's premise — "a non-Claude roster is what the provider
619
+ // itself reported" — needs something that reports. `GeminiSession` and
620
+ // `DeepSeekSession` declare no static `refreshModels`, nothing ever calls
621
+ // `updateModels` on their registries, and `models-cache.gemini.json` is
622
+ // therefore a snapshot of THIS REPO'S OWN static table plus learned context
623
+ // windows, not a provider claim. REPLACE against that file means a row added
624
+ // to `GEMINI_MODEL_METADATA` by a later release never reaches the picker on
625
+ // an install that has the file, because no refresh will ever re-publish it —
626
+ // while `GeminiSession.getAllowedModels()` still accepts it. Derived from the
627
+ // seam (`hasDiscoverySeam`, wired from `typeof ProviderClass.refreshModels
628
+ // === 'function'` at `getRegistryForProvider`), never from a list of provider
629
+ // names, so a provider that GAINS a seam flips automatically.
630
+ const hasDiscoverySeam = hooks.hasDiscoverySeam !== false
631
+ const unionsStaticFallbacks = isClaudeRegistry
632
+ || hooks.unionsStaticFallbacks === true
633
+ || !hasDiscoverySeam
476
634
  // #6381: the CURRENT overlay (swapped by applyOverlay on hot-reload), retained
477
635
  // so getOverlayPricing() reflects live edits. The fallback rows don't carry
478
636
  // pricing, so pricing is read from this map directly.
@@ -496,14 +654,34 @@ export function createModelsRegistry(hooks = {}) {
496
654
  const overlayRows = []
497
655
  const overriddenBase = []
498
656
  const baseByFullId = new Map(baseFallbackModels.map((m) => [m.fullId, m]))
657
+ // #7777 — every fullId this overlay declares, whatever it does with it:
658
+ // seeds a new row, overrides a static row's label/window/shortId, or names
659
+ // a static row while overriding nothing (a pricing-only entry). All three
660
+ // are the operator asserting "this model exists, offer it", which is what
661
+ // the union gate keys on. Rebuilt from scratch here rather than mutated, so
662
+ // a reload that DROPS an entry drops its union pass.
663
+ const declaredFullIds = new Map()
499
664
  for (const entry of overlayMap.values()) {
500
665
  // #6219 — an overlay must not reintroduce a disallowed model (e.g. fable).
666
+ // A skipped row declares nothing, so it is recorded after this guard.
501
667
  if (isDisallowedModelId(entry.shortId) || isDisallowedModelId(entry.fullId)) continue
668
+ declaredFullIds.set(entry.fullId, entry)
502
669
  const baseRow = baseByFullId.get(entry.fullId)
503
670
  if (baseRow) {
504
- // Override the base row's label/window from the overlay when supplied.
671
+ // Override the base row's label/window/shortId from the overlay when
672
+ // supplied. #7802 — SPREAD the base row first: `docs/guides/model-
673
+ // overlay.md` documents the overlay's reach on an existing id as
674
+ // exactly `label` / `contextWindow` / `shortId`, nothing else, so
675
+ // every OTHER key the base row carried (`reasoningLevels`,
676
+ // `defaultReasoningLevel`, `provenance`, and anything future
677
+ // `MODEL_ENTRY_METADATA_KEYS` growth adds) must survive an override
678
+ // untouched. A bare 4-key literal here silently dropped all of them —
679
+ // for `reasoningLevels` specifically, that disabled the
680
+ // `set_thinking_level` gate for a model the overlay only meant to
681
+ // relabel.
505
682
  if (entry.label !== undefined || entry.contextWindow !== undefined || entry.shortId !== undefined) {
506
683
  baseByFullId.set(entry.fullId, Object.freeze({
684
+ ...baseRow,
507
685
  id: entry.shortId ?? baseRow.id,
508
686
  label: entry.label ?? baseRow.label,
509
687
  fullId: baseRow.fullId,
@@ -522,6 +700,7 @@ export function createModelsRegistry(hooks = {}) {
522
700
  }
523
701
  // Preserve base order, then append overlay-only rows.
524
702
  for (const m of baseFallbackModels) overriddenBase.push(baseByFullId.get(m.fullId))
703
+ overlayDeclaredFullIds = declaredFullIds
525
704
  return overlayRows.length > 0 || overriddenBase.some((m, i) => m !== baseFallbackModels[i])
526
705
  ? Object.freeze([...overriddenBase, ...overlayRows])
527
706
  : baseFallbackModels
@@ -530,7 +709,249 @@ export function createModelsRegistry(hooks = {}) {
530
709
  // #5932: `let` (was const) so applyOverlay() can swap in a re-folded set.
531
710
  let fallbackModels = computeFallbackModels(overlay)
532
711
 
533
- let activeModels = fallbackModels
712
+ /**
713
+ * The rows of `fallbackModels` that may be UNIONED back into a roster this
714
+ * registry learned from the provider (a discovery refresh, or a cache file
715
+ * written by one).
716
+ *
717
+ * #7761 gated that union at `updateModels`; #7776 is the same union written a
718
+ * SECOND time at `loadCache`, and a third time as `applyOverlay`'s
719
+ * cache-warmed re-seed. Two copies of one rule disagreeing is this repo's
720
+ * "guard wired to only some of its callers" (#7262), and the gap was not
721
+ * cosmetic: `loadCache` runs for every non-Claude provider at construction
722
+ * (`getRegistryForProvider`), so the statics came back at boot and stayed
723
+ * until the first successful refresh — indefinitely when the probe never
724
+ * succeeds. One helper, three call sites, so a future change cannot fix one
725
+ * and miss the others.
726
+ *
727
+ * The scoping is the STATIC seed only: operator OVERLAY rows are a deliberate
728
+ * declaration and keep unioning on every registry (#5932 AC2) — including
729
+ * (#7777) an overlay row that OVERRIDES a static id, which shares that row's
730
+ * fullId and so needs `overlayDeclaredFullIds` to be told apart from the
731
+ * undeclared static beside it.
732
+ */
733
+ function unionableSeedRows() {
734
+ if (unionsStaticFallbacks) return fallbackModels
735
+ return fallbackModels.filter((m) => !staticFallbackFullIds.has(m.fullId) || overlayDeclaredFullIds.has(m.fullId))
736
+ }
737
+
738
+ /**
739
+ * The fullIds in the CURRENT roster that a PROVIDER put there — the `value`s
740
+ * of the last `updateModels()` refresh, or the rows the last `loadCache()`
741
+ * read off disk, in both cases taken BEFORE the seed union runs. Empty until
742
+ * one of those two happens (CLI-only / pre-init), and cleared by
743
+ * `resetModels()`.
744
+ *
745
+ * This is the provenance half of `isUnpersistableDeclaredRow()` below, and it
746
+ * is deliberately a record of HOW a row got into `activeModels` rather than a
747
+ * test on the id itself (#7799 round 2).
748
+ */
749
+ let providerReportedFullIds = new Set()
750
+ // #8967 — the subset of provider-reported ids a LIVE answer reported in this
751
+ // process. Unlike `providerReportedFullIds` it is never stamped by
752
+ // `loadCache`, so it tells a live observation from a cache-warmed one.
753
+ const liveReportedFullIds = new Set()
754
+ // #8967 — optional source of model ids live sessions are using right now.
755
+ let inUseModelsProvider = null
756
+ function inUseModelFullIds() {
757
+ const out = new Set()
758
+ if (!inUseModelsProvider) return out
759
+ try {
760
+ for (const id of inUseModelsProvider() || []) {
761
+ if (typeof id !== 'string' || !id) continue
762
+ out.add(toFullIdMap.get(id) ?? id)
763
+ }
764
+ } catch (err) {
765
+ log.warn(`in-use models provider threw (ignored): ${err?.message || err}`)
766
+ }
767
+ return out
768
+ }
769
+ // Resolve current declaration ownership structurally, including at load time
770
+ // before synthesis. Removing an override restores the static base's authority.
771
+ function declaringModelId(fullId) {
772
+ if (overlayDeclaredFullIds.has(fullId)) return fullId
773
+ if (isClaudeRegistry && fullId.endsWith(ONE_M_SUFFIX)) {
774
+ const base = fullId.slice(0, -ONE_M_SUFFIX.length)
775
+ if (overlayDeclaredFullIds.has(base)) return base
776
+ }
777
+ return null
778
+ }
779
+
780
+ /**
781
+ * True for a row that is in the roster ONLY because the operator's overlay
782
+ * declares its id — the union pass put it back, no provider reported it.
783
+ * Such a row must never be PERSISTED.
784
+ *
785
+ * #7799 review — `saveCache()` writes `activeModels` under the CURRENT schema
786
+ * marker, and `loadCache`'s one-time `migrateLegacyStaticSeed` pass can only
787
+ * clear a payload written by an older build — so a declaration-only row that
788
+ * reaches disk outlives the declaration that justified it: delete the entry
789
+ * from `models.json`, restart, and the row is served forever from a cache no
790
+ * code path can clean, with no declaration anywhere. That is #7761's exact
791
+ * failure mode ("a retired model reached available_models forever, in every
792
+ * process, with no path that could ever clear it") reached through the cache
793
+ * file instead of the seed.
794
+ *
795
+ * Nothing is lost by leaving it out: the row is fully reconstructible at
796
+ * boot, because `loadCache` runs the SAME union over `unionableSeedRows()`
797
+ * and re-adds it whenever the declaration is still there. The inverse fix —
798
+ * dropping declared ids on load — is wrong: it would also delete ids the
799
+ * provider genuinely still reports, which the undeclared-static filter would
800
+ * then refuse to re-add.
801
+ *
802
+ * #7799 ROUND 2 — the first cut of this keyed on IDENTITY (a static-seed id ∩
803
+ * a declared id) rather than on provenance, and both halves of that were
804
+ * wrong:
805
+ *
806
+ * - It withheld rows the provider REPORTED. An operator with a `pricing`-only
807
+ * entry for an id the binary still serves lost the ratchet-learned context
808
+ * window (`utils/context-window-learn.js` calls `saveCache()` explicitly
809
+ * "so a server restart doesn't lose the learned window") and the live label
810
+ * on EVERY restart, and lost the model outright the moment the entry was
811
+ * deleted — `unionableSeedRows()` then filters the undeclared static, so
812
+ * nothing re-added a model the binary genuinely serves.
813
+ * - It withheld NOTHING for an overlay-only id, the guide's own headline
814
+ * shape, because such an id is not in `staticFallbackFullIds`. Declare
815
+ * `gpt-5.5`, refresh, delete the entry, restart: `loadCache` keeps every
816
+ * well-formed non-Claude row, so the picker still offered it — the very
817
+ * leak the guard was written to close, and the thing the docs assert does
818
+ * not happen.
819
+ *
820
+ * Provenance covers both: a reported row keeps being persisted with whatever
821
+ * the provider (and the ratchet) taught it, and a declaration-only row is held
822
+ * out whether its id is in the static seed or not.
823
+ */
824
+ function isUnpersistableDeclaredRow(fullId) {
825
+ if (providerReportedFullIds.has(fullId)) return false
826
+ const declaration = declaringModelId(fullId)
827
+ return declaration !== null && !providerReportedFullIds.has(declaration)
828
+ }
829
+
830
+ /**
831
+ * True for a row that must never be broadcast carrying `provenance`, and
832
+ * the one place that strips it back off when a producer stamped it anyway.
833
+ *
834
+ * For a row that is genuinely part of this repo's own static seed (a
835
+ * `baseFallbackModels` entry the operator never named), `provenance:
836
+ * 'catalogued'` means "this repo's in-repo catalogue vouches for this
837
+ * row", which is true, and stays. For a row that is in the roster ONLY
838
+ * because the operator's overlay declares its fullId
839
+ * (`isUnpersistableDeclaredRow`), no source may make that claim — since
840
+ * #7802 keeps a static base row's own metadata alive under an overlay
841
+ * label/window override, a declared-only row can carry that base row's
842
+ * `provenance` stamp straight through (e.g. an overlay-declared override
843
+ * of a retired provider id). Stripping leaves it ABSENT rather than
844
+ * mislabeled; every OTHER metadata key (`reasoningLevels`, …) is
845
+ * unaffected.
846
+ *
847
+ * #7888 round 3 — this used to be re-implemented (or forgotten) at each of
848
+ * SIX places that could put a row into `activeModels`: the construction
849
+ * initializer, `updateModels`'s and `loadCache`'s union loops (each via a
850
+ * now-removed `unionRowMetadataSources` wrapper that stripped `provenance`
851
+ * from the `withModelMetadata` SOURCES instead of the built row — same
852
+ * outcome, different shape), `applyOverlay`'s cache-warmed and fully-cold
853
+ * branches, and `resetModels()`. Three rounds of review fixed those one at
854
+ * a time (#7806, then the cache-warmed branch, then the last three) — the
855
+ * whack-a-mole shape the round-3 task exists to end. Every one of those
856
+ * call sites now builds its array and hands it to `setActiveModels()`
857
+ * below, which maps every row through this function before it is ever
858
+ * assigned to `activeModels`; no call site maps through it directly
859
+ * anymore, so a future one cannot forget to.
860
+ */
861
+ function stripUnpersistableProvenance(row) {
862
+ if (row.provenance === undefined) return row
863
+ if (!isUnpersistableDeclaredRow(row.fullId)) return row
864
+ const { provenance: _provenance, ...rest } = row
865
+ return Object.freeze(rest)
866
+ }
867
+
868
+ // Authoritative contextWindow values observed from SDK `modelUsage`,
869
+ // keyed by fullId. These override the static resolveContextWindow()
870
+ // heuristic and must survive subsequent updateModels() refreshes
871
+ // (which otherwise rebuild every entry from the heuristic on every
872
+ // SDK session init). Cleared on resetModels(). Declared here, ahead of
873
+ // `setActiveModels`'s first call below, because `resolveDeclaredRowWindow`
874
+ // (which that call reaches through `setActiveModels`) closes over it — a
875
+ // `const`/`let` declared after that first call would still be in its
876
+ // temporal dead zone when the closure runs.
877
+ const contextWindowOverrides = new Map()
878
+
879
+ // #7810 — ratchet-learned contextWindow values for DECLARATION-ONLY rows: a
880
+ // fullId `isUnpersistableDeclaredRow()` excludes from `persistableModels()`
881
+ // because the operator's overlay, not a provider report, is its only
882
+ // justification for being in the roster. That row is rebuilt from the
883
+ // overlay + heuristic on every boot (`unionableSeedRows()`, in both
884
+ // `updateModels()` and `loadCache()`), which otherwise throws away a
885
+ // window a live turn actually measured. Persisted under its OWN cache key
886
+ // (`saveCacheImpl`), separate from `models`, so the row itself still
887
+ // cannot outlive its declaration (`isUnpersistableDeclaredRow` is
888
+ // unaffected) while the measured window survives a restart. Keyed by
889
+ // fullId; `let` so `loadCache()` can replace it wholesale, the same way it
890
+ // replaces `providerReportedFullIds`. Cleared on resetModels(). Same
891
+ // TDZ reason as `contextWindowOverrides` above for living ahead of
892
+ // `setActiveModels`'s first call.
893
+ let learnedContextWindows = new Map()
894
+
895
+ /**
896
+ * #7810 round 2 — the ONE place a declaration-only row's contextWindow is
897
+ * resolved to the precedence this feature documents: live override >
898
+ * operator-declared > learned > heuristic. Folded into `setActiveModels`
899
+ * (below) rather than left at each call site that can hand it a
900
+ * declaration-only row, for the same reason #7888 round 3 made
901
+ * `setActiveModels` the only place `activeModels` is assigned at all: a
902
+ * rule copied to N call sites is a rule N-1 of them can drift from.
903
+ *
904
+ * Round 1 of THIS review (`withLiveOrLearnedWindow`, since removed) copied
905
+ * the rule to two of `applyOverlay`'s branches and got the coverage right,
906
+ * but not the precedence: it returned a declaration-only row UNCHANGED
907
+ * whenever the operator had pinned an explicit `contextWindow`, which
908
+ * skips the live override too, not just the learned map — inverting the
909
+ * documented order. Reachable in production: a live turn ratchets a
910
+ * declaration-only row via `updateContextWindow`, then `reloadModelsOverlay`
911
+ * fires (e.g. an unrelated edit to `~/.chroxy/models.json`) against an
912
+ * overlay entry that pins that SAME id — the pin silently overwrote the
913
+ * more-recent live measurement for the rest of the process, no restart
914
+ * required. Verified against the pre-round-2 code: declare `my-model`
915
+ * unpinned, ratchet it to 272000 live, then hot-reload an overlay that
916
+ * pins it to 50000 — the roster read back 50000, not 272000.
917
+ *
918
+ * The `??` chain here has no such special case: `contextWindowOverrides`
919
+ * is consulted UNCONDITIONALLY first, exactly like the (already-correct)
920
+ * `updateModels()` union-loop chain did before this round removed its now-
921
+ * redundant copy. A row that is not declaration-only is returned
922
+ * unchanged — a provider-reported row's override handling lives inline
923
+ * where that row is built (the main `updateModels()` conversion loop),
924
+ * unrelated to this map.
925
+ */
926
+ function resolveDeclaredRowWindow(row) {
927
+ if (!isUnpersistableDeclaredRow(row.fullId)) return row
928
+ const resolved = contextWindowOverrides.get(row.fullId)
929
+ ?? overlayDeclaredFullIds.get(row.fullId)?.contextWindow
930
+ ?? learnedContextWindows.get(row.fullId)
931
+ ?? row.contextWindow
932
+ if (resolved === undefined || resolved === row.contextWindow) return row
933
+ return { ...row, contextWindow: resolved }
934
+ }
935
+
936
+ /**
937
+ * The ONLY assignment to `activeModels` (`updateContextWindow` included —
938
+ * see below). Every row that becomes part of the active roster passes
939
+ * through `stripUnpersistableProvenance` and `resolveDeclaredRowWindow`
940
+ * here, once each, so neither invariant can be bypassed by a call site
941
+ * that builds a models array correctly in every other respect but forgets
942
+ * one of these two steps — the defect shape all three rounds of #7888
943
+ * review found, and #7810 round 2 reopened one level down for the window
944
+ * value specifically. Idempotent on a row that doesn't need adjusting, so
945
+ * callers may pass an array that is already a mix of previously-active
946
+ * rows (`updateContextWindow`) and freshly-built ones (`applyOverlay`'s
947
+ * cache-warmed seed) without sorting them first.
948
+ */
949
+ function setActiveModels(models) {
950
+ activeModels = models.map((m) => resolveDeclaredRowWindow(stripUnpersistableProvenance(m)))
951
+ }
952
+
953
+ let activeModels
954
+ setActiveModels(fallbackModels)
534
955
  let defaultModelId = null
535
956
  let allowedModelIds = new Set()
536
957
  let toFullIdMap = new Map()
@@ -549,12 +970,6 @@ export function createModelsRegistry(hooks = {}) {
549
970
  // Snapshot of the last saved cache payload so saveCache() can skip
550
971
  // redundant writes. `null` forces the first save to always run.
551
972
  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
973
 
559
974
  // #4106: warn-once set for synthesized 1M variants that lack a matching
560
975
  // pricing entry. updateModels() can be called repeatedly across the
@@ -595,7 +1010,10 @@ export function createModelsRegistry(hooks = {}) {
595
1010
  const filtered = models.some((m) => isDisallowedModelId(m.id) || isDisallowedModelId(m.fullId))
596
1011
  ? models.filter((m) => !isDisallowedModelId(m.id) && !isDisallowedModelId(m.fullId))
597
1012
  : models
598
- activeModels = filtered
1013
+ // #7888 round 3 — the chokepoint: every write to `activeModels` this
1014
+ // registry makes (except `updateContextWindow`'s in-place window update,
1015
+ // which routes through the same function) funnels through here.
1016
+ setActiveModels(filtered)
599
1017
  // #6219 review (#6232): never leave defaultModelId pointing at a model that
600
1018
  // isn't in the active list — e.g. the SDK marked the now-filtered disallowed
601
1019
  // model (fable) as "Default", so nextDefault is its short id which isn't in
@@ -604,6 +1022,12 @@ export function createModelsRegistry(hooks = {}) {
604
1022
  // (opus → sonnet) else the first model (mirrors updateModels' fallback). Only
605
1023
  // fires when filtering actually dropped the chosen default — a present
606
1024
  // nextDefault (the common case + loadCache's own discard result) is kept.
1025
+ // Reads `filtered`, not `activeModels` — stripping `provenance` never
1026
+ // touches `id`/`fullId`, so the two are equivalent for this lookup, and
1027
+ // `filtered` is already in hand.
1028
+ if (isClaudeRegistry) {
1029
+ nextDefault = filtered.find(m => m.fullId === CLAUDE_NEW_SESSION_DEFAULT_MODEL)?.id ?? null
1030
+ }
607
1031
  const defaultPresent =
608
1032
  nextDefault != null && filtered.some((m) => m.id === nextDefault || m.fullId === nextDefault)
609
1033
  if (nextDefault != null && !defaultPresent) {
@@ -612,17 +1036,77 @@ export function createModelsRegistry(hooks = {}) {
612
1036
  } else {
613
1037
  defaultModelId = nextDefault
614
1038
  }
615
- rebuildLookups(filtered)
1039
+ // Rebuilds from `activeModels` (the post-strip list) rather than
1040
+ // `filtered` so the lookup tables always mirror exactly what
1041
+ // `getModels()` serves, not a pre-chokepoint snapshot of it.
1042
+ rebuildLookups(activeModels)
616
1043
  }
617
1044
 
618
- function snapshotString() {
619
- return canonicalStringify({ models: activeModels, defaultModelId })
1045
+ /**
1046
+ * The rows `saveCacheImpl` actually writes — `activeModels` minus the ones
1047
+ * that are in the roster ONLY because the operator declared them
1048
+ * (`isUnpersistableDeclaredRow`).
1049
+ *
1050
+ * #7799 round 3 — this exists so the write-skip key and the payload are the
1051
+ * SAME list. Round 2 filtered the payload but kept hashing `activeModels`,
1052
+ * and the filter reads a second input (`providerReportedFullIds`) that moves
1053
+ * WITHOUT `activeModels` moving: warm the cache from a disk file that lacks a
1054
+ * declared id, let the union re-add it, then let the binary come back and
1055
+ * REPORT it with the same rendering in the same array position. The roster is
1056
+ * byte-identical, so `saveCacheImpl` returned `true` without writing — a
1057
+ * success report for work not done — and the now-provider-reported row stayed
1058
+ * off disk. Delete the entry ("it was only a re-price") and restart with the
1059
+ * binary unreachable and the model it serves is gone from the picker, which is
1060
+ * the very harm the withholding guard was written to prevent, reached from the
1061
+ * other side.
1062
+ */
1063
+ function persistableModels() {
1064
+ // #8967: `offered` is a runtime-only marker; it never reaches the cache.
1065
+ return activeModels
1066
+ .filter((m) => !isUnpersistableDeclaredRow(m.fullId))
1067
+ .map(({ offered: _offered, ...row }) => row)
1068
+ }
1069
+
1070
+ /**
1071
+ * #7810 — learned entries whose direct declaration or synthesized-variant
1072
+ * base the overlay no longer declares are pruned here, so the map
1073
+ * cannot grow without bound across overlay edits and a deleted
1074
+ * declaration's learned window cannot resurrect the row it belonged to
1075
+ * (the same invariant `isUnpersistableDeclaredRow` upholds for the row
1076
+ * itself — see that function). Called from `saveCacheImpl` (so the prune
1077
+ * actually reaches disk) and from `loadCache` (so a file saved before the
1078
+ * declaration was removed doesn't reintroduce a stale entry in memory).
1079
+ */
1080
+ function prunedLearnedContextWindows() {
1081
+ for (const fullId of learnedContextWindows.keys()) {
1082
+ if (declaringModelId(fullId) === null) {
1083
+ learnedContextWindows.delete(fullId)
1084
+ // A measured declaration-only window must not survive removal through
1085
+ // the live ratchet map and reappear if the same declaration is re-added.
1086
+ if (!providerReportedFullIds.has(fullId)) contextWindowOverrides.delete(fullId)
1087
+ }
1088
+ }
1089
+ return learnedContextWindows
1090
+ }
1091
+
1092
+ // Takes the lists so `saveCacheImpl` can hash the exact payload it writes.
1093
+ // #7810 — `learned` is part of the hash, not an afterthought: a ratchet on
1094
+ // a declaration-only row never changes `persistableModels()` (the row is
1095
+ // excluded from it by definition), so hashing `models`/`defaultModelId`
1096
+ // alone would make a save that ONLY updates the learned window compare
1097
+ // equal to the last save and get skipped by the `snapshot ===
1098
+ // lastSavedSnapshot` short-circuit below — the exact write-skip-key gap
1099
+ // #7799 round 3 found for `providerReportedFullIds`, reopened for this map.
1100
+ function snapshotString(models = persistableModels(), learned = prunedLearnedContextWindows()) {
1101
+ return canonicalStringify({ models, defaultModelId, learnedContextWindows: Object.fromEntries(learned) })
620
1102
  }
621
1103
 
622
1104
  // Hoisted out of the returned method so loadCache() can heal the disk
623
1105
  // file in the same pass when stale entries are pruned (#3162).
624
1106
  function saveCacheImpl(path) {
625
- const snapshot = snapshotString()
1107
+ const persistable = persistableModels()
1108
+ const learned = prunedLearnedContextWindows()
1109
+ const snapshot = snapshotString(persistable, learned)
626
1110
  if (snapshot === lastSavedSnapshot) return true
627
1111
 
628
1112
  try {
@@ -636,7 +1120,28 @@ export function createModelsRegistry(hooks = {}) {
636
1120
  // host. writeFileRestricted handles atomic rename + cleanup
637
1121
  // internally; no manual rename/unlink wrapper is needed here.
638
1122
  writeFileRestricted(path, JSON.stringify({
639
- models: activeModels,
1123
+ // #7776 re-review: the schema marker is what tells the next `loadCache`
1124
+ // this payload was written by a build whose `activeModels` no longer
1125
+ // carries the unioned static seed. Written on every registry (the
1126
+ // Claude loader ignores it) so there is exactly one save path.
1127
+ v: MODELS_CACHE_SCHEMA_VERSION,
1128
+ // …and the rows that are here ONLY because the operator declared them
1129
+ // are held OUT of that payload for the same reason the marker exists
1130
+ // (#7799 review — see `isUnpersistableDeclaredRow`): a declaration is
1131
+ // live operator state, and persisting a row that only exists because of
1132
+ // it is how the row outlives the declaration. A row the PROVIDER
1133
+ // reported is persisted as it always was, learned context window
1134
+ // included, whether or not an overlay entry also names its id.
1135
+ //
1136
+ // This is the same array the write-skip key above hashed (#7799 round
1137
+ // 3) — computed once, so the key cannot describe a different payload.
1138
+ models: persistable,
1139
+ // #7810 — ratchet-learned windows for the rows `models` just excluded.
1140
+ // Own key, separate from `models`, so the row itself stays out of the
1141
+ // roster payload (it must still not outlive its declaration) while
1142
+ // the measured window survives a restart. Same pruned map the
1143
+ // write-skip key hashed, converted to a plain object for JSON.
1144
+ learnedContextWindows: Object.fromEntries(learned),
640
1145
  defaultModelId,
641
1146
  savedAt: Date.now(),
642
1147
  }, null, 2), { tmpSuffix: `.tmp-${process.pid}` })
@@ -652,7 +1157,7 @@ export function createModelsRegistry(hooks = {}) {
652
1157
  }
653
1158
  }
654
1159
 
655
- rebuildLookups(fallbackModels)
1160
+ applyModels(fallbackModels, null)
656
1161
 
657
1162
  // #5932: captured in a const so applyOverlay() can re-run the full
658
1163
  // updateModels() pipeline against a re-folded fallback set. Methods reference
@@ -678,27 +1183,85 @@ export function createModelsRegistry(hooks = {}) {
678
1183
  const map = newOverlay instanceof Map ? newOverlay : new Map()
679
1184
  currentOverlay = map // #6381: keep getOverlayPricing in sync with reloads
680
1185
  fallbackModels = computeFallbackModels(map)
1186
+ prunedLearnedContextWindows()
681
1187
  if (lastSdkModels) {
682
1188
  registry.updateModels(lastSdkModels)
683
1189
  } 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
1190
+ // Cache-warmed (loadCache) but no SDK refresh yet. PRESERVE every
1191
+ // cache entry (date-suffixed ids past the family filter, e.g.
1192
+ // `claude-sonnet-4-20250514`, AND — #7808 — any id the cache shares
1193
+ // with the re-folded fallback) and let the new fallback (base +
1194
+ // overlay overrides + overlay-only rows) contribute only the ids the
1195
+ // cache does NOT already carry. Preserve from the CACHE list, not
1196
+ // `activeModels`, so an overlay-only row the operator REMOVED still
1197
+ // drops (it lives in fallbackModels, never lastCacheModels).
1198
+ //
1199
+ // #7808 — the cache row must win outright for a shared fullId, not
1200
+ // merely by presence: `lastCacheModels` is what the provider itself
1201
+ // last reported (`loadCache` stamps `providerReportedFullIds` from
1202
+ // it), so a model the binary still serves must not have its live
1203
+ // label/window overwritten by an overlay decoration just because a
1204
+ // hot reload landed before the next refresh — the same precedence
1205
+ // `updateModels`/`loadCache` already hold, where a reported row is
1206
+ // never touched by the overlay at all (`docs/guides/model-
1207
+ // overlay.md`: "Where the provider does still report the model, its
1208
+ // own values win"). Before this fix the seed (which — #7777 — can
1209
+ // carry the OPERATOR's decoration for an id it overrides) was spread
1210
+ // first, so it won the collision and that decorated copy could reach
1211
+ // `saveCache()`.
1212
+ //
1213
+ // #7776 — the seed half of that list is the #3075 union's THIRD copy,
1214
+ // so it reads `unionableSeedRows()` like the other two: on a non-Claude
1215
+ // registry an overlay reload must not put back the statics that
1216
+ // `loadCache`/`updateModels` just declined to. Its contribution here is
1217
+ // now scoped the same way that union scopes its OWN additions: only ids
1218
+ // the reported roster (the cache, in this window) does not carry.
1219
+ //
1220
+ // #7806 (missed site) — an id only here because the operator declared
1221
+ // it must not go out `provenance: 'catalogued'` just because this
1222
+ // union pushes the built `fallbackModels` row straight through
1223
+ // instead of routing it via `withModelMetadata`. #7888 round 3 — no
1224
+ // longer stripped here: `applyModels` → `setActiveModels` strips
1225
+ // `provenance` from every row in `next` (cache-preserved rows
1226
+ // included — a no-op for them, since they're provider-reported)
1227
+ // before it is ever assigned to `activeModels`, so this array can be
1228
+ // built without worrying about which half needs it.
1229
+ const seed = unionableSeedRows()
1230
+ const cacheFullIds = new Set(lastCacheModels.map((m) => m.fullId))
1231
+ const seedOnly = seed.filter((m) => !cacheFullIds.has(m.fullId))
1232
+ const next = seedOnly.length > 0 ? Object.freeze([...lastCacheModels, ...seedOnly]) : lastCacheModels
1233
+ // #7810 round 2 — no per-site restoration call needed here any more:
1234
+ // `applyModels` → `setActiveModels` → `resolveDeclaredRowWindow` now
1235
+ // applies the live-override/learned-window precedence to every row
1236
+ // this branch hands it (cache-preserved rows included — a no-op for
1237
+ // them, since they're provider-reported), the same way `applyModels`
1238
+ // already strips `provenance` unconditionally.
695
1239
  applyModels(next, defaultModelId)
696
1240
  } else {
1241
+ // #7888 re-review — the fully-cold reload (no SDK data, no cache
1242
+ // warmed yet: first boot before `loadCache()` ever succeeds, or a
1243
+ // hot-reload racing the first refresh). Same construction-time gap as
1244
+ // the `activeModels` initializer: `fallbackModels` can carry a
1245
+ // declared-only override's stray `provenance` straight from the base
1246
+ // row it overrides, and this branch has no union to route it
1247
+ // through. #7888 round 3 — `applyModels` strips it now; no per-site
1248
+ // map needed here either.
1249
+ // #7810 round 2 — same reasoning for the window: `applyModels` now
1250
+ // restores it too, so `fallbackModels` can go straight through here
1251
+ // exactly like `provenance` does.
697
1252
  applyModels(fallbackModels, defaultModelId)
698
1253
  }
699
1254
  return activeModels
700
1255
  },
701
1256
 
1257
+ /**
1258
+ * #8967 — register a function returning the model ids live sessions are
1259
+ * using; a cache-only row among them survives a live refresh.
1260
+ */
1261
+ setInUseModelsProvider(fn) {
1262
+ inUseModelsProvider = typeof fn === 'function' ? fn : null
1263
+ },
1264
+
702
1265
  updateModels(sdkModels) {
703
1266
  if (!Array.isArray(sdkModels)) {
704
1267
  log.debug(`updateModels: ignoring non-array input (got ${sdkModels === null ? 'null' : typeof sdkModels})`)
@@ -736,16 +1299,36 @@ export function createModelsRegistry(hooks = {}) {
736
1299
  const match = label.match(/^Default\s*\((.+)\)$/)
737
1300
  if (match) label = match[1]
738
1301
  }
1302
+ if (fullId === 'default' && (!label || /^(?:default|recommended)$/i.test(label))) label = 'Provider default'
739
1303
  if (!label || /^recommended$/i.test(label)) {
740
1304
  label = providerMeta?.label || humanizeModelId(derivedId)
741
1305
  }
742
1306
  // Prefer an authoritative value observed from SDK modelUsage
743
1307
  // over the static heuristic, so a learned contextWindow isn't
744
1308
  // lost when _fetchSupportedModels() fires on every init.
1309
+ //
1310
+ // #7723 — the CALLER's `contextWindow` sits directly below the
1311
+ // learned override and ABOVE the provider's static table: it is
1312
+ // what the provider reported for this id on THIS refresh (live
1313
+ // discovery), so it beats a hand-maintained table row and the
1314
+ // heuristic.
1315
+ //
1316
+ // This is a PRECEDENCE CLARIFICATION, not a repair of a dropped
1317
+ // window on the live path: `refreshDiscoveredModels()` publishes
1318
+ // the catalogue through `applyCatalog` BEFORE it calls updateModels
1319
+ // (model-discovery.js), so the discovered window already reached
1320
+ // this chain one slot below, as `providerMeta.contextWindow`. What
1321
+ // the caller's key now additionally carries is (a) a window that
1322
+ // sink refuses — `applyCatalog` stores only `Number.isInteger`
1323
+ // values, so a fractional one became null and fell through to the
1324
+ // 200k default — and (b) any caller with no provider metadata hook
1325
+ // at all, which is the shape the follow-on stamping producers and
1326
+ // the cache-reload path feed.
745
1327
  const contextWindow = contextWindowOverrides.get(fullId)
1328
+ ?? usableContextWindow(m)
746
1329
  ?? providerMeta?.contextWindow
747
1330
  ?? resolveContextWindowFn(fullId)
748
- return { id: derivedId, label, fullId, contextWindow }
1331
+ return withModelMetadata({ id: derivedId, label, fullId, contextWindow }, m, providerMeta)
749
1332
  })
750
1333
 
751
1334
  if (droppedCount > 0) {
@@ -768,24 +1351,119 @@ export function createModelsRegistry(hooks = {}) {
768
1351
  return converted
769
1352
  }
770
1353
 
1354
+ // #8260: Claude supportedModels() is a partial observation on EACH
1355
+ // session init, not a retirement signal. Keep previously reported targets
1356
+ // (including the cache-warmed boot), with fresh metadata winning by value.
1357
+ // Overlay-only rows are excluded: removing an operator declaration must
1358
+ // still remove that row. Other providers retain replacement semantics.
1359
+ //
1360
+ // #8967 — but a SUCCESSFUL live answer is authoritative over the disk
1361
+ // cache. Only rows a live answer reported earlier in THIS process
1362
+ // (`liveReportedFullIds`) ride out a partial observation; a row that is
1363
+ // only here because `loadCache` warmed it is dropped unless a live
1364
+ // session is still using it, in which case it stays selectable, marked
1365
+ // `offered: false`. Live rows lead, in the live answer's order.
1366
+ const fresh = new Map(converted.map(m => [m.fullId, m]))
1367
+ const reported = new Map(fresh)
1368
+ if (isClaudeRegistry) {
1369
+ const inUse = inUseModelFullIds()
1370
+ for (const m of activeModels) {
1371
+ // (holds for cache rows too: `loadCache` stamps them into providerReportedFullIds)
1372
+ if (fresh.has(m.fullId) || !providerReportedFullIds.has(m.fullId)) continue
1373
+ if (liveReportedFullIds.has(m.fullId)) {
1374
+ reported.set(m.fullId, m)
1375
+ } else if (inUse.has(m.fullId)) {
1376
+ reported.set(m.fullId, { ...m, offered: false })
1377
+ }
1378
+ }
1379
+ for (const fullId of fresh.keys()) liveReportedFullIds.add(fullId)
1380
+ }
1381
+ converted.splice(0, converted.length, ...reported.values())
1382
+
771
1383
  // Merge fallback entries that the SDK omitted so the picker stays
772
1384
  // useful when the CLI under-reports (#3075 — observed on Opus 4.7,
773
1385
  // where supportedModels() returned only the 4.6 family). Match on
774
1386
  // fullId — fallback's id is a short alias (e.g. `opus`) that would
775
1387
  // otherwise collide with a derived id of the same family.
1388
+ //
1389
+ // #7761 — the STATIC seed rides this union on the Claude registry, and
1390
+ // on a non-Claude one only where the provider opts in
1391
+ // (`unionsStaticFallbacks`). "supportedModels() under-reports" is a fact
1392
+ // about the Claude CLI; a provider whose `model/list` IS its own roster
1393
+ // does not under-report, and unioning its hand-maintained table back in
1394
+ // meant a retired model (`gpt-4o`, `o1`, …) reached `available_models`
1395
+ // forever, in every process, with no path that could ever clear it —
1396
+ // REPLACE held at `CodexSession.getFallbackModels()` and nowhere a client
1397
+ // could see. Operator overlay rows are NOT part of the seed and keep
1398
+ // unioning everywhere (see `staticFallbackFullIds`).
1399
+ //
1400
+ // That rationale ("a vendor table this repo hand-maintains") is the
1401
+ // codex/gemini one and is NOT why the config-driven family —
1402
+ // anthropicCompatible / openaiCompatible — replaces. Their seed is the
1403
+ // operator's own `models:` array, which is user input rather than a
1404
+ // possibly-stale table. REPLACE is still right there for a different
1405
+ // reason: a discovered catalogue already supersedes `models:` as the
1406
+ // validation allowlist, so keeping the two in sync at the picker is the
1407
+ // consistent answer, not an override of the operator. An operator who
1408
+ // wants a row that discovery does not report declares it in the model
1409
+ // OVERLAY — including by OVERRIDING an id already in the static seed,
1410
+ // which `computeFallbackModels` merges in place under the base row's own
1411
+ // fullId. That shape used to be dropped with the static it decorated
1412
+ // (#7777); `unionableSeedRows()` now reads `overlayDeclaredFullIds`, so
1413
+ // the row survives the gate — and (#7799 review) so do the operator's own
1414
+ // `label` / `contextWindow` / `shortId`, which is the whole of what
1415
+ // `docs/guides/model-overlay.md` promises. Membership alone would have
1416
+ // been a half fix: on every shipping non-Claude provider
1417
+ // (`getModelMetadata` is defined by codex, gemini, deepseek, ollama,
1418
+ // anthropic-compatible and acp) `providerMeta` used to win all three
1419
+ // back, so the row came back renamed and re-windowed from this repo's own
1420
+ // static table.
776
1421
  const seenFullIds = new Set(converted.map(m => m.fullId))
777
- for (const fb of fallbackModels) {
1422
+ // #7799 round 2 — provenance, recorded BEFORE the union adds to it: these
1423
+ // are the ids the provider itself reported, and they stay persistable
1424
+ // however the overlay decorates them (`isUnpersistableDeclaredRow`).
1425
+ providerReportedFullIds = new Set(seenFullIds)
1426
+ for (const fb of unionableSeedRows()) {
778
1427
  if (!seenFullIds.has(fb.fullId)) {
779
1428
  // Re-derive the short id with the registry's hook so non-Claude
780
1429
  // providers don't accidentally inherit Claude's `claude-` strip.
1430
+ //
1431
+ // The OPERATOR's entry outranks `providerMeta` here and only here:
1432
+ // this branch runs precisely when the provider did NOT report the id,
1433
+ // so `providerMeta` is the static table rather than a live answer, and
1434
+ // #5932's precedence (SDK live > overlay > static heuristic) has the
1435
+ // overlay ahead of it. Fields the operator did not supply are
1436
+ // `undefined` and fall straight through, so a bare declaration renders
1437
+ // exactly as it did.
1438
+ //
1439
+ // #7810 round 2 — this row's `contextWindow` only needs to reach the
1440
+ // operator-declared/heuristic tier here: `declared?.contextWindow`
1441
+ // falling through to the static/heuristic fallback. A live override
1442
+ // and a ratchet-learned value both outrank that, but neither is
1443
+ // read here any more — `applyModels` → `setActiveModels` →
1444
+ // `resolveDeclaredRowWindow` applies that full precedence (live
1445
+ // override > operator-declared > learned > heuristic) to every
1446
+ // declaration-only row on its way into `activeModels`, once, so
1447
+ // this construction site only has to get its OWN tier right.
1448
+ const declared = overlayDeclaredFullIds.get(fb.fullId)
781
1449
  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)
1450
+ const id = declared?.shortId ?? providerMeta?.id ?? deriveIdFn(fb.fullId)
1451
+ const label = declared?.label || providerMeta?.label || humanizeModelId(id)
1452
+ const contextWindow = declared?.contextWindow
785
1453
  ?? providerMeta?.contextWindow
786
1454
  ?? fb.contextWindow
787
1455
  ?? resolveContextWindowFn(fb.fullId)
788
- converted.push({ id, label, fullId: fb.fullId, contextWindow })
1456
+ // #7806 — a declared-only row (the operator's overlay is its ONLY
1457
+ // justification for being here) must not inherit `provenance` from
1458
+ // either source. #7888 round 3 — no longer stripped inline here:
1459
+ // `providerMeta`/`fb` pass through `withModelMetadata` as-is, and
1460
+ // `applyModels` → `setActiveModels` strips `provenance` off the
1461
+ // built row below, once, for every row this function returns.
1462
+ converted.push(withModelMetadata(
1463
+ { id, label, fullId: fb.fullId, contextWindow },
1464
+ providerMeta,
1465
+ fb,
1466
+ ))
789
1467
  seenFullIds.add(fb.fullId)
790
1468
  }
791
1469
  }
@@ -796,6 +1474,18 @@ export function createModelsRegistry(hooks = {}) {
796
1474
  // claude binary), so the picker should surface it as a distinct chip
797
1475
  // even though `supportedModels()` doesn't list it (#3075).
798
1476
  //
1477
+ // #7747 — CLAUDE REGISTRY ONLY. `[1m]` is a Claude-CLI id convention and
1478
+ // nothing on a non-Claude send path strips the suffix before the id goes
1479
+ // upstream, so every synthesized chip was a 400/404 waiting for a tap:
1480
+ // `gemini-2.5-pro[1m]` off gemini's own 2M static table, an OpenRouter
1481
+ // `meta-llama/llama-4-scout[1m]` whose hardcoded 1_000_000 UNDERSTATES
1482
+ // the real window 10x beside a correct base row, and `gpt-4.1[1m]` off
1483
+ // the union this same commit scoped (#7761). The synthesized row also
1484
+ // inherits the base entry's whole metadata roster, so after #7736 it
1485
+ // would carry a `provenance` it did not earn — a row the SERVER invented,
1486
+ // labelled as provider truth. The loop and the `claude-` pricing warn
1487
+ // below it finally agree about who this block is for.
1488
+ //
799
1489
  // Pricing-table drift guard (#4106): the day Anthropic ships a 1M
800
1490
  // variant of Sonnet/Haiku/any-future-model, `updateModels` will
801
1491
  // synthesize the `[1m]` chip here, but if the pricing table at the
@@ -805,42 +1495,52 @@ export function createModelsRegistry(hooks = {}) {
805
1495
  // premium ratio is. Warn-once per variant so an operator notices
806
1496
  // before the bills lie. Forward-compat only — no current breakage.
807
1497
  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)
1498
+ if (isClaudeRegistry) {
1499
+ for (const m of converted) {
1500
+ if (!m.fullId || m.fullId.endsWith(ONE_M_SUFFIX)) continue
1501
+ if (m.contextWindow < 1_000_000) continue
1502
+ const variantFullId = `${m.fullId}${ONE_M_SUFFIX}`
1503
+ if (seenFullIds.has(variantFullId)) continue
1504
+ const variantId = `${m.id}${ONE_M_SUFFIX}`
1505
+ // Consult the metadata hook first so a registry that supplies one
1506
+ // gets its authoritative label instead of the humanizeModelId
1507
+ // mangling (#4441 follow-up to #4438). `getRegistryForProvider`
1508
+ // wires that hook for NON-Claude providers only, and those no longer
1509
+ // reach this loop — so the branch is forward-compat for a Claude
1510
+ // registry constructed with a hook of its own, and keeps the
1511
+ // synthesis path consistent with the five other call sites.
1512
+ const providerMeta = getModelMetadataFn ? getModelMetadataFn(variantFullId) : null
1513
+ // #7723: the synthesized variant is the SAME model at a longer window,
1514
+ // so it inherits the base entry's metadata when the provider has none
1515
+ // of its own for the variant id.
1516
+ variants.push(withModelMetadata({
1517
+ id: variantId,
1518
+ label: providerMeta?.label || humanizeModelId(variantId),
1519
+ fullId: variantFullId,
1520
+ contextWindow: contextWindowOverrides.get(variantFullId)
1521
+ ?? learnedContextWindows.get(variantFullId)
1522
+ ?? 1_000_000,
1523
+ }, providerMeta, m))
1524
+ seenFullIds.add(variantFullId)
1525
+ // Drift detection (#4106 + #4116). Two failure modes both lose
1526
+ // the premium tier in different ways:
1527
+ // (1) No `[1m]` entry at all → resolvePricingKey may return null
1528
+ // (cost=0) or fall back to the base family entry (no
1529
+ // longContext block) depending on the family.
1530
+ // (2) `[1m]` entry exists but lacks `longContext` → premium
1531
+ // block silently absent; >200K turns billed at base rates.
1532
+ // Both produce undercounting; warn for either. Gate to `claude-*`
1533
+ // so an OVERLAY-seeded row on this registry — the one remaining way
1534
+ // a non-`claude-` id reaches here — doesn't get a Claude-pricing nag.
1535
+ if (variantFullId.startsWith('claude-')) {
1536
+ const entry = CLAUDE_PRICING_USD_PER_MTOK[variantFullId]
1537
+ if ((!entry || !entry.longContext) && !pricingDriftWarned.has(variantFullId)) {
1538
+ const reason = entry
1539
+ ? `no longContext premium block; >200K turns will bill at base rates`
1540
+ : `no entry in CLAUDE_PRICING_USD_PER_MTOK; cost may be 0 or fall back to base`
1541
+ log.warn(`pricing-table drift: synthesized 1M variant ${variantFullId} ${reason}. Add an explicit entry (with longContext) in packages/server/src/claude-model-catalog.js.`)
1542
+ pricingDriftWarned.add(variantFullId)
1543
+ }
844
1544
  }
845
1545
  }
846
1546
  }
@@ -856,8 +1556,8 @@ export function createModelsRegistry(hooks = {}) {
856
1556
  // short alias `opus`) still match — else the first converted entry.
857
1557
  // Warn so the regex miss surfaces in logs.
858
1558
  if (nextDefault === null && converted.length > 0) {
859
- let picked = null
860
- for (const preferredShortId of ['opus', 'sonnet']) {
1559
+ let picked = isClaudeRegistry && reported.has(toFullIdMap.get(defaultModelId)) ? defaultModelId : null
1560
+ for (const preferredShortId of picked ? [] : ['opus', 'sonnet']) {
861
1561
  const fb = fallbackModels.find((m) => m.id === preferredShortId)
862
1562
  if (!fb) continue
863
1563
  const match = converted.find((m) => m.fullId === fb.fullId)
@@ -868,11 +1568,16 @@ export function createModelsRegistry(hooks = {}) {
868
1568
  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
1569
  }
870
1570
 
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
1571
+ // Keep provider observations for overlay reloads. Claude retains its
1572
+ // reconciled provider rows (never declaration-only rows); other providers
1573
+ // retain the raw replacement snapshot. Re-derive against the new overlay.
1574
+ lastSdkModels = isClaudeRegistry
1575
+ // #8967: only LIVE-reported rows are replayed by applyOverlay; a kept
1576
+ // in-use cache row must not be laundered into a live observation.
1577
+ ? converted.filter(m => providerReportedFullIds.has(m.fullId) && liveReportedFullIds.has(m.fullId)).map(m => ({
1578
+ ...m, value: m.fullId, displayName: m.id === nextDefault ? `Default (${m.label})` : m.label,
1579
+ }))
1580
+ : sdkModels
876
1581
  applyModels(converted, nextDefault)
877
1582
  return converted
878
1583
  },
@@ -888,27 +1593,67 @@ export function createModelsRegistry(hooks = {}) {
888
1593
  return false
889
1594
  }
890
1595
  let changed = false
891
- activeModels = activeModels.map(m => {
1596
+ // #7888 round 3 — routed through `setActiveModels` (the chokepoint)
1597
+ // rather than assigning `activeModels` directly, so this is not a
1598
+ // seventh place that could reintroduce the whack-a-mole bug if it were
1599
+ // ever rewritten to build rows a different way. A no-op in practice
1600
+ // today: every row already came from `setActiveModels`, so none of
1601
+ // them carry unpersistable `provenance` to begin with, and
1602
+ // `{ ...m, contextWindow }` doesn't add any.
1603
+ const updated = activeModels.map(m => {
892
1604
  if ((m.id === modelId || m.fullId === modelId) && m.contextWindow !== contextWindow) {
893
1605
  changed = true
894
1606
  // Persist the authoritative value so a later updateModels()
895
1607
  // refresh doesn't revert us to the static heuristic.
896
1608
  contextWindowOverrides.set(m.fullId, contextWindow)
1609
+ // #7810 — a declaration-only row (nothing here but the operator's
1610
+ // overlay justifies its presence) is withheld from the persisted
1611
+ // cache entirely (`isUnpersistableDeclaredRow`), so without this a
1612
+ // ratchet learned here would be thrown away on every restart.
1613
+ // Record it under its own key so `saveCache`/`loadCache` can carry
1614
+ // the window without the row. Re-validated with the same
1615
+ // finite-positive-integer check the read side enforces — the guard
1616
+ // above admits NaN (#7771: `typeof NaN === 'number'` and
1617
+ // `NaN <= 0` is false, so it never fires), and this new
1618
+ // persistence path must not write a value it would refuse to load
1619
+ // back.
1620
+ if (isUnpersistableDeclaredRow(m.fullId) && Number.isInteger(contextWindow) && contextWindow > 0) {
1621
+ learnedContextWindows.set(m.fullId, contextWindow)
1622
+ }
897
1623
  return { ...m, contextWindow }
898
1624
  }
899
1625
  return m
900
1626
  })
1627
+ setActiveModels(updated)
901
1628
  return changed
902
1629
  },
903
1630
 
904
1631
  resetModels() {
905
1632
  contextWindowOverrides.clear()
1633
+ // #7810: the declaration-only counterpart of contextWindowOverrides —
1634
+ // a reset forgets everything learned, this map included.
1635
+ learnedContextWindows.clear()
906
1636
  pricingDriftWarned.clear()
907
1637
  // #5932: drop the retained SDK + cache lists too, so a reset truly returns
908
1638
  // to the bare fallback view (a later applyOverlay won't re-merge stale
909
1639
  // SDK/cache data).
910
1640
  lastSdkModels = null
911
1641
  lastCacheModels = null
1642
+ // #7799 round 2: and the provenance record with them — a reset has
1643
+ // nothing a provider reported, so every declared row is declaration-only
1644
+ // again until the next refresh or cache load.
1645
+ providerReportedFullIds = new Set()
1646
+ liveReportedFullIds.clear()
1647
+ // #7888 re-review — the line above is exactly what makes an overlay
1648
+ // override of a base row declaration-only again: without a strip
1649
+ // between here and `activeModels`, a row that HAD lost `provenance`
1650
+ // (an earlier construction/applyOverlay/union pass stripped it)
1651
+ // reacquires the base row's stamp straight from `fallbackModels`,
1652
+ // which never had it stripped in the first place. #7888 round 3 —
1653
+ // `applyModels` now strips unconditionally (`setActiveModels`), so
1654
+ // this call can pass `fallbackModels` straight through; the ordering
1655
+ // that makes it correct is that `providerReportedFullIds` was already
1656
+ // cleared above, before `applyModels` runs.
912
1657
  applyModels(fallbackModels, null)
913
1658
  lastSavedSnapshot = null
914
1659
  },
@@ -950,33 +1695,85 @@ export function createModelsRegistry(hooks = {}) {
950
1695
  const parsed = JSON.parse(raw)
951
1696
  if (!Array.isArray(parsed?.models) || parsed.models.length === 0) return false
952
1697
 
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
- }
1698
+ // #7810 — hydrate the ratchet-learned windows for declaration-only
1699
+ // rows BEFORE the union loop below runs (it reads this map). Absent
1700
+ // on an old-format payload written before this key existed —
1701
+ // `parseLearnedContextWindows` returns an empty map for that,
1702
+ // exactly like a missing/corrupt value in any one entry. Replaces
1703
+ // (not merges) the in-memory map, the same way `providerReportedFullIds`
1704
+ // is replaced below — the disk file is the source of truth for what a
1705
+ // PREVIOUS boot learned. Pruned immediately against the CURRENT
1706
+ // overlay so a file saved before a declaration was removed can't
1707
+ // reintroduce a stale entry into memory (`saveCache` prunes on write,
1708
+ // but a file from an older build, or one edited by hand, may not
1709
+ // have been).
1710
+ learnedContextWindows = parseLearnedContextWindows(parsed.learnedContextWindows)
1711
+ const learnedCountBeforePrune = learnedContextWindows.size
1712
+ prunedLearnedContextWindows()
1713
+ const learnedWasPruned = learnedContextWindows.size < learnedCountBeforePrune
1714
+
1715
+ // #8260: a release-pinned static table is not evidence that Claude
1716
+ // stopped accepting a discovered target. Preserve well-formed cached
1717
+ // aliases, pinned versions and dates across reconnect/restart. Resetting
1718
+ // the registry/cache explicitly clears observations; partial discovery
1719
+ // never retires them. Non-Claude migration rules below are unchanged.
1720
+
1721
+ // #7776 re-review (the critical) — a payload written by a PRE-FIX
1722
+ // build holds `discovered ∪ statics` in `models`, because that is what
1723
+ // `activeModels` was and `saveCache()` persists `activeModels` (written
1724
+ // in production by the context-window ratchet, codex-session.js:794 →
1725
+ // context-window-learn.js:138). Gating the union closed the re-ADD; the
1726
+ // rows were already on disk, so on a registry that REPLACES they were
1727
+ // served at boot and until the first successful refresh — indefinitely
1728
+ // when the probe never succeeds, which is the whole reason `loadCache`
1729
+ // was in scope. Once #7766 lands the catalog-backed validator REJECTS
1730
+ // them, so each is an offered chip that 400s.
1731
+ //
1732
+ // So: on a legacy payload, drop the static seed alongside the `[1m]`
1733
+ // filter below. One-time — the heal-on-prune rewrite at the bottom of
1734
+ // this function persists the result with the current marker, so there
1735
+ // is no second code path and no second pass. A discovered row whose id
1736
+ // COINCIDES with a static is dropped too (a pre-fix payload cannot tell
1737
+ // the two apart); the next refresh re-publishes it, and until then it is
1738
+ // absent rather than offered-and-rejected.
1739
+ //
1740
+ // Scoped to registries that REPLACE: where the seed still unions
1741
+ // (Claude, ollama's recommendation list, a provider with no discovery
1742
+ // seam) the rows are legitimate and the union would re-add them anyway.
1743
+ const payloadSchemaVersion = typeof parsed.v === 'number' ? parsed.v : 0
1744
+ const migrateLegacyStaticSeed = !isClaudeRegistry
1745
+ && !unionsStaticFallbacks
1746
+ && payloadSchemaVersion < MODELS_CACHE_SCHEMA_VERSION
970
1747
 
971
1748
  const valid = parsed.models.filter(m =>
972
- m && typeof m.id === 'string' && typeof m.fullId === 'string',
1749
+ m && typeof m.id === 'string' && m.id.trim() !== ''
1750
+ && typeof m.fullId === 'string' && m.fullId.trim() !== '',
973
1751
  )
974
1752
  const models = valid
975
1753
  .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)
1754
+ // #7723: non-Claude registries keep every well-formed cached entry
1755
+ // — their ids carry no family/minor grammar for this filter to
1756
+ // read, so applying it would delete exactly the discovered models
1757
+ // the cache exists to remember.
1758
+ //
1759
+ // …with ONE exclusion (#7776/#7747). `saveCache()` persists
1760
+ // `activeModels`, which on a pre-fix build included the synthesized
1761
+ // `[1m]` rows, so a cache written before this change already holds
1762
+ // `gpt-4.1[1m]` / `gemini-2.5-pro[1m]` on disk. The synthesis is now
1763
+ // Claude-only, but the row is re-served verbatim from that file at
1764
+ // every boot — so the chip #7747 removed would come back for exactly
1765
+ // the installs that hit the bug. `[1m]` is a Claude-CLI id
1766
+ // convention and no non-Claude send path strips the suffix, so the
1767
+ // id is a 400/404 wherever it appears here: drop it on load. A
1768
+ // provider that genuinely ships an id ending in `[1m]` will
1769
+ // re-publish it through discovery, which does not route here.
1770
+ if (!isClaudeRegistry) {
1771
+ if (m.fullId.endsWith(ONE_M_SUFFIX)) return false
1772
+ // …and the static seed on a legacy payload (see above).
1773
+ if (migrateLegacyStaticSeed && staticFallbackFullIds.has(m.fullId)) return false
1774
+ return true
1775
+ }
1776
+ return true
980
1777
  })
981
1778
  .map(m => {
982
1779
  // #4434: when the cached label is missing/empty (older cache
@@ -988,7 +1785,10 @@ export function createModelsRegistry(hooks = {}) {
988
1785
  // Mirrors the post-filter merge step below which already
989
1786
  // consults `getModelMetadataFn` for the same reason.
990
1787
  const providerMeta = getModelMetadataFn ? getModelMetadataFn(m.fullId) : null
991
- return {
1788
+ // #7723: the cached entry's own metadata wins over the provider's
1789
+ // static table — the cache is what the provider REPORTED, the
1790
+ // table is what the repo happens to know.
1791
+ return withModelMetadata({
992
1792
  id: m.id,
993
1793
  fullId: m.fullId,
994
1794
  label: typeof m.label === 'string' && m.label.length > 0
@@ -997,12 +1797,17 @@ export function createModelsRegistry(hooks = {}) {
997
1797
  contextWindow: typeof m.contextWindow === 'number' && m.contextWindow > 0
998
1798
  ? m.contextWindow
999
1799
  : resolveContextWindowFn(m.fullId),
1000
- }
1800
+ }, m, providerMeta)
1001
1801
  })
1002
1802
 
1003
1803
  const droppedStaleCount = valid.length - models.length
1004
1804
  if (droppedStaleCount > 0) {
1005
- log.info(`loadCache: dropped ${droppedStaleCount} stale cache entr${droppedStaleCount === 1 ? 'y' : 'ies'} not in FALLBACK_MODELS`)
1805
+ const droppedReason = isClaudeRegistry
1806
+ ? 'invalid identity'
1807
+ : (migrateLegacyStaticSeed
1808
+ ? 'carrying the Claude-only [1m] id convention or a pre-#7776 static-seed row (one-time cache migration)'
1809
+ : 'carrying the Claude-only [1m] id convention')
1810
+ log.info(`loadCache: dropped ${droppedStaleCount} cache entr${droppedStaleCount === 1 ? 'y' : 'ies'} ${droppedReason}`)
1006
1811
  }
1007
1812
 
1008
1813
  if (models.length === 0) {
@@ -1012,21 +1817,66 @@ export function createModelsRegistry(hooks = {}) {
1012
1817
  return false
1013
1818
  }
1014
1819
 
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) {
1820
+ // Merge in any seed entries the filtered cache doesn't cover so the
1821
+ // picker always has the canonical aliases (on the Claude registry:
1822
+ // sonnet/opus/haiku) even when the cache was mostly stale. The `[1m]`
1823
+ // variant synthesis that updateModels() does is intentionally NOT
1824
+ // repeated here — variants are already in the saved cache for SDK
1825
+ // users, and CLI-only users would not have a working SDK call to
1826
+ // populate them anyway.
1827
+ //
1828
+ // #7776 — this is the SAME #3075 union as `updateModels`, and #7761
1829
+ // gated only that copy. All three read `unionableSeedRows()` now.
1830
+ //
1831
+ // The direction the gate encodes here, stated rather than assumed: the
1832
+ // seed is dropped on top of a cache for a provider that CAN re-publish
1833
+ // a roster — the cache is then what discovery last reported, and
1834
+ // re-seeding the statics restores exactly what #7761 removed, at boot,
1835
+ // for the whole window before the first successful refresh. It is KEPT
1836
+ // for a provider with no discovery seam, where the cache can only ever
1837
+ // be a snapshot of this repo's own static table and nothing will ever
1838
+ // re-publish a newly-added static row (`hasDiscoverySeam`), and for one
1839
+ // whose seed is a recommendation list rather than a roster claim
1840
+ // (`unionsStaticFallbacks`, ollama). Both are read through
1841
+ // `unionableSeedRows()`; neither is a provider-name check.
1842
+ // Retain only rows actually read from disk. The seed union below must
1843
+ // never turn a construction-time overlay declaration into an observation.
1844
+ const cachedModels = [...models]
1845
+ const seenFullIds = new Set(cachedModels.map(m => m.fullId))
1846
+ // #7799 round 2 — same provenance record as the `updateModels` copy,
1847
+ // taken BEFORE the union: a cache file is what a provider reported, so
1848
+ // the rows read off disk carry provider provenance and the ones this
1849
+ // loop appends do not. `applyOverlay`'s cache-warmed branch deliberately
1850
+ // leaves this alone — re-folding an overlay does not change what the
1851
+ // provider once said.
1852
+ providerReportedFullIds = new Set(seenFullIds)
1853
+ for (const fb of unionableSeedRows()) {
1024
1854
  if (!seenFullIds.has(fb.fullId)) {
1855
+ // Same operator-outranks-static-table precedence as the
1856
+ // `updateModels` copy of this union (#7799 review) — the two must
1857
+ // agree or a row changes label/window depending on whether the
1858
+ // roster came from a refresh or from disk.
1859
+ const declared = overlayDeclaredFullIds.get(fb.fullId)
1025
1860
  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 })
1861
+ const id = declared?.shortId ?? providerMeta?.id ?? deriveIdFn(fb.fullId)
1862
+ const label = declared?.label || providerMeta?.label || humanizeModelId(id)
1863
+ // #7810 round 2 — same operator-declared/heuristic tier as the
1864
+ // `updateModels` copy of this union; the learned-window and live-
1865
+ // override tiers above it are no longer read here — see the
1866
+ // comment on `resolveDeclaredRowWindow`, which `applyModels` runs
1867
+ // over this array's rows (and the ones this function reads off
1868
+ // disk unfiltered) before any of them reach `activeModels`.
1869
+ const contextWindow = declared?.contextWindow
1870
+ ?? providerMeta?.contextWindow ?? fb.contextWindow ?? resolveContextWindowFn(fb.fullId)
1871
+ // #7806 — same declared-only provenance rule as the `updateModels`
1872
+ // copy of this union. #7888 round 3 — same removal too: the
1873
+ // strip happens once, in `applyModels` → `setActiveModels`, over
1874
+ // whatever this function returns.
1875
+ models.push(withModelMetadata(
1876
+ { id, fullId: fb.fullId, label, contextWindow },
1877
+ providerMeta,
1878
+ fb,
1879
+ ))
1030
1880
  seenFullIds.add(fb.fullId)
1031
1881
  }
1032
1882
  }
@@ -1041,15 +1891,26 @@ export function createModelsRegistry(hooks = {}) {
1041
1891
  applyModels(models, nextDefault)
1042
1892
  // #5932: remember the cache-applied list so an overlay reload in the
1043
1893
  // CLI-only window (no SDK refresh yet) preserves these entries.
1044
- lastCacheModels = models
1894
+ lastCacheModels = cachedModels
1045
1895
  // Treat the loaded state as the last-saved baseline so subsequent
1046
1896
  // saveCache() calls only hit disk when the registry actually drifts.
1897
+ // Since #7799 round 3 the baseline is taken over the PERSISTABLE rows —
1898
+ // the same list `saveCacheImpl` writes — so "the snapshot matches" means
1899
+ // "the payload would be identical", which it did not while the key was
1900
+ // hashed over `activeModels` and the payload was filtered.
1047
1901
  lastSavedSnapshot = snapshotString()
1048
1902
 
1049
1903
  // Heal the disk file when we pruned anything. Without this the
1050
1904
  // CLI-only/offline path would re-filter the same stale entries on
1051
1905
  // every startup since updateModels() never runs to overwrite them.
1052
- if (droppedStaleCount > 0 || defaultDiscarded) {
1906
+ // #7810 — `learnedWasPruned` joins the same heal trigger: the
1907
+ // baseline snapshot just taken above already reflects the PRUNED
1908
+ // in-memory map (a declaration removed since this file was written),
1909
+ // so without forcing a write here `saveCacheImpl`'s own
1910
+ // snapshot-matches-baseline skip would never let the stale entry
1911
+ // actually leave the file — every future load would re-prune the
1912
+ // same dead entry from memory without it ever going away on disk.
1913
+ if (droppedStaleCount > 0 || defaultDiscarded || learnedWasPruned) {
1053
1914
  // Force a write by clearing the snapshot baseline (saveCacheImpl
1054
1915
  // skips when snapshot matches lastSavedSnapshot).
1055
1916
  lastSavedSnapshot = null
@@ -1088,6 +1949,30 @@ export function createModelsRegistry(hooks = {}) {
1088
1949
  // appears in the picker / allowlist and survives the loadCache prune.
1089
1950
  const defaultRegistry = createModelsRegistry({ overlay: defaultOverlay })
1090
1951
 
1952
+ /**
1953
+ * #7722 — a stable signature for ONE provider's overlay slice, used to decide
1954
+ * whether a reload actually moved that provider's registry. Three
1955
+ * normalisations, each for one way an edit-free save can look like an edit:
1956
+ *
1957
+ * - the `.sort()` on entries: a Map iterates in insertion order, which is the
1958
+ * file's ROW order, so moving two lines in models.json would otherwise read
1959
+ * as a change;
1960
+ * - `canonicalStringify` rather than `JSON.stringify`: every row is rebuilt as
1961
+ * a fixed-shape object by `loadModelsOverlayResult`, EXCEPT `pricing`, which
1962
+ * is copied through verbatim from `JSON.parse` and so carries the file's key
1963
+ * order;
1964
+ * - the empty/absent short-circuit: a provider mentioned by neither overlay
1965
+ * must compare equal to itself, not read as changed.
1966
+ *
1967
+ * @param {Map<string, object>|undefined} slice
1968
+ * @returns {string}
1969
+ */
1970
+ function overlaySliceSignature(slice) {
1971
+ if (!slice || slice.size === 0) return '[]'
1972
+ const rows = [...slice.entries()].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))
1973
+ return canonicalStringify(rows)
1974
+ }
1975
+
1091
1976
  /**
1092
1977
  * #5932 — hot-reload the user model overlay (`~/.chroxy/models.json`) into the
1093
1978
  * DEFAULT (Claude) registry + the module-level pricing path, without a daemon
@@ -1100,8 +1985,14 @@ const defaultRegistry = createModelsRegistry({ overlay: defaultOverlay })
1100
1985
  * deleted/absent file legitimately CLEARS the overlay (an explicit operator
1101
1986
  * action). Never throws.
1102
1987
  *
1988
+ * #7722: the result also carries `providers` — one `{ provider, models,
1989
+ * defaultModelId }` snapshot per NON-Claude registry whose overlay slice this
1990
+ * reload actually CHANGED — so the caller can emit a provider-tagged
1991
+ * `available_models` broadcast for each instead of labelling every roster
1992
+ * `claude-sdk`. A registry the save did not move is absent, not empty.
1993
+ *
1103
1994
  * @param {string} [path]
1104
- * @returns {{ reloaded: boolean, reason?: string, models?: object[], defaultModelId?: string|null }}
1995
+ * @returns {{ reloaded: boolean, reason?: string, models?: object[], defaultModelId?: string|null, providers?: {provider: string, models: object[], defaultModelId: string|null}[] }}
1105
1996
  */
1106
1997
  export function reloadModelsOverlay(path = getDefaultOverlayPath()) {
1107
1998
  const result = loadModelsOverlayResult(path)
@@ -1111,19 +2002,71 @@ export function reloadModelsOverlay(path = getDefaultOverlayPath()) {
1111
2002
  }
1112
2003
  defaultOverlay = result.overlay
1113
2004
  defaultRegistry.applyOverlay(result.overlay)
2005
+ // #7722: the provider registries whose roster this reload actually CHANGED.
2006
+ // A reload can only move a provider registry through its overlay SLICE — the
2007
+ // fallback list and the on-disk cache are untouched here — so the changed set
2008
+ // is exactly the names whose slice differs between the PREVIOUS
2009
+ // `providerOverlays` and the NEW `result.byProvider`: a name added, a name
2010
+ // that lost all its rows, or a row edited in place. Read BEFORE
2011
+ // `providerOverlays` is reassigned below, so the previous slices are still
2012
+ // readable.
2013
+ //
2014
+ // An already-built registry whose slice did NOT move is deliberately absent:
2015
+ // re-broadcasting a byte-identical roster is pure wire cost, and a
2016
+ // config-driven / anthropic-compatible registry seeds its fallback list from
2017
+ // catalogMeta (hundreds of rows) over a tunnel that may be on a cellular link.
2018
+ const changed = []
2019
+ for (const name of new Set([...providerOverlays.keys(), ...result.byProvider.keys()])) {
2020
+ const before = overlaySliceSignature(providerOverlays.get(name))
2021
+ const after = overlaySliceSignature(result.byProvider.get(name))
2022
+ if (before === after) continue
2023
+ changed.push(name)
2024
+ }
1114
2025
  // #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.
2026
+ // registry. A provider whose registry hasn't been built yet needs no re-fold
2027
+ // here — `getRegistryForProvider` seeds a fresh registry from
2028
+ // `providerOverlays` on first build. #7722 made that first build happen
2029
+ // EAGERLY for a CHANGED provider: the snapshot loop below calls
2030
+ // `getRegistryForProvider(name)` so the reload can report that provider's
2031
+ // roster, which for an overlay-tagged provider moves the build — the
2032
+ // `registry.loadCache()` disk read included — off the first session and onto
2033
+ // the reload. Providers the overlay never mentions stay lazy. A provider that
2034
+ // lost all its overlay entries gets an empty Map → its overlay-only rows drop.
1119
2035
  providerOverlays = result.byProvider
1120
2036
  for (const [name, registry] of providerRegistryCache) {
1121
2037
  registry.applyOverlay(providerOverlays.get(name) ?? new Map())
1122
2038
  }
2039
+ // #7722: snapshot each changed provider's roster. A Claude-family / unknown /
2040
+ // unregistered name resolves to the DEFAULT registry and is skipped, so a
2041
+ // mistyped `provider` field can never broadcast the Claude roster under that
2042
+ // tag, and a Claude-tagged row (a documented no-op) can't produce a duplicate
2043
+ // of the default broadcast the caller already sends.
2044
+ //
2045
+ // Wrapped because the docstring above promises this function NEVER THROWS and
2046
+ // `watchModelsOverlay`'s `fire()` only try/catches `onReload`, not the reload
2047
+ // itself — it runs from a setTimeout, where a throw is an unhandled exception.
2048
+ // `getRegistryForProvider` executes provider-class code (`getFallbackModels()`,
2049
+ // `getModelMetadata`) that a reload never used to reach; every shipping
2050
+ // implementation is pure, so this only ever costs a warn line.
2051
+ const providers = []
2052
+ for (const name of changed) {
2053
+ try {
2054
+ if (usesDefaultModelsRegistry(name)) continue
2055
+ const registry = getRegistryForProvider(name)
2056
+ providers.push({
2057
+ provider: name,
2058
+ models: registry.getModels(),
2059
+ defaultModelId: registry.getDefaultModelId(),
2060
+ })
2061
+ } catch (err) {
2062
+ log.warn(`reloadModelsOverlay: roster snapshot for provider "${name}" failed: ${err?.message || err}`)
2063
+ }
2064
+ }
1123
2065
  return {
1124
2066
  reloaded: true,
1125
2067
  models: defaultRegistry.getModels(),
1126
2068
  defaultModelId: defaultRegistry.getDefaultModelId(),
2069
+ providers,
1127
2070
  }
1128
2071
  }
1129
2072
 
@@ -1132,8 +2075,9 @@ export function reloadModelsOverlay(path = getDefaultOverlayPath()) {
1132
2075
  * containing DIRECTORY (not the file inode) so an editor's atomic
1133
2076
  * write-temp-then-rename still fires, filters to the overlay filename, and
1134
2077
  * 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).
2078
+ * `onReload({ models, defaultModelId, providers })` callback fires — the caller
2079
+ * broadcasts one provider-tagged `available_models` per roster (#7722). A
2080
+ * malformed save is ignored (last-good kept, no callback).
1137
2081
  *
1138
2082
  * Returns a `{ close() }` handle; call it on daemon shutdown. Never throws — a
1139
2083
  * watch that can't be established (e.g. unsupported FS) logs a warn and returns
@@ -1306,6 +2250,25 @@ export function _resetProviderRegistryCacheForTests(providerName) {
1306
2250
  providerRegistryCache.clear()
1307
2251
  }
1308
2252
 
2253
+ /**
2254
+ * Test helper (#7722 review). Undoes `registerProviderRegistry(name, Class)`:
2255
+ * drops the name→class mapping AND any registry already built from it, so a
2256
+ * test that registers a throwaway provider class (e.g. one that throws on
2257
+ * purpose) leaves no module state behind for the next test.
2258
+ *
2259
+ * `_resetProviderRegistryCacheForTests()` is NOT enough on its own — it clears
2260
+ * `providerRegistryCache` only, so the name stays resolvable via
2261
+ * `nameToProviderClass` and keeps rebuilding the same registry.
2262
+ *
2263
+ * @param {string} providerName
2264
+ * @returns {boolean} true when a registration was actually removed
2265
+ */
2266
+ export function _unregisterProviderRegistryForTests(providerName) {
2267
+ if (typeof providerName !== 'string' || providerName.length === 0) return false
2268
+ providerRegistryCache.delete(providerName)
2269
+ return nameToProviderClass.delete(providerName)
2270
+ }
2271
+
1309
2272
  /**
1310
2273
  * Lazily create and cache a provider-scoped registry.
1311
2274
  *
@@ -1342,6 +2305,16 @@ export function getRegistryForProvider(providerName) {
1342
2305
  // strip) — identity is the safest default. Providers can override via
1343
2306
  // `getModelMetadata()` when they want a different short id.
1344
2307
  deriveId: (fullId) => fullId,
2308
+ // #7761: a non-Claude refresh REPLACES the static seed unless the provider
2309
+ // declares that seed to be a recommendation list (ollama).
2310
+ unionsStaticFallbacks: ProviderClass.staticModelsAreRecommendations === true,
2311
+ // #7776 re-review: …and REPLACE needs something that can re-publish. A
2312
+ // provider with no static `refreshModels` (gemini, deepseek) never has
2313
+ // `updateModels` called on its registry, so its cache is a snapshot of this
2314
+ // repo's own static table — the seed must keep unioning there or a
2315
+ // statically-added model never reaches the picker on an install that has a
2316
+ // cache file. Derived from the seam, not from a provider-name list.
2317
+ hasDiscoverySeam: typeof ProviderClass.refreshModels === 'function',
1345
2318
  resolveContextWindow: (fullId) => {
1346
2319
  const meta = typeof ProviderClass.getModelMetadata === 'function'
1347
2320
  ? ProviderClass.getModelMetadata(fullId)
@@ -1378,6 +2351,130 @@ export function getRegistryForProvider(providerName) {
1378
2351
  return registry
1379
2352
  }
1380
2353
 
2354
+ /**
2355
+ * #7722 — true when `providerName`'s models come from the DEFAULT (Claude)
2356
+ * registry: a Claude-family provider, an unknown/unregistered name, a provider
2357
+ * class with no `getFallbackModels()`, and `null`/`undefined` (no active
2358
+ * session) all land there. The SINGLE derivation of that question — the overlay
2359
+ * reload uses it to decide which rosters are worth reporting separately, and
2360
+ * `server-cli.js` uses it to decide which clients an overlay-reload broadcast
2361
+ * reaches. Two copies of this predicate would be free to disagree about exactly
2362
+ * the edge cases (unregistered names, docker-* subclasses) it exists for.
2363
+ *
2364
+ * @param {string|null|undefined} providerName
2365
+ * @returns {boolean}
2366
+ */
2367
+ export function usesDefaultModelsRegistry(providerName) {
2368
+ return getRegistryForProvider(providerName) === defaultRegistry
2369
+ }
2370
+
2371
+ /**
2372
+ * #7759 — the provider name an `available_models` roster is TAGGED with, given
2373
+ * the session's own provider (which may be absent) and this daemon's resolved
2374
+ * default.
2375
+ *
2376
+ * Never null. Every `available_models` sender used to fall back to
2377
+ * `provider: null` when it had no session to read a provider off — a post-auth
2378
+ * connect with no active session, the legacy single-session bootstrap on a ctx
2379
+ * with no billing canary, a session entry that carries no provider — and
2380
+ * `getRegistryForProvider(null)` answers those with the CLAUDE default
2381
+ * registry. The client files a null tag in its UNTAGGED bucket
2382
+ * (`store-core/models-by-provider.ts`), whose docstring means "a pre-provider
2383
+ * daemon that tags nothing"; a MODERN daemon writing there makes that bucket
2384
+ * lie, and while it is the only roster in play the client serves it to a
2385
+ * session of any provider — Claude chips in a codex session, with `set_model`
2386
+ * live on tap.
2387
+ *
2388
+ * The caller must resolve its registry from THIS name, not from the raw
2389
+ * session provider: the tag has to name the registry that actually produced
2390
+ * the rows, or producer and consumer are answering different questions about
2391
+ * the same message. Do NOT substitute a hardcoded Claude name for the absent
2392
+ * case (`ws-forwarding.js` uses `'claude-sdk'`): `claude-sdk`, `claude-cli`,
2393
+ * `claude-byok` and `claude-tui` share ONE registry but are four distinct
2394
+ * bucket keys, so a single Claude name tags a roster that the other three
2395
+ * cannot look up. The daemon's own default is the one concrete name that is
2396
+ * also a TRUE statement about which registry answered.
2397
+ *
2398
+ * @param {string|null|undefined} sessionProvider - the session's provider, or
2399
+ * null/absent when there is no session (or it reports none).
2400
+ * @param {string|null|undefined} defaultProvider - this daemon's resolved
2401
+ * default (`billingCanary.defaultProvider` / `config.provider`, both of which
2402
+ * are `config.provider || DEFAULT_PROVIDER`). Floored to DEFAULT_PROVIDER so
2403
+ * a ctx that carries neither still yields a concrete name.
2404
+ * @returns {string}
2405
+ */
2406
+ export function resolveRosterProvider(sessionProvider, defaultProvider) {
2407
+ const fromSession = typeof sessionProvider === 'string' ? sessionProvider.trim() : ''
2408
+ if (fromSession) return fromSession
2409
+ const fromDefault = typeof defaultProvider === 'string' ? defaultProvider.trim() : ''
2410
+ if (fromDefault) return fromDefault
2411
+ return DEFAULT_PROVIDER
2412
+ }
2413
+
2414
+ /**
2415
+ * #7784 — ONE roster row for a model, from the ROSTER THE CLIENT WAS SENT.
2416
+ *
2417
+ * `available_models` is `getRegistryForProvider(entry.provider).getModels()`
2418
+ * tagged with that provider name, at both send sites in `ws-history.js`, and
2419
+ * the dashboard picks a row out of it by `fullId === active || id === active`
2420
+ * (the #5628 dual match: a session's model arrives as either form). This
2421
+ * function is that same expression on those same rows, so a server-side
2422
+ * consumer asking "what does the active model advertise?" reads the row the
2423
+ * operator is actually looking at.
2424
+ *
2425
+ * That matters because the alternative — calling
2426
+ * `ProviderClass.getModelMetadata(id)` — is a SECOND source with its own
2427
+ * refresh timing, and the two provably disagree: after codex's `model/list`
2428
+ * answers with zero rows the catalog records the empty answer while nothing is
2429
+ * broadcast for it (`refreshDiscoveredModels` never calls `updateModels([])`),
2430
+ * so the registry keeps serving the previously discovered rows — levels and all
2431
+ * — while `getModelMetadata` for those same ids returns null. The picker then
2432
+ * offered the stale row's efforts and the gate refused every one of them
2433
+ * (#7784, and `codex-model-catalog.js`'s own header documents the state).
2434
+ *
2435
+ * A provider whose class has no `getFallbackModels()` lands on the DEFAULT
2436
+ * registry, and this function reads it rather than answering null — deliberately,
2437
+ * because that is the roster the client was SENT for that provider (the send
2438
+ * sites tag whatever registry answered). Deviating here would re-create the
2439
+ * divergence this function exists to remove; that the fallback is the Claude
2440
+ * roster is `getRegistryForProvider`'s documented behaviour and a separate
2441
+ * question.
2442
+ *
2443
+ * @param {string|null|undefined} providerName
2444
+ * @param {string|null|undefined} modelId - short id or full id
2445
+ * @returns {Object|null} the roster row, or null when the roster has no such model
2446
+ */
2447
+ export function getRosterModelRow(providerName, modelId) {
2448
+ if (typeof modelId !== 'string' || modelId.length === 0) return null
2449
+ const rows = getRegistryForProvider(providerName).getModels()
2450
+ if (!Array.isArray(rows)) return null
2451
+ for (const row of rows) {
2452
+ if (row?.fullId === modelId || row?.id === modelId) return row
2453
+ }
2454
+ return null
2455
+ }
2456
+
2457
+ /**
2458
+ * #7784 — does `LEGACY_THINKING_LEVELS` stand in for a model row that
2459
+ * advertises no reasoning levels on this provider?
2460
+ *
2461
+ * The ONE derivation of that question. It is `isClaudeProvider`, because the
2462
+ * legacy triple is the Claude family's real roster and nobody else's — handing
2463
+ * it to a provider that simply has not advertised its own levels yet lets a
2464
+ * level no model offered ride out as if one had (#7782). It lives here rather
2465
+ * than at either consumer because BOTH need the same answer: the server's
2466
+ * `set_thinking_level` gate asks it directly, and `listProviders()` ships it to
2467
+ * clients as the `thinkingLevelLegacyFallback` capability so the picker resolves
2468
+ * its options from the same fact instead of always taking the fallback.
2469
+ *
2470
+ * @param {string|null|undefined} providerName
2471
+ * @param {Function} [ProviderClass] - optional resolved class (authoritative)
2472
+ * @returns {boolean}
2473
+ */
2474
+ export function thinkingLevelLegacyFallbackApplies(providerName, ProviderClass = null) {
2475
+ return isClaudeProvider(providerName, ProviderClass)
2476
+ }
2477
+
1381
2478
  // Accept both short ids and full model IDs in set_model.
1382
2479
  // Proxy delegates to the default registry's live Set so mutations
1383
2480
  // (from updateModels/resetModels) are always reflected.
@@ -1397,6 +2494,11 @@ export function updateModels(sdkModels) {
1397
2494
  return defaultRegistry.updateModels(sdkModels)
1398
2495
  }
1399
2496
 
2497
+ /** #8967 — see the registry method; wired by the daemon to its SessionManager. */
2498
+ export function setInUseModelsProvider(fn) {
2499
+ return defaultRegistry.setInUseModelsProvider(fn)
2500
+ }
2501
+
1400
2502
  export function updateContextWindow(modelId, contextWindow) {
1401
2503
  return defaultRegistry.updateContextWindow(modelId, contextWindow)
1402
2504
  }