@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
@@ -0,0 +1,270 @@
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 { sameFileIdentity, type FileIdentity } from "../lib/file-identity";
5
+
6
+ /**
7
+ * Retention of the last complete native-main login while Codex rewrites its login file (#7345).
8
+ *
9
+ * Codex rewrites the file in place (truncate, then write), so a reader can briefly see it empty
10
+ * or half written. The owner's contract: only those two states may be answered from the last
11
+ * complete login, and only while it is still provably the same owner's same file. Everything
12
+ * else is authoritative and ends retention at once, with no time window to wait out:
13
+ *
14
+ * - a missing file (logout or deletion; Codex may still confirm a login through its own RPC,
15
+ * which the caller asks separately),
16
+ * - a well-formed file without a ChatGPT token pair (explicit no-login or an API-key login),
17
+ * - an unreadable file,
18
+ * - account replacement (another OpenCodex credential publication, a different file identity,
19
+ * or a complete file naming a different login),
20
+ * - pause or revocation of the main account,
21
+ * - a change of the selected or configured refresh owner,
22
+ * - ownership loss (another home or path, the cross-process owner lock released, or native-main
23
+ * traffic blocked by recovery).
24
+ *
25
+ * File identity is only meaningful while its inode number cannot be reused: on POSIX the retained
26
+ * entry keeps a descriptor open on the file it was read from, so a deleted and recreated file
27
+ * always gets a new number, and a retained file that is no longer linked is never served.
28
+ *
29
+ * Retention never serves a write guard: callers that compare the file before publishing read the
30
+ * physical observation. It also never vouches for an expired access token; that goes to the
31
+ * selected refresh owner exactly as an unavailable file would.
32
+ */
33
+
34
+ export type NativeMainAuthObservation =
35
+ | {
36
+ kind: "complete";
37
+ raw: string;
38
+ root: Record<string, unknown>;
39
+ tokens: Record<string, unknown>;
40
+ /** dev/ino of the file the bytes came from, or null when it changed during the read. */
41
+ identity: FileIdentity | null;
42
+ }
43
+ /** Empty or not yet parseable: the in-place rewrite window. */
44
+ | { kind: "incomplete"; identity: FileIdentity | null }
45
+ /** Well-formed but carries no ChatGPT access or refresh token. */
46
+ | { kind: "no-login" }
47
+ | { kind: "missing" }
48
+ | { kind: "unreadable" };
49
+
50
+ export type NativeMainRetentionInvalidation =
51
+ | "logout"
52
+ | "missing"
53
+ | "unreadable"
54
+ | "account-replacement"
55
+ | "pause"
56
+ | "revocation"
57
+ | "refresh-mode-change"
58
+ | "ownership-loss";
59
+
60
+ export interface NativeMainLoginOwner {
61
+ readonly codexHome: string;
62
+ readonly path: string;
63
+ }
64
+
65
+ /** Captured before an observation starts; a completion under an older generation is stale. */
66
+ export interface NativeMainObservationTicket {
67
+ readonly generation: number;
68
+ }
69
+
70
+ export interface RetainNativeMainLoginOptions {
71
+ /** Content fingerprint; an unchanged login keeps its entry, descriptor and configured mode. */
72
+ fingerprint: string;
73
+ /** The configured refresh owner, read only when a new login is retained. */
74
+ configuredRefreshMode: () => string;
75
+ }
76
+
77
+ interface RetainedLogin {
78
+ readonly owner: NativeMainLoginOwner;
79
+ readonly identity: FileIdentity;
80
+ readonly fingerprint: string;
81
+ readonly configuredRefreshMode: string;
82
+ readonly fd: number | undefined;
83
+ mutationEpoch: number;
84
+ credential: unknown;
85
+ }
86
+
87
+ let retained: RetainedLogin | undefined;
88
+ let generation = 0;
89
+ let lastRefreshMode: string | undefined;
90
+ let lastInvalidation: NativeMainRetentionInvalidation | undefined;
91
+
92
+ function isRecord(value: unknown): value is Record<string, unknown> {
93
+ return value !== null && typeof value === "object" && !Array.isArray(value);
94
+ }
95
+
96
+ function nonEmptyString(value: unknown): boolean {
97
+ return typeof value === "string" && value.trim().length > 0;
98
+ }
99
+
100
+ function closeQuietly(fd: number | undefined): void {
101
+ if (fd === undefined) return;
102
+ try { closeSync(fd); } catch { /* already closed */ }
103
+ }
104
+
105
+ function drop(): void {
106
+ const entry = retained;
107
+ retained = undefined;
108
+ closeQuietly(entry?.fd);
109
+ }
110
+
111
+ /** Classify login file text. A truncated JSON object never parses, so a partial write is "incomplete". */
112
+ export function classifyNativeMainAuthText(raw: string, identity: FileIdentity | null = null): NativeMainAuthObservation {
113
+ if (!raw.trim()) return { kind: "incomplete", identity };
114
+ let parsed: unknown;
115
+ try {
116
+ parsed = JSON.parse(raw);
117
+ } catch {
118
+ return { kind: "incomplete", identity };
119
+ }
120
+ if (!isRecord(parsed) || !isRecord(parsed.tokens)) return { kind: "no-login" };
121
+ if (!nonEmptyString(parsed.tokens.access_token) && !nonEmptyString(parsed.tokens.refresh_token)) {
122
+ return { kind: "no-login" };
123
+ }
124
+ return { kind: "complete", raw, root: parsed, tokens: parsed.tokens, identity };
125
+ }
126
+
127
+ function missingOrUnreadable(error: unknown): NativeMainAuthObservation {
128
+ const code = (error as NodeJS.ErrnoException | null)?.code;
129
+ return { kind: code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unreadable" };
130
+ }
131
+
132
+ /**
133
+ * One physical observation through the #7918 reader. The bytes come from its plain read and the
134
+ * identity from a stat before and after it; a replacement during the read leaves the identity null,
135
+ * so nothing is retained or served for those bytes.
136
+ */
137
+ export function observeNativeMainAuthFile(path: string): NativeMainAuthObservation {
138
+ let read: ReturnType<typeof readNativeMainAuthBytesWithIdentity>;
139
+ try {
140
+ read = readNativeMainAuthBytesWithIdentity(path);
141
+ } catch (error) {
142
+ return missingOrUnreadable(error);
143
+ }
144
+ return classifyNativeMainAuthText(read.bytes.toString("utf8"), read.identity);
145
+ }
146
+
147
+ export function beginNativeMainObservation(): NativeMainObservationTicket {
148
+ return { generation };
149
+ }
150
+
151
+ /** End retention now. Pending observations captured before this call can no longer retain. */
152
+ export function invalidateRetainedNativeMainLogin(reason: NativeMainRetentionInvalidation): void {
153
+ generation += 1;
154
+ drop();
155
+ lastInvalidation = reason;
156
+ }
157
+
158
+ /** Hold the file's inode on POSIX so its number cannot be reused while retained. */
159
+ function holdFile(path: string, identity: FileIdentity): number | undefined | null {
160
+ if (process.platform === "win32") return undefined;
161
+ let fd: number | undefined;
162
+ try {
163
+ fd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW | fsConstants.O_NONBLOCK);
164
+ const held = fstatSync(fd, { bigint: true });
165
+ if (held.isFile() && sameFileIdentity({ dev: held.dev, ino: held.ino }, identity)) return fd;
166
+ } catch { /* the file moved; nothing to hold */ }
167
+ closeQuietly(fd);
168
+ return null;
169
+ }
170
+
171
+ /**
172
+ * Record a complete login. Refused for a stale ticket (an invalidation happened while the
173
+ * observation or refresh was in flight) or an unknown or moved file identity.
174
+ */
175
+ export function retainNativeMainLogin(
176
+ ticket: NativeMainObservationTicket,
177
+ owner: NativeMainLoginOwner,
178
+ identity: FileIdentity | null,
179
+ credential: unknown,
180
+ options: RetainNativeMainLoginOptions,
181
+ ): boolean {
182
+ if (ticket.generation !== generation) return false;
183
+ if (!identity) {
184
+ drop();
185
+ return false;
186
+ }
187
+ const current = retained;
188
+ if (current && current.owner.codexHome === owner.codexHome && current.owner.path === owner.path
189
+ && sameFileIdentity(current.identity, identity) && current.fingerprint === options.fingerprint) {
190
+ current.mutationEpoch = codexCredentialMutationEpoch();
191
+ current.credential = credential;
192
+ return true;
193
+ }
194
+ drop();
195
+ const fd = holdFile(owner.path, identity);
196
+ if (fd === null) return false;
197
+ retained = {
198
+ owner: { codexHome: owner.codexHome, path: owner.path },
199
+ identity,
200
+ fingerprint: options.fingerprint,
201
+ configuredRefreshMode: options.configuredRefreshMode(),
202
+ fd,
203
+ mutationEpoch: codexCredentialMutationEpoch(),
204
+ credential,
205
+ };
206
+ return true;
207
+ }
208
+
209
+ function heldFileStillLinked(fd: number | undefined): boolean {
210
+ if (fd === undefined) return true;
211
+ try {
212
+ return fstatSync(fd, { bigint: true }).nlink > 0n;
213
+ } catch {
214
+ return false;
215
+ }
216
+ }
217
+
218
+ /**
219
+ * The retained login for an incomplete observation of the same owner's same file, or undefined.
220
+ * Any mismatch is itself authoritative and ends retention. `configuredRefreshMode` is read only
221
+ * when a retained login exists.
222
+ */
223
+ export function retainedNativeMainLogin<T>(
224
+ owner: NativeMainLoginOwner,
225
+ identity: FileIdentity | null,
226
+ configuredRefreshMode: () => string,
227
+ ): T | undefined {
228
+ const entry = retained;
229
+ if (!entry) return undefined;
230
+ if (entry.owner.codexHome !== owner.codexHome || entry.owner.path !== owner.path) {
231
+ invalidateRetainedNativeMainLogin("ownership-loss");
232
+ return undefined;
233
+ }
234
+ if (entry.mutationEpoch !== codexCredentialMutationEpoch() || !identity
235
+ || !sameFileIdentity(identity, entry.identity) || !heldFileStillLinked(entry.fd)) {
236
+ invalidateRetainedNativeMainLogin("account-replacement");
237
+ return undefined;
238
+ }
239
+ if (configuredRefreshMode() !== entry.configuredRefreshMode) {
240
+ invalidateRetainedNativeMainLogin("refresh-mode-change");
241
+ return undefined;
242
+ }
243
+ return entry.credential as T;
244
+ }
245
+
246
+ /** The authoritative invalidation an observation implies, if any. */
247
+ export function invalidationForObservation(observation: NativeMainAuthObservation): NativeMainRetentionInvalidation | undefined {
248
+ if (observation.kind === "missing") return "missing";
249
+ if (observation.kind === "no-login") return "logout";
250
+ if (observation.kind === "unreadable") return "unreadable";
251
+ return undefined;
252
+ }
253
+
254
+ /** Every resolution of the refresh owner reports here; a different owner ends retention. */
255
+ export function observeNativeMainRefreshMode(mode: string): void {
256
+ if (lastRefreshMode !== undefined && lastRefreshMode !== mode) invalidateRetainedNativeMainLogin("refresh-mode-change");
257
+ lastRefreshMode = mode;
258
+ }
259
+
260
+ /** Diagnostic for tests: why retention last ended. */
261
+ export function lastNativeMainRetentionInvalidationForTests(): NativeMainRetentionInvalidation | undefined {
262
+ return lastInvalidation;
263
+ }
264
+
265
+ export function resetNativeMainRetentionForTests(): void {
266
+ drop();
267
+ generation += 1;
268
+ lastRefreshMode = undefined;
269
+ lastInvalidation = undefined;
270
+ }
@@ -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);
@@ -42,6 +42,14 @@ type MainPolicyQuota = { identityKey: string; quota: StoredAccountQuota };
42
42
  /** Fresh WHAM topology proof is consumed by the merge, never retained in a cache or DTO. */
