@bitkyc08/opencodex 2.100.3 → 2.100.5-preview.20261118.1

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 (249) 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-BiOGtxDS.js} +21 -20
  4. package/gui/dist/assets/{Tray-BV4ms9U9.js → Tray-BwsMejUO.js} +1 -1
  5. package/gui/dist/assets/brand-mark-BY1dgACL.js +1 -0
  6. package/gui/dist/assets/{index-DCdXsMyZ.js → index-CwHSKMdG.js} +46 -13
  7. package/gui/dist/assets/index-DJxM-imn.css +2 -0
  8. package/gui/dist/assets/{segment-thumb-features-DXSidY6D.js → segment-thumb-features-Bds9Hb_7.js} +1 -1
  9. package/gui/dist/classic/assets/{App-DA-scMPq.js → App-CGLOiqQL.js} +20 -19
  10. package/gui/dist/classic/assets/{Tray-BrHaVRAq.js → Tray-Da4r2O70.js} +1 -1
  11. package/gui/dist/classic/assets/{index-BqOaGLf5.js → index-CvoKXKL9.js} +46 -13
  12. package/gui/dist/classic/assets/quota-summary-DvqzfCmr.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/native/ocx-child/src/link_ws.rs +24 -19
  18. package/native/ocx-child/src/link_ws_frame.rs +136 -50
  19. package/package.json +3 -3
  20. package/src/adapters/anthropic/per-message-effort.ts +296 -0
  21. package/src/adapters/anthropic-input-schema.ts +270 -0
  22. package/src/adapters/anthropic.ts +4 -63
  23. package/src/adapters/claude-cli/adapter.ts +1 -0
  24. package/src/adapters/command-code-tool-text.ts +9 -1
  25. package/src/adapters/command-code.ts +18 -2
  26. package/src/adapters/devin/cloud-direct/chat.ts +95 -14
  27. package/src/adapters/devin/live-models.ts +11 -1
  28. package/src/adapters/google-errors.ts +14 -2
  29. package/src/adapters/kiro/reasoning.ts +3 -0
  30. package/src/adapters/kiro-tools.ts +14 -9
  31. package/src/adapters/openai-responses/passthrough.ts +3 -1
  32. package/src/adapters/openai-responses/request-strips.ts +1 -0
  33. package/src/adapters/qoder/adapter.ts +9 -1
  34. package/src/adapters/tool-catalog-nudge.ts +1 -1
  35. package/src/adapters/zed.ts +4 -2
  36. package/src/claude/chat-tool-dispatch.ts +4 -1
  37. package/src/claude/desktop-remote-store.ts +60 -10
  38. package/src/cli/account-api.ts +4 -0
  39. package/src/cli/account-auth.ts +30 -2
  40. package/src/cli/account-extended.ts +33 -2
  41. package/src/cli/capabilities-access-remote.ts +3 -3
  42. package/src/cli/capabilities-accounts.ts +3 -3
  43. package/src/cli/capabilities-base.ts +11 -6
  44. package/src/cli/capabilities-observe-system.ts +2 -2
  45. package/src/cli/claude.ts +3 -3
  46. package/src/cli/disconnect-runtime.ts +16 -6
  47. package/src/cli/dispatch.ts +7 -1
  48. package/src/cli/index.ts +2 -2
  49. package/src/cli/link-apply-restart.ts +4 -2
  50. package/src/cli/link-routes.ts +4 -1
  51. package/src/cli/link.ts +5 -4
  52. package/src/cli/logout-command.ts +23 -4
  53. package/src/cli/preflight-exemptions.ts +3 -0
  54. package/src/cli/provider.ts +3 -2
  55. package/src/cli/registry.ts +5 -2
  56. package/src/cli/resolve.ts +23 -8
  57. package/src/cli/restart-failure.ts +11 -1
  58. package/src/cli/runtime-api.ts +4 -0
  59. package/src/cli/status.ts +4 -1
  60. package/src/cli/system-command.ts +1 -1
  61. package/src/cli/system-restart-client.ts +9 -3
  62. package/src/cli/system-settings-parity.ts +2 -1
  63. package/src/client/connect.ts +73 -11
  64. package/src/client/desktop-refusal.ts +38 -0
  65. package/src/client/lifecycle-lock.ts +29 -4
  66. package/src/client/runtime-restart.ts +27 -15
  67. package/src/client/runtime.ts +4 -2
  68. package/src/client/state.ts +14 -0
  69. package/src/clients/config-export.ts +12 -7
  70. package/src/codex/account-lifecycle.ts +3 -1
  71. package/src/codex/account-pause.ts +4 -0
  72. package/src/codex/account-runtime-state.ts +4 -0
  73. package/src/codex/auth-api/main-account-probe.ts +3 -1
  74. package/src/codex/auth-api/main-hard-lock-refusal-read.ts +172 -0
  75. package/src/codex/auth-context.ts +40 -2
  76. package/src/codex/catalog/build-entries.ts +10 -0
  77. package/src/codex/catalog/derive-entry.ts +7 -0
  78. package/src/codex/catalog/metadata.ts +8 -0
  79. package/src/codex/catalog/native-models.ts +16 -6
  80. package/src/codex/catalog/pinned-models.ts +1 -0
  81. package/src/codex/catalog/provider-models.ts +5 -5
  82. package/src/codex/catalog/reserve-warn.ts +7 -5
  83. package/src/codex/catalog/reserve.ts +4 -3
  84. package/src/codex/catalog/retained-sync.ts +2 -0
  85. package/src/codex/catalog/routed-defaults.ts +35 -0
  86. package/src/codex/catalog-auto-refresh.ts +13 -2
  87. package/src/codex/config-drift-heal.ts +40 -12
  88. package/src/codex/config-write-lock.ts +39 -1
  89. package/src/codex/convergence.ts +2 -0
  90. package/src/codex/data/roster-pinned-models.json +346 -1
  91. package/src/codex/inject/config-write-section.ts +39 -1
  92. package/src/codex/inject/plan.ts +10 -8
  93. package/src/codex/inject/remove.ts +21 -19
  94. package/src/codex/inject/restore.ts +5 -1
  95. package/src/codex/inject-coordination.ts +58 -7
  96. package/src/codex/inject.ts +10 -12
  97. package/src/codex/journal-config-restore.ts +42 -0
  98. package/src/codex/journal.ts +62 -8
  99. package/src/codex/loopback-target.ts +22 -8
  100. package/src/codex/main-account.ts +94 -30
  101. package/src/codex/native-main-auth-file.ts +14 -0
  102. package/src/codex/native-main-credentials.ts +276 -0
  103. package/src/codex/native-main-owner.ts +3 -0
  104. package/src/codex/native-main-refresh-mode.ts +14 -1
  105. package/src/codex/quota.ts +63 -14
  106. package/src/combos/failover.ts +195 -1
  107. package/src/combos/index.ts +5 -0
  108. package/src/combos/resolve.ts +115 -19
  109. package/src/config/diagnostics.ts +3 -0
  110. package/src/config/live-reconcile.ts +6 -3
  111. package/src/config/load-degrade.ts +2 -0
  112. package/src/config/persisted-mutation.ts +2 -2
  113. package/src/config/persisted-projections.ts +18 -0
  114. package/src/config/process-state.ts +4 -3
  115. package/src/config/reserve-capability.ts +96 -0
  116. package/src/config/schema/config-schema.ts +6 -0
  117. package/src/config/schema/leaf-validators.ts +2 -0
  118. package/src/config/schema/routed-catalog-defaults.ts +49 -0
  119. package/src/config/subagent-models.ts +20 -12
  120. package/src/config.ts +7 -7
  121. package/src/desktop-update/acquire.ts +202 -0
  122. package/src/desktop-update/cli.ts +168 -0
  123. package/src/desktop-update/drain.ts +40 -0
  124. package/src/desktop-update/headless.ts +285 -0
  125. package/src/desktop-update/image.ts +85 -0
  126. package/src/desktop-update/install.ts +53 -0
  127. package/src/desktop-update/msi.ts +72 -0
  128. package/src/desktop-update/release.ts +128 -0
  129. package/src/desktop-update/runtime.ts +155 -0
  130. package/src/desktop-update/staging.ts +118 -0
  131. package/src/desktop-update/trust.ts +45 -0
  132. package/src/generated/compatibility-version.json +327 -195
  133. package/src/generated/model-metadata.ts +3 -3
  134. package/src/images/fulfill-video.ts +3 -3
  135. package/src/images/loop.ts +6 -2
  136. package/src/images/plan.ts +147 -11
  137. package/src/images/types.ts +13 -4
  138. package/src/images/xai-video-client.ts +72 -10
  139. package/src/lib/client-error-body.ts +6 -0
  140. package/src/lib/developer-role-rejection.ts +15 -0
  141. package/src/lib/gcp-adc.ts +48 -4
  142. package/src/lib/offline-resend.ts +150 -0
  143. package/src/lib/paced-stream.ts +3 -3
  144. package/src/lib/provider-outbound.ts +17 -6
  145. package/src/lib/request-failure-model.ts +2 -0
  146. package/src/lib/response-body-inactivity.ts +23 -1
  147. package/src/lib/upstream-retry.ts +39 -6
  148. package/src/link/explicit-route.ts +4 -4
  149. package/src/link/remote-windows.ts +79 -31
  150. package/src/link/residual-recovery.ts +20 -8
  151. package/src/messaging/budget.ts +23 -5
  152. package/src/messaging/remote-ports.ts +22 -10
  153. package/src/messaging/rpc.ts +4 -4
  154. package/src/oauth/antigravity-risk.ts +126 -0
  155. package/src/oauth/credential-siblings.ts +32 -0
  156. package/src/oauth/generic-account-failover.ts +113 -30
  157. package/src/oauth/generic-session-affinity.ts +10 -3
  158. package/src/oauth/index.ts +22 -14
  159. package/src/oauth/login-cli.ts +35 -1
  160. package/src/oauth/pool-kernel.ts +3 -3
  161. package/src/oauth/store.ts +38 -7
  162. package/src/providers/anthropic-billing-refusal.ts +27 -3
  163. package/src/providers/anthropic-reset-grants.ts +4 -0
  164. package/src/providers/claude-cli-usage.ts +2 -0
  165. package/src/providers/codebuddy-models.ts +11 -0
  166. package/src/providers/google-vertex-model-discovery.ts +49 -15
  167. package/src/providers/kiro-models.ts +5 -0
  168. package/src/providers/model-rename-fields.ts +2 -0
  169. package/src/providers/quota/workbuddy.ts +6 -2
  170. package/src/providers/registry/entries-core.ts +9 -3
  171. package/src/providers/registry/entries-extended.ts +20 -9
  172. package/src/providers/registry/model-seeds.ts +4 -1
  173. package/src/providers/stale-context-window-migration.ts +2 -0
  174. package/src/providers/workbuddy-credit-balance.ts +125 -16
  175. package/src/responses/citation-markers.ts +26 -23
  176. package/src/responses/effort-history.ts +732 -0
  177. package/src/routing/history/integrity.ts +41 -4
  178. package/src/server/auth-cors.ts +13 -3
  179. package/src/server/codex-model-list.ts +2 -1
  180. package/src/server/direct-local-http.ts +26 -3
  181. package/src/server/index/link-listener.ts +20 -14
  182. package/src/server/index/serve-options.ts +1 -0
  183. package/src/server/index.ts +3 -2
  184. package/src/server/link-turn.ts +17 -5
  185. package/src/server/management/config-routes.ts +39 -3
  186. package/src/server/management/link-child-preflight.ts +1 -1
  187. package/src/server/management/link-enrollment.ts +3 -3
  188. package/src/server/management/link-route-edit.ts +20 -1
  189. package/src/server/management/link-route-request.ts +11 -5
  190. package/src/server/management/oauth-account-routes.ts +43 -13
  191. package/src/server/management/provider-credential-release.ts +44 -0
  192. package/src/server/management/provider-overwrite-carry.ts +3 -0
  193. package/src/server/management/provider-routes.ts +12 -12
  194. package/src/server/management/static-catalog-probe.ts +33 -0
  195. package/src/server/management/usage-aggregate-cache.ts +6 -3
  196. package/src/server/messages-native.ts +16 -2
  197. package/src/server/proxy-liveness.ts +54 -9
  198. package/src/server/relay.ts +6 -1
  199. package/src/server/request-log-conversation.ts +8 -4
  200. package/src/server/request-log-failure-detail.ts +26 -9
  201. package/src/server/request-log.ts +5 -1
  202. package/src/server/reserve-capability-startup.ts +32 -0
  203. package/src/server/responses/adapter-continuation.ts +59 -25
  204. package/src/server/responses/adapter-delivery.ts +2 -0
  205. package/src/server/responses/adapter-dispatch.ts +39 -18
  206. package/src/server/responses/antigravity-fault-rotation.ts +24 -0
  207. package/src/server/responses/antigravity-validation-refusal.ts +43 -6
  208. package/src/server/responses/codex-tool-catalog.ts +47 -10
  209. package/src/server/responses/combo-selection-keepalive.ts +254 -0
  210. package/src/server/responses/combo-session-recall.ts +26 -1
  211. package/src/server/responses/combo-stream-preflight.ts +35 -26
  212. package/src/server/responses/core-combo-failure.ts +6 -0
  213. package/src/server/responses/core-combo-native.ts +2 -1
  214. package/src/server/responses/core-combo.ts +67 -28
  215. package/src/server/responses/core-errors.ts +9 -6
  216. package/src/server/responses/core-options.ts +10 -0
  217. package/src/server/responses/core.ts +21 -0
  218. package/src/server/responses/estimated-usage.ts +115 -0
  219. package/src/server/responses/input-admission.ts +41 -3
  220. package/src/server/responses/jev-model-invoke.ts +7 -2
  221. package/src/server/responses/passthrough-completion.ts +6 -3
  222. package/src/server/responses/passthrough-delivery.ts +47 -8
  223. package/src/server/responses/passthrough-dispatch.ts +3 -0
  224. package/src/server/responses/request-prepare.ts +9 -5
  225. package/src/server/responses/request-send-budget.ts +1 -1
  226. package/src/server/responses/request-transport.ts +10 -2
  227. package/src/server/responses/sidecar-execution.ts +11 -4
  228. package/src/service/desktop-supervision.d.mts +2 -0
  229. package/src/service/desktop-supervision.mjs +5 -0
  230. package/src/service/windows-checked-stop-live.ts +28 -5
  231. package/src/stall-timeout.ts +11 -0
  232. package/src/types/config.ts +15 -92
  233. package/src/types/provider.ts +13 -0
  234. package/src/types/request.ts +23 -3
  235. package/src/types/routed-catalog-defaults.ts +17 -0
  236. package/src/types/routing-profile.ts +90 -0
  237. package/src/types.ts +1 -0
  238. package/src/update/index.ts +1 -1
  239. package/src/usage/expected-prices.ts +35 -0
  240. package/src/usage/ledger-scanner.ts +44 -10
  241. package/src/usage/log.ts +14 -4
  242. package/src/usage/telemetry-contract.ts +1 -0
  243. package/src/web-search/loop.ts +20 -2
  244. package/src/web-search/parse.ts +2 -12
  245. package/src/web-search/passthrough-bridge.ts +7 -0
  246. package/src/web-search/sources.ts +13 -0
  247. package/gui/dist/assets/brand-mark-XOLJbomA.js +0 -1
  248. package/gui/dist/assets/index-DQtCRNAw.css +0 -2
  249. package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +0 -1
