opencode-quota-gui 1.3.1 → 1.3.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 (155) hide show
  1. package/README.md +16 -12
  2. package/dist/contracts/build-identity.js +1 -1
  3. package/dist/contracts/card-order.d.ts +2 -0
  4. package/dist/contracts/card-order.js +2 -2
  5. package/dist/contracts/card-visibility.d.ts +2 -1
  6. package/dist/contracts/card-visibility.js +2 -1
  7. package/dist/contracts/dashboard.d.ts +87 -5
  8. package/dist/contracts/dashboard.js +10 -0
  9. package/dist/contracts/dto-guards.d.ts +4 -0
  10. package/dist/contracts/dto-guards.js +29 -7
  11. package/dist/contracts/guards.js +3 -1
  12. package/dist/contracts/identity.d.ts +37 -5
  13. package/dist/contracts/identity.js +43 -0
  14. package/dist/contracts/provider-auto-resume.d.ts +9 -0
  15. package/dist/contracts/provider-auto-resume.js +24 -0
  16. package/dist/contracts/provider-failure.d.ts +22 -0
  17. package/dist/contracts/provider-failure.js +25 -1
  18. package/dist/contracts/row-order.d.ts +13 -0
  19. package/dist/contracts/row-order.js +34 -0
  20. package/dist/contracts/row-visibility.d.ts +53 -0
  21. package/dist/contracts/row-visibility.js +130 -0
  22. package/dist/data/modelsdev-pricing.min.json +1 -1
  23. package/dist/data/modelsdev-temporal.min.json +3 -634
  24. package/dist/gui/aggregation.d.ts +29 -1
  25. package/dist/gui/aggregation.js +157 -4
  26. package/dist/gui/analytics-bridge.d.ts +8 -9
  27. package/dist/gui/analytics-bridge.js +197 -54
  28. package/dist/gui/analytics-engine.d.ts +7 -15
  29. package/dist/gui/analytics-engine.js +246 -106
  30. package/dist/gui/analytics-model.d.ts +7 -0
  31. package/dist/gui/analytics-model.js +75 -9
  32. package/dist/gui/analytics-pricing-upkeep.d.ts +21 -0
  33. package/dist/gui/analytics-pricing-upkeep.js +23 -0
  34. package/dist/gui/analytics-protocol.d.ts +17 -7
  35. package/dist/gui/analytics-protocol.js +1 -0
  36. package/dist/gui/analytics-service.d.ts +10 -0
  37. package/dist/gui/analytics-service.js +30 -9
  38. package/dist/gui/analytics-state.d.ts +30 -5
  39. package/dist/gui/analytics-state.js +46 -7
  40. package/dist/gui/analytics-worker-runtime.d.ts +5 -0
  41. package/dist/gui/analytics-worker-runtime.js +9 -1
  42. package/dist/gui/analytics-worker.js +11 -0
  43. package/dist/gui/config.d.ts +2 -2
  44. package/dist/gui/config.js +46 -5
  45. package/dist/gui/identity.d.ts +6 -20
  46. package/dist/gui/identity.js +6 -54
  47. package/dist/gui/primary-quota-windows.js +55 -34
  48. package/dist/gui/provider-cards.d.ts +12 -8
  49. package/dist/gui/provider-cards.js +12 -53
  50. package/dist/gui/quota-notification-detector.d.ts +25 -2
  51. package/dist/gui/quota-notification-detector.js +60 -5
  52. package/dist/gui/quota-notification-observer.d.ts +1 -1
  53. package/dist/gui/quota-notification-observer.js +5 -1
  54. package/dist/gui/quota-observation.d.ts +4 -0
  55. package/dist/gui/quota-observation.js +18 -0
  56. package/dist/gui/rpc.js +3 -0
  57. package/dist/gui/server.js +6 -1
  58. package/dist/gui/snapshot-service.d.ts +3 -17
  59. package/dist/gui/snapshot-service.js +159 -9
  60. package/dist/gui/sources.js +84 -11
  61. package/dist/gui/temporal-status.d.ts +3 -2
  62. package/dist/gui/temporal-status.js +10 -6
  63. package/dist/gui-experimental.cjs +228 -228
  64. package/dist/lib/accounting-format.d.ts +8 -0
  65. package/dist/lib/accounting-format.js +12 -2
  66. package/dist/lib/anthropic-api-auth.d.ts +7 -0
  67. package/dist/lib/anthropic-api-auth.js +27 -0
  68. package/dist/lib/anthropic-api-rate-limits.d.ts +47 -0
  69. package/dist/lib/anthropic-api-rate-limits.js +92 -0
  70. package/dist/lib/anthropic-oauth-throttle.d.ts +76 -0
  71. package/dist/lib/anthropic-oauth-throttle.js +379 -0
  72. package/dist/lib/anthropic.d.ts +22 -4
  73. package/dist/lib/anthropic.js +498 -180
  74. package/dist/lib/cache-observer-ingestion.js +27 -0
  75. package/dist/lib/cache-observer.d.ts +3 -0
  76. package/dist/lib/cache-observer.js +9 -3
  77. package/dist/lib/cli-show.d.ts +5 -0
  78. package/dist/lib/cli-show.js +16 -5
  79. package/dist/lib/cli-status.js +3 -6
  80. package/dist/lib/config.d.ts +1 -1
  81. package/dist/lib/config.js +64 -2
  82. package/dist/lib/dashboard-visibility.d.ts +5 -0
  83. package/dist/lib/dashboard-visibility.js +11 -10
  84. package/dist/lib/display-sanitize.js +1 -0
  85. package/dist/lib/entries.d.ts +10 -1
  86. package/dist/lib/entries.js +4 -0
  87. package/dist/lib/grouped-entry-normalization.js +1 -1
  88. package/dist/lib/maintainer-announcements.js +2 -2
  89. package/dist/lib/modelsdev-pricing.d.ts +74 -2
  90. package/dist/lib/modelsdev-pricing.js +457 -63
  91. package/dist/lib/modelsdev-temporal.d.ts +6 -0
  92. package/dist/lib/modelsdev-temporal.js +16 -2
  93. package/dist/lib/opencode-config-providers.js +2 -2
  94. package/dist/lib/opencode-storage.d.ts +20 -0
  95. package/dist/lib/opencode-storage.js +89 -2
  96. package/dist/lib/opencode-version-core.d.ts +7 -0
  97. package/dist/lib/opencode-version-core.js +10 -0
  98. package/dist/lib/opencode-warming-refresh.d.ts +19 -0
  99. package/dist/lib/opencode-warming-refresh.js +95 -0
  100. package/dist/lib/provider-metadata.d.ts +11 -3
  101. package/dist/lib/provider-metadata.js +20 -2
  102. package/dist/lib/provider-registration.d.ts +342 -3
  103. package/dist/lib/provider-registration.js +409 -27
  104. package/dist/lib/quota-auto-resume.d.ts +74 -0
  105. package/dist/lib/quota-auto-resume.js +539 -0
  106. package/dist/lib/quota-command-format.js +22 -9
  107. package/dist/lib/quota-identity.d.ts +64 -0
  108. package/dist/lib/quota-identity.js +111 -0
  109. package/dist/lib/quota-providers.js +2 -2
  110. package/dist/lib/quota-render-data.js +2 -2
  111. package/dist/lib/quota-reset-notifications.js +11 -155
  112. package/dist/lib/quota-retry-wait.d.ts +106 -5
  113. package/dist/lib/quota-retry-wait.js +301 -34
  114. package/dist/lib/quota-runtime-context.js +1 -0
  115. package/dist/lib/quota-state-codec.d.ts +2 -0
  116. package/dist/lib/quota-state-codec.js +14 -1
  117. package/dist/lib/quota-state.d.ts +1 -1
  118. package/dist/lib/quota-state.js +60 -28
  119. package/dist/lib/quota-stats.d.ts +26 -0
  120. package/dist/lib/quota-stats.js +19 -1
  121. package/dist/lib/quota-surface-data.js +18 -3
  122. package/dist/lib/quota-telemetry.js +2 -2
  123. package/dist/lib/resolved-auth-identity.d.ts +19 -0
  124. package/dist/lib/resolved-auth-identity.js +44 -0
  125. package/dist/lib/state-file-lock.d.ts +26 -0
  126. package/dist/lib/state-file-lock.js +205 -0
  127. package/dist/lib/toast-format-grouped.js +7 -4
  128. package/dist/lib/tui-compact-format.js +29 -16
  129. package/dist/lib/types.d.ts +20 -0
  130. package/dist/lib/types.js +4 -1
  131. package/dist/plugin.js +67 -1
  132. package/dist/providers/alibaba-coding-plan.js +21 -3
  133. package/dist/providers/alibaba-token-plan.js +9 -5
  134. package/dist/providers/anthropic.d.ts +6 -2
  135. package/dist/providers/anthropic.js +123 -14
  136. package/dist/providers/chutes.js +2 -0
  137. package/dist/providers/claude-agent.js +24 -5
  138. package/dist/providers/copilot.js +5 -4
  139. package/dist/providers/glm-coding-plan-provider.js +30 -23
  140. package/dist/providers/ollama-cloud.js +10 -0
  141. package/dist/providers/openai.js +24 -23
  142. package/dist/providers/opencode-go.js +7 -6
  143. package/dist/providers/opencode-zen.js +1 -1
  144. package/dist/providers/result-helpers.d.ts +4 -2
  145. package/dist/providers/result-helpers.js +5 -1
  146. package/dist/providers/synthetic.js +4 -0
  147. package/dist/providers/xai.js +9 -8
  148. package/dist/rpc.d.ts +8 -0
  149. package/dist/rpc.js +15 -2
  150. package/dist/ui/assets/{index-BcueIm3Z.css → index-6_g1FHs-.css} +1 -1
  151. package/dist/ui/assets/index-sZnGUuML.js +10 -0
  152. package/dist/ui/assets/{popover-4bFSvRZ7.js → popover-C4ZLYe9E.js} +1 -1
  153. package/dist/ui/index.html +2 -2
  154. package/package.json +3 -3
  155. package/dist/ui/assets/index-C6qRSoh8.js +0 -10
