@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
|
@@ -274,8 +274,9 @@ export function preferKiroModelSupport(
|
|
|
274
274
|
if (!model) return ids;
|
|
275
275
|
if (providerName === "google-antigravity") {
|
|
276
276
|
const positive = ids.filter(id => accountListsModel(providerName, id, model) === true);
|
|
277
|
-
|
|
278
|
-
|
|
277
|
+
const modelMatched = positive.length ? positive : ids.filter(id => accountListsModel(providerName, id, model) !== false);
|
|
278
|
+
const nonExhausted = modelMatched.filter(id => !isAccountQuotaExhausted(providerName, id, model));
|
|
279
|
+
return nonExhausted.length ? nonExhausted : modelMatched;
|
|
279
280
|
}
|
|
280
281
|
if (providerName !== "kiro") return ids;
|
|
281
282
|
const cap = config?.providers?.kiro?.oauthAccountFailover?.maxConcurrentPerAccount;
|
|
@@ -341,7 +342,10 @@ export function routeAntigravityModel(
|
|
|
341
342
|
const ready = new Set(eligibleFailoverAccounts(providerName, now, classifyModelFamilyForQuota(providerName, model)));
|
|
342
343
|
const rank = (id: string) => (ready.has(id) ? 0 : 2) + (accountListsModel(providerName, id, model) === true ? 0 : 1);
|
|
343
344
|
const tier = Math.min(...serving.map(rank));
|
|
344
|
-
|
|
345
|
+
// Same exhaustion preference as the initial pick: a listing account whose quota family is
|
|
346
|
+
// spent loses to one with headroom, unless every candidate in the tier is spent.
|
|
347
|
+
const candidates = preferKiroModelSupport(providerName, serving.filter(id => rank(id) === tier), model, config);
|
|
348
|
+
const best = rankAntigravityModelAccounts(config, candidates, model, now)[0]!;
|
|
345
349
|
return { kind: "reroute", accountId: best };
|
|
346
350
|
}
|
|
347
351
|
|
|
@@ -351,7 +355,8 @@ function rankAntigravityModelAccounts(config: OcxConfig, ids: string[], model: s
|
|
|
351
355
|
const rows = new Map((getAccountSet(provider)?.accounts ?? []).map(row => [row.id, row]));
|
|
352
356
|
const strategy = activeGenericStrategy(config, provider);
|
|
353
357
|
if (strategy === "round-robin") {
|
|
354
|
-
const
|
|
358
|
+
const poolKey = genericPoolKey(provider, classifyModelFamilyForQuota(provider, model));
|
|
359
|
+
const best = peekRoundRobinAccount(poolKey, ids, genericStickyLimit(config, provider));
|
|
355
360
|
return best ? [best, ...ids.filter(id => id !== best)] : ids;
|
|
356
361
|
}
|
|
357
362
|
if (strategy === "fill-first") return stableGenericRoster(provider).filter(id => ids.includes(id));
|
|
@@ -446,16 +451,44 @@ export function rotateAntigravityAccountOnAuthRefusal(
|
|
|
446
451
|
const set = getAccountSet("google-antigravity");
|
|
447
452
|
if (!set || set.accounts.length < 2) return null;
|
|
448
453
|
const family = classifyModelFamilyForQuota("google-antigravity", requestedModelId);
|
|
454
|
+
coolAntigravityAccount(set, failedAccountId, sentGeneration, family, now, {
|
|
455
|
+
cooldownUntil: now + DEFAULT_COOLDOWN_MS, cooldownSource: "auth", identity: sentGeneration,
|
|
456
|
+
});
|
|
457
|
+
return nextAntigravitySibling(set, failedAccountId, requestedModelId, family, now);
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/**
|
|
461
|
+
* The one cooldown write both Antigravity sibling rotations (403 refusal, 5xx fault) share. It is
|
|
462
|
+
* fenced on the sent credential generation, so a re-login that landed mid-request is never cooled,
|
|
463
|
+
* and it never shortens a cooldown already running for the same account and family: a 15-second
|
|
464
|
+
* fault window must not cut short a 60-second refusal or a quota cooldown.
|
|
465
|
+
*/
|
|
466
|
+
function coolAntigravityAccount(
|
|
467
|
+
set: NonNullable<ReturnType<typeof getAccountSet>>,
|
|
468
|
+
failedAccountId: string,
|
|
469
|
+
sentGeneration: string,
|
|
470
|
+
family: QuotaModelFamily | undefined,
|
|
471
|
+
now: number,
|
|
472
|
+
entry: AccountHealth,
|
|
473
|
+
): void {
|
|
449
474
|
const failed = set.accounts.find(row => row.id === failedAccountId);
|
|
450
|
-
if (failed
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
475
|
+
if (!failed || credentialGeneration(failed.credential) !== sentGeneration) return;
|
|
476
|
+
const key = healthKey("google-antigravity", failedAccountId, family);
|
|
477
|
+
if (isCooled("google-antigravity", failedAccountId, now, family)
|
|
478
|
+
&& (health.get(key)?.cooldownUntil ?? 0) >= entry.cooldownUntil) return;
|
|
479
|
+
health.set(key, entry);
|
|
480
|
+
presence.delete("google-antigravity");
|
|
481
|
+
sweepExpiredOnWrite(now);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
/** Next live sibling after the failed account, in roster order, honouring cooldowns and model support. */
|
|
485
|
+
function nextAntigravitySibling(
|
|
486
|
+
set: NonNullable<ReturnType<typeof getAccountSet>>,
|
|
487
|
+
failedAccountId: string,
|
|
488
|
+
requestedModelId: string | null | undefined,
|
|
489
|
+
family: QuotaModelFamily | undefined,
|
|
490
|
+
now: number,
|
|
491
|
+
): string | null {
|
|
459
492
|
const eligible = new Set(preferKiroModelSupport("google-antigravity",
|
|
460
493
|
eligibleIdsIn(set, "google-antigravity", now, family).filter(id => id !== failedAccountId), requestedModelId));
|
|
461
494
|
const order = set.accounts.map(row => row.id);
|
|
@@ -464,6 +497,31 @@ export function rotateAntigravityAccountOnAuthRefusal(
|
|
|
464
497
|
return ring.find(id => id !== failedAccountId && eligible.has(id)) ?? null;
|
|
465
498
|
}
|
|
466
499
|
|
|
500
|
+
/**
|
|
501
|
+
* A 502/503/504 that survived the same-account retry ladder says this account's route to Google is
|
|
502
|
+
* failing right now, not that the credential is bad. Cool it for a short, fixed window (pool-wide
|
|
503
|
+
* capacity trouble then clears on its own within seconds) and name a live sibling to replay on.
|
|
504
|
+
* No stored verdict: nothing here outlives the process or the window.
|
|
505
|
+
*/
|
|
506
|
+
const ANTIGRAVITY_FAULT_COOLDOWN_MS = 15_000;
|
|
507
|
+
|
|
508
|
+
export function rotateAntigravityAccountOnUpstreamFault(
|
|
509
|
+
poolActivated: boolean,
|
|
510
|
+
failedAccountId: string,
|
|
511
|
+
sentGeneration: string,
|
|
512
|
+
requestedModelId: string | null | undefined,
|
|
513
|
+
now = Date.now(),
|
|
514
|
+
): string | null {
|
|
515
|
+
if (!poolActivated) return null;
|
|
516
|
+
const set = getAccountSet("google-antigravity");
|
|
517
|
+
if (!set || set.accounts.length < 2) return null;
|
|
518
|
+
const family = classifyModelFamilyForQuota("google-antigravity", requestedModelId);
|
|
519
|
+
coolAntigravityAccount(set, failedAccountId, sentGeneration, family, now, {
|
|
520
|
+
cooldownUntil: now + ANTIGRAVITY_FAULT_COOLDOWN_MS, cooldownSource: "default",
|
|
521
|
+
});
|
|
522
|
+
return nextAntigravitySibling(set, failedAccountId, requestedModelId, family, now);
|
|
523
|
+
}
|
|
524
|
+
|
|
467
525
|
/** Generic pool strategies the kernel can actually run. `quota` IS the pre-kernel path. */
|
|
468
526
|
type ActiveGenericStrategy = "round-robin" | "fill-first" | "reset-first" | "least-loaded";
|
|
469
527
|
|
|
@@ -580,10 +638,16 @@ export function noteGenericPoolSelection(
|
|
|
580
638
|
requestedModelId?: string | null,
|
|
581
639
|
): void {
|
|
582
640
|
if (activeGenericStrategy(config, providerName) !== "round-robin") return;
|
|
583
|
-
const poolKey = genericPoolKey(providerName);
|
|
584
|
-
const limit = genericStickyLimit(config, providerName);
|
|
585
641
|
const family = classifyModelFamilyForQuota(providerName, requestedModelId);
|
|
586
|
-
const
|
|
642
|
+
const poolKey = genericPoolKey(providerName, family);
|
|
643
|
+
const limit = genericStickyLimit(config, providerName);
|
|
644
|
+
const eligible = preferKiroModelSupport(
|
|
645
|
+
providerName,
|
|
646
|
+
eligibleFailoverAccounts(providerName, Date.now(), family),
|
|
647
|
+
requestedModelId,
|
|
648
|
+
config,
|
|
649
|
+
);
|
|
650
|
+
const picked = pickRoundRobinAccount(poolKey, eligible, limit);
|
|
587
651
|
// The resolver may have admitted a different account than the ring proposed: a removal, a
|
|
588
652
|
// reauth verdict or a manual selection can land during credential resolution. Realign the
|
|
589
653
|
// cursor onto what actually served rather than leaving it on a road not taken.
|
|
@@ -684,7 +748,7 @@ export function rotateGenericOAuthAccountOnRefusal(
|
|
|
684
748
|
// PICK here, not peek: the failure already happened and this answer is the one being used,
|
|
685
749
|
// so the ring genuinely advances. A caller that only asks whether a sibling exists peeks.
|
|
686
750
|
return (commit ? pickRoundRobinAccount : peekRoundRobinAccount)(
|
|
687
|
-
genericPoolKey(providerName),
|
|
751
|
+
genericPoolKey(providerName, family),
|
|
688
752
|
candidates,
|
|
689
753
|
genericStickyLimit(config, providerName),
|
|
690
754
|
);
|
|
@@ -822,7 +886,7 @@ export function preferredInitialAccount(
|
|
|
822
886
|
// PEEK, not pick: this proposal is discardable, and advancing the ring for an account the
|
|
823
887
|
// resolver then rejects would skip a turn for nothing. noteGenericPoolSelection commits.
|
|
824
888
|
const picked = peekRoundRobinAccount(
|
|
825
|
-
genericPoolKey(providerName),
|
|
889
|
+
genericPoolKey(providerName, family),
|
|
826
890
|
eligibleNow,
|
|
827
891
|
genericStickyLimit(config, providerName),
|
|
828
892
|
);
|
|
@@ -889,6 +953,13 @@ export function genericFailoverRetryAfterSeconds(providerName: string, now = Dat
|
|
|
889
953
|
return earliest === null ? null : Math.max(1, Math.ceil((earliest - now) / 1000));
|
|
890
954
|
}
|
|
891
955
|
|
|
956
|
+
/** A manual selection must win in every ring a request can read, including the per-family ones. */
|
|
957
|
+
export function seedGenericPoolSelection(providerName: string, accountId: string): void {
|
|
958
|
+
seedPoolRotationAccount(genericPoolKey(providerName), accountId);
|
|
959
|
+
if (providerName !== "google-antigravity") return;
|
|
960
|
+
for (const family of ["gem", "cla"] satisfies QuotaModelFamily[]) seedPoolRotationAccount(genericPoolKey(providerName, family), accountId);
|
|
961
|
+
}
|
|
962
|
+
|
|
892
963
|
/** Test seam and manual-recovery hook. */
|
|
893
964
|
export function forgetGenericFailoverRoster(providerName: string): void {
|
|
894
965
|
presence.delete(providerName);
|
|
@@ -13,7 +13,8 @@ const IDLE_TTL_MS = 24 * 60 * 60_000;
|
|
|
13
13
|
const MAX_ENTRIES = 2_000;
|
|
14
14
|
const bindings = new Map<string, { accountId: string; lastUsedAt: number; selection: OAuthAccountSelection }>();
|
|
15
15
|
const prefix = (provider: string) => `${JSON.stringify([getConfigDir(), provider])}\u0000`;
|
|
16
|
-
const key = (provider: string, session: string
|
|
16
|
+
const key = (provider: string, session: string, family?: string) =>
|
|
17
|
+
prefix(provider) + (family ? `session:${family}:` : "session:") + createHash("sha256").update(session).digest("hex");
|
|
17
18
|
const cursorKey = (provider: string) => prefix(provider) + "fill-first";
|
|
18
19
|
|
|
19
20
|
/** A persisted operator/roster/policy change revokes old session choices before its writer returns. */
|
|
@@ -59,7 +60,9 @@ export function genericSessionAccount(
|
|
|
59
60
|
config: OcxConfig, provider: string, session: string | null, model?: string | null, now = Date.now(),
|
|
60
61
|
): string | null {
|
|
61
62
|
if (!genericSessionAffinityEnabled(config, provider) || !session) return null;
|
|
62
|
-
|
|
63
|
+
const family = classifyModelFamilyForQuota(provider, model);
|
|
64
|
+
return readBinding(config, provider, key(provider, session, family), model, now)
|
|
65
|
+
?? (family ? readBinding(config, provider, key(provider, session), model, now) : null);
|
|
63
66
|
}
|
|
64
67
|
|
|
65
68
|
function readBinding(config: OcxConfig, provider: string, id: string, model: string | null | undefined, now: number): string | null {
|
|
@@ -127,6 +130,10 @@ export function bindGenericSessionAccount(
|
|
|
127
130
|
const hit = session && genericSessionAccount(config, provider, session, model, now) === accountId;
|
|
128
131
|
if (!hit && config.pool?.kernel === true && config.providers[provider]?.oauthAccountFailover?.strategy === "fill-first")
|
|
129
132
|
keep(cursorKey(provider));
|
|
130
|
-
|
|
133
|
+
const family = classifyModelFamilyForQuota(provider, model);
|
|
134
|
+
if (session) {
|
|
135
|
+
keep(key(provider, session, family));
|
|
136
|
+
if (family) keep(key(provider, session));
|
|
137
|
+
}
|
|
131
138
|
while (bindings.size > MAX_ENTRIES) bindings.delete(bindings.keys().next().value!);
|
|
132
139
|
}
|
package/src/oauth/login-cli.ts
CHANGED
|
@@ -18,6 +18,13 @@ import { codexAccountNamespaceProviderCollisionError } from "../codex/account-na
|
|
|
18
18
|
import { assertAnthropicInstanceLoginConfig } from "./store-anthropic-instance";
|
|
19
19
|
import { reportOAuthLoginError } from "./login-cli-errors";
|
|
20
20
|
import { terminalSafeText } from "../lib/terminal-safe-text";
|
|
21
|
+
import {
|
|
22
|
+
ANTIGRAVITY_RISK_CLI_FLAG,
|
|
23
|
+
antigravityRiskDecisionMessage,
|
|
24
|
+
requiresAntigravityRiskAcknowledgement,
|
|
25
|
+
resolveAntigravityRiskAcknowledgement,
|
|
26
|
+
} from "./antigravity-risk";
|
|
27
|
+
import { isAgentDriven } from "../cli/agent-driven";
|
|
21
28
|
|
|
22
29
|
/**
|
|
23
30
|
* Seams a test drives in place of a browser, a terminal and a real provider. Production passes
|
|
@@ -34,6 +41,10 @@ export interface LoginCliDeps {
|
|
|
34
41
|
warn?: (message: string) => void;
|
|
35
42
|
/** Ask one question, read one line. Defaults to a readline prompt that owns its own lifetime. */
|
|
36
43
|
ask?: (question: string) => Promise<string>;
|
|
44
|
+
/** Whether a person can answer a prompt. Defaults to stdin and stdout both being terminals. */
|
|
45
|
+
isInteractive?: () => boolean;
|
|
46
|
+
/** Whether a coding agent or CI runner drives this process. Defaults to isAgentDriven(). */
|
|
47
|
+
agentDriven?: () => boolean;
|
|
37
48
|
}
|
|
38
49
|
|
|
39
50
|
/**
|
|
@@ -116,10 +127,12 @@ export function warnIfLiveReloadSkipped(result: LocalProviderReloadResult | null
|
|
|
116
127
|
* that used to be their only pointer to it.
|
|
117
128
|
*/
|
|
118
129
|
export function loginUsageMessage(): string {
|
|
119
|
-
return `Usage: ocx login <provider> [--headless]\n`
|
|
130
|
+
return `Usage: ocx login <provider> [--headless] [${ANTIGRAVITY_RISK_CLI_FLAG}]\n`
|
|
120
131
|
+ ` --headless: no browser and no local port — approve in any browser, then paste the code\n`
|
|
121
132
|
+ ` it shows or confirm the device code printed here\n`
|
|
122
133
|
+ ` (${listCodeLoginProviders().join(", ")})\n`
|
|
134
|
+
+ ` ${ANTIGRAVITY_RISK_CLI_FLAG}: google-antigravity only; accept the account-ban risk without\n`
|
|
135
|
+
+ ` the interactive prompt (the warning is still printed)\n`
|
|
123
136
|
+ ` Codex / ChatGPT: ocx login codex (account pool, needs a running proxy; 'chatgpt' and\n`
|
|
124
137
|
+ ` 'openai' are the same route. An OpenAI platform key is 'openai-apikey'.)\n`
|
|
125
138
|
+ ` OAuth login: ${listOAuthProviders().join(", ")}\n`
|
|
@@ -129,10 +142,16 @@ export function loginUsageMessage(): string {
|
|
|
129
142
|
export interface LoginCliOptions {
|
|
130
143
|
/** `--headless`: no callback server, no browser launch — print the URL and read back the code. */
|
|
131
144
|
codeMode?: boolean;
|
|
145
|
+
/** `--accept-antigravity-risk`: accept the Antigravity warning without a prompt. */
|
|
146
|
+
acceptAntigravityRisk?: boolean;
|
|
132
147
|
}
|
|
133
148
|
|
|
134
149
|
export async function handleLogin(provider?: string, deps: LoginCliDeps = {}, opts: LoginCliOptions = {}): Promise<void> {
|
|
135
150
|
const name = (provider ?? "").trim().toLowerCase();
|
|
151
|
+
if (opts.acceptAntigravityRisk && !requiresAntigravityRiskAcknowledgement(DEPRECATED_OAUTH_PROVIDER_ALIASES[name] ?? name)) {
|
|
152
|
+
console.error(`${ANTIGRAVITY_RISK_CLI_FLAG} only applies to google-antigravity`);
|
|
153
|
+
process.exit(1);
|
|
154
|
+
}
|
|
136
155
|
try {
|
|
137
156
|
// Check raw ownership before tolerant loading can print diagnostics or fall back to defaults.
|
|
138
157
|
if (name === "anthropic2") assertAnthropicInstanceLoginConfig({ providers: {} }, name);
|
|
@@ -210,6 +229,21 @@ async function handleCodeLogin(name: string, deps: LoginCliDeps): Promise<void>
|
|
|
210
229
|
|
|
211
230
|
export async function handleOAuthLogin(name: string, deps: LoginCliDeps = {}, opts: LoginCliOptions = {}): Promise<void> {
|
|
212
231
|
if (name === "anthropic2") assertAnthropicInstanceLoginConfig(loadConfig(), name);
|
|
232
|
+
// Runs in-process, so there is no management API check behind it: this prompt is the gate.
|
|
233
|
+
if (requiresAntigravityRiskAcknowledgement(name)) {
|
|
234
|
+
const decision = await resolveAntigravityRiskAcknowledgement({
|
|
235
|
+
flag: opts.acceptAntigravityRisk === true,
|
|
236
|
+
// readline writes the question to stdout, so both ends must be a terminal.
|
|
237
|
+
interactive: (deps.isInteractive ?? (() => process.stdin.isTTY === true && process.stdout.isTTY === true))(),
|
|
238
|
+
agentDriven: (deps.agentDriven ?? isAgentDriven)(),
|
|
239
|
+
warn: text => console.error(text),
|
|
240
|
+
ask: question => withPrompt(deps.ask, ask => ask(question)),
|
|
241
|
+
});
|
|
242
|
+
if (decision !== "accepted") {
|
|
243
|
+
console.error(antigravityRiskDecisionMessage(decision));
|
|
244
|
+
process.exit(1);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
213
247
|
if (opts.codeMode) return handleCodeLogin(name, deps);
|
|
214
248
|
const login = deps.runLogin ?? runLogin;
|
|
215
249
|
const launch = deps.openUrl ?? openUrl;
|
package/src/oauth/pool-kernel.ts
CHANGED
|
@@ -10,8 +10,8 @@ export const POOL_KEY_ANTHROPIC = "anthropic";
|
|
|
10
10
|
* with the two dedicated kinds, and so `reconcilePoolRotationState` can recognise
|
|
11
11
|
* the entry as sweepable rather than skipping it as unknown.
|
|
12
12
|
*/
|
|
13
|
-
export function genericPoolKey(providerName: string): string {
|
|
14
|
-
return `generic:${providerName}`;
|
|
13
|
+
export function genericPoolKey(providerName: string, family?: string): string {
|
|
14
|
+
return family ? `generic:${providerName}:${family}` : `generic:${providerName}`;
|
|
15
15
|
}
|
|
16
16
|
|
|
17
17
|
interface SelectionState {
|
|
@@ -309,7 +309,7 @@ export function reconcilePoolRotationState(context: GenerationContext): number {
|
|
|
309
309
|
: poolKey === POOL_KEY_CODEX || poolKey.startsWith(`${POOL_KEY_CODEX}:`)
|
|
310
310
|
? context.codexAccountIds
|
|
311
311
|
: poolKey.startsWith("generic:")
|
|
312
|
-
? genericIds.get(poolKey.slice("generic:".length)) ?? new Set<string>()
|
|
312
|
+
? genericIds.get(poolKey.slice("generic:".length).split(":")[0]!) ?? new Set<string>()
|
|
313
313
|
: null;
|
|
314
314
|
if (!valid) continue;
|
|
315
315
|
if (valid.size === 0) {
|
|
@@ -4,6 +4,9 @@ const MAX_BILLING_REFUSAL_BYTES = 8 * 1024;
|
|
|
4
4
|
const BILLING_REFUSAL_DEADLINE_MS = 250;
|
|
5
5
|
// Keep the whole-message credit-balance pattern used by anthropic-account-refusal.
|
|
6
6
|
const CREDIT_BALANCE_REFUSAL = /^Your credit balance is too low to access the Anthropic API\.(?: Please go to Plans & Billing to upgrade or purchase credits\.)?$/i;
|
|
7
|
+
// Anthropic's OAuth refusal when a turn bills against an empty extra-usage balance. Exact wording
|
|
8
|
+
// only, as above: a validation error that quotes it back must not grant a combo hop.
|
|
9
|
+
const EXTRA_USAGE_REFUSAL = /^(?:You['\u2019]re out of extra usage|Third-party apps now draw from your extra usage, not your plan limits)\.(?: Add more at claude\.ai\/settings\/usage and keep going\.)?$/i;
|
|
7
10
|
const BILLING_ERROR_TYPES = new Set(["invalid_request_error", "billing_error", "permission_error"]);
|
|
8
11
|
const ACCOUNT_REFUSAL_CODES = new Set(["subscription_required", "insufficient_quota", "permission_denied"]);
|
|
9
12
|
|
|
@@ -22,13 +25,17 @@ export function isAnthropicBillingRefusal(status: number, payload: unknown): boo
|
|
|
22
25
|
return CREDIT_BALANCE_REFUSAL.test(error.message.trim());
|
|
23
26
|
}
|
|
24
27
|
|
|
28
|
+
function withoutProviderPrefix(status: number, message: string): string {
|
|
29
|
+
const text = message.trim();
|
|
30
|
+
const prefix = `Provider error ${status}: `;
|
|
31
|
+
return text.startsWith(prefix) ? text.slice(prefix.length) : text;
|
|
32
|
+
}
|
|
33
|
+
|
|
25
34
|
/** Bounded combo evidence after existing HTTP error formatting, before any output. */
|
|
26
35
|
export function isAnthropicBillingFailure(status: number, message: string, code?: string | null): boolean {
|
|
27
36
|
if (status !== 400 && status !== 402 || Buffer.byteLength(message, "utf8") > MAX_BILLING_REFUSAL_BYTES) return false;
|
|
28
37
|
if (code != null && !BILLING_ERROR_TYPES.has(code) && !ACCOUNT_REFUSAL_CODES.has(code)) return false;
|
|
29
|
-
|
|
30
|
-
const prefix = `Provider error ${status}: `;
|
|
31
|
-
if (text.startsWith(prefix)) text = text.slice(prefix.length);
|
|
38
|
+
const text = withoutProviderPrefix(status, message);
|
|
32
39
|
try { return isAnthropicBillingRefusal(status, JSON.parse(text)); } catch { /* Exact prose needs a structured type. */ }
|
|
33
40
|
return typeof code === "string" && BILLING_ERROR_TYPES.has(code)
|
|
34
41
|
&& isAnthropicBillingRefusal(status, { type: "error", error: { type: code, message: text } });
|
|
@@ -53,3 +60,20 @@ export async function readAnthropicBillingRefusal(response: Response, signal?: A
|
|
|
53
60
|
return false;
|
|
54
61
|
}
|
|
55
62
|
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A 400 extra-usage refusal says this OAuth target cannot serve the turn; a later combo target
|
|
66
|
+
* may. Same evidence bar as billing: an `invalid_request_error` envelope with the exact wording.
|
|
67
|
+
*/
|
|
68
|
+
export function isAnthropicExtraUsageFailure(status: number, message: string, code?: string | null): boolean {
|
|
69
|
+
if (status !== 400 || Buffer.byteLength(message, "utf8") > MAX_BILLING_REFUSAL_BYTES) return false;
|
|
70
|
+
if (code != null && code !== "invalid_request_error") return false;
|
|
71
|
+
const text = withoutProviderPrefix(status, message);
|
|
72
|
+
try {
|
|
73
|
+
const payload: unknown = JSON.parse(text);
|
|
74
|
+
return record(payload) && payload.type === "error" && record(payload.error)
|
|
75
|
+
&& payload.error.type === "invalid_request_error" && payload.error.code == null
|
|
76
|
+
&& typeof payload.error.message === "string" && EXTRA_USAGE_REFUSAL.test(payload.error.message.trim());
|
|
77
|
+
} catch { /* Exact prose needs a structured type. */ }
|
|
78
|
+
return code === "invalid_request_error" && EXTRA_USAGE_REFUSAL.test(text);
|
|
79
|
+
}
|
|
@@ -197,6 +197,7 @@ function apiKeyDiscoveryAuth(selection: { key: string | undefined; ambient?: tru
|
|
|
197
197
|
export async function resolveVertexDiscoveryAuth(
|
|
198
198
|
provider: OcxProviderConfig,
|
|
199
199
|
signal: AbortSignal = vertexDiscoveryDeadline(),
|
|
200
|
+
options: { forceExchange?: boolean } = {},
|
|
200
201
|
): Promise<VertexDiscoveryAuth | undefined> {
|
|
201
202
|
if (provider.authMode === "forward" || isVertexApiKeyPoolPaused(provider)) return undefined;
|
|
202
203
|
const selection = selectVertexDiscoveryCredential(provider);
|
|
@@ -204,7 +205,11 @@ export async function resolveVertexDiscoveryAuth(
|
|
|
204
205
|
let authority: Awaited<ReturnType<typeof getVertexAccessTokenWithAuthority>>;
|
|
205
206
|
try {
|
|
206
207
|
const markerAccount = gcpCredentialMarkerAccount(selection.marker);
|
|
207
|
-
authority = await getVertexAccessTokenWithAuthority({
|
|
208
|
+
authority = await getVertexAccessTokenWithAuthority({
|
|
209
|
+
signal,
|
|
210
|
+
...(markerAccount ? { markerAccount } : {}),
|
|
211
|
+
...(options.forceExchange ? { forceExchange: true } : {}),
|
|
212
|
+
});
|
|
208
213
|
} catch {
|
|
209
214
|
return undefined;
|
|
210
215
|
}
|
|
@@ -155,6 +155,7 @@ export const PROVIDER_MODEL_RENAME_ROLES = {
|
|
|
155
155
|
escapeBuiltinToolNames: "none",
|
|
156
156
|
anthropicEofTolerance: "none",
|
|
157
157
|
forwardAdvisorTool: "none",
|
|
158
|
+
perMessageEffort: "none",
|
|
158
159
|
noVisionModels: "list",
|
|
159
160
|
googleMode: "none",
|
|
160
161
|
googleToolSchemaPolicy: "none",
|
|
@@ -165,6 +166,7 @@ export const PROVIDER_MODEL_RENAME_ROLES = {
|
|
|
165
166
|
unsafeAllowNativeLocalExec: "none",
|
|
166
167
|
nativeLocalExec: "none",
|
|
167
168
|
messagePhaseInference: "none",
|
|
169
|
+
estimateMissingUsage: "none",
|
|
168
170
|
tlsProfile: "none",
|
|
169
171
|
} as const satisfies Record<keyof OcxProviderConfig, ModelRenameRole>;
|
|
170
172
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { OAuthCredentials } from "../../oauth/types";
|
|
2
2
|
import { workBuddyApi, WorkBuddyApiError } from "../../oauth/workbuddy";
|
|
3
3
|
import { workBuddyHeaders } from "../workbuddy";
|
|
4
|
-
import { parseWorkBuddyCredits, remainingWorkBuddyCredits, workBuddyCapacity, workBuddyRecord, type WorkBuddyCreditBalance } from "../workbuddy-credit-balance";
|
|
4
|
+
import { parseWorkBuddyCredits, remainingWorkBuddyCredits, workBuddyCapacity, workBuddyExactCredits, workBuddyRecord, type WorkBuddyCreditBalance } from "../workbuddy-credit-balance";
|
|
5
5
|
import { REQUEST_TIMEOUT_MS } from "../quota-wire";
|
|
6
6
|
import { TERMINAL_QUOTA_FAILURE, type ProviderQuotaProbeResult } from "./report-cache";
|
|
7
7
|
|
|
@@ -56,6 +56,7 @@ async function expiringCredits(summary: Record<string, unknown>, headers: Record
|
|
|
56
56
|
return workBuddyExpiringCredits(lists.flat(), new Set(codes), now);
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
+
/** Display-only credit balance for one account; the enterprise meter fills an empty personal summary. */
|
|
59
60
|
export async function fetchWorkBuddyQuota(provider: string, credential: OAuthCredentials): Promise<ProviderQuotaProbeResult> {
|
|
60
61
|
if (!credential.workbuddy) return null;
|
|
61
62
|
const signal = AbortSignal.timeout(REQUEST_TIMEOUT_MS), now = Date.now();
|
|
@@ -67,7 +68,10 @@ export async function fetchWorkBuddyQuota(provider: string, credential: OAuthCre
|
|
|
67
68
|
const team = await workBuddyApi("/billing/meter/get-enterprise-user-usage", headers, signal, true);
|
|
68
69
|
const total = workBuddyCapacity(team.limitNum), used = workBuddyCapacity(team.credit);
|
|
69
70
|
if (total === undefined || used === undefined) return null;
|
|
70
|
-
|
|
71
|
+
const exact = workBuddyExactCredits(team.limitNum, team.credit);
|
|
72
|
+
credits = exact
|
|
73
|
+
? { total: Number(exact.total), used, remaining: Number(exact.remaining), frozen: 0, groups: [], exact }
|
|
74
|
+
: { total, used, remaining: remainingWorkBuddyCredits(total, used), frozen: 0, groups: [] };
|
|
71
75
|
}
|
|
72
76
|
if (!credits) return null;
|
|
73
77
|
if (credits.remaining > 0) {
|
|
@@ -8,10 +8,18 @@ export interface WorkBuddyCreditAmount {
|
|
|
8
8
|
export const WORKBUDDY_CREDIT_KINDS = ["plan_base", "plan_bonus", "addon", "benefit", "other"] as const;
|
|
9
9
|
export type WorkBuddyCreditKind = typeof WORKBUDDY_CREDIT_KINDS[number];
|
|
10
10
|
|
|
11
|
+
/** Plain decimal text (no sign or exponent) of a validated, bounded credit amount. */
|
|
12
|
+
export interface WorkBuddyExactCredits {
|
|
13
|
+
total: string;
|
|
14
|
+
remaining: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
11
17
|
/** Display-only credits; they are neither USD nor provider-wide model eligibility. */
|
|
12
18
|
export interface WorkBuddyCreditBalance extends WorkBuddyCreditAmount {
|
|
13
19
|
groups: Array<WorkBuddyCreditAmount & { kind: WorkBuddyCreditKind }>;
|
|
14
20
|
expiring?: { amount: number; at: number };
|
|
21
|
+
/** Optional exact companions of `total` and `remaining`; the numeric fields stay the contract. */
|
|
22
|
+
exact?: WorkBuddyExactCredits;
|
|
15
23
|
}
|
|
16
24
|
|
|
17
25
|
export function workBuddyRecord(value: unknown): Record<string, unknown> {
|
|
@@ -24,19 +32,69 @@ export function workBuddyCapacity(value: unknown): number | undefined {
|
|
|
24
32
|
return Number.isFinite(number) && number >= 0 && number <= Number.MAX_SAFE_INTEGER ? number : undefined;
|
|
25
33
|
}
|
|
26
34
|
|
|
35
|
+
interface Decimal { digits: bigint; scale: number }
|
|
36
|
+
|
|
37
|
+
const ZERO: Decimal = { digits: 0n, scale: 0 };
|
|
38
|
+
// Exact metadata bounds: balances above MAX_SAFE_INTEGER (16 digits) are already rejected.
|
|
39
|
+
const EXACT_TEXT = /^(\d{1,16})(?:\.(\d{1,32}))?$/;
|
|
40
|
+
const EXACT_SCALE = 32;
|
|
41
|
+
|
|
42
|
+
/** Decimal value of a number's shortest round-trip text, as the summed capacities always used. */
|
|
43
|
+
function numberDecimal(value: number): Decimal {
|
|
44
|
+
const [coefficient, exponent = "0"] = value.toString().split("e");
|
|
45
|
+
const [whole, fraction = ""] = coefficient!.split(".");
|
|
46
|
+
let digits = BigInt(`${whole}${fraction}`);
|
|
47
|
+
let scale = fraction.length - Number(exponent);
|
|
48
|
+
if (scale < 0) { digits *= 10n ** BigInt(-scale); scale = 0; }
|
|
49
|
+
return { digits, scale };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** Bounded plain decimal text as digits and scale; signs, exponents and spaces are refused. */
|
|
53
|
+
function textDecimal(text: string): Decimal | undefined {
|
|
54
|
+
const match = EXACT_TEXT.exec(text);
|
|
55
|
+
return match ? { digits: BigInt(`${match[1]}${match[2] ?? ""}`), scale: match[2]?.length ?? 0 } : undefined;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Exact value of a validated capacity: quoted decimals keep their text, and numbers (already
|
|
60
|
+
* rounded by JSON.parse) use their shortest decimal. Values outside the bounds, such as subnormal
|
|
61
|
+
* numbers or long quoted fractions, have no exact form and leave only the numeric projection.
|
|
62
|
+
*/
|
|
63
|
+
function exactCapacity(value: unknown): Decimal | undefined {
|
|
64
|
+
if (workBuddyCapacity(value) === undefined) return undefined;
|
|
65
|
+
const decimal = typeof value === "string" ? textDecimal(value) : numberDecimal(value as number);
|
|
66
|
+
return decimal && decimal.scale <= EXACT_SCALE ? decimal : undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Exact sum, aligned to the largest scale among the values. */
|
|
70
|
+
function addDecimals(values: readonly Decimal[]): Decimal {
|
|
71
|
+
const scale = Math.max(0, ...values.map(value => value.scale));
|
|
72
|
+
return { digits: values.reduce((sum, value) => sum + value.digits * 10n ** BigInt(scale - value.scale), 0n), scale };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function decimalNumber(value: Decimal): number {
|
|
76
|
+
return Number(`${value.digits}e-${value.scale}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Canonical plain text without trailing fractional zeros; undefined outside the exact bounds. */
|
|
80
|
+
function decimalText(value: Decimal): string | undefined {
|
|
81
|
+
if (value.digits < 0n) return undefined;
|
|
82
|
+
let { digits, scale } = value;
|
|
83
|
+
while (scale > 0 && digits % 10n === 0n) { digits /= 10n; scale--; }
|
|
84
|
+
const raw = digits.toString().padStart(scale + 1, "0");
|
|
85
|
+
const text = scale ? `${raw.slice(0, -scale)}.${raw.slice(-scale)}` : raw;
|
|
86
|
+
return textDecimal(text) ? text : undefined;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Exact `[numerator, denominator]` of bounded exact text, for display rounding. */
|
|
90
|
+
export function workBuddyExactRatio(text: string): [bigint, bigint] | undefined {
|
|
91
|
+
const value = textDecimal(text);
|
|
92
|
+
return value && [value.digits, 10n ** BigInt(value.scale)];
|
|
93
|
+
}
|
|
94
|
+
|
|
27
95
|
/** Sum bounded numeric capacities as decimals before converting the result back to a number. */
|
|
28
96
|
function sumCapacities(values: readonly number[]): number {
|
|
29
|
-
|
|
30
|
-
const [coefficient, exponent = "0"] = value.toString().split("e");
|
|
31
|
-
const [whole, fraction = ""] = coefficient!.split(".");
|
|
32
|
-
let digits = BigInt(`${whole}${fraction}`);
|
|
33
|
-
let scale = fraction.length - Number(exponent);
|
|
34
|
-
if (scale < 0) { digits *= 10n ** BigInt(-scale); scale = 0; }
|
|
35
|
-
return { digits, scale };
|
|
36
|
-
});
|
|
37
|
-
const scale = Math.max(0, ...parts.map(part => part.scale));
|
|
38
|
-
const digits = parts.reduce((sum, part) => sum + part.digits * 10n ** BigInt(scale - part.scale), 0n);
|
|
39
|
-
return Number(`${digits}e-${scale}`);
|
|
97
|
+
return decimalNumber(addDecimals(values.map(numberDecimal)));
|
|
40
98
|
}
|
|
41
99
|
|
|
42
100
|
function sumAmounts(rows: readonly WorkBuddyCreditAmount[]): WorkBuddyCreditAmount {
|
|
@@ -53,6 +111,29 @@ export function remainingWorkBuddyCredits(total: number, used: number, frozen =
|
|
|
53
111
|
return Math.max(0, sumCapacities([total, -used, -frozen]));
|
|
54
112
|
}
|
|
55
113
|
|
|
114
|
+
/** Exact remaining credits when the provider omits them, bounded below by zero. */
|
|
115
|
+
function exactRemaining(total: Decimal, used: Decimal, frozen: Decimal): Decimal {
|
|
116
|
+
const remaining = addDecimals([total, { ...used, digits: -used.digits }, { ...frozen, digits: -frozen.digits }]);
|
|
117
|
+
return remaining.digits < 0n ? ZERO : remaining;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Exact total/remaining for raw amounts, or undefined when any lacks a bounded exact form. */
|
|
121
|
+
export function workBuddyExactCredits(total: unknown, used: unknown): WorkBuddyExactCredits | undefined {
|
|
122
|
+
const exactTotal = exactCapacity(total), exactUsed = exactCapacity(used);
|
|
123
|
+
if (!exactTotal || !exactUsed) return undefined;
|
|
124
|
+
const totalText = decimalText(exactTotal), remainingText = decimalText(exactRemaining(exactTotal, exactUsed, ZERO));
|
|
125
|
+
return totalText !== undefined && remainingText !== undefined ? { total: totalText, remaining: remainingText } : undefined;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** Exact text must be bounded plain decimal text encoding the same numeric fields; null rejects. */
|
|
129
|
+
function exactCredits(value: unknown, balance: WorkBuddyCreditAmount): WorkBuddyExactCredits | undefined | null {
|
|
130
|
+
if (value === undefined) return undefined;
|
|
131
|
+
const row = workBuddyRecord(value), { total, remaining } = row;
|
|
132
|
+
if (Object.keys(row).length !== 2 || typeof total !== "string" || typeof remaining !== "string") return null;
|
|
133
|
+
if (!textDecimal(total) || !textDecimal(remaining)) return null;
|
|
134
|
+
return Number(total) === balance.total && Number(remaining) === balance.remaining ? { total, remaining } : null;
|
|
135
|
+
}
|
|
136
|
+
|
|
56
137
|
function amount(value: unknown): WorkBuddyCreditAmount | undefined {
|
|
57
138
|
const row = workBuddyRecord(value);
|
|
58
139
|
const total = workBuddyCapacity(row.total), used = workBuddyCapacity(row.used);
|
|
@@ -73,29 +154,57 @@ export function normalizeWorkBuddyCredits(value: unknown): WorkBuddyCreditBalanc
|
|
|
73
154
|
if (!quantities || !kind || seen.has(kind)) return undefined;
|
|
74
155
|
seen.add(kind); groups.push({ kind, ...quantities });
|
|
75
156
|
}
|
|
157
|
+
const exact = exactCredits(row.exact, balance);
|
|
158
|
+
if (exact === null) return undefined;
|
|
76
159
|
const expiring = workBuddyRecord(row.expiring), quantity = workBuddyCapacity(expiring.amount);
|
|
77
160
|
const at = typeof expiring.at === "number" && expiring.at > 0 && Number.isFinite(new Date(expiring.at).getTime()) ? expiring.at : undefined;
|
|
78
|
-
return { ...balance, groups, ...(
|
|
161
|
+
return { ...balance, groups, ...(exact ? { exact } : {}),
|
|
162
|
+
...(quantity !== undefined && quantity > 0 && at !== undefined ? { expiring: { amount: quantity, at } } : {}) };
|
|
79
163
|
}
|
|
80
164
|
|
|
81
|
-
|
|
165
|
+
interface PackageAmount extends WorkBuddyCreditAmount { exact?: { total: Decimal; remaining: Decimal } }
|
|
166
|
+
|
|
167
|
+
/** One summary package or credit group, with exact total/remaining when both have a bounded form. */
|
|
168
|
+
function packageAmount(row: Record<string, unknown>): PackageAmount | undefined {
|
|
82
169
|
const total = workBuddyCapacity(row.CycleTotalCapacity), used = workBuddyCapacity(row.CycleUsedCapacity);
|
|
83
170
|
const frozen = row.CycleFrozenCapacity === undefined ? 0 : workBuddyCapacity(row.CycleFrozenCapacity);
|
|
84
171
|
if (total === undefined || used === undefined || frozen === undefined) return undefined;
|
|
85
|
-
const
|
|
86
|
-
|
|
172
|
+
const estimated = row.CycleRemainCapacity === undefined;
|
|
173
|
+
const remaining = estimated ? remainingWorkBuddyCredits(total, used, frozen) : workBuddyCapacity(row.CycleRemainCapacity);
|
|
174
|
+
if (remaining === undefined) return undefined;
|
|
175
|
+
const exactTotal = exactCapacity(row.CycleTotalCapacity);
|
|
176
|
+
let exactLeft: Decimal | undefined;
|
|
177
|
+
if (!estimated) exactLeft = exactCapacity(row.CycleRemainCapacity);
|
|
178
|
+
else {
|
|
179
|
+
const exactUsed = exactCapacity(row.CycleUsedCapacity);
|
|
180
|
+
const exactFrozen = row.CycleFrozenCapacity === undefined ? ZERO : exactCapacity(row.CycleFrozenCapacity);
|
|
181
|
+
if (exactTotal && exactUsed && exactFrozen) exactLeft = exactRemaining(exactTotal, exactUsed, exactFrozen);
|
|
182
|
+
}
|
|
183
|
+
return { total, used, remaining, frozen, ...(exactTotal && exactLeft ? { exact: { total: exactTotal, remaining: exactLeft } } : {}) };
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Exact package sums, present only when every package has bounded exact amounts. */
|
|
187
|
+
function sumExact(rows: readonly PackageAmount[]): WorkBuddyExactCredits | undefined {
|
|
188
|
+
if (rows.some(row => !row.exact)) return undefined;
|
|
189
|
+
const total = decimalText(addDecimals(rows.map(row => row.exact!.total)));
|
|
190
|
+
const remaining = decimalText(addDecimals(rows.map(row => row.exact!.remaining)));
|
|
191
|
+
return total !== undefined && remaining !== undefined ? { total, remaining } : undefined;
|
|
87
192
|
}
|
|
88
193
|
|
|
194
|
+
/** Balance from the resource summary: Packages summed once, CreditGroups as a breakdown. */
|
|
89
195
|
export function parseWorkBuddyCredits(value: unknown): WorkBuddyCreditBalance | undefined {
|
|
90
196
|
const summary = workBuddyRecord(value);
|
|
91
197
|
if (!Array.isArray(summary.Packages) || summary.Packages.length > 512) return undefined;
|
|
92
|
-
const packages:
|
|
198
|
+
const packages: PackageAmount[] = [];
|
|
93
199
|
for (const raw of summary.Packages) {
|
|
94
200
|
const quantities = packageAmount(workBuddyRecord(raw));
|
|
95
201
|
if (!quantities) return undefined;
|
|
96
202
|
packages.push(quantities);
|
|
97
203
|
}
|
|
98
204
|
const balance: WorkBuddyCreditBalance = { ...sumAmounts(packages), groups: [] };
|
|
205
|
+
const exact = sumExact(packages);
|
|
206
|
+
// The numeric fields are the nearest numbers to the exact sums, which normalization re-checks.
|
|
207
|
+
if (exact) Object.assign(balance, { total: Number(exact.total), remaining: Number(exact.remaining), exact });
|
|
99
208
|
// CreditGroups is a breakdown of Packages, not another balance to add to it.
|
|
100
209
|
if (Array.isArray(summary.CreditGroups) && summary.CreditGroups.length <= 16) {
|
|
101
210
|
const grouped = new Map<WorkBuddyCreditKind, WorkBuddyCreditAmount[]>();
|