@@ -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,
@@ -1,5 +1,6 @@
1
1
  import { publishCredentialSync } from "../local-credentials/generation";
2
2
  import { captureMainAccountIdentityGeneration, getMainQuotaCredentialGeneration, isMainAccountIdentityGenerationLive, isMainQuotaWriterLive, matchesMainQuotaCredential, observeMainDecisionCredentialUsable, type MainQuotaWriter } from "./main-account-cache";
3
+ import { observeMainCodexAccountIdentity } from "./account-lifecycle";
3
4
  import { classifyChatgptRefreshFailure, noteChatgptRefreshFailure } from "./chatgpt-refresh-failure";
4
5
  import { readBoundedResponseBody } from "../lib/bounded-body";
5
6
  import { createHash } from "node:crypto";
@@ -23,7 +24,16 @@ import {
23
24
  } from "./account-store";
24
25
  import { resolveWriteTarget } from "../config/atomic-write";
25
26
  import { resolveCodexHomeDir } from "./home";
26
- import { readNativeMainAuthBytes, writeNativeMainAuthFile } from "./native-main-auth-file";
27
+ import { writeNativeMainAuthFile } from "./native-main-auth-file";
28
+ import {
29
+ beginNativeMainObservation,
30
+ invalidateRetainedNativeMainLogin,
31
+ invalidationForObservation,
32
+ observeNativeMainAuthFile,
33
+ retainedNativeMainLogin,
34
+ retainNativeMainLogin,
35
+ type NativeMainObservationTicket,
36
+ } from "./native-main-credentials";
27
37
  import { assertNotRealCodexHomeUnderTest } from "../lib/test-home-guard";
