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
@@ -6,12 +6,19 @@
6
6
  */
7
7
  import { providerFailureCategoryForHttpStatus, } from "../contracts/provider-failure.js";
8
8
  import { isCanonicalAccountingDecimal } from "./accounting-format.js";
9
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
9
10
  import { resolveDeepSeekApiKey } from "./deepseek-auth.js";
10
11
  import { sanitizeDisplaySnippet, sanitizeDisplayText } from "./display-sanitize.js";
11
12
  import { fetchWithTimeout } from "./http.js";
12
13
  const DEEPSEEK_BALANCE_URL = "https://api.deepseek.com/user/balance";
13
14
  const USER_AGENT = "opencode-quota-gui/1.0";
14
15
  const MAX_PARSE_ISSUES = 6;
16
+ const guard = createApiKeyRetryGuard((retryAtMs) => ({
17
+ success: false,
18
+ error: "DeepSeek API error 429",
19
+ failureCategory: "provider_api",
20
+ retryAtMs,
21
+ }));
15
22
  function isRecord(value) {
16
23
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
17
24
  }
@@ -77,11 +84,13 @@ async function fetchDeepSeekBalance(apiKey, requestTimeoutMs) {
77
84
  consume: async (response) => {
78
85
  responseStatus = response.status;
79
86
  if (!response.ok) {
80
- const text = await response.text();
87
+ const deadline = retryAfterDeadline(response);
88
+ const text = await response.text().catch(() => "");
81
89
  return {
82
90
  success: false,
83
91
  message: `DeepSeek API error ${response.status}: ${sanitizeDisplaySnippet(text, 120)}`,
84
92
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
93
+ ...(deadline !== undefined ? { retryAtMs: deadline } : {}),
85
94
  };
86
95
  }
87
96
  return {
@@ -110,20 +119,23 @@ export async function queryDeepSeekBalance(options = {}) {
110
119
  const resolved = await resolveDeepSeekApiKey();
111
120
  if (!resolved)
112
121
  return null;
113
- const result = await fetchDeepSeekBalance(resolved.key, options.requestTimeoutMs);
114
- if (!result.success) {
122
+ return guard(resolved.key, async () => {
123
+ const result = await fetchDeepSeekBalance(resolved.key, options.requestTimeoutMs);
124
+ if (!result.success) {
125
+ return {
126
+ success: false,
127
+ error: result.message,
128
+ failureCategory: result.failureCategory,
129
+ ...(result.retryAtMs !== undefined ? { retryAtMs: result.retryAtMs } : {}),
130
+ };
131
+ }
115
132
  return {
116
- success: false,
117
- error: result.message,
118
- failureCategory: result.failureCategory,
133
+ success: true,
134
+ isAvailable: result.data.isAvailable,
135
+ balanceInfos: result.data.balanceInfos,
136
+ parseIssues: result.data.parseIssues,
119
137
  };
120
- }
121
- return {
122
- success: true,
123
- isAvailable: result.data.isAvailable,
124
- balanceInfos: result.data.balanceInfos,
125
- parseIssues: result.data.parseIssues,
126
- };
138
+ }, options.requestTimeoutMs);
127
139
  }
128
140
  export { getDeepSeekKeyDiagnostics, hasDeepSeekApiKey as hasDeepSeekApiKeyConfigured, } from "./deepseek-auth.js";
129
141
  //# sourceMappingURL=deepseek.js.map
@@ -103,6 +103,7 @@ export function sanitizeQuotaToastError(error) {
103
103
  return {
104
104
  label: sanitizeDisplayText(error.label),
105
105
  message: sanitizeDisplayText(error.message),
106
+ ...(error.retryAtMs !== undefined ? { retryAtMs: error.retryAtMs } : {}),
106
107
  ...(error.retryable === true ? { retryable: true } : {}),
107
108
  ...(error.failureCategory !== undefined ? { failureCategory: error.failureCategory } : {}),
108
109
  ...(error.kind ? { kind: error.kind } : {}),
@@ -167,6 +167,8 @@ export declare function cloneAccountingPercentageBasis(basis: AccountingPercenta
167
167
  export declare function cloneBankedResetAvailability(bankedResets: BankedResetAvailability): BankedResetAvailability;
168
168
  export declare function cloneQuotaToastEntry(entry: QuotaToastEntry): QuotaToastEntry;
169
169
  export interface QuotaToastError {
170
+ /** Deadline observed in an upstream Retry-After response. */
171
+ retryAtMs?: number;
170
172
  /** Short label that will be rendered as "label: message". */
171
173
  label: string;
172
174
  message: string;
@@ -266,6 +268,11 @@ export interface QuotaProviderResult {
266
268
  errors: QuotaToastError[];
267
269
  /** Additive discovered-account descriptors; absent when no account identity exists. */
268
270
  accounts?: readonly QuotaProviderAccount[];
271
+ /**
272
+ * Optional display-only plan for a provider-scope result with no discovered accounts (the Claude CLI
273
+ * login shown alone). Never an identity input and never set beside OpenCode account descriptors.
274
+ */
275
+ planLabel?: string;
269
276
  /** Internal provider diagnostics; not projected into normal presentation/export surfaces. */
270
277
  diagnostics?: QuotaProviderDiagnostic[];
271
278
  /**
@@ -282,8 +289,23 @@ export interface QuotaProviderMatchContext {
282
289
  quotaProviders?: QuotaProviderDefinition[];
283
290
  currentProviderID?: string;
284
291
  }
292
+ /** Marks a single provider operation as an explicit freshness request. */
293
+ export declare const QUOTA_FORCE_REFRESH: unique symbol;
285
294
  export interface QuotaProviderContext {
295
+ /** Ephemeral memoization shared only within one quota refresh operation. */
296
+ operationCache?: Map<symbol, unknown>;
286
297
  client: {
298
+ integration?: {
299
+ list: () => Promise<{
300
+ data: Array<{
301
+ id: string;
302
+ connections: Array<{
303
+ type: string;
304
+ method?: string;
305
+ }>;
306
+ }>;
307
+ }>;
308
+ };
287
309
  config: {
288
310
  providers: () => Promise<{
289
311
  data?: {
@@ -340,6 +362,7 @@ export type QuotaProviderCachePolicy = {
340
362
  kind: "uncached";
341
363
  } | {
342
364
  kind: "resolved-auth";
365
+ revalidateWithCycleCache?: true;
343
366
  resolveIdentity: (ctx: QuotaProviderContext, cacheContext: QuotaProviderCacheContext) => Promise<ResolvedAuthIdentity | null>;
344
367
  };
345
368
  export interface QuotaProvider {
@@ -66,4 +66,6 @@ export function cloneQuotaToastEntry(entry) {
66
66
  : {}),
67
67
  };
68
68
  }
69
+ /** Marks a single provider operation as an explicit freshness request. */
70
+ export const QUOTA_FORCE_REFRESH = Symbol("quota-force-refresh");
69
71
  //# sourceMappingURL=entries.js.map
@@ -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 { sanitizeDisplaySnippet, sanitizeDisplayText } from "./display-sanitize.js";
3
4
  import { clampPercent } from "./format-utils.js";
4
5
  import { fetchWithTimeout } from "./http.js";
@@ -11,81 +12,104 @@ export async function queryGlmCodingPlanQuota(descriptor, options = {}) {
11
12
  if (auth.state === "invalid") {
12
13
  return { success: false, error: auth.error, failureCategory: "credentials" };
13
14
  }
14
- let responseStatus;
15
- try {
16
- return await fetchWithTimeout(descriptor.endpoint, {
17
- request: {
18
- headers: {
19
- Authorization: auth.apiKey,
20
- "User-Agent": "opencode-quota-gui/1.0",
21
- "Content-Type": "application/json",
15
+ return guard(JSON.stringify([descriptor.endpoint, auth.apiKey]), async () => {
16
+ let responseStatus;
17
+ try {
18
+ return await fetchWithTimeout(descriptor.endpoint, {
19
+ request: {
20
+ headers: {
21
+ Authorization: auth.apiKey,
22
+ "User-Agent": "opencode-quota-gui/1.0",
23
+ "Content-Type": "application/json",
24
+ },
22
25
  },
23
- },
24
- timeoutMs: options.requestTimeoutMs,
25
- consume: async (response) => {
26
- responseStatus = response.status;
27
- if (!response.ok) {
28
- const body = sanitizeDisplaySnippet(await response.text(), 120);
29
- return {
30
- success: false,
31
- error: `${descriptor.httpErrorPrefix} ${response.status}: ${body}`,
32
- failureCategory: providerFailureCategoryForHttpStatus(response.status),
33
- };
34
- }
35
- const body = (await response.json());
36
- if (descriptor.envelope === "zai" &&
37
- (body.success === false || (typeof body.code === "number" && body.code >= 400))) {
38
- const message = typeof body.msg === "string" ? sanitizeDisplayText(body.msg) : "";
39
- return {
40
- success: false,
41
- error: message ||
42
- (typeof body.code === "number"
43
- ? `${descriptor.apiErrorPrefix} ${body.code}`
44
- : descriptor.apiErrorPrefix),
45
- failureCategory: "provider_api",
46
- };
47
- }
48
- const limits = descriptor.envelope === "zai" ? (body.data?.limits ?? body.limits) : body.data?.limits;
49
- if (!Array.isArray(limits)) {
50
- return { success: false, error: "Invalid quota data", failureCategory: "provider_api" };
51
- }
52
- const windows = {};
53
- for (const limit of limits) {
54
- const resetDate = limit.nextResetTime ? new Date(Math.round(limit.nextResetTime)) : null;
55
- const resetTimeIso = resetDate && Number.isFinite(resetDate.valueOf()) && resetDate.valueOf() > 0
56
- ? resetDate.toISOString()
57
- : undefined;
58
- let percentRemaining = clampPercent(100 - limit.percentage);
59
- if (limit.type === "CREDIT_LIMIT" &&
60
- typeof limit.usage === "number" &&
61
- Number.isFinite(limit.usage) &&
62
- limit.usage > 0 &&
63
- typeof limit.currentValue === "number" &&
64
- Number.isFinite(limit.currentValue) &&
65
- limit.currentValue >= 0) {
66
- percentRemaining = clampPercent(((limit.usage - limit.currentValue) / limit.usage) * 100);
26
+ timeoutMs: options.requestTimeoutMs,
27
+ consume: async (response) => {
28
+ responseStatus = response.status;
29
+ if (!response.ok) {
30
+ const retryAtMs = retryAfterDeadline(response);
31
+ const body = sanitizeDisplaySnippet(await response.text().catch(() => ""), 120);
32
+ return {
33
+ success: false,
34
+ error: `${descriptor.httpErrorPrefix} ${response.status}: ${body}`,
35
+ failureCategory: providerFailureCategoryForHttpStatus(response.status),
36
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
37
+ };
67
38
  }
68
- const window = { percentRemaining, resetTimeIso };
69
- const isQuotaWindow = limit.type === "TOKENS_LIMIT" || limit.type === "CREDIT_LIMIT";
70
- if (isQuotaWindow && limit.unit === 3)
71
- windows.fiveHour = window;
72
- else if (isQuotaWindow && limit.unit === 6)
73
- windows.weekly = window;
74
- else if (limit.type === "TIME_LIMIT")
75
- windows.mcp = window;
76
- }
77
- return { success: true, label: descriptor.label, windows };
78
- },
79
- });
80
- }
81
- catch (error) {
82
- return {
83
- success: false,
84
- error: sanitizeDisplayText(error instanceof Error ? error.message : String(error)),
85
- failureCategory: responseStatus === undefined
86
- ? "provider_api"
87
- : providerFailureCategoryForHttpStatus(responseStatus),
88
- };
89
- }
39
+ const body = (await response.json());
40
+ if (descriptor.envelope === "zai" &&
41
+ (body.success === false || (typeof body.code === "number" && body.code >= 400))) {
42
+ const message = typeof body.msg === "string" ? sanitizeDisplayText(body.msg) : "";
43
+ return {
44
+ success: false,
45
+ error: message ||
46
+ (typeof body.code === "number"
47
+ ? `${descriptor.apiErrorPrefix} ${body.code}`
48
+ : descriptor.apiErrorPrefix),
49
+ failureCategory: "provider_api",
50
+ };
51
+ }
52
+ const limits = descriptor.envelope === "zai"
53
+ ? (body.data?.limits ?? body.limits)
54
+ : body.data?.limits;
55
+ if (!Array.isArray(limits)) {
56
+ return {
57
+ success: false,
58
+ error: "Invalid quota data",
59
+ failureCategory: "provider_api",
60
+ };
61
+ }
62
+ const windows = {};
63
+ for (const limit of limits) {
64
+ const resetDate = limit.nextResetTime
65
+ ? new Date(Math.round(limit.nextResetTime))
66
+ : null;
67
+ const resetTimeIso = resetDate && Number.isFinite(resetDate.valueOf()) && resetDate.valueOf() > 0
68
+ ? resetDate.toISOString()
69
+ : undefined;
70
+ let percentRemaining = clampPercent(100 - limit.percentage);
71
+ if (limit.type === "CREDIT_LIMIT" &&
72
+ typeof limit.usage === "number" &&
73
+ Number.isFinite(limit.usage) &&
74
+ limit.usage > 0 &&
75
+ typeof limit.currentValue === "number" &&
76
+ Number.isFinite(limit.currentValue) &&
77
+ limit.currentValue >= 0) {
78
+ percentRemaining = clampPercent(((limit.usage - limit.currentValue) / limit.usage) * 100);
79
+ }
80
+ const window = { percentRemaining, resetTimeIso };
81
+ const isQuotaWindow = limit.type === "TOKENS_LIMIT" || limit.type === "CREDIT_LIMIT";
82
+ if (isQuotaWindow && limit.unit === 3)
83
+ windows.fiveHour = window;
84
+ else if (isQuotaWindow && limit.unit === 6)
85
+ windows.weekly = window;
86
+ else if (limit.type === "TIME_LIMIT")
87
+ windows.mcp = window;
88
+ }
89
+ return { success: true, label: descriptor.label, windows };
90
+ },
91
+ });
92
+ }
93
+ catch (error) {
94
+ return {
95
+ success: false,
96
+ error: sanitizeDisplayText(error instanceof Error ? error.message : String(error)),
97
+ failureCategory: responseStatus === undefined
98
+ ? "provider_api"
99
+ : providerFailureCategoryForHttpStatus(responseStatus),
100
+ };
101
+ }
102
+ }, options.requestTimeoutMs, (retryAtMs) => ({
103
+ success: false,
104
+ error: `${descriptor.httpErrorPrefix} 429`,
105
+ failureCategory: "provider_api",
106
+ retryAtMs,
107
+ }));
90
108
  }
109
+ const guard = createApiKeyRetryGuard((retryAtMs) => ({
110
+ success: false,
111
+ error: "HTTP 429",
112
+ failureCategory: "provider_api",
113
+ retryAtMs,
114
+ }));
91
115
  //# sourceMappingURL=glm-coding-plan.js.map
@@ -1,9 +1,10 @@
1
1
  import crypto from "node:crypto";
2
2
  import { providerFailureCategoryForHttpStatus, } from "../contracts/provider-failure.js";
3
3
  import { readGlobalProviderConfigString } from "./api-key-resolver.js";
4
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
4
5
  import { clearAgyCompanionCacheForTests, inspectAgyCompanionPresence, resolveAgyClientCredentials, } from "./google-agy-companion.js";
5
6
  import { getCachedAccessToken, makeAccountCacheKey, setCachedAccessToken, } from "./google-token-cache.js";
6
- import { fetchWithTimeout } from "./http.js";
7
+ import { fetchWithTimeout, RequestTimeoutError } from "./http.js";
7
8
  import { mapWithConcurrency } from "./map-with-concurrency.js";
8
9
  import { readAuthFileCached } from "./opencode-auth.js";
9
10
  import { composeResolvedAuthIdentities, deriveResolvedAuthIdentity, } from "./resolved-auth-identity.js";
@@ -188,6 +189,8 @@ async function refreshAccessToken(params) {
188
189
  timeoutMs: params.timeoutMs ?? AGY_TOKEN_TIMEOUT_MS,
189
190
  consume: async (response, timeoutSignal) => {
190
191
  if (!response.ok) {
192
+ const retryAtMs = retryAfterDeadline(response);
193
+ const retry = retryAtMs !== undefined ? { retryAtMs } : {};
191
194
  try {
192
195
  const errorData = (await response.json());
193
196
  if (errorData.error === "invalid_grant") {
@@ -196,6 +199,7 @@ async function refreshAccessToken(params) {
196
199
  return {
197
200
  error: errorData.error_description || `HTTP ${response.status}`,
198
201
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
202
+ ...retry,
199
203
  };
200
204
  }
201
205
  catch (error) {
@@ -204,6 +208,7 @@ async function refreshAccessToken(params) {
204
208
  return {
205
209
  error: `HTTP ${response.status}`,
206
210
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
211
+ ...retry,
207
212
  };
208
213
  }
209
214
  }
@@ -222,6 +227,13 @@ async function refreshAccessToken(params) {
222
227
  });
223
228
  }
224
229
  catch (err) {
230
+ if (err instanceof RequestTimeoutError) {
231
+ return {
232
+ error: "Token refresh timeout",
233
+ failureCategory: "provider_api",
234
+ ...(err.retryAtMs !== undefined ? { retryAtMs: err.retryAtMs } : {}),
235
+ };
236
+ }
225
237
  if (err instanceof Error && err.message.includes("timeout")) {
226
238
  return { error: "Token refresh timeout", failureCategory: "provider_api" };
227
239
  }
@@ -244,14 +256,26 @@ async function refreshAgyAccessTokenWithCache(params) {
244
256
  return { accessToken: params.account.accessToken };
245
257
  }
246
258
  }
247
- const refreshed = await refreshAccessToken({
248
- refreshToken: params.account.refreshToken,
249
- clientId: params.credentials.clientId,
250
- clientSecret: params.credentials.clientSecret,
251
- timeoutMs: params.timeoutMs,
252
- });
253
- if ("error" in refreshed)
254
- return refreshed;
259
+ // Guarded per refresh token: the token endpoint's limit is independent of quota reads.
260
+ const guarded = await tokenGuard(params.account.refreshToken, async () => {
261
+ const result = await refreshAccessToken({
262
+ refreshToken: params.account.refreshToken,
263
+ clientId: params.credentials.clientId,
264
+ clientSecret: params.credentials.clientSecret,
265
+ timeoutMs: params.timeoutMs,
266
+ });
267
+ return "error" in result
268
+ ? { success: false, ...result }
269
+ : { success: true, ...result };
270
+ }, params.timeoutMs);
271
+ if (!guarded.success) {
272
+ return {
273
+ error: guarded.error,
274
+ failureCategory: guarded.failureCategory,
275
+ ...(guarded.retryAtMs !== undefined ? { retryAtMs: guarded.retryAtMs } : {}),
276
+ };
277
+ }
278
+ const refreshed = { accessToken: guarded.accessToken, expiresIn: guarded.expiresIn };
255
279
  await setCachedAccessToken({
256
280
  key,
257
281
  entry: {
@@ -263,12 +287,27 @@ async function refreshAgyAccessTokenWithCache(params) {
263
287
  }
264
288
  class GoogleAgyQuotaRequestError extends Error {
265
289
  failureCategory;
266
- constructor(message, failureCategory) {
290
+ retryAtMs;
291
+ constructor(message, failureCategory, retryAtMs) {
267
292
  super(message);
268
293
  this.name = "GoogleAgyQuotaRequestError";
269
294
  this.failureCategory = failureCategory;
295
+ if (retryAtMs !== undefined)
296
+ this.retryAtMs = retryAtMs;
270
297
  }
271
298
  }
299
+ const tokenGuard = createApiKeyRetryGuard((retryAtMs) => ({
300
+ success: false,
301
+ error: "Token refresh failed: HTTP 429",
302
+ failureCategory: "provider_api",
303
+ retryAtMs,
304
+ }));
305
+ const accountGuard = createApiKeyRetryGuard((retryAtMs) => ({
306
+ success: false,
307
+ error: "Google AGY quota API error: 429",
308
+ failureCategory: "provider_api",
309
+ retryAtMs,
310
+ }));
272
311
  async function retrieveGoogleAgyQuotaSummary(accessToken, projectId, timeoutMs = AGY_QUOTA_TIMEOUT_MS) {
273
312
  return await fetchWithTimeout(AGY_QUOTA_SUMMARY_API_URL, {
274
313
  request: {
@@ -287,7 +326,7 @@ async function retrieveGoogleAgyQuotaSummary(accessToken, projectId, timeoutMs =
287
326
  const failureCategory = providerFailureCategoryForHttpStatus(response.status);
288
327
  throw new GoogleAgyQuotaRequestError(response.status === 401 || response.status === 403
289
328
  ? `Google AGY quota auth error: ${response.status}`
290
- : `Google AGY quota API error: ${response.status}`, failureCategory);
329
+ : `Google AGY quota API error: ${response.status}`, failureCategory, retryAfterDeadline(response));
291
330
  }
292
331
  return (await response.json());
293
332
  },
@@ -486,7 +525,36 @@ function mapSummaryBuckets(response, account, accountIndex) {
486
525
  }
487
526
  return Array.from(deduplicated.values()).sort(compareSummaryBuckets);
488
527
  }
528
+ /** Cooldowns are per refresh token + project; a concurrent identical call shares one request. */
489
529
  async function fetchAccountQuota(params) {
530
+ const accountEmail = params.account.email || params.account.sourceKey;
531
+ const { tokenRetryAtMs, ...result } = await accountGuard(`${params.account.refreshToken}\n${params.account.projectId}`, () => fetchAccountQuotaUncached(params), params.timeoutMs, (retryAtMs) => ({
532
+ success: false,
533
+ error: "Google AGY quota API error: 429",
534
+ failureCategory: "provider_api",
535
+ accountEmail,
536
+ retryAtMs,
537
+ }));
538
+ const buckets = result.buckets?.map((bucket) => {
539
+ const projected = {
540
+ ...bucket,
541
+ accountIndex: params.accountIndex,
542
+ sourceKey: params.account.sourceKey,
543
+ };
544
+ if (params.account.email)
545
+ projected.accountEmail = params.account.email;
546
+ else
547
+ delete projected.accountEmail;
548
+ return projected;
549
+ });
550
+ return {
551
+ ...result,
552
+ accountEmail,
553
+ ...(buckets ? { buckets } : {}),
554
+ ...(tokenRetryAtMs !== undefined ? { retryAtMs: tokenRetryAtMs } : {}),
555
+ };
556
+ }
557
+ async function fetchAccountQuotaUncached(params) {
490
558
  const accountEmail = params.account.email || params.account.sourceKey;
491
559
  try {
492
560
  const tokenResult = await refreshAgyAccessTokenWithCache({
@@ -500,6 +568,7 @@ async function fetchAccountQuota(params) {
500
568
  error: tokenResult.error,
501
569
  failureCategory: tokenResult.failureCategory,
502
570
  accountEmail,
571
+ ...(tokenResult.retryAtMs !== undefined ? { tokenRetryAtMs: tokenResult.retryAtMs } : {}),
503
572
  };
504
573
  }
505
574
  let summary;
@@ -520,6 +589,7 @@ async function fetchAccountQuota(params) {
520
589
  error: retryToken.error,
521
590
  failureCategory: retryToken.failureCategory,
522
591
  accountEmail,
592
+ ...(retryToken.retryAtMs !== undefined ? { tokenRetryAtMs: retryToken.retryAtMs } : {}),
523
593
  };
524
594
  }
525
595
  summary = await retrieveGoogleAgyQuotaSummary(retryToken.accessToken, params.account.projectId, params.timeoutMs);
@@ -546,6 +616,9 @@ async function fetchAccountQuota(params) {
546
616
  error: "API timeout",
547
617
  failureCategory: "provider_api",
548
618
  accountEmail,
619
+ ...(err instanceof RequestTimeoutError && err.retryAtMs !== undefined
620
+ ? { retryAtMs: err.retryAtMs }
621
+ : {}),
549
622
  };
550
623
  }
551
624
  return {
@@ -553,6 +626,9 @@ async function fetchAccountQuota(params) {
553
626
  error: err instanceof Error ? err.message : String(err),
554
627
  failureCategory: err instanceof GoogleAgyQuotaRequestError ? err.failureCategory : "provider_api",
555
628
  accountEmail,
629
+ ...(err instanceof GoogleAgyQuotaRequestError && err.retryAtMs !== undefined
630
+ ? { retryAtMs: err.retryAtMs }
631
+ : {}),
556
632
  };
557
633
  }
558
634
  }
@@ -585,17 +661,19 @@ export async function queryGoogleAgyQuota(options = {}) {
585
661
  }));
586
662
  const allBuckets = [];
587
663
  const errors = [];
588
- for (const result of results) {
664
+ for (const [accountIndex, result] of results.entries()) {
589
665
  if (result.success && result.buckets && result.buckets.length > 0) {
590
666
  allBuckets.push(...result.buckets);
591
667
  }
592
668
  else if (!result.success && result.error && result.accountEmail) {
593
669
  errors.push({
594
670
  email: result.accountEmail,
671
+ accountIndex,
595
672
  error: result.error,
596
673
  ...(result.failureCategory !== undefined
597
674
  ? { failureCategory: result.failureCategory }
598
675
  : {}),
676
+ ...(result.retryAtMs !== undefined ? { retryAtMs: result.retryAtMs } : {}),
599
677
  });
600
678
  }
601
679
  }