@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
package/src/codex/inject/plan.ts
CHANGED
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
* post-transition bytes is what keeps the committed file from re-enabling the
|
|
10
10
|
* flag the reconcile just turned off.
|
|
11
11
|
*/
|
|
12
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
12
13
|
import { websocketsEnabled } from "../../config";
|
|
13
14
|
import {
|
|
14
15
|
HISTORY_RELABEL_STANDS_DOWN,
|
|
@@ -22,7 +23,7 @@ import {
|
|
|
22
23
|
journaledReplacedRootWebSearch,
|
|
23
24
|
} from "../journal";
|
|
24
25
|
import { stripJournaledOpenaiBaseUrl } from "../injected-marker";
|
|
25
|
-
import { CODEX_CONFIG_PATH, resolveCodexStateDbPath } from "../paths";
|
|
26
|
+
import { CODEX_CONFIG_PATH, CODEX_PROFILE_PATH, resolveCodexStateDbPath } from "../paths";
|
|
26
27
|
import { transformManagedSubagentDefaults, type WrittenSubagentDefaults } from "../subagent-defaults";
|
|
27
28
|
import type { OcxConfig } from "../../types";
|
|
28
29
|
import type { CodexWriteCandidate } from "../write-coordination";
|
|
@@ -35,6 +36,7 @@ import {
|
|
|
35
36
|
ensureFastModeFeature,
|
|
36
37
|
ensureRootWebSearchDisabled,
|
|
37
38
|
normalizeServiceTier,
|
|
39
|
+
preserveUnmanagedProfileKeys,
|
|
38
40
|
removeProfileSection,
|
|
39
41
|
setRootModelCatalogPath,
|
|
40
42
|
setRootModelProvider,
|
|
@@ -71,6 +73,11 @@ export interface CodexInjectionPlanOk {
|
|
|
71
73
|
content: string;
|
|
72
74
|
/** The exact string about to replace the profile file. */
|
|
73
75
|
profileContent: string;
|
|
76
|
+
/**
|
|
77
|
+
* The profile bytes `profileContent` preserved keys from (null when absent).
|
|
78
|
+
* Re-checked under the write lock so an edit landing meanwhile is not overwritten.
|
|
79
|
+
*/
|
|
80
|
+
profileSource: string | null;
|
|
74
81
|
/** The resolved catalog path, never the raw option. */
|
|
75
82
|
catalogPath: string | null;
|
|
76
83
|
providerTableMode: boolean;
|
|
@@ -323,12 +330,16 @@ export function deriveCodexInjectionPlan(
|
|
|
323
330
|
managedDefaultsMessage = ` ⚠️ ${nativeSubagentDefaultsWarning}\n`;
|
|
324
331
|
}
|
|
325
332
|
|
|
326
|
-
const
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
333
|
+
const profileSource = readCodexProfileSource();
|
|
334
|
+
const profileContent = preserveUnmanagedProfileKeys(
|
|
335
|
+
profileSource,
|
|
336
|
+
buildProfileFileForTarget(
|
|
337
|
+
routingTarget,
|
|
338
|
+
catalogPath,
|
|
339
|
+
websocketsForRoutingTarget(config, routingTarget),
|
|
340
|
+
config?.fastMode,
|
|
341
|
+
config?.codexProviderDisplayName,
|
|
342
|
+
),
|
|
332
343
|
);
|
|
333
344
|
content = applyEol(content, eol);
|
|
334
345
|
|
|
@@ -395,6 +406,7 @@ export function deriveCodexInjectionPlan(
|
|
|
395
406
|
baselineContent,
|
|
396
407
|
content,
|
|
397
408
|
profileContent,
|
|
409
|
+
profileSource,
|
|
398
410
|
catalogPath,
|
|
399
411
|
providerTableMode,
|
|
400
412
|
keepRootOverrideAlongsideTable,
|
|
@@ -414,3 +426,18 @@ export function deriveCodexInjectionPlan(
|
|
|
414
426
|
},
|
|
415
427
|
};
|
|
416
428
|
}
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* Current profile bytes, or null when absent. Read directly: a profile removed between an
|
|
433
|
+
* existence check and the read is simply absent. If it reappears before the write lock, the
|
|
434
|
+
* lock-time comparison refuses retryably; other read errors propagate.
|
|
435
|
+
*/
|
|
436
|
+
export function readCodexProfileSource(): string | null {
|
|
437
|
+
try {
|
|
438
|
+
return readFileSync(CODEX_PROFILE_PATH, "utf-8");
|
|
439
|
+
} catch (error) {
|
|
440
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
441
|
+
return null;
|
|
442
|
+
}
|
|
443
|
+
}
|
|
@@ -189,6 +189,9 @@ export function captureCodexPreImages(): CodexPreImages {
|
|
|
189
189
|
};
|
|
190
190
|
}
|
|
191
191
|
|
|
192
|
+
/** The profile bytes one injection published, set just before it writes them. */
|
|
193
|
+
export interface CodexProfilePublish { published?: string }
|
|
194
|
+
|
|
192
195
|
/**
|
|
193
196
|
* How many transactions of evidence the ledger keeps.
|
|
194
197
|
*
|
|
@@ -366,10 +369,16 @@ export function recordCodexNativeTransactionProvenance(
|
|
|
366
369
|
*
|
|
367
370
|
* Every surface is attempted even after one fails: a second failure is worth
|
|
368
371
|
* knowing about, and stopping early would leave more unrestored than necessary.
|
|
372
|
+
*
|
|
373
|
+
* `profilePublish`, when given, limits the profile surface to bytes this
|
|
374
|
+
* operation wrote: it is reverted only if `published` is set and the file still
|
|
375
|
+
* holds exactly those bytes. A refusal before the publish, or a profile another
|
|
376
|
+
* writer replaced since, is left as it is.
|
|
369
377
|
*/
|
|
370
378
|
export function restoreCodexPreImages(
|
|
371
379
|
pre: CodexPreImages,
|
|
372
380
|
heldConfigWriteLock?: LockHandle,
|
|
381
|
+
profilePublish?: CodexProfilePublish,
|
|
373
382
|
): { complete: boolean; unrestored: readonly string[] } {
|
|
374
383
|
const locked = withConfigWriteLockHeld(CODEX_CONFIG_PATH, heldConfigWriteLock, held => {
|
|
375
384
|
const unrestored: string[] = [];
|
|
@@ -382,6 +391,8 @@ export function restoreCodexPreImages(
|
|
|
382
391
|
// The current journal remains recovery authority until both artifacts are restored.
|
|
383
392
|
if (name === "journal" && unrestored.length > 0) { unrestored.push(name); continue; }
|
|
384
393
|
try {
|
|
394
|
+
if (name === "profile" && profilePublish
|
|
395
|
+
&& (profilePublish.published === undefined || readOrNull(path) !== profilePublish.published)) continue;
|
|
385
396
|
publishCodexArtifact(path, held, (destination, hooks) => {
|
|
386
397
|
if (bytes === null) {
|
|
387
398
|
hooks.validateBeforeRename?.(destination);
|
package/src/codex/inject.ts
CHANGED
|
@@ -25,6 +25,7 @@ import {
|
|
|
25
25
|
captureCodexPreImages,
|
|
26
26
|
codexInjectLockOutcome,
|
|
27
27
|
codexWriteCoordinationEligibility,
|
|
28
|
+
type CodexProfilePublish,
|
|
28
29
|
CodexPartialWriteError,
|
|
29
30
|
CodexWriteConflictError,
|
|
30
31
|
DEFAULT_INJECT_LOCK_TIMEOUT_MS,
|
|
@@ -82,6 +83,7 @@ import {
|
|
|
82
83
|
deriveCodexInjectionPlan,
|
|
83
84
|
type CodexInjectionPlanContext,
|
|
84
85
|
type CodexInjectionPlanOk,
|
|
86
|
+
readCodexProfileSource,
|
|
85
87
|
} from "./inject/plan";
|
|
86
88
|
|
|
87
89
|
export { effectiveLoopbackListenerPort, isLoopbackHostname, shouldInjectApiAuthHeader } from "./loopback-target";
|
|
@@ -378,9 +380,7 @@ async function injectCodexConfigImpl(
|
|
|
378
380
|
&& rootTomlString(nativeInput, REALTIME_WS_BASE_URL_KEY) === journaledRealtimeWsBaseUrl);
|
|
379
381
|
return !hasInjectedCodexRouting(nativeInput) && !looksInjectedByValue;
|
|
380
382
|
};
|
|
381
|
-
const readCurrentProfile =
|
|
382
|
-
? readFileSync(CODEX_PROFILE_PATH, "utf-8")
|
|
383
|
-
: null;
|
|
383
|
+
const readCurrentProfile = readCodexProfileSource;
|
|
384
384
|
const unverifiedJournalMessage = "Codex configuration was not written: the journal has no verified baseline for the current config/profile. Current files and the journal were preserved.";
|
|
385
385
|
// When the reconcile will rewrite config.toml under the lock, the baseline it
|
|
386
386
|
// must be journaled against does not exist yet — this check runs inside the
|
|
@@ -440,13 +440,15 @@ async function injectCodexConfigImpl(
|
|
|
440
440
|
message: "Codex config injection refused: config.toml changed while the write lock was being acquired. Retry to inject on the latest bytes.",
|
|
441
441
|
});
|
|
442
442
|
}
|
|
443
|
+
// The profile carries unmanaged root keys from the bytes the plan read; a profile edit since then would be overwritten.
|
|
444
|
+
if (readCurrentProfile() !== admittedPlan.profileSource) throw new CodexInjectRefusal({ success: false, retryable: true, message: "Codex config injection refused: opencodex.config.toml changed while the write lock was being acquired. Retry to inject on the latest bytes." });
|
|
443
445
|
if (missingConfig) publishCodexArtifact(CODEX_CONFIG_PATH, heldConfigWriteLock, (_path, hooks) => { hooks.validateBeforeRename?.(CODEX_CONFIG_PATH); createEmptyCodexConfigInBoundary(); hooks.afterRename?.(CODEX_CONFIG_PATH); });
|
|
444
446
|
let nativeInput = rawContent;
|
|
445
447
|
let plan = admittedPlan;
|
|
446
448
|
if (v1Reconcile) {
|
|
447
449
|
const reconciled = v1Reconcile.run(heldConfigWriteLock);
|
|
448
450
|
if (!reconciled.ok) {
|
|
449
|
-
throw new CodexInjectRefusal({ success: false, message: reconciled.message });
|
|
451
|
+
throw new CodexInjectRefusal({ success: false, message: reconciled.message, retryable: reconciled.retryable });
|
|
450
452
|
}
|
|
451
453
|
nativeInput = reconciled.content;
|
|
452
454
|
if (reconciled.content !== rawContent) {
|
|
@@ -490,6 +492,7 @@ async function injectCodexConfigImpl(
|
|
|
490
492
|
publishCodexArtifact(CODEX_CONFIG_PATH, heldConfigWriteLock, (path, hooks) => atomicWriteFile(path, plan.content, undefined, hooks));
|
|
491
493
|
historyArtifactStageForTests?.("after-config");
|
|
492
494
|
assertCodexHomeOwner(getCodexHome());
|
|
495
|
+
profilePublish.published = plan.profileContent;
|
|
493
496
|
publishCodexArtifact(CODEX_PROFILE_PATH, heldConfigWriteLock, (path, hooks) => atomicWriteFile(path, plan.profileContent, undefined, hooks));
|
|
494
497
|
publishCodexArtifact(JOURNAL_PATH, heldConfigWriteLock, (_path, hooks) => markJournalInjectedState(plan.content, plan.profileContent, {
|
|
495
498
|
// A root override is ours whenever we wrote one and no user-owned value won. That is
|
|
@@ -529,6 +532,7 @@ async function injectCodexConfigImpl(
|
|
|
529
532
|
* legacy-uncoordinated home, which publishes no transition to resolve.
|
|
530
533
|
*/
|
|
531
534
|
let transitionReceipt: { nativeGeneration: number; currentTxId: string } | undefined;
|
|
535
|
+
const profilePublish: CodexProfilePublish = {}; // rollback reverts only profile bytes this operation published
|
|
532
536
|
|
|
533
537
|
/*
|
|
534
538
|
* The file-level write lock every config.toml writer shares (see
|
|
@@ -548,6 +552,10 @@ async function injectCodexConfigImpl(
|
|
|
548
552
|
*/
|
|
549
553
|
let effectivePlan: CodexInjectionPlanOk = admittedPlan;
|
|
550
554
|
|
|
555
|
+
if (v1Reconcile && !await v1Reconcile.admit()) {
|
|
556
|
+
return { success: false, retryable: true, message: "Codex config injection refused: the CLI selection is busy. Retry after the CLI update finishes." };
|
|
557
|
+
}
|
|
558
|
+
try {
|
|
551
559
|
const configLock = await acquireConfigWriteLock(CODEX_CONFIG_PATH, {
|
|
552
560
|
timeoutMs: Math.min(options.lockTimeoutMs ?? CONFIG_WRITE_LOCK_WAIT_MS, CONFIG_WRITE_LOCK_WAIT_MS),
|
|
553
561
|
});
|
|
@@ -590,7 +598,7 @@ async function injectCodexConfigImpl(
|
|
|
590
598
|
effectivePlan = resolved.plan;
|
|
591
599
|
} catch (error) {
|
|
592
600
|
if (error instanceof ConfigWriteDestinationChanged || codexHomeOwnerBlocksCompensation(getCodexHome(), error)) throw error;
|
|
593
|
-
const restored = restoreCodexPreImages(preImages, heldConfigWriteLock);
|
|
601
|
+
const restored = restoreCodexPreImages(preImages, heldConfigWriteLock, profilePublish);
|
|
594
602
|
if (!restored.complete) throw new CodexPartialWriteError(restored.unrestored);
|
|
595
603
|
throw error;
|
|
596
604
|
}
|
|
@@ -610,7 +618,7 @@ async function injectCodexConfigImpl(
|
|
|
610
618
|
...(eligibility.kind === "adopt" ? { adoption: { direction: "apply" as const } } : {}),
|
|
611
619
|
onPostCallbackFailure: () => {
|
|
612
620
|
if (!coordinatedPreImages) throw new Error("Codex injection preimages were not captured.");
|
|
613
|
-
const restored = restoreCodexPreImages(coordinatedPreImages, heldConfigWriteLock);
|
|
621
|
+
const restored = restoreCodexPreImages(coordinatedPreImages, heldConfigWriteLock, profilePublish);
|
|
614
622
|
if (!restored.complete) throw new CodexPartialWriteError(restored.unrestored);
|
|
615
623
|
},
|
|
616
624
|
admitted: { authoritySnapshotId: witness.comparisonId },
|
|
@@ -687,7 +695,7 @@ async function injectCodexConfigImpl(
|
|
|
687
695
|
if (error instanceof ConfigWriteDestinationChanged || codexHomeOwnerBlocksCompensation(getCodexHome(), error)) throw error;
|
|
688
696
|
// Compensate, then ALWAYS throw. Returning a partial result would let the
|
|
689
697
|
// lock commit a row describing an apply that did not finish.
|
|
690
|
-
const restored = restoreCodexPreImages(preImages, heldConfigWriteLock);
|
|
698
|
+
const restored = restoreCodexPreImages(preImages, heldConfigWriteLock, profilePublish);
|
|
691
699
|
if (!restored.complete) {
|
|
692
700
|
throw new CodexPartialWriteError(restored.unrestored);
|
|
693
701
|
}
|
|
@@ -725,6 +733,9 @@ async function injectCodexConfigImpl(
|
|
|
725
733
|
releaseConfigWriteLock(configLock.handle);
|
|
726
734
|
heldConfigWriteLock = undefined;
|
|
727
735
|
}
|
|
736
|
+
} finally {
|
|
737
|
+
v1Reconcile?.release();
|
|
738
|
+
}
|
|
728
739
|
// Both write paths have committed, including the coordinator's post-callback checks.
|
|
729
740
|
// Compare against the admitted original, not post-v1-reconcile input: the native
|
|
730
741
|
// feature transition is part of this transaction too. Refusals/rollbacks return
|
package/src/codex/lineage.ts
CHANGED
|
@@ -31,12 +31,10 @@
|
|
|
31
31
|
* posture as the affinity key itself. Two callers presenting identical thread ids can never read
|
|
32
32
|
* each other's lineage, and no raw identifier or durable hash is stored.
|
|
33
33
|
*
|
|
34
|
-
* LIFETIME
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
* account ownership, and nothing here should be read as a promise to a conversation that outlives
|
|
39
|
-
* a restart.
|
|
34
|
+
* LIFETIME: lineage records and their keys remain process-local. The HMAC key is fresh random
|
|
35
|
+
* bytes taken at module load, so yesterday's keys cannot be reproduced after a restart. An
|
|
36
|
+
* affinity store may persist separate digests of cohort anchors under its own secret; it must
|
|
37
|
+
* never persist these process-local keys.
|
|
40
38
|
*
|
|
41
39
|
* The one upgrade that is neither a fresh start nor an untouched process is a code swap under a
|
|
42
40
|
* live conversation, where the binding map is still populated with entries made under the
|
|
@@ -50,6 +48,12 @@ import { retainedUtf8Bytes } from "../lib/admission";
|
|
|
50
48
|
|
|
51
49
|
const CODEX_LINEAGE_COMPONENT_MAX_BYTES = 512;
|
|
52
50
|
const CODEX_LINEAGE_KEY = randomBytes(32);
|
|
51
|
+
let conversationAnchorObserver: ((key: string, familyId: string, threadId: string) => void) | undefined;
|
|
52
|
+
|
|
53
|
+
/** Register the consumer of derived cohort anchors, or remove it. */
|
|
54
|
+
export function setCodexConversationAnchorObserver(fn?: (key: string, familyId: string, threadId: string) => void): void {
|
|
55
|
+
conversationAnchorObserver = fn;
|
|
56
|
+
}
|
|
53
57
|
|
|
54
58
|
/**
|
|
55
59
|
* Mirrors `CODEX_THREAD_AFFINITY_IDLE_TTL_MS` in ./routing. Deliberately duplicated rather than
|
|
@@ -149,12 +153,14 @@ function boundedLineageComponent(value: string | null): string | undefined {
|
|
|
149
153
|
* byte-identical to the key the thread actually binds under.
|
|
150
154
|
*/
|
|
151
155
|
export function codexConversationKeyFor(familyId: string, threadId: string): string {
|
|
152
|
-
|
|
156
|
+
const key = `app:${createHmac("sha256", CODEX_LINEAGE_KEY)
|
|
153
157
|
.update("opencodex-app-pool-affinity-v1\0")
|
|
154
158
|
.update(familyId)
|
|
155
159
|
.update("\0")
|
|
156
160
|
.update(threadId)
|
|
157
161
|
.digest("base64url")}`;
|
|
162
|
+
conversationAnchorObserver?.(key, familyId, threadId);
|
|
163
|
+
return key;
|
|
158
164
|
}
|
|
159
165
|
|
|
160
166
|
/**
|
package/src/codex/quota.ts
CHANGED
|
@@ -38,7 +38,7 @@ type QuotaDiskFile = {
|
|
|
38
38
|
|
|
39
39
|
type MainPolicyQuota = { identityKey: string; quota: StoredAccountQuota };
|
|
40
40
|
/** Fresh WHAM topology proof is consumed by the merge, never retained in a cache or DTO. */
|
|
41
|
-
type MainPolicyQuotaObservation = Omit<StoredAccountQuota, "updatedAt"> & { shortWindowAbsent?: true };
|
|
41
|
+
type MainPolicyQuotaObservation = Omit<StoredAccountQuota, "updatedAt"> & { shortWindowAbsent?: true; monthlyWindowAbsent?: true };
|
|
42
42
|
let mainPolicyQuota: MainPolicyQuota | null = null;
|
|
43
43
|
let diskHydrated = false;
|
|
44
44
|
let persistTimer: ReturnType<typeof setTimeout> | null = null;
|
|
@@ -343,9 +343,12 @@ export function setAccountQuotaFromParsed(
|
|
|
343
343
|
// Retiring a short tuple releases a routing block, so it needs the same writer proof as
|
|
344
344
|
// history: a live main writer for main, a live captured pool writer for pool requests.
|
|
345
345
|
const mayRetireShort = isMain ? mainWriter !== undefined : livePoolEvidence;
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
346
|
+
// Monthly-window absence (#8067) comes from the same complete topology and needs the same proof.
|
|
347
|
+
const displayQuota: MainPolicyQuotaObservation = {
|
|
348
|
+
...quota,
|
|
349
|
+
...(mayRetireShort && policyQuota?.shortWindowAbsent === true ? { shortWindowAbsent: true as const } : {}),
|
|
350
|
+
...(mayRetireShort && policyQuota?.monthlyWindowAbsent === true ? { monthlyWindowAbsent: true as const } : {}),
|
|
351
|
+
};
|
|
349
352
|
const next = mergeAccountQuota(displayQuota, legacyExisting, updatedAt);
|
|
350
353
|
accountQuota.set(accountId, next);
|
|
351
354
|
if (isMain) {
|
|
@@ -448,8 +451,11 @@ function mergeAccountQuota(
|
|
|
448
451
|
// while silently dropping `monthlyIsPrimaryWindow` would look like tertiary-only data to
|
|
449
452
|
// any future reader, and that failure would be invisible.
|
|
450
453
|
if (quota.monthlyIsPrimaryWindow === true) next.monthlyIsPrimaryWindow = true;
|
|
451
|
-
} else if (
|
|
454
|
+
} else if (quota.monthlyWindowAbsent !== true
|
|
455
|
+
&& (snapshotHasWeekly(quota) || snapshotHasShort(quota) || snapshotHasCustom(quota))
|
|
452
456
|
&& existing?.monthlyPercent !== undefined) {
|
|
457
|
+
// A complete topology with no monthly-length window retires the carried tuple, so a plan
|
|
458
|
+
// change away from a monthly primary (Free to Pro Lite) cannot keep its old exhausted reading.
|
|
453
459
|
next.monthlyPercent = existing.monthlyPercent;
|
|
454
460
|
if (existing.monthlyResetAt !== undefined) next.monthlyResetAt = existing.monthlyResetAt;
|
|
455
461
|
if (existing.monthlyIsPrimaryWindow === true) next.monthlyIsPrimaryWindow = true;
|
|
@@ -991,7 +997,17 @@ export function poolWhamPolicyObservation(
|
|
|
991
997
|
}
|
|
992
998
|
const malformed = readings.some(window => window?.used_percent != null
|
|
993
999
|
&& normalizeUsagePercent(window.used_percent) === undefined);
|
|
994
|
-
|
|
1000
|
+
if (data.rate_limit?.allowed === false || malformed) return quota;
|
|
1001
|
+
const observation = withWhamShortWindowAbsence(data, quota);
|
|
1002
|
+
// #8067: the same complete topology proves a pool account has no monthly window when no window
|
|
1003
|
+
// declares a monthly duration and no tertiary window is present, so a plan change away from a
|
|
1004
|
+
// monthly primary (Free to Pro Lite) retires the carried tuple. Pool-only: main observations
|
|
1005
|
+
// keep their existing retention rules.
|
|
1006
|
+
const [primary, secondary, tertiary] = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window];
|
|
1007
|
+
return observation.shortWindowAbsent === true
|
|
1008
|
+
&& !isExplicitMonthlyWindow(primary) && !isExplicitMonthlyWindow(secondary) && tertiary == null
|
|
1009
|
+
? { ...observation, monthlyWindowAbsent: true }
|
|
1010
|
+
: observation;
|
|
995
1011
|
}
|
|
996
1012
|
|
|
997
1013
|
function isMeasuredLongWindow(window: WhamUsageWindow | null | undefined): boolean {
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The namespace of caller-owned affinity keys, kept in a module with no imports so that stores
|
|
3
|
+
* which must refuse these keys (the durable Codex pool affinity store) can test for them without
|
|
4
|
+
* importing the routing modules that request-owned affinity itself depends on.
|
|
5
|
+
*/
|
|
6
|
+
export const REQUEST_OWNED_AFFINITY_KEY_PREFIX = "request-owned:v1:";
|
|
7
|
+
|
|
8
|
+
/** Identify namespace keys that must remain process-local. */
|
|
9
|
+
export function isRequestOwnedAffinityKey(value: string): boolean {
|
|
10
|
+
return value.startsWith(REQUEST_OWNED_AFFINITY_KEY_PREFIX);
|
|
11
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Caller-owned affinity is scoped to the exact Authorization value and conversation key under a
|
|
3
|
+
* process-random HMAC key. It is process-local and must never be anchored or persisted, as required
|
|
4
|
+
* by the structure contract. Decisions describe the binding at selection time.
|
|
5
|
+
*/
|
|
6
|
+
import { createHmac, randomBytes } from "node:crypto";
|
|
7
|
+
import { MAIN_CODEX_ACCOUNT_ID } from "./account-id";
|
|
8
|
+
import { codexConversationIdentity } from "./lineage";
|
|
9
|
+
import { getThreadAffinity, getModelDetourAffinity, deleteThreadAffinity, deleteModelDetourAffinity, notePendingReleaseReason, type CodexAffinityDecision, type CodexAffinityReason, type ThreadAffinityEntry } from "./routing/thread-affinity";
|
|
10
|
+
import type { CodexQuotaScope } from "./routing/health-store";
|
|
11
|
+
import { classifyCodexUpstreamOutcome } from "./routing/cooldown-math";
|
|
12
|
+
import type { CodexAuthContext } from "./auth-context";
|
|
13
|
+
import { isRequestOwnedAffinityKey, REQUEST_OWNED_AFFINITY_KEY_PREFIX } from "./request-owned-affinity-key";
|
|
14
|
+
export { isRequestOwnedAffinityKey } from "./request-owned-affinity-key";
|
|
15
|
+
|
|
16
|
+
const key = randomBytes(32);
|
|
17
|
+
const prefix = REQUEST_OWNED_AFFINITY_KEY_PREFIX;
|
|
18
|
+
|
|
19
|
+
/** Derive the opaque key for this caller and conversation, if both exist. */
|
|
20
|
+
export function requestOwnedAffinityKey(headers: Headers): string | undefined {
|
|
21
|
+
const authorization = headers.get("authorization");
|
|
22
|
+
const conversation = codexConversationIdentity(headers)?.conversationKey;
|
|
23
|
+
if (!authorization || !conversation) return undefined;
|
|
24
|
+
return prefix + createHmac("sha256", key)
|
|
25
|
+
.update("opencodex-request-owned-affinity-v1\0").update(authorization).update("\0").update(conversation)
|
|
26
|
+
.digest("base64url");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Report a bind only when the selection-time entry names the selected account. */
|
|
30
|
+
export function honestAffinityDecision(
|
|
31
|
+
decision: CodexAffinityDecision | undefined,
|
|
32
|
+
affinityKey: string | undefined,
|
|
33
|
+
accountId: string,
|
|
34
|
+
quotaScope?: CodexQuotaScope,
|
|
35
|
+
modelId?: string,
|
|
36
|
+
requestOwnedKeyWithheld = false,
|
|
37
|
+
): CodexAffinityDecision | undefined {
|
|
38
|
+
if (!decision || (decision.move !== "new_bind" && decision.move !== "rebound")) return decision;
|
|
39
|
+
// This is a selection-time snapshot, immediately after the synchronous selector returns.
|
|
40
|
+
if (affinityKey && (getThreadAffinity(affinityKey, quotaScope)?.accountId === accountId
|
|
41
|
+
|| getModelDetourAffinity(affinityKey, modelId, quotaScope)?.accountId === accountId)) return decision;
|
|
42
|
+
if (decision.move === "rebound") return { move: "cleared", reason: decision.reason };
|
|
43
|
+
return { move: "unbound", reason: affinityKey ? decision.reason : requestOwnedKeyWithheld ? "request_owned" : "no_conversation" };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Identify the issuer for a Pool or keyed caller-main context. */
|
|
47
|
+
export function conversationStateAccountId(ctx: { kind: "main" | "pool" | "main-pool"; accountId: string | null; affinityKey?: string; conversationStateKey?: string }): string | undefined {
|
|
48
|
+
return ctx.kind === "main" ? (ctx.affinityKey || ctx.conversationStateKey ? MAIN_CODEX_ACCOUNT_ID : undefined) : ctx.accountId ?? undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Describe the account actually serving a caller-owned fallback. */
|
|
52
|
+
export function callerOwnedFallbackAffinityDecision(
|
|
53
|
+
decision: CodexAffinityDecision | undefined, affinityKey: string | undefined, quotaScope: CodexQuotaScope | undefined,
|
|
54
|
+
modelId: string | undefined, requestOwnedKeyWithheld: boolean, reason: "cooldown" | "unusable",
|
|
55
|
+
): CodexAffinityDecision {
|
|
56
|
+
const ordinary = affinityKey ? getThreadAffinity(affinityKey, quotaScope) : undefined;
|
|
57
|
+
const detour = affinityKey ? getModelDetourAffinity(affinityKey, modelId, quotaScope) : undefined;
|
|
58
|
+
if (ordinary?.accountId === MAIN_CODEX_ACCOUNT_ID || detour?.accountId === MAIN_CODEX_ACCOUNT_ID)
|
|
59
|
+
return honestAffinityDecision(decision ?? { move: "reused", reason: "healthy" }, affinityKey, MAIN_CODEX_ACCOUNT_ID, quotaScope, modelId, requestOwnedKeyWithheld)!;
|
|
60
|
+
if (ordinary || detour) return { move: "detour", reason };
|
|
61
|
+
return { move: "unbound", reason: affinityKey ? decision?.reason ?? "healthy" : requestOwnedKeyWithheld ? "request_owned" : "no_conversation" };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Opaque process-local identity for the bindings present when main was selected. */
|
|
65
|
+
export type RequestOwnedBindingSnapshot = object;
|
|
66
|
+
type EntryIdentity = { entry: ThreadAffinityEntry; accountId: string; generation: number; createdAt: number };
|
|
67
|
+
const bindingSnapshots = new WeakMap<RequestOwnedBindingSnapshot, { key: string; scope?: CodexQuotaScope; modelId?: string; ordinary?: EntryIdentity; detour?: EntryIdentity }>();
|
|
68
|
+
|
|
69
|
+
function identity(entry: ThreadAffinityEntry | undefined): EntryIdentity | undefined {
|
|
70
|
+
return entry && { entry, accountId: entry.accountId, generation: entry.generation, createdAt: entry.createdAt };
|
|
71
|
+
}
|
|
72
|
+
function matches(captured: EntryIdentity | undefined, current: ThreadAffinityEntry | undefined): boolean {
|
|
73
|
+
return !!captured && captured.entry === current && captured.accountId === current.accountId
|
|
74
|
+
&& captured.generation === current.generation && captured.createdAt === current.createdAt;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Capture the exact entries that a request is authorized to release after selection. */
|
|
78
|
+
export function captureRequestOwnedAffinityBindings(key: string | undefined, scope?: CodexQuotaScope, modelId?: string): RequestOwnedBindingSnapshot | undefined {
|
|
79
|
+
if (!key || !isRequestOwnedAffinityKey(key)) return undefined;
|
|
80
|
+
const snapshot = {};
|
|
81
|
+
bindingSnapshots.set(snapshot, { key, scope, modelId, ordinary: identity(getThreadAffinity(key, scope)), detour: identity(getModelDetourAffinity(key, modelId, scope)) });
|
|
82
|
+
return snapshot;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Whether a context carries a caller-owned routing key. */
|
|
86
|
+
export function isKeyedRequestOwnedMain(ctx: CodexAuthContext): ctx is Extract<CodexAuthContext, { kind: "main" }> & { affinityKey: string } {
|
|
87
|
+
return ctx.kind === "main" && !!ctx.affinityKey && isRequestOwnedAffinityKey(ctx.affinityKey);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Release this caller’s scoped binding after its own main credential is refused. */
|
|
91
|
+
export function releaseRequestOwnedMainOnOutcome(ctx: CodexAuthContext, outcome: number, _modelId?: string): void {
|
|
92
|
+
if (!isKeyedRequestOwnedMain(ctx) || !ctx.affinityBindingSnapshot) return;
|
|
93
|
+
const snapshot = bindingSnapshots.get(ctx.affinityBindingSnapshot);
|
|
94
|
+
if (!snapshot || snapshot.key !== ctx.affinityKey) return;
|
|
95
|
+
const outcomeClass = classifyCodexUpstreamOutcome(outcome);
|
|
96
|
+
const reason: CodexAffinityReason | undefined = outcomeClass === "quota" ? "quota_refusal"
|
|
97
|
+
: outcomeClass === "credential" ? "unusable" : outcomeClass === "transient" ? "transient" : undefined;
|
|
98
|
+
if (!reason) return;
|
|
99
|
+
const key = ctx.affinityKey;
|
|
100
|
+
const { scope, modelId: selectedModelId } = snapshot;
|
|
101
|
+
let released = false;
|
|
102
|
+
const ordinary = getThreadAffinity(key, scope);
|
|
103
|
+
const detour = getModelDetourAffinity(key, selectedModelId, scope);
|
|
104
|
+
const mainDetour = matches(snapshot.detour, detour) && detour?.accountId === MAIN_CODEX_ACCOUNT_ID;
|
|
105
|
+
// A caller-main fallback or model detour can leave an ordinary binding on a different
|
|
106
|
+
// account. Retire it too so the next placement reports the release rather than reuse. If
|
|
107
|
+
// main was itself bound and another turn has since rebound elsewhere, keep that newer entry.
|
|
108
|
+
const callerMainDetour = ctx.affinityDecision?.move === "detour";
|
|
109
|
+
if (matches(snapshot.ordinary, ordinary) && (ordinary?.accountId === MAIN_CODEX_ACCOUNT_ID || mainDetour || callerMainDetour)) {
|
|
110
|
+
deleteThreadAffinity(key, scope);
|
|
111
|
+
released = true;
|
|
112
|
+
}
|
|
113
|
+
if (mainDetour) {
|
|
114
|
+
deleteModelDetourAffinity(key, selectedModelId, scope);
|
|
115
|
+
released = true;
|
|
116
|
+
}
|
|
117
|
+
if (released) notePendingReleaseReason(key, reason);
|
|
118
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import type { CodexAuthPolicyConfig } from "./auth-context";
|
|
2
|
+
import type { OcxConfig } from "../types";
|
|
3
|
+
import type { CodexQuotaScope } from "./routing";
|
|
4
|
+
import { MAIN_CODEX_ACCOUNT_ID } from "./account-id";
|
|
5
|
+
import { computeCodexUsageScore, getCodexQuotaHealthSnapshot, isEffectiveCodexAccountPinned } from "./routing";
|
|
6
|
+
import { getEffectiveCodexAutoSwitchThreshold } from "./account-auto-switch";
|
|
7
|
+
import { codexAccountUsesCreditsAfterLimit, codexUsageLimitResetAt } from "./account-credit-use";
|
|
8
|
+
import { CODEX_UNKNOWN_USAGE_SCORE, getAccountQuota, getMainPolicyQuota } from "./quota";
|
|
9
|
+
import { hasSpendableCodexCredits } from "./quota-types";
|
|
10
|
+
import { isMainAccountHardLocked } from "./main-account-hard-lock";
|
|
11
|
+
import { authorizationCredential } from "../lib/authorization-scheme";
|
|
12
|
+
import { extractAccountId } from "../oauth/chatgpt";
|
|
13
|
+
import { matchesMainQuotaCredential } from "./main-account-cache";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* A request-owned bearer cannot inspect the physical main credential for its plan, but cached
|
|
17
|
+
* WHAM usage is still valid routing evidence for the same logical main account. Score it with
|
|
18
|
+
* the conservative unknown-plan rule: an unobserved governing window preserves the pin, while
|
|
19
|
+
* any known weekly/monthly/short value at the threshold releases it through the ordinary Pool
|
|
20
|
+
* path. This keeps the keyring boundary intact instead of reading auth.json just to classify a
|
|
21
|
+
* request that already brought its own credential (#3157).
|
|
22
|
+
*/
|
|
23
|
+
function requestOwnedMainPinHasQuotaHeadroom(config: OcxConfig): boolean {
|
|
24
|
+
const threshold = getEffectiveCodexAutoSwitchThreshold(config, MAIN_CODEX_ACCOUNT_ID);
|
|
25
|
+
if (threshold <= 0) return true;
|
|
26
|
+
const usage = computeCodexUsageScore(getAccountQuota(MAIN_CODEX_ACCOUNT_ID), undefined, Date.now(), codexAccountUsesCreditsAfterLimit(config, MAIN_CODEX_ACCOUNT_ID));
|
|
27
|
+
return usage >= CODEX_UNKNOWN_USAGE_SCORE || usage < threshold;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Whether a request carrying its OWN main credential still serves on main because the operator
|
|
32
|
+
* manually pinned it (#3166), split from the surrounding resolution so request preview can ask
|
|
33
|
+
* the identical question (#4850).
|
|
34
|
+
*
|
|
35
|
+
* Exported for exactly one reason: two copies of this fence is how #4850 happened. Final
|
|
36
|
+
* authentication honoured the ownership boundary while request preview, computing its fence from
|
|
37
|
+
* recovery and drain state alone, still handed pool eligibility the default liveness probe and
|
|
38
|
+
* opened the physical `auth.json` twice per spawn. A predicate one caller can forget is a
|
|
39
|
+
* predicate the other caller will eventually disagree with.
|
|
40
|
+
*
|
|
41
|
+
* Read-free by construction, which is what makes it usable on the fenced side. Every input is
|
|
42
|
+
* config, policy, or in-memory runtime state: the pin fields, the paused list, the cached quota
|
|
43
|
+
* score, the main policy quota the hard lock and the credits switch read, and `callerMatchesObservedMain`, which compares HMAC digests against the observed
|
|
44
|
+
* credential record in `main-account-cache.ts`. Nothing here opens a file.
|
|
45
|
+
*
|
|
46
|
+
* `candidate` is the pin before the hard-lock question, because the caller still owes the
|
|
47
|
+
* pending-binding check that only final authentication can fail closed on.
|
|
48
|
+
*/
|
|
49
|
+
export function requestOwnedMainPinState(
|
|
50
|
+
headers: Headers,
|
|
51
|
+
config: OcxConfig,
|
|
52
|
+
policy: CodexAuthPolicyConfig,
|
|
53
|
+
requestScopedMainCredential: boolean,
|
|
54
|
+
fixedAccountId: string | undefined,
|
|
55
|
+
quotaScope?: CodexQuotaScope,
|
|
56
|
+
): { candidate: boolean; preserve: boolean } {
|
|
57
|
+
const candidate = requestScopedMainCredential
|
|
58
|
+
&& fixedAccountId === undefined
|
|
59
|
+
&& config.activeCodexAccountPinned === MAIN_CODEX_ACCOUNT_ID
|
|
60
|
+
&& isEffectiveCodexAccountPinned(config)
|
|
61
|
+
&& !policy.pausedCodexAccountIds?.includes(MAIN_CODEX_ACCOUNT_ID)
|
|
62
|
+
&& requestOwnedMainPinHasQuotaHeadroom(config);
|
|
63
|
+
return {
|
|
64
|
+
candidate,
|
|
65
|
+
preserve: candidate && !(callerMatchesObservedMain(headers)
|
|
66
|
+
&& (isMainAccountHardLocked(policy)
|
|
67
|
+
|| mainCreditsHoldResetAt(policy) !== undefined
|
|
68
|
+
|| getCodexQuotaHealthSnapshot(MAIN_CODEX_ACCOUNT_ID, quotaScope)?.cooldownUntil)),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function mainCreditsHoldResetAt(config: Pick<OcxConfig, "creditCodexAccountIds">): number | undefined {
|
|
73
|
+
if (codexAccountUsesCreditsAfterLimit(config, MAIN_CODEX_ACCOUNT_ID)
|
|
74
|
+
&& hasSpendableCodexCredits(getMainPolicyQuota())) return undefined;
|
|
75
|
+
return codexUsageLimitResetAt(getMainPolicyQuota(), undefined, Date.now());
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
/** No auth-file I/O: an unsigned claim alone never identifies a caller as stored main. */
|
|
80
|
+
export function callerMatchesObservedMain(headers: Headers): boolean {
|
|
81
|
+
const bearer = authorizationCredential(headers);
|
|
82
|
+
if (!bearer) return false;
|
|
83
|
+
const effectiveAccountId = headers.get("chatgpt-account-id")
|
|
84
|
+
?? extractAccountId(undefined, bearer);
|
|
85
|
+
return matchesMainQuotaCredential(bearer, effectiveAccountId);
|
|
86
|
+
}
|