@bitkyc08/opencodex 2.100.3 → 2.100.4

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 (181) hide show
  1. package/AGENTS_INSTALL.md +23 -1
  2. package/bin/ocx.mjs +8 -1
  3. package/gui/dist/assets/{App-Dnb6VMsP.js → App-DcpyI78f.js} +20 -19
  4. package/gui/dist/assets/{Tray-BV4ms9U9.js → Tray-CzjPJprT.js} +1 -1
  5. package/gui/dist/assets/brand-mark-BTIi7e69.js +1 -0
  6. package/gui/dist/assets/index-DJxM-imn.css +2 -0
  7. package/gui/dist/assets/index-DVgU6S3y.js +138 -0
  8. package/gui/dist/assets/{segment-thumb-features-DXSidY6D.js → segment-thumb-features-Bn6Y-g3R.js} +1 -1
  9. package/gui/dist/classic/assets/{App-DA-scMPq.js → App-eYJAyNHM.js} +19 -18
  10. package/gui/dist/classic/assets/{Tray-BrHaVRAq.js → Tray-xHMYxLkV.js} +1 -1
  11. package/gui/dist/classic/assets/index-DSaVRW4F.js +138 -0
  12. package/gui/dist/classic/assets/quota-summary-DyzHlkFl.js +1 -0
  13. package/gui/dist/classic/index.html +1 -1
  14. package/gui/dist/index.html +2 -2
  15. package/native/ocx-child/src/cli.rs +5 -3
  16. package/native/ocx-child/src/codex_home.rs +1 -0
  17. package/package.json +2 -2
  18. package/src/adapters/anthropic/per-message-effort.ts +296 -0
  19. package/src/adapters/anthropic.ts +3 -0
  20. package/src/adapters/claude-cli/adapter.ts +1 -0
  21. package/src/adapters/devin/cloud-direct/chat.ts +71 -14
  22. package/src/adapters/google-errors.ts +14 -2
  23. package/src/adapters/qoder/adapter.ts +9 -1
  24. package/src/adapters/zed.ts +4 -2
  25. package/src/claude/desktop-remote-store.ts +60 -10
  26. package/src/cli/account-api.ts +4 -0
  27. package/src/cli/account-auth.ts +30 -2
  28. package/src/cli/account-extended.ts +33 -2
  29. package/src/cli/capabilities-access-remote.ts +3 -3
  30. package/src/cli/capabilities-accounts.ts +3 -3
  31. package/src/cli/capabilities-base.ts +11 -6
  32. package/src/cli/capabilities-observe-system.ts +2 -2
  33. package/src/cli/claude.ts +3 -3
  34. package/src/cli/disconnect-runtime.ts +16 -6
  35. package/src/cli/dispatch.ts +7 -1
  36. package/src/cli/index.ts +2 -2
  37. package/src/cli/link-apply-restart.ts +4 -2
  38. package/src/cli/link-routes.ts +4 -1
  39. package/src/cli/link.ts +5 -4
  40. package/src/cli/preflight-exemptions.ts +3 -0
  41. package/src/cli/registry.ts +5 -2
  42. package/src/cli/resolve.ts +23 -8
  43. package/src/cli/restart-failure.ts +11 -1
  44. package/src/cli/runtime-api.ts +4 -0
  45. package/src/cli/status.ts +4 -1
  46. package/src/cli/system-command.ts +1 -1
  47. package/src/cli/system-restart-client.ts +9 -3
  48. package/src/cli/system-settings-parity.ts +2 -1
  49. package/src/client/connect.ts +63 -9
  50. package/src/client/desktop-refusal.ts +38 -0
  51. package/src/client/lifecycle-lock.ts +29 -4
  52. package/src/client/runtime-restart.ts +27 -15
  53. package/src/client/runtime.ts +4 -2
  54. package/src/client/state.ts +14 -0
  55. package/src/codex/account-pause.ts +4 -0
  56. package/src/codex/account-runtime-state.ts +4 -0
  57. package/src/codex/auth-api/main-account-probe.ts +3 -1
  58. package/src/codex/auth-api/main-hard-lock-refusal-read.ts +172 -0
  59. package/src/codex/auth-context.ts +40 -2
  60. package/src/codex/catalog/build-entries.ts +10 -0
  61. package/src/codex/catalog/derive-entry.ts +7 -0
  62. package/src/codex/catalog/reserve-warn.ts +7 -5
  63. package/src/codex/catalog/reserve.ts +4 -3
  64. package/src/codex/catalog/retained-sync.ts +2 -0
  65. package/src/codex/catalog/routed-defaults.ts +35 -0
  66. package/src/codex/convergence.ts +2 -0
  67. package/src/codex/loopback-target.ts +22 -8
  68. package/src/codex/main-account.ts +88 -29
  69. package/src/codex/native-main-auth-file.ts +14 -0
  70. package/src/codex/native-main-credentials.ts +270 -0
  71. package/src/codex/native-main-owner.ts +3 -0
  72. package/src/codex/native-main-refresh-mode.ts +14 -1
  73. package/src/codex/quota.ts +63 -14
  74. package/src/combos/failover.ts +12 -1
  75. package/src/combos/index.ts +5 -0
  76. package/src/combos/resolve.ts +115 -19
  77. package/src/config/diagnostics.ts +3 -0
  78. package/src/config/live-reconcile.ts +6 -3
  79. package/src/config/load-degrade.ts +2 -0
  80. package/src/config/persisted-mutation.ts +2 -2
  81. package/src/config/persisted-projections.ts +18 -0
  82. package/src/config/process-state.ts +4 -3
  83. package/src/config/reserve-capability.ts +96 -0
  84. package/src/config/schema/config-schema.ts +6 -0
  85. package/src/config/schema/leaf-validators.ts +2 -0
  86. package/src/config/schema/routed-catalog-defaults.ts +49 -0
  87. package/src/config.ts +7 -7
  88. package/src/desktop-update/acquire.ts +202 -0
  89. package/src/desktop-update/cli.ts +168 -0
  90. package/src/desktop-update/drain.ts +40 -0
  91. package/src/desktop-update/headless.ts +285 -0
  92. package/src/desktop-update/image.ts +85 -0
  93. package/src/desktop-update/install.ts +53 -0
  94. package/src/desktop-update/msi.ts +72 -0
  95. package/src/desktop-update/release.ts +128 -0
  96. package/src/desktop-update/runtime.ts +155 -0
  97. package/src/desktop-update/staging.ts +118 -0
  98. package/src/desktop-update/trust.ts +45 -0
  99. package/src/generated/compatibility-version.json +246 -130
  100. package/src/images/fulfill-video.ts +3 -3
  101. package/src/images/loop.ts +6 -2
  102. package/src/images/plan.ts +147 -11
  103. package/src/images/types.ts +13 -4
  104. package/src/images/xai-video-client.ts +72 -10
  105. package/src/lib/gcp-adc.ts +48 -4
  106. package/src/lib/offline-resend.ts +150 -0
  107. package/src/lib/paced-stream.ts +3 -3
  108. package/src/lib/provider-outbound.ts +17 -6
  109. package/src/lib/request-failure-model.ts +2 -0
  110. package/src/lib/response-body-inactivity.ts +23 -1
  111. package/src/lib/upstream-retry.ts +38 -5
  112. package/src/link/explicit-route.ts +4 -4
  113. package/src/link/remote-windows.ts +79 -31
  114. package/src/link/residual-recovery.ts +20 -8
  115. package/src/messaging/budget.ts +23 -5
  116. package/src/messaging/rpc.ts +4 -4
  117. package/src/oauth/antigravity-risk.ts +126 -0
  118. package/src/oauth/generic-account-failover.ts +89 -18
  119. package/src/oauth/generic-session-affinity.ts +10 -3
  120. package/src/oauth/login-cli.ts +35 -1
  121. package/src/oauth/pool-kernel.ts +3 -3
  122. package/src/providers/anthropic-billing-refusal.ts +27 -3
  123. package/src/providers/google-vertex-model-discovery.ts +6 -1
  124. package/src/providers/model-rename-fields.ts +2 -0
  125. package/src/providers/quota/workbuddy.ts +6 -2
  126. package/src/providers/workbuddy-credit-balance.ts +125 -16
  127. package/src/responses/effort-history.ts +732 -0
  128. package/src/routing/history/integrity.ts +41 -4
  129. package/src/server/auth-cors.ts +13 -3
  130. package/src/server/codex-model-list.ts +2 -1
  131. package/src/server/direct-local-http.ts +26 -3
  132. package/src/server/index/link-listener.ts +20 -14
  133. package/src/server/index/serve-options.ts +1 -0
  134. package/src/server/index.ts +3 -2
  135. package/src/server/link-turn.ts +17 -5
  136. package/src/server/management/config-routes.ts +39 -3
  137. package/src/server/management/link-child-preflight.ts +1 -1
  138. package/src/server/management/link-route-edit.ts +20 -1
  139. package/src/server/management/oauth-account-routes.ts +22 -5
  140. package/src/server/management/provider-overwrite-carry.ts +3 -0
  141. package/src/server/management/provider-routes.ts +4 -4
  142. package/src/server/management/static-catalog-probe.ts +33 -0
  143. package/src/server/proxy-liveness.ts +54 -9
  144. package/src/server/relay.ts +6 -1
  145. package/src/server/request-log-conversation.ts +2 -2
  146. package/src/server/request-log.ts +5 -1
  147. package/src/server/reserve-capability-startup.ts +32 -0
  148. package/src/server/responses/adapter-delivery.ts +2 -0
  149. package/src/server/responses/adapter-dispatch.ts +31 -10
  150. package/src/server/responses/antigravity-fault-rotation.ts +24 -0
  151. package/src/server/responses/antigravity-validation-refusal.ts +43 -6
  152. package/src/server/responses/combo-selection-keepalive.ts +254 -0
  153. package/src/server/responses/core-combo.ts +24 -9
  154. package/src/server/responses/core-errors.ts +9 -6
  155. package/src/server/responses/core-options.ts +8 -0
  156. package/src/server/responses/core.ts +21 -0
  157. package/src/server/responses/estimated-usage.ts +115 -0
  158. package/src/server/responses/jev-model-invoke.ts +7 -2
  159. package/src/server/responses/passthrough-completion.ts +6 -3
  160. package/src/server/responses/passthrough-delivery.ts +47 -8
  161. package/src/server/responses/passthrough-dispatch.ts +3 -0
  162. package/src/server/responses/request-prepare.ts +9 -5
  163. package/src/server/responses/sidecar-execution.ts +5 -0
  164. package/src/service/desktop-supervision.d.mts +2 -0
  165. package/src/service/desktop-supervision.mjs +5 -0
  166. package/src/stall-timeout.ts +11 -0
  167. package/src/types/config.ts +15 -92
  168. package/src/types/provider.ts +13 -0
  169. package/src/types/request.ts +19 -0
  170. package/src/types/routed-catalog-defaults.ts +17 -0
  171. package/src/types/routing-profile.ts +90 -0
  172. package/src/types.ts +1 -0
  173. package/src/update/index.ts +1 -1
  174. package/src/usage/log.ts +14 -4
  175. package/src/usage/telemetry-contract.ts +1 -0
  176. package/src/web-search/passthrough-bridge.ts +7 -0
  177. package/gui/dist/assets/brand-mark-XOLJbomA.js +0 -1
  178. package/gui/dist/assets/index-DCdXsMyZ.js +0 -105
  179. package/gui/dist/assets/index-DQtCRNAw.css +0 -2
  180. package/gui/dist/classic/assets/index-BqOaGLf5.js +0 -105
  181. package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +0 -1
