@bitkyc08/opencodex 2.100.1 → 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.
Files changed (163) hide show
  1. package/gui/dist/assets/App-BpJOzw4F.js +59 -0
  2. package/gui/dist/assets/Tray-BcaI-VCr.js +1 -0
  3. package/gui/dist/assets/{brand-mark-nr3ziR-T.js → brand-mark-DU-0Vdkr.js} +1 -1
  4. package/gui/dist/assets/index-Bbor_y80.js +94 -0
  5. package/gui/dist/assets/index-DJEkIDAi.css +2 -0
  6. package/gui/dist/assets/{segment-thumb-features-DKCVUUTi.js → segment-thumb-features-e9A_FogJ.js} +1 -1
  7. package/gui/dist/classic/assets/{App-CgPBKUP-.js → App-BrIlUiLc.js} +18 -18
  8. package/gui/dist/classic/assets/{Tray-BedmOsE7.js → Tray-DT146AhS.js} +1 -1
  9. package/gui/dist/classic/assets/index-DyJHagvT.js +94 -0
  10. package/gui/dist/classic/assets/quota-summary-CakPe9Ni.js +1 -0
  11. package/gui/dist/classic/index.html +1 -1
  12. package/gui/dist/index.html +2 -2
  13. package/package.json +2 -2
  14. package/src/adapters/client-fingerprint.ts +5 -3
  15. package/src/adapters/cursor/native-exec.ts +3 -2
  16. package/src/adapters/cursor/tool-guidance.ts +3 -3
  17. package/src/adapters/cursor/tool-wording.ts +10 -1
  18. package/src/adapters/devin/cloud-direct/tool-schema.ts +20 -2
  19. package/src/adapters/google-antigravity-wire.ts +13 -6
  20. package/src/adapters/google-truncation.ts +4 -2
  21. package/src/adapters/google.ts +8 -2
  22. package/src/adapters/openai-chat/tool-schema.ts +9 -0
  23. package/src/adapters/openai-responses/tool-schema.ts +18 -4
  24. package/src/adapters/run-turn-queue.ts +139 -5
  25. package/src/adapters/upstream-http-error.ts +4 -2
  26. package/src/bridge/sse.ts +8 -1
  27. package/src/claude/chat-tool-dispatch.ts +233 -0
  28. package/src/claude/inbound-tool-loading.ts +42 -17
  29. package/src/cli/account-api.ts +6 -0
  30. package/src/cli/account-extended.ts +60 -6
  31. package/src/cli/account-key-quota.ts +22 -2
  32. package/src/cli/account.ts +1 -1
  33. package/src/cli/capabilities-access-remote.ts +10 -0
  34. package/src/cli/capabilities-agents-routing.ts +2 -2
  35. package/src/cli/capabilities-base.ts +2 -2
  36. package/src/cli/claude.ts +19 -14
  37. package/src/cli/config-command.ts +24 -1
  38. package/src/cli/connect.ts +36 -3
  39. package/src/cli/gui-pair-client.ts +23 -2
  40. package/src/cli/help.ts +1 -1
  41. package/src/cli/hub.ts +18 -1
  42. package/src/cli/link-child-ops.ts +136 -0
  43. package/src/cli/link-status-child.ts +94 -0
  44. package/src/cli/link.ts +22 -9
  45. package/src/cli/registry.ts +3 -2
  46. package/src/cli/sync-command.ts +3 -1
  47. package/src/cli/sync-fanout.ts +8 -81
  48. package/src/client/link-readiness.ts +16 -6
  49. package/src/client/link-tunnel-status.ts +76 -0
  50. package/src/clients/config-export.ts +14 -1
  51. package/src/codex/account-resume-health.ts +41 -0
  52. package/src/codex/auth-api/login-flow.ts +6 -0
  53. package/src/codex/auth-api/routes.ts +35 -2
  54. package/src/codex/catalog/gather-capture.ts +2 -0
  55. package/src/codex/catalog/provider-models.ts +13 -8
  56. package/src/codex/convergence-types.ts +2 -0
  57. package/src/codex/quota.ts +111 -6
  58. package/src/combos/cooldown-store.ts +208 -0
  59. package/src/combos/failover.ts +432 -35
  60. package/src/config/salvage.ts +1 -0
  61. package/src/config/schema/config-schema.ts +6 -3
  62. package/src/config/schema/leaf-validators.ts +34 -12
  63. package/src/generated/compatibility-version.json +213 -121
  64. package/src/lib/catalog-etag.ts +10 -0
  65. package/src/lib/client-error-body.ts +15 -0
  66. package/src/lib/context-overflow-verdict.ts +266 -9
  67. package/src/lib/failure-detail.ts +72 -3
  68. package/src/lib/hard-refusal.ts +259 -0
  69. package/src/link/child-activity.ts +57 -0
  70. package/src/link/child-catalog-freshness.ts +149 -0
  71. package/src/link/child-gated-ocx.ts +117 -0
  72. package/src/link/child-observations.ts +205 -0
  73. package/src/link/child-observe.ts +121 -0
  74. package/src/link/child-ops-engine.ts +162 -0
  75. package/src/link/child-update-contract.ts +165 -0
  76. package/src/link/paths.ts +5 -0
  77. package/src/link/remote-windows.ts +42 -6
  78. package/src/link/ssh-argv.ts +126 -32
  79. package/src/link/status-projection.ts +73 -0
  80. package/src/link/sync-fanout-classify.ts +98 -0
  81. package/src/link/tunnel-state.ts +10 -4
  82. package/src/messaging/mcp-queue-rpc.ts +2 -1
  83. package/src/messaging/mcp-queue-server.ts +5 -0
  84. package/src/messaging/mcp-reply-tools.ts +24 -9
  85. package/src/messaging/mcp-reply-wait.ts +70 -0
  86. package/src/oauth/account-resume-health.ts +60 -0
  87. package/src/oauth/index.ts +1 -0
  88. package/src/oauth/store.ts +44 -1
  89. package/src/providers/api-key-pause-state.ts +23 -0
  90. package/src/providers/api-key-pause.ts +68 -10
  91. package/src/providers/api-key-selection-capture.ts +3 -1
  92. package/src/providers/api-key-selection.ts +3 -2
  93. package/src/providers/api-keys.ts +18 -5
  94. package/src/providers/claude-cli-usage-state.ts +11 -6
  95. package/src/providers/claude-cli-usage.ts +27 -9
  96. package/src/providers/codex-capacity.ts +11 -2
  97. package/src/providers/key-failover.ts +13 -6
  98. package/src/providers/model-discovery-config.ts +31 -0
  99. package/src/providers/model-discovery-diagnostic.ts +34 -3
  100. package/src/providers/model-discovery.ts +43 -7
  101. package/src/providers/model-rename-fields.ts +2 -0
  102. package/src/providers/openai-sidecar.ts +15 -2
  103. package/src/providers/provider-id-rewrite.ts +3 -0
  104. package/src/providers/quota/account-cache.ts +52 -34
  105. package/src/providers/quota/anthropic-usage-windows.ts +19 -9
  106. package/src/providers/quota/report-cache.ts +53 -5
  107. package/src/providers/quota/vendor-probes-key.ts +73 -0
  108. package/src/providers/quota/vendor-probes-oauth.ts +57 -3
  109. package/src/providers/quota-key-accounts.ts +12 -5
  110. package/src/providers/quota-mistral-budget.ts +18 -0
  111. package/src/providers/quota-types.ts +25 -0
  112. package/src/providers/quota.ts +22 -22
  113. package/src/providers/reasoning-metadata.ts +1051 -12
  114. package/src/quota/reset-observer.ts +4 -2
  115. package/src/quota/reset-seen-store.ts +9 -0
  116. package/src/quota/window-mapping.ts +1 -0
  117. package/src/quota-pool/assemble.ts +4 -1
  118. package/src/responses/hosted-tool-policy.ts +56 -12
  119. package/src/router.ts +2 -0
  120. package/src/server/auth-cors.ts +11 -8
  121. package/src/server/catalog-download.ts +3 -5
  122. package/src/server/chat-native.ts +11 -2
  123. package/src/server/claude-messages.ts +2 -1
  124. package/src/server/images.ts +41 -13
  125. package/src/server/index/link-listener.ts +16 -2
  126. package/src/server/index/link-relay-sessions.ts +43 -2
  127. package/src/server/index/optional-listeners.ts +18 -0
  128. package/src/server/management/config-routes.ts +7 -1
  129. package/src/server/management/context.ts +1 -1
  130. package/src/server/management/link-child-ops-routes.ts +116 -0
  131. package/src/server/management/link-route-state.ts +10 -0
  132. package/src/server/management/link-routes.ts +10 -0
  133. package/src/server/management/oauth-account-routes.ts +33 -4
  134. package/src/server/management/provider-overwrite-carry.ts +28 -3
  135. package/src/server/management/provider-routes.ts +16 -11
  136. package/src/server/management/route-registry.ts +3 -0
  137. package/src/server/messages-native.ts +5 -0
  138. package/src/server/request-log-failure-detail.ts +59 -1
  139. package/src/server/responses/adapter-dispatch.ts +35 -44
  140. package/src/server/responses/combo-stream-preflight.ts +146 -29
  141. package/src/server/responses/compact.ts +16 -5
  142. package/src/server/responses/context-overflow.ts +58 -2
  143. package/src/server/responses/core-combo-failure.ts +29 -4
  144. package/src/server/responses/core-combo-native.ts +3 -1
  145. package/src/server/responses/core-combo.ts +30 -3
  146. package/src/server/responses/core-errors.ts +3 -1
  147. package/src/server/responses/core-opaque-recovery.ts +45 -2
  148. package/src/server/responses/core-options.ts +12 -0
  149. package/src/server/responses/passthrough-dispatch.ts +30 -38
  150. package/src/server/responses/request-transport.ts +43 -14
  151. package/src/server/responses/reset-replay.ts +58 -2
  152. package/src/server/responses/run-turn-execution.ts +56 -30
  153. package/src/types/claude-tool-loading.ts +48 -0
  154. package/src/types/config.ts +5 -35
  155. package/src/types/provider.ts +21 -0
  156. package/src/types.ts +1 -0
  157. package/src/web-search/parse.ts +21 -2
  158. package/gui/dist/assets/App-g3Cm2xhZ.js +0 -59
  159. package/gui/dist/assets/Tray-BMDkAiXy.js +0 -1
  160. package/gui/dist/assets/index-Bziu8gTy.css +0 -2
  161. package/gui/dist/assets/index-OYzhQUNP.js +0 -94
  162. package/gui/dist/classic/assets/index-BR-HhNrp.js +0 -94
  163. package/gui/dist/classic/assets/quota-summary-CXKhvSmQ.js +0 -1
