@bitkyc08/opencodex 2.95.0 → 2.97.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (276) hide show
  1. package/bin/ocx.mjs +214 -19
  2. package/gui/dist/assets/{App-8yedBkhm.js → App-DuNhggE1.js} +18 -18
  3. package/gui/dist/assets/{Tray-erSMzxPG.js → Tray-CEw0y0jR.js} +1 -1
  4. package/gui/dist/assets/index-CynE_Rue.js +94 -0
  5. package/gui/dist/assets/{quota-summary-BK4VuQNc.js → quota-summary-VHFSlUuM.js} +1 -1
  6. package/gui/dist/index.html +1 -1
  7. package/package.json +1 -1
  8. package/src/adapters/command-code.ts +15 -16
  9. package/src/adapters/cursor/transport-retry.ts +2 -2
  10. package/src/adapters/devin/cloud-direct/chat.ts +15 -6
  11. package/src/adapters/kiro/stream.ts +63 -4
  12. package/src/adapters/kiro-constants.ts +15 -1
  13. package/src/adapters/kiro-events.ts +31 -1
  14. package/src/adapters/kiro-retry.ts +3 -3
  15. package/src/adapters/ollama-native.ts +21 -7
  16. package/src/adapters/openai-responses/canonical-forward.ts +50 -13
  17. package/src/adapters/openai-responses/empty-assistant.ts +15 -3
  18. package/src/adapters/openai-responses/passthrough.ts +8 -8
  19. package/src/adapters/openai-responses/reasoning.ts +9 -4
  20. package/src/adapters/openai-responses/request-strips.ts +1 -1
  21. package/src/adapters/openai-responses/transport.ts +17 -26
  22. package/src/adapters/physical-send.ts +3 -3
  23. package/src/adapters/qoder/adapter.ts +1 -1
  24. package/src/adapters/qoder/image-input.ts +5 -2
  25. package/src/adapters/zed-openai-stream.ts +2 -1
  26. package/src/bridge/errors.ts +11 -2
  27. package/src/bridge/response-json.ts +2 -1
  28. package/src/bridge/sse.ts +14 -6
  29. package/src/chat/failure-verdict.ts +21 -0
  30. package/src/chat/outbound.ts +139 -21
  31. package/src/claude/outbound.ts +49 -2
  32. package/src/cli/agent.ts +44 -15
  33. package/src/cli/capabilities-agents-routing.ts +9 -0
  34. package/src/cli/capabilities-base.ts +25 -3
  35. package/src/cli/capabilities-command.ts +12 -3
  36. package/src/cli/capability-contracts.ts +2 -0
  37. package/src/cli/codex-launch-auth.ts +30 -1
  38. package/src/cli/codex-launcher.ts +12 -5
  39. package/src/cli/codex-shim-autorestore.ts +5 -4
  40. package/src/cli/dispatch.ts +11 -176
  41. package/src/cli/ensure-desired-integrations.ts +4 -3
  42. package/src/cli/help.ts +2 -2
  43. package/src/cli/index.ts +9 -2
  44. package/src/cli/link.ts +1 -1
  45. package/src/cli/message-command.ts +2 -1
  46. package/src/cli/message-mcp-command.ts +29 -0
  47. package/src/cli/registry.ts +12 -4
  48. package/src/cli/root.ts +8 -0
  49. package/src/cli/sync-command.ts +243 -0
  50. package/src/cli/sync-fanout-process.ts +92 -0
  51. package/src/cli/sync-fanout.ts +150 -0
  52. package/src/cli/sync-flags.ts +10 -0
  53. package/src/cli/sync-link-status.ts +39 -0
  54. package/src/cli/sync-update-guard.ts +18 -0
  55. package/src/client/connect.ts +31 -14
  56. package/src/client/link-home.ts +3 -2
  57. package/src/client/machine-listener.ts +3 -0
  58. package/src/client/restore-ownership.ts +19 -1
  59. package/src/client/runtime-restart.ts +12 -4
  60. package/src/client/runtime.ts +40 -11
  61. package/src/client/stop-routing.ts +62 -0
  62. package/src/client/sync-runtime.ts +65 -0
  63. package/src/clients/config-export.ts +32 -3
  64. package/src/codex/account-store.ts +1 -0
  65. package/src/codex/auth-context-provider.ts +15 -0
  66. package/src/codex/auth-context.ts +59 -122
  67. package/src/codex/catalog/antigravity-discovery.ts +16 -5
  68. package/src/codex/catalog/provider-models.ts +6 -8
  69. package/src/codex/forward-transport-headers.ts +65 -36
  70. package/src/codex/inject/config-toml.ts +88 -0
  71. package/src/codex/inject/multi-agent-v2.ts +30 -4
  72. package/src/codex/inject/plan.ts +34 -7
  73. package/src/codex/inject-coordination.ts +11 -0
  74. package/src/codex/inject.ts +18 -7
  75. package/src/codex/installation-id.ts +72 -0
  76. package/src/codex/lineage.ts +13 -7
  77. package/src/codex/quota.ts +22 -6
  78. package/src/codex/request-owned-affinity-key.ts +11 -0
  79. package/src/codex/request-owned-affinity.ts +118 -0
  80. package/src/codex/request-owned-main-pin.ts +86 -0
  81. package/src/codex/role-capability.ts +52 -41
  82. package/src/codex/routing/active-account.ts +13 -5
  83. package/src/codex/routing/selection.ts +40 -1
  84. package/src/codex/routing/thread-affinity-store.ts +916 -0
  85. package/src/codex/routing/thread-affinity.ts +90 -12
  86. package/src/codex/toml-source-lines.ts +72 -13
  87. package/src/combos/failover.ts +6 -109
  88. package/src/combos/request.ts +2 -2
  89. package/src/combos/resolve.ts +29 -11
  90. package/src/config/process-state.ts +5 -0
  91. package/src/config/schema/leaf-validators.ts +1 -0
  92. package/src/generated/compatibility-version.json +496 -192
  93. package/src/grok/sync.ts +10 -1
  94. package/src/images/loop.ts +2 -1
  95. package/src/lib/client-error-body.ts +184 -0
  96. package/src/lib/client-retry-after.ts +66 -0
  97. package/src/lib/config-ownership.ts +4 -0
  98. package/src/lib/context-overflow-verdict.ts +113 -0
  99. package/src/lib/desktop-cli-handoff.d.mts +1 -1
  100. package/src/lib/desktop-cli-handoff.mjs +11 -1
  101. package/src/lib/empty-tool-catalog.ts +25 -3
  102. package/src/lib/error-destination.ts +47 -0
  103. package/src/lib/failure-detail.ts +66 -0
  104. package/src/lib/model-identity.ts +44 -0
  105. package/src/lib/private-sqlite-path.ts +124 -0
  106. package/src/lib/response-service-tier.ts +17 -0
  107. package/src/lib/retry-after.ts +3 -0
  108. package/src/lib/spend-ledger-owner.ts +43 -4
  109. package/src/lib/upstream-condition.ts +142 -0
  110. package/src/lib/upstream-retry.ts +14 -11
  111. package/src/lib/windows-owner-acl.ts +13 -6
  112. package/src/lib/windows-secret-acl.ts +2 -2
  113. package/src/link/remote-platform.ts +14 -0
  114. package/src/link/remote-windows.ts +51 -9
  115. package/src/link/ssh-argv.ts +63 -10
  116. package/src/messaging/mcp-queue-rpc.ts +102 -0
  117. package/src/messaging/mcp-queue-server.ts +42 -0
  118. package/src/messaging/mcp-queue-tools.ts +39 -0
  119. package/src/oauth/anthropic-identity.ts +2 -6
  120. package/src/oauth/generic-account-failover.ts +13 -11
  121. package/src/oauth/index.ts +41 -74
  122. package/src/oauth/oauth-errors.ts +67 -0
  123. package/src/oauth/store.ts +1 -1
  124. package/src/protocols/codecs/ollama.ts +197 -0
  125. package/src/protocols/encoders/adapter-events.ts +4 -0
  126. package/src/protocols/encoders/chat.ts +18 -10
  127. package/src/protocols/trace.ts +18 -0
  128. package/src/providers/anthropic-subscription.ts +25 -0
  129. package/src/providers/claude-cli-usage.ts +15 -67
  130. package/src/providers/fastwire.ts +3 -2
  131. package/src/providers/quota/anthropic-decision-windows.ts +5 -19
  132. package/src/providers/quota/anthropic-usage-windows.ts +65 -0
  133. package/src/providers/quota/vendor-probes-key.ts +60 -24
  134. package/src/providers/request-pacing.ts +3 -2
  135. package/src/responses/apply-patch-envelope.ts +45 -19
  136. package/src/responses/compaction-history-framing.ts +5 -1
  137. package/src/responses/freeform-wrapper-scan.ts +5 -3
  138. package/src/responses/parser-tools.ts +1 -0
  139. package/src/responses/progressive-freeform-input.ts +354 -45
  140. package/src/responses/schema.ts +5 -2
  141. package/src/routing/fallback-policy.ts +3 -1
  142. package/src/server/admission-model-scope.ts +17 -6
  143. package/src/server/admitted-http-turn.ts +56 -0
  144. package/src/server/audio-dictation.ts +3 -0
  145. package/src/server/audio-live.ts +8 -2
  146. package/src/server/audio-upstream.ts +2 -0
  147. package/src/server/auth-cors.ts +5 -0
  148. package/src/server/chat-completions.ts +45 -20
  149. package/src/server/chat-native-sse.ts +52 -7
  150. package/src/server/chat-native.ts +60 -35
  151. package/src/server/claude-bridge-pool-session.ts +59 -0
  152. package/src/server/claude-messages.ts +57 -27
  153. package/src/server/context-history.ts +14 -7
  154. package/src/server/images.ts +14 -5
  155. package/src/server/inbound-body-admission.ts +11 -4
  156. package/src/server/index/live-sideband.ts +16 -2
  157. package/src/server/index/ollama-routes.ts +89 -0
  158. package/src/server/index/serve-options.ts +22 -4
  159. package/src/server/index/websocket-handler.ts +5 -3
  160. package/src/server/index.ts +6 -36
  161. package/src/server/inference/client-encoder-delivery.ts +4 -2
  162. package/src/server/json-serialized-bytes.ts +44 -0
  163. package/src/server/live.ts +30 -5
  164. package/src/server/management/agent-settings-routes.ts +24 -21
  165. package/src/server/management/codex-cli-update-routes.ts +2 -1
  166. package/src/server/management/route-registry.ts +1 -1
  167. package/src/server/messages-native-scope.ts +2 -1
  168. package/src/server/messages-native-tool-guard.ts +1 -1
  169. package/src/server/messages-native.ts +12 -7
  170. package/src/server/messages-shared.ts +6 -2
  171. package/src/server/native-final-log.ts +93 -0
  172. package/src/server/ollama-inbound.ts +349 -0
  173. package/src/server/ollama-native-paths.ts +21 -0
  174. package/src/server/ollama-route-policy.ts +73 -0
  175. package/src/server/relay.ts +22 -3
  176. package/src/server/request-decompress.ts +4 -2
  177. package/src/server/request-log-failure-attribution.ts +22 -0
  178. package/src/server/request-log-failure-detail.ts +80 -0
  179. package/src/server/request-log-terminal-status.ts +4 -2
  180. package/src/server/request-log.ts +79 -42
  181. package/src/server/response-log-body.ts +6 -1
  182. package/src/server/responses/account-change-state.ts +17 -6
  183. package/src/server/responses/adapter-continuation.ts +9 -4
  184. package/src/server/responses/adapter-delivery.ts +5 -4
  185. package/src/server/responses/adapter-dispatch.ts +36 -30
  186. package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
  187. package/src/server/responses/codex-auth-error.ts +22 -17
  188. package/src/server/responses/codex-ws-exchange.ts +11 -8
  189. package/src/server/responses/codex-ws-metadata.ts +94 -21
  190. package/src/server/responses/codex-ws-request.ts +3 -1
  191. package/src/server/responses/combo-required-tool-contract.ts +24 -12
  192. package/src/server/responses/compact.ts +89 -41
  193. package/src/server/responses/compaction-recovery.ts +4 -2
  194. package/src/server/responses/compaction-routing.ts +9 -4
  195. package/src/server/responses/core-auth.ts +32 -14
  196. package/src/server/responses/core-codex-account.ts +34 -12
  197. package/src/server/responses/core-combo-failure.ts +5 -1
  198. package/src/server/responses/core-combo-native.ts +2 -1
  199. package/src/server/responses/core-combo.ts +51 -33
  200. package/src/server/responses/core-errors.ts +22 -20
  201. package/src/server/responses/core-lifetime.ts +6 -3
  202. package/src/server/responses/core-normalize.ts +8 -1
  203. package/src/server/responses/core-options.ts +7 -0
  204. package/src/server/responses/core-pipeline.ts +4 -3
  205. package/src/server/responses/fetch-helpers.ts +7 -1
  206. package/src/server/responses/input-admission.ts +28 -2
  207. package/src/server/responses/native-injection.ts +1 -1
  208. package/src/server/responses/native-response-json.ts +13 -4
  209. package/src/server/responses/native-response-output.ts +1 -2
  210. package/src/server/responses/non-replayable-error.ts +2 -1
  211. package/src/server/responses/pacing-overload.ts +3 -2
  212. package/src/server/responses/passthrough-build-error.ts +36 -0
  213. package/src/server/responses/passthrough-delivery.ts +55 -14
  214. package/src/server/responses/passthrough-dispatch.ts +26 -39
  215. package/src/server/responses/passthrough-error.ts +9 -9
  216. package/src/server/responses/policy-fallback.ts +2 -1
  217. package/src/server/responses/request-prepare.ts +67 -48
  218. package/src/server/responses/request-sidecar-auth.ts +3 -1
  219. package/src/server/responses/request-transport.ts +35 -31
  220. package/src/server/responses/run-turn-execution.ts +6 -6
  221. package/src/server/responses/sidecar-execution.ts +16 -12
  222. package/src/server/responses/spend-storage-error.ts +2 -1
  223. package/src/server/responses/ws-upstream.ts +9 -0
  224. package/src/server/responses-custom-tool-repair.ts +14 -3
  225. package/src/server/responses-terminal-repair.ts +5 -2
  226. package/src/server/responses-undeclared-tool-guard.ts +39 -16
  227. package/src/server/safe-response-headers.ts +162 -13
  228. package/src/server/search.ts +13 -4
  229. package/src/server/turn-state-handles.ts +164 -0
  230. package/src/server/workflow-refusal.ts +2 -1
  231. package/src/server/ws-bridge.ts +5 -2
  232. package/src/service/ownership-mutation-lease.d.mts +11 -2
  233. package/src/service/ownership-mutation-lease.mjs +53 -11
  234. package/src/types/config.ts +2 -0
  235. package/src/update/index.ts +133 -25
  236. package/src/update/npm-install.d.mts +8 -0
  237. package/src/update/npm-install.mjs +20 -1
  238. package/src/update/orchestrated-admission.d.mts +4 -0
  239. package/src/update/orchestrated-admission.mjs +12 -0
  240. package/src/update/orchestrated-arguments.d.mts +12 -0
  241. package/src/update/orchestrated-arguments.mjs +64 -0
  242. package/src/update/orchestrated-child.d.mts +12 -0
  243. package/src/update/orchestrated-child.mjs +70 -0
  244. package/src/update/orchestrated-entry.ts +234 -0
  245. package/src/update/orchestrated-identity-probe-entry.ts +20 -0
  246. package/src/update/orchestrated-identity.ts +53 -0
  247. package/src/update/orchestrated-live-identity.ts +48 -0
  248. package/src/update/orchestrated-node-driver.mjs +99 -0
  249. package/src/update/orchestrated-outcome.d.mts +21 -0
  250. package/src/update/orchestrated-outcome.mjs +40 -0
  251. package/src/update/orchestrated-plan.ts +49 -0
  252. package/src/update/orchestrated-pnpm.d.mts +8 -0
  253. package/src/update/orchestrated-pnpm.mjs +33 -0
  254. package/src/update/orchestrated-session.d.mts +37 -0
  255. package/src/update/orchestrated-session.mjs +264 -0
  256. package/src/update/orchestrated-token.d.mts +10 -0
  257. package/src/update/orchestrated-token.mjs +21 -0
  258. package/src/update/orchestrated-token.ts +3 -0
  259. package/src/update/orchestrated-tree.d.mts +1 -0
  260. package/src/update/orchestrated-tree.mjs +14 -0
  261. package/src/update/pnpm-global-install.d.mts +6 -0
  262. package/src/update/pnpm-global-install.mjs +9 -2
  263. package/src/update/posix-install-supervisor-entry.mjs +6 -0
  264. package/src/update/posix-install-supervisor.d.mts +10 -0
  265. package/src/update/posix-install-supervisor.mjs +88 -0
  266. package/src/update/sync-update-mutex.d.mts +10 -0
  267. package/src/update/sync-update-mutex.mjs +164 -0
  268. package/src/update/sync-update-mutex.ts +1 -0
  269. package/src/update/test-home-guard.mjs +33 -0
  270. package/src/update/transactional-install.mjs +2 -2
  271. package/src/usage/error-detail.ts +225 -0
  272. package/src/usage/log.ts +60 -27
  273. package/src/vision/describe.ts +4 -7
  274. package/src/web-search/executor.ts +4 -7
  275. package/src/web-search/loop.ts +31 -5
  276. package/gui/dist/assets/index-D7DCm5eQ.js +0 -94