@@ -535,7 +535,7 @@ export class CodexReserveUnavailableError extends CodexAccountCooldownError {
535
535
  this.name = "CodexReserveUnavailableError";
536
536
  this.message = "Codex Reserve is unavailable for this main credential."
537
537
  + " Use the stored main login or its matching caller credential, and retry when OpenAI grants Reserve access."
538
- + " Reserve compatibility requires the effective local Desktop authless opt-in; it cannot switch accounts automatically.";
538
+ + " Reserve compatibility requires the local Reserve setting (codexReserveEnabled); it cannot switch accounts automatically.";
539
539
  }
540
540
  }
541
541
 
@@ -587,7 +587,8 @@ export class CodexRecoveryWithheldError extends CodexAccountCooldownError {
587
587
  }
588
588
 
589
589
  export type CodexAuthPolicyConfig = Readonly<Pick<OcxConfig,
590
- "codexMainAccountHardLock" | "codexMainAccountHardLockThresholds" | "codexDesktopAuthless" | "runtimeRole" | "pausedCodexAccountIds"
590
+ "codexMainAccountHardLock" | "codexMainAccountHardLockThresholds" | "codexDesktopAuthless" | "codexReserveEnabled"
591
+ | "codexReserveMigration" | "runtimeRole" | "pausedCodexAccountIds"
591
592
  | "creditCodexAccountIds" | "codexAccounts" | "codexUseRemainingQuotaAccountIds"
