opencode-quota-gui 1.3.0 → 1.3.1

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 (146) hide show
  1. package/README.md +27 -17
  2. package/dist/bin/opencode-quota-gui.js +0 -0
  3. package/dist/contracts/build-identity.js +1 -1
  4. package/dist/contracts/dashboard.d.ts +8 -1
  5. package/dist/contracts/dto-guards.js +2 -0
  6. package/dist/contracts/openai-quota.d.ts +3 -0
  7. package/dist/contracts/openai-quota.js +3 -0
  8. package/dist/data/modelsdev-temporal.min.json +57 -0
  9. package/dist/gui/config.d.ts +3 -3
  10. package/dist/gui/config.js +31 -2
  11. package/dist/gui/lifecycle.d.ts +5 -3
  12. package/dist/gui/lifecycle.js +3 -3
  13. package/dist/gui/primary-quota-windows.js +16 -14
  14. package/dist/gui/provider-cards.d.ts +10 -2
  15. package/dist/gui/provider-cards.js +51 -23
  16. package/dist/gui/quota-notification-detector.d.ts +4 -4
  17. package/dist/gui/quota-notification-detector.js +76 -42
  18. package/dist/gui/quota-notification-observer.d.ts +2 -3
  19. package/dist/gui/quota-notification-observer.js +68 -19
  20. package/dist/gui/rpc.d.ts +2 -0
  21. package/dist/gui/rpc.js +11 -3
  22. package/dist/gui/server.js +11 -2
  23. package/dist/gui/snapshot-service.d.ts +3 -1
  24. package/dist/gui/snapshot-service.js +126 -18
  25. package/dist/gui/sources.js +98 -56
  26. package/dist/gui-experimental.cjs +230 -225
  27. package/dist/lib/accounting-format.js +8 -0
  28. package/dist/lib/alibaba-coding-plan-cli.d.ts +79 -0
  29. package/dist/lib/alibaba-coding-plan-cli.js +539 -0
  30. package/dist/lib/anthropic-auth.d.ts +2 -3
  31. package/dist/lib/anthropic-auth.js +2 -3
  32. package/dist/lib/anthropic.d.ts +48 -12
  33. package/dist/lib/anthropic.js +610 -275
  34. package/dist/lib/api-key-retry-after.d.ts +7 -0
  35. package/dist/lib/api-key-retry-after.js +62 -0
  36. package/dist/lib/atomic-json.d.ts +2 -0
  37. package/dist/lib/atomic-json.js +1 -0
  38. package/dist/lib/cache-observer-ingestion.d.ts +90 -0
  39. package/dist/lib/cache-observer-ingestion.js +981 -0
  40. package/dist/lib/cache-observer.d.ts +138 -0
  41. package/dist/lib/cache-observer.js +317 -0
  42. package/dist/lib/canonical-config-lock.d.ts +9 -0
  43. package/dist/lib/canonical-config-lock.js +36 -0
  44. package/dist/lib/chutes.js +62 -51
  45. package/dist/lib/claude-agent-transcript-ttl.d.ts +48 -0
  46. package/dist/lib/claude-agent-transcript-ttl.js +154 -0
  47. package/dist/lib/claude-agent-ttl-tracker.d.ts +21 -0
  48. package/dist/lib/claude-agent-ttl-tracker.js +152 -0
  49. package/dist/lib/cli-show.js +5 -3
  50. package/dist/lib/config-write-target.d.ts +1 -1
  51. package/dist/lib/config-write-target.js +5 -2
  52. package/dist/lib/config.d.ts +2 -1
  53. package/dist/lib/config.js +193 -2
  54. package/dist/lib/copilot.js +171 -86
  55. package/dist/lib/dashboard-web-policy.d.ts +4 -4
  56. package/dist/lib/dashboard-web-policy.js +2 -2
  57. package/dist/lib/deepseek.js +25 -13
  58. package/dist/lib/display-sanitize.js +1 -0
  59. package/dist/lib/entries.d.ts +23 -0
  60. package/dist/lib/entries.js +2 -0
  61. package/dist/lib/glm-coding-plan.js +98 -74
  62. package/dist/lib/google-agy.js +90 -12
  63. package/dist/lib/google-gemini-cli.js +84 -11
  64. package/dist/lib/http.d.ts +4 -0
  65. package/dist/lib/http.js +16 -2
  66. package/dist/lib/init-installer.js +5 -3
  67. package/dist/lib/kilo.js +37 -18
  68. package/dist/lib/kimi.js +35 -18
  69. package/dist/lib/mimo.d.ts +2 -0
  70. package/dist/lib/mimo.js +36 -0
  71. package/dist/lib/nanogpt.d.ts +1 -0
  72. package/dist/lib/nanogpt.js +26 -3
  73. package/dist/lib/ollama-cloud.d.ts +1 -1
  74. package/dist/lib/ollama-cloud.js +48 -35
  75. package/dist/lib/openai.js +84 -38
  76. package/dist/lib/opencode-auth-sqlite.d.ts +2 -2
  77. package/dist/lib/opencode-auth-sqlite.js +2 -2
  78. package/dist/lib/opencode-config-editor.d.ts +1 -0
  79. package/dist/lib/opencode-config-editor.js +6 -1
  80. package/dist/lib/opencode-go.js +29 -2
  81. package/dist/lib/opencode-version-core.d.ts +23 -0
  82. package/dist/lib/opencode-version-core.js +49 -0
  83. package/dist/lib/opencode-version.d.ts +2 -22
  84. package/dist/lib/opencode-version.js +4 -48
  85. package/dist/lib/opencode-zen.d.ts +3 -0
  86. package/dist/lib/opencode-zen.js +71 -5
  87. package/dist/lib/provider-add.js +5 -2
  88. package/dist/lib/provider-registration.d.ts +19 -9
  89. package/dist/lib/provider-registration.js +17 -6
  90. package/dist/lib/quota-command-format.js +1 -1
  91. package/dist/lib/quota-exhaustion-projection.d.ts +11 -0
  92. package/dist/lib/quota-exhaustion-projection.js +25 -0
  93. package/dist/lib/quota-providers-remote.d.ts +2 -1
  94. package/dist/lib/quota-providers-remote.js +59 -3
  95. package/dist/lib/quota-providers.d.ts +1 -1
  96. package/dist/lib/quota-providers.js +12 -35
  97. package/dist/lib/quota-render-data.d.ts +6 -0
  98. package/dist/lib/quota-render-data.js +43 -17
  99. package/dist/lib/quota-state-codec.js +17 -1
  100. package/dist/lib/quota-state.d.ts +7 -1
  101. package/dist/lib/quota-state.js +208 -34
  102. package/dist/lib/quota-stats.js +21 -0
  103. package/dist/lib/quota-status.js +3 -51
  104. package/dist/lib/scoped-update.d.ts +1 -1
  105. package/dist/lib/synthetic.js +65 -54
  106. package/dist/lib/types.d.ts +31 -1
  107. package/dist/lib/types.js +13 -0
  108. package/dist/lib/xai.js +48 -22
  109. package/dist/plugin.js +261 -13
  110. package/dist/provider-logos/NOTICE.md +1 -1
  111. package/dist/provider-logos/OPENCODE-NOTICE.md +4 -3
  112. package/dist/providers/alibaba-coding-plan.js +107 -104
  113. package/dist/providers/anthropic.d.ts +12 -3
  114. package/dist/providers/anthropic.js +71 -228
  115. package/dist/providers/cache-policies.d.ts +11 -4
  116. package/dist/providers/cache-policies.js +19 -13
  117. package/dist/providers/claude-agent.d.ts +19 -0
  118. package/dist/providers/claude-agent.js +196 -0
  119. package/dist/providers/copilot.js +2 -0
  120. package/dist/providers/glm-coding-plan-provider.d.ts +1 -0
  121. package/dist/providers/google-account-format.js +1 -0
  122. package/dist/providers/google-agy.d.ts +6 -5
  123. package/dist/providers/google-agy.js +43 -15
  124. package/dist/providers/google-gemini-cli.js +1 -0
  125. package/dist/providers/kilo.js +1 -0
  126. package/dist/providers/kimi-code.js +2 -0
  127. package/dist/providers/mimo.js +1 -0
  128. package/dist/providers/nanogpt.js +1 -0
  129. package/dist/providers/opencode-go.js +3 -0
  130. package/dist/providers/opencode-zen.js +2 -0
  131. package/dist/providers/openrouter.js +1 -0
  132. package/dist/providers/quota-providers.js +16 -5
  133. package/dist/providers/registry.js +2 -0
  134. package/dist/providers/result-helpers.d.ts +2 -0
  135. package/dist/providers/result-helpers.js +2 -0
  136. package/dist/rpc.d.ts +121 -8
  137. package/dist/rpc.js +204 -12
  138. package/dist/ui/assets/{index-cDd9jUVY.css → index-BcueIm3Z.css} +1 -1
  139. package/dist/ui/assets/index-C6qRSoh8.js +10 -0
  140. package/dist/ui/assets/{popover-BGkgv9s0.js → popover-4bFSvRZ7.js} +1 -1
  141. package/dist/ui/assets/providers/claude-agent.svg +3 -0
  142. package/dist/ui/index.html +2 -2
  143. package/package.json +44 -45
  144. package/dist/lib/alibaba-coding-plan-local-quota.d.ts +0 -47
  145. package/dist/lib/alibaba-coding-plan-local-quota.js +0 -146
  146. package/dist/ui/assets/index-DLHeXYff.js +0 -9