@@ -21,6 +21,14 @@ export type AccountingSemanticSortKey = readonly [
21
21
  ];
22
22
  export declare function getAccountingSemanticSortKey(entry: QuotaToastEntry): AccountingSemanticSortKey;
23
23
  export declare function compareAccountingSemanticEntries(left: QuotaToastEntry, right: QuotaToastEntry): number;
24
+ /**
25
+ * The row's display label. Explicit presentation labels supplied by the
26
+ * provider (`metricLabel`, then `label`) win for window, component and
27
+ * aggregate metrics: semantic metadata is identity and eligibility only, never
28
+ * a source of visible copy. A named metric is different: its semantic name is
29
+ * the row's identity, so the label is always derived from it and provider copy
30
+ * cannot drift it (the canonical Fable weekly window renders as "Fable").
31
+ */
24
32
  export declare function getAccountingEntryLabel(entry: QuotaToastEntry): string;
25
33
  export type AccountingBooleanWording = "semantic" | "generic";
26
34
  export type AccountingBasisRequest = {
@@ -234,10 +234,20 @@ export function compareAccountingSemanticEntries(left, right) {
234
234
  const rightKey = getAccountingSemanticSortKey(right);
235
235
  return leftKey[0] - rightKey[0] || leftKey[1] - rightKey[1] || leftKey[2] - rightKey[2];
236
236
  }
237
+ /**
238
+ * The row's display label. Explicit presentation labels supplied by the
239
+ * provider (`metricLabel`, then `label`) win for window, component and
240
+ * aggregate metrics: semantic metadata is identity and eligibility only, never
241
+ * a source of visible copy. A named metric is different: its semantic name is
242
+ * the row's identity, so the label is always derived from it and provider copy
243
+ * cannot drift it (the canonical Fable weekly window renders as "Fable").
244
+ */
237
245
  export function getAccountingEntryLabel(entry) {
246
+ const explicit = entry.metricLabel?.trim() || entry.label?.trim();
238
247
  if (!entry.semantic)
239
- return entry.metricLabel?.trim() || entry.label?.trim() || entry.name;
240
- return formatAccountingSemanticLabel(entry.accounting.resultType, entry.semantic, isPercentEntry(entry) ? "percent" : entry.kind);
248
+ return explicit || entry.name;
249
+ const semanticLabel = formatAccountingSemanticLabel(entry.accounting.resultType, entry.semantic, isPercentEntry(entry) ? "percent" : entry.kind);
250
+ return entry.semantic.metric.kind === "named" ? semanticLabel : explicit || semanticLabel;
241
251
  }
242
252
  export function interpretAccountingRow(entry, options) {
243
253
  const label = getAccountingEntryLabel(entry);
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Anthropic API-key discovery for the Anthropic API card. It is independent of the Claude Agent
3
+ * CLI login and of OpenCode's Anthropic OAuth entry (`./anthropic-auth.ts`): only an API key counts.
4
+ */
5
+ /** The configured Anthropic API key, or null. Callers must never log or display it. */
6
+ export declare function resolveAnthropicApiKey(): Promise<string | null>;
7
+ //# sourceMappingURL=anthropic-api-auth.d.ts.map
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Anthropic API-key discovery for the Anthropic API card. It is independent of the Claude Agent
3
+ * CLI login and of OpenCode's Anthropic OAuth entry (`./anthropic-auth.ts`): only an API key counts.
4
+ */
5
+ import { createProviderApiKeyResolver, getGlobalOpencodeConfigCandidatePaths, } from "./api-key-resolver.js";
6
+ import { getCredentialDatabasePaths, readAuthFile } from "./opencode-auth.js";
7
+ const ALLOWED_ANTHROPIC_ENV_VARS = ["ANTHROPIC_API_KEY"];
8
+ const ANTHROPIC_PROVIDER_KEYS = ["anthropic"];
9
+ const anthropicApiKeyResolver = createProviderApiKeyResolver({
10
+ envVars: [{ name: "ANTHROPIC_API_KEY", source: "env:ANTHROPIC_API_KEY" }],
11
+ providerKeys: ANTHROPIC_PROVIDER_KEYS,
12
+ allowedEnvVars: ALLOWED_ANTHROPIC_ENV_VARS,
13
+ configJsonSource: "opencode.json",
14
+ configJsoncSource: "opencode.jsonc",
15
+ getConfigCandidates: getGlobalOpencodeConfigCandidatePaths,
16
+ // The strict policy accepts only `type: "api"` entries, so an OAuth login never counts.
17
+ auth: {
18
+ readAuth: () => readAuthFile({ integrationIds: ANTHROPIC_PROVIDER_KEYS }),
19
+ getCredentialDatabasePaths,
20
+ authSource: "opencode.db",
21
+ },
22
+ });
23
+ /** The configured Anthropic API key, or null. Callers must never log or display it. */
24
+ export async function resolveAnthropicApiKey() {
25
+ return (await anthropicApiKeyResolver.resolve())?.key ?? null;
26
+ }
27
+ //# sourceMappingURL=anthropic-api-auth.js.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Passive Anthropic API rate-limit observations.
3
+ *
4
+ * A host `http.response` hook offers the response to real OpenCode Messages traffic; nothing here
5
+ * issues a request. Only first-party Messages responses to API-key (`x-api-key`) requests are
6
+ * kept, only the allowlisted rate-limit headers are read, and bodies and request content are never
7
+ * touched. Observations live in memory, keyed by a sha256 digest of the request's key so a key
8
+ * change never shows the previous key's limits; the digest is never persisted or displayed.
9
+ */
10
+ export interface AnthropicRateLimitMeter {
11
+ limit?: number;
12
+ remaining?: number;
13
+ resetAtIso?: string;
14
+ }
15
+ export declare const ANTHROPIC_RATE_LIMIT_METERS: readonly [readonly ["requests", "requests"], readonly ["tokens", "tokens"], readonly ["input-tokens", "inputTokens"], readonly ["output-tokens", "outputTokens"]];
16
+ type MeterName = (typeof ANTHROPIC_RATE_LIMIT_METERS)[number][1];
17
+ export interface AnthropicApiObservation {
18
+ observedAtMs: number;
19
+ status: number;
20
+ meters: Partial<Record<MeterName, AnthropicRateLimitMeter>>;
21
+ /** Seconds from a `retry-after` header, as sent with the observed response. */
22
+ retryAfterSeconds?: number;
23
+ }
24
+ export declare function digestAnthropicApiKey(apiKey: string): string;
25
+ export declare function readAnthropicApiObservation(keyDigest: string): AnthropicApiObservation | undefined;
26
+ export declare function clearAnthropicApiObservations(): void;
27
+ /**
28
+ * Offer one finished host request/response. Never throws, never awaits, never alters either side.
29
+ * Returns whether an observation was recorded.
30
+ */
31
+ export declare function observeAnthropicApiResponse(event: {
32
+ request: {
33
+ url: string;
34
+ headers: {
35
+ get(name: string): string | null;
36
+ };
37
+ };
38
+ response: {
39
+ status: number;
40
+ headers: {
41
+ get(name: string): string | null;
42
+ };
43
+ };
44
+ nowMs?: number;
45
+ }): boolean;
46
+ export {};
47
+ //# sourceMappingURL=anthropic-api-rate-limits.d.ts.map
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Passive Anthropic API rate-limit observations.
3
+ *
4
+ * A host `http.response` hook offers the response to real OpenCode Messages traffic; nothing here
5
+ * issues a request. Only first-party Messages responses to API-key (`x-api-key`) requests are
6
+ * kept, only the allowlisted rate-limit headers are read, and bodies and request content are never
7
+ * touched. Observations live in memory, keyed by a sha256 digest of the request's key so a key
8
+ * change never shows the previous key's limits; the digest is never persisted or displayed.
9
+ */
10
+ import { createHash } from "node:crypto";
11
+ export const ANTHROPIC_RATE_LIMIT_METERS = [
12
+ ["requests", "requests"],
13
+ ["tokens", "tokens"],
14
+ ["input-tokens", "inputTokens"],
15
+ ["output-tokens", "outputTokens"],
16
+ ];
17
+ const STATE_KEY = Symbol.for("opencode-quota-gui.anthropic-api-rate-limits.v1");
18
+ function observations() {
19
+ const holder = globalThis;
20
+ holder[STATE_KEY] ??= new Map();
21
+ return holder[STATE_KEY];
22
+ }
23
+ export function digestAnthropicApiKey(apiKey) {
24
+ return createHash("sha256").update(apiKey).digest("hex");
25
+ }
26
+ export function readAnthropicApiObservation(keyDigest) {
27
+ return observations().get(keyDigest);
28
+ }
29
+ export function clearAnthropicApiObservations() {
30
+ observations().clear();
31
+ }
32
+ function nonNegativeInteger(value) {
33
+ if (value === null || !/^\d+$/u.test(value.trim()))
34
+ return undefined;
35
+ const parsed = Number(value);
36
+ return Number.isSafeInteger(parsed) ? parsed : undefined;
37
+ }
38
+ function isoTimestamp(value) {
39
+ if (value === null)
40
+ return undefined;
41
+ const ms = Date.parse(value);
42
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
43
+ }
44
+ function isMessagesRequest(url) {
45
+ // `count_tokens` has its own limit and is not a Messages meter.
46
+ return (url.protocol === "https:" &&
47
+ url.hostname === "api.anthropic.com" &&
48
+ url.pathname === "/v1/messages");
49
+ }
50
+ /**
51
+ * Offer one finished host request/response. Never throws, never awaits, never alters either side.
52
+ * Returns whether an observation was recorded.
53
+ */
54
+ export function observeAnthropicApiResponse(event) {
55
+ try {
56
+ if (!isMessagesRequest(new URL(event.request.url)))
57
+ return false;
58
+ // Presence decides: Claude subscription (OAuth) traffic carries a bearer token instead.
59
+ const apiKey = event.request.headers.get("x-api-key");
60
+ if (apiKey === null || apiKey.trim() === "")
61
+ return false;
62
+ const meters = {};
63
+ for (const [header, name] of ANTHROPIC_RATE_LIMIT_METERS) {
64
+ const read = (suffix) => event.response.headers.get(`anthropic-ratelimit-${header}-${suffix}`);
65
+ const limit = nonNegativeInteger(read("limit"));
66
+ const remaining = nonNegativeInteger(read("remaining"));
67
+ const resetAtIso = isoTimestamp(read("reset"));
68
+ if (limit === undefined && remaining === undefined && resetAtIso === undefined)
69
+ continue;
70
+ meters[name] = {
71
+ ...(limit !== undefined ? { limit } : {}),
72
+ ...(remaining !== undefined ? { remaining } : {}),
73
+ ...(resetAtIso !== undefined ? { resetAtIso } : {}),
74
+ };
75
+ }
76
+ const retryAfterSeconds = nonNegativeInteger(event.response.headers.get("retry-after"));
77
+ // A response without any rate-limit header keeps the previous observation rather than erasing it.
78
+ if (Object.keys(meters).length === 0 && retryAfterSeconds === undefined)
79
+ return false;
80
+ observations().set(digestAnthropicApiKey(apiKey.trim()), {
81
+ observedAtMs: event.nowMs ?? Date.now(),
82
+ status: event.response.status,
83
+ meters,
84
+ ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),
85
+ });
86
+ return true;
87
+ }
88
+ catch {
89
+ return false;
90
+ }
91
+ }
92
+ //# sourceMappingURL=anthropic-api-rate-limits.js.map
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Cross-process request spacing and 429 cooldown for Anthropic's OAuth usage endpoint.
3
+ *
4
+ * Claude Agent is polled by every OpenCode process. Anthropic rate-limits per
5
+ * account, so two processes polling independently keep the limit alive. The
6
+ * shared record keeps timing only - never a token, token hash, account, email
7
+ * or any other identity - so it is safe under the Windows process-local
8
+ * identity contract.
9
+ *
10
+ * Claiming holds `state-file-lock` until the attempt publishes its outcome, so
11
+ * a concurrent process either sees the claimed attempt or skips; it never
12
+ * performs an independent fetch. A busy lock is a skip, not a wait.
13
+ */
14
+ /** Default minimum spacing between Anthropic usage requests. */
15
+ export declare const ANTHROPIC_OAUTH_DEFAULT_POLL_INTERVAL_MS = 180000;
16
+ /** The configured spacing may not go below one minute. */
17
+ export declare const ANTHROPIC_OAUTH_MIN_POLL_INTERVAL_MS = 60000;
18
+ /** A 429 without a usable Retry-After starts at one minute. */
19
+ export declare const ANTHROPIC_OAUTH_RATE_LIMIT_BASE_MS = 60000;
20
+ /** Our own exponential backoff is capped at five minutes. */
21
+ export declare const ANTHROPIC_OAUTH_RATE_LIMIT_MAX_MS: number;
22
+ /** A server Retry-After longer than one day is treated as malformed. */
23
+ export declare const ANTHROPIC_OAUTH_RETRY_AFTER_MAX_MS: number;
24
+ type AnthropicOAuthThrottleSkipReason = "spacing" | "cooldown" | "busy" | "unavailable";
25
+ type AnthropicOAuthAttemptCompletion = {
26
+ kind: "success";
27
+ }
28
+ /** A non-429 response ended any previous 429 backoff. */
29
+ | {
30
+ kind: "response";
31
+ }
32
+ /** No response was received; an existing 429 streak is preserved. */
33
+ | {
34
+ kind: "network-error";
35
+ } | {
36
+ kind: "rate-limited";
37
+ retryAfterMs?: number;
38
+ nowMs: number;
39
+ };
40
+ export interface AnthropicOAuthAttemptCompletionResult {
41
+ blockedUntilMs?: number;
42
+ failureCount: number;
43
+ }
44
+ export type AnthropicOAuthThrottleClaim = {
45
+ state: "claimed";
46
+ claimedAtMs: number;
47
+ failureCount: number;
48
+ /** Publishes the outcome and releases the claim; safe to call once. */
49
+ complete: (outcome: AnthropicOAuthAttemptCompletion) => Promise<AnthropicOAuthAttemptCompletionResult>;
50
+ } | {
51
+ state: "skip";
52
+ reason: AnthropicOAuthThrottleSkipReason;
53
+ /** The next real request time when one is known. */
54
+ retryAtMs?: number;
55
+ };
56
+ export declare function normalizeAnthropicOAuthPollIntervalMs(value: number | undefined): number;
57
+ export declare function getAnthropicOAuthRateLimitDurationMs(failureCount: number, retryAfterMs: number | undefined): number;
58
+ /** Reset per-process memory used only for tests; the shared file is untouched. */
59
+ export declare function resetAnthropicOAuthThrottleMemoryForTests(): void;
60
+ /** Remove the shared record and lock used only for tests. */
61
+ export declare function clearAnthropicOAuthThrottleStateForTests(): void;
62
+ /**
63
+ * Claim the next Anthropic usage request. The returned claim holds the
64
+ * cross-process lock until `complete` publishes the outcome; every skip path
65
+ * releases it before returning.
66
+ */
67
+ export declare function claimAnthropicOAuthUsageRequest(params: {
68
+ nowMs: number;
69
+ pollIntervalMs?: number;
70
+ requestTimeoutMs?: number;
71
+ /** Test seam: bound for reclaiming a live owner whose PID may have been reused. */
72
+ liveOwnerMaxAgeMs?: number;
73
+ statePath?: string;
74
+ }): Promise<AnthropicOAuthThrottleClaim>;
75
+ export {};
76
+ //# sourceMappingURL=anthropic-oauth-throttle.d.ts.map
@@ -0,0 +1,379 @@
1
+ /**
2
+ * Cross-process request spacing and 429 cooldown for Anthropic's OAuth usage endpoint.
3
+ *
4
+ * Claude Agent is polled by every OpenCode process. Anthropic rate-limits per
5
+ * account, so two processes polling independently keep the limit alive. The
6
+ * shared record keeps timing only - never a token, token hash, account, email
7
+ * or any other identity - so it is safe under the Windows process-local
8
+ * identity contract.
9
+ *
10
+ * Claiming holds `state-file-lock` until the attempt publishes its outcome, so
11
+ * a concurrent process either sees the claimed attempt or skips; it never
12
+ * performs an independent fetch. A busy lock is a skip, not a wait.
13
+ */
14
+ import { randomUUID } from "node:crypto";
15
+ import { rmSync } from "node:fs";
16
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
17
+ import { dirname } from "node:path";
18
+ import { getGuiPrivateStatePath } from "./private-state-paths.js";
19
+ import { acquireStateFileLock } from "./state-file-lock.js";
20
+ import { REQUEST_TIMEOUT_MS } from "./types.js";
21
+ /** Default minimum spacing between Anthropic usage requests. */
22
+ export const ANTHROPIC_OAUTH_DEFAULT_POLL_INTERVAL_MS = 180_000;
23
+ /** The configured spacing may not go below one minute. */
24
+ export const ANTHROPIC_OAUTH_MIN_POLL_INTERVAL_MS = 60_000;
25
+ /** A 429 without a usable Retry-After starts at one minute. */
26
+ export const ANTHROPIC_OAUTH_RATE_LIMIT_BASE_MS = 60_000;
27
+ /** Our own exponential backoff is capped at five minutes. */
28
+ export const ANTHROPIC_OAUTH_RATE_LIMIT_MAX_MS = 5 * 60_000;
29
+ /** A server Retry-After longer than one day is treated as malformed. */
30
+ export const ANTHROPIC_OAUTH_RETRY_AFTER_MAX_MS = 24 * 60 * 60_000;
31
+ const STATE_VERSION = 1;
32
+ const STATE_FILE_NAME = "anthropic-oauth-throttle.json";
33
+ const MAX_BACKOFF_EXPONENT = 30;
34
+ /** In-process fail-closed deadline for corrupt, unreadable or unpublishable shared state. */
35
+ let failClosedUntilMs = 0;
36
+ /**
37
+ * A completed rate-limit deadline whose shared write failed. The next claim
38
+ * retries the write before doing anything else; until then this process fails
39
+ * closed rather than letting the known cooldown be lost.
40
+ */
41
+ let pendingPublish;
42
+ function getAnthropicOAuthThrottleStatePath() {
43
+ return getGuiPrivateStatePath(STATE_FILE_NAME);
44
+ }
45
+ export function normalizeAnthropicOAuthPollIntervalMs(value) {
46
+ return typeof value === "number" && Number.isFinite(value) && value > 0
47
+ ? Math.max(ANTHROPIC_OAUTH_MIN_POLL_INTERVAL_MS, value)
48
+ : ANTHROPIC_OAUTH_DEFAULT_POLL_INTERVAL_MS;
49
+ }
50
+ export function getAnthropicOAuthRateLimitDurationMs(failureCount, retryAfterMs) {
51
+ if (retryAfterMs !== undefined &&
52
+ Number.isFinite(retryAfterMs) &&
53
+ retryAfterMs > 0 &&
54
+ retryAfterMs <= ANTHROPIC_OAUTH_RETRY_AFTER_MAX_MS) {
55
+ // A server deadline is honored in full; the five-minute cap only applies to
56
+ // our own backoff when the header is missing, zero, or malformed.
57
+ return retryAfterMs;
58
+ }
59
+ return Math.min(ANTHROPIC_OAUTH_RATE_LIMIT_BASE_MS * 2 ** Math.min(failureCount, MAX_BACKOFF_EXPONENT), ANTHROPIC_OAUTH_RATE_LIMIT_MAX_MS);
60
+ }
61
+ /** Reset per-process memory used only for tests; the shared file is untouched. */
62
+ export function resetAnthropicOAuthThrottleMemoryForTests() {
63
+ failClosedUntilMs = 0;
64
+ pendingPublish = undefined;
65
+ }
66
+ /** Remove the shared record and lock used only for tests. */
67
+ export function clearAnthropicOAuthThrottleStateForTests() {
68
+ failClosedUntilMs = 0;
69
+ pendingPublish = undefined;
70
+ const statePath = getAnthropicOAuthThrottleStatePath();
71
+ try {
72
+ rmSync(statePath, { force: true });
73
+ }
74
+ catch {
75
+ // A test directory may already be gone.
76
+ }
77
+ try {
78
+ rmSync(`${statePath}.lock`, { recursive: true, force: true });
79
+ }
80
+ catch {
81
+ // A test directory may already be gone.
82
+ }
83
+ }
84
+ function isFileSystemError(error, code) {
85
+ return error?.code === code;
86
+ }
87
+ function isRecord(value) {
88
+ return typeof value === "object" && value !== null && !Array.isArray(value);
89
+ }
90
+ function isPositiveFinite(value) {
91
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
92
+ }
93
+ function isNonNegativeInteger(value) {
94
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
95
+ }
96
+ function parseState(raw, nowMs) {
97
+ let value;
98
+ try {
99
+ value = JSON.parse(raw);
100
+ }
101
+ catch {
102
+ return { kind: "corrupt" };
103
+ }
104
+ if (!isRecord(value) || value.version !== STATE_VERSION)
105
+ return { kind: "corrupt" };
106
+ const issuedAtMs = value.issuedAtMs;
107
+ if (!isPositiveFinite(issuedAtMs))
108
+ return { kind: "corrupt" };
109
+ const lastAttemptAtMs = value.lastAttemptAtMs;
110
+ const blockedUntilMs = value.blockedUntilMs;
111
+ const failureCount = value.failureCount;
112
+ if (lastAttemptAtMs !== undefined && !isPositiveFinite(lastAttemptAtMs))
113
+ return { kind: "corrupt" };
114
+ if (blockedUntilMs !== undefined && !isPositiveFinite(blockedUntilMs))
115
+ return { kind: "corrupt" };
116
+ if (failureCount !== undefined && !isNonNegativeInteger(failureCount))
117
+ return { kind: "corrupt" };
118
+ // Clock rollback: never trust the future timestamps for scheduling, but do
119
+ // honor a recorded deadline for a bounded time. The caller repairs the record.
120
+ if (issuedAtMs > nowMs || (lastAttemptAtMs !== undefined && lastAttemptAtMs > nowMs)) {
121
+ const recordedDeadlineLengthMs = blockedUntilMs !== undefined ? Math.max(0, blockedUntilMs - issuedAtMs) : 0;
122
+ return {
123
+ kind: "rollback",
124
+ blockedForMs: Math.min(recordedDeadlineLengthMs, ANTHROPIC_OAUTH_RATE_LIMIT_MAX_MS),
125
+ failureCount: failureCount !== undefined ? Math.min(failureCount, MAX_BACKOFF_EXPONENT) : 0,
126
+ };
127
+ }
128
+ return {
129
+ kind: "ok",
130
+ state: {
131
+ version: STATE_VERSION,
132
+ issuedAtMs,
133
+ ...(lastAttemptAtMs !== undefined ? { lastAttemptAtMs } : {}),
134
+ ...(blockedUntilMs !== undefined
135
+ ? // A far-future deadline from a corrupt or hostile file must not block
136
+ // forever; a server Retry-After is honored up to the 24-hour safety limit.
137
+ {
138
+ blockedUntilMs: Math.min(blockedUntilMs, nowMs + ANTHROPIC_OAUTH_RETRY_AFTER_MAX_MS),
139
+ }
140
+ : {}),
141
+ ...(failureCount !== undefined
142
+ ? { failureCount: Math.min(failureCount, MAX_BACKOFF_EXPONENT) }
143
+ : {}),
144
+ },
145
+ };
146
+ }
147
+ async function readState(statePath, nowMs) {
148
+ let raw;
149
+ try {
150
+ raw = await readFile(statePath, "utf8");
151
+ }
152
+ catch (error) {
153
+ if (isFileSystemError(error, "ENOENT"))
154
+ return { state: undefined, unreadable: false };
155
+ return { state: undefined, unreadable: true };
156
+ }
157
+ return { state: parseState(raw, nowMs), unreadable: false };
158
+ }
159
+ async function writeState(statePath, state) {
160
+ const tempPath = `${statePath}.${process.pid}.${randomUUID()}.tmp`;
161
+ try {
162
+ await writeFile(tempPath, JSON.stringify(state), { encoding: "utf8", mode: 0o600 });
163
+ await rename(tempPath, statePath);
164
+ }
165
+ catch (error) {
166
+ await rm(tempPath, { force: true }).catch(() => undefined);
167
+ throw error;
168
+ }
169
+ }
170
+ async function acquireClaimLock(statePath, liveOwnerMaxAgeMs) {
171
+ try {
172
+ await mkdir(dirname(statePath), { recursive: true, mode: 0o700 });
173
+ // A busy lock means another process is already attempting or publishing.
174
+ // Skipping (instead of waiting) is the cross-process contract.
175
+ return await acquireStateFileLock(statePath, { timeoutMs: 0, liveOwnerMaxAgeMs });
176
+ }
177
+ catch {
178
+ return undefined;
179
+ }
180
+ }
181
+ /**
182
+ * Claim the next Anthropic usage request. The returned claim holds the
183
+ * cross-process lock until `complete` publishes the outcome; every skip path
184
+ * releases it before returning.
185
+ */
186
+ export async function claimAnthropicOAuthUsageRequest(params) {
187
+ const { nowMs } = params;
188
+ const pollIntervalMs = normalizeAnthropicOAuthPollIntervalMs(params.pollIntervalMs);
189
+ const statePath = params.statePath ?? getAnthropicOAuthThrottleStatePath();
190
+ const liveOwnerMaxAgeMs = params.liveOwnerMaxAgeMs ??
191
+ 2 * (params.requestTimeoutMs ?? REQUEST_TIMEOUT_MS) + pollIntervalMs;
192
+ // A pending deadline is retried under the lock rather than skipped here.
193
+ if (nowMs < failClosedUntilMs && pendingPublish?.statePath !== statePath) {
194
+ return { state: "skip", reason: "unavailable", retryAtMs: failClosedUntilMs };
195
+ }
196
+ const release = await acquireClaimLock(statePath, liveOwnerMaxAgeMs);
197
+ if (!release)
198
+ return { state: "skip", reason: "busy" };
199
+ const skipAndRelease = async (skip) => {
200
+ await release().catch(() => undefined);
201
+ return skip;
202
+ };
203
+ try {
204
+ if (pendingPublish?.statePath === statePath) {
205
+ const pending = pendingPublish;
206
+ try {
207
+ // A previous completion could not publish its deadline; write it before
208
+ // any new decision so another process cannot act on stale timing.
209
+ await writeState(statePath, pending.state);
210
+ pendingPublish = undefined;
211
+ failClosedUntilMs = 0;
212
+ }
213
+ catch {
214
+ const retryAtMs = Math.max(pending.state.blockedUntilMs ?? 0, nowMs + pollIntervalMs);
215
+ failClosedUntilMs = Math.max(failClosedUntilMs, retryAtMs);
216
+ return await skipAndRelease({
217
+ state: "skip",
218
+ reason: "unavailable",
219
+ retryAtMs,
220
+ });
221
+ }
222
+ }
223
+ if (nowMs < failClosedUntilMs) {
224
+ return await skipAndRelease({
225
+ state: "skip",
226
+ reason: "unavailable",
227
+ retryAtMs: failClosedUntilMs,
228
+ });
229
+ }
230
+ const read = await readState(statePath, nowMs);
231
+ if (read.unreadable || read.state?.kind === "corrupt") {
232
+ // Fail closed until one interval from now, and repair the record so the
233
+ // next interval can attempt instead of blocking forever.
234
+ failClosedUntilMs = Math.max(failClosedUntilMs, nowMs + pollIntervalMs);
235
+ await writeState(statePath, {
236
+ version: STATE_VERSION,
237
+ issuedAtMs: nowMs,
238
+ lastAttemptAtMs: nowMs,
239
+ }).catch(() => undefined);
240
+ return await skipAndRelease({
241
+ state: "skip",
242
+ reason: "unavailable",
243
+ retryAtMs: nowMs + pollIntervalMs,
244
+ });
245
+ }
246
+ if (read.state?.kind === "rollback") {
247
+ const delayMs = read.state.blockedForMs;
248
+ if (delayMs > 0) {
249
+ // The clock moved backward, but a recorded cooldown length is still
250
+ // honored for at most our own five-minute backoff cap. Then the record
251
+ // is rewritten with a sane clock so the next interval can proceed.
252
+ const repaired = {
253
+ version: STATE_VERSION,
254
+ issuedAtMs: nowMs,
255
+ blockedUntilMs: nowMs + delayMs,
256
+ failureCount: read.state.failureCount,
257
+ };
258
+ try {
259
+ await writeState(statePath, repaired);
260
+ }
261
+ catch {
262
+ pendingPublish = { statePath, state: repaired };
263
+ }
264
+ failClosedUntilMs = Math.max(failClosedUntilMs, nowMs + delayMs);
265
+ return await skipAndRelease({
266
+ state: "skip",
267
+ reason: "cooldown",
268
+ retryAtMs: nowMs + delayMs,
269
+ });
270
+ }
271
+ // No recorded deadline: the claim below re-establishes the clock.
272
+ }
273
+ const state = read.state?.kind === "ok" ? read.state.state : undefined;
274
+ if (state?.blockedUntilMs !== undefined && state.blockedUntilMs > nowMs) {
275
+ // Spacing still applies after the server deadline, and the caller shows
276
+ // the next real attempt.
277
+ const spacingUntilMs = state.lastAttemptAtMs !== undefined ? state.lastAttemptAtMs + pollIntervalMs : 0;
278
+ return await skipAndRelease({
279
+ state: "skip",
280
+ reason: "cooldown",
281
+ retryAtMs: Math.ceil(Math.max(state.blockedUntilMs, spacingUntilMs)),
282
+ });
283
+ }
284
+ if (state?.lastAttemptAtMs !== undefined && state.lastAttemptAtMs + pollIntervalMs > nowMs) {
285
+ return await skipAndRelease({
286
+ state: "skip",
287
+ reason: "spacing",
288
+ retryAtMs: Math.ceil(state.lastAttemptAtMs + pollIntervalMs),
289
+ });
290
+ }
291
+ const claimedAtMs = nowMs;
292
+ const failureCount = state?.failureCount ?? 0;
293
+ // A provisional deadline is published before the HTTP attempt. If this
294
+ // process dies mid-request, another process waits at least our own first
295
+ // backoff step instead of seeing only the request spacing.
296
+ await writeState(statePath, {
297
+ version: STATE_VERSION,
298
+ issuedAtMs: nowMs,
299
+ lastAttemptAtMs: claimedAtMs,
300
+ blockedUntilMs: claimedAtMs + ANTHROPIC_OAUTH_RATE_LIMIT_BASE_MS,
301
+ failureCount,
302
+ });
303
+ let completed = false;
304
+ let completionResult = { failureCount };
305
+ const complete = async (outcome) => {
306
+ // The 429 deadline is published before the body read; a later completion
307
+ // call returns the same deadline instead of overwriting it.
308
+ if (completed)
309
+ return completionResult;
310
+ completed = true;
311
+ const outcomeNowMs = outcome.kind === "rate-limited" ? outcome.nowMs : Date.now();
312
+ try {
313
+ const fresh = await readState(statePath, outcomeNowMs);
314
+ const base = fresh.unreadable || fresh.state?.kind !== "ok" ? undefined : fresh.state.state;
315
+ const baseLastAttemptAtMs = Math.max(base?.lastAttemptAtMs ?? 0, claimedAtMs);
316
+ const baseFailureCount = base?.failureCount ?? failureCount;
317
+ const result = outcome.kind === "rate-limited"
318
+ ? {
319
+ blockedUntilMs: Math.ceil(outcomeNowMs +
320
+ getAnthropicOAuthRateLimitDurationMs(baseFailureCount, outcome.retryAfterMs)),
321
+ failureCount: Math.min(baseFailureCount + 1, MAX_BACKOFF_EXPONENT),
322
+ }
323
+ : outcome.kind === "success" || outcome.kind === "response"
324
+ ? { failureCount: 0 }
325
+ : { failureCount: baseFailureCount };
326
+ const nextState = {
327
+ version: STATE_VERSION,
328
+ issuedAtMs: outcomeNowMs,
329
+ lastAttemptAtMs: baseLastAttemptAtMs,
330
+ ...(result.blockedUntilMs !== undefined ? { blockedUntilMs: result.blockedUntilMs } : {}),
331
+ failureCount: result.failureCount,
332
+ };
333
+ try {
334
+ await writeState(statePath, nextState);
335
+ }
336
+ catch {
337
+ // Keep the known deadline in-process and retry the shared write on the
338
+ // next claim; the provisional record already blocks other processes.
339
+ pendingPublish = { statePath, state: nextState };
340
+ failClosedUntilMs = Math.max(failClosedUntilMs, nextState.blockedUntilMs ?? outcomeNowMs + pollIntervalMs);
341
+ }
342
+ completionResult = result;
343
+ }
344
+ catch {
345
+ // A read failure must not discard a proven 429 deadline either.
346
+ if (outcome.kind === "rate-limited") {
347
+ const blockedUntilMs = Math.ceil(outcomeNowMs + getAnthropicOAuthRateLimitDurationMs(failureCount, outcome.retryAfterMs));
348
+ const nextFailureCount = Math.min(failureCount + 1, MAX_BACKOFF_EXPONENT);
349
+ const nextState = {
350
+ version: STATE_VERSION,
351
+ issuedAtMs: outcomeNowMs,
352
+ lastAttemptAtMs: claimedAtMs,
353
+ blockedUntilMs,
354
+ failureCount: nextFailureCount,
355
+ };
356
+ pendingPublish = { statePath, state: nextState };
357
+ failClosedUntilMs = Math.max(failClosedUntilMs, blockedUntilMs);
358
+ completionResult = {
359
+ blockedUntilMs,
360
+ failureCount: nextFailureCount,
361
+ };
362
+ }
363
+ }
364
+ finally {
365
+ await release().catch(() => undefined);
366
+ }
367
+ return completionResult;
368
+ };
369
+ return { state: "claimed", claimedAtMs, failureCount, complete };
370
+ }
371
+ catch {
372
+ return await skipAndRelease({
373
+ state: "skip",
374
+ reason: "unavailable",
375
+ retryAtMs: nowMs + pollIntervalMs,
376
+ });
377
+ }
378
+ }
379
+ //# sourceMappingURL=anthropic-oauth-throttle.js.map