@bitkyc08/opencodex 2.100.0 → 2.100.2
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/gui/dist/assets/App-BpJOzw4F.js +59 -0
- package/gui/dist/assets/Tray-BcaI-VCr.js +1 -0
- package/gui/dist/assets/brand-mark-DU-0Vdkr.js +1 -0
- package/gui/dist/assets/index-Bbor_y80.js +94 -0
- package/gui/dist/assets/index-DJEkIDAi.css +2 -0
- package/gui/dist/assets/{segment-thumb-features-CcxZBnxv.js → segment-thumb-features-e9A_FogJ.js} +1 -1
- package/gui/dist/classic/assets/{App-aYgIQMxI.js → App-BrIlUiLc.js} +18 -18
- package/gui/dist/classic/assets/{Tray-D8jfUXpQ.js → Tray-DT146AhS.js} +1 -1
- package/gui/dist/classic/assets/index-DyJHagvT.js +94 -0
- package/gui/dist/classic/assets/quota-summary-CakPe9Ni.js +1 -0
- package/gui/dist/classic/index.html +1 -1
- package/gui/dist/index.html +2 -2
- package/package.json +2 -2
- package/src/adapters/anthropic-image-normalize.ts +1 -1
- package/src/adapters/client-fingerprint.ts +6 -4
- package/src/adapters/cursor/native-exec.ts +3 -2
- package/src/adapters/cursor/tool-guidance.ts +3 -3
- package/src/adapters/cursor/tool-wording.ts +10 -1
- package/src/adapters/devin/cloud-direct/tool-schema.ts +20 -2
- package/src/adapters/google-antigravity-wire.ts +13 -6
- package/src/adapters/google-truncation.ts +4 -2
- package/src/adapters/google.ts +8 -2
- package/src/adapters/openai-chat/mistral-image-limit.ts +28 -15
- package/src/adapters/openai-chat/tool-schema.ts +9 -0
- package/src/adapters/openai-chat-images.ts +100 -0
- package/src/adapters/openai-chat.ts +6 -9
- package/src/adapters/openai-responses/tool-schema.ts +18 -4
- package/src/adapters/run-turn-queue.ts +139 -5
- package/src/adapters/upstream-http-error.ts +4 -2
- package/src/bridge/sse.ts +8 -1
- package/src/claude/chat-tool-dispatch.ts +233 -0
- package/src/claude/inbound-tool-loading.ts +42 -17
- package/src/cli/account-api.ts +6 -0
- package/src/cli/account-extended.ts +60 -6
- package/src/cli/account-key-quota.ts +22 -2
- package/src/cli/account.ts +1 -1
- package/src/cli/capabilities-access-remote.ts +10 -0
- package/src/cli/capabilities-agents-routing.ts +2 -2
- package/src/cli/capabilities-base.ts +2 -2
- package/src/cli/claude.ts +19 -14
- package/src/cli/config-command.ts +24 -1
- package/src/cli/connect.ts +36 -3
- package/src/cli/gui-pair-client.ts +23 -2
- package/src/cli/help.ts +1 -1
- package/src/cli/hub.ts +18 -1
- package/src/cli/link-child-ops.ts +136 -0
- package/src/cli/link-status-child.ts +94 -0
- package/src/cli/link.ts +22 -9
- package/src/cli/registry.ts +3 -2
- package/src/cli/sync-command.ts +3 -1
- package/src/cli/sync-fanout.ts +8 -81
- package/src/client/link-readiness.ts +16 -6
- package/src/client/link-tunnel-status.ts +76 -0
- package/src/clients/config-export.ts +14 -1
- package/src/codex/account-resume-health.ts +41 -0
- package/src/codex/auth-api/login-flow.ts +6 -0
- package/src/codex/auth-api/routes.ts +35 -2
- package/src/codex/catalog/gather-capture.ts +2 -0
- package/src/codex/catalog/provider-models.ts +13 -8
- package/src/codex/convergence-types.ts +2 -0
- package/src/codex/quota.ts +111 -6
- package/src/combos/cooldown-store.ts +208 -0
- package/src/combos/failover.ts +432 -35
- package/src/config/salvage.ts +1 -0
- package/src/config/schema/config-schema.ts +6 -3
- package/src/config/schema/leaf-validators.ts +34 -12
- package/src/generated/compatibility-version.json +227 -135
- package/src/lib/catalog-etag.ts +10 -0
- package/src/lib/client-error-body.ts +15 -0
- package/src/lib/config-ownership.ts +9 -2
- package/src/lib/context-overflow-verdict.ts +266 -9
- package/src/lib/failure-detail.ts +72 -3
- package/src/lib/hard-refusal.ts +259 -0
- package/src/link/child-activity.ts +57 -0
- package/src/link/child-catalog-freshness.ts +149 -0
- package/src/link/child-gated-ocx.ts +117 -0
- package/src/link/child-observations.ts +205 -0
- package/src/link/child-observe.ts +121 -0
- package/src/link/child-ops-engine.ts +162 -0
- package/src/link/child-update-contract.ts +165 -0
- package/src/link/paths.ts +5 -0
- package/src/link/remote-windows.ts +42 -6
- package/src/link/ssh-argv.ts +126 -32
- package/src/link/status-projection.ts +73 -0
- package/src/link/sync-fanout-classify.ts +98 -0
- package/src/link/tunnel-state.ts +10 -4
- package/src/messaging/mcp-queue-rpc.ts +2 -1
- package/src/messaging/mcp-queue-server.ts +5 -0
- package/src/messaging/mcp-reply-tools.ts +24 -9
- package/src/messaging/mcp-reply-wait.ts +70 -0
- package/src/oauth/account-resume-health.ts +60 -0
- package/src/oauth/anthropic-model-quota.ts +12 -0
- package/src/oauth/anthropic-routing.ts +11 -4
- package/src/oauth/index.ts +1 -0
- package/src/oauth/kiro-iam-identity-center.ts +4 -1
- package/src/oauth/store.ts +44 -1
- package/src/providers/api-key-pause-state.ts +23 -0
- package/src/providers/api-key-pause.ts +68 -10
- package/src/providers/api-key-selection-capture.ts +3 -1
- package/src/providers/api-key-selection.ts +3 -2
- package/src/providers/api-keys.ts +18 -5
- package/src/providers/claude-cli-identity.ts +9 -3
- package/src/providers/claude-cli-usage-state.ts +11 -6
- package/src/providers/claude-cli-usage.ts +27 -8
- package/src/providers/codex-capacity.ts +11 -2
- package/src/providers/key-failover.ts +13 -6
- package/src/providers/model-discovery-config.ts +31 -0
- package/src/providers/model-discovery-diagnostic.ts +34 -3
- package/src/providers/model-discovery.ts +43 -7
- package/src/providers/model-rename-fields.ts +2 -0
- package/src/providers/openai-sidecar.ts +15 -2
- package/src/providers/provider-id-rewrite.ts +3 -0
- package/src/providers/quota/account-cache.ts +52 -34
- package/src/providers/quota/anthropic-family-headers.ts +8 -1
- package/src/providers/quota/anthropic-usage-windows.ts +66 -9
- package/src/providers/quota/report-cache.ts +53 -5
- package/src/providers/quota/vendor-probes-key.ts +73 -0
- package/src/providers/quota/vendor-probes-oauth.ts +57 -3
- package/src/providers/quota-key-accounts.ts +12 -5
- package/src/providers/quota-mistral-budget.ts +18 -0
- package/src/providers/quota-types.ts +32 -0
- package/src/providers/quota.ts +22 -22
- package/src/providers/reasoning-metadata.ts +1051 -12
- package/src/providers/registry/entries-extended.ts +3 -1
- package/src/providers/registry/model-ids.ts +1 -0
- package/src/providers/registry/types.ts +6 -0
- package/src/quota/reset-observer.ts +4 -2
- package/src/quota/reset-seen-store.ts +9 -0
- package/src/quota/window-mapping.ts +1 -0
- package/src/quota-pool/assemble.ts +4 -1
- package/src/responses/hosted-tool-policy.ts +56 -12
- package/src/responses/retained-compaction.ts +31 -5
- package/src/router.ts +2 -0
- package/src/server/auth-cors.ts +11 -8
- package/src/server/catalog-download.ts +3 -5
- package/src/server/chat-native.ts +11 -2
- package/src/server/claude-messages.ts +2 -1
- package/src/server/images.ts +41 -13
- package/src/server/index/link-listener.ts +16 -2
- package/src/server/index/link-relay-sessions.ts +43 -2
- package/src/server/index/optional-listeners.ts +18 -0
- package/src/server/management/config-routes.ts +7 -1
- package/src/server/management/context.ts +1 -1
- package/src/server/management/link-child-ops-routes.ts +116 -0
- package/src/server/management/link-route-state.ts +10 -0
- package/src/server/management/link-routes.ts +10 -0
- package/src/server/management/oauth-account-routes.ts +33 -4
- package/src/server/management/provider-overwrite-carry.ts +28 -3
- package/src/server/management/provider-routes.ts +16 -11
- package/src/server/management/route-registry.ts +3 -0
- package/src/server/messages-native.ts +5 -0
- package/src/server/request-log-failure-detail.ts +59 -1
- package/src/server/responses/adapter-dispatch.ts +35 -44
- package/src/server/responses/combo-stream-preflight.ts +146 -29
- package/src/server/responses/compact.ts +27 -4
- package/src/server/responses/context-overflow.ts +58 -2
- package/src/server/responses/core-combo-failure.ts +29 -4
- package/src/server/responses/core-combo-native.ts +3 -1
- package/src/server/responses/core-combo.ts +30 -3
- package/src/server/responses/core-errors.ts +3 -1
- package/src/server/responses/core-opaque-recovery.ts +45 -2
- package/src/server/responses/core-options.ts +12 -0
- package/src/server/responses/passthrough-dispatch.ts +30 -38
- package/src/server/responses/request-transport.ts +43 -14
- package/src/server/responses/reset-replay.ts +58 -2
- package/src/server/responses/run-turn-execution.ts +56 -30
- package/src/types/claude-tool-loading.ts +48 -0
- package/src/types/config.ts +5 -35
- package/src/types/provider.ts +21 -0
- package/src/types.ts +1 -0
- package/src/web-search/parse.ts +44 -4
- package/gui/dist/assets/App-CitvEefy.js +0 -59
- package/gui/dist/assets/Tray-CeKVWQyB.js +0 -1
- package/gui/dist/assets/brand-mark-M92UnxX2.js +0 -1
- package/gui/dist/assets/index-BP47do6-.js +0 -94
- package/gui/dist/assets/index-DmDooSAG.css +0 -2
- package/gui/dist/classic/assets/index-CfGqHooN.js +0 -94
- package/gui/dist/classic/assets/quota-summary-R-ih7OlS.js +0 -1
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { resolveProviderApiKey } from "./key-store";
|
|
2
|
+
import { isProviderApiKeyPaused, ProviderApiKeyPausedError } from "./api-key-pause";
|
|
2
3
|
import { createOpenAiSidecarCreditGuard } from "./openai-sidecar-credit";
|
|
3
4
|
import {
|
|
4
5
|
CodexPoolAuthenticationError,
|
|
@@ -57,6 +58,7 @@ export interface OpenAiImagesProviderSelection {
|
|
|
57
58
|
provider: OcxProviderConfig;
|
|
58
59
|
apiKey: string;
|
|
59
60
|
};
|
|
61
|
+
paused?: boolean;
|
|
60
62
|
error?: string;
|
|
61
63
|
}
|
|
62
64
|
|
|
@@ -288,7 +290,7 @@ export async function resolveFirstUsableOpenAiSidecar(
|
|
|
288
290
|
return undefined;
|
|
289
291
|
}
|
|
290
292
|
|
|
291
|
-
export function selectOpenAiImagesProvider(config: OcxConfig): OpenAiImagesProviderSelection {
|
|
293
|
+
export function selectOpenAiImagesProvider(config: OcxConfig, allowPausedActiveRecovery = false): OpenAiImagesProviderSelection {
|
|
292
294
|
const selection: OpenAiImagesProviderSelection = {
|
|
293
295
|
forwardCandidates: listOpenAiForwardSidecarCandidates(config),
|
|
294
296
|
};
|
|
@@ -300,6 +302,14 @@ export function selectOpenAiImagesProvider(config: OcxConfig): OpenAiImagesProvi
|
|
|
300
302
|
&& provider.authMode !== "forward"
|
|
301
303
|
&& provider.baseUrl.replace(/\/+$/, "") === "https://api.openai.com/v1"
|
|
302
304
|
) {
|
|
305
|
+
const canRecover = allowPausedActiveRecovery && provider.apiKeyPool?.some(entry => !entry.disabled);
|
|
306
|
+
if (isProviderApiKeyPaused(provider) && !canRecover) {
|
|
307
|
+
if (allowPausedActiveRecovery) {
|
|
308
|
+
selection.paused = true;
|
|
309
|
+
selection.error = new ProviderApiKeyPausedError().message;
|
|
310
|
+
}
|
|
311
|
+
return selection;
|
|
312
|
+
}
|
|
303
313
|
const apiKey = resolveProviderApiKey(provider.apiKey)?.trim();
|
|
304
314
|
if (apiKey) selection.keyed = { providerName: OPENAI_API_PROVIDER_ID, provider, apiKey };
|
|
305
315
|
}
|
|
@@ -309,7 +319,7 @@ export function selectOpenAiImagesProvider(config: OcxConfig): OpenAiImagesProvi
|
|
|
309
319
|
/** Resolve an explicit custom Images provider, otherwise preserve the existing OpenAI fallback. */
|
|
310
320
|
export function selectImagesProvider(config: OcxConfig): OpenAiImagesProviderSelection {
|
|
311
321
|
const configuredProvider = config.images?.provider;
|
|
312
|
-
if (configuredProvider === undefined) return selectOpenAiImagesProvider(config);
|
|
322
|
+
if (configuredProvider === undefined) return selectOpenAiImagesProvider(config, true);
|
|
313
323
|
if (typeof configuredProvider !== "string" || !configuredProvider.trim()) {
|
|
314
324
|
return { forwardCandidates: [], error: "images.provider must be a nonblank provider name" };
|
|
315
325
|
}
|
|
@@ -337,6 +347,9 @@ export function selectImagesProvider(config: OcxConfig): OpenAiImagesProviderSel
|
|
|
337
347
|
error: `images.provider "${providerName}" must be an API-key openai-responses provider`,
|
|
338
348
|
};
|
|
339
349
|
}
|
|
350
|
+
if (provider.apiKeyPool?.length && provider.apiKeyPool.every(entry => entry.disabled === true)) {
|
|
351
|
+
return { forwardCandidates: [], paused: true, error: new ProviderApiKeyPausedError().message };
|
|
352
|
+
}
|
|
340
353
|
|
|
341
354
|
const apiKey = resolveProviderApiKey(provider.apiKey)?.trim();
|
|
342
355
|
if (!apiKey) {
|
|
@@ -98,6 +98,9 @@ export function rewriteProviderReferences(config: OcxConfig, from: string, to: s
|
|
|
98
98
|
if (config.claudeCode?.appendOnlyToolLoadingModels) {
|
|
99
99
|
config.claudeCode.appendOnlyToolLoadingModels = config.claudeCode.appendOnlyToolLoadingModels.map(id => route(id) ?? id);
|
|
100
100
|
}
|
|
101
|
+
if (config.claudeCode?.chatToolDispatchModels) {
|
|
102
|
+
config.claudeCode.chatToolDispatchModels = config.claudeCode.chatToolDispatchModels.map(id => route(id) ?? id);
|
|
103
|
+
}
|
|
101
104
|
// First-party picker bindings hold routes too; their keys are Anthropic picker ids.
|
|
102
105
|
routeRecordValues(config.claudeCode?.intercept?.modelMap);
|
|
103
106
|
|
|
@@ -17,7 +17,7 @@ import { replaceCachedProviderQuotas } from "../quota-routing-cache";
|
|
|
17
17
|
import { getProviderRegistryEntry } from "../registry";
|
|
18
18
|
import { getProviderQuotaReportCache, hasQuotaRows, routingEvidence, setProviderQuotaReportCache } from "./report-cache";
|
|
19
19
|
import { isCanonicalCommandCodeBaseUrl, isCanonicalKimiCodeBaseUrl } from "./vendor-probes-key";
|
|
20
|
-
import type
|
|
20
|
+
import { isWeeklyAllowancePercent, type AccountQuotaMode, type ProviderQuota, type ProviderQuotaWindow, type QuotaFailureCode } from "../quota-types";
|
|
21
21
|
import type { OcxConfig, OcxProviderConfig } from "../../types";
|
|
22
22
|
|
|
23
23
|
/** Match oauth/index REFRESH_SKEW_MS — use stored access without refresh when still fresh. */
|
|
@@ -44,11 +44,45 @@ export type AccountQuotaCacheEntry = {
|
|
|
44
44
|
anthropicCredentialGeneration?: string;
|
|
45
45
|
isCurrent?: () => boolean;
|
|
46
46
|
};
|
|
47
|
+
const validReset = (resetAt: unknown): resetAt is number => typeof resetAt === "number"
|
|
48
|
+
&& Number.isFinite(resetAt) && resetAt > 0 && Number.isFinite(new Date(resetAt).getTime());
|
|
49
|
+
|
|
50
|
+
/** Persisted rows validate only the outer quota object, so window data may be malformed. Null when unchanged. */
|
|
51
|
+
function retainedQuotaWindows(value: unknown, now: number): ProviderQuotaWindow[] | null {
|
|
52
|
+
const windows: ProviderQuotaWindow[] = Array.isArray(value) ? value : [];
|
|
53
|
+
const retained: ProviderQuotaWindow[] = [];
|
|
54
|
+
let changed = !Array.isArray(value);
|
|
55
|
+
for (const window of windows) {
|
|
56
|
+
if (!window || typeof window !== "object" || typeof window.label !== "string" || !window.label.trim()
|
|
57
|
+
|| typeof window.percent !== "number" || !Number.isFinite(window.percent)
|
|
58
|
+
|| window.percent < 0 || window.percent > 100) {
|
|
59
|
+
changed = true;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if ((window.passiveObservedAt !== undefined && (typeof window.passiveObservedAt !== "number"
|
|
63
|
+
|| !Number.isFinite(window.passiveObservedAt) || window.passiveObservedAt <= 0 || window.passiveObservedAt > now
|
|
64
|
+
|| now - window.passiveObservedAt >= ANTHROPIC_PASSIVE_FAMILY_MAX_AGE_MS))
|
|
65
|
+
|| validReset(window.resetAt) && window.resetAt <= now) {
|
|
66
|
+
changed = true;
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
const normalized = { ...window };
|
|
70
|
+
if (window.resetAt !== undefined && !validReset(window.resetAt)) delete normalized.resetAt;
|
|
71
|
+
// A hand-edited share outside (0, 100] is dropped; the measurement itself stays usable.
|
|
72
|
+
if (window.weeklyAllowancePercent !== undefined && !isWeeklyAllowancePercent(window.weeklyAllowancePercent)) {
|
|
73
|
+
delete normalized.weeklyAllowancePercent;
|
|
74
|
+
}
|
|
75
|
+
const rewritten = "resetAt" in window !== "resetAt" in normalized
|
|
76
|
+
|| "weeklyAllowancePercent" in window !== "weeklyAllowancePercent" in normalized;
|
|
77
|
+
retained.push(rewritten ? normalized : window);
|
|
78
|
+
if (rewritten) changed = true;
|
|
79
|
+
}
|
|
80
|
+
return changed ? retained : null;
|
|
81
|
+
}
|
|
82
|
+
|
|
47
83
|
/** Expired measurements become unknown; missing reset evidence never implies a fresh allowance. */
|
|
48
84
|
export function normalizeAnthropicQuota(quota: ProviderQuota | null | undefined, now: number): ProviderQuota | null {
|
|
49
85
|
if (!quota) return null;
|
|
50
|
-
const validReset = (resetAt: unknown): resetAt is number => typeof resetAt === "number"
|
|
51
|
-
&& Number.isFinite(resetAt) && resetAt > 0 && Number.isFinite(new Date(resetAt).getTime());
|
|
52
86
|
let result = quota;
|
|
53
87
|
for (const [percent, reset] of [
|
|
54
88
|
["fiveHourPercent", "fiveHourResetAt"],
|
|
@@ -63,38 +97,22 @@ export function normalizeAnthropicQuota(quota: ProviderQuota | null | undefined,
|
|
|
63
97
|
if (valid) delete result[percent];
|
|
64
98
|
delete result[reset];
|
|
65
99
|
}
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
78
|
-
if ((window.passiveObservedAt !== undefined && (typeof window.passiveObservedAt !== "number"
|
|
79
|
-
|| !Number.isFinite(window.passiveObservedAt) || window.passiveObservedAt <= 0 || window.passiveObservedAt > now
|
|
80
|
-
|| now - window.passiveObservedAt >= ANTHROPIC_PASSIVE_FAMILY_MAX_AGE_MS))
|
|
81
|
-
|| validReset(window.resetAt) && window.resetAt <= now) {
|
|
82
|
-
changed = true;
|
|
83
|
-
continue;
|
|
84
|
-
}
|
|
85
|
-
if (window.resetAt !== undefined && !validReset(window.resetAt)) {
|
|
86
|
-
const normalized = { ...window };
|
|
87
|
-
delete normalized.resetAt;
|
|
88
|
-
retained.push(normalized);
|
|
89
|
-
changed = true;
|
|
90
|
-
} else {
|
|
91
|
-
retained.push(window);
|
|
92
|
-
}
|
|
100
|
+
for (const field of ["customWindows", "displayWindows"] as const) {
|
|
101
|
+
// Read the caller's original object; `result` may already be a copy with other fields rewritten.
|
|
102
|
+
if (quota[field] === undefined) {
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const retained = retainedQuotaWindows(quota[field], now);
|
|
106
|
+
if (!retained) {
|
|
107
|
+
continue;
|
|
108
|
+
}
|
|
109
|
+
if (result === quota) {
|
|
110
|
+
result = { ...quota };
|
|
93
111
|
}
|
|
94
|
-
if (
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
112
|
+
if (retained.length) {
|
|
113
|
+
result[field] = retained;
|
|
114
|
+
} else {
|
|
115
|
+
delete result[field];
|
|
98
116
|
}
|
|
99
117
|
}
|
|
100
118
|
return hasQuotaRows(result) ? result : null;
|
|
@@ -14,7 +14,14 @@ export function parseAnthropicFamilyHeaders(headers: Headers, now: number, statu
|
|
|
14
14
|
...(resetAt !== undefined && resetAt > 0 && Number.isFinite(new Date(resetAt).getTime()) ? { resetAt } : {}) }];
|
|
15
15
|
}
|
|
16
16
|
export function mergeAnthropicFamilyWindows(previous: ProviderQuotaWindow[] = [], observed: ProviderQuotaWindow[] = []): ProviderQuotaWindow[] {
|
|
17
|
-
|
|
17
|
+
const same = (a: ProviderQuotaWindow, b: ProviderQuotaWindow) => a.label === b.label && a.scope === b.scope;
|
|
18
|
+
// Headers carry no allowance; the share is a seat policy the last usage probe already read.
|
|
19
|
+
// A probe window (no passiveObservedAt) is itself that reading, so a missing share stays missing.
|
|
20
|
+
return [...previous.filter(window => !observed.some(update => same(update, window))), ...observed.map(update => {
|
|
21
|
+
const allowance = update.weeklyAllowancePercent === undefined && update.passiveObservedAt !== undefined
|
|
22
|
+
? previous.find(window => same(window, update))?.weeklyAllowancePercent : undefined;
|
|
23
|
+
return allowance === undefined ? update : { ...update, weeklyAllowancePercent: allowance };
|
|
24
|
+
})];
|
|
18
25
|
}
|
|
19
26
|
|
|
20
27
|
const enumerated = new WeakSet<object>();
|
|
@@ -6,6 +6,8 @@ export interface AnthropicUsageBucket {
|
|
|
6
6
|
window: UsageWindow;
|
|
7
7
|
row: Record<string, unknown>;
|
|
8
8
|
percentField: "percent" | "utilization";
|
|
9
|
+
/** Share of the weekly limit this scoped family may consume, from `weekly_scoped_shares`. */
|
|
10
|
+
weeklyAllowancePercent?: number;
|
|
9
11
|
}
|
|
10
12
|
const legacyFields = { "5h": "five_hour", weekly: "seven_day", fable: "seven_day_fable",
|
|
11
13
|
opus: "seven_day_opus", sonnet: "seven_day_sonnet" } as const;
|
|
@@ -18,21 +20,65 @@ function scopedFamily(row: Record<string, unknown>): "fable" | "opus" | "sonnet"
|
|
|
18
20
|
return (["fable", "opus", "sonnet"] as const).find(family => label.includes(family));
|
|
19
21
|
}
|
|
20
22
|
|
|
23
|
+
/**
|
|
24
|
+
* A family window's usage restated on the shared weekly scale.
|
|
25
|
+
*
|
|
26
|
+
* A scoped percent is relative to the family's own allowance: Fable at 60% of an allowance
|
|
27
|
+
* that is 50% of the week has 20 weekly points left, not 40. Ranking that compares a family
|
|
28
|
+
* request across accounts must use this figure alongside the shared weekly percent; a window
|
|
29
|
+
* without a valid allowance keeps its own percent. 100 maps to 100, so exhaustion is unchanged.
|
|
30
|
+
*/
|
|
31
|
+
export function familyWeeklyEquivalentPercent(window: { percent?: number; weeklyAllowancePercent?: number }): number | undefined {
|
|
32
|
+
const percent = window.percent;
|
|
33
|
+
if (typeof percent !== "number" || !Number.isFinite(percent)) return undefined;
|
|
34
|
+
const allowance = window.weeklyAllowancePercent;
|
|
35
|
+
if (typeof allowance !== "number" || !Number.isFinite(allowance) || allowance <= 0 || allowance > 100) return percent;
|
|
36
|
+
const used = Math.max(0, Math.min(100, percent));
|
|
37
|
+
return percent >= 100 ? percent : 100 - allowance * (100 - used) / 100;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* `weekly_scoped_shares[]` names, by raw `limits` index, the share of the weekly limit a scoped
|
|
42
|
+
* row may consume (Fable: "up to 50% of your weekly limit"). Only a recognized scoped row,
|
|
43
|
+
* routed or display-only, receives it; a malformed, out-of-range or conflicting share is ignored.
|
|
44
|
+
*/
|
|
45
|
+
function applyWeeklyShares(body: Record<string, unknown>, scopedRows: Map<number, AnthropicUsageBucket>): void {
|
|
46
|
+
if (!Array.isArray(body.weekly_scoped_shares)) return;
|
|
47
|
+
const conflicted = new Set<AnthropicUsageBucket>();
|
|
48
|
+
for (const raw of body.weekly_scoped_shares) {
|
|
49
|
+
const share = asRecord(raw);
|
|
50
|
+
const index = share?.limit_index;
|
|
51
|
+
const allowance = toFiniteNumber(share?.allowance_percent_of_weekly);
|
|
52
|
+
if (typeof index !== "number" || !Number.isInteger(index) || allowance === undefined || allowance <= 0 || allowance > 100) continue;
|
|
53
|
+
const bucket = scopedRows.get(index);
|
|
54
|
+
if (!bucket || conflicted.has(bucket)) continue;
|
|
55
|
+
if (bucket.weeklyAllowancePercent !== undefined && bucket.weeklyAllowancePercent !== allowance) {
|
|
56
|
+
delete bucket.weeklyAllowancePercent;
|
|
57
|
+
conflicted.add(bucket);
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
bucket.weeklyAllowancePercent = allowance;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
21
64
|
/**
|
|
22
65
|
* Recognized rows supersede legacy duplicates even when skipped or malformed; duplicates
|
|
23
66
|
* and malformed shared measurements make family enumeration incomplete. Shared finite
|
|
24
67
|
* measurements apply regardless of the binding flag, though an unknown flag also makes
|
|
25
68
|
* enumeration incomplete. A null legacy five_hour requires an explicitly active session.
|
|
26
|
-
* Scoped rows retain active-only behavior;
|
|
69
|
+
* Scoped rows retain active-only behavior for routing; an inactive scoped row is returned
|
|
70
|
+
* separately as display-only evidence. Unknown kinds/families cannot clear refusals.
|
|
27
71
|
*/
|
|
28
72
|
export function anthropicUsageBuckets(body: Record<string, unknown>): {
|
|
29
|
-
buckets: AnthropicUsageBucket[]; familyEnumeration: boolean;
|
|
73
|
+
buckets: AnthropicUsageBucket[]; displayBuckets: AnthropicUsageBucket[]; familyEnumeration: boolean;
|
|
30
74
|
} {
|
|
31
75
|
const selected = new Map<UsageWindow, AnthropicUsageBucket>();
|
|
76
|
+
const displayOnly = new Map<UsageWindow, AnthropicUsageBucket>();
|
|
32
77
|
const represented = new Set<UsageWindow>();
|
|
78
|
+
const scopedRows = new Map<number, AnthropicUsageBucket>();
|
|
33
79
|
const limits = Array.isArray(body.limits) ? body.limits : [];
|
|
34
80
|
let familyEnumeration = Array.isArray(body.limits);
|
|
35
|
-
for (const raw of limits) {
|
|
81
|
+
for (const [index, raw] of limits.entries()) {
|
|
36
82
|
const row = asRecord(raw);
|
|
37
83
|
const window = row?.kind === "session" ? "5h" : row?.kind === "weekly_all" ? "weekly"
|
|
38
84
|
: row?.kind === "weekly_scoped" ? scopedFamily(row) : undefined;
|
|
@@ -47,19 +93,30 @@ export function anthropicUsageBuckets(body: Record<string, unknown>): {
|
|
|
47
93
|
selected.set(window, { window, row, percentField: "percent" });
|
|
48
94
|
continue;
|
|
49
95
|
}
|
|
50
|
-
if (row.is_active === false)
|
|
96
|
+
if (row.is_active === false) {
|
|
97
|
+
// Display-only rows still carry their share, so a dashboard can say "up to 50% of the week".
|
|
98
|
+
const bucket: AnthropicUsageBucket = { window, row, percentField: "percent" };
|
|
99
|
+
displayOnly.set(window, bucket);
|
|
100
|
+
scopedRows.set(index, bucket);
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
51
103
|
if (row.is_active !== undefined && row.is_active !== true) { familyEnumeration = false; continue; }
|
|
52
104
|
if (toFiniteNumber(row.percent) === undefined) familyEnumeration = false;
|
|
53
|
-
|
|
105
|
+
const bucket: AnthropicUsageBucket = { window, row, percentField: "percent" };
|
|
106
|
+
selected.set(window, bucket);
|
|
107
|
+
scopedRows.set(index, bucket);
|
|
54
108
|
}
|
|
109
|
+
applyWeeklyShares(body, scopedRows);
|
|
55
110
|
for (const window of Object.keys(legacyFields) as UsageWindow[]) {
|
|
56
111
|
if (represented.has(window)) continue;
|
|
57
112
|
const row = asRecord(body[legacyFields[window]]);
|
|
58
113
|
if (row) selected.set(window, { window, row, percentField: "utilization" });
|
|
59
114
|
}
|
|
60
115
|
// Stable canonical order, independent of how upstream orders limits.
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
116
|
+
const ordered = (source: Map<UsageWindow, AnthropicUsageBucket>) => (Object.keys(legacyFields) as UsageWindow[])
|
|
117
|
+
.flatMap(window => {
|
|
118
|
+
const bucket = source.get(window);
|
|
119
|
+
return bucket ? [bucket] : [];
|
|
120
|
+
});
|
|
121
|
+
return { buckets: ordered(selected), displayBuckets: ordered(displayOnly), familyEnumeration };
|
|
65
122
|
}
|
|
@@ -6,7 +6,8 @@ import { effectiveCodexAuthAccountId, listCodexAuthAccountsSnapshot } from "../.
|
|
|
6
6
|
import { CODEX_EXHAUSTED_USAGE_PERCENT, withoutRetiredCodexQuota, type StoredAccountQuota } from "../../codex/quota";
|
|
7
7
|
import { isMainAccountIdentityGenerationLive } from "../../codex/main-account-cache";
|
|
8
8
|
import { codexPlanKey } from "../../codex/plan";
|
|
9
|
-
import { resolveProviderApiKey } from "../key-store";
|
|
9
|
+
import { isKeychainReference, resolveProviderApiKey } from "../key-store";
|
|
10
|
+
import { resolveEnvValue } from "../../config/proxy-env";
|
|
10
11
|
import { apiKeyPoolEntryId } from "../api-keys";
|
|
11
12
|
import { getProviderRegistryEntry, providerCodexAccountMode } from "../registry";
|
|
12
13
|
import { isCanonicalOpenAiForwardProvider, OPENAI_CODEX_PROVIDER_ID } from "../openai-tiers";
|
|
@@ -21,7 +22,42 @@ import type { ProviderQuota, ProviderRoutingQuota } from "../quota-types";
|
|
|
21
22
|
export const LAST_GOOD_MAX_AGE_MS = CODEX_CAPACITY_MAX_QUOTA_AGE_MS;
|
|
22
23
|
const nativeMainReportGenerations = new WeakMap<ProviderQuotaReport, number>();
|
|
23
24
|
export const accountReportCurrent = new WeakMap<ProviderQuotaReport, () => boolean>();
|
|
25
|
+
/** The measured quota a reset detector should observe when the shown quota is an estimate (pooled rows). */
|
|
26
|
+
export const observedQuotaFor = new WeakMap<ProviderQuotaReport, ProviderQuota>();
|
|
24
27
|
export const routingEvidence = new WeakMap<ProviderQuotaReport, ProviderQuotaRoutingEvidence>();
|
|
28
|
+
/**
|
|
29
|
+
* Credential identity captured by a probe that opted into binding; never serialized with the
|
|
30
|
+
* report. Only producers whose report must not outlive its credential register here (#8290),
|
|
31
|
+
* so a provider that did not opt in keeps its dev-era cache and join behaviour unchanged.
|
|
32
|
+
*/
|
|
33
|
+
export const keyReportCredentialIds = new WeakMap<ProviderQuotaReport, string>();
|
|
34
|
+
const keyReportDestinations = new WeakMap<ProviderQuotaReport, { adapter: string; baseUrl: string }>();
|
|
35
|
+
/**
|
|
36
|
+
* Whether a probe-bound report still describes the provider as it is configured NOW.
|
|
37
|
+
*
|
|
38
|
+
* A report is published only for the credential and destination that produced it. The
|
|
39
|
+
* comparison is a full digest: the 8-character apiKeyPoolEntryId is a cache discriminator,
|
|
40
|
+
* not an identity, and two distinct keys can share it.
|
|
41
|
+
*/
|
|
42
|
+
export function keyReportCredentialCurrent(value: ProviderQuotaReport, provider: OcxProviderConfig | undefined, passive = false): boolean {
|
|
43
|
+
const captured = keyReportCredentialIds.get(value);
|
|
44
|
+
if (!captured) return true;
|
|
45
|
+
if (!provider || provider.disabled || (provider.authMode ?? "key") !== "key") return false;
|
|
46
|
+
const destination = keyReportDestinations.get(value);
|
|
47
|
+
if (!destination || destination.adapter !== provider.adapter || destination.baseUrl !== provider.baseUrl) return false;
|
|
48
|
+
// A passive read cannot open the OS keychain or publish credential observations.
|
|
49
|
+
if (passive && isKeychainReference(provider.apiKey)) return false;
|
|
50
|
+
const current = (passive ? resolveEnvValue(provider.apiKey) : resolveProviderApiKey(provider.apiKey))?.trim();
|
|
51
|
+
return !!current && createHash("sha256").update(current).digest("hex") === captured;
|
|
52
|
+
}
|
|
53
|
+
/** Validate joined results against the joining caller's independently mutable configuration. */
|
|
54
|
+
export function validateJoinedReports(response: ProviderQuotaResponse, config: OcxConfig): ProviderQuotaResponse {
|
|
55
|
+
return { ...response, reports: response.reports.filter(item => {
|
|
56
|
+
const provider = config.providers[item.provider];
|
|
57
|
+
return !!provider && !provider.disabled && isProviderQuotaReportCurrent(item)
|
|
58
|
+
&& keyReportCredentialCurrent(item, provider);
|
|
59
|
+
}) };
|
|
60
|
+
}
|
|
25
61
|
/** Only the live Antigravity probe binds this projection; display/last-good rows cannot create it. */
|
|
26
62
|
export const antigravityEvidence = new WeakMap<ProviderQuotaReport, { receipt: AntigravityQuotaReceipt; windows: readonly DecisionQuotaWindow[] }>();
|
|
27
63
|
export let providerQuotaBeforePublishForTests: (() => void | Promise<void>) | null = null;
|
|
@@ -136,6 +172,9 @@ function cacheKey(config: OcxConfig): string {
|
|
|
136
172
|
const resolvedKey = typeof provider.apiKey === "string"
|
|
137
173
|
? resolveProviderApiKey(provider.apiKey)?.trim()
|
|
138
174
|
: undefined;
|
|
175
|
+
// The 8-char pool id is a cheap discriminator, not an identity: two keys can share it.
|
|
176
|
+
// A probe-bound report is re-validated against its captured full digest
|
|
177
|
+
// (keyReportCredentialCurrent), so a collision cannot serve the other key's budgets.
|
|
139
178
|
const activeKeyId = resolvedKey ? apiKeyPoolEntryId(resolvedKey) : "none";
|
|
140
179
|
return `${name}:${provider.adapter}:${provider.authMode ?? "key"}:${providerCodexAccountMode(name, provider) ?? "none"}:${provider.disabled === true ? "off" : "on"}:${provider.baseUrl}:${activeKeyId}`;
|
|
141
180
|
})
|
|
@@ -266,6 +305,7 @@ export function publicCapacityAggregation(
|
|
|
266
305
|
export function hasQuotaRows(quota: ProviderQuota | null | undefined): quota is ProviderQuota {
|
|
267
306
|
if (!quota) return false;
|
|
268
307
|
return typeof quota.fiveHourPercent === "number"
|
|
308
|
+
|| (quota.unknownBudgetWindows?.length ?? 0) > 0
|
|
269
309
|
|| typeof quota.weeklyPercent === "number"
|
|
270
310
|
|| typeof quota.monthlyPercent === "number"
|
|
271
311
|
|| quota.creditsUsd?.unlimited === true
|
|
@@ -321,9 +361,15 @@ export function keyReport(
|
|
|
321
361
|
config: OcxProviderConfig,
|
|
322
362
|
probedCredential: string,
|
|
323
363
|
inferenceQuota?: ProviderQuota,
|
|
364
|
+
options?: { bindCredential?: boolean },
|
|
324
365
|
): ProviderQuotaReport | null {
|
|
325
366
|
const result = report(provider, source, quota);
|
|
326
|
-
if (!result
|
|
367
|
+
if (!result) return result;
|
|
368
|
+
if (options?.bindCredential === true) {
|
|
369
|
+
keyReportCredentialIds.set(result, createHash("sha256").update(probedCredential).digest("hex"));
|
|
370
|
+
keyReportDestinations.set(result, { adapter: config.adapter, baseUrl: config.baseUrl });
|
|
371
|
+
}
|
|
372
|
+
if (!inferenceQuota) return result;
|
|
327
373
|
const binding = providerQuotaRoutingBinding(provider, config, probedCredential);
|
|
328
374
|
if (binding) routingEvidence.set(result, { quota: inferenceQuota, binding });
|
|
329
375
|
return result;
|
|
@@ -386,11 +432,13 @@ export function publishCollectedDecisionQuota(reports: ProviderQuotaReport[], co
|
|
|
386
432
|
* no probe, token refresh, account snapshot or publication into routing evidence. The Home's own
|
|
387
433
|
* dashboard and traffic keep the cache current.
|
|
388
434
|
*/
|
|
389
|
-
export function heldProviderQuotaReports(
|
|
435
|
+
export function heldProviderQuotaReports(config: OcxConfig): ProviderQuotaResponse {
|
|
390
436
|
const held = getProviderQuotaReportCache()?.response;
|
|
391
|
-
const configured = new Set(configuredProviders);
|
|
392
437
|
return {
|
|
393
438
|
generatedAt: held?.generatedAt ?? Date.now(),
|
|
394
|
-
reports: (held?.reports ?? []).filter(item =>
|
|
439
|
+
reports: (held?.reports ?? []).filter(item => {
|
|
440
|
+
const provider = config.providers[item.provider];
|
|
441
|
+
return !!provider && isProviderQuotaReportCurrent(item) && keyReportCredentialCurrent(item, provider, true);
|
|
442
|
+
}),
|
|
395
443
|
};
|
|
396
444
|
}
|
|
@@ -15,6 +15,7 @@ import {
|
|
|
15
15
|
} from "./report-cache";
|
|
16
16
|
import { getTokenForAccountQuotaProbe } from "./account-cache";
|
|
17
17
|
import type { AccountQuotaMode, ProviderQuota, ProviderQuotaCreditsUsd } from "../quota-types";
|
|
18
|
+
import { markDisplayOnlyQuota } from "../quota-types";
|
|
18
19
|
import type { OcxProviderConfig } from "../../types";
|
|
19
20
|
|
|
20
21
|
// A quota probe must use the provider's inference route so it neither reports a false healthy path nor leaks a key through another exit.
|
|
@@ -41,6 +42,7 @@ const OPENCODE_GO_BASE_URL = "https://opencode.ai/zen/go/v1";
|
|
|
41
42
|
const OPENCODE_GO_USAGE_URL = `${OPENCODE_GO_BASE_URL}/usage`;
|
|
42
43
|
const OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
|
|
43
44
|
const DEEPSEEK_BASE_URL = "https://api.deepseek.com";
|
|
45
|
+
const MISTRAL_BASE_URL = "https://api.mistral.ai";
|
|
44
46
|
const CLINE_BASE_URL = "https://api.cline.bot";
|
|
45
47
|
const OLLAMA_CLOUD_BASE_URL = "https://ollama.com";
|
|
46
48
|
const OLLAMA_CLOUD_USAGE_URL = `${OLLAMA_CLOUD_BASE_URL}/api/usage`;
|
|
@@ -76,6 +78,74 @@ function isCanonicalDeepSeekBaseUrl(baseUrl: string): boolean {
|
|
|
76
78
|
return normalized === DEEPSEEK_BASE_URL || normalized === `${DEEPSEEK_BASE_URL}/v1`;
|
|
77
79
|
}
|
|
78
80
|
|
|
81
|
+
/** Only the exact HTTPS origin, optionally with the `/v1` API root: no credentials, port, query or fragment. */
|
|
82
|
+
function isCanonicalMistralBaseUrl(baseUrl: string): boolean {
|
|
83
|
+
const normalized = normalizedBaseUrl(baseUrl);
|
|
84
|
+
return normalized === MISTRAL_BASE_URL || normalized === `${MISTRAL_BASE_URL}/v1`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const MISTRAL_PLAN_NAMES = new Set(["FREE", "INDIVIDUAL", "EDU", "TEAM"]);
|
|
88
|
+
const MISTRAL_BUDGETS = [["api_budget", "API budget"], ["vibe_budget", "Vibe budget"]] as const;
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Mistral Studio/Vibe budgets (#8290).
|
|
92
|
+
*
|
|
93
|
+
* Display-only: the result never carries routing evidence, so neither key ranking nor the
|
|
94
|
+
* passive quota pool may spend or order a key from it. The destination is fixed and canonical,
|
|
95
|
+
* the request rides the provider's own egress, redirects are refused, and the body is bounded
|
|
96
|
+
* by readQuotaJson. A denial (401/403 and other non-retryable client statuses) is terminal and
|
|
97
|
+
* suppresses the previous row; transport trouble, 408, 429 and 5xx are transient and keep it.
|
|
98
|
+
*/
|
|
99
|
+
async function fetchMistralQuota(provider: string, config: OcxProviderConfig): Promise<ProviderQuotaProbeResult> {
|
|
100
|
+
if (!isCanonicalMistralBaseUrl(config.baseUrl)) return null;
|
|
101
|
+
const apiKey = resolveProviderApiKey(config.apiKey)?.trim();
|
|
102
|
+
if (!apiKey) return null;
|
|
103
|
+
const init: RequestInit = {
|
|
104
|
+
headers: { Accept: "application/json", Authorization: `Bearer ${apiKey}` },
|
|
105
|
+
redirect: "error", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
106
|
+
};
|
|
107
|
+
const settled = await Promise.allSettled([
|
|
108
|
+
quotaFetch(provider, config, `${MISTRAL_BASE_URL}/v1/billing/budget`, init),
|
|
109
|
+
quotaFetch(provider, config, `${MISTRAL_BASE_URL}/v1/billing/subscription`, init),
|
|
110
|
+
]);
|
|
111
|
+
const responses = settled.flatMap(result => result.status === "fulfilled" ? [result.value] : []);
|
|
112
|
+
// 402 is a billing refusal of the reading, not proof that the credential is invalid: the
|
|
113
|
+
// plan may be exhausted or the billing endpoint may be gated. Keep the last-good row, as for
|
|
114
|
+
// 408/429, instead of erasing the measured budgets on a payment-required response.
|
|
115
|
+
if (responses.some(response => response.status >= 400 && response.status < 500 && response.status !== 402 && response.status !== 408 && response.status !== 429)) return TERMINAL_QUOTA_FAILURE;
|
|
116
|
+
if (responses.length !== 2 || responses.some(response => !response.ok)) return null;
|
|
117
|
+
const [budgetResponse, subscriptionResponse] = responses as [Response, Response];
|
|
118
|
+
const [budgetValue, subscriptionValue] = await Promise.all([
|
|
119
|
+
readQuotaJson(budgetResponse), readQuotaJson(subscriptionResponse),
|
|
120
|
+
]);
|
|
121
|
+
if (budgetValue === QUOTA_JSON_READ_FAILURE || subscriptionValue === QUOTA_JSON_READ_FAILURE) return null;
|
|
122
|
+
const budget = asRecord(budgetValue);
|
|
123
|
+
const subscription = asRecord(subscriptionValue);
|
|
124
|
+
if (!budget || !subscription) return null;
|
|
125
|
+
const plan = typeof subscription.plan_name === "string" && MISTRAL_PLAN_NAMES.has(subscription.plan_name)
|
|
126
|
+
? subscription.plan_name : undefined;
|
|
127
|
+
const customWindows: NonNullable<ProviderQuota["customWindows"]> = [];
|
|
128
|
+
const unknownBudgetWindows: NonNullable<ProviderQuota["unknownBudgetWindows"]> = [];
|
|
129
|
+
for (const [key, label] of MISTRAL_BUDGETS) {
|
|
130
|
+
const row = asRecord(budget[key]);
|
|
131
|
+
const resetAt = normalizeResetAt(row?.reset_at);
|
|
132
|
+
const reset = resetAt === undefined ? {} : { resetAt };
|
|
133
|
+
const suffix = plan ? ` (${plan})` : "";
|
|
134
|
+
const initial = toFiniteNumber(row?.initial_budget);
|
|
135
|
+
const percent = toFiniteNumber(row?.usage_percentage);
|
|
136
|
+
const currency = typeof row?.currency === "string" && /^[A-Za-z]{3}$/.test(row.currency) ? row.currency.toUpperCase() : undefined;
|
|
137
|
+
if (initial === undefined || initial <= 0 || percent === undefined || percent < 0 || percent > 100 || !currency) {
|
|
138
|
+
unknownBudgetWindows.push({ label: `${label}${suffix}`, ...reset });
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
const used = initial * (percent / 100);
|
|
142
|
+
customWindows.push({ label, displayLabel: `${label} (${currency} ${used.toFixed(2)} of ${currency} ${initial.toFixed(2)} used${plan ? `; ${plan}` : ""})`, percent, ...reset });
|
|
143
|
+
}
|
|
144
|
+
const quota: ProviderQuota = { customWindows, unknownBudgetWindows, updatedAt: Date.now() };
|
|
145
|
+
// Vibe and PAYG entitlements are display information, not inference eligibility evidence.
|
|
146
|
+
return keyReport(provider, "mistral:budget", markDisplayOnlyQuota(quota), config, apiKey, undefined, { bindCredential: true });
|
|
147
|
+
}
|
|
148
|
+
|
|
79
149
|
function isCanonicalClineBaseUrl(baseUrl: string): boolean {
|
|
80
150
|
const normalized = normalizedBaseUrl(baseUrl);
|
|
81
151
|
return normalized === CLINE_BASE_URL || normalized === `${CLINE_BASE_URL}/api/v1`;
|
|
@@ -1470,6 +1540,9 @@ export function keyQuotaReaderForProvider(name: string, provider: OcxProviderCon
|
|
|
1470
1540
|
if (isCanonicalA6apiBaseUrl(provider.baseUrl)) return fetchA6apiQuota;
|
|
1471
1541
|
if (name === "openrouter" && isCanonicalOpenRouterBaseUrl(provider.baseUrl)) return fetchOpenRouterQuota;
|
|
1472
1542
|
if (name === "deepseek" && isCanonicalDeepSeekBaseUrl(provider.baseUrl)) return fetchDeepSeekQuota;
|
|
1543
|
+
// The canonical-URL guard alone decides eligibility, so a custom provider name that points
|
|
1544
|
+
// at Mistral's own origin still probes, and a Mistral-named lookalike still dispatches nothing.
|
|
1545
|
+
if (isCanonicalMistralBaseUrl(provider.baseUrl)) return fetchMistralQuota;
|
|
1473
1546
|
if (name === "cline-pass" && isCanonicalClineBaseUrl(provider.baseUrl)) return fetchClineQuota;
|
|
1474
1547
|
if (isCanonicalOllamaCloudBaseUrl(provider.baseUrl ?? getProviderRegistryEntry(name)?.baseUrl)) return fetchOllamaCloudQuota;
|
|
1475
1548
|
// #4201: the Responses preset is the same domestic GLM Coding Plan subscription on the OpenAI
|
|
@@ -4,6 +4,7 @@ import { MAIN_CODEX_ACCOUNT_ID } from "../../codex/main-account";
|
|
|
4
4
|
import { getValidAccessToken } from "../../oauth";
|
|
5
5
|
import { loadConfig } from "../../config";
|
|
6
6
|
import { configuredAnthropicInstance, type AnthropicInstanceId } from "../anthropic-instance";
|
|
7
|
+
import { isAnthropicPoolEnabledFor } from "../../oauth/anthropic-pool-config";
|
|
7
8
|
import { captureOAuthAccountSelection, credentialGeneration, getAccountCredential, getAccountSet } from "../../oauth/store";
|
|
8
9
|
import { hydrateKiroAccountState, persistKiroAccountState } from "../kiro-account-state-disk";
|
|
9
10
|
import { kiroProbeCurrent, kiroProbeIdentity } from "./kiro-account-probe";
|
|
@@ -22,7 +23,7 @@ import { aggregateCodexPoolCapacity, CODEX_CAPACITY_MAX_QUOTA_AGE_MS, type Codex
|
|
|
22
23
|
import { asRecord, normalizePercent, normalizeResetAt, readQuotaJson, REQUEST_TIMEOUT_MS, toFiniteNumber } from "../quota-wire";
|
|
23
24
|
import { providerCodexAccountMode } from "../registry";
|
|
24
25
|
import {
|
|
25
|
-
accountReportCurrent,
|
|
26
|
+
accountReportCurrent, observedQuotaFor,
|
|
26
27
|
AUTHORITATIVE_EMPTY_QUOTA,
|
|
27
28
|
TERMINAL_QUOTA_FAILURE,
|
|
28
29
|
providerLabel,
|
|
@@ -38,6 +39,7 @@ import {
|
|
|
38
39
|
accountCacheKey,
|
|
39
40
|
captureProviderAccountQuotaEpoch,
|
|
40
41
|
accountQuotaCache,
|
|
42
|
+
getCachedProviderAccountQuota,
|
|
41
43
|
hydrateAccountQuotaCache,
|
|
42
44
|
mayCommitAccountQuotaKey,
|
|
43
45
|
persistAccountQuotaCache,
|
|
@@ -282,6 +284,51 @@ export async function fetchAnthropicUsageProbeForInstance(
|
|
|
282
284
|
return probe;
|
|
283
285
|
}
|
|
284
286
|
|
|
287
|
+
/** Pool switch plus each seat's routability, in store order; a change retires a cached pooled report. */
|
|
288
|
+
function anthropicPoolState(config: OcxConfig, instance: AnthropicInstanceId): string {
|
|
289
|
+
const accounts = getAccountSet(instance)?.accounts ?? [];
|
|
290
|
+
return JSON.stringify([isAnthropicPoolEnabledFor(config, instance),
|
|
291
|
+
accounts.map(row => [row.id, row.paused === true, row.needsReauth === true])]);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/**
|
|
295
|
+
* Pooled Anthropic report: the same display-only configured-weight estimate the Codex pool row
|
|
296
|
+
* carries, so the Providers overview shows pool-wide 5-hour/weekly bars, the next recovery and the
|
|
297
|
+
* effective account instead of the active seat alone.
|
|
298
|
+
*
|
|
299
|
+
* Only when the account pool is enabled and holds more than one account: with the pool off,
|
|
300
|
+
* requests are served by the active account, so its own reading is the provider's quota. Each
|
|
301
|
+
* account reads its last-good per-account row (the active one was just refreshed above); Anthropic
|
|
302
|
+
* reports no seat tier, so every routable account weighs 1. Paused, reauth and stale accounts are
|
|
303
|
+
* excluded and surface as incomplete coverage, exactly as for Codex.
|
|
304
|
+
*/
|
|
305
|
+
function anthropicPoolReport(
|
|
306
|
+
provider: string,
|
|
307
|
+
instance: AnthropicInstanceId,
|
|
308
|
+
config: OcxConfig,
|
|
309
|
+
activeAccountId: string,
|
|
310
|
+
activeQuota: ProviderQuota,
|
|
311
|
+
): ProviderQuotaReport | null {
|
|
312
|
+
if (!isAnthropicPoolEnabledFor(config, instance)) return null;
|
|
313
|
+
const accounts = getAccountSet(instance)?.accounts ?? [];
|
|
314
|
+
if (accounts.length < 2) return null;
|
|
315
|
+
const capacity = aggregateCodexPoolCapacity(accounts.map(row => ({
|
|
316
|
+
isMain: false,
|
|
317
|
+
active: row.id === activeAccountId,
|
|
318
|
+
weight: 1,
|
|
319
|
+
paused: row.paused === true,
|
|
320
|
+
needsReauth: row.needsReauth === true,
|
|
321
|
+
quota: (row.id === activeAccountId ? activeQuota : getCachedProviderAccountQuota(instance, row.id)) as CodexCapacityQuota | null,
|
|
322
|
+
})));
|
|
323
|
+
if (!capacity.aggregation || !capacity.quota) return null;
|
|
324
|
+
return report(
|
|
325
|
+
provider,
|
|
326
|
+
"anthropic:oauth-usage",
|
|
327
|
+
capacity.quota as ProviderQuota,
|
|
328
|
+
publicCapacityAggregation(capacity.aggregation, "aggregate"),
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
|
|
285
332
|
/** `config` is the caller's live object; currency re-reads it instead of reloading the file. */
|
|
286
333
|
export async function fetchAnthropicQuota(provider: string, config: OcxConfig = loadConfig()): Promise<ProviderQuotaReport | null> {
|
|
287
334
|
const instance = configuredAnthropicInstance(config, provider);
|
|
@@ -336,9 +383,16 @@ export async function fetchAnthropicQuota(provider: string, config: OcxConfig =
|
|
|
336
383
|
accountQuotaCache.set(probedAccountKey, { ts: Date.now(), quota, isCurrent: anthropicCurrent }); anthropicPublish?.();
|
|
337
384
|
}
|
|
338
385
|
}
|
|
339
|
-
const
|
|
386
|
+
const pooledReport = anthropicPoolReport(provider, instance, config, probedAccountId, quota);
|
|
387
|
+
const quotaReport = pooledReport ?? report(provider, "anthropic:oauth-usage", quota);
|
|
388
|
+
// The estimate carries no reset times, so reset detection keeps observing the active seat's reading.
|
|
389
|
+
if (pooledReport) observedQuotaFor.set(pooledReport, quota);
|
|
390
|
+
// Current only while the pool switch and membership are unchanged: pausing, resuming or reauthorizing
|
|
391
|
+
// an inactive seat changes the aggregate, and turning the pool on or adding a seat changes the report.
|
|
392
|
+
const poolState = anthropicPoolState(config, instance);
|
|
340
393
|
if (quotaReport && anthropicCurrent) {
|
|
341
|
-
accountReportCurrent.set(quotaReport, () => anthropicCurrent() &&
|
|
394
|
+
accountReportCurrent.set(quotaReport, () => anthropicCurrent() && anthropicPoolState(config, instance) === poolState
|
|
395
|
+
&& getAccountSet(instance)?.activeAccountId === probedAccountId);
|
|
342
396
|
}
|
|
343
397
|
return quotaReport;
|
|
344
398
|
}
|
|
@@ -174,12 +174,19 @@ export async function readProviderApiKeyQuotas(
|
|
|
174
174
|
return !!currentKey && identity(name, current, row.id, currentKey) === key;
|
|
175
175
|
} catch { return false; }
|
|
176
176
|
};
|
|
177
|
+
const isPaused = () => row.disabled === true
|
|
178
|
+
|| roster(config.providers[name] ?? providerSnapshot).find(candidate => candidate.id === row.id)?.disabled === true;
|
|
179
|
+
const cached = key ? cache.get(key) : undefined;
|
|
177
180
|
const entry = key && resolved && isCurrent()
|
|
178
|
-
?
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
181
|
+
? isPaused()
|
|
182
|
+
? (cached && (!cached.quota || Date.now() - cached.quota.updatedAt < LAST_GOOD_MS)
|
|
183
|
+
? cached
|
|
184
|
+
: { ts: Date.now(), quota: null, unavailable: true as const })
|
|
185
|
+
: await readEntry(key, force, isCurrent, () => {
|
|
186
|
+
const isolatedProvider = { ...providerSnapshot, apiKey: resolved, apiKeyPool: undefined };
|
|
187
|
+
const isolatedConfig = { ...config, providers: { [name]: isolatedProvider } };
|
|
188
|
+
return probe(isolatedProvider, isolatedConfig);
|
|
189
|
+
})
|
|
183
190
|
: { ts: Date.now(), quota: null, unavailable: true as const };
|
|
184
191
|
const result = {
|
|
185
192
|
keyId: row.id,
|