@@ -1,53 +1,9 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { parseOpenCodeVersion, } from "./opencode-version-core.js";
3
+ // Keep this legacy module path's public surface intact while the implementation
4
+ // of pure version helpers lives in a browser-safe module.
5
+ export * from "./opencode-version-core.js";
2
6
  const OPENCODE_VERSION_TIMEOUT_MS = 5_000;
3
- /** The numeric core of `1.18.32`, `opencode v2.2.0`, or `2.2.0-beta.1`. */
4
- const OPENCODE_VERSION_PATTERN = /^(?:opencode\s+)?v?(\d+)\.(\d+)\.(\d+)/;
5
- /** Parses the numeric version core; a prerelease or build suffix is ignored. */
6
- export function parseOpenCodeVersion(output) {
7
- const match = OPENCODE_VERSION_PATTERN.exec(output.trim());
8
- if (!match)
9
- return undefined;
10
- const major = Number(match[1]);
11
- const minor = Number(match[2]);
12
- const patch = Number(match[3]);
13
- if (![major, minor, patch].every((part) => Number.isSafeInteger(part)))
14
- return undefined;
15
- return { major, minor, patch };
16
- }
17
- /** OpenCode 1 prints a bare `1.18.32`; OpenCode 2 prints `opencode v2.0.16`. */
18
- export function parseOpenCodeMajor(output) {
19
- const version = parseOpenCodeVersion(output);
20
- if (version?.major === 1)
21
- return 1;
22
- if (version?.major === 2)
23
- return 2;
24
- return undefined;
25
- }
26
- /** Compares the numeric parts only; a prerelease suffix never lowers the result. */
27
- function isAtLeast(version, major, minor, patch) {
28
- if (version.major !== major)
29
- return version.major > major;
30
- if (version.minor !== minor)
31
- return version.minor > minor;
32
- return version.patch >= patch;
33
- }
34
- /**
35
- * Whether the host has the Native GUI baseline (2.2.0+). Missing or
36
- * unparseable versions are not assumed capable.
37
- */
38
- export function supportsNativeGui(version) {
39
- const parsed = typeof version === "string" ? parseOpenCodeVersion(version) : version;
40
- return parsed !== undefined && isAtLeast(parsed, 2, 2, 0);
41
- }
42
- /**
43
- * Whether the host predates the Native GUI and therefore keeps the compatibility
44
- * web dashboard on by default. Only a parseable version below 2.2.0 qualifies;
45
- * missing or unparseable versions fail closed.
46
- */
47
- export function isPreNativeGuiVersion(version) {
48
- const parsed = typeof version === "string" ? parseOpenCodeVersion(version) : version;
49
- return parsed !== undefined && !isAtLeast(parsed, 2, 2, 0);
50
- }
51
7
  function runOpenCodeVersion() {
52
8
  return new Promise((resolve, reject) => {
53
9
  execFile("opencode", ["--version"], { encoding: "utf8", timeout: OPENCODE_VERSION_TIMEOUT_MS, windowsHide: true }, (error, stdout) => (error ? reject(error) : resolve(stdout)));
@@ -46,6 +46,8 @@ export interface OpenCodeZenBillingData {
46
46
  export type OpenCodeZenOptionalError = {
47
47
  message: string;
48
48
  failureCategory?: ProviderFailureCategory;
49
+ /** Deadline observed in an upstream Retry-After response. */
50
+ retryAtMs?: number;
49
51
  };
50
52
  export type OpenCodeZenResult = {
51
53
  success: true;
@@ -56,6 +58,7 @@ export type OpenCodeZenResult = {
56
58
  success: false;
57
59
  error: string;
58
60
  failureCategory?: ProviderFailureCategory;
61
+ retryAtMs?: number;
59
62
  };
60
63
  export declare function queryOpenCodeZenQuota(credential: OpenCodeConsoleCredential, options?: {
61
64
  requestTimeoutMs?: number;
@@ -1,4 +1,5 @@
1
1
  import { providerFailureCategoryForHttpStatus } from "../contracts/provider-failure.js";
2
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
2
3
  import { sanitizeDisplayText } from "./display-sanitize.js";
3
4
  import { fetchWithTimeout } from "./http.js";
4
5
  import { consoleBaseUrl, consoleHeaders, } from "./opencode-console-auth.js";
@@ -9,6 +10,20 @@ const SESSION_ERROR = "OpenCode Console session expired or invalid. Run `opencod
9
10
  * one US dollar is 100,000,000 micro-cents (billing units).
10
11
  */
11
12
  export const OPENCODE_ZEN_BILLING_UNITS_PER_DOLLAR = 100_000_000;
13
+ const routeGuard = createApiKeyRetryGuard((retryAtMs) => ({
14
+ success: false,
15
+ error: "OpenCode Console request error 429",
16
+ failureCategory: providerFailureCategoryForHttpStatus(429),
17
+ retryAtMs,
18
+ }));
19
+ // Coalesce whole queries so a waiter cannot resend optional routes that settled
20
+ // while it was waiting for the required balance route.
21
+ const quotaQueryGuard = createApiKeyRetryGuard((retryAtMs) => ({
22
+ success: false,
23
+ error: "OpenCode Console billing/status error 429",
24
+ failureCategory: providerFailureCategoryForHttpStatus(429),
25
+ retryAtMs,
26
+ }));
12
27
  function asRecord(value) {
13
28
  return value && typeof value === "object" && !Array.isArray(value)
14
29
  ? value
@@ -218,7 +233,26 @@ function sanitizeMessage(text, secrets = [], maxLength = 120) {
218
233
  }
219
234
  return (sanitized || "unknown").slice(0, maxLength);
220
235
  }
221
- async function fetchConsoleRoute(params) {
236
+ /** One cooldown per workspace credential and route; other workspaces are unaffected. */
237
+ function fetchConsoleRoute(params) {
238
+ const { credential } = params;
239
+ const identity = JSON.stringify([
240
+ credential.accessToken,
241
+ credential.orgId ?? null,
242
+ consoleBaseUrl(credential),
243
+ params.path ?? params.route,
244
+ ]);
245
+ return routeGuard(identity, () => {
246
+ params.onRequest?.();
247
+ return requestConsoleRoute(params);
248
+ }, params.timeoutMs, (retryAtMs) => ({
249
+ success: false,
250
+ error: `OpenCode Console ${params.route} error 429`,
251
+ failureCategory: providerFailureCategoryForHttpStatus(429),
252
+ retryAtMs,
253
+ }));
254
+ }
255
+ async function requestConsoleRoute(params) {
222
256
  const path = params.path ?? params.route;
223
257
  try {
224
258
  return await fetchWithTimeout(`${consoleBaseUrl(params.credential)}/api/${path}`, {
@@ -236,10 +270,12 @@ async function fetchConsoleRoute(params) {
236
270
  return { success: false, error: SESSION_ERROR, failureCategory: "credentials" };
237
271
  }
238
272
  if (!response.ok) {
273
+ const retryAtMs = retryAfterDeadline(response);
239
274
  return {
240
275
  success: false,
241
276
  error: `OpenCode Console ${params.route} error ${response.status}`,
242
277
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
278
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
243
279
  };
244
280
  }
245
281
  if (response.headers.get("content-type")?.includes("text/html")) {
@@ -293,14 +329,43 @@ function memberBudgetRequest(request) {
293
329
  parse: (json) => parseMemberBudgets(json, accountId),
294
330
  });
295
331
  }
296
- export async function queryOpenCodeZenQuota(credential, options = {}) {
332
+ export function queryOpenCodeZenQuota(credential, options = {}) {
333
+ const timeoutMs = options.requestTimeoutMs ?? CONSOLE_TIMEOUT_MS;
334
+ const now = new Date();
335
+ const identity = JSON.stringify([
336
+ credential.accessToken,
337
+ credential.orgId ?? null,
338
+ consoleBaseUrl(credential),
339
+ credential.accountId?.trim() ?? null,
340
+ currentUtcMonth(now),
341
+ ]);
342
+ return quotaQueryGuard(identity, () => queryOpenCodeZenQuotaOnce(credential, timeoutMs, now), timeoutMs);
343
+ }
344
+ async function queryOpenCodeZenQuotaOnce(credential, timeoutMs, now) {
297
345
  const request = {
298
346
  credential,
299
- timeoutMs: options.requestTimeoutMs ?? CONSOLE_TIMEOUT_MS,
347
+ timeoutMs,
300
348
  };
301
- const now = new Date();
349
+ // A fresh attempt sends every route concurrently. When billing/status did not
350
+ // start a request (an observed Retry-After block, or another in-flight
351
+ // request), settle it first: a cooldown result makes the optional routes
352
+ // pointless, so they are not sent.
353
+ let billingStarted = false;
354
+ const balancePending = fetchConsoleRoute({
355
+ ...request,
356
+ route: "billing/status",
357
+ parse: parseBalance,
358
+ onRequest: () => {
359
+ billingStarted = true;
360
+ },
361
+ });
362
+ if (!billingStarted) {
363
+ const early = await balancePending;
364
+ if (!early.success && early.retryAtMs !== undefined)
365
+ return early;
366
+ }
302
367
  const [balance, creditLimit, autoRecharge, member, monthlyUsage] = await Promise.all([
303
- fetchConsoleRoute({ ...request, route: "billing/status", parse: parseBalance }),
368
+ balancePending,
304
369
  fetchConsoleRoute({ ...request, route: "billing/account", parse: parseCreditLimit }),
305
370
  fetchConsoleRoute({ ...request, route: "billing/auto-recharge", parse: parseAutoRecharge }),
306
371
  memberBudgetRequest(request),
@@ -345,6 +410,7 @@ export async function queryOpenCodeZenQuota(credential, options = {}) {
345
410
  ...(result.failureCategory !== undefined
346
411
  ? { failureCategory: result.failureCategory }
347
412
  : {}),
413
+ ...(result.retryAtMs !== undefined ? { retryAtMs: result.retryAtMs } : {}),
348
414
  },
349
415
  ]);
350
416
  return {
@@ -101,8 +101,11 @@ function sidecarManagedComments(index, definition) {
101
101
  }
102
102
  export async function planProviderAdd(options) {
103
103
  const single = validateQuotaProviders([options.definition]);
104
- if (!single.value) {
105
- throw new Error(single.issues.map((issue) => issue.key + ": " + issue.message).join("\n"));
104
+ if (!single.value || single.value.length !== 1) {
105
+ const validationMessage = single.issues
106
+ .map((issue) => issue.key + ": " + issue.message)
107
+ .join("\n");
108
+ throw new Error(validationMessage || "definition is not a supported quota provider");
106
109
  }
107
110
  const definition = single.value[0];
108
111
  const configDir = options.configDir ?? getOpencodeRuntimeDirs().configDir;
@@ -1,7 +1,7 @@
1
- export type QuotaProviderAutoSetup = "yes" | "usually" | "manual_env_config" | "needs_quick_setup";
2
- export type QuotaProviderAuthentication = "opencode_auth_oauth_token" | "opencode_auth_api_key" | "companion_auth_oauth_token" | "local_cli_auth" | "github_oauth_or_pat" | "external_api_key" | "state_only";
1
+ export type QuotaProviderAutoSetup = "yes" | "usually" | "manual_env_config" | "needs_quick_setup" | "unavailable";
2
+ export type QuotaProviderAuthentication = "opencode_auth_oauth_token" | "opencode_auth_api_key" | "companion_auth_oauth_token" | "local_cli_auth" | "github_oauth_or_pat" | "external_api_key" | "state_only" | "unavailable";
3
3
  export type QuotaProviderAuthFallback = "env_api_key" | "global_opencode_config";
4
- export type QuotaProviderQuotaSource = "remote_api" | "local_estimation" | "local_runtime_accounting" | "local_cli_report";
4
+ export type QuotaProviderQuotaSource = "remote_api" | "local_estimation" | "local_runtime_accounting" | "local_cli_report" | "unavailable";
5
5
  export interface QuotaProviderShapeSource {
6
6
  recommendedReplacementId?: string;
7
7
  autoSetup: QuotaProviderAutoSetup;
@@ -24,12 +24,22 @@ export declare const QUOTA_PROVIDER_REGISTRATION_SOURCE: readonly [{
24
24
  readonly id: "anthropic";
25
25
  readonly label: "Anthropic";
26
26
  readonly runtimeIds: readonly ["anthropic"];
27
- readonly synonyms: readonly ["claude", "claude-code"];
27
+ readonly synonyms: readonly [];
28
+ readonly shape: {
29
+ readonly autoSetup: "unavailable";
30
+ readonly authentication: "unavailable";
31
+ readonly quota: "unavailable";
32
+ };
33
+ }, {
34
+ readonly id: "claude-agent";
35
+ readonly label: "Claude Agent";
36
+ readonly runtimeIds: readonly ["claude-agent", "claude-code"];
37
+ readonly synonyms: readonly ["claude-code", "claude"];
28
38
  readonly shape: {
29
39
  readonly autoSetup: "needs_quick_setup";
30
40
  readonly authentication: "local_cli_auth";
31
41
  readonly quota: "local_cli_report";
32
- readonly quickSetupAnchor: "anthropic-claude";
42
+ readonly quickSetupAnchor: "claude-agent";
33
43
  };
34
44
  }, {
35
45
  readonly id: "copilot";
@@ -95,10 +105,10 @@ export declare const QUOTA_PROVIDER_REGISTRATION_SOURCE: readonly [{
95
105
  readonly synonyms: readonly ["alibaba"];
96
106
  readonly liveLocalUsage: true;
97
107
  readonly shape: {
98
- readonly autoSetup: "yes";
99
- readonly authentication: "opencode_auth_api_key";
100
- readonly authFallbacks: readonly ["env_api_key", "global_opencode_config"];
101
- readonly quota: "local_estimation";
108
+ readonly autoSetup: "needs_quick_setup";
109
+ readonly authentication: "local_cli_auth";
110
+ readonly quota: "local_cli_report";
111
+ readonly quickSetupAnchor: "alibaba-coding-plan";
102
112
  };
103
113
  }, {
104
114
  readonly id: "alibaba-token-plan";
@@ -3,12 +3,23 @@ export const QUOTA_PROVIDER_REGISTRATION_SOURCE = [
3
3
  id: "anthropic",
4
4
  label: "Anthropic",
5
5
  runtimeIds: ["anthropic"],
6
- synonyms: ["claude", "claude-code"],
6
+ synonyms: [],
7
+ shape: {
8
+ autoSetup: "unavailable",
9
+ authentication: "unavailable",
10
+ quota: "unavailable",
11
+ },
12
+ },
13
+ {
14
+ id: "claude-agent",
15
+ label: "Claude Agent",
16
+ runtimeIds: ["claude-agent", "claude-code"],
17
+ synonyms: ["claude-code", "claude"],
7
18
  shape: {
8
19
  autoSetup: "needs_quick_setup",
9
20
  authentication: "local_cli_auth",
10
21
  quota: "local_cli_report",
11
- quickSetupAnchor: "anthropic-claude",
22
+ quickSetupAnchor: "claude-agent",
12
23
  },
13
24
  },
14
25
  {
@@ -80,10 +91,10 @@ export const QUOTA_PROVIDER_REGISTRATION_SOURCE = [
80
91
  synonyms: ["alibaba"],
81
92
  liveLocalUsage: true,
82
93
  shape: {
83
- autoSetup: "yes",
84
- authentication: "opencode_auth_api_key",
85
- authFallbacks: ["env_api_key", "global_opencode_config"],
86
- quota: "local_estimation",
94
+ autoSetup: "needs_quick_setup",
95
+ authentication: "local_cli_auth",
96
+ quota: "local_cli_report",
97
+ quickSetupAnchor: "alibaba-coding-plan",
87
98
  },
88
99
  },
89
100
  {
@@ -56,7 +56,7 @@ const DIALOG_TIME_WINDOWS = new Set([
56
56
  /**
57
57
  * The TUI dialog's label for a row: a time window's quota drops "quota" ("5h quota" is
58
58
  * "5h", "Weekly quota" is "Weekly"), since the dialog's table heads that column "window".
59
- * Other labels, such as "Month spend" or "Fable weekly quota", stay whole.
59
+ * Other labels, such as "Month spend" or "Fable", stay whole.
60
60
  */
61
61
  function getDialogMetricLabel(entry, metricLabel) {
62
62
  const metric = entry.semantic?.metric;
@@ -1,5 +1,16 @@
1
1
  import type { FixedWindowProjectionEvidence, QuotaRunwayProjection } from "./entries.js";
2
2
  export declare function isFixedWindowProjectionEvidence(value: unknown, resetTimeIso?: string): value is FixedWindowProjectionEvidence;
3
+ /**
4
+ * Builds fixed-window evidence for a provider window whose length is known and whose reset is
5
+ * observed. The start is inferred as `reset - duration`, which is only valid for windows that
6
+ * reset on a fixed cycle; callers must pass a duration that matches that window kind. Returns
7
+ * nothing unless the observation falls strictly inside the inferred window.
8
+ */
9
+ export declare function buildFixedWindowEvidence(params: {
10
+ durationMs: number;
11
+ resetTimeIso?: string;
12
+ observedAtMs: number;
13
+ }): FixedWindowProjectionEvidence | undefined;
3
14
  export declare function projectQuotaRunway(params: {
4
15
  percentRemaining: number;
5
16
  fixedWindow?: FixedWindowProjectionEvidence;
@@ -27,6 +27,31 @@ export function isFixedWindowProjectionEvidence(value, resetTimeIso) {
27
27
  return false;
28
28
  return true;
29
29
  }
30
+ /**
31
+ * Builds fixed-window evidence for a provider window whose length is known and whose reset is
32
+ * observed. The start is inferred as `reset - duration`, which is only valid for windows that
33
+ * reset on a fixed cycle; callers must pass a duration that matches that window kind. Returns
34
+ * nothing unless the observation falls strictly inside the inferred window.
35
+ */
36
+ export function buildFixedWindowEvidence(params) {
37
+ if (!(Number.isFinite(params.durationMs) && params.durationMs > 0))
38
+ return undefined;
39
+ if (!Number.isFinite(params.observedAtMs))
40
+ return undefined;
41
+ const endsAt = parseIsoTimestamp(params.resetTimeIso);
42
+ if (endsAt === null)
43
+ return undefined;
44
+ const startedAt = endsAt - params.durationMs;
45
+ if (!(startedAt < params.observedAtMs && params.observedAtMs < endsAt))
46
+ return undefined;
47
+ return {
48
+ kind: "fixed_window",
49
+ startedAtIso: new Date(startedAt).toISOString(),
50
+ observedAtIso: new Date(params.observedAtMs).toISOString(),
51
+ endsAtIso: new Date(endsAt).toISOString(),
52
+ fullReset: true,
53
+ };
54
+ }
30
55
  export function projectQuotaRunway(params) {
31
56
  const nowMs = params.nowMs ?? Date.now();
32
57
  if (!Number.isFinite(params.percentRemaining) || !Number.isFinite(nowMs))
@@ -23,7 +23,8 @@ export type RemoteQuotaProviderResult = {
23
23
  success: false;
24
24
  error: string;
25
25
  failureCategory?: ProviderFailureCategory;
26
+ retryAtMs?: number;
26
27
  };
27
28
  export declare function resolveQuotaProviderApiKey(source: RemoteApiQuotaProviderDefinition): Promise<QuotaProviderAuthResolution>;
28
- export declare function fetchRemoteQuotaProvider(source: RemoteApiQuotaProviderDefinition, apiKey: string, requestTimeoutMs?: number): Promise<RemoteQuotaProviderResult>;
29
+ export declare function fetchRemoteQuotaProvider(source: RemoteApiQuotaProviderDefinition, apiKey: string | undefined, requestTimeoutMs?: number, fetcher?: typeof fetch): Promise<RemoteQuotaProviderResult>;
29
30
  //# sourceMappingURL=quota-providers-remote.d.ts.map
@@ -1,3 +1,4 @@
1
+ import { createHmac, randomBytes } from "node:crypto";
1
2
  import { providerFailureCategoryForHttpStatus, } from "../contracts/provider-failure.js";
2
3
  import { createProviderApiKeyResolver, getApiKeyCheckedPaths, getGlobalOpencodeConfigCandidatePaths, } from "./api-key-resolver.js";
3
4
  import { sanitizeSingleLineDisplayText } from "./display-sanitize.js";
@@ -753,17 +754,62 @@ function parseOpenRouterKeyV1(source, body) {
753
754
  entries: [openRouterSpendEntry(source, usage)],
754
755
  };
755
756
  }
756
- export async function fetchRemoteQuotaProvider(source, apiKey, requestTimeoutMs) {
757
+ export async function fetchRemoteQuotaProvider(source, apiKey, requestTimeoutMs, fetcher = fetch) {
758
+ const identity = createHmac("sha256", remoteIdentityKey)
759
+ .update(JSON.stringify([source.url, apiKey ?? null]))
760
+ .digest("base64url");
761
+ const now = Date.now();
762
+ for (const [key, deadline] of remoteRetryDeadlines) {
763
+ if (deadline <= now)
764
+ remoteRetryDeadlines.delete(key);
765
+ }
766
+ const deadline = remoteRetryDeadlines.get(identity);
767
+ if (deadline !== undefined)
768
+ return {
769
+ success: false,
770
+ error: "HTTP 429",
771
+ failureCategory: "provider_api",
772
+ retryAtMs: deadline,
773
+ };
774
+ const previous = remoteInFlight.get(identity);
775
+ if (previous) {
776
+ if (previous.source === JSON.stringify(source) &&
777
+ previous.fetcher === fetcher &&
778
+ previous.timeout === requestTimeoutMs) {
779
+ return structuredClone(await previous.request);
780
+ }
781
+ await previous.request;
782
+ return fetchRemoteQuotaProvider(source, apiKey, requestTimeoutMs, fetcher);
783
+ }
784
+ const request = fetchRemoteQuotaProviderUncached(source, apiKey, requestTimeoutMs, fetcher);
785
+ const pending = { request, source: JSON.stringify(source), fetcher, timeout: requestTimeoutMs };
786
+ remoteInFlight.set(identity, pending);
787
+ try {
788
+ const result = await request;
789
+ if (!result.success && result.retryAtMs !== undefined && result.retryAtMs > Date.now()) {
790
+ remoteRetryDeadlines.set(identity, result.retryAtMs);
791
+ }
792
+ return result;
793
+ }
794
+ finally {
795
+ if (remoteInFlight.get(identity) === pending)
796
+ remoteInFlight.delete(identity);
797
+ }
798
+ }
799
+ const remoteRetryDeadlines = new Map();
800
+ const remoteInFlight = new Map();
801
+ const remoteIdentityKey = randomBytes(32);
802
+ async function fetchRemoteQuotaProviderUncached(source, apiKey, requestTimeoutMs, fetcher = fetch) {
757
803
  const timeoutMs = requestTimeoutMs ?? REQUEST_TIMEOUT_MS;
758
804
  const controller = new AbortController();
759
805
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
760
806
  try {
761
- const response = await fetch(source.url, {
807
+ const response = await fetcher(source.url, {
762
808
  method: "GET",
763
809
  redirect: "manual",
764
810
  signal: controller.signal,
765
811
  headers: {
766
- Authorization: `Bearer ${apiKey}`,
812
+ ...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
767
813
  Accept: "application/json",
768
814
  },
769
815
  });
@@ -771,10 +817,17 @@ export async function fetchRemoteQuotaProvider(source, apiKey, requestTimeoutMs)
771
817
  return { success: false, error: "Redirect rejected", failureCategory: "provider_api" };
772
818
  }
773
819
  if (!response.ok) {
820
+ const header = response.status === 429 ? response.headers.get("retry-after")?.trim() : undefined;
821
+ const retryAtMs = header && /^\d+$/.test(header)
822
+ ? Date.now() + Number(header) * 1000
823
+ : header && /^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(header)
824
+ ? Date.parse(header)
825
+ : NaN;
774
826
  return {
775
827
  success: false,
776
828
  error: `HTTP ${response.status}`,
777
829
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
830
+ ...(Number.isSafeInteger(retryAtMs) && retryAtMs > Date.now() ? { retryAtMs } : {}),
778
831
  };
779
832
  }
780
833
  const body = await readBoundedJson(response);
@@ -788,6 +841,9 @@ export async function fetchRemoteQuotaProvider(source, apiKey, requestTimeoutMs)
788
841
  }
789
842
  }
790
843
  catch (error) {
844
+ if (error && typeof error === "object" && "code" in error && error.code === "unsafe-endpoint") {
845
+ return { success: false, error: "Unsafe provider endpoint", failureCategory: "provider_api" };
846
+ }
791
847
  if (controller.signal.aborted || (error instanceof Error && error.name === "AbortError")) {
792
848
  return {
793
849
  success: false,
@@ -3,7 +3,7 @@ export declare const QUOTA_PROVIDER_REMOTE_FORMATS: readonly ["quota-v1", "openr
3
3
  export declare const QUOTA_PROVIDER_MODES: readonly ["remote-api", "local-estimate"];
4
4
  export declare const QUOTA_PROVIDER_WINDOW_TYPES: readonly ["utc-day", "rolling"];
5
5
  export declare const QUOTA_PROVIDERS_AGGREGATE_ID = "quota-providers";
6
- export declare const MAINTAINED_LOCAL_ESTIMATE_IDS: readonly ["alibaba-coding-plan"];
6
+ export declare const MAINTAINED_LOCAL_ESTIMATE_IDS: readonly [];
7
7
  export declare function isMaintainedQuotaProviderTuning(definition: QuotaProviderDefinition): boolean;
8
8
  export declare function customQuotaProviderDefinitions(definitions: readonly QuotaProviderDefinition[]): QuotaProviderDefinition[];
9
9
  export declare function resolveQuotaProviderSessionModelIdentity(params: {
@@ -6,12 +6,20 @@ export const QUOTA_PROVIDER_REMOTE_FORMATS = ["quota-v1", "openrouter-key-v1", "
6
6
  export const QUOTA_PROVIDER_MODES = ["remote-api", "local-estimate"];
7
7
  export const QUOTA_PROVIDER_WINDOW_TYPES = ["utc-day", "rolling"];
8
8
  export const QUOTA_PROVIDERS_AGGREGATE_ID = "quota-providers";
9
- export const MAINTAINED_LOCAL_ESTIMATE_IDS = ["alibaba-coding-plan"];
9
+ export const MAINTAINED_LOCAL_ESTIMATE_IDS = [];
10
+ const LOCAL_ESTIMATE_PROVIDER_IDS_WITHOUT_ESTIMATES = new Set(["alibaba", "alibaba-coding-plan"]);
11
+ function hasUnsupportedAlibabaLocalEstimate(definition) {
12
+ if (!isPlainObject(definition) || definition.mode !== "local-estimate")
13
+ return false;
14
+ const providerId = hasOwnKey(definition, "providerId") ? definition.providerId : definition.id;
15
+ return (typeof providerId === "string" && LOCAL_ESTIMATE_PROVIDER_IDS_WITHOUT_ESTIMATES.has(providerId));
16
+ }
10
17
  export function isMaintainedQuotaProviderTuning(definition) {
11
18
  return MAINTAINED_LOCAL_ESTIMATE_IDS.includes(definition.id);
12
19
  }
13
20
  export function customQuotaProviderDefinitions(definitions) {
14
- return definitions.filter((definition) => !isMaintainedQuotaProviderTuning(definition));
21
+ return definitions.filter((definition) => !isMaintainedQuotaProviderTuning(definition) &&
22
+ !hasUnsupportedAlibabaLocalEstimate(definition));
15
23
  }
16
24
  export function resolveQuotaProviderSessionModelIdentity(params) {
17
25
  if (params.currentProviderID) {
@@ -829,29 +837,6 @@ function validateWindows(raw, providerKey, issues) {
829
837
  }
830
838
  return windows.length === raw.length ? windows : undefined;
831
839
  }
832
- function validateMaintainedWindows(id, windows, providerKey, issues) {
833
- if (!windows || !MAINTAINED_LOCAL_ESTIMATE_IDS.includes(id))
834
- return;
835
- const expected = [
836
- { id: "five-hour", type: "rolling", durationMinutes: 300 },
837
- { id: "weekly", type: "rolling", durationMinutes: 10_080 },
838
- { id: "monthly", type: "rolling", durationMinutes: 43_200 },
839
- ];
840
- if (windows.length !== expected.length ||
841
- expected.some((item, index) => {
842
- const window = windows[index];
843
- return (!window ||
844
- window.id !== item.id ||
845
- window.type !== item.type ||
846
- window.durationMinutes !== item.durationMinutes ||
847
- window.usdBudget !== undefined);
848
- })) {
849
- issues.push({
850
- key: `${providerKey}.windows`,
851
- message: "alibaba-coding-plan tuning requires ordered five-hour, weekly, and monthly rolling request windows",
852
- });
853
- }
854
- }
855
840
  function validatePricingModelMap(raw, providerKey, providerId, issues) {
856
841
  if (raw === undefined)
857
842
  return undefined;
@@ -916,6 +901,8 @@ export function validateQuotaProviders(value) {
916
901
  issues.push({ key: providerKey, message: "expected an object" });
917
902
  continue;
918
903
  }
904
+ if (hasUnsupportedAlibabaLocalEstimate(raw))
905
+ continue;
919
906
  const issueStart = issues.length;
920
907
  const mode = raw.mode;
921
908
  const allowedFields = mode === "local-estimate"
@@ -1005,14 +992,6 @@ export function validateQuotaProviders(value) {
1005
992
  const modelIds = validateModelIds({ raw, providerKey, providerId, issues });
1006
993
  const modelIdsValid = !hasOwnKey(raw, "modelIds") ||
1007
994
  (Array.isArray(raw.modelIds) && modelIds?.length === raw.modelIds.length);
1008
- if (idValid &&
1009
- MAINTAINED_LOCAL_ESTIMATE_IDS.includes(id) &&
1010
- mode !== "local-estimate") {
1011
- issues.push({
1012
- key: `${providerKey}.mode`,
1013
- message: `${id} tuning must use local-estimate mode`,
1014
- });
1015
- }
1016
995
  if (mode === "remote-api") {
1017
996
  for (const field of ["url", "format"]) {
1018
997
  if (!hasOwnKey(raw, field)) {
@@ -1104,8 +1083,6 @@ export function validateQuotaProviders(value) {
1104
1083
  issues.push({ key: `${providerKey}.windows`, message: "field is required" });
1105
1084
  }
1106
1085
  const windows = validateWindows(raw.windows, providerKey, issues);
1107
- if (idValid)
1108
- validateMaintainedWindows(id, windows, providerKey, issues);
1109
1086
  const pricingModelMap = providerId && hasOwnKey(raw, "pricingModelMap")
1110
1087
  ? validatePricingModelMap(raw.pricingModelMap, providerKey, providerId, issues)
1111
1088
  : undefined;
@@ -54,6 +54,8 @@ export type CollectQuotaRenderDataResult = {
54
54
  export type QuotaStatusLiveProbe = {
55
55
  providerId: string;
56
56
  result: QuotaProviderResult;
57
+ /** Server-only opaque scope, never projected into dashboard DTOs. */
58
+ cacheScope?: string;
57
59
  };
58
60
  export declare function matchesQuotaProviderCurrentSelection(params: {
59
61
  provider: QuotaProvider;
@@ -78,6 +80,7 @@ export declare function fetchProviderResults(params: {
78
80
  ctx: QuotaProviderContext;
79
81
  ttlMs: number;
80
82
  bypassCache?: boolean;
83
+ forceRefresh?: boolean;
81
84
  }): Promise<QuotaProviderResult[]>;
82
85
  export declare function collectQuotaStatusLiveProbes(params: {
83
86
  client: QuotaProviderContext["client"];
@@ -107,6 +110,7 @@ export declare function collectQuotaDashboardProviderResults(params: {
107
110
  configMeta?: Pick<LoadConfigMeta, "settingSources">;
108
111
  providers?: QuotaProvider[];
109
112
  bypassProviderCache?: boolean;
113
+ forceProviderRefresh?: boolean;
110
114
  resolveRuntimeProviderIds?: RuntimeProviderIdResolver;
111
115
  /** Dashboard-only OpenAI reset-detail visibility callback. */
112
116
  openaiResetDetailsVisible?: (sourceId?: string) => boolean;
@@ -120,6 +124,8 @@ export declare function collectQuotaRenderData(params: {
120
124
  formatStyle?: QuotaFormatStyle;
121
125
  configMeta?: Pick<LoadConfigMeta, "settingSources">;
122
126
  bypassProviderCache?: boolean;
127
+ forceProviderRefresh?: boolean;
128
+ includeProviderScope?: boolean;
123
129
  providers?: QuotaProvider[];
124
130
  includeAllWindowsData?: boolean;
125
131
  /**