@bitkyc08/opencodex 2.100.3 → 2.100.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS_INSTALL.md +23 -1
- package/bin/ocx.mjs +8 -1
- package/gui/dist/assets/{App-Dnb6VMsP.js → App-DcpyI78f.js} +20 -19
- package/gui/dist/assets/{Tray-BV4ms9U9.js → Tray-CzjPJprT.js} +1 -1
- package/gui/dist/assets/brand-mark-BTIi7e69.js +1 -0
- package/gui/dist/assets/index-DJxM-imn.css +2 -0
- package/gui/dist/assets/index-DVgU6S3y.js +138 -0
- package/gui/dist/assets/{segment-thumb-features-DXSidY6D.js → segment-thumb-features-Bn6Y-g3R.js} +1 -1
- package/gui/dist/classic/assets/{App-DA-scMPq.js → App-eYJAyNHM.js} +19 -18
- package/gui/dist/classic/assets/{Tray-BrHaVRAq.js → Tray-xHMYxLkV.js} +1 -1
- package/gui/dist/classic/assets/index-DSaVRW4F.js +138 -0
- package/gui/dist/classic/assets/quota-summary-DyzHlkFl.js +1 -0
- package/gui/dist/classic/index.html +1 -1
- package/gui/dist/index.html +2 -2
- package/native/ocx-child/src/cli.rs +5 -3
- package/native/ocx-child/src/codex_home.rs +1 -0
- package/package.json +2 -2
- package/src/adapters/anthropic/per-message-effort.ts +296 -0
- package/src/adapters/anthropic.ts +3 -0
- package/src/adapters/claude-cli/adapter.ts +1 -0
- package/src/adapters/devin/cloud-direct/chat.ts +71 -14
- package/src/adapters/google-errors.ts +14 -2
- package/src/adapters/qoder/adapter.ts +9 -1
- package/src/adapters/zed.ts +4 -2
- package/src/claude/desktop-remote-store.ts +60 -10
- package/src/cli/account-api.ts +4 -0
- package/src/cli/account-auth.ts +30 -2
- package/src/cli/account-extended.ts +33 -2
- package/src/cli/capabilities-access-remote.ts +3 -3
- package/src/cli/capabilities-accounts.ts +3 -3
- package/src/cli/capabilities-base.ts +11 -6
- package/src/cli/capabilities-observe-system.ts +2 -2
- package/src/cli/claude.ts +3 -3
- package/src/cli/disconnect-runtime.ts +16 -6
- package/src/cli/dispatch.ts +7 -1
- package/src/cli/index.ts +2 -2
- package/src/cli/link-apply-restart.ts +4 -2
- package/src/cli/link-routes.ts +4 -1
- package/src/cli/link.ts +5 -4
- package/src/cli/preflight-exemptions.ts +3 -0
- package/src/cli/registry.ts +5 -2
- package/src/cli/resolve.ts +23 -8
- package/src/cli/restart-failure.ts +11 -1
- package/src/cli/runtime-api.ts +4 -0
- package/src/cli/status.ts +4 -1
- package/src/cli/system-command.ts +1 -1
- package/src/cli/system-restart-client.ts +9 -3
- package/src/cli/system-settings-parity.ts +2 -1
- package/src/client/connect.ts +63 -9
- package/src/client/desktop-refusal.ts +38 -0
- package/src/client/lifecycle-lock.ts +29 -4
- package/src/client/runtime-restart.ts +27 -15
- package/src/client/runtime.ts +4 -2
- package/src/client/state.ts +14 -0
- package/src/codex/account-pause.ts +4 -0
- package/src/codex/account-runtime-state.ts +4 -0
- package/src/codex/auth-api/main-account-probe.ts +3 -1
- package/src/codex/auth-api/main-hard-lock-refusal-read.ts +172 -0
- package/src/codex/auth-context.ts +40 -2
- package/src/codex/catalog/build-entries.ts +10 -0
- package/src/codex/catalog/derive-entry.ts +7 -0
- package/src/codex/catalog/reserve-warn.ts +7 -5
- package/src/codex/catalog/reserve.ts +4 -3
- package/src/codex/catalog/retained-sync.ts +2 -0
- package/src/codex/catalog/routed-defaults.ts +35 -0
- package/src/codex/convergence.ts +2 -0
- package/src/codex/loopback-target.ts +22 -8
- package/src/codex/main-account.ts +88 -29
- package/src/codex/native-main-auth-file.ts +14 -0
- package/src/codex/native-main-credentials.ts +270 -0
- package/src/codex/native-main-owner.ts +3 -0
- package/src/codex/native-main-refresh-mode.ts +14 -1
- package/src/codex/quota.ts +63 -14
- package/src/combos/failover.ts +12 -1
- package/src/combos/index.ts +5 -0
- package/src/combos/resolve.ts +115 -19
- package/src/config/diagnostics.ts +3 -0
- package/src/config/live-reconcile.ts +6 -3
- package/src/config/load-degrade.ts +2 -0
- package/src/config/persisted-mutation.ts +2 -2
- package/src/config/persisted-projections.ts +18 -0
- package/src/config/process-state.ts +4 -3
- package/src/config/reserve-capability.ts +96 -0
- package/src/config/schema/config-schema.ts +6 -0
- package/src/config/schema/leaf-validators.ts +2 -0
- package/src/config/schema/routed-catalog-defaults.ts +49 -0
- package/src/config.ts +7 -7
- package/src/desktop-update/acquire.ts +202 -0
- package/src/desktop-update/cli.ts +168 -0
- package/src/desktop-update/drain.ts +40 -0
- package/src/desktop-update/headless.ts +285 -0
- package/src/desktop-update/image.ts +85 -0
- package/src/desktop-update/install.ts +53 -0
- package/src/desktop-update/msi.ts +72 -0
- package/src/desktop-update/release.ts +128 -0
- package/src/desktop-update/runtime.ts +155 -0
- package/src/desktop-update/staging.ts +118 -0
- package/src/desktop-update/trust.ts +45 -0
- package/src/generated/compatibility-version.json +246 -130
- package/src/images/fulfill-video.ts +3 -3
- package/src/images/loop.ts +6 -2
- package/src/images/plan.ts +147 -11
- package/src/images/types.ts +13 -4
- package/src/images/xai-video-client.ts +72 -10
- package/src/lib/gcp-adc.ts +48 -4
- package/src/lib/offline-resend.ts +150 -0
- package/src/lib/paced-stream.ts +3 -3
- package/src/lib/provider-outbound.ts +17 -6
- package/src/lib/request-failure-model.ts +2 -0
- package/src/lib/response-body-inactivity.ts +23 -1
- package/src/lib/upstream-retry.ts +38 -5
- package/src/link/explicit-route.ts +4 -4
- package/src/link/remote-windows.ts +79 -31
- package/src/link/residual-recovery.ts +20 -8
- package/src/messaging/budget.ts +23 -5
- package/src/messaging/rpc.ts +4 -4
- package/src/oauth/antigravity-risk.ts +126 -0
- package/src/oauth/generic-account-failover.ts +89 -18
- package/src/oauth/generic-session-affinity.ts +10 -3
- package/src/oauth/login-cli.ts +35 -1
- package/src/oauth/pool-kernel.ts +3 -3
- package/src/providers/anthropic-billing-refusal.ts +27 -3
- package/src/providers/google-vertex-model-discovery.ts +6 -1
- package/src/providers/model-rename-fields.ts +2 -0
- package/src/providers/quota/workbuddy.ts +6 -2
- package/src/providers/workbuddy-credit-balance.ts +125 -16
- package/src/responses/effort-history.ts +732 -0
- package/src/routing/history/integrity.ts +41 -4
- package/src/server/auth-cors.ts +13 -3
- package/src/server/codex-model-list.ts +2 -1
- package/src/server/direct-local-http.ts +26 -3
- package/src/server/index/link-listener.ts +20 -14
- package/src/server/index/serve-options.ts +1 -0
- package/src/server/index.ts +3 -2
- package/src/server/link-turn.ts +17 -5
- package/src/server/management/config-routes.ts +39 -3
- package/src/server/management/link-child-preflight.ts +1 -1
- package/src/server/management/link-route-edit.ts +20 -1
- package/src/server/management/oauth-account-routes.ts +22 -5
- package/src/server/management/provider-overwrite-carry.ts +3 -0
- package/src/server/management/provider-routes.ts +4 -4
- package/src/server/management/static-catalog-probe.ts +33 -0
- package/src/server/proxy-liveness.ts +54 -9
- package/src/server/relay.ts +6 -1
- package/src/server/request-log-conversation.ts +2 -2
- package/src/server/request-log.ts +5 -1
- package/src/server/reserve-capability-startup.ts +32 -0
- package/src/server/responses/adapter-delivery.ts +2 -0
- package/src/server/responses/adapter-dispatch.ts +31 -10
- package/src/server/responses/antigravity-fault-rotation.ts +24 -0
- package/src/server/responses/antigravity-validation-refusal.ts +43 -6
- package/src/server/responses/combo-selection-keepalive.ts +254 -0
- package/src/server/responses/core-combo.ts +24 -9
- package/src/server/responses/core-errors.ts +9 -6
- package/src/server/responses/core-options.ts +8 -0
- package/src/server/responses/core.ts +21 -0
- package/src/server/responses/estimated-usage.ts +115 -0
- package/src/server/responses/jev-model-invoke.ts +7 -2
- package/src/server/responses/passthrough-completion.ts +6 -3
- package/src/server/responses/passthrough-delivery.ts +47 -8
- package/src/server/responses/passthrough-dispatch.ts +3 -0
- package/src/server/responses/request-prepare.ts +9 -5
- package/src/server/responses/sidecar-execution.ts +5 -0
- package/src/service/desktop-supervision.d.mts +2 -0
- package/src/service/desktop-supervision.mjs +5 -0
- package/src/stall-timeout.ts +11 -0
- package/src/types/config.ts +15 -92
- package/src/types/provider.ts +13 -0
- package/src/types/request.ts +19 -0
- package/src/types/routed-catalog-defaults.ts +17 -0
- package/src/types/routing-profile.ts +90 -0
- package/src/types.ts +1 -0
- package/src/update/index.ts +1 -1
- package/src/usage/log.ts +14 -4
- package/src/usage/telemetry-contract.ts +1 -0
- package/src/web-search/passthrough-bridge.ts +7 -0
- package/gui/dist/assets/brand-mark-XOLJbomA.js +0 -1
- package/gui/dist/assets/index-DCdXsMyZ.js +0 -105
- package/gui/dist/assets/index-DQtCRNAw.css +0 -2
- package/gui/dist/classic/assets/index-BqOaGLf5.js +0 -105
- package/gui/dist/classic/assets/quota-summary-Dy5_wfTT.js +0 -1
package/src/client/connect.ts
CHANGED
|
@@ -13,15 +13,16 @@ import { getConfigDir, withConfigDirHardeningSettled } from "../config/paths";
|
|
|
13
13
|
import { claudeDesktopIntegrationEnabledNow } from "../codex/desired-state";
|
|
14
14
|
import { siblingOfLivePort, siblingSkipMessage } from "../codex/sibling-start";
|
|
15
15
|
import {
|
|
16
|
-
inspectRemoteDesktopStore, readDesktopDisconnectReceipt, writeDesktopDisconnectReceipt,
|
|
16
|
+
inspectRemoteDesktopStore, readDesktopDisconnectReceipt, writeDesktopDisconnectReceipt, removeDesktopDisconnectReceipt,
|
|
17
17
|
replaceRemoteDesktopCredential, restoreRemoteDesktopStore, finishRemoteDesktopCleanup,
|
|
18
18
|
type DesktopDisconnectReceipt, type DesktopRemoteOwner, type DesktopStoreResult,
|
|
19
19
|
} from "../claude/desktop-remote-store";
|
|
20
20
|
import {
|
|
21
|
-
withClientLifecycle, withClientLifecycleSync,
|
|
21
|
+
withClientDisconnectAttempt, withClientLifecycle, withClientLifecycleSync,
|
|
22
22
|
type ClientLifecycleHeld, type ClientLifecycleLockDeps,
|
|
23
23
|
} from "./lifecycle-lock";
|
|
24
24
|
import { invalidateCodexModelsCache, invalidateCodexModelsCacheWithPermit } from "../codex/catalog/sync";
|
|
25
|
+
import { desktopLifecycleRefusal } from "./desktop-refusal";
|
|
25
26
|
import { withCatalogWriteSerialization } from "../codex/catalog-write-serialization";
|
|
26
27
|
import {
|
|
27
28
|
injectCodexConfig,
|
|
@@ -1265,6 +1266,47 @@ function restoreConnectedCodex(connection: OcxClientConnectionConfig, receipt: D
|
|
|
1265
1266
|
}
|
|
1266
1267
|
}
|
|
1267
1268
|
|
|
1269
|
+
/**
|
|
1270
|
+
* Abort a disconnect that failed before its commit point.
|
|
1271
|
+
*
|
|
1272
|
+
* Until `desktop_restored` the receipt records intent only, so removing it returns the Child to a plain
|
|
1273
|
+
* connected state; left in place it made every client start refuse with client_disconnect_pending
|
|
1274
|
+
* until someone moved the folder aside by hand. A receipt this attempt wrote is removed outright:
|
|
1275
|
+
* D excludes other disconnects and every Desktop writer refuses while it exists. A receipt an
|
|
1276
|
+
* earlier run left (including one stuck by an older release) is removed only while the Desktop
|
|
1277
|
+
* store shows no restore has started; that run may have stopped inside the Desktop restore before
|
|
1278
|
+
* it could record desktop_restored, and then the receipt is the gate a retry needs.
|
|
1279
|
+
*
|
|
1280
|
+
* On a link Child the route-intent drain runs before the Codex restore, so by then the file
|
|
1281
|
+
* integrations the link routed may already be off. That is not undone here: the connection stays,
|
|
1282
|
+
* and the runtime's next route-intent apply turns them back on, as it does after any Home change.
|
|
1283
|
+
*/
|
|
1284
|
+
function abortPreparedDisconnect(
|
|
1285
|
+
prepared: { receipt: DesktopDisconnectReceipt; created: boolean; connection: OcxClientConnectionConfig | null },
|
|
1286
|
+
error: unknown,
|
|
1287
|
+
deps: Pick<ClientConnectDeps, "lifecycleLockDeps">,
|
|
1288
|
+
): Error {
|
|
1289
|
+
const base = error instanceof Error ? error.message : String(error);
|
|
1290
|
+
let outcome: "removed" | "desktop_started";
|
|
1291
|
+
try {
|
|
1292
|
+
outcome = withClientLifecycleSync(held => withConfigMutationLockSync(() => {
|
|
1293
|
+
if (!prepared.created && !UNTOUCHED_DESKTOP.has(inspectRemoteDesktopStore(prepared.receipt.owner).kind)) return "desktop_started" as const;
|
|
1294
|
+
removeDesktopDisconnectReceipt(held, prepared.receipt);
|
|
1295
|
+
return "removed" as const;
|
|
1296
|
+
}), deps.lifecycleLockDeps);
|
|
1297
|
+
} catch {
|
|
1298
|
+
return new Error(`${base}. The disconnect receipt could not be rolled back; run ocx disconnect again to finish it or roll it back.`, { cause: error });
|
|
1299
|
+
}
|
|
1300
|
+
const drained = prepared.connection?.transport === "link"
|
|
1301
|
+
? " File integrations this link routed may already be off; the runtime's next route-intent apply turns them back on." : "";
|
|
1302
|
+
return new Error(outcome === "removed"
|
|
1303
|
+
? `${base}. The disconnect was rolled back: this Child is still connected and its runtime can start.${drained}`
|
|
1304
|
+
: `${base}. A Claude Desktop restore had already started under this disconnect, so its receipt was kept; once the cause above is fixed, run ocx disconnect again to finish it.`, { cause: error });
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
/** Desktop store states an interrupted disconnect cannot have produced: no restore has begun. */
|
|
1308
|
+
const UNTOUCHED_DESKTOP: ReadonlySet<string> = new Set(["absent", "active", "legacy_current_connection"]);
|
|
1309
|
+
|
|
1268
1310
|
/**
|
|
1269
1311
|
* `ocx disconnect --expect-link <id>`: refuse unless this machine is connected to that link (the same
|
|
1270
1312
|
* check `ocx sync --expect-link` makes), read-only under the client lifecycle and config locks. A Home's
|
|
@@ -1333,6 +1375,16 @@ function drainLoneNativeIntentOriginals(lifecycleLockDeps?: ClientLifecycleLockD
|
|
|
1333
1375
|
}
|
|
1334
1376
|
|
|
1335
1377
|
export async function disconnectClient(
|
|
1378
|
+
options: Parameters<typeof disconnectClientAttempt>[0] = {},
|
|
1379
|
+
deps: Pick<ClientConnectDeps, "lifecycleLockDeps"> = {},
|
|
1380
|
+
): ReturnType<typeof disconnectClientAttempt> {
|
|
1381
|
+
// The attempt lock is a file under the config directory: wait for parent ACL admission first,
|
|
1382
|
+
// as every other phase does, so nothing is created under a directory still being hardened.
|
|
1383
|
+
await withConfigDirHardeningSettled(getConfigDir(), () => undefined);
|
|
1384
|
+
return withClientDisconnectAttempt(() => disconnectClientAttempt(options, deps), deps.lifecycleLockDeps);
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
async function disconnectClientAttempt(
|
|
1336
1388
|
options: { keepCatalog?: boolean; expectedOwner?: DesktopRemoteOwner; expectLink?: string; recoverConfig?: boolean } = {},
|
|
1337
1389
|
deps: Pick<ClientConnectDeps, "lifecycleLockDeps"> = {},
|
|
1338
1390
|
): Promise<{
|
|
@@ -1367,6 +1419,7 @@ export async function disconnectClient(
|
|
|
1367
1419
|
throw new Error("client_disconnect_expected_owner_changed");
|
|
1368
1420
|
}
|
|
1369
1421
|
let receipt = previous;
|
|
1422
|
+
let created = false;
|
|
1370
1423
|
let connection: OcxClientConnectionConfig | null = null;
|
|
1371
1424
|
if (state.kind === "connected") {
|
|
1372
1425
|
connection = state.value;
|
|
@@ -1383,19 +1436,17 @@ export async function disconnectClient(
|
|
|
1383
1436
|
}
|
|
1384
1437
|
if (!receipt) {
|
|
1385
1438
|
const desktop = inspectRemoteDesktopStore(desktopOwner(connection));
|
|
1386
|
-
if (desktop.
|
|
1387
|
-
throw new Error(`desktop_lifecycle_unsafe: ${desktop.path} exists but holds no Claude Desktop remote state or disconnect receipt (a leftover or renamed file), so disconnect cannot tell what it would restore. Move that folder aside, then run ocx disconnect again.`);
|
|
1388
|
-
}
|
|
1389
|
-
if (desktop.kind === "unsafe" || desktop.kind === "conflict") throw new Error(`desktop_lifecycle_unsafe: the Claude Desktop remote profile store could not be verified (${desktop.kind}); nothing was changed.`);
|
|
1439
|
+
if (desktop.kind === "unsafe" || desktop.kind === "conflict") throw new Error(desktopLifecycleRefusal(desktop));
|
|
1390
1440
|
preflightDisconnectCatalog(connection, keepCatalog);
|
|
1391
1441
|
receipt = { version: 1, owner: desktopOwner(connection), tokenFingerprint: connection.tokenFingerprint, keepCatalog, phase: "prepared" };
|
|
1392
1442
|
writeDesktopDisconnectReceipt(held, previous, receipt);
|
|
1443
|
+
created = true;
|
|
1393
1444
|
}
|
|
1394
1445
|
} else if (state.kind !== "disconnected" || !receipt || !disconnectAtLeast(receipt, "clearing_connection")) {
|
|
1395
1446
|
throw new Error("disconnect refused: no recoverable connected state; if this is not a Hub and no admission secret or installed service uses the token, inspect it and use ocx disconnect --orphaned-token --yes");
|
|
1396
1447
|
}
|
|
1397
1448
|
if (!receipt || receipt.keepCatalog !== keepCatalog) throw new Error("client_disconnect_options_changed");
|
|
1398
|
-
return { receipt, connection };
|
|
1449
|
+
return { receipt, connection, created };
|
|
1399
1450
|
}), deps.lifecycleLockDeps));
|
|
1400
1451
|
|
|
1401
1452
|
// This sibling step owns only file integrations; failures retain the prepared receipt/token.
|
|
@@ -1407,8 +1458,11 @@ export async function disconnectClient(
|
|
|
1407
1458
|
}
|
|
1408
1459
|
// The prepared receipt blocks even a sync queued for its actual N/C injection commit.
|
|
1409
1460
|
// Codex-only restore MUST stay outside L; it never invokes Desktop cleanup.
|
|
1410
|
-
|
|
1411
|
-
|
|
1461
|
+
let recoveryBackupDir: string | undefined;
|
|
1462
|
+
if (prepared.connection && !disconnectAtLeast(prepared.receipt, "desktop_restored")) {
|
|
1463
|
+
try { recoveryBackupDir = restoreConnectedCodex(prepared.connection, prepared.receipt, options.recoverConfig === true); }
|
|
1464
|
+
catch (error) { throw abortPreparedDisconnect(prepared, error, deps); }
|
|
1465
|
+
}
|
|
1412
1466
|
|
|
1413
1467
|
return withConfigDirHardeningSettled(getConfigDir(), () => withClientLifecycleSync(held => withConfigMutationLockSync(() => {
|
|
1414
1468
|
const read = readDesktopDisconnectReceipt();
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { DesktopStoreInspectReason } from "../claude/desktop-remote-store";
|
|
2
|
+
|
|
3
|
+
const FOLDER = "the desktop-remote folder in the OpenCodex home";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The `ocx disconnect` refusal for a Claude Desktop remote store it cannot verify: what was found,
|
|
7
|
+
* where, and the step that clears it, with the machine-readable code last. Each fix leaves the next
|
|
8
|
+
* inspection able to decide; none is run for the person, because each gives up or rewrites
|
|
9
|
+
* something in Claude Desktop that only they can judge.
|
|
10
|
+
*/
|
|
11
|
+
export function desktopLifecycleRefusal(desktop: { kind: string; reason?: DesktopStoreInspectReason; path?: string }): string {
|
|
12
|
+
const at = desktop.path;
|
|
13
|
+
const body = (() => {
|
|
14
|
+
switch (desktop.reason) {
|
|
15
|
+
case "root_without_state":
|
|
16
|
+
return `${at} exists but holds no Claude Desktop remote state or disconnect receipt (a leftover or renamed file), so disconnect cannot tell what it would restore. Nothing was changed. Move that folder aside, then run ocx disconnect again.`;
|
|
17
|
+
case "store_unreadable":
|
|
18
|
+
return `OpenCodex cannot read safely the Claude Desktop remote state in ${at ?? FOLDER}: state.json or baseline.json is not an owner-only regular file, is not valid, or was written for another OpenCodex home or Claude Desktop library. Nothing was changed. If either file is not owner-only, make it so (chmod 600) and retry. Otherwise move that folder aside and keep it (its baseline.json holds the Claude Desktop profile OpenCodex replaced); disconnect then gives Claude Desktop's OpenCodex profile its standard settings. In either case, then run ocx disconnect again.`;
|
|
19
|
+
case "store_other_connection":
|
|
20
|
+
return `${at} records a Claude Desktop profile applied for a different connection (another Home or an earlier link), so this disconnect cannot restore it. Nothing was changed. In Claude Desktop, remove that connection's OpenCodex profile; then move ${FOLDER} aside, then run ocx disconnect again.`;
|
|
21
|
+
case "library_unreadable":
|
|
22
|
+
return `the Claude Desktop profile list in ${at} (_meta.json or the selected profile file) could not be read safely. Nothing was changed. Restore that file to valid JSON from Claude Desktop or a backup, then run ocx disconnect again.`;
|
|
23
|
+
case "profile_missing":
|
|
24
|
+
return `the OpenCodex profile in the Claude Desktop library ${at} was removed or renamed outside OpenCodex, so disconnect cannot restore the profile it replaced. Nothing was changed. Rename it back to "opencodex" in Claude Desktop; if it was deleted, move ${FOLDER} aside instead; then run ocx disconnect again.`;
|
|
25
|
+
case "profile_edited":
|
|
26
|
+
return `the OpenCodex profile ${at} was edited outside OpenCodex after it was applied. Nothing was changed. Disconnect restores the profile OpenCodex replaced, which discards those edits: copy anything you want to keep from that file, undo the edits, then run ocx disconnect again.`;
|
|
27
|
+
case "profile_ambiguous":
|
|
28
|
+
return `a profile in the Claude Desktop library ${at} reaches this Home, but disconnect cannot identify it as OpenCodex's current profile (it has another name, an older key, or is a second copy). Nothing was changed. In Claude Desktop, remove every profile that reaches this Home except one named "opencodex" that uses this connection's current key; if the only one left uses an older key, remove that one too, then run ocx disconnect again.`;
|
|
29
|
+
case "token_unreadable":
|
|
30
|
+
return `the service token or its rotation backup (${at}) is not a safe regular file, so disconnect cannot tell which keys belong to this connection. Nothing was changed. Make both files owner-only regular files (move a directory or link at that path aside), then run ocx disconnect again.`;
|
|
31
|
+
case "connection_changed":
|
|
32
|
+
return `the saved connection changed while disconnect was checking Claude Desktop. Nothing was changed. Check ocx connect status, then run ocx disconnect again.`;
|
|
33
|
+
default:
|
|
34
|
+
return `the Claude Desktop remote profile store could not be verified (${desktop.kind}). Nothing was changed. Check ${FOLDER} and the Claude Desktop profile library, then run ocx disconnect again.`;
|
|
35
|
+
}
|
|
36
|
+
})();
|
|
37
|
+
return `Disconnect refused: ${body} (code desktop_lifecycle_unsafe)`;
|
|
38
|
+
}
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
/**
|
|
1
|
+
/**
|
|
2
|
+
* Client/Desktop lifecycle exclusion. Lock order: D -> N -> L -> C; never acquire N inside L.
|
|
3
|
+
* D (one disconnect attempt) is outermost and taken by nothing else.
|
|
4
|
+
*/
|
|
2
5
|
import { Database } from "bun:sqlite";
|
|
3
6
|
import { chmodSync, closeSync, lstatSync, mkdirSync, openSync } from "node:fs";
|
|
4
7
|
import { dirname, join, resolve } from "node:path";
|
|
@@ -54,14 +57,14 @@ function preparePath(lockPath: string): void {
|
|
|
54
57
|
assertPath(lockPath, false);
|
|
55
58
|
}
|
|
56
59
|
|
|
57
|
-
function acquire(deps: ClientLifecycleLockDeps): Database {
|
|
60
|
+
function acquire(deps: ClientLifecycleLockDeps, name = "client-desktop-lifecycle.sqlite", suffix = ""): Database {
|
|
58
61
|
let database: Database | undefined;
|
|
59
62
|
try {
|
|
60
63
|
// The production namespace belongs to the effective OS user, never HOME,
|
|
61
64
|
// OPENCODEX_HOME, Desktop library overrides or an environment test switch.
|
|
62
65
|
const path = deps.lockPath === undefined
|
|
63
|
-
? join(resolveEffectiveUserRuntimeRoot(resolveEffectiveUserIdentity()),
|
|
64
|
-
: resolve(deps.lockPath);
|
|
66
|
+
? join(resolveEffectiveUserRuntimeRoot(resolveEffectiveUserIdentity()), name)
|
|
67
|
+
: resolve(deps.lockPath) + suffix;
|
|
65
68
|
preparePath(path);
|
|
66
69
|
database = new Database(path, { create: true });
|
|
67
70
|
database.exec("PRAGMA locking_mode = NORMAL; PRAGMA busy_timeout = 0; BEGIN IMMEDIATE");
|
|
@@ -127,3 +130,25 @@ export function withClientLifecycleSync<T>(
|
|
|
127
130
|
finally { activeLeases.delete(held); }
|
|
128
131
|
return finish(database, outcome);
|
|
129
132
|
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* D: one ocx disconnect attempt at a time, held across the whole attempt.
|
|
136
|
+
*
|
|
137
|
+
* A disconnect restores Codex outside L, so two attempts used to share one prepared receipt
|
|
138
|
+
* there; rolling back one attempt's receipt then removed the other's while it was still
|
|
139
|
+
* restoring. D is a separate lock so taking it never orders against N, L or C.
|
|
140
|
+
*/
|
|
141
|
+
export async function withClientDisconnectAttempt<T>(work: () => Promise<T>, deps: ClientLifecycleLockDeps = {}): Promise<T> {
|
|
142
|
+
let database: Database;
|
|
143
|
+
try { database = acquire(deps, "client-disconnect-attempt.sqlite", ".disconnect-attempt"); }
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (errorCode(error) === "client_lifecycle_busy") {
|
|
146
|
+
throw new ClientLifecycleError("client_disconnect_busy: another ocx disconnect is running on this machine; let it finish, then run ocx disconnect again");
|
|
147
|
+
}
|
|
148
|
+
throw error;
|
|
149
|
+
}
|
|
150
|
+
let outcome: Outcome<T>;
|
|
151
|
+
try { outcome = { ok: true, value: await work() }; }
|
|
152
|
+
catch (error) { outcome = { ok: false, error }; }
|
|
153
|
+
return finish(database, outcome);
|
|
154
|
+
}
|
|
@@ -6,7 +6,8 @@
|
|
|
6
6
|
* when this process starts its own replacement, so:
|
|
7
7
|
*
|
|
8
8
|
* - Under the desktop app or a viable service supervisor the restart is refused (409
|
|
9
|
-
* `restart_supervised`) and the runtime keeps serving.
|
|
9
|
+
* `restart_supervised`) and the runtime keeps serving. A runtime whose only owner evidence is a
|
|
10
|
+
* bare OCX_SERVICE=1 is always refused (`legacy-flag`), connection ended or not (#8545). The supervisor owns this process and its
|
|
10
11
|
* port; handing off to it means exiting before anything proves the replacement can start.
|
|
11
12
|
* - Unless the connection it serves is no longer the durable one (`ocx disconnect`, or a newer
|
|
12
13
|
* connect). Then there is nothing to keep, and under every owner the restart hands off to the
|
|
@@ -36,12 +37,18 @@ type ClientConnectionState = ReturnType<typeof readClientConnectionState>;
|
|
|
36
37
|
* `service-unproven`: a service manager's marker shows it launched and owns this process, but its
|
|
37
38
|
* relaunch cannot be proven (for example a systemd unit started by hand while disabled). Neither
|
|
38
39
|
* exiting for it nor detaching from it is safe, so the restart is refused.
|
|
40
|
+
*
|
|
41
|
+
* `legacy-flag`: the only owner evidence is a bare OCX_SERVICE=1, which a service registered before
|
|
42
|
+
* the manager marker existed (before 2.49.0) and the proxies of ocx claude, ocx codex and ocx opencode
|
|
43
|
+
* all carry. Nothing tells them apart, and the owner is never inferred (not from the service
|
|
44
|
+
* diagnostic, not from the parent's command line), so the restart is refused with advice to
|
|
45
|
+
* re-register the service once (#8545 owner decision, 2026-11-16).
|
|
39
46
|
*/
|
|
40
|
-
export type ClientRestartSupervisor = "service" | "desktop" | "service-unproven";
|
|
47
|
+
export type ClientRestartSupervisor = "service" | "desktop" | "service-unproven" | "legacy-flag";
|
|
41
48
|
|
|
42
|
-
/** Verdicts that keep the runtime:
|
|
43
|
-
export function restartRefusedByOwner(supervisor: ClientRestartSupervisor | null): supervisor is "service-unproven" {
|
|
44
|
-
return supervisor === "service-unproven";
|
|
49
|
+
/** Verdicts that keep the runtime: exiting for the owner or detaching from it is not proven safe. */
|
|
50
|
+
export function restartRefusedByOwner(supervisor: ClientRestartSupervisor | null): supervisor is "service-unproven" | "legacy-flag" {
|
|
51
|
+
return supervisor === "service-unproven" || supervisor === "legacy-flag";
|
|
45
52
|
}
|
|
46
53
|
|
|
47
54
|
export type ClientRestartAdmission =
|
|
@@ -58,7 +65,7 @@ export interface ClientRestartIo {
|
|
|
58
65
|
connectionChanged?: () => boolean;
|
|
59
66
|
/**
|
|
60
67
|
* Positive evidence of who owns this process ({@link restartOwnerProven}). Without it the
|
|
61
|
-
* ended-connection recycle is never reached and the
|
|
68
|
+
* ended-connection recycle is never reached, and the supervisor check refuses the restart.
|
|
62
69
|
*/
|
|
63
70
|
ownerProven?: () => boolean;
|
|
64
71
|
/**
|
|
@@ -140,7 +147,7 @@ export function createClientRestartController(io: ClientRestartIo): ClientRestar
|
|
|
140
147
|
async request() {
|
|
141
148
|
if (io.stopping?.()) return { kind: "stopping" };
|
|
142
149
|
// Only positive ownership evidence opens the ended-connection recycle; without it (a bare
|
|
143
|
-
// OCX_SERVICE=1) the
|
|
150
|
+
// OCX_SERVICE=1) the supervisor check below refuses the request as `legacy-flag`.
|
|
144
151
|
if (io.recycle && (io.ownerProven?.() ?? true) && io.connectionChanged?.()) {
|
|
145
152
|
if (flight) return { kind: "accepted", alreadyRestarting: true };
|
|
146
153
|
// An owner that cannot be proven to relaunch this process keeps it, connection ended or not.
|
|
@@ -175,8 +182,7 @@ export function createClientRestartController(io: ClientRestartIo): ClientRestar
|
|
|
175
182
|
/** Production supervision check: the desktop app, then a service that will really relaunch us. */
|
|
176
183
|
export async function clientRestartSupervisor(): Promise<ClientRestartSupervisor | null> {
|
|
177
184
|
const { diagnoseService } = await import("../service/diagnostics");
|
|
178
|
-
|
|
179
|
-
return classifyClientRestartSupervisor({ desktop: isDesktopSupervised(), env: process.env, diagnose: diagnoseService, legacyServiceViable: isServiceViable });
|
|
185
|
+
return classifyClientRestartSupervisor({ desktop: isDesktopSupervised(), env: process.env, diagnose: diagnoseService });
|
|
180
186
|
}
|
|
181
187
|
|
|
182
188
|
/**
|
|
@@ -202,26 +208,32 @@ export function restartOwnerEvidence(input: { desktop: boolean; env: NodeJS.Proc
|
|
|
202
208
|
return input.env.OCX_SERVICE !== "1" ? "none" : null;
|
|
203
209
|
}
|
|
204
210
|
|
|
211
|
+
/** What a client runtime with a bare OCX_SERVICE=1 states in its record: no owner, and `ocx disconnect` gives the advice. */
|
|
212
|
+
export const LEGACY_FLAG_RESTART_OWNER = "legacy-flag";
|
|
213
|
+
export type RecordedRestartOwner = RestartOwner | typeof LEGACY_FLAG_RESTART_OWNER;
|
|
214
|
+
|
|
215
|
+
/** The record's `restartOwner`: the proven owner, or `legacy-flag` for a bare OCX_SERVICE=1. */
|
|
216
|
+
export function recordedRestartOwner(input: { desktop: boolean; env: NodeJS.ProcessEnv; managed?: (env: NodeJS.ProcessEnv) => boolean }): RecordedRestartOwner {
|
|
217
|
+
return restartOwnerEvidence(input) ?? LEGACY_FLAG_RESTART_OWNER;
|
|
218
|
+
}
|
|
219
|
+
|
|
205
220
|
/**
|
|
206
221
|
* Ownership and relaunch are separate facts. With a manager's marker, only a service diagnostic
|
|
207
222
|
* that is viable and running lets this process exit for the manager to relaunch it; otherwise it is
|
|
208
|
-
* `service-unproven` and keeps the runtime. A bare OCX_SERVICE=1
|
|
209
|
-
*
|
|
223
|
+
* `service-unproven` and keeps the runtime. A bare OCX_SERVICE=1 is `legacy-flag` whatever the
|
|
224
|
+
* service diagnostic says: refused, never stopped or replaced on inference (#8545).
|
|
210
225
|
*/
|
|
211
226
|
export function classifyClientRestartSupervisor(input: {
|
|
212
227
|
desktop: boolean;
|
|
213
228
|
env: NodeJS.ProcessEnv;
|
|
214
229
|
diagnose: () => { viable: boolean; running: boolean };
|
|
215
|
-
/** origin/dev's check for a bare OCX_SERVICE=1: src/service/orchestration.ts isServiceViable. */
|
|
216
|
-
legacyServiceViable: () => boolean;
|
|
217
230
|
/** Manager-launched evidence; defaults to the current markers only (isMarkedSupervisedServiceChild). */
|
|
218
231
|
managed?: (env: NodeJS.ProcessEnv) => boolean;
|
|
219
232
|
}): ClientRestartSupervisor | null {
|
|
220
233
|
if (input.desktop) return "desktop";
|
|
221
234
|
// The managed marker (launchd, systemd, WinSW) or the Windows wrapper's protocol marker.
|
|
222
235
|
if (!(input.managed ?? isMarkedSupervisedServiceChild)(input.env)) {
|
|
223
|
-
|
|
224
|
-
return input.legacyServiceViable() ? "service" : null;
|
|
236
|
+
return input.env.OCX_SERVICE !== "1" ? null : "legacy-flag";
|
|
225
237
|
}
|
|
226
238
|
// Relaunch needs positive evidence: viable AND running (launchd's viable also covers an
|
|
227
239
|
// unknown load state for its other callers; running there means loaded).
|
package/src/client/runtime.ts
CHANGED
|
@@ -31,7 +31,7 @@ import { clientLinkStatePath, isChildInitiatedLink, recordChildInitiatedLink } f
|
|
|
31
31
|
import { startMachineListener, type MachineListenerDeps } from "./machine-listener";
|
|
32
32
|
import { isLinkConnection, readClientConnectionState, readClientConnectionStateWithEvidence } from "./state";
|
|
33
33
|
import { withClientLifecycleSync } from "./lifecycle-lock";
|
|
34
|
-
import { clientConnectionEnded, clientRestartRollbackAction, clientRestartSupervisor, createClientRestartController, restartOwnerEvidence, type ClientRestartController, type RestartOwner } from "./runtime-restart";
|
|
34
|
+
import { clientConnectionEnded, clientRestartRollbackAction, clientRestartSupervisor, createClientRestartController, LEGACY_FLAG_RESTART_OWNER, restartOwnerEvidence, type ClientRestartController, type RecordedRestartOwner, type RestartOwner } from "./runtime-restart";
|
|
35
35
|
import { createLinkParityReporter, type LinkParityReporter } from "./link-parity-reporter";
|
|
36
36
|
import { restoreLinkClientRouting } from "./stop-routing";
|
|
37
37
|
import { SUPERVISOR_MARKER_ENVS } from "../lib/supervisor-markers";
|
|
@@ -110,7 +110,7 @@ export function clientRuntimeRecord(
|
|
|
110
110
|
pid: number,
|
|
111
111
|
port: number,
|
|
112
112
|
attestationSecret: string = createLocalAttestationSecret(),
|
|
113
|
-
owner:
|
|
113
|
+
owner: RecordedRestartOwner | null = recordedOwner(),
|
|
114
114
|
): RuntimePortState {
|
|
115
115
|
let command: string[] | undefined;
|
|
116
116
|
try { command = currentServingCommand(); } catch { /* no reliable relaunch identity; update admission fails closed */ }
|
|
@@ -124,6 +124,8 @@ function classifiedOwner(): RestartOwner | null {
|
|
|
124
124
|
return ownerMemo.value;
|
|
125
125
|
}
|
|
126
126
|
const ownerProven = (): boolean => classifiedOwner() !== null;
|
|
127
|
+
/** The record's owner: the proven one, or legacy-flag for a bare OCX_SERVICE=1 (#8545; recordedRestartOwner). */
|
|
128
|
+
const recordedOwner = (): RecordedRestartOwner => classifiedOwner() ?? LEGACY_FLAG_RESTART_OWNER;
|
|
127
129
|
|
|
128
130
|
export function standaloneRecycleEnv(
|
|
129
131
|
env: NodeJS.ProcessEnv,
|
package/src/client/state.ts
CHANGED
|
@@ -162,6 +162,20 @@ export function assertNoClientDisconnectPending(): void {
|
|
|
162
162
|
}
|
|
163
163
|
}
|
|
164
164
|
|
|
165
|
+
/**
|
|
166
|
+
* The message client startup refuses with. A pending disconnect names the command that clears it:
|
|
167
|
+
* under the desktop app or a service the supervisor only logs this line, and on 2.100.2 a person
|
|
168
|
+
* had to move desktop-remote/ aside by hand because nothing said a retry would finish or roll back.
|
|
169
|
+
*/
|
|
170
|
+
export function clientStartupRefusalMessage(reason: string): string {
|
|
171
|
+
if (reason !== "client_disconnect_pending") return `client startup refused: ${reason}`;
|
|
172
|
+
const receipt = readDesktopDisconnectReceipt();
|
|
173
|
+
const valid = receipt.kind === "valid" ? receipt.value : null;
|
|
174
|
+
const command = valid?.keepCatalog ? "ocx disconnect --keep-catalog" : "ocx disconnect";
|
|
175
|
+
return `client startup refused: an ocx disconnect on this machine stopped part way${valid ? ` at phase ${valid.phase}` : ""}. `
|
|
176
|
+
+ `Run ${command} again to finish it or roll it back. (code client_disconnect_pending)`;
|
|
177
|
+
}
|
|
178
|
+
|
|
165
179
|
/** Full snapshot CAS for work returning from an await, including selection and rotation state. */
|
|
166
180
|
export function assertClientConnectionUnchanged(expected: OcxClientConnectionConfig): void {
|
|
167
181
|
assertNoClientDisconnectPending();
|
|
@@ -2,6 +2,8 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import type { AccountPauseDetails } from "../types/account-auto-pause";
|
|
3
3
|
import type { OcxConfig } from "../types";
|
|
4
4
|
import { deleteConfigTopLevelKey } from "../config/rebase-provenance";
|
|
5
|
+
import { MAIN_CODEX_ACCOUNT_ID } from "./account-id";
|
|
6
|
+
import { invalidateRetainedNativeMainLogin } from "./native-main-credentials";
|
|
5
7
|
|
|
6
8
|
/** Whether an account is administratively excluded from future pool selection. */
|
|
7
9
|
export function isCodexAccountPaused(config: OcxConfig, accountId: string): boolean {
|
|
@@ -10,6 +12,8 @@ export function isCodexAccountPaused(config: OcxConfig, accountId: string): bool
|
|
|
10
12
|
|
|
11
13
|
/** Persist the account's pool eligibility without changing credentials or runtime health. */
|
|
12
14
|
export function setCodexAccountPaused(config: OcxConfig, accountId: string, paused: boolean, details?: AccountPauseDetails): void {
|
|
15
|
+
// Pausing main ends a retained native-main login; resuming never revives it (#7345).
|
|
16
|
+
if (paused && accountId === MAIN_CODEX_ACCOUNT_ID) invalidateRetainedNativeMainLogin("pause");
|
|
13
17
|
config.codexAccountPauseState = { ...config.codexAccountPauseState,
|
|
14
18
|
[accountId]: { revision: randomUUID(), ...(paused && details ? { details } : {}) } };
|
|
15
19
|
const pausedIds = new Set(config.pausedCodexAccountIds ?? []);
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { setDecisionAccountUsable } from "../lib/decision-quota-sink";
|
|
2
2
|
import { captureConfigGeneration, type GenerationContext } from "../lib/state-store-sweeper";
|
|
3
3
|
import { isCodexAccountGenerationLive } from "./account-store";
|
|
4
|
+
import { MAIN_CODEX_ACCOUNT_ID } from "./account-id";
|
|
5
|
+
import { invalidateRetainedNativeMainLogin } from "./native-main-credentials";
|
|
4
6
|
|
|
5
7
|
/**
|
|
6
8
|
* Accounts quarantined for reauthentication, each remembering WHICH credential produced the
|
|
@@ -25,6 +27,7 @@ const refusedMainRefreshGrants = new Set<string>();
|
|
|
25
27
|
const MAX_REFUSED_MAIN_REFRESH_GRANTS = 64;
|
|
26
28
|
|
|
27
29
|
export function markMainRefreshGrantRejected(key: string): void {
|
|
30
|
+
invalidateRetainedNativeMainLogin("revocation");
|
|
28
31
|
refusedMainRefreshGrants.add(key);
|
|
29
32
|
if (refusedMainRefreshGrants.size > MAX_REFUSED_MAIN_REFRESH_GRANTS) {
|
|
30
33
|
refusedMainRefreshGrants.delete(refusedMainRefreshGrants.values().next().value!);
|
|
@@ -47,6 +50,7 @@ export function markAccountNeedsReauth(
|
|
|
47
50
|
credentialGeneration?: number,
|
|
48
51
|
): void {
|
|
49
52
|
if (writerGeneration < lastReconciledGeneration && !liveAccountIds.has(id)) return;
|
|
53
|
+
if (id === MAIN_CODEX_ACCOUNT_ID) invalidateRetainedNativeMainLogin("revocation");
|
|
50
54
|
setDecisionAccountUsable(id === "__main__" ? "codex-main" : "codex", id, false, credentialGeneration);
|
|
51
55
|
// An account-wide mark supersedes a generation-scoped one: it is the stronger claim.
|
|
52
56
|
if (credentialGeneration === undefined || !reauthAccounts.has(id)) {
|
|
@@ -154,6 +154,8 @@ export interface MainAccountInfoProbeOptions {
|
|
|
154
154
|
passive?: boolean;
|
|
155
155
|
/** Exact owned result obtained before entering WHAM's shared credential claim. Never serialized. */
|
|
156
156
|
preparedToken?: MainAccountToken | null;
|
|
157
|
+
/** Always use paced usage scheduling, so failure backoff and Retry-After are recorded in every mode. */
|
|
158
|
+
paced?: boolean;
|
|
157
159
|
}
|
|
158
160
|
|
|
159
161
|
export const EMPTY_MAIN_ACCOUNT_INFO: MainAccountInfo = { email: null, plan: null, quota: null };
|
|
@@ -215,7 +217,7 @@ export async function fetchMainAccountInfoAttempt(
|
|
|
215
217
|
}
|
|
216
218
|
}
|
|
217
219
|
const probeOptions = preparedToken === undefined ? options : { ...options, preparedToken };
|
|
218
|
-
const paced = sharedMainQuotaPacingEnabled(config ?? loadConfig());
|
|
220
|
+
const paced = options.paced === true || sharedMainQuotaPacingEnabled(config ?? loadConfig());
|
|
219
221
|
const operation = async () => ({
|
|
220
222
|
...await fetchMainAccountInfoWhileOwned(forceRefresh, retriesRemaining, nativeMainLease, explicitRefresh, postReset, paced, probeOptions),
|
|
221
223
|
identityGeneration: captureMainAccountIdentityGeneration(),
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import type { OcxConfig } from "../../types";
|
|
2
|
+
import { MAIN_CODEX_ACCOUNT_ID } from "../account-id";
|
|
3
|
+
import { reconcileMainCodexAccountRuntimeState } from "../account-lifecycle";
|
|
4
|
+
import { isCodexAccountPaused } from "../account-pause";
|
|
5
|
+
import { isAccountNeedsReauth } from "../account-runtime-state";
|
|
6
|
+
import { getMainAccountHardLockStatus } from "../main-account-hard-lock";
|
|
7
|
+
import { getValidMainAccountToken, mainAccountTokenIsCurrent, mainAccountTokenQuotaWriter } from "../main-account";
|
|
8
|
+
import {
|
|
9
|
+
captureMainAccountIdentityGeneration, captureMainQuotaDispatch, getMainQuotaCredentialGeneration, getObservedMainQuotaIdentityKey,
|
|
10
|
+
isMainAccountIdentityGenerationLive, isMainQuotaDispatchLive, matchesMainQuotaCredential, observeMainQuotaCredential,
|
|
11
|
+
} from "../main-account-cache";
|
|
12
|
+
import { tryAcquireNativeMainProfileClaim } from "../native-main-admission";
|
|
13
|
+
import { isNativeMainTrafficBlocked } from "../native-profile-startup";
|
|
14
|
+
import {
|
|
15
|
+
getMainPolicyUsageObservedAt, isValidWhamHistoryObservation, parseMainPolicyUsageQuota, parseUsageQuota, setAccountQuotaFromParsed,
|
|
16
|
+
type WhamUsageResponse,
|
|
17
|
+
} from "../quota";
|
|
18
|
+
import { fetchCodexUsage, nextCodexUsageQueryAt } from "../quota-query-backoff";
|
|
19
|
+
import { WHAM_REQUEST_TIMEOUT_MS } from "../quota-recovery-timing";
|
|
20
|
+
import { captureConfigGeneration } from "../../lib/state-store-sweeper";
|
|
21
|
+
import type { AdmissionLease } from "../../lib/admission";
|
|
22
|
+
import { fetchMainAccountInfoAttempt } from "./main-account-probe";
|
|
23
|
+
import { isQuotaDispatchCurrent, nextQuotaDispatchSequence, publishQuotaDispatch } from "./pool-quota-probe";
|
|
24
|
+
|
|
25
|
+
/** A hard-lock reading younger than this is current enough to refuse on (#8113). */
|
|
26
|
+
export const MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS = 60_000;
|
|
27
|
+
/** At most one refusal-triggered WHAM read per main identity in this window. */
|
|
28
|
+
export const MAIN_HARD_LOCK_REFUSAL_READ_INTERVAL_MS = 60_000;
|
|
29
|
+
|
|
30
|
+
// Last refusal read per main identity, kept for the whole interval so an A→B→A switch cannot reset it.
|
|
31
|
+
const lastReadAt = new Map<string, number>();
|
|
32
|
+
let inFlight: Promise<void> | undefined;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The caller's own credential when the refused request authenticates as the main login itself
|
|
36
|
+
* (caller-owned Direct, or a request-scoped main bearer in Pool). Such a request may not read the
|
|
37
|
+
* physical main credential, so its fresh read uses this bearer, which the lock already proved is
|
|
38
|
+
* the observed main credential.
|
|
39
|
+
*/
|
|
40
|
+
export interface MainHardLockRefusalCaller {
|
|
41
|
+
bearer: string;
|
|
42
|
+
accountId: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Test-only: forget the per-identity pacing and any settled read. */
|
|
46
|
+
export function resetMainHardLockRefusalReadForTests(): void {
|
|
47
|
+
lastReadAt.clear();
|
|
48
|
+
inFlight = undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Before a main hard-lock refusal, read WHAM once when the reading behind the lock is stale (#8113).
|
|
53
|
+
*
|
|
54
|
+
* A reset redeemed outside OpenCodex leaves the cached reading above the threshold until a later
|
|
55
|
+
* observation replaces it, and the paced background recovery may not run for minutes. When the
|
|
56
|
+
* cached reading is older than {@link MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS}, this reads usage once:
|
|
57
|
+
* with the proxy-owned main credential and the native-main claim through the recovery probe, or,
|
|
58
|
+
* for a caller-owned main request, with the caller's own bearer, published only while that bearer
|
|
59
|
+
* still matches the observed main credential. Concurrent refusals share
|
|
60
|
+
* one read, and each main identity gets at most one read per
|
|
61
|
+
* {@link MAIN_HARD_LOCK_REFUSAL_READ_INTERVAL_MS}. Server-advised usage backoff, a paused main,
|
|
62
|
+
* reauthentication quarantine and native-main maintenance all skip the read. The read is passive:
|
|
63
|
+
* it never sets or clears the reauthentication quarantine.
|
|
64
|
+
*
|
|
65
|
+
* Returns `true` when the lock no longer blocks, so the caller may resolve the request again;
|
|
66
|
+
* `false` keeps the refusal. A failed read keeps the existing policy observation.
|
|
67
|
+
*/
|
|
68
|
+
export async function refreshMainHardLockBeforeRefusal(
|
|
69
|
+
config: OcxConfig,
|
|
70
|
+
policy: Parameters<typeof getMainAccountHardLockStatus>[0] = config,
|
|
71
|
+
signal?: AbortSignal,
|
|
72
|
+
/** The caller-owned main credential; `null` when the request is caller-owned but unusable for a read. */
|
|
73
|
+
caller?: MainHardLockRefusalCaller | null,
|
|
74
|
+
now: () => number = Date.now,
|
|
75
|
+
): Promise<boolean> {
|
|
76
|
+
const blocked = () => getMainAccountHardLockStatus(policy, now()).state === "blocked";
|
|
77
|
+
if (!blocked()) return true;
|
|
78
|
+
if (caller === null) return false;
|
|
79
|
+
// The usage measurement's age, not the snapshot's write time: credits-only merges rewrite the latter.
|
|
80
|
+
const observedAt = getMainPolicyUsageObservedAt();
|
|
81
|
+
if (observedAt !== undefined && now() - observedAt < MAIN_HARD_LOCK_REFUSAL_READ_AGE_MS) return false;
|
|
82
|
+
if (isNativeMainTrafficBlocked() || isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)
|
|
83
|
+
|| isCodexAccountPaused(config, MAIN_CODEX_ACCOUNT_ID)) return false;
|
|
84
|
+
if (!inFlight) {
|
|
85
|
+
const identity = getObservedMainQuotaIdentityKey() ?? "";
|
|
86
|
+
for (const [key, at] of lastReadAt) {
|
|
87
|
+
if (now() - at >= MAIN_HARD_LOCK_REFUSAL_READ_INTERVAL_MS) lastReadAt.delete(key);
|
|
88
|
+
}
|
|
89
|
+
if (lastReadAt.has(identity)) return false;
|
|
90
|
+
const queryAfter = nextCodexUsageQueryAt(`main:${captureConfigGeneration()}:${getMainQuotaCredentialGeneration()}`);
|
|
91
|
+
if (queryAfter !== undefined && queryAfter > now()) return false;
|
|
92
|
+
let read: Promise<void>;
|
|
93
|
+
if (caller) {
|
|
94
|
+
// Without a live proof for the caller's credential there is nothing to read; keep the minute.
|
|
95
|
+
const dispatch = captureMainQuotaDispatch(caller.bearer, caller.accountId, captureConfigGeneration());
|
|
96
|
+
if (!dispatch) return false;
|
|
97
|
+
lastReadAt.set(identity, now());
|
|
98
|
+
read = readCallerMainUsage(caller, dispatch);
|
|
99
|
+
} else {
|
|
100
|
+
const lease = tryAcquireNativeMainProfileClaim();
|
|
101
|
+
if (!lease) return false;
|
|
102
|
+
lastReadAt.set(identity, now());
|
|
103
|
+
read = readMainUsage(config, lease).finally(() => lease.release());
|
|
104
|
+
}
|
|
105
|
+
read = read
|
|
106
|
+
.catch(() => { /* the refusal stands on the existing observation */ })
|
|
107
|
+
.finally(() => { if (inFlight === read) inFlight = undefined; });
|
|
108
|
+
inFlight = read;
|
|
109
|
+
}
|
|
110
|
+
await abortable(inFlight, signal);
|
|
111
|
+
return !blocked();
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
async function readMainUsage(config: OcxConfig, lease: AdmissionLease): Promise<void> {
|
|
115
|
+
reconcileMainCodexAccountRuntimeState();
|
|
116
|
+
const identityGeneration = captureMainAccountIdentityGeneration();
|
|
117
|
+
// Refresh can need an exclusive credential claim, so obtain the token before WHAM's shared claim.
|
|
118
|
+
const prepared = await getValidMainAccountToken({ preserveReauth: true });
|
|
119
|
+
if (!prepared) return;
|
|
120
|
+
if (mainAccountTokenQuotaWriter(prepared)) {
|
|
121
|
+
if (!mainAccountTokenIsCurrent(prepared)) return;
|
|
122
|
+
} else observeMainQuotaCredential(prepared.accessToken, prepared.chatgptAccountId);
|
|
123
|
+
if (!isMainAccountIdentityGenerationLive(identityGeneration) || isAccountNeedsReauth(MAIN_CODEX_ACCOUNT_ID)) return;
|
|
124
|
+
// Paced in every account mode: a failed or Retry-After answer must defer the next read.
|
|
125
|
+
await fetchMainAccountInfoAttempt(true, 1, lease, false, false, false, config,
|
|
126
|
+
{ passive: true, preparedToken: prepared, paced: true });
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Usage read with the caller's own main bearer: no physical credential read, no reauth state. */
|
|
130
|
+
async function readCallerMainUsage(
|
|
131
|
+
caller: MainHardLockRefusalCaller, dispatch: NonNullable<ReturnType<typeof captureMainQuotaDispatch>>,
|
|
132
|
+
): Promise<void> {
|
|
133
|
+
// The dispatch proof also fences credential commits (refresh, reauthentication) that advance the
|
|
134
|
+
// mutation epoch before the observed credential itself changes.
|
|
135
|
+
const writerGeneration = dispatch.configGeneration;
|
|
136
|
+
// Ordered like the main probe: a response publishes only if no later dispatch already published.
|
|
137
|
+
const sequence = nextQuotaDispatchSequence();
|
|
138
|
+
const key = `main:${writerGeneration}:${dispatch.credentialGeneration}`;
|
|
139
|
+
const admission = await fetchCodexUsage(key, {
|
|
140
|
+
headers: { Authorization: `Bearer ${caller.bearer}`, "ChatGPT-Account-Id": caller.accountId },
|
|
141
|
+
signal: AbortSignal.timeout(WHAM_REQUEST_TIMEOUT_MS),
|
|
142
|
+
}, undefined, { pacingKey: key });
|
|
143
|
+
// A joined read belongs to another owner, which publishes its own evidence.
|
|
144
|
+
if (!admission || admission.kind === "joined") return;
|
|
145
|
+
let usable = false;
|
|
146
|
+
try {
|
|
147
|
+
if (!admission.response.ok) return;
|
|
148
|
+
const data = await admission.response.json() as WhamUsageResponse;
|
|
149
|
+
if (data === null || typeof data !== "object" || Array.isArray(data)) return;
|
|
150
|
+
// The main login may have changed while the read was in flight; never publish across it.
|
|
151
|
+
if (!isMainQuotaDispatchLive(dispatch) || !matchesMainQuotaCredential(caller.bearer, caller.accountId)
|
|
152
|
+
|| writerGeneration !== captureConfigGeneration() || !isQuotaDispatchCurrent(sequence)) return;
|
|
153
|
+
const quota = parseUsageQuota(data);
|
|
154
|
+
if (!quota) return;
|
|
155
|
+
setAccountQuotaFromParsed(MAIN_CODEX_ACCOUNT_ID, quota, writerGeneration, dispatch.writer, parseMainPolicyUsageQuota(data),
|
|
156
|
+
undefined, false, false, isValidWhamHistoryObservation(data) ? quota : null);
|
|
157
|
+
publishQuotaDispatch(sequence);
|
|
158
|
+
usable = true;
|
|
159
|
+
} finally {
|
|
160
|
+
admission.settle(usable);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function abortable(promise: Promise<void>, signal?: AbortSignal): Promise<void> {
|
|
165
|
+
if (!signal) return promise;
|
|
166
|
+
signal.throwIfAborted();
|
|
167
|
+
return new Promise<void>((resolve, reject) => {
|
|
168
|
+
const onAbort = () => reject(signal.reason);
|
|
169
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
170
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
171
|
+
});
|
|
172
|
+
}
|