43
43
  type MainPolicyQuotaObservation = Omit<StoredAccountQuota, "updatedAt"> & { shortWindowAbsent?: true; monthlyWindowAbsent?: true };
44
44
  let mainPolicyQuota: MainPolicyQuota | null = null;
45
+ /**
46
+ * When each main policy usage window was last measured in this process (#8113). A window's time
47
+ * moves only when a write measures that window's percentage; reset metadata, credits and other
48
+ * windows never renew it. Process-local and never persisted: a reading restored from disk has none.
49
+ */
50
+ type PolicyUsageWindow = "shortPercent" | "weeklyPercent" | "monthlyPercent";
51
+ const POLICY_USAGE_WINDOWS: readonly PolicyUsageWindow[] = ["shortPercent", "weeklyPercent", "monthlyPercent"];
52
+ let mainPolicyUsageObservation: { identityKey: string; at: Partial<Record<PolicyUsageWindow, number>> } | undefined;
45
53
  let diskHydrated = false;
46
54
  let persistTimer: ReturnType<typeof setTimeout> | null = null;
47
55
  let persistStartedAt: number | null = null;
@@ -442,6 +450,13 @@ export function setAccountQuotaFromParsed(
442
450
  const policyExisting = mainWriter && mainPolicyQuota?.identityKey === mainWriter.identityKey
443
451
  ? mainPolicyQuota.quota
444
452
  : undefined;
453
+ // Only a measured percentage renews its own window; anything else keeps the earlier time.
454
+ if (mainWriter && policyQuota) {
455
+ const at = mainPolicyUsageObservation?.identityKey === mainWriter.identityKey && policyExisting
456
+ ? { ...mainPolicyUsageObservation.at } : {};
457
+ for (const window of POLICY_USAGE_WINDOWS) if (finitePercent(policyQuota[window])) at[window] = updatedAt;
458
+ mainPolicyUsageObservation = { identityKey: mainWriter.identityKey, at };
459
+ }
445
460
  mainPolicyQuota = mainWriter && (policyQuota || policyExisting)
446
461
  ? {
447
462
  identityKey: mainWriter.identityKey,
@@ -450,6 +465,7 @@ export function setAccountQuotaFromParsed(
450
465
  : policyExisting!,
451
466
  }
452
467
  : null;
468
+ if (!mainPolicyQuota) mainPolicyUsageObservation = undefined;
453
469
  }
454
470
  schedulePersistAccountQuotas();
455
471
  // Credits carry the previous usage tuple; they must not refresh its observation clock.
@@ -831,7 +847,7 @@ export function updateAccountQuota(
831
847
  stampCodexQuotaUsageObservation(quota, { weeklyPercent: nextWeekly, monthlyPercent: nextMonthly }, existing);
832
848
  accountQuota.set(accountId, quota);
833
849
  // This legacy writer has no physical credential provenance.
834
- if (accountId === MAIN_CODEX_ACCOUNT_ID) mainPolicyQuota = null;
850
+ if (accountId === MAIN_CODEX_ACCOUNT_ID) { mainPolicyQuota = null; mainPolicyUsageObservation = undefined; }
835
851
  schedulePersistAccountQuotas();
836
852
  // Observed like the other committed write. This function has no in-repo caller today, but it
837
853
  // is re-exported as public API through src/codex/auth-api.ts, so a future caller would
@@ -898,6 +914,7 @@ function hydrateAccountQuotasFromDisk(): void {
898
914
  quotaHistory.hydrate(parsed.history);
899
915
  // Policy evidence deliberately outlives the legacy six-hour rotation-cache TTL.
900
916
  mainPolicyQuota = readMainPolicyQuota(parsed.mainPolicyQuota);
917
+ mainPolicyUsageObservation = undefined;
901
918
  const now = Date.now();
902
919
  for (const [accountId, quota] of Object.entries(parsed.quotas)) {
903
920
  if (!quota || typeof quota !== "object" || typeof quota.updatedAt !== "number") continue;
@@ -955,6 +972,26 @@ export function getMainPolicyQuota(): StoredAccountQuota | null {
955
972
  return structuredClone(mainPolicyQuota.quota);
956
973
  }
957
974
 
975
+ /**
976
+ * The oldest measurement time among the windows the observed main identity's policy reading
977
+ * retains, or undefined when any of them was not measured in this process (for example a reading
978
+ * restored from disk) (#8113). Any stale retained window therefore makes the whole reading stale.
979
+ */
980
+ export function getMainPolicyUsageObservedAt(): number | undefined {
981
+ hydrateAccountQuotasFromDisk();
982
+ if (!mainPolicyQuota || mainPolicyQuota.identityKey !== getObservedMainQuotaIdentityKey()) return undefined;
983
+ const observation = mainPolicyUsageObservation?.identityKey === mainPolicyQuota.identityKey
984
+ ? mainPolicyUsageObservation.at : undefined;
985
+ let oldest: number | undefined;
986
+ for (const window of POLICY_USAGE_WINDOWS) {
987
+ if (!finitePercent(mainPolicyQuota.quota[window])) continue;
988
+ const at = observation?.[window];
989
+ if (at === undefined) return undefined;
990
+ oldest = oldest === undefined ? at : Math.min(oldest, at);
991
+ }
992
+ return oldest;
993
+ }
994
+
958
995
  /** An owned identity observation may retire legacy main quota only when its retained policy tag proves replacement. */
959
996
  export function discardMismatchedMainQuota(): void {
960
997
  hydrateAccountQuotasFromDisk();
@@ -1001,14 +1038,14 @@ export function clearAccountQuota(accountId?: string): void {
1001
1038
  if (accountId) {
1002
1039
  hydrateAccountQuotasFromDisk();
1003
1040
  accountQuota.delete(accountId);
1004
- if (accountId === MAIN_CODEX_ACCOUNT_ID) mainPolicyQuota = null;
1041
+ if (accountId === MAIN_CODEX_ACCOUNT_ID) { mainPolicyQuota = null; mainPolicyUsageObservation = undefined; }
1005
1042
  schedulePersistAccountQuotas();
1006
1043
  forgetCodexQuotaBaseline(accountId);
1007
1044
  return;
1008
1045
  }
1009
1046
  accountQuota.clear();
1010
1047
  forgetCodexQuotaBaseline();
1011
- mainPolicyQuota = null;
1048
+ { mainPolicyQuota = null; mainPolicyUsageObservation = undefined; }
1012
1049
  diskHydrated = false;
1013
1050
  if (persistTimer) {
1014
1051
  clearTimeout(persistTimer);
@@ -1063,7 +1100,8 @@ export function parseMainPolicyUsageQuota(data: WhamUsageResponse): MainPolicyQu
1063
1100
  const windows = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
1064
1101
  if (windows.some(window => isInvalidPolicyUsagePercent(window?.used_percent))) return null;
1065
1102
  const quota = filterMainPolicyMonthlyQuota(parseUsageQuota(data), isThirtyDayOnlyCodexPlan(data.plan_type));
1066
- return quota ? withWhamShortWindowAbsence(data, quota) : null;
1103
+ // #8596: a complete, allowed main read retires a carried monthly tuple under the pool proof (#8067).
1104
+ return quota ? withWhamMonthlyWindowAbsence(data, withWhamShortWindowAbsence(data, quota)) : null;
1067
1105
  }
1068
1106
 
1069
1107
  /** Derive absence from complete WHAM topology without changing the display quota. */
@@ -1097,22 +1135,33 @@ export function poolWhamPolicyObservation(
1097
1135
  data: WhamUsageResponse, quota: Omit<StoredAccountQuota, "updatedAt"> | null,
1098
1136
  ): MainPolicyQuotaObservation | null {
1099
1137
  if (!quota || !isValidWhamHistoryObservation(data)) return null;
1100
- // Retirement releases a block, so a present reading that does not parse is not "unknown".
1138
+ if (data.rate_limit?.allowed === false || hasMalformedWhamReading(data)) return quota;
1139
+ return withWhamMonthlyWindowAbsence(data, withWhamShortWindowAbsence(data, quota));
1140
+ }
1141
+
1142
+ /** Retirement releases a block, so a present reading that does not parse is not "unknown". */
1143
+ function hasMalformedWhamReading(data: WhamUsageResponse): boolean {
1101
1144
  const readings = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
1102
1145
  for (const limit of Array.isArray(data.additional_rate_limits) ? data.additional_rate_limits : []) {
1103
1146
  if (limit && typeof limit === "object") readings.push(limit.rate_limit?.primary_window, limit.rate_limit?.secondary_window);
1104
1147
  }
1105
- const malformed = readings.some(window => window?.used_percent != null
1148
+ return readings.some(window => window?.used_percent != null
1106
1149
  && normalizeUsagePercent(window.used_percent) === undefined);
1107
- if (data.rate_limit?.allowed === false || malformed) return quota;
1108
- const observation = withWhamShortWindowAbsence(data, quota);
1109
- // #8067: the same complete topology proves a pool account has no monthly window when no window
1110
- // declares a monthly duration and no tertiary window is present, so a plan change away from a
1111
- // monthly primary (Free to Pro Lite) retires the carried tuple. Pool-only: main observations
1112
- // keep their existing retention rules.
1150
+ }
1151
+
1152
+ /**
1153
+ * #8067/#8596: the complete topology that proves short-window absence also proves there is no
1154
+ * monthly window when no window declares a monthly duration and no tertiary window is present,
1155
+ * so a plan change away from a monthly primary (Free to Pro Lite) retires the carried tuple.
1156
+ * An explicit denial and invalid or unparseable readings never supply that proof.
1157
+ */
1158
+ function withWhamMonthlyWindowAbsence(
1159
+ data: WhamUsageResponse, observation: MainPolicyQuotaObservation,
1160
+ ): MainPolicyQuotaObservation {
1161
+ if (observation.shortWindowAbsent !== true || data.rate_limit?.allowed === false) return observation;
1162
+ if (!isValidWhamHistoryObservation(data) || hasMalformedWhamReading(data)) return observation;
1113
1163
  const [primary, secondary, tertiary] = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
1114
- return observation.shortWindowAbsent === true
1115
- && !isExplicitMonthlyWindow(primary) && !isExplicitMonthlyWindow(secondary) && tertiary == null
1164
+ return !isExplicitMonthlyWindow(primary) && !isExplicitMonthlyWindow(secondary) && tertiary == null
1116
1165
  ? { ...observation, monthlyWindowAbsent: true }
1117
1166
  : observation;
1118
1167
  }
@@ -2,7 +2,7 @@ import { parseResetCooldownMs } from "../codex/routing";
2
2
  import { CYBER_POLICY_FALLBACK_MESSAGE, TERMINAL_REFUSAL_FALLBACK_MESSAGE, classifyError, isCyberPolicyCode, isCyberPolicyMessage, isRateLimitOrQuotaFailureMessage, isSubscriptionGateMessage, isTerminalRefusalCode, safetyRefusalCodeFromMessage } from "../lib/errors";
3
3
  import { isHardPolicyOrOriginRefusal } from "../lib/hard-refusal";
4
4
  import { isNonReplayableUpstreamCode } from "../lib/upstream-retry";
5
- import { isAnthropicBillingFailure } from "../providers/anthropic-billing-refusal";
5
+ import { isAnthropicBillingFailure, isAnthropicExtraUsageFailure } from "../providers/anthropic-billing-refusal";
6
6
  import { hasConflictingReasoningEffortCode } from "../providers/reasoning-metadata";
7
7
  import { isKiroAccountProfileRefusal } from "../adapters/kiro-refusal";
8
8
  import type { OcxComboTarget } from "../types";
@@ -192,6 +192,16 @@ export function comboTargetCooldownExpiry(
192
192
  return entry.cooldownUntil;
193
193
  }
194
194
 
195
+ /** HTTP status recorded with the target's live cooldown, when the cooling failure had one. */
196
+ export function comboTargetCooldownStatus(
197
+ comboId: string,
198
+ target: Pick<OcxComboTarget, "provider" | "model">,
199
+ now = Date.now(),
200
+ ): number | undefined {
201
+ return isComboTargetInCooldown(comboId, target, now)
202
+ ? targetCooldowns.get(cooldownMapKey(comboId, target))?.status : undefined;
203
+ }
204
+
195
205
  /** Identity of the current live write, independent of its possibly repeated expiry. */
196
206
  export function comboTargetCooldownRevision(
197
207
  comboId: string,
@@ -1601,6 +1611,7 @@ function decideComboFailure(
1601
1611
  if (isResponseFormatCapabilityRefusal(status, message, rawCode)) return "hop";
1602
1612
  if (providerModerationHop(status, message, rawCode, options?.providerModerationRefusal, options?.malformedResponseFormat)) return "hop";
1603
1613
  if (isAnthropicBillingFailure(status, message, rawCode)) return "hop";
1614
+ if (isAnthropicExtraUsageFailure(status, message, rawCode)) return "hop";
1604
1615
  // Kiro's body validator rejects the request for the identity it was routed under. The account
1605
1616
  // layer rotates logins first; this is the no-alternate case, so the next combo target is the
1606
1617
  // only remaining chance to serve the turn. Only a caller that knows the failed target is a Kiro
@@ -22,8 +22,11 @@ export {
22
22
  export {
23
23
  advanceComboAfterFailure,
24
24
  clearComboSelectionState,
25
+ comboExclusion,
25
26
  comboExclusionReasons,
27
+ comboTargetUnavailableCause,
26
28
  comboTargetSkipTrigger,
29
+ comboUnavailableDiagnostics,
27
30
  NoAvailableComboTargetsError,
28
31
  noteComboFailure,
29
32
  noteComboSuccess,
@@ -34,7 +37,9 @@ export {
34
37
  snapshotComboQuotaCooldowns,
35
38
  tryPickComboModel,
36
39
  UnknownComboError,
40
+ type ComboExclusion,
37
41
  type ComboPick,
42
+ type ComboUnavailableDiagnostics,
38
43
  type QuotaInactiveReason,
39
44
  } from "./resolve";
40
45
  export {