28
38
  import {
29
39
  clearAccountNeedsReauth,
@@ -39,6 +49,7 @@ import { isNativeMainTrafficBlocked } from "./native-profile-startup";
39
49
  import { loadConfig } from "../config";
40
50
  import {
41
51
  requestCodexAuthStatus,
52
+ configuredNativeMainRefreshMode,
42
53
  resolveNativeMainRefreshMode,
43
54
  type CodexAuthStatus,
44
55
  } from "./native-main-refresh-mode";
@@ -94,6 +105,8 @@ type MainAuthJsonCredential = {
94
105
  accessToken?: string;
95
106
  refreshToken?: string;
96
107
  chatgptAccountId: string;
108
+ /** Served from retention while the file is mid-rewrite (#7345); never a write-guard snapshot. */
109
+ retained?: true;
97
110
  };
98
111
 
99
112
  export interface NativeMainRefreshDependencies {
@@ -212,41 +225,78 @@ function statIdentity(path: string): FileIdentity | null {
212
225
  }
213
226
  }
214
227
 
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>;
228
+ interface MainAuthJsonReadOptions {
229
+ /** Answer an empty or partially written file from the last complete same-owner login. */
230
+ serveRetained?: boolean;
231
+ /**
232
+ * Ticket a complete observation retains under; `false` for write guards, which observe
233
+ * without retaining. A ticket captured before an async exchange refuses a stale completion.
234
+ */
235
+ retainWith?: NativeMainObservationTicket | false;
236
+ }
237
+
238
+ /**
239
+ * The native-main login, through {@link observeNativeMainAuthFile} (#7345). Missing, no-login and
240
+ * unreadable observations end retention; only an incomplete one may be answered from it, and only
241
+ * when the caller asks and the owner, file identity and credential epoch are unchanged.
242
+ */
243
+ function readMainAuthJsonCredential(options: MainAuthJsonReadOptions = {}): MainAuthJsonCredential | null {
244
+ const codexHome = resolveCodexHomeDir();
245
+ const path = resolveWriteTarget(join(codexHome, "auth.json"));
246
+ const owner = { codexHome, path };
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
+ // Finish the owned identity transition, including prior-account cleanup, before capturing
265
+ // retention. Write guards and explicit pre-exchange tickets keep their existing authority.
266
+ if (options.serveRetained && credential.identity && !isNativeMainTrafficBlocked()) {
267
+ observeMainCodexAccountIdentity(credential.chatgptAccountId);
268
+ }
269
+ const ticket = options.retainWith === undefined ? beginNativeMainObservation() : options.retainWith;
270
+ if (ticket) {
271
+ retainNativeMainLogin(ticket, owner, credential.identity, credential, {
272
+ fingerprint: credential.rawSha256,
273
+ configuredRefreshMode: configuredRefreshOwner,
274
+ });
275
+ }
276
+ return credential;
277
+ }
278
+ const invalidation = invalidationForObservation(observation);
279
+ if (invalidation) {
280
+ invalidateRetainedNativeMainLogin(invalidation);
281
+ return null;
282
+ }
283
+ if (observation.kind !== "incomplete" || !options.serveRetained) return null;
284
+ if (isNativeMainTrafficBlocked()) {
285
+ invalidateRetainedNativeMainLogin("ownership-loss");
286
+ return null;
287
+ }
288
+ const retained = retainedNativeMainLogin<MainAuthJsonCredential>(owner, observation.identity, configuredRefreshOwner);
289
+ if (!retained) return null;
290
+ if (credentialRefreshGrantRejected(retained)) {
291
+ invalidateRetainedNativeMainLogin("revocation");
248
292
  return null;
249
293
  }
294
+ return { ...retained, retained: true };
295
+ }
296
+
297
+ /** Read only when a new login is retained or a retained one is about to be served. */
298
+ function configuredRefreshOwner(): string {
299
+ return configuredNativeMainRefreshMode(loadConfig());
250
300
  }
