@bitkyc08/opencodex 2.81.0 → 2.82.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/bin/ocx.mjs +166 -73
  2. package/gui/dist/assets/App-Ds_qL7o8.js +54 -0
  3. package/gui/dist/assets/{Tray-EwAOsP0S.js → Tray-BqHF5Trd.js} +1 -1
  4. package/gui/dist/assets/{index-Brk6F3fn.css → index-BAbcj51J.css} +1 -1
  5. package/gui/dist/assets/{index-RsoaAxXY.js → index-D3FBCNiP.js} +13 -13
  6. package/gui/dist/assets/{quota-summary-D2lN8tDm.js → quota-summary-DTBC8n7-.js} +1 -1
  7. package/gui/dist/index.html +2 -2
  8. package/package.json +1 -1
  9. package/src/adapters/anthropic.ts +1 -1
  10. package/src/adapters/openai-responses/compaction-search-history.ts +109 -0
  11. package/src/adapters/openai-responses/passthrough.ts +9 -4
  12. package/src/adapters/openai-responses/tool-output-recovery.ts +20 -0
  13. package/src/claude/agents-inject.ts +14 -3
  14. package/src/claude/context-windows.ts +19 -17
  15. package/src/claude/desktop-3p.ts +88 -12
  16. package/src/claude/desktop-profile.ts +2 -1
  17. package/src/claude/gateway-cache.ts +18 -1
  18. package/src/claude/inbound.ts +77 -3
  19. package/src/claude/intercept/cli-catalog.ts +3 -0
  20. package/src/claude/intercept/picker-ca-persistence.ts +7 -6
  21. package/src/claude/intercept/picker-models.ts +14 -6
  22. package/src/claude/intercept/settings.ts +3 -0
  23. package/src/claude/long-context.ts +66 -0
  24. package/src/claude/model-info.ts +19 -16
  25. package/src/claude/outbound.ts +94 -9
  26. package/src/claude/subagent-model.ts +40 -11
  27. package/src/cli/agent.ts +9 -5
  28. package/src/cli/aside-profile-recovery.ts +33 -0
  29. package/src/cli/capabilities-base.ts +5 -5
  30. package/src/cli/capabilities-integrations.ts +2 -2
  31. package/src/cli/cli-path-diagnostics.ts +132 -0
  32. package/src/cli/desktop-runtime-guidance.ts +65 -0
  33. package/src/cli/dispatch.ts +5 -0
  34. package/src/cli/doctor.ts +16 -3
  35. package/src/cli/index.ts +14 -9
  36. package/src/cli/integration-aside-sync.ts +2 -1
  37. package/src/cli/integrations.ts +16 -3
  38. package/src/cli/resolve.ts +25 -2
  39. package/src/cli/root.ts +4 -2
  40. package/src/cli/status.ts +64 -12
  41. package/src/cli/update-restart-child.ts +4 -2
  42. package/src/cli/update-restart-home.ts +28 -10
  43. package/src/cli/update-restart-service-record.ts +116 -0
  44. package/src/cli/update-restart-supervision.ts +96 -0
  45. package/src/cli/update-restart.ts +59 -13
  46. package/src/cli/v2.ts +27 -20
  47. package/src/cli/version-skew-notice.ts +77 -0
  48. package/src/clients/lazycodex.ts +1 -1
  49. package/src/clients/omo-role-models.ts +32 -7
  50. package/src/codex/auth-api/account-selection.ts +107 -0
  51. package/src/codex/auth-api/routes.ts +10 -49
  52. package/src/codex/auth-context.ts +20 -1
  53. package/src/codex/autostart-health.ts +12 -3
  54. package/src/codex/catalog/build-entries.ts +18 -0
  55. package/src/codex/catalog/bundled.ts +155 -26
  56. package/src/codex/catalog/combo-member.ts +3 -2
  57. package/src/codex/catalog/effort.ts +26 -5
  58. package/src/codex/catalog/gather-capture.ts +5 -0
  59. package/src/codex/catalog/model-hints.ts +15 -8
  60. package/src/codex/catalog/model-visibility.ts +3 -1
  61. package/src/codex/catalog/operator-tiers.ts +38 -0
  62. package/src/codex/catalog/provider-models.ts +43 -35
  63. package/src/codex/catalog/retained-sync.ts +7 -5
  64. package/src/codex/catalog/routed-gather.ts +15 -1
  65. package/src/codex/catalog-auto-refresh-sources.ts +3 -4
  66. package/src/codex/catalog-auto-refresh.ts +19 -0
  67. package/src/codex/catalog.ts +1 -1
  68. package/src/codex/codex-home-owner.ts +3 -0
  69. package/src/codex/config-write-lock.ts +333 -0
  70. package/src/codex/convergence.ts +2 -1
  71. package/src/codex/features.ts +257 -200
  72. package/src/codex/inject/config-write-section.ts +34 -0
  73. package/src/codex/inject/multi-agent-v2.ts +14 -6
  74. package/src/codex/inject/remove.ts +36 -11
  75. package/src/codex/inject/restore.ts +85 -20
  76. package/src/codex/inject-coordination.ts +15 -6
  77. package/src/codex/inject.ts +62 -20
  78. package/src/codex/journal.ts +62 -17
  79. package/src/codex/main-account-cache.ts +43 -0
  80. package/src/codex/paths.ts +2 -0
  81. package/src/codex/prepared-home.ts +18 -0
  82. package/src/codex/prompt-journal.ts +25 -12
  83. package/src/codex/prompt-layers.ts +49 -26
  84. package/src/codex/prompt-lock-claim.ts +134 -0
  85. package/src/codex/prompt-lock-evidence.ts +26 -0
  86. package/src/codex/prompt-lock-io.ts +16 -0
  87. package/src/codex/prompt-lock-owner.ts +130 -0
  88. package/src/codex/prompt-lock.ts +84 -53
  89. package/src/codex/routing/failure-window.ts +146 -0
  90. package/src/codex/routing/selection.ts +4 -1
  91. package/src/codex/routing.ts +13 -17
  92. package/src/codex/runtime.ts +106 -18
  93. package/src/codex/shim.ts +45 -19
  94. package/src/combos/jev-service-exchange.ts +281 -0
  95. package/src/combos/jev.ts +34 -220
  96. package/src/config/atomic-write.ts +1 -1
  97. package/src/config/codex-ws-reuse-setting.ts +10 -0
  98. package/src/config/live-reconcile.ts +17 -0
  99. package/src/config/load-degrade.ts +8 -0
  100. package/src/config/rebase-provenance.ts +11 -0
  101. package/src/config/schema/config-schema.ts +4 -0
  102. package/src/generated/compatibility-version.json +303 -171
  103. package/src/generated/model-metadata.ts +2 -2
  104. package/src/grok/inject.ts +50 -4
  105. package/src/grok/sync.ts +2 -1
  106. package/src/images/loop.ts +29 -11
  107. package/src/integrations/aside-profiles.ts +10 -3
  108. package/src/integrations/catalog-refresh.ts +18 -2
  109. package/src/integrations/writer.ts +9 -3
  110. package/src/lib/bun-path-runtime.d.mts +32 -0
  111. package/src/lib/bun-path-runtime.mjs +95 -0
  112. package/src/lib/bun-runtime-preflight.ts +140 -0
  113. package/src/lib/desktop-cli-handoff.d.mts +20 -0
  114. package/src/lib/desktop-cli-handoff.mjs +92 -0
  115. package/src/lib/desktop-cli-record.d.mts +29 -0
  116. package/src/lib/desktop-cli-record.mjs +102 -0
  117. package/src/lib/request-execution-budget.ts +8 -0
  118. package/src/lib/synced-state-location.ts +46 -6
  119. package/src/lib/test-home-guard.ts +87 -1
  120. package/src/lib/translator-budget.ts +17 -4
  121. package/src/lib/windows-atomic-replace.ts +38 -16
  122. package/src/lib/windows-elevation.ts +6 -0
  123. package/src/lib/windows-secret-acl.ts +92 -25
  124. package/src/lib/winsw.ts +2 -3
  125. package/src/oauth/anthropic-account-refusal.ts +39 -1
  126. package/src/oauth/anthropic-routing.ts +1 -1
  127. package/src/oauth/anthropic-send-ownership.ts +3 -3
  128. package/src/oauth/chatgpt.ts +113 -41
  129. package/src/oauth/index.ts +6 -2
  130. package/src/oauth/store.ts +1 -1
  131. package/src/providers/azure-model-metadata.ts +115 -0
  132. package/src/providers/derive.ts +21 -0
  133. package/src/providers/quota/vendor-probes-key.ts +127 -17
  134. package/src/providers/quota.ts +1 -1
  135. package/src/responses/reasoning-envelope.ts +29 -1
  136. package/src/responses/reasoning-replay-cache.ts +17 -1
  137. package/src/responses/spill-store.ts +15 -2
  138. package/src/responses/state/metrics.ts +8 -0
  139. package/src/responses/state/spill-failure.ts +12 -0
  140. package/src/responses/state/spill-queue.ts +12 -5
  141. package/src/responses/state.ts +18 -10
  142. package/src/responses/task-input.ts +17 -0
  143. package/src/server/background-lifecycle.ts +27 -0
  144. package/src/server/chat-completions.ts +1 -0
  145. package/src/server/chat-native.ts +28 -12
  146. package/src/server/claude-messages.ts +43 -6
  147. package/src/server/inbound-body-admission.ts +1 -0
  148. package/src/server/index/claude-intercept-lifecycle.ts +3 -1
  149. package/src/server/index/serve-options.ts +10 -2
  150. package/src/server/index/spend-ledger-lifecycle.ts +2 -1
  151. package/src/server/index/startup-warnings.ts +19 -0
  152. package/src/server/index.ts +1 -0
  153. package/src/server/management/agent-settings-routes.ts +93 -32
  154. package/src/server/management/codex-agent-role-routes.ts +4 -2
  155. package/src/server/management/codex-prompt-routes.ts +1 -0
  156. package/src/server/management/codex-role-auto-assign.ts +13 -2
  157. package/src/server/management/config-routes.ts +59 -8
  158. package/src/server/management/context.ts +2 -2
  159. package/src/server/management/shared.ts +3 -3
  160. package/src/server/messages-native-oauth.ts +9 -8
  161. package/src/server/messages-native.ts +49 -13
  162. package/src/server/messages-response-headers.ts +14 -0
  163. package/src/server/request-log-conversation.ts +48 -5
  164. package/src/server/request-log.ts +31 -2
  165. package/src/server/responses/adapter-continuation.ts +2 -2
  166. package/src/server/responses/adapter-dispatch.ts +34 -13
  167. package/src/server/responses/codex-ws-exchange.ts +17 -2
  168. package/src/server/responses/codex-ws-pool.ts +100 -13
  169. package/src/server/responses/codex-ws-wire.ts +9 -0
  170. package/src/server/responses/combo-requested-effort.ts +3 -1
  171. package/src/server/responses/core-codex-account.ts +22 -1
  172. package/src/server/responses/core-combo-native.ts +20 -3
  173. package/src/server/responses/core-combo.ts +22 -14
  174. package/src/server/responses/core-lifetime.ts +3 -36
  175. package/src/server/responses/core-options.ts +5 -0
  176. package/src/server/responses/core-replay.ts +73 -0
  177. package/src/server/responses/core.ts +3 -3
  178. package/src/server/responses/fetch-helpers.ts +26 -3
  179. package/src/server/responses/passthrough-delivery.ts +24 -2
  180. package/src/server/responses/passthrough-dispatch.ts +19 -2
  181. package/src/server/responses/request-prepare.ts +4 -0
  182. package/src/server/responses/request-send-budget.ts +112 -49
  183. package/src/server/responses/response-effects.ts +1 -0
  184. package/src/server/responses/run-turn-execution.ts +2 -0
  185. package/src/server/responses/sidecar-execution.ts +25 -16
  186. package/src/server/responses/sidecar-send-budget.ts +58 -0
  187. package/src/server/responses/ws-upstream.ts +19 -6
  188. package/src/server/startup-health-cache.ts +2 -1
  189. package/src/server/workflow-refusal.ts +3 -0
  190. package/src/service/cli.ts +20 -4
  191. package/src/service/desktop-command-guard.ts +32 -0
  192. package/src/service/desktop-startup.ts +66 -40
  193. package/src/service/desktop-supervision.d.mts +26 -0
  194. package/src/service/desktop-supervision.mjs +140 -0
  195. package/src/service/managing-cli.ts +1 -0
  196. package/src/service/orchestration.ts +46 -20
  197. package/src/service/repair.ts +25 -9
  198. package/src/service/state.ts +4 -3
  199. package/src/service/systemd.ts +17 -8
  200. package/src/service/windows-ops.ts +61 -22
  201. package/src/storage/policy-job.ts +5 -1
  202. package/src/storage/policy-worker.ts +3 -1
  203. package/src/storage/policy.ts +9 -0
  204. package/src/types/config.ts +21 -0
  205. package/src/types/request.ts +5 -0
  206. package/src/types/wire.ts +1 -0
  207. package/src/update/index.ts +57 -9
  208. package/src/update/restart-ownership.ts +10 -3
  209. package/src/update/runtime-ownership.d.mts +6 -0
  210. package/src/update/runtime-ownership.mjs +23 -7
  211. package/src/web-search/loop.ts +5 -2
  212. package/gui/dist/assets/App-7yhoys8a.js +0 -54