@@ -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 { AccountQuotaMode, ProviderQuota, ProviderQuotaWindow, QuotaFailureCode } from "../quota-types";
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
- // Persisted rows validate only the outer quota object, so custom data may be malformed.
67
- if (quota.customWindows !== undefined) {
68
- const windows = Array.isArray(quota.customWindows) ? quota.customWindows : [];
69
- const retained: ProviderQuotaWindow[] = [];
70
- let changed = !Array.isArray(quota.customWindows);
71
- for (const window of windows) {
72
- if (!window || typeof window !== "object" || typeof window.label !== "string" || !window.label.trim()
73
- || typeof window.percent !== "number" || !Number.isFinite(window.percent)
74
- || window.percent < 0 || window.percent > 100) {
75
- changed = true;
76
- continue;
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 (changed) {
95
- if (result === quota) result = { ...quota };
96
- if (retained.length) result.customWindows = retained;
97
- else delete result.customWindows;
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;
@@ -39,8 +39,8 @@ export function familyWeeklyEquivalentPercent(window: { percent?: number; weekly
39
39
 
40
40
  /**
41
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 selected scoped row
43
- * receives it; a malformed, out-of-range or conflicting share is ignored.
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
44
  */
45
45
  function applyWeeklyShares(body: Record<string, unknown>, scopedRows: Map<number, AnthropicUsageBucket>): void {
46
46
  if (!Array.isArray(body.weekly_scoped_shares)) return;
@@ -66,12 +66,14 @@ function applyWeeklyShares(body: Record<string, unknown>, scopedRows: Map<number
66
66
  * and malformed shared measurements make family enumeration incomplete. Shared finite
67
67
  * measurements apply regardless of the binding flag, though an unknown flag also makes
68
68
  * enumeration incomplete. A null legacy five_hour requires an explicitly active session.
69
- * Scoped rows retain active-only behavior; unknown kinds/families cannot clear refusals.
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.
70
71
  */
71
72
  export function anthropicUsageBuckets(body: Record<string, unknown>): {
72
- buckets: AnthropicUsageBucket[]; familyEnumeration: boolean;
73
+ buckets: AnthropicUsageBucket[]; displayBuckets: AnthropicUsageBucket[]; familyEnumeration: boolean;
73
74
  } {
74
75
  const selected = new Map<UsageWindow, AnthropicUsageBucket>();
76
+ const displayOnly = new Map<UsageWindow, AnthropicUsageBucket>();
75
77
  const represented = new Set<UsageWindow>();
76
78
  const scopedRows = new Map<number, AnthropicUsageBucket>();
77
79
  const limits = Array.isArray(body.limits) ? body.limits : [];
@@ -91,7 +93,13 @@ export function anthropicUsageBuckets(body: Record<string, unknown>): {
91
93
  selected.set(window, { window, row, percentField: "percent" });
92
94
  continue;
93
95
  }
94
- if (row.is_active === false) continue;
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
+ }
95
103
  if (row.is_active !== undefined && row.is_active !== true) { familyEnumeration = false; continue; }
96
104
  if (toFiniteNumber(row.percent) === undefined) familyEnumeration = false;
97
105
  const bucket: AnthropicUsageBucket = { window, row, percentField: "percent" };
@@ -105,8 +113,10 @@ export function anthropicUsageBuckets(body: Record<string, unknown>): {
105
113
  if (row) selected.set(window, { window, row, percentField: "utilization" });
106
114
  }
107
115
  // Stable canonical order, independent of how upstream orders limits.
108
- return { buckets: (Object.keys(legacyFields) as UsageWindow[]).flatMap(window => {
109
- const bucket = selected.get(window);
110
- return bucket ? [bucket] : [];
111
- }), familyEnumeration };
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 };
112
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 || !inferenceQuota) return 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(configuredProviders: readonly string[]): ProviderQuotaResponse {
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 => configured.has(item.provider) && isProviderQuotaReportCurrent(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 quotaReport = report(provider, "anthropic:oauth-usage", quota);
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() && getAccountSet(instance)?.activeAccountId === probedAccountId);
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
- ? await readEntry(key, force, isCurrent, () => {
179
- const isolatedProvider = { ...providerSnapshot, apiKey: resolved, apiKeyPool: undefined };
180
- const isolatedConfig = { ...config, providers: { [name]: isolatedProvider } };
181
- return probe(isolatedProvider, isolatedConfig);
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,
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Mistral budget windows the reset detector may keep while their percent is unknown.
3
+ *
4
+ * This lives beside the provider quota seam rather than in src/quota/: src/providers/quota.ts is
5
+ * statically reachable from the core request path, and tests/usage/quota-reset-core-boundary.test.ts
6
+ * keeps every src/quota module off that path. The seam calls this on every Mistral report, so it
7
+ * must stay a plain import with no dependency on the reset subsystem.
8
+ */
9
+ export function mistralUnknownBudgetWindows(
10
+ quota: { unknownBudgetWindows?: ReadonlyArray<{ label: string; resetAt?: number }> },
11
+ ): { window: string; resetAt: number }[] {
12
+ return (quota.unknownBudgetWindows ?? []).flatMap(entry => {
13
+ const match = /^(API budget|Vibe budget)(?: \((?:FREE|INDIVIDUAL|EDU|TEAM)\))?$/.exec(entry.label);
14
+ return match && typeof entry.resetAt === "number" && Number.isFinite(entry.resetAt) && entry.resetAt > 0
15
+ ? [{ window: `custom:${match[1]}`, resetAt: entry.resetAt }]
16
+ : [];
17
+ });
18
+ }
@@ -10,6 +10,16 @@
10
10
 
11
11
  export const PROVIDER_QUOTA_MAX_AGE_MS = 30 * 60_000;
12
12
 
13
+ // Process-local authority: display readings must not acquire key-selection authority.
14
+ const displayOnlyQuotas = new WeakSet<ProviderQuota>();
15
+ export function markDisplayOnlyQuota(quota: ProviderQuota): ProviderQuota {
16
+ displayOnlyQuotas.add(quota);
17
+ return quota;
18
+ }
19
+ export function isDisplayOnlyQuota(quota: ProviderQuota): boolean {
20
+ return displayOnlyQuotas.has(quota);
21
+ }
22
+
13
23
  /** Management-only eligibility evidence; private credential binding never leaves the server. */
14
24
  export type ProviderRoutingQuota =
15
25
  | { state: "unknown" }
@@ -17,6 +27,8 @@ export type ProviderRoutingQuota =
17
27
 
18
28
  export interface ProviderQuotaWindow {
19
29
  label: string;
30
+ /** Presentation text only; identity and routing use label and structured fields. */
31
+ displayLabel?: string;
20
32
  percent: number;
21
33
  resetAt?: number;
22
34
  /**
@@ -60,6 +72,8 @@ export interface ProviderQuotaCreditsUsd {
60
72
  }
61
73
 
62
74
  export interface ProviderQuota {
75
+ /** Display-only budget windows for which the upstream did not provide a usable entitlement. */
76
+ unknownBudgetWindows?: { label: string; resetAt?: number }[];
63
77
  /** Display-only subscription credits; not a routing or exhaustion window. */
64
78
  workbuddyCredits?: import("./workbuddy-credit-balance").WorkBuddyCreditBalance;
65
79
  fiveHourPercent?: number;
@@ -72,6 +86,12 @@ export interface ProviderQuota {
72
86
  kiroCreditsUsed?: number;
73
87
  kiroCreditsLimit?: number;
74
88
  customWindows?: ProviderQuotaWindow[];
89
+ /**
90
+ * Display-only measurements the producer withheld from routing: Anthropic model-scoped rows
91
+ * that upstream reports with `is_active: false`. Routing, exhaustion, cooldown recovery and
92
+ * reset ordering read only `customWindows`; nothing but quota display reads this field.
93
+ */
94
+ displayWindows?: ProviderQuotaWindow[];
75
95
  creditsUsd?: ProviderQuotaCreditsUsd;
76
96
  updatedAt: number;
77
97
  }
@@ -96,3 +116,8 @@ export type QuotaFailureCode = typeof QUOTA_FAILURE_CODES[number];
96
116
  export function parseQuotaFailureCode(value: unknown): QuotaFailureCode | undefined {
97
117
  return QUOTA_FAILURE_CODES.find(code => code === value);
98
118
  }
119
+
120
+ /** A model family's share of the weekly limit is meaningful only as a finite percent in (0, 100]. */
121
+ export function isWeeklyAllowancePercent(value: unknown): value is number {
122
+ return typeof value === "number" && Number.isFinite(value) && value > 0 && value <= 100;
123
+ }