251
301
 
252
302
  function mainAccessTokenFresh(accessToken: string | undefined, now: number, skewMs: number): boolean {
@@ -275,7 +325,10 @@ export interface MainAccountCredentialStatus {
275
325
 
276
326
  /** One owned physical observation; no credential material escapes this view. */
277
327
  export function getMainAccountCredentialStatus(now = Date.now()): MainAccountCredentialStatus {
278
- const current = readMainAuthJsonCredential();
328
+ let current = readMainAuthJsonCredential({ serveRetained: true });
329
+ // A retained login is usable only while its bearer is fresh: an expired one goes to the refresh
330
+ // owner, which cannot refresh a file mid-rewrite, so it must not be selected (#7345).
331
+ if (current?.retained && !mainAccessTokenFresh(current.accessToken, now, MAIN_TOKEN_REFRESH_SKEW_MS)) current = null;
279
332
  const owned = !current && codexOwnedMainCredential?.home === resolveCodexHomeDir() ? codexOwnedMainCredential : null;
280
333
  const refreshGrantRejected = credentialRefreshGrantRejected(current);
281
334
  const hasRefreshGrant = !!current?.refreshToken && !refreshGrantRejected;
@@ -304,7 +357,7 @@ export function hasMainAccountRefreshGrant(): boolean {
304
357
  }
305
358
 
306
359
  function assertMainAuthJsonSnapshotUnchanged(expected: MainAuthJsonCredential): void {
307
- const current = readMainAuthJsonCredential();
360
+ const current = readMainAuthJsonCredential({ retainWith: false });
308
361
  if (!current || current.path !== expected.path || current.rawSha256 !== expected.rawSha256) {
309
362
  throw new MainAuthJsonChangedDuringRefreshError();
310
363
  }
@@ -436,7 +489,7 @@ export function beginNativeMainReauth(): {
436
489
  options?: { signal?: AbortSignal },
437
490
  ) => Promise<{ chatgptAccountId: string }>;
438
491
  } {
439
- const expected = readMainAuthJsonCredential();
492
+ const expected = readMainAuthJsonCredential({ retainWith: false });
440
493
  if (!expected || !expected.chatgptAccountId) {
441
494
  throw new NativeMainReauthUnavailableError(
442
495
  "No native main credential exists to reauthenticate; enrollment is the native profile workflow",
@@ -511,7 +564,16 @@ async function resolveMainAccountToken(
511
564
  ): Promise<{ accessToken: string; chatgptAccountId: string } | null> {
512
565
  if (dependencies.signal?.aborted) throw dependencies.signal.reason;
513
566
  const codexHome = resolveCodexHomeDir();
514
- const initial = readMainAuthJsonCredential();
567
+ let initial = readMainAuthJsonCredential({ serveRetained: true });
568
+ // Retention covers a rewrite, not a refresh: an expired or rejected retained bearer goes to the
569
+ // selected refresh owner exactly as an unavailable file would (#7345). Upstream rejecting the
570
+ // retained bearer is revocation evidence, so that copy is dropped for good.
571
+ if (initial?.retained && initial.accessToken === rejectedAccessToken) {
572
+ invalidateRetainedNativeMainLogin("revocation");
573
+ initial = null;
574
+ } else if (initial?.retained && !mainAccessTokenFresh(initial.accessToken, Date.now(), MAIN_TOKEN_REFRESH_SKEW_MS)) {
575
+ initial = null;
576
+ }
515
577
  // Every skip below ends a forced refresh WITHOUT asking the token endpoint anything, which from
516
578
  // the outside is indistinguishable from a refusal: same failed request, no write, no verdict.
517
579
  // A forced refresh is the only caller that passes `rejectedAccessToken`, so only it reports.
@@ -599,7 +661,9 @@ async function resolveMainAccountToken(
599
661
  resolveNativeProfileContext({ codexHome }),
600
662
  () => withCodexRefreshFileLock(lockKey, signal, async () => {
601
663
  if (resolveCodexHomeDir() !== codexHome) throw new MainAuthJsonChangedDuringRefreshError();
602
- const locked = readMainAuthJsonCredential();
664
+ // Captured before the exchange: an invalidation while it runs makes its completion stale.
665
+ const ticket = beginNativeMainObservation();
666
+ const locked = readMainAuthJsonCredential({ retainWith: ticket });
603
667
  if (!locked) throw new MainAuthJsonChangedDuringRefreshError();
604
668
  if (credentialRefreshGrantRejected(locked)) throw new MainAccountTokenRefreshError("reauth");
605
669
  if (!locked.refreshToken
@@ -666,6 +730,7 @@ async function resolveMainAccountToken(
666
730
  // A permitted in-flight success speaks only for its own profile and grant.
667
731
  clearMainRefreshGrantRejection(mainRefreshGrantKey(locked)!);
668
732
  if (dependencies.preserveReauth !== true) clearAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID);
733
+ readMainAuthJsonCredential({ retainWith: ticket });
669
734
  if (dependencies.signal?.aborted) throw dependencies.signal.reason;
670
735
  return result;
671
736
  }),
@@ -712,7 +777,6 @@ async function refreshThroughCodex(
712
777
  codexHome: string,
713
778
  refresh = true,
714
779
  ): Promise<{ accessToken: string; chatgptAccountId: string } | null> {
715
- // Deferred to keep lifecycle's cache/plan cleanup off this module's load-time import cycle.
716
780
  const { observeCodexOwnedMainAccountCredential } = await import("./account-lifecycle");
717
781
  if (resolveCodexHomeDir() !== codexHome) throw new MainAuthJsonChangedDuringRefreshError();
718
782
  const identityGeneration = captureMainAccountIdentityGeneration();
@@ -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 });
@@ -0,0 +1,276 @@
1
+ import { closeSync, constants as fsConstants, fstatSync, openSync } from "node:fs";
2
+ import { readNativeMainAuthBytesWithIdentity } from "./native-main-auth-file";
3
+ import { codexCredentialMutationEpoch } from "./credential-mutation-epoch";
4
+ import { captureMainAccountIdentityGeneration, isMainAccountIdentityGenerationLive } from "./main-account-cache";
5
+ import { sameFileIdentity, type FileIdentity } from "../lib/file-identity";
6
+
7
+ /**
8
+ * Retention of the last complete native-main login while Codex rewrites its login file (#7345).
9
+ *
10
+ * Codex rewrites the file in place (truncate, then write), so a reader can briefly see it empty
11
+ * or half written. The owner's contract: only those two states may be answered from the last
12
+ * complete login, and only while it is still provably the same owner's same file. Everything
13
+ * else is authoritative and ends retention at once, with no time window to wait out:
14
+ *
15
+ * - a missing file (logout or deletion; Codex may still confirm a login through its own RPC,
16
+ * which the caller asks separately),
17
+ * - a well-formed file without a ChatGPT token pair (explicit no-login or an API-key login),
18
+ * - an unreadable file,
19
+ * - account replacement (another OpenCodex credential publication, a different file identity,
20
+ * or a complete file naming a different login),
21
+ * - pause or revocation of the main account,
22
+ * - a change of the selected or configured refresh owner,
23
+ * - ownership loss (another home or path, the cross-process owner lock released, or native-main
24
+ * traffic blocked by recovery).
25
+ *
26
+ * File identity is only meaningful while its inode number cannot be reused: on POSIX the retained
27
+ * entry keeps a descriptor open on the file it was read from, so a deleted and recreated file
28
+ * always gets a new number, and a retained file that is no longer linked is never served.
29
+ *
30
+ * Retention never serves a write guard: callers that compare the file before publishing read the
31
+ * physical observation. It also never vouches for an expired access token; that goes to the
32
+ * selected refresh owner exactly as an unavailable file would.
33
+ */
34
+
35
+ export type NativeMainAuthObservation =
36
+ | {
37
+ kind: "complete";
38
+ raw: string;
39
+ root: Record<string, unknown>;
40
+ tokens: Record<string, unknown>;
41
+ /** dev/ino of the file the bytes came from, or null when it changed during the read. */
42
+ identity: FileIdentity | null;
43
+ }
44
+ /** Empty or not yet parseable: the in-place rewrite window. */
45
+ | { kind: "incomplete"; identity: FileIdentity | null }
46
+ /** Well-formed but carries no ChatGPT access or refresh token. */
47
+ | { kind: "no-login" }
48
+ | { kind: "missing" }
49
+ | { kind: "unreadable" };
50
+
51
+ export type NativeMainRetentionInvalidation =
52
+ | "logout"
53
+ | "missing"
54
+ | "unreadable"
55
+ | "account-replacement"
56
+ | "pause"
57
+ | "revocation"
58
+ | "refresh-mode-change"
59
+ | "ownership-loss";
60
+
61
+ export interface NativeMainLoginOwner {
62
+ readonly codexHome: string;
63
+ readonly path: string;
64
+ }
65
+
66
+ /** A retention/identity fence; refreshes capture it before the asynchronous exchange. */
67
+ export interface NativeMainObservationTicket {
68
+ readonly generation: number;
69
+ readonly identityGeneration: number;
70
+ }
71
+
72
+ export interface RetainNativeMainLoginOptions {
73
+ /** Content fingerprint; an unchanged login keeps its entry, descriptor and configured mode. */
74
+ fingerprint: string;
75
+ /** The configured refresh owner, read only when a new login is retained. */
76
+ configuredRefreshMode: () => string;
77
+ }
78
+
79
+ interface RetainedLogin {
80
+ readonly owner: NativeMainLoginOwner;
81
+ readonly identity: FileIdentity;
82
+ readonly fingerprint: string;
83
+ readonly configuredRefreshMode: string;
84
+ readonly identityGeneration: number;
85
+ readonly fd: number | undefined;
86
+ mutationEpoch: number;
87
+ credential: unknown;
88
+ }
89
+
90
+ let retained: RetainedLogin | undefined;
91
+ let generation = 0;
92
+ let lastRefreshMode: string | undefined;
93
+ let lastInvalidation: NativeMainRetentionInvalidation | undefined;
94
+
95
+ function isRecord(value: unknown): value is Record<string, unknown> {
96
+ return value !== null && typeof value === "object" && !Array.isArray(value);
97
+ }
98
+
99
+ function nonEmptyString(value: unknown): boolean {
100
+ return typeof value === "string" && value.trim().length > 0;
101
+ }
102
+
103
+ function closeQuietly(fd: number | undefined): void {
104
+ if (fd === undefined) return;
105
+ try { closeSync(fd); } catch { /* already closed */ }
106
+ }
107
+
108
+ function drop(): void {
109
+ const entry = retained;
110
+ retained = undefined;
111
+ closeQuietly(entry?.fd);
112
+ }
113
+
114
+ /** Classify login file text. A truncated JSON object never parses, so a partial write is "incomplete". */
115
+ export function classifyNativeMainAuthText(raw: string, identity: FileIdentity | null = null): NativeMainAuthObservation {
116
+ if (!raw.trim()) return { kind: "incomplete", identity };
117
+ let parsed: unknown;
118
+ try {
119
+ parsed = JSON.parse(raw);
120
+ } catch {
121
+ return { kind: "incomplete", identity };
122
+ }
123
+ if (!isRecord(parsed) || !isRecord(parsed.tokens)) return { kind: "no-login" };
124
+ if (!nonEmptyString(parsed.tokens.access_token) && !nonEmptyString(parsed.tokens.refresh_token)) {
125
+ return { kind: "no-login" };
126
+ }
127
+ return { kind: "complete", raw, root: parsed, tokens: parsed.tokens, identity };
128
+ }
129
+
130
+ function missingOrUnreadable(error: unknown): NativeMainAuthObservation {
131
+ const code = (error as NodeJS.ErrnoException | null)?.code;
132
+ return { kind: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable" };
133
+ }
134
+
135
+ /**
136
+ * One physical observation through the #7918 reader. The bytes come from its plain read and the
137
+ * identity from a stat before and after it; a replacement during the read leaves the identity null,
138
+ * so nothing is retained or served for those bytes.
139
+ */
140
+ export function observeNativeMainAuthFile(path: string): NativeMainAuthObservation {
141
+ let read: ReturnType<typeof readNativeMainAuthBytesWithIdentity>;
142
+ try {
143
+ read = readNativeMainAuthBytesWithIdentity(path);
144
+ } catch (error) {
145
+ return missingOrUnreadable(error);
146
+ }
147
+ return classifyNativeMainAuthText(read.bytes.toString("utf8"), read.identity);
148
+ }
149
+
150
+ export function beginNativeMainObservation(): NativeMainObservationTicket {
151
+ return { generation, identityGeneration: captureMainAccountIdentityGeneration() };
152
+ }
153
+
154
+ /** End retention now. Pending observations captured before this call can no longer retain. */
155
+ export function invalidateRetainedNativeMainLogin(reason: NativeMainRetentionInvalidation): void {
156
+ generation += 1;
157
+ drop();
158
+ lastInvalidation = reason;
159
+ }
160
+
161
+ /** Hold the file's inode on POSIX so its number cannot be reused while retained. */
162
+ function holdFile(path: string, identity: FileIdentity): number | undefined | null {
163
+ if (process.platform === "win32") return undefined;
164
+ let fd: number | undefined;
165
+ try {
166
+ fd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
167
+ const held = fstatSync(fd, { bigint: true });
168
+ if (held.isFile() && sameFileIdentity({ dev: held.dev, ino: held.ino }, identity)) return fd;
169
+ } catch { /* the file moved; nothing to hold */ }
170
+ closeQuietly(fd);
171
+ return null;
172
+ }
173
+
174
+ /**
175
+ * Record a complete login. Refused for a stale ticket (an invalidation happened while the
176
+ * observation or refresh was in flight), an account identity change, or an unknown or moved file identity.
177
+ */
178
+ export function retainNativeMainLogin(
179
+ ticket: NativeMainObservationTicket,
180
+ owner: NativeMainLoginOwner,
181
+ identity: FileIdentity | null,
182
+ credential: unknown,
183
+ options: RetainNativeMainLoginOptions,
184
+ ): boolean {
185
+ if (ticket.generation !== generation || !isMainAccountIdentityGenerationLive(ticket.identityGeneration)) return false;
186
+ if (!identity) {
187
+ drop();
188
+ return false;
189
+ }
190
+ const current = retained;
191
+ if (current && current.owner.codexHome === owner.codexHome && current.owner.path === owner.path
192
+ && current.identityGeneration === ticket.identityGeneration
193
+ && sameFileIdentity(current.identity, identity) && current.fingerprint === options.fingerprint) {
194
+ current.mutationEpoch = codexCredentialMutationEpoch();
195
+ current.credential = credential;
196
+ return true;
197
+ }
198
+ drop();
199
+ const fd = holdFile(owner.path, identity);
200
+ if (fd === null) return false;
201
+ retained = {
202
+ owner: { codexHome: owner.codexHome, path: owner.path },
203
+ identity,
204
+ fingerprint: options.fingerprint,
205
+ configuredRefreshMode: options.configuredRefreshMode(),
206
+ identityGeneration: ticket.identityGeneration,
207
+ fd,
208
+ mutationEpoch: codexCredentialMutationEpoch(),
209
+ credential,
210
+ };
211
+ return true;
212
+ }
213
+
214
+ function heldFileStillLinked(fd: number | undefined): boolean {
215
+ if (fd === undefined) return true;
216
+ try {
217
+ return fstatSync(fd, { bigint: true }).nlink > 0n;
218
+ } catch {
219
+ return false;
220
+ }
221
+ }
222
+
223
+ /**
224
+ * The retained login for an incomplete observation of the same owner's same file, or undefined.
225
+ * Any mismatch is itself authoritative and ends retention. `configuredRefreshMode` is read only
226
+ * when a retained login exists.
227
+ */
228
+ export function retainedNativeMainLogin<T>(
229
+ owner: NativeMainLoginOwner,
230
+ identity: FileIdentity | null,
231
+ configuredRefreshMode: () => string,
232
+ ): T | undefined {
233
+ const entry = retained;
234
+ if (!entry) return undefined;
235
+ if (entry.owner.codexHome !== owner.codexHome || entry.owner.path !== owner.path) {
236
+ invalidateRetainedNativeMainLogin("ownership-loss");
237
+ return undefined;
238
+ }
239
+ if (!isMainAccountIdentityGenerationLive(entry.identityGeneration)
240
+ || entry.mutationEpoch !== codexCredentialMutationEpoch() || !identity
241
+ || !sameFileIdentity(identity, entry.identity) || !heldFileStillLinked(entry.fd)) {
242
+ invalidateRetainedNativeMainLogin("account-replacement");
243
+ return undefined;
244
+ }
245
+ if (configuredRefreshMode() !== entry.configuredRefreshMode) {
246
+ invalidateRetainedNativeMainLogin("refresh-mode-change");
247
+ return undefined;
248
+ }
249
+ return entry.credential as T;
250
+ }
251
+
252
+ /** The authoritative invalidation an observation implies, if any. */
253
+ export function invalidationForObservation(observation: NativeMainAuthObservation): NativeMainRetentionInvalidation | undefined {
254
+ if (observation.kind === "missing") return "missing";
255
+ if (observation.kind === "no-login") return "logout";
256
+ if (observation.kind === "unreadable") return "unreadable";
257
+ return undefined;
258
+ }
259
+
260
+ /** Every resolution of the refresh owner reports here; a different owner ends retention. */
261
+ export function observeNativeMainRefreshMode(mode: string): void {
262
+ if (lastRefreshMode !== undefined && lastRefreshMode !== mode) invalidateRetainedNativeMainLogin("refresh-mode-change");
263
+ lastRefreshMode = mode;
264
+ }
265
+
266
+ /** Diagnostic for tests: why retention last ended. */
267
+ export function lastNativeMainRetentionInvalidationForTests(): NativeMainRetentionInvalidation | undefined {
268
+ return lastInvalidation;
269
+ }
270
+
271
+ export function resetNativeMainRetentionForTests(): void {
272
+ drop();
273
+ generation += 1;
274
+ lastRefreshMode = undefined;
275
+ lastInvalidation = undefined;
276
+ }
@@ -10,6 +10,7 @@ import {
10
10
  } from "./native-main-lock-file";
11
11
  import type { NativeProfileContext } from "./native-profile-store";
12
12
  import { NativeProfileError } from "./native-profile-types";
13
+ import { invalidateRetainedNativeMainLogin } from "./native-main-credentials";
13
14
 
14
15
  export const NATIVE_MAIN_OWNER_RETRY_MS = 250;
15
16
  export const NATIVE_MAIN_OWNER_DB = ".opencodex-native-main.owner.sqlite";
@@ -92,6 +93,8 @@ export function nativeMainOwnerFilesystemSupported(
92
93
  }
93
94
 
94
95
  function publish(entry: OwnerEntry, snapshot: NativeMainOwnerSnapshot): void {
96
+ // Losing the cross-process owner lock ends a retained native-main login (#7345).
97
+ if (entry.snapshot.status === "held" && snapshot.status !== "held") invalidateRetainedNativeMainLogin("ownership-loss");
95
98
  entry.snapshot = snapshot;
96
99
  for (const listener of entry.listeners) {
97
100
  try { listener({ ...snapshot }); } catch { /* an observer cannot forfeit process ownership */ }
@@ -20,6 +20,7 @@ import { compareCodexVersions, displayCodexRuntimePath, resolveCodexRuntimeAsync
20
20
  import type { ResolveCodexRuntimeResult } from "./runtime";
21
21
  import { isTestHomeGuardArmed } from "../lib/test-home-guard";
22
22
  import type { OcxConfig } from "../types/config";
23
+ import { observeNativeMainRefreshMode } from "./native-main-credentials";
23
24
 
24
25
  export type NativeMainRefreshMode = "codex" | "opencodex";
25
26
 
@@ -66,14 +67,26 @@ export function setNativeMainRefreshResolutionForTests(value: NativeMainRefreshR
66
67
  resolutionForTests = value;
67
68
  }
68
69
 
69
- function configuredMode(config: Pick<OcxConfig, "nativeMainRefresh"> | null | undefined): NativeMainRefreshMode | "auto" {
70
+ /** The operator's configured refresh owner, before runtime resolution. */
71
+ export function configuredNativeMainRefreshMode(config: Pick<OcxConfig, "nativeMainRefresh"> | null | undefined): NativeMainRefreshMode | "auto" {
70
72
  const value = config?.nativeMainRefresh;
71
73
  return value === "codex" || value === "opencodex" ? value : "auto";
72
74
  }
75
+ const configuredMode = configuredNativeMainRefreshMode;
73
76
 
74
77
  export async function resolveNativeMainRefreshMode(
75
78
  config: Pick<OcxConfig, "nativeMainRefresh"> | null | undefined,
76
79
  deps: { resolveRuntime?: () => Promise<ResolveCodexRuntimeResult> } = {},
80
+ ): Promise<NativeMainRefreshResolution> {
81
+ const resolution = await resolveNativeMainRefreshOwner(config, deps);
82
+ // A different refresh owner ends any retained native-main login (#7345).
83
+ observeNativeMainRefreshMode(resolution.mode);
84
+ return resolution;
85
+ }
86
+
87
+ async function resolveNativeMainRefreshOwner(
88
+ config: Pick<OcxConfig, "nativeMainRefresh"> | null | undefined,
89
+ deps: { resolveRuntime?: () => Promise<ResolveCodexRuntimeResult> },
77
90
  ): Promise<NativeMainRefreshResolution> {
78
91
  if (resolutionForTests) return resolutionForTests;
79
92
  const configured = configuredMode(config);