592
593
  >>;
593
594
 
@@ -1063,6 +1064,43 @@ export async function resolveCodexAuthContext(
1063
1064
  config: OcxConfig,
1064
1065
  mode: CodexAccountMode,
1065
1066
  options: ResolveCodexAuthContextOptions = {},
1067
+ ): Promise<CodexAuthContext> {
1068
+ try {
1069
+ return await resolveCodexAuthContextWithHint(headers, config, mode, options);
1070
+ } catch (error) {
1071
+ // #8113: a refusal resting on a reading older than 60 s first gets one fresh WHAM read, so a
1072
+ // reset redeemed outside OpenCodex lifts the lock now instead of at the next paced recovery.
1073
+ if (!(error instanceof CodexMainAccountHardLockError)) throw error;
1074
+ const { refreshMainHardLockBeforeRefusal } = await import("./auth-api/main-hard-lock-refusal-read");
1075
+ if (!await refreshMainHardLockBeforeRefusal(config, options.codexAuthPolicy ?? config, options.signal,
1076
+ callerOwnedMainRefusal(headers, mode, options))) throw error;
1077
+ return await resolveCodexAuthContextWithHint(headers, config, mode, options);
1078
+ }
1079
+ }
1080
+
1081
+ /**
1082
+ * A refusal for a request that authenticates as the main login itself. That request may never
1083
+ * read the physical main credential, so its fresh read uses the caller's own bearer (#8113).
1084
+ * Any other refusal is about the proxy-owned main credential.
1085
+ */
1086
+ function callerOwnedMainRefusal(
1087
+ headers: Headers, mode: CodexAccountMode, options: ResolveCodexAuthContextOptions,
1088
+ ): { bearer: string; accountId: string } | null | undefined {
1089
+ if (options.substituteMainCredentialForDirect === true || !hasCallerCodexBearer(headers)) return undefined;
1090
+ if (mode !== "direct" && options.requestScopedMainCredential !== true) return undefined;
1091
+ // An explicit stored-account selection resolves the proxy-owned credential, whatever bearer arrived.
1092
+ if (options.accountId !== undefined && options.requestScopedMainCredential !== true) return undefined;
1093
+ const bearer = authorizationCredential(headers);
1094
+ const accountId = headers.get("chatgpt-account-id") ?? (bearer ? extractAccountId(undefined, bearer) : undefined);
1095
+ // Caller-owned without a usable credential: no read at all, never the physical one.
1096
+ return bearer && accountId ? { bearer, accountId } : null;
1097
+ }
1098
+
1099
+ async function resolveCodexAuthContextWithHint(
1100
+ headers: Headers,
1101
+ config: OcxConfig,
1102
+ mode: CodexAccountMode,
1103
+ options: ResolveCodexAuthContextOptions,
1066
1104
  ): Promise<CodexAuthContext> {
1067
1105
  // Filled by the inner resolver with the request's own fenced model evidence, so the hint obeys it.
1068
1106
  const eligibility: RecoveryHintEligibility = {};
@@ -52,6 +52,7 @@ import { PICKER_ORDER_PRIORITY_BASE, SPAWN_PRIORITY_FIELD } from "./subagent-ros
52
52
  import { applyConfiguredUltraFast, configuredUltraFastSlugs } from "./configured-tiers";
53
53
  import { applyNativeUltraFastTier } from "./native-ultrafast";
54
54
  import { applyNativePriority, retainedNativeSourcePriorities, type NativePrioritySource } from "./native-priority";
55
+ import type { RoutedCatalogDefaults } from "../../config/schema/routed-catalog-defaults";
55
56
 
56
57
  export interface ObservedCatalogEntryBuildInput {
57
58
  readonly template: RawEntry | null;
@@ -76,6 +77,8 @@ export interface ObservedCatalogEntryBuildInput {
76
77
  /** Codex-only manual selector metadata; deliberately independent of live permission. */
77
78
  readonly reserve?: ReserveCatalogProjection;
78
79
  readonly nativeSource?: NativePrioritySource;
80
+ /** Captured `routedCatalogDefaults` (#6872); applied to routed rows only, never read from config here. */
81
+ readonly routedCatalogDefaults?: Readonly<RoutedCatalogDefaults>;
79
82
  }
80
83
 
81
84
  /** Build entries with the process-observed Codex feature state. */
@@ -96,6 +99,7 @@ export function buildCatalogEntries(
96
99
  keepNativeChatGptOnV1 = false,
97
100
  modelPickerOrder: readonly string[] = [],
98
101
  nativeSource?: NativePrioritySource,
102
+ routedCatalogDefaults?: Readonly<RoutedCatalogDefaults>,
99
103
  ): RawEntry[] {
100
104
  const entries = buildCatalogEntriesFromObservedState({
101
105
  template,
@@ -115,6 +119,7 @@ export function buildCatalogEntries(
115
119
  accountNativeSlugs,
116
120
  accountNativeSlugsBySelector,
117
121
  nativeSource,
122
+ routedCatalogDefaults,
118
123
  });
119
124
  // Live discovery does not run the disk merge; use the same captured declarations and row fences.
120
125
  const configured = configuredUltraFastSlugs(goModels);
@@ -148,6 +153,7 @@ export function buildCatalogEntriesFromObservedState({
148
153
  accountNativeSlugsBySelector,
149
154
  reserve,
150
155
  nativeSource,
156
+ routedCatalogDefaults,
151
157
  }: ObservedCatalogEntryBuildInput): RawEntry[] {
152
158
  // Codex's models-manager sorts by `priority` ASC and advertises the first 5 picker-visible
153
159
  // models to spawn_agent (sort_by_key(priority) + MAX_MODEL_OVERRIDES_IN_SPAWN_AGENT=5). Catalog
@@ -228,6 +234,8 @@ export function buildCatalogEntriesFromObservedState({
228
234
  5,
229
235
  nativeAlias,
230
236
  exactComboSlugs,
237
+ undefined,
238
+ routedCatalogDefaults,
231
239
  );
232
240
  routed.opencodex_catalog_kind = CODEX_NATIVE_ALIAS_CATALOG_KIND;
233
241
  const rankHit = rank.get(slug) ?? rank.get(`${nativeAlias.provider}/${nativeAlias.id}`);
@@ -286,6 +294,8 @@ export function buildCatalogEntriesFromObservedState({
286
294
  5,
287
295
  m,
288
296
  exactComboSlugs,
297
+ undefined,
298
+ routedCatalogDefaults,
289
299
  );
290
300
  if (m.provider === COMBO_NAMESPACE && m.nativeAlias === true && !slug.includes("/")) {
291
301
  e.opencodex_catalog_kind = CODEX_NATIVE_ALIAS_CATALOG_KIND;
@@ -28,6 +28,8 @@ import {
28
28
  import { CATALOG_INACTIVE_REASON_FIELD, SPAWN_PRIORITY_FIELD } from "./subagent-roster";
29
29
  import { OCX_NATIVE_SOURCE_PRIORITY_FIELD } from "./native-priority";
30
30
  import { applyRoutedDescription } from "./ownership";
31
+ import { applyRoutedCatalogDefaults } from "./routed-defaults";
32
+ import type { RoutedCatalogDefaults } from "../../config/schema/routed-catalog-defaults";
31
33
 
32
34
  export function finishUpstreamNativeEntry(clone: RawEntry, priority: number, contextCap?: NativeContextLimitsInput): RawEntry {
33
35
  if (priority !== 9) clone.priority = priority;
@@ -99,6 +101,8 @@ function preservePinnedNativeCustomReasoning(model?: CatalogModel): boolean {
99
101
  * Cria uma entrada nativa ou roteada a partir do snapshot upstream, de um clone
100
102
  * do template ou de campos mínimos. Aplica os metadados e limites pertinentes
101
103
  * sem alterar o template nem herdar sua marca de nome ou histórico de prioridade.
104
+ * `routedDefaults` (#6872) only reaches ordinary routed rows, between routed normalization
105
+ * and provider/model metadata; native rows and Codex-forward native aliases ignore it.
102
106
  */
103
107
  export function deriveEntry(
104
108
  template: RawEntry | null,
@@ -108,6 +112,7 @@ export function deriveEntry(
108
112
  model?: CatalogModel,
109
113
  exactComboSlugs: ReadonlySet<string> = new Set(),
110
114
  contextCap?: NativeContextLimitsInput,
115
+ routedDefaults?: Readonly<RoutedCatalogDefaults>,
111
116
  ): RawEntry {
112
117
  const preserveExact = isExactComboCatalogModel(model, exactComboSlugs);
113
118
  // Go exposes model-specific upstream enums; synthetic tiers mislead subagent overrides.
@@ -173,6 +178,7 @@ export function deriveEntry(
173
178
  // native tool/search/responses-lite contract while preserving the routed slug and wire id.
174
179
  if (!codexForwardNativeCapabilityAlias) {
175
180
  normalizeRoutedCatalogEntry(e, model?.parallelToolCalls === true, model?.codexToolMode);
181
+ applyRoutedCatalogDefaults(e, routedDefaults);
176
182
  } else if (model?.codexToolMode !== undefined) {
177
183
  applyRoutedCodexToolMode(e, model.codexToolMode);
178
184
  }
@@ -218,6 +224,7 @@ export function deriveEntry(
218
224
  applyRoutedDescription(entry, desc, model);
219
225
  if (isRouted) {
220
226
  applyRoutedCodexToolMode(entry, model?.codexToolMode);
227
+ if (model?.codexForwardNativeCapabilityAlias !== true) applyRoutedCatalogDefaults(entry, routedDefaults);
221
228
  applyReasoningLevels(
222
229
  entry,
223
230
  model?.reasoningEfforts,
@@ -1,5 +1,5 @@
1
1
  import type { OcxConfig } from "../../types";
2
- import { isEffectiveCodexDesktopAuthless } from "../loopback-target";
2
+ import { isEffectiveCodexReserve } from "../loopback-target";
3
3
  import { NATIVE_RESERVE_MODEL } from "./native-models";
4
4
 
5
5
  /**
@@ -14,9 +14,9 @@ import { NATIVE_RESERVE_MODEL } from "./native-models";
14
14
  * inputs that produced the omission are still in scope.
15
15
  *
16
16
  * Deliberately scoped to an operator who asked for the feature. A default install has
17
- * `codexDesktopAuthless` unset, wants no Reserve row, and must not be told about one. An install
18
- * that stores the flag on a bind where it cannot take effect is a different silence, already
19
- * reported as `inertReason` by `describeCodexDesktopSwitches`, and is not repeated here.
17
+ * `codexReserveEnabled` off, wants no Reserve row, and must not be told about one. An install
18
+ * that enables Reserve on a bind where it cannot take effect is a different silence and is not
19
+ * repeated here.
20
20
  */
21
21
  export type ReserveCatalogSuppressionReason =
22
22
  | "no-canonical-openai-provider"
@@ -30,6 +30,8 @@ type ReserveSuppressionConfig = Pick<
30
30
  | "hostname"
31
31
  | "unauthenticatedLoopbackListener"
32
32
  | "codexDesktopAuthless"
33
+ | "codexReserveEnabled"
34
+ | "codexReserveMigration"
33
35
  | "codexAccountNamespaces"
34
36
  | "codexAccountPickerEnabled"
35
37
  >;
@@ -45,7 +47,7 @@ export function reserveCatalogSuppressionReason(
45
47
  config: ReserveSuppressionConfig,
46
48
  input: ReserveSuppressionInput,
47
49
  ): ReserveCatalogSuppressionReason | undefined {
48
- if (!isEffectiveCodexDesktopAuthless(config) || input.mainSelectors.length > 0) return undefined;
50
+ if (!isEffectiveCodexReserve(config) || input.mainSelectors.length > 0) return undefined;
49
51
  if (!input.includeAccountBoundNativeOpenAi) return "no-canonical-openai-provider";
50
52
  // Checked before the empty-map case: when an operator has explicitly turned the picker off,
51
53
  // naming the empty map would send them to hand-author selectors that the opt-in generates.
@@ -1,5 +1,5 @@
1
1
  import type { OcxConfig } from "../../types";
2
- import { isEffectiveCodexDesktopAuthless } from "../loopback-target";
2
+ import { isEffectiveCodexReserve } from "../loopback-target";
3
3
  import { CODEX_ACCOUNT_BOUND_CATALOG_KIND } from "./account-models";
4
4
  import { NATIVE_RESERVE_MODEL } from "./native-models";
5
5
  import type { RawEntry } from "./parsing";
@@ -17,12 +17,13 @@ export interface ReserveCatalogProjection {
17
17
 
18
18
  /** The caller supplies a validated actual observation and an already context-capped Luna pin. */
19
19
  export function createReserveCatalogProjection(
20
- config: Pick<OcxConfig, "runtimeRole" | "hostname" | "unauthenticatedLoopbackListener" | "codexDesktopAuthless">,
20
+ config: Pick<OcxConfig, "runtimeRole" | "hostname" | "unauthenticatedLoopbackListener" | "codexDesktopAuthless"
21
+ | "codexReserveEnabled" | "codexReserveMigration">,
21
22
  mainSelectors: readonly string[],
22
23
  observedSource: RawEntry | null,
23
24
  lunaSource: RawEntry | null,
24
25
  ): ReserveCatalogProjection | undefined {
25
- if (!isEffectiveCodexDesktopAuthless(config) || mainSelectors.length === 0) return undefined;
26
+ if (!isEffectiveCodexReserve(config) || mainSelectors.length === 0) return undefined;
26
27
  const original = observedSource ?? lunaSource;
27
28
  if (!original) return undefined;
28
29
  const source = structuredClone(original);
@@ -5,6 +5,7 @@ import { join } from "node:path";
5
5
  import { initializeConfigOwnership } from "../../lib/config-ownership";
6
6
  import { getConfigDir, loadConfig, ultraFastTierEnabled, websocketsEnabled, withConfigMutationLockSync } from "../../config";
7
7
  import { resolveMultiAgentMode } from "../../config/multi-agent-surface";
8
+ import { resolveRoutedCatalogDefaults } from "../../config/schema/routed-catalog-defaults";
8
9
  import { shouldSyncCodexOnStart } from "../desired-state";
9
10
  import { legacyCustomModelCatalogSlugs } from "../custom-model-catalog-migration";
10
11
  import { getCodexHome } from "../paths";
@@ -466,6 +467,7 @@ function writeRetainedCatalogSync({
466
467
  disabledNativeAccountSlugs: new Set(),
467
468
  multiAgentV2Enabled,
468
469
  openaiContextCap,
470
+ routedCatalogDefaults: resolveRoutedCatalogDefaults(config),
469
471
  });
470
472
  // Keep genuine native entries (gpt-*, codex-*) with their real per-model fields and append
471
473
  // routed providers as namespaced slugs. Cursor and other adopted providers can expose model ids
@@ -0,0 +1,35 @@
1
+ import type { RoutedCatalogDefaults } from "../../config/schema/routed-catalog-defaults";
2
+ import type { RawEntry } from "./parsing";
3
+
4
+ /**
5
+ * Project operator `routedCatalogDefaults` (#6872) onto a freshly derived routed row.
6
+ *
7
+ * `deriveEntry` calls this after the inherited template has been normalized for routing and
8
+ * before provider/model metadata is applied, which fixes the precedence: concrete provider/model
9
+ * declarations > these defaults > template values > strict-field fallbacks. The final
10
+ * `ensureStrictCatalogFields` pass still removes `default_verbosity` from a row whose
11
+ * `support_verbosity` ended up false, so a model without verbosity support never advertises an
12
+ * operator default. Verbosity support itself is never set here: it stays the provider's,
13
+ * model's or template's own declaration.
14
+ *
15
+ * Only the four allowlisted serialized fields are written. Values of any other type are ignored,
16
+ * so a caller that bypassed config validation cannot smuggle other row fields through here.
17
+ */
18
+ export function applyRoutedCatalogDefaults(
19
+ entry: RawEntry,
20
+ defaults: Readonly<RoutedCatalogDefaults> | undefined,
21
+ ): void {
22
+ if (!defaults) return;
23
+ if (typeof defaults.includeSkillsUsageInstructions === "boolean") {
24
+ entry.include_skills_usage_instructions = defaults.includeSkillsUsageInstructions;
25
+ }
26
+ if (typeof defaults.includeAppsUsageInstructions === "boolean") {
27
+ entry.include_apps_usage_instructions = defaults.includeAppsUsageInstructions;
28
+ }
29
+ if (typeof defaults.includePluginUsageInstructions === "boolean") {
30
+ entry.include_plugin_usage_instructions = defaults.includePluginUsageInstructions;
31
+ }
32
+ if (defaults.defaultVerbosity === "low" || defaults.defaultVerbosity === "medium" || defaults.defaultVerbosity === "high") {
33
+ entry.default_verbosity = defaults.defaultVerbosity;
34
+ }
35
+ }
@@ -99,6 +99,7 @@ import {
99
99
  import { ACCOUNT_GATED_NATIVE_OPENAI_MODELS } from "./catalog/native-models";
100
100
  import { providerCodexAccountMode } from "../providers/registry";
101
101
  import { OPENAI_CODEX_PROVIDER_ID } from "../providers/openai-tiers";
102
+ import { resolveRoutedCatalogDefaults } from "../config/schema/routed-catalog-defaults";
102
103
  import { withCatalogWriteSerialization } from "./catalog-write-serialization";
103
104
  import {
104
105
  auditRefusedCatalogReplacement,
@@ -351,6 +352,7 @@ function prepareCatalog(
351
352
  disabledNativeAccountSlugs: new Set(),
352
353
  multiAgentV2Enabled,
353
354
  openaiContextCap,
355
+ routedCatalogDefaults: resolveRoutedCatalogDefaults(config),
354
356
  });
355
357
  const accountBoundEntries = accountSelectors.length === 0
356
358
  ? []
@@ -1,15 +1,18 @@
1
1
  import type { OcxConfig } from "../types";
2
2
  import type { DataPlaneAdmission } from "../server/auth-cors";
3
3
  import { NATIVE_RESERVE_MODEL } from "./catalog/native-models";
4
+ import { isCodexReserveEnabled } from "../config/reserve-capability";
5
+
6
+ type ReserveCapabilityConfig = Pick<OcxConfig, "codexReserveEnabled" | "codexReserveMigration" | "codexDesktopAuthless">;
4
7
 
5
8
  export const CODEX_RESERVE_HELPER_UNSUPPORTED_MESSAGE =
6
9
  "Luna Reserve compatibility is only available as a conversation model, not a vision helper. Choose another vision model.";
7
10
 
8
11
  export const CODEX_RESERVE_OPT_IN_REQUIRED_MESSAGE =
9
- "Luna Reserve (gpt-reserve) is not forwarded without the local Desktop authless opt-in."
12
+ "Luna Reserve (gpt-reserve) is not forwarded while the local Reserve setting is off."
10
13
  + " OpenCodex holds no Reserve entitlement to send for this request, so the upstream would answer with a"
11
14
  + " usage-limit error that names neither the cause nor the fix."
12
- + " Enable the opt-in with 'ocx system settings --desktop-authless on' (or set codexDesktopAuthless to true"
15
+ + " Enable it with 'ocx system settings --reserve on' (or set codexReserveEnabled to true"
13
16
  + " in config.json), then retry. Choose another model to keep working without it.";
14
17
 
15
18
  /**
@@ -17,7 +20,7 @@ export const CODEX_RESERVE_OPT_IN_REQUIRED_MESSAGE =
17
20
  *
18
21
  * Read the two together. This answers a narrower question: Reserve was asked for, every ingress
19
22
  * condition eligibility requires already holds, and the single missing piece is the operator
20
- * opt-in. Flipping `codexDesktopAuthless` to true therefore always turns a true here into a true
23
+ * opt-in. Enabling `codexReserveEnabled` therefore always turns a true here into a true
21
24
  * from {@link isCodexReserveRequestEligible}, which is what makes it honest for the refusal to
22
25
  * name that one setting. The other two ineligibility reasons are deliberately not covered: a
23
26
  * client role and a non-loopback admission source are different situations, and the correct
@@ -28,17 +31,17 @@ export const CODEX_RESERVE_OPT_IN_REQUIRED_MESSAGE =
28
31
  * routed `gpt-reserve` onto some other provider owns a path that works, and it must keep working.
29
32
  */
30
33
  export function isCodexReserveOptInMissing(
31
- config: Pick<OcxConfig, "codexDesktopAuthless" | "runtimeRole">,
34
+ config: ReserveCapabilityConfig & Pick<OcxConfig, "runtimeRole">,
32
35
  modelId: string,
33
36
  admission: Pick<DataPlaneAdmission, "source"> | undefined,
34
37
  ): boolean {
35
- return modelId === NATIVE_RESERVE_MODEL && config.codexDesktopAuthless !== true
38
+ return modelId === NATIVE_RESERVE_MODEL && !isCodexReserveEnabled(config)
36
39
  && config.runtimeRole !== "client" && admission?.source === "loopback";
37
40
  }
38
41
 
39
42
  /** Callers classify the concrete destination as canonical forward before using this predicate. */
40
43
  export function isCodexReserveHelperUnsupported(
41
- config: Pick<OcxConfig, "codexDesktopAuthless" | "runtimeRole">,
44
+ config: ReserveCapabilityConfig & Pick<OcxConfig, "runtimeRole">,
42
45
  modelId: string,
43
46
  admission: Pick<DataPlaneAdmission, "source"> | undefined,
44
47
  terminalHelper: boolean,
@@ -48,10 +51,10 @@ export function isCodexReserveHelperUnsupported(
48
51
 
49
52
  /** Runtime authority comes from the receiving listener, not the catalog's injection target. */
50
53
  export function isCodexReserveRequestEligible(
51
- config: Pick<OcxConfig, "codexDesktopAuthless" | "runtimeRole">,
54
+ config: ReserveCapabilityConfig & Pick<OcxConfig, "runtimeRole">,
52
55
  admission: Pick<DataPlaneAdmission, "source"> | undefined,
53
56
  ): boolean {
54
- return config.codexDesktopAuthless === true && config.runtimeRole !== "client"
57
+ return isCodexReserveEnabled(config) && config.runtimeRole !== "client"
55
58
  && admission?.source === "loopback";
56
59
  }
57
60
 
@@ -129,6 +132,17 @@ export function isEffectiveCodexDesktopAuthless(
129
132
  && !shouldInjectApiAuthHeader(config);
130
133
  }
131
134
 
135
+ /**
136
+ * Catalog half of Reserve eligibility: the operator's Reserve capability, a non-client role, and a
137
+ * bind whose local Codex reaches this proxy without an admission token. Requests are judged by
138
+ * {@link isCodexReserveRequestEligible}, where the receiving listener remains the authority.
139
+ */
140
+ export function isEffectiveCodexReserve(
141
+ config: (ReserveCapabilityConfig & Pick<OcxConfig, "runtimeRole" | "hostname" | "unauthenticatedLoopbackListener">) | undefined,
142
+ ): boolean {
143
+ return isCodexReserveEnabled(config) && config?.runtimeRole !== "client" && !shouldInjectApiAuthHeader(config);
144
+ }
145
+
132
146
  /** Keep reporting aligned with the admission-token gate used by standalone injection. */
133
147
  export function isEffectiveCodexClientCompaction(
134
148
  config: Pick<OcxConfig, "runtimeRole" | "hostname" | "unauthenticatedLoopbackListener" | "codexClientCompaction"> | undefined,
@@ -23,7 +23,16 @@ import {
23
23
  } from "./account-store";
24
24
  import { resolveWriteTarget } from "../config/atomic-write";
25
25
  import { resolveCodexHomeDir } from "./home";
26
- import { readNativeMainAuthBytes, writeNativeMainAuthFile } from "./native-main-auth-file";
26
+ import { writeNativeMainAuthFile } from "./native-main-auth-file";
27
+ import {
28
+ beginNativeMainObservation,
29
+ invalidateRetainedNativeMainLogin,
30
+ invalidationForObservation,
31
+ observeNativeMainAuthFile,
32
+ retainedNativeMainLogin,
33
+ retainNativeMainLogin,
34
+ type NativeMainObservationTicket,
35
+ } from "./native-main-credentials";
27
36
  import { assertNotRealCodexHomeUnderTest } from "../lib/test-home-guard";
28
37
  import {
29
38
  clearAccountNeedsReauth,
@@ -39,6 +48,7 @@ import { isNativeMainTrafficBlocked } from "./native-profile-startup";
39
48
  import { loadConfig } from "../config";
40
49
  import {
41
50
  requestCodexAuthStatus,
51
+ configuredNativeMainRefreshMode,
42
52
  resolveNativeMainRefreshMode,
43
53
  type CodexAuthStatus,
44
54
  } from "./native-main-refresh-mode";
@@ -94,6 +104,8 @@ type MainAuthJsonCredential = {
94
104
  accessToken?: string;
95
105
  refreshToken?: string;
96
106
  chatgptAccountId: string;
107
+ /** Served from retention while the file is mid-rewrite (#7345); never a write-guard snapshot. */
108
+ retained?: true;
97
109
  };
98
110
 
99
111
  export interface NativeMainRefreshDependencies {
@@ -212,41 +224,73 @@ function statIdentity(path: string): FileIdentity | null {
212
224
  }
213
225
  }
214
226
 
215
- function readMainAuthJsonCredential(): MainAuthJsonCredential | null {
216
- const path = resolveWriteTarget(join(resolveCodexHomeDir(), "auth.json"));
217
- let raw: string;
218
- try {
219
- raw = readNativeMainAuthBytes(path, "plain").toString("utf8");
220
- } catch {
221
- return null;
222
- }
223
- try {
224
- const parsed = JSON.parse(raw) as unknown;
225
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
226
- const root = parsed as Record<string, unknown>;
227
- const tokenValue = root.tokens;
228
- if (!tokenValue || typeof tokenValue !== "object" || Array.isArray(tokenValue)) return null;
229
- const tokens = tokenValue as Record<string, unknown>;
227
+ interface MainAuthJsonReadOptions {
228
+ /** Answer an empty or partially written file from the last complete same-owner login. */
229
+ serveRetained?: boolean;
230
+ /**
231
+ * Ticket a complete observation retains under; `false` for write guards, which observe
232
+ * without retaining. A ticket captured before an async exchange refuses a stale completion.
233
+ */
234
+ retainWith?: NativeMainObservationTicket | false;
235
+ }
236
+
237
+ /**
238
+ * The native-main login, through {@link observeNativeMainAuthFile} (#7345). Missing, no-login and
239
+ * unreadable observations end retention; only an incomplete one may be answered from it, and only
240
+ * when the caller asks and the owner, file identity and credential epoch are unchanged.
241
+ */
242
+ function readMainAuthJsonCredential(options: MainAuthJsonReadOptions = {}): MainAuthJsonCredential | null {
243
+ const codexHome = resolveCodexHomeDir();
244
+ const path = resolveWriteTarget(join(codexHome, "auth.json"));
245
+ const owner = { codexHome, path };
246
+ const ticket = options.retainWith === undefined ? beginNativeMainObservation() : options.retainWith;
247
+ const observation = observeNativeMainAuthFile(path);
248
+ if (observation.kind === "complete") {
249
+ const { raw, root, tokens } = observation;
230
250
  const accessToken = nonEmptyString(tokens.access_token);
231
251
  const refreshToken = nonEmptyString(tokens.refresh_token);
232
- if (!accessToken && !refreshToken) return null;
233
252
  const idToken = nonEmptyString(tokens.id_token);
234
- const chatgptAccountId = extractAccountId(idToken, accessToken)
235
- ?? nonEmptyString(tokens.account_id)
236
- ?? "";
237
- return {
253
+ const credential: MainAuthJsonCredential = {
238
254
  path,
239
255
  rawSha256: sha256(raw),
240
- identity: statIdentity(path),
256
+ // The identity the bytes were read from; null (fail closed) when it changed mid-read.
257
+ identity: observation.identity,
241
258
  root,
242
259
  tokens,
243
260
  ...(accessToken ? { accessToken } : {}),
244
261
  ...(refreshToken ? { refreshToken } : {}),
245
- chatgptAccountId,
262
+ chatgptAccountId: extractAccountId(idToken, accessToken) ?? nonEmptyString(tokens.account_id) ?? "",
246
263
  };
247
- } catch {
264
+ if (ticket) {
265
+ retainNativeMainLogin(ticket, owner, credential.identity, credential, {
266
+ fingerprint: credential.rawSha256,
267
+ configuredRefreshMode: configuredRefreshOwner,
268
+ });
269
+ }
270
+ return credential;
271
+ }
272
+ const invalidation = invalidationForObservation(observation);
273
+ if (invalidation) {
274
+ invalidateRetainedNativeMainLogin(invalidation);
275
+ return null;
276
+ }
277
+ if (observation.kind !== "incomplete" || !options.serveRetained) return null;
278
+ if (isNativeMainTrafficBlocked()) {
279
+ invalidateRetainedNativeMainLogin("ownership-loss");
248
280
  return null;
249
281
  }
282
+ const retained = retainedNativeMainLogin<MainAuthJsonCredential>(owner, observation.identity, configuredRefreshOwner);
283
+ if (!retained) return null;
284
+ if (credentialRefreshGrantRejected(retained)) {
285
+ invalidateRetainedNativeMainLogin("revocation");
286
+ return null;
287
+ }
288
+ return { ...retained, retained: true };
289
+ }
290
+
291
+ /** Read only when a new login is retained or a retained one is about to be served. */
292
+ function configuredRefreshOwner(): string {
293
+ return configuredNativeMainRefreshMode(loadConfig());
250
294
  }
251
295
 
252
296
  function mainAccessTokenFresh(accessToken: string | undefined, now: number, skewMs: number): boolean {
@@ -275,7 +319,10 @@ export interface MainAccountCredentialStatus {
275
319
 
276
320
  /** One owned physical observation; no credential material escapes this view. */
277
321
  export function getMainAccountCredentialStatus(now = Date.now()): MainAccountCredentialStatus {
278
- const current = readMainAuthJsonCredential();
322
+ let current = readMainAuthJsonCredential({ serveRetained: true });
323
+ // A retained login is usable only while its bearer is fresh: an expired one goes to the refresh
324
+ // owner, which cannot refresh a file mid-rewrite, so it must not be selected (#7345).
325
+ if (current?.retained && !mainAccessTokenFresh(current.accessToken, now, MAIN_TOKEN_REFRESH_SKEW_MS)) current = null;
279
326
  const owned = !current && codexOwnedMainCredential?.home === resolveCodexHomeDir() ? codexOwnedMainCredential : null;
280
327
  const refreshGrantRejected = credentialRefreshGrantRejected(current);
281
328
  const hasRefreshGrant = !!current?.refreshToken && !refreshGrantRejected;
@@ -304,7 +351,7 @@ export function hasMainAccountRefreshGrant(): boolean {
304
351
  }
305
352
 
306
353
  function assertMainAuthJsonSnapshotUnchanged(expected: MainAuthJsonCredential): void {
307
- const current = readMainAuthJsonCredential();
354
+ const current = readMainAuthJsonCredential({ retainWith: false });
308
355
  if (!current || current.path !== expected.path || current.rawSha256 !== expected.rawSha256) {
309
356
  throw new MainAuthJsonChangedDuringRefreshError();
310
357
  }
@@ -436,7 +483,7 @@ export function beginNativeMainReauth(): {
436
483
  options?: { signal?: AbortSignal },
437
484
  ) => Promise<{ chatgptAccountId: string }>;
438
485
  } {
439
- const expected = readMainAuthJsonCredential();
486
+ const expected = readMainAuthJsonCredential({ retainWith: false });
440
487
  if (!expected || !expected.chatgptAccountId) {
441
488
  throw new NativeMainReauthUnavailableError(
442
489
  "No native main credential exists to reauthenticate; enrollment is the native profile workflow",
@@ -511,7 +558,16 @@ async function resolveMainAccountToken(
511
558
  ): Promise<{ accessToken: string; chatgptAccountId: string } | null> {
512
559
  if (dependencies.signal?.aborted) throw dependencies.signal.reason;
513
560
  const codexHome = resolveCodexHomeDir();
514
- const initial = readMainAuthJsonCredential();
561
+ let initial = readMainAuthJsonCredential({ serveRetained: true });
562
+ // Retention covers a rewrite, not a refresh: an expired or rejected retained bearer goes to the
563
+ // selected refresh owner exactly as an unavailable file would (#7345). Upstream rejecting the
564
+ // retained bearer is revocation evidence, so that copy is dropped for good.
565
+ if (initial?.retained && initial.accessToken === rejectedAccessToken) {
566
+ invalidateRetainedNativeMainLogin("revocation");
567
+ initial = null;
568
+ } else if (initial?.retained && !mainAccessTokenFresh(initial.accessToken, Date.now(), MAIN_TOKEN_REFRESH_SKEW_MS)) {
569
+ initial = null;
570
+ }
515
571
  // Every skip below ends a forced refresh WITHOUT asking the token endpoint anything, which from
516
572
  // the outside is indistinguishable from a refusal: same failed request, no write, no verdict.
517
573
  // A forced refresh is the only caller that passes `rejectedAccessToken`, so only it reports.
@@ -599,7 +655,9 @@ async function resolveMainAccountToken(
599
655
  resolveNativeProfileContext({ codexHome }),
600
656
  () => withCodexRefreshFileLock(lockKey, signal, async () => {
601
657
  if (resolveCodexHomeDir() !== codexHome) throw new MainAuthJsonChangedDuringRefreshError();
602
- const locked = readMainAuthJsonCredential();
658
+ // Captured before the exchange: an invalidation while it runs makes its completion stale.
659
+ const ticket = beginNativeMainObservation();
660
+ const locked = readMainAuthJsonCredential({ retainWith: ticket });
603
661
  if (!locked) throw new MainAuthJsonChangedDuringRefreshError();
604
662
  if (credentialRefreshGrantRejected(locked)) throw new MainAccountTokenRefreshError("reauth");
605
663
  if (!locked.refreshToken
@@ -666,6 +724,7 @@ async function resolveMainAccountToken(
666
724
  // A permitted in-flight success speaks only for its own profile and grant.
667
725
  clearMainRefreshGrantRejection(mainRefreshGrantKey(locked)!);
668
726
  if (dependencies.preserveReauth !== true) clearAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
727
+ readMainAuthJsonCredential({ retainWith: ticket });
669
728
  if (dependencies.signal?.aborted) throw dependencies.signal.reason;
670
729
  return result;
671
730
  }),
@@ -34,6 +34,20 @@ export function nativeAuthStatStamp(value: BigIntStats): string {
34
34
  return `${value.dev}:${value.ino}:${value.size}:${value.mtimeNs}:${value.ctimeNs}`;
35
35
  }
36
36
 
37
+ /**
38
+ * Plain read bracketed by a stat before and after (#7345 retention). The identity is the file's
39
+ * dev/ino when both stats name the same file, and null when it was replaced during the read. The
40
+ * bytes still come from the plain path read, so read-count oracles observe it. Throws the error of
41
+ * either stat or the read unchanged: a file removed right after the read is missing, not a login.
42
+ */
43
+ export function readNativeMainAuthBytesWithIdentity(path: string): { bytes: Buffer; identity: { dev: bigint; ino: bigint } | null } {
44
+ const before = statSync(path, { bigint: true });
45
+ const bytes = readNativeMainAuthBytes(path, "plain");
46
+ const after = statSync(path, { bigint: true });
47
+ const same = after.dev === before.dev && after.ino === before.ino;
48
+ return { bytes, identity: same ? { dev: after.dev, ino: after.ino } : null };
49
+ }
50
+
37
51
  /** Reads with a stat before and after, as the desktop identity reader did. */
38
52
  export function readNativeMainAuthBytesStable(path: string, maxBytes: bigint): { bytes: Buffer; stat: BigIntStats } {
39
53
  const before = statSync(path, { bigint: true });