@bitkyc08/opencodex 2.96.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.
- package/bin/ocx.mjs +214 -19
- package/gui/dist/assets/{App-bwugJRKn.js → App-DuNhggE1.js} +15 -15
- package/gui/dist/assets/{Tray-BOPQyDbH.js → Tray-CEw0y0jR.js} +1 -1
- package/gui/dist/assets/index-CynE_Rue.js +94 -0
- package/gui/dist/assets/{quota-summary-6HsrHQAy.js → quota-summary-VHFSlUuM.js} +1 -1
- package/gui/dist/index.html +1 -1
- package/package.json +1 -1
- package/src/adapters/command-code.ts +15 -16
- package/src/adapters/cursor/transport-retry.ts +2 -2
- package/src/adapters/devin/cloud-direct/chat.ts +15 -6
- package/src/adapters/kiro/stream.ts +63 -4
- package/src/adapters/kiro-constants.ts +15 -1
- package/src/adapters/kiro-events.ts +31 -1
- package/src/adapters/kiro-retry.ts +3 -3
- package/src/adapters/ollama-native.ts +11 -1
- package/src/adapters/openai-responses/empty-assistant.ts +15 -3
- package/src/adapters/openai-responses/passthrough.ts +5 -4
- package/src/adapters/openai-responses/reasoning.ts +9 -4
- package/src/adapters/openai-responses/request-strips.ts +1 -1
- package/src/adapters/physical-send.ts +3 -3
- package/src/adapters/zed-openai-stream.ts +2 -1
- package/src/bridge/errors.ts +11 -2
- package/src/bridge/response-json.ts +2 -1
- package/src/bridge/sse.ts +14 -6
- package/src/chat/failure-verdict.ts +21 -0
- package/src/chat/outbound.ts +139 -21
- package/src/claude/outbound.ts +49 -2
- package/src/cli/capabilities-base.ts +25 -3
- package/src/cli/capabilities-command.ts +12 -3
- package/src/cli/capability-contracts.ts +2 -0
- package/src/cli/codex-launch-auth.ts +30 -1
- package/src/cli/codex-launcher.ts +12 -5
- package/src/cli/codex-shim-autorestore.ts +5 -4
- package/src/cli/dispatch.ts +11 -176
- package/src/cli/help.ts +2 -2
- package/src/cli/index.ts +5 -1
- package/src/cli/link.ts +1 -1
- package/src/cli/registry.ts +11 -3
- package/src/cli/root.ts +8 -0
- package/src/cli/sync-command.ts +243 -0
- package/src/cli/sync-fanout-process.ts +92 -0
- package/src/cli/sync-fanout.ts +150 -0
- package/src/cli/sync-flags.ts +10 -0
- package/src/cli/sync-link-status.ts +39 -0
- package/src/cli/sync-update-guard.ts +18 -0
- package/src/client/connect.ts +31 -14
- package/src/client/link-home.ts +3 -2
- package/src/client/machine-listener.ts +3 -0
- package/src/client/restore-ownership.ts +19 -1
- package/src/client/runtime-restart.ts +12 -4
- package/src/client/runtime.ts +40 -11
- package/src/client/stop-routing.ts +62 -0
- package/src/client/sync-runtime.ts +65 -0
- package/src/clients/config-export.ts +32 -3
- package/src/codex/auth-context.ts +49 -103
- package/src/codex/catalog/antigravity-discovery.ts +16 -5
- package/src/codex/catalog/provider-models.ts +6 -8
- package/src/codex/forward-transport-headers.ts +35 -6
- package/src/codex/inject/config-toml.ts +88 -0
- package/src/codex/inject/multi-agent-v2.ts +30 -4
- package/src/codex/inject/plan.ts +34 -7
- package/src/codex/inject-coordination.ts +11 -0
- package/src/codex/inject.ts +18 -7
- package/src/codex/lineage.ts +13 -7
- package/src/codex/quota.ts +22 -6
- package/src/codex/request-owned-affinity-key.ts +11 -0
- package/src/codex/request-owned-affinity.ts +118 -0
- package/src/codex/request-owned-main-pin.ts +86 -0
- package/src/codex/role-capability.ts +52 -41
- package/src/codex/routing/active-account.ts +13 -5
- package/src/codex/routing/selection.ts +40 -1
- package/src/codex/routing/thread-affinity-store.ts +916 -0
- package/src/codex/routing/thread-affinity.ts +90 -12
- package/src/codex/toml-source-lines.ts +72 -13
- package/src/combos/failover.ts +6 -109
- package/src/combos/request.ts +2 -2
- package/src/combos/resolve.ts +29 -11
- package/src/config/process-state.ts +5 -0
- package/src/config/schema/leaf-validators.ts +1 -0
- package/src/generated/compatibility-version.json +433 -165
- package/src/images/loop.ts +2 -1
- package/src/lib/client-error-body.ts +184 -0
- package/src/lib/client-retry-after.ts +66 -0
- package/src/lib/config-ownership.ts +4 -0
- package/src/lib/context-overflow-verdict.ts +113 -0
- package/src/lib/desktop-cli-handoff.d.mts +1 -1
- package/src/lib/desktop-cli-handoff.mjs +11 -1
- package/src/lib/empty-tool-catalog.ts +25 -3
- package/src/lib/error-destination.ts +47 -0
- package/src/lib/failure-detail.ts +66 -0
- package/src/lib/model-identity.ts +44 -0
- package/src/lib/private-sqlite-path.ts +124 -0
- package/src/lib/response-service-tier.ts +17 -0
- package/src/lib/retry-after.ts +3 -0
- package/src/lib/spend-ledger-owner.ts +43 -4
- package/src/lib/upstream-condition.ts +142 -0
- package/src/lib/upstream-retry.ts +14 -11
- package/src/lib/windows-owner-acl.ts +13 -6
- package/src/link/remote-platform.ts +14 -0
- package/src/link/remote-windows.ts +51 -9
- package/src/link/ssh-argv.ts +63 -10
- package/src/oauth/generic-account-failover.ts +13 -11
- package/src/oauth/index.ts +36 -74
- package/src/oauth/oauth-errors.ts +67 -0
- package/src/oauth/store.ts +1 -1
- package/src/protocols/codecs/ollama.ts +197 -0
- package/src/protocols/encoders/adapter-events.ts +4 -0
- package/src/protocols/encoders/chat.ts +18 -10
- package/src/protocols/trace.ts +18 -0
- package/src/providers/fastwire.ts +3 -2
- package/src/providers/quota/anthropic-usage-windows.ts +13 -3
- package/src/providers/quota/vendor-probes-key.ts +60 -24
- package/src/providers/request-pacing.ts +3 -2
- package/src/responses/apply-patch-envelope.ts +45 -19
- package/src/responses/compaction-history-framing.ts +5 -1
- package/src/responses/freeform-wrapper-scan.ts +5 -3
- package/src/responses/progressive-freeform-input.ts +354 -45
- package/src/routing/fallback-policy.ts +3 -1
- package/src/server/admission-model-scope.ts +17 -6
- package/src/server/admitted-http-turn.ts +56 -0
- package/src/server/auth-cors.ts +5 -0
- package/src/server/chat-completions.ts +45 -20
- package/src/server/chat-native-sse.ts +52 -7
- package/src/server/chat-native.ts +60 -35
- package/src/server/claude-bridge-pool-session.ts +59 -0
- package/src/server/claude-messages.ts +51 -24
- package/src/server/context-history.ts +5 -1
- package/src/server/inbound-body-admission.ts +11 -4
- package/src/server/index/ollama-routes.ts +89 -0
- package/src/server/index/serve-options.ts +21 -4
- package/src/server/index/websocket-handler.ts +4 -2
- package/src/server/index.ts +6 -36
- package/src/server/inference/client-encoder-delivery.ts +4 -2
- package/src/server/json-serialized-bytes.ts +44 -0
- package/src/server/management/agent-settings-routes.ts +24 -21
- package/src/server/management/codex-cli-update-routes.ts +2 -1
- package/src/server/management/route-registry.ts +1 -1
- package/src/server/messages-native-scope.ts +2 -1
- package/src/server/messages-native-tool-guard.ts +1 -1
- package/src/server/messages-native.ts +12 -7
- package/src/server/messages-shared.ts +6 -2
- package/src/server/native-final-log.ts +93 -0
- package/src/server/ollama-inbound.ts +349 -0
- package/src/server/ollama-native-paths.ts +21 -0
- package/src/server/ollama-route-policy.ts +73 -0
- package/src/server/relay.ts +22 -3
- package/src/server/request-decompress.ts +4 -2
- package/src/server/request-log-failure-attribution.ts +22 -0
- package/src/server/request-log-failure-detail.ts +80 -0
- package/src/server/request-log-terminal-status.ts +4 -2
- package/src/server/request-log.ts +79 -42
- package/src/server/response-log-body.ts +6 -1
- package/src/server/responses/account-change-state.ts +17 -6
- package/src/server/responses/adapter-continuation.ts +9 -4
- package/src/server/responses/adapter-delivery.ts +5 -4
- package/src/server/responses/adapter-dispatch.ts +31 -30
- package/src/server/responses/anthropic-thinking-recovery.ts +3 -0
- package/src/server/responses/codex-auth-error.ts +19 -18
- package/src/server/responses/codex-ws-exchange.ts +11 -8
- package/src/server/responses/codex-ws-metadata.ts +94 -21
- package/src/server/responses/codex-ws-request.ts +3 -1
- package/src/server/responses/compact.ts +53 -23
- package/src/server/responses/compaction-recovery.ts +4 -2
- package/src/server/responses/compaction-routing.ts +9 -4
- package/src/server/responses/core-auth.ts +32 -14
- package/src/server/responses/core-codex-account.ts +17 -6
- package/src/server/responses/core-combo-failure.ts +5 -1
- package/src/server/responses/core-combo-native.ts +2 -1
- package/src/server/responses/core-combo.ts +41 -27
- package/src/server/responses/core-errors.ts +22 -20
- package/src/server/responses/core-lifetime.ts +6 -3
- package/src/server/responses/core-normalize.ts +1 -0
- package/src/server/responses/core-options.ts +7 -0
- package/src/server/responses/core-pipeline.ts +4 -3
- package/src/server/responses/fetch-helpers.ts +7 -1
- package/src/server/responses/input-admission.ts +28 -2
- package/src/server/responses/native-injection.ts +1 -1
- package/src/server/responses/native-response-json.ts +13 -4
- package/src/server/responses/native-response-output.ts +1 -2
- package/src/server/responses/non-replayable-error.ts +2 -1
- package/src/server/responses/pacing-overload.ts +3 -2
- package/src/server/responses/passthrough-delivery.ts +55 -14
- package/src/server/responses/passthrough-dispatch.ts +19 -17
- package/src/server/responses/passthrough-error.ts +9 -9
- package/src/server/responses/policy-fallback.ts +2 -1
- package/src/server/responses/request-prepare.ts +67 -48
- package/src/server/responses/request-transport.ts +35 -31
- package/src/server/responses/run-turn-execution.ts +6 -6
- package/src/server/responses/sidecar-execution.ts +16 -12
- package/src/server/responses/spend-storage-error.ts +2 -1
- package/src/server/responses/ws-upstream.ts +9 -0
- package/src/server/responses-custom-tool-repair.ts +14 -3
- package/src/server/responses-terminal-repair.ts +5 -2
- package/src/server/responses-undeclared-tool-guard.ts +39 -16
- package/src/server/safe-response-headers.ts +162 -13
- package/src/server/turn-state-handles.ts +164 -0
- package/src/server/workflow-refusal.ts +2 -1
- package/src/service/ownership-mutation-lease.d.mts +11 -2
- package/src/service/ownership-mutation-lease.mjs +53 -11
- package/src/types/config.ts +2 -0
- package/src/update/index.ts +133 -25
- package/src/update/npm-install.d.mts +8 -0
- package/src/update/npm-install.mjs +20 -1
- package/src/update/orchestrated-admission.d.mts +4 -0
- package/src/update/orchestrated-admission.mjs +12 -0
- package/src/update/orchestrated-arguments.d.mts +12 -0
- package/src/update/orchestrated-arguments.mjs +64 -0
- package/src/update/orchestrated-child.d.mts +12 -0
- package/src/update/orchestrated-child.mjs +70 -0
- package/src/update/orchestrated-entry.ts +234 -0
- package/src/update/orchestrated-identity-probe-entry.ts +20 -0
- package/src/update/orchestrated-identity.ts +53 -0
- package/src/update/orchestrated-live-identity.ts +48 -0
- package/src/update/orchestrated-node-driver.mjs +99 -0
- package/src/update/orchestrated-outcome.d.mts +21 -0
- package/src/update/orchestrated-outcome.mjs +40 -0
- package/src/update/orchestrated-plan.ts +49 -0
- package/src/update/orchestrated-pnpm.d.mts +8 -0
- package/src/update/orchestrated-pnpm.mjs +33 -0
- package/src/update/orchestrated-session.d.mts +37 -0
- package/src/update/orchestrated-session.mjs +264 -0
- package/src/update/orchestrated-token.d.mts +10 -0
- package/src/update/orchestrated-token.mjs +21 -0
- package/src/update/orchestrated-token.ts +3 -0
- package/src/update/orchestrated-tree.d.mts +1 -0
- package/src/update/orchestrated-tree.mjs +14 -0
- package/src/update/pnpm-global-install.d.mts +6 -0
- package/src/update/pnpm-global-install.mjs +9 -2
- package/src/update/posix-install-supervisor-entry.mjs +6 -0
- package/src/update/posix-install-supervisor.d.mts +10 -0
- package/src/update/posix-install-supervisor.mjs +88 -0
- package/src/update/sync-update-mutex.d.mts +10 -0
- package/src/update/sync-update-mutex.mjs +164 -0
- package/src/update/sync-update-mutex.ts +1 -0
- package/src/update/test-home-guard.mjs +33 -0
- package/src/update/transactional-install.mjs +2 -2
- package/src/usage/error-detail.ts +225 -0
- package/src/usage/log.ts +60 -27
- package/src/web-search/loop.ts +31 -5
- package/gui/dist/assets/index-ebuVUtB7.js +0 -94
|
@@ -1,8 +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";
|
|
1
5
|
import type { OcxRuntimeProviderConfig } from "./auth-context-provider";
|
|
2
6
|
export type { OcxRuntimeProviderConfig } from "./auth-context-provider";
|
|
3
7
|
export { stripCodexRuntimeProviderFields } from "./auth-context-provider";
|
|
4
8
|
import { bindPoolCreditPolicy, poolCreditHoldResetAt, poolContextCreditHoldResetAt, poolCreditRecoveryNeeded, poolContextCreditRecoveryNeeded, poolCreditRecoveryRetryAt } from "./pool-credit-policy";
|
|
5
|
-
import { hasSpendableCodexCredits } from "./quota-types";
|
|
6
9
|
import { nextQuotaQueryDelay } from "./quota-query-backoff";
|
|
7
10
|
import { noteMainAccountActivity } from "./main-account-external-usage";
|
|
8
11
|
import { codexAccountPriorityFailbackEnabled } from "./account-priority";
|
|
@@ -40,9 +43,7 @@ import type { NativeMainStartupBlockReason } from "./native-profile-startup";
|
|
|
40
43
|
import { waitForMainAccountPolicyBinding } from "./main-account-policy-wait";
|
|
41
44
|
import {
|
|
42
45
|
codexQuotaScopeForModel,
|
|
43
|
-
computeCodexUsageScore,
|
|
44
46
|
getCodexQuotaHealthSnapshot,
|
|
45
|
-
isEffectiveCodexAccountPinned,
|
|
46
47
|
releaseCodexQuotaProbeLease,
|
|
47
48
|
releaseCodexQuotaScopeProbeLease,
|
|
48
49
|
tryAcquireCodexQuotaProbeLease,
|
|
@@ -74,8 +75,8 @@ import type { CodexCooldownSource, CodexQuotaScope } from "./routing";
|
|
|
74
75
|
import { maskAccountId } from "../lib/privacy";
|
|
75
76
|
import { formatErrorResponse, formatUsageLimitReachedResponse } from "../bridge";
|
|
76
77
|
import { nextCodexPoolRecoveryAt } from "./routing/pool-recovery";
|
|
77
|
-
import {
|
|
78
|
-
import { codexAccountUsesCreditsAfterLimit
|
|
78
|
+
import { getAccountQuota, isValidWhamHistoryObservation, parseUsageQuota, parseMainPolicyUsageQuota, setAccountQuotaFromParsed } from "./quota";
|
|
79
|
+
import { codexAccountUsesCreditsAfterLimit } from "./account-credit-use";
|
|
79
80
|
import type { CodexAccountMode, OcxConfig, OcxProviderConfig } from "../types";
|
|
80
81
|
import { FORWARD_HEADERS } from "../adapters/openai-responses";
|
|
81
82
|
import { isolateCodexPoolAccountHeaders } from "./forward-transport-headers";
|
|
@@ -85,7 +86,6 @@ import {
|
|
|
85
86
|
resolveMainAccountHardLockThresholds,
|
|
86
87
|
getMainAccountHardLockStatus,
|
|
87
88
|
isMainAccountHardLockEnabled,
|
|
88
|
-
isMainAccountHardLocked,
|
|
89
89
|
} from "./main-account-hard-lock";
|
|
90
90
|
import {
|
|
91
91
|
captureMainAccountIdentityGeneration,
|
|
@@ -102,67 +102,9 @@ import { CODEX_RESERVE_HELPER_UNSUPPORTED_MESSAGE, isCodexReserveHelperUnsupport
|
|
|
102
102
|
import type { DataPlaneAdmission } from "../server/auth-cors";
|
|
103
103
|
import { getMainReserveAuthorization, isMainReserveAuthorizationLive, nativeUserIdClaims, type MainReserveAuthorization } from "./reserve-availability";
|
|
104
104
|
import { UpstreamRetryEvidenceError } from "../lib/upstream-retry";
|
|
105
|
-
import { getEffectiveCodexAutoSwitchThreshold } from "./account-auto-switch";
|
|
106
105
|
import { CODEX_MAIN_DUPLICATE_ACTION, configuredCodexMainDuplicate } from "./collision-identity";
|
|
107
106
|
import { AgentAssertionUnsupportedError, authorizationCredential, hasAgentAssertionAuthorization } from "../lib/authorization-scheme";
|
|
108
107
|
|
|
109
|
-
/**
|
|
110
|
-
* A request-owned bearer cannot inspect the physical main credential for its plan, but cached
|
|
111
|
-
* WHAM usage is still valid routing evidence for the same logical main account. Score it with
|
|
112
|
-
* the conservative unknown-plan rule: an unobserved governing window preserves the pin, while
|
|
113
|
-
* any known weekly/monthly/short value at the threshold releases it through the ordinary Pool
|
|
114
|
-
* path. This keeps the keyring boundary intact instead of reading auth.json just to classify a
|
|
115
|
-
* request that already brought its own credential (#3157).
|
|
116
|
-
*/
|
|
117
|
-
function requestOwnedMainPinHasQuotaHeadroom(config: OcxConfig): boolean {
|
|
118
|
-
const threshold = getEffectiveCodexAutoSwitchThreshold(config, MAIN_CODEX_ACCOUNT_ID);
|
|
119
|
-
if (threshold <= 0) return true;
|
|
120
|
-
const usage = computeCodexUsageScore(getAccountQuota(MAIN_CODEX_ACCOUNT_ID), undefined, Date.now(), codexAccountUsesCreditsAfterLimit(config, MAIN_CODEX_ACCOUNT_ID));
|
|
121
|
-
return usage >= CODEX_UNKNOWN_USAGE_SCORE || usage < threshold;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Whether a request carrying its OWN main credential still serves on main because the operator
|
|
126
|
-
* manually pinned it (#3166), split from the surrounding resolution so request preview can ask
|
|
127
|
-
* the identical question (#4850).
|
|
128
|
-
*
|
|
129
|
-
* Exported for exactly one reason: two copies of this fence is how #4850 happened. Final
|
|
130
|
-
* authentication honoured the ownership boundary while request preview, computing its fence from
|
|
131
|
-
* recovery and drain state alone, still handed pool eligibility the default liveness probe and
|
|
132
|
-
* opened the physical `auth.json` twice per spawn. A predicate one caller can forget is a
|
|
133
|
-
* predicate the other caller will eventually disagree with.
|
|
134
|
-
*
|
|
135
|
-
* Read-free by construction, which is what makes it usable on the fenced side. Every input is
|
|
136
|
-
* config, policy, or in-memory runtime state: the pin fields, the paused list, the cached quota
|
|
137
|
-
* score, the main policy quota the hard lock and the credits switch read, and `callerMatchesObservedMain`, which compares HMAC digests against the observed
|
|
138
|
-
* credential record in `main-account-cache.ts`. Nothing here opens a file.
|
|
139
|
-
*
|
|
140
|
-
* `candidate` is the pin before the hard-lock question, because the caller still owes the
|
|
141
|
-
* pending-binding check that only final authentication can fail closed on.
|
|
142
|
-
*/
|
|
143
|
-
export function requestOwnedMainPinState(
|
|
144
|
-
headers: Headers,
|
|
145
|
-
config: OcxConfig,
|
|
146
|
-
policy: CodexAuthPolicyConfig,
|
|
147
|
-
requestScopedMainCredential: boolean,
|
|
148
|
-
fixedAccountId: string | undefined,
|
|
149
|
-
quotaScope?: CodexQuotaScope,
|
|
150
|
-
): { candidate: boolean; preserve: boolean } {
|
|
151
|
-
const candidate = requestScopedMainCredential
|
|
152
|
-
&& fixedAccountId === undefined
|
|
153
|
-
&& config.activeCodexAccountPinned === MAIN_CODEX_ACCOUNT_ID
|
|
154
|
-
&& isEffectiveCodexAccountPinned(config)
|
|
155
|
-
&& !policy.pausedCodexAccountIds?.includes(MAIN_CODEX_ACCOUNT_ID)
|
|
156
|
-
&& requestOwnedMainPinHasQuotaHeadroom(config);
|
|
157
|
-
return {
|
|
158
|
-
candidate,
|
|
159
|
-
preserve: candidate && !(callerMatchesObservedMain(headers)
|
|
160
|
-
&& (isMainAccountHardLocked(policy)
|
|
161
|
-
|| mainCreditsHoldResetAt(policy) !== undefined
|
|
162
|
-
|| getCodexQuotaHealthSnapshot(MAIN_CODEX_ACCOUNT_ID, quotaScope)?.cooldownUntil)),
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
|
|
166
108
|
/**
|
|
167
109
|
* One conversation tree keys as ONE cohort (#4780).
|
|
168
110
|
*
|
|
@@ -247,12 +189,12 @@ export function requestOwnedMainCredentialIsLive(inputs: {
|
|
|
247
189
|
}
|
|
248
190
|
|
|
249
191
|
/**
|
|
250
|
-
* May this request
|
|
192
|
+
* May this request use stored-credential Pool lineage?
|
|
251
193
|
*
|
|
252
|
-
* Two credentials authenticate outside
|
|
253
|
-
* Reserve
|
|
254
|
-
*
|
|
255
|
-
*
|
|
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.
|
|
256
198
|
*
|
|
257
199
|
* Exported so that a preview asks the question with the code that answers it, instead of a
|
|
258
200
|
* restatement that can drift. It drifted once already: preview read a family relation from raw
|
|
@@ -272,6 +214,15 @@ export function codexPoolStateEligible(
|
|
|
272
214
|
);
|
|
273
215
|
}
|
|
274
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
|
+
|
|
275
226
|
/**
|
|
276
227
|
* The lineage a PREVIEW is allowed to see: read-only, and only for a request that may hold Pool
|
|
277
228
|
* state. Recording is left to the resolution that actually binds, so a preview can never leave a
|
|
@@ -289,7 +240,7 @@ export function previewCodexPoolLineage(
|
|
|
289
240
|
|
|
290
241
|
export type CodexAuthContext =
|
|
291
242
|
| {
|
|
292
|
-
kind: "main"; accountId: null; reserveAuthorization?: MainReserveAuthorization;
|
|
243
|
+
kind: "main"; accountId: null; reserveAuthorization?: MainReserveAuthorization; affinityKey?: string; conversationStateKey?: string; affinityDecision?: CodexAffinityDecision; affinityBindingSnapshot?: RequestOwnedBindingSnapshot;
|
|
293
244
|
/** Captured for the observed main credential actually selected for upstream. */
|
|
294
245
|
mainQuotaDispatch?: MainQuotaDispatch;
|
|
295
246
|
}
|
|
@@ -304,7 +255,7 @@ export type CodexAuthContext =
|
|
|
304
255
|
/** Bypass Pool selection and suppress quota/transient failover for an exact selector. */
|
|
305
256
|
fixedAccount?: boolean;
|
|
306
257
|
/** Pool binding key; the Desktop fallback is an opaque process-local HMAC. */
|
|
307
|
-
affinityKey?: string;
|
|
258
|
+
affinityKey?: string; conversationStateKey?: string;
|
|
308
259
|
/**
|
|
309
260
|
* Set when this request was admitted through an active quota cooldown as
|
|
310
261
|
* the account's single probe. Must be echoed into the upstream outcome so
|
|
@@ -338,7 +289,7 @@ export type CodexAuthContext =
|
|
|
338
289
|
chatgptAccountId: string;
|
|
339
290
|
/** Bypass Pool selection and suppress quota/transient failover for an exact selector. */
|
|
340
291
|
fixedAccount?: boolean;
|
|
341
|
-
affinityKey?: string; // See `pool.affinityKey`.
|
|
292
|
+
affinityKey?: string; conversationStateKey?: string; // See `pool.affinityKey`.
|
|
342
293
|
/** See `pool.probeLeaseId`. */
|
|
343
294
|
probeLeaseId?: string;
|
|
344
295
|
quotaScope?: CodexQuotaScope;
|
|
@@ -786,12 +737,6 @@ export function createCodexAuthDispatchGuard(
|
|
|
786
737
|
};
|
|
787
738
|
}
|
|
788
739
|
|
|
789
|
-
function mainCreditsHoldResetAt(config: Pick<OcxConfig, "creditCodexAccountIds">): number | undefined {
|
|
790
|
-
if (codexAccountUsesCreditsAfterLimit(config, MAIN_CODEX_ACCOUNT_ID)
|
|
791
|
-
&& hasSpendableCodexCredits(getMainPolicyQuota())) return undefined;
|
|
792
|
-
return codexUsageLimitResetAt(getMainPolicyQuota(), undefined, Date.now());
|
|
793
|
-
}
|
|
794
|
-
|
|
795
740
|
function assertMainAccountPolicy(
|
|
796
741
|
config: Pick<OcxConfig, "codexMainAccountHardLock" | "codexMainAccountHardLockThresholds" | "creditCodexAccountIds" | "codexUseRemainingQuotaAccountIds"> | undefined,
|
|
797
742
|
): void {
|
|
@@ -807,15 +752,6 @@ function assertMainAccountPolicy(
|
|
|
807
752
|
noteMainAccountActivity();
|
|
808
753
|
}
|
|
809
754
|
|
|
810
|
-
/** No auth-file I/O: an unsigned claim alone never identifies a caller as stored main. */
|
|
811
|
-
function callerMatchesObservedMain(headers: Headers): boolean {
|
|
812
|
-
const bearer = authorizationCredential(headers);
|
|
813
|
-
if (!bearer) return false;
|
|
814
|
-
const effectiveAccountId = headers.get("chatgpt-account-id")
|
|
815
|
-
?? extractAccountId(undefined, bearer);
|
|
816
|
-
return matchesMainQuotaCredential(bearer, effectiveAccountId);
|
|
817
|
-
}
|
|
818
|
-
|
|
819
755
|
/** Constant-time digest comparison so bearer bytes never drive branch timing. */
|
|
820
756
|
function sameCredentialMaterial(a: string, b: string): boolean {
|
|
821
757
|
return timingSafeEqual(createHash("sha256").update(a).digest(), createHash("sha256").update(b).digest());
|
|
@@ -990,7 +926,8 @@ export function cooldownErrorResponse(
|
|
|
990
926
|
const res = formatErrorResponse(429, "rate_limit_error", cooldownErrorMessage(err, accountSelector));
|
|
991
927
|
const headers = new Headers(res.headers);
|
|
992
928
|
if (!(err instanceof CodexReserveUnavailableError)) {
|
|
993
|
-
|
|
929
|
+
const advice = formatClientRetryAfter(Math.max(1, Math.ceil((err.cooldownUntil - now) / 1000)));
|
|
930
|
+
if (advice !== undefined) headers.set("Retry-After", advice);
|
|
994
931
|
}
|
|
995
932
|
return new Response(res.body, { status: res.status, headers });
|
|
996
933
|
}
|
|
@@ -1282,6 +1219,8 @@ async function resolveCodexAuthContextUnannotated(
|
|
|
1282
1219
|
directSelectionAdmission.release();
|
|
1283
1220
|
}
|
|
1284
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);
|
|
1285
1224
|
// Pool discovery excludes request-owned main credentials by design: they must never be folded
|
|
1286
1225
|
// into stored-account entitlement, affinity, or persistence state. An effective manual main pin
|
|
1287
1226
|
// is the one exception where that exclusion is selection evidence in the opposite direction.
|
|
@@ -1294,7 +1233,7 @@ async function resolveCodexAuthContextUnannotated(
|
|
|
1294
1233
|
options.isDirectCallerEntitledToCodexModel ?? isDirectCallerEntitledToCodexModel
|
|
1295
1234
|
)(headers, options.modelId);
|
|
1296
1235
|
if (callerEntitled && preserveRequestOwnedMainPin()) {
|
|
1297
|
-
return { kind: "main", accountId: null };
|
|
1236
|
+
return { kind: "main", accountId: null, ...(mode === "pool" && conversationStateKey ? { conversationStateKey } : {}) };
|
|
1298
1237
|
}
|
|
1299
1238
|
}
|
|
1300
1239
|
// An explicit namespace binding is stronger than the provider's default mode. It must use the
|
|
@@ -1309,19 +1248,24 @@ async function resolveCodexAuthContextUnannotated(
|
|
|
1309
1248
|
}
|
|
1310
1249
|
// A caller bearer can still accompany a request that selects a configured Pool account. Do not
|
|
1311
1250
|
// let that request read, delete, or create a file-main affinity binding while deciding whether a
|
|
1312
|
-
// stored account is available
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
// first-placing child consults it; a request-owned or fixed credential never enters Pool
|
|
1318
|
-
// state, so it never enters lineage either.
|
|
1319
|
-
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)
|
|
1320
1256
|
? recordCodexThreadLineage(headers)
|
|
1321
1257
|
: undefined;
|
|
1322
1258
|
// Why this request is on this account, carried to the request log so a move reads as an event
|
|
1323
1259
|
// instead of something inferred from account labels across lines (#4546).
|
|
1324
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
|
+
};
|
|
1325
1269
|
// The half-open trial this request was granted, if it is the one allowed to test a held
|
|
1326
1270
|
// account. Declared out here because the release paths below and the returned context are on
|
|
1327
1271
|
// opposite sides of several throws (#4701).
|
|
@@ -1470,17 +1414,17 @@ async function resolveCodexAuthContextUnannotated(
|
|
|
1470
1414
|
throw new CodexRecoveryWithheldError(resolution.accountId, resolution.retryAt, resolution.detourAccountId);
|
|
1471
1415
|
}
|
|
1472
1416
|
const selected = resolution.status === "selected" ? resolution.accountId : null;
|
|
1473
|
-
affinityDecision = resolution.affinity;
|
|
1417
|
+
affinityDecision = selected ? honestAffinityDecision(resolution.affinity, affinityKey, selected, quotaScope, options.modelId, requestScopedMainCredential && config.codexPool?.requestOwnedAffinity !== true) : resolution.affinity;
|
|
1474
1418
|
transientProbe = resolution.status === "selected" ? resolution.transientProbe : undefined;
|
|
1475
1419
|
// Main now takes part in ordering when the request carries its own main bearer (#5019), so
|
|
1476
1420
|
// selection can name it outright rather than only through the no-candidate fallback below.
|
|
1477
1421
|
// Serve that selection from the credential the request arrived with: the read fence above
|
|
1478
1422
|
// forbids this request from claiming, reading or reconciling the stored main profile, and a
|
|
1479
|
-
// request-owned credential owns no
|
|
1480
|
-
// 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.
|
|
1481
1425
|
if (selected === MAIN_CODEX_ACCOUNT_ID && requestScopedMainCredential) {
|
|
1482
1426
|
releaseTransientProbeGrant();
|
|
1483
|
-
const context = await
|
|
1427
|
+
const context = await resolveKeyedCallerMain();
|
|
1484
1428
|
console.info("[codex] Pool selected caller-owned main credential.");
|
|
1485
1429
|
return context;
|
|
1486
1430
|
}
|
|
@@ -1500,7 +1444,7 @@ async function resolveCodexAuthContextUnannotated(
|
|
|
1500
1444
|
&& !(callerMatchesObservedMain(headers) && policy.pausedCodexAccountIds?.includes(MAIN_CODEX_ACCOUNT_ID))
|
|
1501
1445
|
&& options.excludeAccountId !== MAIN_CODEX_ACCOUNT_ID
|
|
1502
1446
|
) {
|
|
1503
|
-
const context = await
|
|
1447
|
+
const context = await resolveKeyedCallerMain("unusable");
|
|
1504
1448
|
console.info("[codex] Pool used caller-owned main credential: no selectable stored account.");
|
|
1505
1449
|
return context;
|
|
1506
1450
|
}
|
|
@@ -1667,7 +1611,7 @@ async function resolveCodexAuthContextUnannotated(
|
|
|
1667
1611
|
&& !(callerMatchesObservedMain(headers) && policy.pausedCodexAccountIds?.includes(MAIN_CODEX_ACCOUNT_ID))
|
|
1668
1612
|
&& options.excludeAccountId !== MAIN_CODEX_ACCOUNT_ID
|
|
1669
1613
|
&& !callerIsCooledPoolAccount(headers, config, accountId)) {
|
|
1670
|
-
const context = await
|
|
1614
|
+
const context = await resolveKeyedCallerMain("cooldown");
|
|
1671
1615
|
console.info("[codex] Pool used caller-owned main credential: stored account cooldown.");
|
|
1672
1616
|
return context;
|
|
1673
1617
|
}
|
|
@@ -1727,6 +1671,7 @@ async function resolveCodexAuthContextUnannotated(
|
|
|
1727
1671
|
chatgptAccountId: token.chatgptAccountId,
|
|
1728
1672
|
...(fixedAccountId !== undefined ? { fixedAccount: true } : {}),
|
|
1729
1673
|
...(affinityKey ? { affinityKey } : {}),
|
|
1674
|
+
...(conversationStateKey ? { conversationStateKey } : {}),
|
|
1730
1675
|
...(quotaScope ? { quotaScope } : {}),
|
|
1731
1676
|
...(probeLeaseId ? { probeLeaseId } : {}),
|
|
1732
1677
|
...(probeQuotaScope ? { probeQuotaScope } : {}),
|
|
@@ -1750,6 +1695,7 @@ async function resolveCodexAuthContextUnannotated(
|
|
|
1750
1695
|
chatgptAccountId: token.chatgptAccountId,
|
|
1751
1696
|
...(fixedAccountId !== undefined ? { fixedAccount: true } : {}),
|
|
1752
1697
|
...(affinityKey ? { affinityKey } : {}),
|
|
1698
|
+
...(conversationStateKey ? { conversationStateKey } : {}),
|
|
1753
1699
|
...(quotaScope ? { quotaScope } : {}),
|
|
1754
1700
|
...(probeLeaseId ? { probeLeaseId } : {}),
|
|
1755
1701
|
...(probeQuotaScope ? { probeQuotaScope } : {}),
|
|
@@ -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, {
|
|
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 (!
|
|
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()];
|
|
@@ -20,24 +20,53 @@ export const FORWARD_HEADERS = [
|
|
|
20
20
|
const MAX_ROUTING_MODEL_BYTES = 256;
|
|
21
21
|
const MAX_ROUTING_TIER_BYTES = 64;
|
|
22
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;
|
|
23
26
|
|
|
24
27
|
/** Compatibility export: caller values never contribute to the selected account identity. */
|
|
25
28
|
export function deriveCodexAccountInstallationId(chatgptAccountId: string, _callerInstallationId: string): string {
|
|
26
29
|
return codexInstallationIdForAccount(chatgptAccountId);
|
|
27
30
|
}
|
|
28
31
|
|
|
32
|
+
/**
|
|
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.
|
|
46
|
+
*/
|
|
29
47
|
export function rewriteTurnMetadataInstallationId(rawMetadata: string, chatgptAccountId: string): string {
|
|
30
48
|
if (!chatgptAccountId.trim()) throw new CodexInstallationIdUnavailableError();
|
|
31
49
|
// A size bound must refuse the Pool send, never bypass identity projection.
|
|
32
|
-
|
|
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
|
+
};
|
|
33
57
|
let parsed: unknown;
|
|
34
|
-
try { parsed = JSON.parse(rawMetadata); } catch { return
|
|
35
|
-
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return
|
|
58
|
+
try { parsed = JSON.parse(rawMetadata); } catch { return passThrough(); }
|
|
59
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return passThrough();
|
|
36
60
|
const record = parsed as Record<string, unknown>;
|
|
37
|
-
if (typeof record.installation_id !== "string" || !record.installation_id.trim()) return
|
|
61
|
+
if (typeof record.installation_id !== "string" || !record.installation_id.trim()) return passThrough();
|
|
38
62
|
const nextId = deriveCodexAccountInstallationId(chatgptAccountId, record.installation_id);
|
|
39
|
-
|
|
40
|
-
|
|
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;
|
|
41
70
|
}
|
|
42
71
|
|
|
43
72
|
export function isolateCodexPoolAccountHeaders(headers: Headers, chatgptAccountId: string): void {
|
|
@@ -672,6 +672,94 @@ export function buildProfileFileForTarget(
|
|
|
672
672
|
return lines.join("\n");
|
|
673
673
|
}
|
|
674
674
|
|
|
675
|
+
/**
|
|
676
|
+
* Root keys this build owns in either profile shape. They are never carried
|
|
677
|
+
* forward: leaving provider-table mode drops `model_provider` from the template,
|
|
678
|
+
* and a caller that passes no catalog path drops `model_catalog_json`, so a
|
|
679
|
+
* carried copy would point the profile at routing this build no longer writes.
|
|
680
|
+
*/
|
|
681
|
+
const MANAGED_PROFILE_ROOT_KEYS = new Set([
|
|
682
|
+
"model_provider",
|
|
683
|
+
"model_catalog_json",
|
|
684
|
+
"openai_base_url",
|
|
685
|
+
]);
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Root keys the previous profile carried that this build does not write.
|
|
689
|
+
*
|
|
690
|
+
* Operators add Codex settings such as `stream_idle_timeout_ms` and
|
|
691
|
+
* `stream_max_retries` to `opencodex.config.toml`. Rebuilding the file from the
|
|
692
|
+
* template dropped them without a word (#8066), so any root key this build does
|
|
693
|
+
* not own is carried over, ahead of the first table. Values that span several
|
|
694
|
+
* lines are copied whole, because one line of a multi-line value would not
|
|
695
|
+
* parse, and every carried assignment keeps its original bytes: nothing is
|
|
696
|
+
* decoded and reserialized, so a 64-bit integer Bun cannot represent survives.
|
|
697
|
+
*
|
|
698
|
+
* A carried root key named like a table the generated profile writes (an inline
|
|
699
|
+
* `features = { ... }` against a generated `[features]`) is dropped: TOML
|
|
700
|
+
* forbids defining the same table twice, and the generated table wins because
|
|
701
|
+
* it carries the settings this build manages.
|
|
702
|
+
*/
|
|
703
|
+
export function preserveUnmanagedProfileKeys(existing: string | null, generated: string): string {
|
|
704
|
+
if (!existing) return generated;
|
|
705
|
+
const generatedKeys = rootKeysOf(generated);
|
|
706
|
+
if (generatedKeys.size === 0) return generated;
|
|
707
|
+
const generatedTables = topLevelTableNamesOf(generated);
|
|
708
|
+
|
|
709
|
+
const existingSource = rootSourceLines(existing);
|
|
710
|
+
const carried: string[] = [];
|
|
711
|
+
const carriedKeys = new Set<string>();
|
|
712
|
+
for (let index = 0; index < existingSource.rootEnd; index += 1) {
|
|
713
|
+
if (!existingSource.lines[index]?.structural) continue;
|
|
714
|
+
const span = sourceAssignmentSpan(existingSource.lines, index, existingSource.rootEnd);
|
|
715
|
+
if (!span) continue;
|
|
716
|
+
index = span.end - 1;
|
|
717
|
+
if (generatedKeys.has(span.key) || MANAGED_PROFILE_ROOT_KEYS.has(span.key)) continue;
|
|
718
|
+
if (generatedTables.has(span.key)) continue;
|
|
719
|
+
if (carriedKeys.has(span.key)) continue;
|
|
720
|
+
carriedKeys.add(span.key);
|
|
721
|
+
// Drop only trailing blank lines; the assignment's own bytes, trailing spaces included, stay.
|
|
722
|
+
carried.push(span.text.replace(/(?:\r?\n[ \t]*)+$/, ""));
|
|
723
|
+
}
|
|
724
|
+
if (carried.length === 0) return generated;
|
|
725
|
+
|
|
726
|
+
const lines = generated.split("\n");
|
|
727
|
+
const firstTable = lines.findIndex((line) => /^\s*\[/.test(line));
|
|
728
|
+
lines.splice(firstTable === -1 ? lines.length : firstTable, 0, [
|
|
729
|
+
"# Root keys OpenCodex does not manage, kept from the previous profile:",
|
|
730
|
+
...carried,
|
|
731
|
+
"",
|
|
732
|
+
].join("\n"));
|
|
733
|
+
return lines.join("\n");
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/** Names of the root assignments in a TOML document, before its first table. */
|
|
737
|
+
function rootKeysOf(content: string): Set<string> {
|
|
738
|
+
const keys = new Set<string>();
|
|
739
|
+
const source = rootSourceLines(content);
|
|
740
|
+
for (let index = 0; index < source.rootEnd; index += 1) {
|
|
741
|
+
if (!source.lines[index]?.structural) continue;
|
|
742
|
+
const span = sourceAssignmentSpan(source.lines, index, source.rootEnd);
|
|
743
|
+
if (!span) continue;
|
|
744
|
+
keys.add(span.key);
|
|
745
|
+
index = span.end - 1;
|
|
746
|
+
}
|
|
747
|
+
return keys;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** First path segment of every table header in a generated document. */
|
|
751
|
+
function topLevelTableNamesOf(content: string): Set<string> {
|
|
752
|
+
const names = new Set<string>();
|
|
753
|
+
for (const line of rootSourceLines(content).lines) {
|
|
754
|
+
if (!line.structural || !/^\s*\[/.test(line.text)) continue;
|
|
755
|
+
try {
|
|
756
|
+
const name = Object.keys(Bun.TOML.parse(line.text))[0];
|
|
757
|
+
if (name !== undefined) names.add(name);
|
|
758
|
+
} catch { /* the template only writes valid headers */ }
|
|
759
|
+
}
|
|
760
|
+
return names;
|
|
761
|
+
}
|
|
762
|
+
|
|
675
763
|
export function chooseCatalogPathForInjection(
|
|
676
764
|
content: string,
|
|
677
765
|
requested?: string | null,
|
|
@@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";
|
|
|
2
2
|
import type { OcxConfig } from "../../types";
|
|
3
3
|
import { ConfigWriteDestinationChanged, type LockHandle } from "../config-write-lock";
|
|
4
4
|
import { CODEX_CONFIG_PATH } from "../paths";
|
|
5
|
+
import type { CodexCliSelectionAsyncParentWrite } from "../cli-update-selection-gate";
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Reconcile the native `features.multi_agent_v2` override when an injection carries an
|
|
@@ -17,7 +18,7 @@ import { CODEX_CONFIG_PATH } from "../paths";
|
|
|
17
18
|
*/
|
|
18
19
|
export type InjectedV1SurfaceReconcile =
|
|
19
20
|
| { ok: true; content: string; changed: boolean }
|
|
20
|
-
| { ok: false; message: string };
|
|
21
|
+
| { ok: false; message: string; retryable?: boolean };
|
|
21
22
|
|
|
22
23
|
let toggleForTests: ((enabled: boolean, env: NodeJS.ProcessEnv, validateBeforeSpawn: () => void) => void) | undefined;
|
|
23
24
|
|
|
@@ -44,6 +45,9 @@ export interface PreparedV1SurfaceReconcile {
|
|
|
44
45
|
* only — `run()` re-checks the flag on the bytes present under the lock.
|
|
45
46
|
*/
|
|
46
47
|
readonly enabledAtPrepare: boolean;
|
|
48
|
+
/** Acquire before the config lock; an already-v1 home needs no selection lease. */
|
|
49
|
+
admit(): Promise<boolean>;
|
|
50
|
+
release(): void;
|
|
47
51
|
/**
|
|
48
52
|
* `heldConfigWriteLock` is the injector's own held write-lock handle: the
|
|
49
53
|
* transition would otherwise re-acquire the same file and refuse itself.
|
|
@@ -74,17 +78,39 @@ export async function prepareInjectedV1SurfaceReconcile(
|
|
|
74
78
|
toggle = (enabled, env, validate) => runCodexFeaturesCommand(enabled ? "enable" : "disable", "multi_agent_v2", env, validate);
|
|
75
79
|
}
|
|
76
80
|
const resolvedToggle = toggle;
|
|
81
|
+
const { beginCodexCliSelectionParentWriteAsync, CodexCliSelectionMutationBusyError } = await import("../cli-update-selection-gate");
|
|
82
|
+
let selection: CodexCliSelectionAsyncParentWrite | undefined;
|
|
83
|
+
const busy = (): InjectedV1SurfaceReconcile => ({
|
|
84
|
+
ok: false, retryable: true,
|
|
85
|
+
message: "Codex config injection refused: the v1 transition has no current CLI selection admission. Retry the injection after the CLI update finishes.",
|
|
86
|
+
});
|
|
77
87
|
return {
|
|
78
88
|
enabledAtPrepare,
|
|
89
|
+
async admit() {
|
|
90
|
+
if (!enabledAtPrepare) return true;
|
|
91
|
+
if (selection) return selection.entered;
|
|
92
|
+
selection = await beginCodexCliSelectionParentWriteAsync();
|
|
93
|
+
return selection.entered;
|
|
94
|
+
},
|
|
95
|
+
release() { selection?.exit(); },
|
|
79
96
|
run(heldConfigWriteLock) {
|
|
80
97
|
// Decide on the bytes present NOW, under the lock — the prepare-time
|
|
81
98
|
// answer is stale the moment another writer could have touched the file.
|
|
82
99
|
if (!isMultiAgentV2Enabled()) {
|
|
83
100
|
return { ok: true, content: readFileSync(CODEX_CONFIG_PATH, "utf-8"), changed: false };
|
|
84
101
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
102
|
+
// A prepare-time no-op may have become a transition. Refuse without a child;
|
|
103
|
+
// a fresh pass can acquire admission before taking the config lock.
|
|
104
|
+
if (!selection?.entered) return busy();
|
|
105
|
+
let transition: ReturnType<typeof transitionMultiAgentV2>;
|
|
106
|
+
try {
|
|
107
|
+
transition = selection.commit(() => transitionMultiAgentV2(false, resolvedToggle, {
|
|
108
|
+
...(heldConfigWriteLock !== undefined ? { heldConfigWriteLock } : {}),
|
|
109
|
+
}));
|
|
110
|
+
} catch (error) {
|
|
111
|
+
if (error instanceof CodexCliSelectionMutationBusyError) return busy();
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
88
114
|
if (!transition.ok) {
|
|
89
115
|
if (transition.retryable === false) throw new ConfigWriteDestinationChanged(transition.error);
|
|
90
116
|
return {
|