@@ -1,5 +1,11 @@
1
+ import { formatClientRetryAfter } from "../lib/client-retry-after";
2
+ import { requestOwnedAffinityKey, honestAffinityDecision, callerOwnedFallbackAffinityDecision, captureRequestOwnedAffinityBindings, type RequestOwnedBindingSnapshot } from "./request-owned-affinity";
3
+ import { requestOwnedMainPinState, mainCreditsHoldResetAt, callerMatchesObservedMain } from "./request-owned-main-pin";
4
+ export { requestOwnedMainPinState } from "./request-owned-main-pin";
5
+ import type { OcxRuntimeProviderConfig } from "./auth-context-provider";
6
+ export type { OcxRuntimeProviderConfig } from "./auth-context-provider";
7
+ export { stripCodexRuntimeProviderFields } from "./auth-context-provider";
1
8
  import { bindPoolCreditPolicy, poolCreditHoldResetAt, poolContextCreditHoldResetAt, poolCreditRecoveryNeeded, poolContextCreditRecoveryNeeded, poolCreditRecoveryRetryAt } from "./pool-credit-policy";
2
- import { hasSpendableCodexCredits } from "./quota-types";
3
9
  import { nextQuotaQueryDelay } from "./quota-query-backoff";
4
10
  import { noteMainAccountActivity } from "./main-account-external-usage";