@@ -10,9 +10,10 @@ import {
10
10
  } from "./desktop-3p-library";
11
11
  export { resolveDesktop3pConfigLibraryPath, type Desktop3pConfigLibraryOptions } from "./desktop-3p-library";
12
12
  import { createHash, randomUUID } from "node:crypto";
13
- import { copyFileSync, existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
13
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, lstatSync, unlinkSync } from "node:fs";
14
14
  import { join } from "node:path";
15
15
  import { atomicWriteFile, readConfigDiagnostics, withConfigMutationLockSync } from "../config";
16
+ import { atomicWriteFileNoFollow } from "../config/atomic-write";
16
17
  import { claudeDesktopIntegrationEnabled } from "../codex/desired-state";
17
18
  import type { OcxClaudeDesktopProfile } from "../types";
18
19
  import {
@@ -24,6 +25,7 @@ import {
24
25
  import { nativeOpenAiContextWindow, type NativeContextLimitsInput } from "../codex/catalog";
25
26
  import { localAdmissionToken, localInferenceDestination } from "../lib/local-destinations";
26
27
  import { assertDesktop3pModelsValid } from "./desktop-3p-guard";
28
+ import { claudeSurfaceSupportsOneMillion, ONE_MILLION } from "./long-context";
27
29
 
28
30
  export interface Desktop3pModelEntry {
29
31
  name: string;
@@ -55,12 +57,12 @@ export interface Desktop3pRoutedModel {
55
57
  }
56
58
 
57
59
  /**
58
- * 1M-context eligibility, shared with the Desktop DTO so the dashboard's 1M chip can
59
- * never disagree with what the writer emits. The DTO imports this from here — keeping
60
- * the constant in this module avoids a cycle, since shared.ts already reads
61
- * claude/desktop-profile.
60
+ * The genuine-1M threshold real Anthropic rows still need. Every other row follows the
61
+ * long-window rule; the writer, the profile renderer and the dashboard DTO all decide through
62
+ * `claudeSurfaceSupportsOneMillion` (long-context.ts), so the 1M chip cannot disagree with the
63
+ * written config.
62
64
  */
63
- export const DESKTOP_SUPPORTS_1M_THRESHOLD = 1_000_000;
65
+ export const DESKTOP_SUPPORTS_1M_THRESHOLD = ONE_MILLION;
64
66
 
65
67
  /** CLI arg parsing for `ocx claude desktop` mode flags (mutually exclusive). */
66
68
  export function parseDesktop3pModeArgs(flags: string[]): { mode: Desktop3pConfigMode } | { error: string } {
@@ -251,7 +253,7 @@ function collectDesktop3pModels(
251
253
  for (const { provider, id, contextWindow } of candidates) {
252
254
  const route = `${provider}/${id}`;
253
255
  const alias = desktop3pAlias(provider, id);
254
- const supports1m = typeof contextWindow === "number" && contextWindow >= DESKTOP_SUPPORTS_1M_THRESHOLD
256
+ const supports1m = claudeSurfaceSupportsOneMillion(provider, id, contextWindow)
255
257
  ? { supports1m: true as const }
256
258
  : {};
257
259
  if (alias === id) {
@@ -317,16 +319,30 @@ export function buildDesktop3pRegistry(
317
319
  }
318
320
 
319
321
  /** Generate Claude Desktop 3P model entries from the proxy's available models. */
322
+ export interface Desktop3pModelOptions {
323
+ /**
324
+ * false under claudeCode.contextAccounting "200k": a long-window model stays selectable at 1M
325
+ * (`supports1m`) but no longer defaults to it (`prefer1m` dropped).
326
+ */
327
+ preferOneMillion?: boolean;
328
+ }
329
+
320
330
  export function generateDesktop3pModels(
321
331
  nativeSlugs: string[],
322
332
  routedModels: Array<Desktop3pRoutedModel>,
323
333
  profile?: OcxClaudeDesktopProfile,
324
334
  nativeContextCap?: NativeContextLimitsInput,
335
+ options: Desktop3pModelOptions = {},
325
336
  ): Desktop3pModelEntry[] {
326
337
  const { models, registry, realAnthropicIds } = collectDesktop3pModels(nativeSlugs, routedModels, profile, nativeContextCap);
327
338
  desktop3pRegistry = registry;
328
339
  desktop3pRealAnthropicIds = realAnthropicIds;
329
- return models;
340
+ return options.preferOneMillion === false ? models.map(({ prefer1m: _prefer1m, ...model }) => model) : models;
341
+ }
342
+
343
+ /** The Desktop model options a config asks for (one place, so writer and export agree). */
344
+ export function desktop3pModelOptions(claudeCode: { contextAccounting?: string } | undefined): Desktop3pModelOptions {
345
+ return { preferOneMillion: claudeCode?.contextAccounting !== "200k" };
330
346
  }
331
347
 
332
348
  /** Resolve an alias using the most recently generated Desktop model registry. */
@@ -382,6 +398,7 @@ export function generateDesktop3pConfig(
382
398
  mode: Desktop3pConfigMode = "static",
383
399
  profile?: OcxClaudeDesktopProfile,
384
400
  nativeContextCap?: NativeContextLimitsInput,
401
+ options: Desktop3pModelOptions = {},
385
402
  ): object {
386
403
  const base = {
387
404
  inferenceProvider: "gateway",
@@ -398,7 +415,7 @@ export function generateDesktop3pConfig(
398
415
  ...base,
399
416
  modelDiscoveryEnabled: mode === "hybrid",
400
417
  inferenceModels: (() => {
401
- const models = generateDesktop3pModels(nativeSlugs, routedModels, profile, nativeContextCap);
418
+ const models = generateDesktop3pModels(nativeSlugs, routedModels, profile, nativeContextCap, options);
402
419
  // Fail loud at the write boundary rather than ship a config Desktop rejects:
403
420
  // the output counterpart of the request-path guards.
404
421
  assertDesktop3pModelsValid(models);
@@ -662,6 +679,7 @@ export function writeDesktop3pConfig(
662
679
  profile?: OcxClaudeDesktopProfile,
663
680
  nativeContextCap?: NativeContextLimitsInput,
664
681
  lifecycleLockDeps?: ClientLifecycleLockDeps,
682
+ refreshOnly?: { appliedFingerprint: string; admit: () => boolean },
665
683
  ): { written: boolean; path: string; reason?: string; fingerprint?: string } {
666
684
  try {
667
685
  return withClientLifecycleSync(() => withConfigMutationLockSync(() => {
@@ -674,9 +692,29 @@ export function writeDesktop3pConfig(
674
692
  if (!claudeDesktopIntegrationEnabled(latest.config)) {
675
693
  return { written: false, path: resolveDesktop3pConfigLibraryPath(), reason: "desired_state_changed" };
676
694
  }
695
+ if (refreshOnly && !desktopRefreshPathsSafe(resolveDesktop3pConfigLibraryPath())) {
696
+ return { written: false, path: resolveDesktop3pConfigLibraryPath(), reason: "desktop_refresh_only_skipped" };
697
+ }
677
698
  if (connection.kind === "connected" || inspectRemoteDesktopCleanup().kind !== "absent") {
678
699
  return { written: false, path: resolveDesktop3pConfigLibraryPath(), reason: "desktop_remote_store_active" };
679
700
  }
701
+ let requiredId: string | undefined;
702
+ if (refreshOnly) {
703
+ const refused = { written: false, path: resolveDesktop3pConfigLibraryPath(), reason: "desktop_refresh_only_skipped" };
704
+ // Ownership and bytes must still match under L→C; discovery outside these locks is not authority.
705
+ if (!refreshOnly.admit() || latest.config.claudeCode?.desktopProfile?.appliedFingerprint !== refreshOnly.appliedFingerprint) return refused;
706
+ const inspected = inspectDesktop3pConfigLibrary({ appliedFingerprint: refreshOnly.appliedFingerprint });
707
+ if (inspected.kind !== "gateway_ours" || !inspected.appliedId || !inspected.selectedProfilePath) return refused;
708
+ if (!desktopRefreshPathsSafe(inspected.libraryPath, inspected.selectedProfilePath)) return refused;
709
+ const metadata = parseMetadata(join(inspected.libraryPath, "_meta.json"));
710
+ if (!isOwnedDesktopGatewayEntry(metadata.entries.find(entry => entry.id === inspected.appliedId))) return refused;
711
+ try {
712
+ const selected = JSON.parse(readFileSync(inspected.selectedProfilePath, "utf8")) as Record<string, unknown>;
713
+ mode = selected.modelDiscoveryEnabled !== true ? "static"
714
+ : Array.isArray(selected.inferenceModels) ? "hybrid" : "discovery";
715
+ } catch { return refused; }
716
+ requiredId = inspected.appliedId;
717
+ }
680
718
  // Claude Desktop runs on this machine, so it dials the unauthenticated loopback listener
681
719
  // when one is enabled — on such a hub that is the only credential-free local socket
682
720
  // (#4236) — and otherwise the bind address, which answers but demands data-plane
@@ -700,8 +738,9 @@ export function writeDesktop3pConfig(
700
738
  );
701
739
  }
702
740
  return writeDesktop3pConfigWithGenerator(() => (
703
- generateDesktop3pConfig(destination.origin, nativeSlugs, routedModels, gatewayKey, mode, profile, nativeContextCap)
704
- ));
741
+ generateDesktop3pConfig(destination.origin, nativeSlugs, routedModels, gatewayKey, mode, profile, nativeContextCap,
742
+ desktop3pModelOptions(latest.config.claudeCode))
743
+ ), requiredId && refreshOnly ? { requiredId, expectedFingerprint: refreshOnly.appliedFingerprint, admit: refreshOnly.admit } : undefined);
705
744
  }), lifecycleLockDeps);
706
745
  } catch { return { written: false, path: resolveDesktop3pConfigLibraryPath(), reason: "desktop_lifecycle_busy_or_unsafe" }; }
707
746
  }
@@ -734,17 +773,38 @@ export function writeRemoteDesktop3pConfig(options: {
734
773
  } catch { return { written: false, path: "", reason: "desktop_lifecycle_busy_or_unsafe" }; }
735
774
  }
736
775
 
776
+ /** Refresh-only writes never follow links, including a dangling backup link. */
777
+ function desktopRefreshPathsSafe(libraryPath: string, configPath?: string): boolean {
778
+ try {
779
+ if (!lstatSync(libraryPath).isDirectory() || !lstatSync(join(libraryPath, "_meta.json")).isFile()) return false;
780
+ if (configPath) {
781
+ if (!lstatSync(configPath).isFile()) return false;
782
+ try { if (lstatSync(`${configPath}.bak`).isSymbolicLink()) return false; }
783
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") return false; }
784
+ }
785
+ return true;
786
+ } catch { return false; }
787
+ }
788
+
737
789
  function writeDesktop3pConfigWithGenerator(
738
790
  generate: () => object,
791
+ refreshOnly?: { requiredId: string; expectedFingerprint: string; admit: () => boolean },
739
792
  ): { written: boolean; path: string; reason?: string; fingerprint?: string } {
740
793
  const libraryPath = resolveDesktop3pConfigLibraryPath();
741
794
  const metadataPath = join(libraryPath, "_meta.json");
742
795
  let configPath = libraryPath;
743
796
 
744
797
  try {
745
- mkdirSync(libraryPath, { recursive: true, mode: 0o700 });
798
+ if (refreshOnly && !desktopRefreshPathsSafe(libraryPath)) {
799
+ return { written: false, path: libraryPath, reason: "desktop_refresh_only_skipped" };
800
+ }
801
+ if (!refreshOnly) mkdirSync(libraryPath, { recursive: true, mode: 0o700 });
746
802
  const metadata = parseMetadata(metadataPath);
747
803
  const selected = metadata.entries.find(entry => entry?.id === metadata.appliedId && isOwnedDesktopGatewayEntry(entry));
804
+ // A refresh may reuse only the applied entry; fallback allocation would silently enroll again.
805
+ if (refreshOnly && selected?.id !== refreshOnly.requiredId) {
806
+ return { written: false, path: libraryPath, reason: "desktop_refresh_only_skipped" };
807
+ }
748
808
  const existing = selected ?? metadata.entries.find(entry => isOwnedDesktopGatewayEntry(entry) && typeof entry.id === "string");
749
809
  const id = existing?.id ?? randomUUID();
750
810
  configPath = profilePath(libraryPath, id);
@@ -757,6 +817,22 @@ function writeDesktop3pConfigWithGenerator(
757
817
  const preserved = readDesktopProfileForeignKeys(configPath);
758
818
  const configJson = JSON.stringify({ ...preserved, ...generated }, null, 2) + "\n";
759
819
  const fingerprint = createHash("sha256").update(configJson).digest("hex").slice(0, 16);
820
+ if (refreshOnly) {
821
+ atomicWriteFileNoFollow(configPath, configJson, undefined, {
822
+ validateBeforeRename: () => {
823
+ try {
824
+ if (!refreshOnly.admit() || !desktopRefreshPathsSafe(libraryPath, configPath)) throw new Error();
825
+ const freshMetadata = parseMetadata(metadataPath);
826
+ if (freshMetadata.appliedId !== refreshOnly.requiredId
827
+ || !isOwnedDesktopGatewayEntry(freshMetadata.entries.find(entry => entry.id === refreshOnly.requiredId))
828
+ || createHash("sha256").update(readFileSync(configPath)).digest("hex").slice(0, 16) !== refreshOnly.expectedFingerprint) {
829
+ throw new Error();
830
+ }
831
+ } catch { throw new Error("desktop_refresh_only_skipped"); }
832
+ },
833
+ });
834
+ return { written: true, path: configPath, fingerprint };
835
+ }
760
836
  const { backupPath } = atomicReplaceDesktopConfig(configPath, configJson);
761
837
  try {
762
838
  atomicWriteFile(metadataPath, JSON.stringify({ ...metadata, appliedId: id, entries }, null, 2) + "\n");
@@ -1,4 +1,5 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { routeSupportsOneMillion } from "./long-context";
2
3
  import type {
3
4
  OcxClaudeDesktopAssignment,
4
5
  OcxClaudeDesktopFamily,
@@ -359,7 +360,7 @@ export function renderDesktopProfile(
359
360
  name: isRealAnthropicRoute(route) ? assignment.alias : desktopProfileWireAlias(assignment.alias),
360
361
  family: assignment.family,
361
362
  isFamilyDefault: effectiveDefaults[assignment.family] === route,
362
- supports1m: typeof model.contextWindow === "number" && model.contextWindow >= 1_000_000,
363
+ supports1m: routeSupportsOneMillion(route, model.contextWindow),
363
364
  };
364
365
  });
365
366
  }
@@ -17,6 +17,7 @@ import { mkdirSync, writeFileSync } from "node:fs";
17
17
  import { homedir } from "node:os";
18
18
  import { join } from "node:path";
19
19
  import { localAdmissionToken, localInferenceDestination } from "../lib/local-destinations";
20
+ import { assertNotRealClaudeConfigUnderTest } from "../lib/test-home-guard";
20
21
  import type { OcxConfig } from "../types";
21
22
 
22
23
  export interface GatewayModelRow {
@@ -46,11 +47,27 @@ export interface GatewayModelTarget {
46
47
  /** Claude Code config dir (CLAUDE_CONFIG_DIR override honored, like the CLI). */
47
48
  export function claudeConfigDir(): string {
48
49
  const custom = process.env.CLAUDE_CONFIG_DIR;
49
- return custom && custom.length > 0 ? custom : join(homedir(), ".claude");
50
+ return custom && custom.length > 0 ? custom : join(currentUserHome(), ".claude");
51
+ }
52
+
53
+ /**
54
+ * The home Claude Code itself resolves. Claude Code runs on Node, whose `os.homedir()`
55
+ * consults HOME (POSIX) or USERPROFILE (Windows) at call time when it is set; Bun's
56
+ * `os.homedir()` keeps the value it read at startup. In production the two agree. Under
57
+ * the test preload, which rewrites HOME after Bun has started, only this one follows the
58
+ * sandbox — the cached value is the developer's real home (#6775). Exported for tests.
59
+ */
60
+ export function currentUserHome(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): string {
61
+ const fromEnv = platform === "win32" ? env.USERPROFILE : env.HOME;
62
+ return fromEnv !== undefined && fromEnv !== "" ? fromEnv : homedir();
50
63
  }
51
64
 
52
65
  /** Write the cache file; returns its path or null (best-effort, never throws). */
53
66
  export function writeGatewayModelCache(baseUrl: string, models: readonly GatewayModelRow[], configDir = claudeConfigDir()): string | null {
67
+ // Outside the best-effort catch: an armed test process must not write here, and must
68
+ // fail loudly rather than degrade to "returned null".
69
+ // The file itself too: writeFileSync follows a link at gateway-models.json.
70
+ assertNotRealClaudeConfigUnderTest(configDir, join(configDir, "cache"), join(configDir, "cache", "gateway-models.json"));
54
71
  try {
55
72
  // Mirror the CLI's usable-id filter so our file matches what it would cache.
56
73
  const usable = models.filter(m => /(claude|anthropic)/i.test(m.id));
@@ -281,7 +281,7 @@ function userMessageToItems(content: unknown, input: Rec[], elide: SkillElisionC
281
281
  pushUserMessage(input, pending);
282
282
  }
283
283
 
284
- function assistantMessageToItems(content: unknown, input: Rec[], budget: TranslatorBudget): void {
284
+ function assistantMessageToItems(content: unknown, input: Rec[], budget: TranslatorBudget, requestedModel: string, nativeReasoningReplay: Map<string, string>): void {
285
285
  if (typeof content === "string") {
286
286
  if (content.length > 0) input.push({ type: "message", role: "assistant", content: [{ type: "output_text", text: content }] });
287
287
  return;
@@ -314,6 +314,24 @@ function assistantMessageToItems(content: unknown, input: Rec[], budget: Transla
314
314
  const owned = decodeReasoningEnvelope(signature, budget);
315
315
  if (!owned) throw new AnthropicRequestError("malformed ocxr1 reasoning signature");
316
316
  if (Object.hasOwn(owned, "sig")) throw new AnthropicRequestError("OpenCodex reasoning continuity cannot be replayed as an Anthropic signature");
317
+ if (owned.nat) {
318
+ // The provider's own blob goes back only to the model that minted it; any other
319
+ // model gets the visible text alone, as before this envelope field existed.
320
+ const nat = owned.nat.model === requestedModel ? owned.nat : undefined;
321
+ if (nat) {
322
+ const previous = nativeReasoningReplay.get(nat.enc);
323
+ nativeReasoningReplay.set(nat.enc, previous === undefined || previous === nat.tag ? nat.tag : "");
324
+ }
325
+ if (nat) budget.chargeRetained(2 * nat.enc.length, { kind: "reasoning" });
326
+ if (thinking.length === 0 && !nat) break;
327
+ input.push({
328
+ type: "reasoning",
329
+ id: nat?.id ?? `rs_${crypto.randomUUID().replace(/-/g, "")}`,
330
+ summary: thinking.length > 0 ? [{ type: "summary_text", text: thinking }] : [],
331
+ ...(nat ? { encrypted_content: nat.enc } : {}),
332
+ });
333
+ break;
334
+ }
317
335
  }
318
336
  const encrypted = signature.length === 0 ? undefined : signature.startsWith(OCX_REASONING_PREFIX) ? signature : encodeReasoningEnvelope({ sig: signature }, budget);
319
337
  if (encrypted) budget.chargeRetained(2 * encrypted.length, { kind: "reasoning" });
@@ -355,6 +373,7 @@ export type ClaudeCacheKeySource = "metadata" | "system" | null;
355
373
  export interface ClaudeInboundTranslation {
356
374
  body: Rec;
357
375
  cacheKeySource: ClaudeCacheKeySource;
376
+ nativeReasoningReplay: ReadonlyMap<string, string>;
358
377
  }
359
378
 
360
379
  /**
@@ -400,6 +419,7 @@ function translateAnthropicRequest(
400
419
  }
401
420
 
402
421
  const input: Rec[] = [];
422
+ const nativeReasoningReplay = new Map<string, string>();
403
423
  const systemParts: string[] = [];
404
424
  const topLevelSystem = systemToInstructions(raw.system);
405
425
  if (topLevelSystem !== undefined) systemParts.push(topLevelSystem);
@@ -411,7 +431,7 @@ function translateAnthropicRequest(
411
431
  for (const msg of raw.messages) {
412
432
  if (!isRec(msg)) throw new AnthropicRequestError("each message must be an object");
413
433
  if (msg.role === "user") userMessageToItems(msg.content, input, elide);
414
- else if (msg.role === "assistant") assistantMessageToItems(msg.content, input, budget);
434
+ else if (msg.role === "assistant") assistantMessageToItems(msg.content, input, budget, raw.model, nativeReasoningReplay);
415
435
  else if (msg.role === "system") {
416
436
  const text = systemMessageText(msg.content);
417
437
  // Keep it where the client put it. `developer` is first-class in the Responses
@@ -531,7 +551,61 @@ function translateAnthropicRequest(
531
551
  reasoning.effort = effortForThinkingBudget(thinking.budget_tokens);
532
552
  }
533
553
  body.reasoning = reasoning;
554
+ // store:false returns a provider's encrypted reasoning only on request. The outbound
555
+ // envelope (`nat`) carries it to the client so the next turn can hand it back.
556
+ body.include = ["reasoning.encrypted_content"];
534
557
  }
535
558
 
536
- return { body, cacheKeySource };
559
+ return { body, cacheKeySource, nativeReasoningReplay };
560
+ }
561
+
562
+ /**
563
+ * Remove proxy-owned native blobs before sending a Messages body to native Anthropic.
564
+ *
565
+ * Every decode, and every re-encode on top of it, is reserved against the request's translator
566
+ * budget first (eight bytes per code unit, as `decodeReasoningEnvelope` does), and every new
567
+ * signature is charged as a retained copy, so a body of near-limit envelopes cannot allocate past the per-turn bound.
568
+ * Throws TranslatorBudgetExceededError when it would; callers answer 413.
569
+ */
570
+ export function nativeAnthropicProjection(body: Rec, budget: TranslatorBudget): Rec {
571
+ if (!Array.isArray(body.messages)) return body;
572
+ let changed = false;
573
+ const messages = body.messages.flatMap(message => {
574
+ if (!isRec(message) || message.role !== "assistant" || !Array.isArray(message.content)) return [message];
575
+ let localChanged = false;
576
+ const content = message.content.flatMap(block => {
577
+ if (!isRec(block) || block.type !== "thinking" || typeof block.signature !== "string"
578
+ || !block.signature.startsWith(OCX_REASONING_PREFIX)) return [block];
579
+ // The decoded object stays alive while it is re-encoded, so its reservation is held until
580
+ // the new signature exists; the encode copies get their own reservation on top of it.
581
+ const decodeReservation = budget.reserveTransient(8 * block.signature.length, { kind: "reasoning" });
582
+ try {
583
+ let decoded: unknown;
584
+ try { decoded = JSON.parse(Buffer.from(block.signature.slice(OCX_REASONING_PREFIX.length), "base64").toString("utf8")); }
585
+ catch { decoded = undefined; }
586
+ if (!isRec(decoded)) { localChanged = true; return []; }
587
+ if (!Object.hasOwn(decoded, "nat")) return [block];
588
+ localChanged = true;
589
+ const { nat: _nat, ...rest } = decoded;
590
+ if (!rest.sig && !rest.red && !rest.krc && !(typeof rest.txt === "string" && rest.txt.length > 0)) return [];
591
+ // The re-encoded envelope is never larger than the decoded one (a field was removed), so a
592
+ // decode-sized reservation bounds the stringify, buffer and base64 copies before they exist.
593
+ const encodeReservation = budget.reserveTransient(8 * block.signature.length, { kind: "reasoning" });
594
+ let signature: string;
595
+ try {
596
+ signature = OCX_REASONING_PREFIX + Buffer.from(JSON.stringify(rest), "utf8").toString("base64");
597
+ } finally {
598
+ encodeReservation.release();
599
+ }
600
+ budget.chargeRetained(2 * signature.length, { kind: "reasoning" });
601
+ return [{ ...block, signature }];
602
+ } finally {
603
+ decodeReservation.release();
604
+ }
605
+ });
606
+ if (!localChanged) return [message];
607
+ changed = true;
608
+ return content.length ? [{ ...message, content }] : [];
609
+ });
610
+ return changed ? { ...body, messages } : body;
537
611
  }
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { readdirSync, unlinkSync } from "node:fs";
16
16
  import { join } from "node:path";
17
+ import { assertNotRealClaudeConfigUnderTest } from "../../lib/test-home-guard";
17
18
  import type { ClaudeFirstPartyDesired } from "../first-party-settings";
18
19
  import { classifyInterceptClient } from "./client-class";
19
20
  import { BOOTSTRAP_MAX_DECODED_BYTES, injectPickerModels, type PickerModelEntry } from "./picker-bootstrap";
@@ -150,6 +151,8 @@ export async function rewriteCliCatalogResponse(
150
151
  */
151
152
  export function invalidateClaudeCodeServedCatalog(claudeDir: string): number {
152
153
  const dir = join(claudeDir, "cache", "model-catalog");
154
+ // Outside the catch below: an armed test process must not prune the real Claude cache (#6775).
155
+ assertNotRealClaudeConfigUnderTest(claudeDir, dir);
153
156
  let names: string[];
154
157
  try { names = readdirSync(dir); } catch { return 0; } // no-excuse-ok: catch -- no cache directory means nothing to drop.
155
158
  let removed = 0;
@@ -1,5 +1,5 @@
1
1
  import { X509Certificate } from "node:crypto";
2
- import { constants, closeSync, fstatSync, lstatSync, openSync, readSync, realpathSync, rmSync, writeFileSync, type Stats } from "node:fs";
2
+ import { constants, closeSync, fstatSync, lstatSync, openSync, readSync, realpathSync, rmSync, writeFileSync, type BigIntStats } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import {
5
5
  decodePickerCaCredential, openPickerCaCredential, pickerCaConfigId, readPickerCaCredential,
@@ -21,18 +21,19 @@ export function canonicalPickerConfigDir(configDir: string): string {
21
21
 
22
22
  /** Public records still cannot follow symlinks or accept oversized/malformed recovery data. */
23
23
  function readState(path: string, configId: string, initialization: boolean): Initialization | AuthorityMetadata | null {
24
- let expected: Stats;
25
- try { expected = lstatSync(path); }
24
+ // BigInt stats: a Windows file ID exceeds 2^53, so Number ino loses low bits and two files can compare equal.
25
+ let expected: BigIntStats;
26
+ try { expected = lstatSync(path, { bigint: true }); }
26
27
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw new Error("picker_ca_metadata_unsafe"); }
27
28
  if (expected.isSymbolicLink()) throw new Error("picker_ca_metadata_unsafe");
28
29
  let fd: number;
29
30
  try { fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
30
31
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw new Error("picker_ca_metadata_unsafe"); }
31
32
  try {
32
- const stat = fstatSync(fd);
33
+ const stat = fstatSync(fd, { bigint: true });
33
34
  if (stat.dev !== expected.dev || stat.ino !== expected.ino) throw new Error("picker_ca_metadata_unsafe");
34
- if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_PUBLIC_STATE_BYTES
35
- || (process.platform !== "win32" && stat.uid !== process.getuid!())) throw new Error();
35
+ if (!stat.isFile() || stat.nlink !== 1n || stat.size > BigInt(MAX_PUBLIC_STATE_BYTES)
36
+ || (process.platform !== "win32" && stat.uid !== BigInt(process.getuid!()))) throw new Error();
36
37
  const bytes = Buffer.alloc(MAX_PUBLIC_STATE_BYTES + 1);
37
38
  let used = 0;
38
39
  while (used < bytes.length) {
@@ -7,7 +7,8 @@ import { dirname } from "node:path";
7
7
  import { nativeOpenAiContextWindow, type NativeContextLimitsInput } from "../../codex/catalog";
8
8
  import type { OcxClaudeDesktopProfile } from "../../types";
9
9
  import { aliasForRoute, claudeCodeNativeAlias } from "../alias";
10
- import { AUTO_CONTEXT_OFF, stripOneMillionMarker, withOneMillionMarker } from "../context-windows";
10
+ import { AUTO_CONTEXT_OFF, stripOneMillionMarker, UNPAIRED_AUTO_CONTEXT, withOneMillionMarker, type AutoContextMode } from "../context-windows";
11
+ import { isAnthropicClaudeRoute } from "../long-context";
11
12
  import { activeDesktop3pAlias, displayModelId, resolveDesktop3pAlias, type Desktop3pRoutedModel } from "../desktop-3p";
12
13
  import { reconcileDesktopProfile, renderDesktopProfile, type DesktopProfileModel } from "../desktop-profile";
13
14
  import type { PickerModelEntry } from "./picker-bootstrap";
@@ -17,6 +18,8 @@ export interface PickerRouteInput {
17
18
  routedModels: Desktop3pRoutedModel[];
18
19
  profile?: OcxClaudeDesktopProfile;
19
20
  nativeContextCap?: NativeContextLimitsInput;
21
+ /** resolveAutoContext(config.claudeCode); only its contextAccounting "200k" opt-in matters here. */
22
+ auto?: AutoContextMode;
20
23
  }
21
24
 
22
25
  /** Candidate routes in the gateway profile's order and with its labels. */
@@ -46,9 +49,14 @@ function splitRoute(route: string): { provider: string; id: string } {
46
49
  return { provider: route.slice(0, slash), id: route.slice(slash + 1) };
47
50
  }
48
51
 
49
- /** Desktop runners do not inherit the proxy's compaction env: mark only real >=1M windows. */
50
- function pickerSelector(alias: string, contextWindow: number | undefined): string {
51
- return withOneMillionMarker(alias, contextWindow === undefined ? {} : { [alias]: contextWindow }, AUTO_CONTEXT_OFF)!;
52
+ /**
53
+ * Desktop runners do not inherit the proxy's compaction env, so a long window (>= the default
54
+ * compact window) is marked on the strength of the `prompt is too long` recovery instead
55
+ * (devlog/_plan/261009_claude_1m_default/020). Real Anthropic models need a genuine 1M.
56
+ */
57
+ function pickerSelector(alias: string, contextWindow: number | undefined, provider: string, id: string, auto?: AutoContextMode): string {
58
+ const mode = auto?.accounting200k ? auto : isAnthropicClaudeRoute(provider, id) ? AUTO_CONTEXT_OFF : UNPAIRED_AUTO_CONTEXT;
59
+ return withOneMillionMarker(alias, contextWindow === undefined ? {} : { [alias]: contextWindow }, mode)!;
52
60
  }
53
61
 
54
62
  export function buildPickerModels(input: PickerRouteInput): PickerModelEntry[] {
@@ -61,7 +69,7 @@ export function buildPickerModels(input: PickerRouteInput): PickerModelEntry[] {
61
69
  const alias = provider === "native" ? claudeCodeNativeAlias(id) : aliasForRoute(provider, id);
62
70
  if (!alias || seen.has(alias)) continue;
63
71
  seen.add(alias);
64
- out.push({ id: pickerSelector(alias, model.contextWindow), name: model.label,
72
+ out.push({ id: pickerSelector(alias, model.contextWindow, provider, id, input.auto), name: model.label,
65
73
  ...(model.contextWindow === undefined ? {} : { contextWindow: model.contextWindow }) });
66
74
  }
67
75
  return out;
@@ -81,7 +89,7 @@ export function buildCliPickerModels(input: PickerRouteInput): PickerModelEntry[
81
89
  const alias = activeDesktop3pAlias(provider, id);
82
90
  if (seen.has(alias) || resolveDesktop3pAlias(alias) !== model.route) continue;
83
91
  seen.add(alias);
84
- out.push({ id: pickerSelector(alias, model.contextWindow), name: model.label,
92
+ out.push({ id: pickerSelector(alias, model.contextWindow, provider, id, input.auto), name: model.label,
85
93
  description: `opencodex · ${model.route}`, route: model.route,
86
94
  ...(model.contextWindow === undefined ? {} : { contextWindow: model.contextWindow }) });
87
95
  }
@@ -1,6 +1,7 @@
1
1
  import { mkdirSync, readFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { atomicWriteFile } from "../../config/atomic-write";
4
+ import { assertNotRealClaudeConfigUnderTest } from "../../lib/test-home-guard";
4
5
  import { claudeConfigDir } from "../auth-detect";
5
6
  import { invalidateClaudeCodeServedCatalog } from "./cli-catalog";
6
7
 
@@ -112,6 +113,8 @@ export function inspectClaudeInterceptSettings(
112
113
  }
113
114
 
114
115
  function writeSettings(path: string, doc: SettingsDoc): void {
116
+ // An armed test process must not rewrite the real Claude settings.json (#6775).
117
+ assertNotRealClaudeConfigUnderTest(dirname(path), path);
115
118
  mkdirSync(dirname(path), { recursive: true });
116
119
  // The managed env embeds the proxy token, so the file must stay owner-only:
117
120
  // atomicWriteFile applies the real NTFS ACL on Windows where chmod is a no-op.
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Long-context thresholds shared by every Claude surface
3
+ * (devlog/_plan/261009_claude_1m_default/020_long_context_eligibility.md).
4
+ *
5
+ * A leaf module: desktop-3p.ts and desktop-profile.ts need the predicate, and context-windows.ts
6
+ * already imports desktop-3p.ts, so the predicate cannot live there.
7
+ */
8
+ import { isAnthropicInstanceId } from "../providers/anthropic-instance-id";
9
+
10
+ export const ONE_MILLION = 1_000_000;
11
+
12
+ /** A window at or below this is Claude Code's own default accounting; widening it gains nothing. */
13
+ export const AUTO_CONTEXT_FLOOR = 200_000;
14
+
15
+ /**
16
+ * Auto-context defaults (devlog 260712 020, user-approved).
17
+ *
18
+ * The compact window is the token count at which Claude Code starts compacting, and it is
19
+ * also the floor `shouldMarkOneMillion` uses — a model may only carry the marker if it can
20
+ * host this window. 350,000 was chosen when the widest native row advertised 372,000.
21
+ *
22
+ * It now matches the auto-compaction limit the Codex catalog ships for the same models
23
+ * (`nativeAutoCompactLimit`: 829,800 against the 922,000 native window). Leaving the two
24
+ * apart meant one model compacting at 350k under Claude Code and at 829,800 under Codex.
25
+ * The value stays clear of the measured 922,000 ceiling by ~92k, so compaction still has
26
+ * room to run before the upstream refuses.
27
+ */
28
+ export const AUTO_COMPACT_WINDOW_DEFAULT = 829_800;
29
+
30
+ /**
31
+ * Whether a window earns the 1M selection on a surface whose Claude Code runner may not inherit
32
+ * CLAUDE_CODE_AUTO_COMPACT_WINDOW (Desktop pickers, discovery, Desktop 3P, generated subagents).
33
+ * A window >= 1M always does. A smaller one does when it can host the default compact window, so
34
+ * a runner that has the variable compacts in time, and one that lacks it overflows into the
35
+ * `prompt is too long` envelope (anthropicErrorBody) and compacts reactively. The floor is fixed
36
+ * on purpose: a custom compact window must not re-admit a 372k route (#854).
37
+ */
38
+ export function isLongContextWindow(window: number | undefined): boolean {
39
+ if (typeof window !== "number" || window <= 0) return false;
40
+ return window >= ONE_MILLION || (window > AUTO_CONTEXT_FLOOR && window >= AUTO_COMPACT_WINDOW_DEFAULT);
41
+ }
42
+
43
+ /**
44
+ * A Claude model on an Anthropic-named route. Claude windows are 200k or a genuine 1M and a bare
45
+ * id rides the native passthrough, so the long-window rule never widens one: a Claude row listed
46
+ * under 1M is a capped one, and on a runner without the compaction env it keeps the 200k
47
+ * accounting it had before long windows were widened. Keyed on the model id as well, so a
48
+ * configured gateway that only shares the name `anthropic2` and serves other models keeps the
49
+ * long-window rule. A custom `anthropic2` gateway serving Claude below 1M is treated like a pool
50
+ * row on these surfaces, which is the pre-existing (unwidened) behavior.
51
+ */
52
+ export function isAnthropicClaudeRoute(provider: string, modelId: string): boolean {
53
+ return isAnthropicInstanceId(provider) && modelId.startsWith("claude-");
54
+ }
55
+
56
+ /** Desktop 3P / picker / discovery / dashboard 1M eligibility for one provider route. */
57
+ export function claudeSurfaceSupportsOneMillion(provider: string, modelId: string, window: number | undefined): boolean {
58
+ if (isAnthropicClaudeRoute(provider, modelId)) return typeof window === "number" && window >= ONE_MILLION;
59
+ return isLongContextWindow(window);
60
+ }
61
+
62
+ /** Same, for a `provider/id` route string. */
63
+ export function routeSupportsOneMillion(route: string, window: number | undefined): boolean {
64
+ const slash = route.indexOf("/");
65
+ return claudeSurfaceSupportsOneMillion(route.slice(0, slash), route.slice(slash + 1), window);
66
+ }
@@ -19,7 +19,8 @@ import { orderForModelPicker, catalogModelEfforts, nativeEffortClamp, nativeOpen
19
19
  import { claudeCodeAlias, claudeCodeNativeAlias } from "./alias";
20
20
  import { cursorFastIdFor } from "../adapters/cursor/catalog";
21
21
  import { desktop3pAlias } from "./desktop-3p";
22
- import { AUTO_CONTEXT_OFF, type AutoContextMode } from "./context-windows";
22
+ import { AUTO_CONTEXT_OFF, shouldMarkOneMillion, UNPAIRED_AUTO_CONTEXT, type AutoContextMode } from "./context-windows";
23
+ import { isAnthropicClaudeRoute } from "./long-context";
23
24
 
24
25
  const MODEL_INFO_CREATED_AT = "2026-01-01T00:00:00Z";
25
26
  const ANTHROPIC_EFFORT_RUNGS = new Set(["low", "medium", "high", "xhigh", "max"]);
@@ -144,23 +145,25 @@ export function buildAnthropicModelInfos(
144
145
  : aliasForRoute(m.provider, m.id);
145
146
  }),
146
147
  ]);
147
- // [1m] picker variant (devlog 260712 B1): Claude Code accounts exactly 1M for ids
148
- // carrying the marker (2.1.207 binary: /\[1m\]/i → 1e6, compaction preserved), so
149
- // ONLY models with an authoritative >=1M window get a second selectable row —
150
- // the auto-context widening that let a 372K route carry the marker (and be
151
- // over-filled) is the #854 defect and does not come back. Guards (audit R1#11):
152
- // same dedupe set, never double-suffix.
148
+ // [1m] picker variant (devlog 260712 B1; widened in devlog/_plan/261009_claude_1m_default/020):
149
+ // Claude Code accounts exactly 1M for ids carrying the marker (2.1.207 binary: /\[1m\]/i -> 1e6,
150
+ // compaction preserved). A discovery client may lack CLAUDE_CODE_AUTO_COMPACT_WINDOW, so the
151
+ // rule is the fixed unpaired one (long-context.ts), not the configurable launch compact window:
152
+ // a custom 350k window must not re-admit a 372k route (#854). The server's auto mode only turns
153
+ // widening off (autoContext: false / maxContextTokens), falling back to >= 1M. Base and Fast
154
+ // rows stay unmarked: this list is a choice list. Guards (audit R1#11): same dedupe set, never
155
+ // double-suffix.
156
+ const variantMode = auto.enabled ? UNPAIRED_AUTO_CONTEXT : AUTO_CONTEXT_OFF;
153
157
  const push1mVariant = (
154
158
  base: AnthropicModelInfo,
155
159
  contextWindow: number | undefined,
156
160
  maxInputTokens?: number,
157
161
  selectorId?: string,
162
+ mode: AutoContextMode = variantMode,
158
163
  ) => {
159
- // The [1m] marker makes Claude Code account 1e6 tokens for the row, so it
160
- // may only name models whose AUTHORITATIVE effective window is >= 1M —
161
- // never the auto-context widening, which would mark a 372K route and have
162
- // Claude Code over-fill it (the #854 defect).
163
- if (contextWindow === undefined || contextWindow < ONE_MILLION) return;
164
+ // A window >= 1M always earns the row; a long window earns it under the unpaired rule,
165
+ // because an overflow is answered as `prompt is too long`, which Claude Code compacts on.
166
+ if (!shouldMarkOneMillion(contextWindow, mode)) return;
164
167
  if (base.id.includes("[1m]")) return;
165
168
  const id = selectorId ?? `${base.id}[1m]`;
166
169
  if (seen.has(id)) return;
@@ -170,9 +173,9 @@ export function buildAnthropicModelInfos(
170
173
  // (measured — see devlog/_plan/260817_native_gpt56_1m_context/001_measurement_evidence.md).
171
174
  // Advertising the flat 1e6 there would invite mid-session context_length_exceeded, so the
172
175
  // variant reports whichever of the two is smaller.
173
- const advertised = typeof maxInputTokens === "number" && maxInputTokens > 0
174
- ? Math.min(ONE_MILLION, maxInputTokens)
175
- : ONE_MILLION;
176
+ // A long window under 1M must not be advertised as 1e6 input either.
177
+ const ceiling = typeof maxInputTokens === "number" && maxInputTokens > 0 ? maxInputTokens : contextWindow;
178
+ const advertised = typeof ceiling === "number" && ceiling > 0 ? Math.min(ONE_MILLION, ceiling) : ONE_MILLION;
176
179
  out.push({ ...base, id, display_name: `${base.display_name} · 1M`, max_input_tokens: advertised });
177
180
  };
178
181
  /**
@@ -251,7 +254,7 @@ export function buildAnthropicModelInfos(
251
254
  && listedModelId.startsWith("claude-fable-")
252
255
  ? `${claudeCodeNativeAlias(listedModelId)}[1m]`
253
256
  : undefined;
254
- push1mVariant(info, m.contextWindow, routedMaxInput, oneMillionSelector);
257
+ push1mVariant(info, m.contextWindow, routedMaxInput, oneMillionSelector, isAnthropicClaudeRoute(m.provider, m.id) ? AUTO_CONTEXT_OFF : variantMode);
255
258
  // The whole model is passed, not a (provider, id) pair: a combo row lives in its own
256
259
  // namespace with no config.providers entry, so the caller classifies it from the
257
260
  // aggregated supportsServiceTier the row already carries.