5
11
  import { codexAccountPriorityFailbackEnabled } from "./account-priority";
@@ -37,9 +43,7 @@ import type { NativeMainStartupBlockReason } from "./native-profile-startup";
37
43
  import { waitForMainAccountPolicyBinding } from "./main-account-policy-wait";
38
44
  import {
39
45
  codexQuotaScopeForModel,
40
- computeCodexUsageScore,
41
46
  getCodexQuotaHealthSnapshot,
42
- isEffectiveCodexAccountPinned,
43
47
  releaseCodexQuotaProbeLease,
44
48
  releaseCodexQuotaScopeProbeLease,
45
49
  tryAcquireCodexQuotaProbeLease,
@@ -71,8 +75,8 @@ import type { CodexCooldownSource, CodexQuotaScope } from "./routing";
71
75
  import { maskAccountId } from "../lib/privacy";
72
76
  import { formatErrorResponse, formatUsageLimitReachedResponse } from "../bridge";
73
77
  import { nextCodexPoolRecoveryAt } from "./routing/pool-recovery";
74
- import { CODEX_UNKNOWN_USAGE_SCORE, getAccountQuota, getMainPolicyQuota, isValidWhamHistoryObservation, parseUsageQuota, parseMainPolicyUsageQuota, setAccountQuotaFromParsed } from "./quota";
75
- import { codexAccountUsesCreditsAfterLimit, codexUsageLimitResetAt } from "./account-credit-use";
78
+ import { getAccountQuota, isValidWhamHistoryObservation, parseUsageQuota, parseMainPolicyUsageQuota, setAccountQuotaFromParsed } from "./quota";
79
+ import { codexAccountUsesCreditsAfterLimit } from "./account-credit-use";
76
80
  import type { CodexAccountMode, OcxConfig, OcxProviderConfig } from "../types";
77
81
  import { FORWARD_HEADERS } from "../adapters/openai-responses";
78
82
  import { isolateCodexPoolAccountHeaders } from "./forward-transport-headers";
@@ -82,7 +86,6 @@ import {
82
86
  resolveMainAccountHardLockThresholds,
83
87
  getMainAccountHardLockStatus,
84
88
  isMainAccountHardLockEnabled,
85
- isMainAccountHardLocked,
86
89
  } from "./main-account-hard-lock";
87
90
  import {
88
91
  captureMainAccountIdentityGeneration,
@@ -99,67 +102,9 @@ import { CODEX_RESERVE_HELPER_UNSUPPORTED_MESSAGE, isCodexReserveHelperUnsupport
99
102
  import type { DataPlaneAdmission } from "../server/auth-cors";
100
103
  import { getMainReserveAuthorization, isMainReserveAuthorizationLive, nativeUserIdClaims, type MainReserveAuthorization } from "./reserve-availability";
101
104
  import { UpstreamRetryEvidenceError } from "../lib/upstream-retry";
102
- import { getEffectiveCodexAutoSwitchThreshold } from "./account-auto-switch";
103
105
  import { CODEX_MAIN_DUPLICATE_ACTION, configuredCodexMainDuplicate } from "./collision-identity";
104
106
  import { AgentAssertionUnsupportedError, authorizationCredential, hasAgentAssertionAuthorization } from "../lib/authorization-scheme";
105
107
 
106
- /**
107
- * A request-owned bearer cannot inspect the physical main credential for its plan, but cached
108
- * WHAM usage is still valid routing evidence for the same logical main account. Score it with
109
- * the conservative unknown-plan rule: an unobserved governing window preserves the pin, while
110
- * any known weekly/monthly/short value at the threshold releases it through the ordinary Pool
111
- * path. This keeps the keyring boundary intact instead of reading auth.json just to classify a
112
- * request that already brought its own credential (#3157).
113
- */
114
- function requestOwnedMainPinHasQuotaHeadroom(config: OcxConfig): boolean {
115
- const threshold = getEffectiveCodexAutoSwitchThreshold(config, MAIN_CODEX_ACCOUNT_ID);
116
- if (threshold <= 0) return true;
117
- const usage = computeCodexUsageScore(getAccountQuota(MAIN_CODEX_ACCOUNT_ID), undefined, Date.now(), codexAccountUsesCreditsAfterLimit(config, MAIN_CODEX_ACCOUNT_ID));
118
- return usage >= CODEX_UNKNOWN_USAGE_SCORE || usage < threshold;
119
- }
120
-
121
- /**
122
- * Whether a request carrying its OWN main credential still serves on main because the operator
123
- * manually pinned it (#3166), split from the surrounding resolution so request preview can ask
124
- * the identical question (#4850).
125
- *
126
- * Exported for exactly one reason: two copies of this fence is how #4850 happened. Final
127
- * authentication honoured the ownership boundary while request preview, computing its fence from
128
- * recovery and drain state alone, still handed pool eligibility the default liveness probe and
129
- * opened the physical `auth.json` twice per spawn. A predicate one caller can forget is a
130
- * predicate the other caller will eventually disagree with.
131
- *
132
- * Read-free by construction, which is what makes it usable on the fenced side. Every input is
133
- * config, policy, or in-memory runtime state: the pin fields, the paused list, the cached quota
134
- * score, the main policy quota the hard lock and the credits switch read, and `callerMatchesObservedMain`, which compares HMAC digests against the observed
135
- * credential record in `main-account-cache.ts`. Nothing here opens a file.
136
- *
137
- * `candidate` is the pin before the hard-lock question, because the caller still owes the
138
- * pending-binding check that only final authentication can fail closed on.
139
- */
140
- export function requestOwnedMainPinState(
141
- headers: Headers,
142
- config: OcxConfig,
143
- policy: CodexAuthPolicyConfig,
144
- requestScopedMainCredential: boolean,
145
- fixedAccountId: string | undefined,
146
- quotaScope?: CodexQuotaScope,
147
- ): { candidate: boolean; preserve: boolean } {
148
- const candidate = requestScopedMainCredential
149
- && fixedAccountId === undefined
150
- && config.activeCodexAccountPinned === MAIN_CODEX_ACCOUNT_ID
151
- && isEffectiveCodexAccountPinned(config)
152
- && !policy.pausedCodexAccountIds?.includes(MAIN_CODEX_ACCOUNT_ID)
153
- && requestOwnedMainPinHasQuotaHeadroom(config);
154
- return {
155
- candidate,
156
- preserve: candidate && !(callerMatchesObservedMain(headers)
157
- && (isMainAccountHardLocked(policy)
158
- || mainCreditsHoldResetAt(policy) !== undefined
159
- || getCodexQuotaHealthSnapshot(MAIN_CODEX_ACCOUNT_ID, quotaScope)?.cooldownUntil)),
160
- };
161
- }
162
-
163
108
  /**
164
109
  * One conversation tree keys as ONE cohort (#4780).
165
110
  *
@@ -244,12 +189,12 @@ export function requestOwnedMainCredentialIsLive(inputs: {
244
189
  }
245
190
 
246
191
  /**
247
- * May this request own Pool affinity state at all?
192
+ * May this request use stored-credential Pool lineage?
248
193
  *
249
- * Two credentials authenticate outside the Pool: an exact account selector (including the
250
- * Reserve pin) and a request-owned main bearer, which exists for one request and must never
251
- * fold into durable account state. Neither may read or write a binding, so neither may read
252
- * or write LINEAGE either.
194
+ * Two credentials authenticate outside stored Pool state: an exact account selector (including
195
+ * Reserve) and a request-owned main bearer, which must never fold into durable account state.
196
+ * Neither may read or write a stored-credential binding or lineage. The optional request-owned
197
+ * affinity namespace is separate from this predicate.
253
198
  *
254
199
  * Exported so that a preview asks the question with the code that answers it, instead of a
255
200
  * restatement that can drift. It drifted once already: preview read a family relation from raw
@@ -269,6 +214,15 @@ export function codexPoolStateEligible(
269
214
  );
270
215
  }
271
216
 
217
+ /** Shared affinity derivation for final authentication and both request previews. */
218
+ export function codexRequestAffinityKey(headers: Headers, config: OcxConfig, policy: CodexAuthPolicyConfig | undefined, options: CodexPoolStateEligibility = {}): string | undefined {
219
+ if (options.accountId !== undefined || requiresReserveAuthorization(policy, options.modelId, options.admission)) return undefined;
220
+ if (options.requestScopedMainCredential === true && hasCallerCodexBearer(headers)) {
221
+ return config.codexPool?.requestOwnedAffinity === true ? requestOwnedAffinityKey(headers) : undefined;
222
+ }
223
+ return codexPoolAffinityKey(headers);
224
+ }
225
+
272
226
  /**
273
227
  * The lineage a PREVIEW is allowed to see: read-only, and only for a request that may hold Pool
274
228
  * state. Recording is left to the resolution that actually binds, so a preview can never leave a
@@ -286,7 +240,7 @@ export function previewCodexPoolLineage(
286
240
 
287
241
  export type CodexAuthContext =
288
242
  | {
289
- kind: "main"; accountId: null; reserveAuthorization?: MainReserveAuthorization;
243
+ kind: "main"; accountId: null; reserveAuthorization?: MainReserveAuthorization; affinityKey?: string; conversationStateKey?: string; affinityDecision?: CodexAffinityDecision; affinityBindingSnapshot?: RequestOwnedBindingSnapshot;
290
244
  /** Captured for the observed main credential actually selected for upstream. */
291
245
  mainQuotaDispatch?: MainQuotaDispatch;
292
246
  }
@@ -301,7 +255,7 @@ export type CodexAuthContext =
301
255
  /** Bypass Pool selection and suppress quota/transient failover for an exact selector. */
302
256
  fixedAccount?: boolean;
303
257
  /** Pool binding key; the Desktop fallback is an opaque process-local HMAC. */
304
- affinityKey?: string;
258
+ affinityKey?: string; conversationStateKey?: string;
305
259
  /**
306
260
  * Set when this request was admitted through an active quota cooldown as
307
261
  * the account's single probe. Must be echoed into the upstream outcome so
@@ -335,7 +289,7 @@ export type CodexAuthContext =
335
289
  chatgptAccountId: string;
336
290
  /** Bypass Pool selection and suppress quota/transient failover for an exact selector. */
337
291
  fixedAccount?: boolean;
338
- affinityKey?: string; // See `pool.affinityKey`.
292
+ affinityKey?: string; conversationStateKey?: string; // See `pool.affinityKey`.
339
293
  /** See `pool.probeLeaseId`. */
340
294
  probeLeaseId?: string;
341
295
  quotaScope?: CodexQuotaScope;
@@ -378,11 +332,6 @@ export function releaseCodexAuthContextProbeLease(ctx: CodexAuthContext | undefi
378
332
  else releaseCodexQuotaProbeLease(ctx.accountId!, leaseId);
379
333
  }
380
334
 
381
- export type OcxRuntimeProviderConfig = OcxProviderConfig & {
382
- _codexAccountOverride?: { accessToken: string; chatgptAccountId: string };
383
- _codexAccountRequired?: boolean;
384
- };
385
-
386
335
  export class CodexAuthContextError extends Error {
387
336
  accountId: string;
388
337
 
@@ -788,12 +737,6 @@ export function createCodexAuthDispatchGuard(
788
737
  };
789
738
  }
790
739
 
791
- function mainCreditsHoldResetAt(config: Pick<OcxConfig, "creditCodexAccountIds">): number | undefined {
792
- if (codexAccountUsesCreditsAfterLimit(config, MAIN_CODEX_ACCOUNT_ID)
793
- && hasSpendableCodexCredits(getMainPolicyQuota())) return undefined;
794
- return codexUsageLimitResetAt(getMainPolicyQuota(), undefined, Date.now());
795
- }
796
-
797
740
  function assertMainAccountPolicy(
798
741
  config: Pick<OcxConfig, "codexMainAccountHardLock" | "codexMainAccountHardLockThresholds" | "creditCodexAccountIds" | "codexUseRemainingQuotaAccountIds"> | undefined,
799
742
  ): void {
@@ -809,15 +752,6 @@ function assertMainAccountPolicy(
809
752
  noteMainAccountActivity();
810
753
  }
811
754
 
812
- /** No auth-file I/O: an unsigned claim alone never identifies a caller as stored main. */
813
- function callerMatchesObservedMain(headers: Headers): boolean {
814
- const bearer = authorizationCredential(headers);
815
- if (!bearer) return false;
816
- const effectiveAccountId = headers.get("chatgpt-account-id")
817
- ?? extractAccountId(undefined, bearer);
818
- return matchesMainQuotaCredential(bearer, effectiveAccountId);
819
- }
820
-
821
755
  /** Constant-time digest comparison so bearer bytes never drive branch timing. */
822
756
  function sameCredentialMaterial(a: string, b: string): boolean {
823
757
  return timingSafeEqual(createHash("sha256").update(a).digest(), createHash("sha256").update(b).digest());
@@ -992,7 +926,8 @@ export function cooldownErrorResponse(
992
926
  const res = formatErrorResponse(429, "rate_limit_error", cooldownErrorMessage(err, accountSelector));
993
927
  const headers = new Headers(res.headers);
994
928
  if (!(err instanceof CodexReserveUnavailableError)) {
995
- headers.set("Retry-After", String(Math.max(1, Math.ceil((err.cooldownUntil - now) / 1000))));
929
+ const advice = formatClientRetryAfter(Math.max(1, Math.ceil((err.cooldownUntil - now) / 1000)));
930
+ if (advice !== undefined) headers.set("Retry-After", advice);
996
931
  }
997
932
  return new Response(res.body, { status: res.status, headers });
998
933
  }
@@ -1284,6 +1219,8 @@ async function resolveCodexAuthContextUnannotated(
1284
1219
  directSelectionAdmission.release();
1285
1220
  }
1286
1221
  };
1222
+ const affinityKey = codexRequestAffinityKey(headers, config, policy, { accountId: fixedAccountId, modelId: options.modelId, admission: options.admission, requestScopedMainCredential });
1223
+ const conversationStateKey = affinityKey ?? (requestScopedMainCredential && fixedAccountId === undefined && !reserve ? requestOwnedAffinityKey(headers) : undefined);
1287
1224
  // Pool discovery excludes request-owned main credentials by design: they must never be folded
1288
1225
  // into stored-account entitlement, affinity, or persistence state. An effective manual main pin
1289
1226
  // is the one exception where that exclusion is selection evidence in the opposite direction.
@@ -1296,7 +1233,7 @@ async function resolveCodexAuthContextUnannotated(
1296
1233
  options.isDirectCallerEntitledToCodexModel ?? isDirectCallerEntitledToCodexModel
1297
1234
  )(headers, options.modelId);
1298
1235
  if (callerEntitled && preserveRequestOwnedMainPin()) {
1299
- return { kind: "main", accountId: null };
1236
+ return { kind: "main", accountId: null, ...(mode === "pool" && conversationStateKey ? { conversationStateKey } : {}) };
1300
1237
  }
1301
1238
  }
1302
1239
  // An explicit namespace binding is stronger than the provider's default mode. It must use the
@@ -1311,19 +1248,24 @@ async function resolveCodexAuthContextUnannotated(
1311
1248
  }
1312
1249
  // A caller bearer can still accompany a request that selects a configured Pool account. Do not
1313
1250
  // let that request read, delete, or create a file-main affinity binding while deciding whether a
1314
- // stored account is available; only the stored credential selected below may own Pool state.
1315
- const affinityKey = poolStateEligible(fixedAccountId, requestScopedMainCredential)
1316
- ? codexPoolAffinityKey(headers)
1317
- : undefined;
1318
- // The thread's family relation, recorded under the same condition as the key itself. A
1319
- // first-placing child consults it; a request-owned or fixed credential never enters Pool
1320
- // state, so it never enters lineage either.
1321
- const lineage = affinityKey !== undefined
1251
+ // stored account is available. Optional caller-owned bindings use a separate namespace; fixed
1252
+ // selectors never own a binding.
1253
+ // A first-placing child consults its thread's family relation. Fixed and request-owned
1254
+ // credentials never enter stored Pool lineage, even when request-owned affinity is enabled.
1255
+ const lineage = affinityKey !== undefined && poolStateEligible(fixedAccountId, requestScopedMainCredential)
1322
1256
  ? recordCodexThreadLineage(headers)
1323
1257
  : undefined;
1324
1258
  // Why this request is on this account, carried to the request log so a move reads as an event
1325
1259
  // instead of something inferred from account labels across lines (#4546).
1326
1260
  let affinityDecision: CodexAffinityDecision | undefined;
1261
+ const resolveKeyedCallerMain = async (fallbackReason?: "cooldown" | "unusable"): Promise<CodexAuthContext> => {
1262
+ const withheld = requestScopedMainCredential && config.codexPool?.requestOwnedAffinity !== true;
1263
+ const decision = fallbackReason ? callerOwnedFallbackAffinityDecision(affinityDecision, affinityKey, quotaScope, options.modelId, withheld, fallbackReason)
1264
+ : honestAffinityDecision(affinityDecision, affinityKey, MAIN_CODEX_ACCOUNT_ID, quotaScope, options.modelId, withheld);
1265
+ const affinityBindingSnapshot = captureRequestOwnedAffinityBindings(affinityKey, quotaScope, options.modelId);
1266
+ const context = await resolveCallerOwnedMainContext();
1267
+ return context.kind === "main" ? { ...context, ...(affinityBindingSnapshot ? { affinityBindingSnapshot } : {}), ...(affinityKey ? { affinityKey } : {}), ...(conversationStateKey ? { conversationStateKey } : {}), ...(decision ? { affinityDecision: decision } : {}) } : context;
1268
+ };
1327
1269
  // The half-open trial this request was granted, if it is the one allowed to test a held
1328
1270
  // account. Declared out here because the release paths below and the returned context are on
1329
1271
  // opposite sides of several throws (#4701).
@@ -1472,17 +1414,17 @@ async function resolveCodexAuthContextUnannotated(
1472
1414
  throw new CodexRecoveryWithheldError(resolution.accountId, resolution.retryAt, resolution.detourAccountId);
1473
1415
  }
1474
1416
  const selected = resolution.status === "selected" ? resolution.accountId : null;
1475
- affinityDecision = resolution.affinity;
1417
+ affinityDecision = selected ? honestAffinityDecision(resolution.affinity, affinityKey, selected, quotaScope, options.modelId, requestScopedMainCredential && config.codexPool?.requestOwnedAffinity !== true) : resolution.affinity;
1476
1418
  transientProbe = resolution.status === "selected" ? resolution.transientProbe : undefined;
1477
1419
  // Main now takes part in ordering when the request carries its own main bearer (#5019), so
1478
1420
  // selection can name it outright rather than only through the no-candidate fallback below.
1479
1421
  // Serve that selection from the credential the request arrived with: the read fence above
1480
1422
  // forbids this request from claiming, reading or reconciling the stored main profile, and a
1481
- // request-owned credential owns no Pool state, so there is nothing here to claim, prime or
1482
- // cool down. Hand back any trial first -- no Pool account is being sent to.
1423
+ // request-owned credential owns no shared health state, so there is nothing here to claim,
1424
+ // prime or cool down. Hand back any trial first -- no Pool account is being sent to.
1483
1425
  if (selected === MAIN_CODEX_ACCOUNT_ID && requestScopedMainCredential) {
1484
1426
  releaseTransientProbeGrant();
1485
- const context = await resolveCallerOwnedMainContext();
1427
+ const context = await resolveKeyedCallerMain();
1486
1428
  console.info("[codex] Pool selected caller-owned main credential.");
1487
1429
  return context;
1488
1430
  }
@@ -1502,7 +1444,7 @@ async function resolveCodexAuthContextUnannotated(
1502
1444
  && !(callerMatchesObservedMain(headers) && policy.pausedCodexAccountIds?.includes(MAIN_CODEX_ACCOUNT_ID))
1503
1445
  && options.excludeAccountId !== MAIN_CODEX_ACCOUNT_ID
1504
1446
  ) {
1505
- const context = await resolveCallerOwnedMainContext();
1447
+ const context = await resolveKeyedCallerMain("unusable");
1506
1448
  console.info("[codex] Pool used caller-owned main credential: no selectable stored account.");
1507
1449
  return context;
1508
1450
  }
@@ -1669,7 +1611,7 @@ async function resolveCodexAuthContextUnannotated(
1669
1611
  && !(callerMatchesObservedMain(headers) && policy.pausedCodexAccountIds?.includes(MAIN_CODEX_ACCOUNT_ID))
1670
1612
  && options.excludeAccountId !== MAIN_CODEX_ACCOUNT_ID
1671
1613
  && !callerIsCooledPoolAccount(headers, config, accountId)) {
1672
- const context = await resolveCallerOwnedMainContext();
1614
+ const context = await resolveKeyedCallerMain("cooldown");
1673
1615
  console.info("[codex] Pool used caller-owned main credential: stored account cooldown.");
1674
1616
  return context;
1675
1617
  }
@@ -1729,6 +1671,7 @@ async function resolveCodexAuthContextUnannotated(
1729
1671
  chatgptAccountId: token.chatgptAccountId,
1730
1672
  ...(fixedAccountId !== undefined ? { fixedAccount: true } : {}),
1731
1673
  ...(affinityKey ? { affinityKey } : {}),
1674
+ ...(conversationStateKey ? { conversationStateKey } : {}),
1732
1675
  ...(quotaScope ? { quotaScope } : {}),
1733
1676
  ...(probeLeaseId ? { probeLeaseId } : {}),
1734
1677
  ...(probeQuotaScope ? { probeQuotaScope } : {}),
@@ -1752,6 +1695,7 @@ async function resolveCodexAuthContextUnannotated(
1752
1695
  chatgptAccountId: token.chatgptAccountId,
1753
1696
  ...(fixedAccountId !== undefined ? { fixedAccount: true } : {}),
1754
1697
  ...(affinityKey ? { affinityKey } : {}),
1698
+ ...(conversationStateKey ? { conversationStateKey } : {}),
1755
1699
  ...(quotaScope ? { quotaScope } : {}),
1756
1700
  ...(probeLeaseId ? { probeLeaseId } : {}),
1757
1701
  ...(probeQuotaScope ? { probeQuotaScope } : {}),
@@ -1795,6 +1739,7 @@ export function applyCodexAuthContextToProvider(
1795
1739
  _codexAccountOverride: {
1796
1740
  accessToken: ctx.accessToken,
1797
1741
  chatgptAccountId: ctx.chatgptAccountId,
1742
+ kind: ctx.kind,
1798
1743
  },
1799
1744
  _codexAccountRequired: true,
1800
1745
  };
@@ -1840,14 +1785,15 @@ export function materializeCodexUpstreamAuth(
1840
1785
  const selected = new Headers();
1841
1786
  for (const name of FORWARD_HEADERS) {
1842
1787
  const value = headers.get(name);
1843
- if (value) selected.set(name, value);
1788
+ if (value || (value !== null && (name === "x-codex-installation-id" || name === "x-codex-turn-metadata"))) selected.set(name, value);
1844
1789
  }
1845
1790
  if (ctx.kind === "pool" || ctx.kind === "main-pool") {
1846
1791
  assertCodexAccountValidationReady(ctx.accountId);
1847
1792
  if (ctx.kind === "pool") assertPoolAccountCredits(ctx.accountId, poolContextCreditHoldResetAt(ctx, options.config), poolContextCreditRecoveryNeeded(ctx, options.config), ctx.quotaScope);
1848
1793
  selected.set("authorization", `Bearer ${ctx.accessToken}`);
1849
1794
  selected.set("chatgpt-account-id", ctx.chatgptAccountId);
1850
- isolateCodexPoolAccountHeaders(selected, ctx.chatgptAccountId);
1795
+ if (ctx.kind === "pool") isolateCodexPoolAccountHeaders(selected, ctx.chatgptAccountId);
1796
+ else selected.delete("x-oai-attestation");
1851
1797
  if (ctx.kind === "main-pool") {
1852
1798
  ctx.mainQuotaWriter = observeSelectedMainCredential(ctx, ctx.mainQuotaWriter);
1853
1799
  assertMainAccountPolicy(options.config);
@@ -1878,7 +1824,7 @@ export function materializeCodexUpstreamAuth(
1878
1824
  selected.delete("chatgpt-account-id");
1879
1825
  selected.set("authorization", `Bearer ${stored.accessToken}`);
1880
1826
  if (stored.chatgptAccountId) selected.set("chatgpt-account-id", stored.chatgptAccountId);
1881
- isolateCodexPoolAccountHeaders(selected, stored.chatgptAccountId ?? "");
1827
+ selected.delete("x-oai-attestation");
1882
1828
  observeSelectedMainCredential(stored, writer);
1883
1829
  assertMainAccountPolicy(options.config);
1884
1830
  assertMaterializedReserve(selected, ctx, options);
@@ -1949,7 +1895,7 @@ export async function materializeCodexUpstreamAuthAsync(
1949
1895
  const selected = new Headers();
1950
1896
  for (const name of FORWARD_HEADERS) {
1951
1897
  const value = headers.get(name);
1952
- if (value) selected.set(name, value);
1898
+ if (value || (value !== null && (name === "x-codex-installation-id" || name === "x-codex-turn-metadata"))) selected.set(name, value);
1953
1899
  }
1954
1900
  if (options.config !== undefined && isMainAccountHardLockEnabled(options.config)) {
1955
1901
  reconcileMainCodexAccountRuntimeState();
@@ -1963,7 +1909,7 @@ export async function materializeCodexUpstreamAuthAsync(
1963
1909
  selected.delete("chatgpt-account-id");
1964
1910
  selected.set("authorization", `Bearer ${stored.accessToken}`);
1965
1911
  if (stored.chatgptAccountId) selected.set("chatgpt-account-id", stored.chatgptAccountId);
1966
- isolateCodexPoolAccountHeaders(selected, stored.chatgptAccountId ?? "");
1912
+ selected.delete("x-oai-attestation");
1967
1913
  observeSelectedMainCredential(stored, writer);
1968
1914
  assertMainAccountPolicy(options.config);
1969
1915
  // An opt-in enabled during token refresh must not turn a proof-less context into Reserve.
@@ -1988,12 +1934,3 @@ export function isCodexAuthContextUsable(ctx: CodexAuthContext, config: OcxConfi
1988
1934
  if (ctx.kind === "main-pool") return isCodexAccountUsable(config, ctx.accountId);
1989
1935
  return isCodexAccountUsable(config, ctx.accountId) && isCodexAccountGenerationLive(ctx.accountId, ctx.generation);
1990
1936
  }
1991
-
1992
- export function stripCodexRuntimeProviderFields(provider: OcxProviderConfig): OcxProviderConfig {
1993
- const {
1994
- _codexAccountOverride: _override,
1995
- _codexAccountRequired: _required,
1996
- ...safeProvider
1997
- } = provider as OcxRuntimeProviderConfig;
1998
- return safeProvider;
1999
- }
@@ -8,19 +8,28 @@ import { captureAntigravityModelObservation, recordAntigravityAccountRoster } fr
8
8
  import type { OcxProviderConfig } from "../../types";
9
9
  import { materializeCapturedHeaders, type CapturedModelsRequest } from "./gather-capture";
10
10
 
11
+ /** True while the active account still holds the exact usable credential discovery sent. */
12
+ export function antigravityActiveAccountCurrent(
13
+ name: string, accountId: string, accessToken: string | undefined, generation: string | undefined,
14
+ ): boolean {
15
+ const row = getAccountCredentialWithStatus(name, accountId);
16
+ return !!row && !row.paused && !row.needsReauth && row.credential.expires > Date.now()
17
+ && row.credential.access === accessToken && credentialGeneration(row.credential) === generation;
18
+ }
19
+
11
20
  /** A sibling contributes only while the exact snapshot sent is still usable. */
12
21
  export async function discoverAntigravitySiblings(
13
22
  name: string, provider: OcxProviderConfig, activeAccountId: string,
14
23
  request: CapturedModelsRequest, maxBytes: number, maxModels: number,
15
- root: string,
24
+ root: string, authorityCurrent: () => boolean,
16
25
  ): Promise<() => AntigravityAvailableModel[]> {
17
- if (root !== getConfigDir()) return () => [];
26
+ if (root !== getConfigDir() || !authorityCurrent()) return () => [];
18
27
  const results: Array<{
19
28
  snapshot: OAuthAccessSnapshot; models: AntigravityAvailableModel[];
20
29
  observation: ReturnType<typeof captureAntigravityModelObservation>;
21
30
  }> = [];
22
31
  const current = (snapshot: OAuthAccessSnapshot): boolean => {
23
- if (getConfigDir() !== root) return false;
32
+ if (getConfigDir() !== root || !authorityCurrent()) return false;
24
33
  const row = getAccountCredentialWithStatus(name, snapshot.accountId);
25
34
  return !!row && !row.paused && !row.needsReauth && row.credential.expires > Date.now()
26
35
  && credentialGeneration(row.credential) === snapshot.generation
@@ -30,8 +39,10 @@ export async function discoverAntigravitySiblings(
30
39
  for (const sibling of getAccountSet(name)?.accounts ?? []) {
31
40
  if (sibling.id === activeAccountId || sibling.paused || sibling.needsReauth) continue;
32
41
  try {
33
- if (getConfigDir() !== root) break;
34
- const snapshot = await getValidAccessSnapshotForAccount(name, sibling.id, { requireUsableAccount: true });
42
+ if (getConfigDir() !== root || !authorityCurrent()) break;
43
+ const snapshot = await getValidAccessSnapshotForAccount(name, sibling.id, {
44
+ requireUsableAccount: true, authorityCurrent: () => getConfigDir() === root && authorityCurrent(),
45
+ });
35
46
  const project = provider.project ?? snapshot.projectId;
36
47
  if (!project || !current(snapshot)) continue;
37
48
  const observation = captureAntigravityModelObservation();
@@ -54,7 +54,7 @@ import type { FastPolicyAuthority } from "../../providers/fastwire";
54
54
  import { effectiveGoogleMode, getProviderRegistryEntry, providerMatchesRegistryTransport, registryEntryForProviderDestination } from "../../providers/registry";
55
55
  import { parseAntigravityAvailableModels, registerAntigravityDiscoveredWireModels } from "../../providers/antigravity-models";
56
56
  import { captureAntigravityModelObservation, recordAntigravityAccountRoster } from "../../providers/antigravity-account-roster";
57
- import { discoverAntigravitySiblings } from "./antigravity-discovery";
57
+ import { antigravityActiveAccountCurrent, discoverAntigravitySiblings } from "./antigravity-discovery";
58
58
  import { applyProviderContextCap, providerContextCap, resolveUnknownRoutedContextWindow } from "../../providers/context-cap";
59
59
  import { clampAutoCompactTokenLimit } from "../../providers/auto-compact-budget";
60
60
  import { effectiveModelAliases } from "../../providers/default-aliases";
@@ -794,16 +794,14 @@ export async function fetchProviderModelsWithAuth(
794
794
  }
795
795
  if (antigravity) {
796
796
  if (getConfigDir() !== metadataConfigDir) return observed(withConfiguredRetention(configured), "degraded");
797
+ // A needsReauth/replacement of the active account stops every later sibling refresh and send.
798
+ const activeCurrent = () => isCurrentCacheGeneration() && (!auth.oauthAccountId
799
+ || antigravityActiveAccountCurrent(name, auth.oauthAccountId, apiKey, auth.oauthGeneration));
797
800
  const admitSiblings = resolveAuth.kind === "refreshing" && name === "google-antigravity"
798
801
  && prov.authMode === "oauth" && auth.oauthAccountId
799
- ? await discoverAntigravitySiblings(name, prov, auth.oauthAccountId, request, discovery.maxResponseBytes, discovery.maxModels, metadataConfigDir)
802
+ ? await discoverAntigravitySiblings(name, prov, auth.oauthAccountId, request, discovery.maxResponseBytes, discovery.maxModels, metadataConfigDir, activeCurrent)
800
803
  : () => [];
801
- if (!isCurrentCacheGeneration() || getConfigDir() !== metadataConfigDir) return observed(withConfiguredRetention(configured), "degraded");
802
- const activeAccount = auth.oauthAccountId ? getAccountCredentialWithStatus(name, auth.oauthAccountId) : null;
803
- if (auth.oauthAccountId && (!activeAccount || activeAccount.paused || activeAccount.needsReauth
804
- || activeAccount.credential.expires <= Date.now() || activeAccount.credential.access !== apiKey
805
- || credentialGeneration(activeAccount.credential) !== auth.oauthGeneration))
806
- return observed(withConfiguredRetention(configured), "degraded");
804
+ if (!activeCurrent() || getConfigDir() !== metadataConfigDir) return observed(withConfiguredRetention(configured), "degraded");
807
805
  const byId = new Map(antigravity.map(model => [model.id, model]));
808
806
  for (const model of admitSiblings()) if (!byId.has(model.id)) byId.set(model.id, model);
809
807
  const merged = [...byId.values()];
@@ -1,4 +1,4 @@
1
- import { createHmac } from "node:crypto";
1
+ import { CodexInstallationIdUnavailableError, codexInstallationIdForAccount } from "./installation-id";
2
2
 
3
3
  /** Native request metadata shared by the HTTP adapter and WS preparation. */
4
4
  export const CODEX_RESPONSES_LITE_HEADER = "x-openai-internal-codex-responses-lite";
@@ -9,55 +9,71 @@ export const CODEX_TURN_METADATA_HEADER = "x-codex-turn-metadata";
9
9
  export const CODEX_TURN_STATE_HEADER = "x-codex-turn-state";
10
10
  export const CODEX_ATTESTATION_HEADER = "x-oai-attestation";
11
11
 
12
+ // Caller credentials are forwarded only to the canonical Codex destination, never by capability.
13
+ export const FORWARD_HEADERS = [
14
+ "authorization", "chatgpt-account-id", "openai-beta", "originator", "session_id", "session-id",
15
+ "thread-id", "x-client-request-id", "x-codex-beta-features", "x-codex-installation-id",
16
+ "x-codex-parent-thread-id", "x-codex-turn-metadata", "x-codex-turn-state", "x-codex-window-id",
17
+ "x-oai-attestation", "x-openai-subagent", "x-responsesapi-include-timing-metrics", "version", CODEX_RESPONSES_LITE_HEADER,
18
+ ];
19
+
12
20
  const MAX_ROUTING_MODEL_BYTES = 256;
13
21
  const MAX_ROUTING_TIER_BYTES = 64;
14
- const INSTALL_BODY_KEY = "opencodex-codex-pool-install-body-v1";
15
- const INSTALL_TAG_KEY = "opencodex-codex-pool-install-tag-v1";
16
- const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
17
22
  const MAX_TURN_METADATA_BYTES = 32 * 1024;
23
+ // Each escaped code unit (U+007F+) becomes 6 ASCII bytes: at most 3x the UTF-8 size of
24
+ // non-ASCII text (DEL alone grows 6x), so 96 KiB holds any DEL-free canonical value.
25
+ const MAX_ESCAPED_TURN_METADATA_BYTES = 3 * MAX_TURN_METADATA_BYTES;
18
26
 
19
- function accountTagForUuidPrefix(account: string, prefix20Hex: string): string {
20
- return createHmac("sha256", INSTALL_TAG_KEY).update(`${account}\0${prefix20Hex.toLowerCase()}`).digest("hex").slice(0, 12);
27
+ /** Compatibility export: caller values never contribute to the selected account identity. */
28
+ export function deriveCodexAccountInstallationId(chatgptAccountId: string, _callerInstallationId: string): string {
29
+ return codexInstallationIdForAccount(chatgptAccountId);
21
30
  }
22
31
 
23
32
  /**
24
- * Deterministic, idempotent RFC 4122 v4 UUID isolated per (chatgptAccountId, callerInstallationId).
25
- * Calling it twice with the same chatgptAccountId returns the identical UUID without double-hashing.
33
+ * Rewrites the `installation_id` inside Codex turn metadata while preserving all other fields.
34
+ *
35
+ * Structure contract: JSON with a nonblank string installation_id is returned as printable ASCII — every code unit outside
36
+ * U+0020–U+007E is escaped (JSON.stringify already escapes U+0000–U+001F, with short forms
37
+ * such as `\\n`; U+007F and above become `\\uXXXX` here). Both consumers of rewritten turn metadata (the
38
+ * `x-codex-turn-metadata` HTTP header and the embedded `client_metadata` value)
39
+ * receive this ASCII-safe form, so header setters never see literal Unicode.
40
+ *
41
+ * The 32 KiB bound applies to the canonical (unescaped UTF-8) rewritten JSON, and the escaped
42
+ * result is capped at 96 KiB. Feeding an accepted result back in is therefore a no-op: it
43
+ * parses to the same canonical JSON, so repeated isolation passes cannot refuse it.
44
+ * Invalid JSON, non-objects, and objects without a nonblank string installation_id pass
45
+ * through unchanged up to 32 KiB; their original bytes are not guaranteed header-safe.
26
46
  */
27
- export function deriveCodexAccountInstallationId(chatgptAccountId: string, callerInstallationId: string): string {
28
- const account = chatgptAccountId.trim();
29
- const raw = callerInstallationId.trim();
30
- if (!account || !raw) return callerInstallationId;
31
- if (UUID_V4_RE.test(raw)) {
32
- const hex = raw.replace(/-/g, "").toLowerCase();
33
- if (hex.slice(20, 32) === accountTagForUuidPrefix(account, hex.slice(0, 20))) {
34
- return raw.toLowerCase();
35
- }
36
- }
37
- const h = createHmac("sha256", INSTALL_BODY_KEY).update(`${account}\0${raw}`).digest("hex");
38
- const variant = ((Number.parseInt(h[16]!, 16) & 0x3) | 0x8).toString(16);
39
- const prefix20 = `${h.slice(0, 8)}${h.slice(8, 12)}4${h.slice(13, 16)}${variant}${h.slice(17, 20)}`;
40
- const node12 = accountTagForUuidPrefix(account, prefix20);
41
- return `${prefix20.slice(0, 8)}-${prefix20.slice(8, 12)}-${prefix20.slice(12, 16)}-${prefix20.slice(16, 20)}-${node12}`;
42
- }
43
-
44
47
  export function rewriteTurnMetadataInstallationId(rawMetadata: string, chatgptAccountId: string): string {
45
- if (!chatgptAccountId.trim() || Buffer.byteLength(rawMetadata, "utf8") > MAX_TURN_METADATA_BYTES) return rawMetadata;
48
+ if (!chatgptAccountId.trim()) throw new CodexInstallationIdUnavailableError();
49
+ // A size bound must refuse the Pool send, never bypass identity projection.
50
+ const rawBytes = Buffer.byteLength(rawMetadata, "utf8");
51
+ if (rawBytes > MAX_ESCAPED_TURN_METADATA_BYTES) throw new CodexInstallationIdUnavailableError();
52
+ // Values returned unchanged keep the raw bound; only rewritten JSON is measured canonically.
53
+ const passThrough = () => {
54
+ if (rawBytes > MAX_TURN_METADATA_BYTES) throw new CodexInstallationIdUnavailableError();
55
+ return rawMetadata;
56
+ };
46
57
  let parsed: unknown;
47
- try { parsed = JSON.parse(rawMetadata); } catch { return rawMetadata; }
48
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return rawMetadata;
58
+ try { parsed = JSON.parse(rawMetadata); } catch { return passThrough(); }
59
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return passThrough();
49
60
  const record = parsed as Record<string, unknown>;
50
- if (typeof record.installation_id !== "string" || !record.installation_id.trim()) return rawMetadata;
61
+ if (typeof record.installation_id !== "string" || !record.installation_id.trim()) return passThrough();
51
62
  const nextId = deriveCodexAccountInstallationId(chatgptAccountId, record.installation_id);
52
- if (nextId === record.installation_id) return rawMetadata;
53
- return JSON.stringify({ ...record, installation_id: nextId });
63
+ const canonical = JSON.stringify({ ...record, installation_id: nextId });
64
+ if (Buffer.byteLength(canonical, "utf8") > MAX_TURN_METADATA_BYTES) throw new CodexInstallationIdUnavailableError();
65
+ // Turn metadata is also sent as an HTTP header; DEL and non-ASCII are invalid field-value bytes.
66
+ const escaped = canonical
67
+ .replace(/[\u007f-\uffff]/g, char => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`);
68
+ if (escaped.length > MAX_ESCAPED_TURN_METADATA_BYTES) throw new CodexInstallationIdUnavailableError();
69
+ return escaped;
54
70
  }
55
71
 
56
72
  export function isolateCodexPoolAccountHeaders(headers: Headers, chatgptAccountId: string): void {
73
+ if (!chatgptAccountId.trim()) throw new CodexInstallationIdUnavailableError();
57
74
  headers.delete(CODEX_ATTESTATION_HEADER);
58
- if (!chatgptAccountId.trim()) return;
59
75
  const installId = headers.get(CODEX_INSTALLATION_ID_HEADER);
60
- if (installId && installId.trim()) {
76
+ if (installId !== null) {
61
77
  headers.set(CODEX_INSTALLATION_ID_HEADER, deriveCodexAccountInstallationId(chatgptAccountId, installId));
62
78
  }
63
79
  const turnMeta = headers.get(CODEX_TURN_METADATA_HEADER);
@@ -67,15 +83,17 @@ export function isolateCodexPoolAccountHeaders(headers: Headers, chatgptAccountI
67
83
  }
68
84
 
69
85
  export function isolateCodexPoolClientMetadata(body: unknown, chatgptAccountId: string | undefined): unknown {
70
- if (!chatgptAccountId?.trim() || !body || typeof body !== "object" || Array.isArray(body)) return body;
86
+ if (chatgptAccountId === undefined) return body;
87
+ if (!chatgptAccountId.trim()) throw new CodexInstallationIdUnavailableError();
88
+ if (!body || typeof body !== "object" || Array.isArray(body)) return body;
71
89
  const record = body as Record<string, unknown>;
72
90
  const cm = record.client_metadata;
73
91
  if (!cm || typeof cm !== "object" || Array.isArray(cm)) return body;
74
92
  const meta = cm as Record<string, unknown>;
75
93
  let nextMeta: Record<string, unknown> | undefined;
76
94
  const rawInstallId = meta[CODEX_INSTALLATION_ID_HEADER];
77
- if (typeof rawInstallId === "string" && rawInstallId.trim()) {
78
- const nextId = deriveCodexAccountInstallationId(chatgptAccountId, rawInstallId);
95
+ if (Object.hasOwn(meta, CODEX_INSTALLATION_ID_HEADER)) {
96
+ const nextId = codexInstallationIdForAccount(chatgptAccountId);
79
97
  if (nextId !== rawInstallId) nextMeta = { ...meta, [CODEX_INSTALLATION_ID_HEADER]: nextId };
80
98
  }
81
99
  const rawTurnMeta = (nextMeta ?? meta)[CODEX_TURN_METADATA_HEADER];
@@ -103,3 +121,14 @@ export function applyCodexRoutingHint(headers: Headers, body: unknown): void {
103
121
  headers.set(CODEX_ROUTING_HINT_HEADER,
104
122
  `model=${record.model}${tier === undefined ? "" : `;tier=${tier}`}`);
105
123
  }
124
+
125
+ /** Selected identity is authoritative after provider-header merges, including deletions. */
126
+ export function mergeCodexSelectedHeaders(configured: HeadersInit | undefined, selected: Headers): Headers {
127
+ const headers = new Headers(configured);
128
+ for (const name of [CODEX_INSTALLATION_ID_HEADER, CODEX_TURN_METADATA_HEADER, CODEX_ATTESTATION_HEADER]) headers.delete(name);
129
+ for (const name of FORWARD_HEADERS) {
130
+ const value = selected.get(name);
131
+ if (value !== null) headers.set(name, value);
132
+ }
133
+ return headers;
134
+ }