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
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Pure, bounded retention-estimate model for cache observation. This module does
3
+ * not read storage, subscribe to host events, issue requests, or observe provider
4
+ * cache validity. Every colour is an estimate: the retention window starts at the
5
+ * request start of the newest successful primary LLM call on the scoped route,
6
+ * plus a route-scoped retention policy, regardless of its cache read or write
7
+ * counters.
8
+ */
9
+ export declare const CACHE_OBSERVER_MAX_INVOCATIONS = 128;
10
+ export interface CacheEvidenceBasis {
11
+ /** The concrete source that supplied this fact (not a guessed provider rule). */
12
+ source: string;
13
+ /** An opaque source reference, such as a message id or documentation locator. */
14
+ reference: string;
15
+ }
16
+ /** Selected provider/model/variant from Started; this does not prove the effective HTTP route. */
17
+ export interface CacheRouteProvenance {
18
+ providerId: string;
19
+ modelId: string;
20
+ variantId?: string;
21
+ protocolId?: "anthropic-messages";
22
+ basis: CacheEvidenceBasis;
23
+ }
24
+ export interface CacheInvocationOrder {
25
+ /** Physical assistant-message completion time from ingestion. */
26
+ completedAtMs: number;
27
+ /** Stable source tie-breaker for invocations sharing a completion time. */
28
+ messageId: string;
29
+ }
30
+ /**
31
+ * Omitted means the category was not reported. A reported zero is a real value;
32
+ * the ingestion layer decides whether an all-zero set is usable telemetry.
33
+ */
34
+ export interface CacheInvocationCounts {
35
+ /** Host-reported fresh input tokens, distinct from cache reads and writes. */
36
+ fresh?: number;
37
+ /** Host-reported cache-read tokens. */
38
+ read?: number;
39
+ /** Host-reported cache-write tokens. */
40
+ write?: number;
41
+ }
42
+ /**
43
+ * A successful, eligible primary LLM request (finish `stop` or `tool-calls`).
44
+ * Failed or incomplete requests are excluded by the ingestion layer before they
45
+ * reach this model.
46
+ */
47
+ export interface CacheInvocationObservation {
48
+ sessionId: string;
49
+ order: CacheInvocationOrder;
50
+ /** Host request-start timestamp (step.started), not exact provider acceptance; completion time is never a TTL origin. */
51
+ dispatchAtMs?: number;
52
+ route?: CacheRouteProvenance;
53
+ /** The concrete source that established this invocation as an eligible primary request. */
54
+ basis: CacheEvidenceBasis;
55
+ counts: CacheInvocationCounts;
56
+ /** Best-effort current configuration snapshot captured during this live call. */
57
+ configuredTtlMs?: CacheConfiguredTtlMs;
58
+ connectionMethod?: "oauth" | "key" | "external";
59
+ /** Claude Agent only: this exact invocation's cache writes were observed as 1-hour-only. */
60
+ observedTtlMs?: 3_600_000;
61
+ }
62
+ /** Host-configured retention values the observer accepts for a configurable route. */
63
+ export type CacheConfiguredTtlMs = 300_000 | 3_600_000;
64
+ /** Retention windows an estimate may use. */
65
+ export type CacheSupportedTtlMs = CacheConfiguredTtlMs | 1_800_000 | 86_400_000;
66
+ /**
67
+ * Host-derived facts about one route. Absent fields mean the route's policy default
68
+ * applies: the observer never assumes a direct OpenAI API route it cannot confirm.
69
+ */
70
+ export interface CacheRouteConfiguration {
71
+ /** The host's `cache.ttl` for a configurable route (direct Anthropic or Kimi). */
72
+ configuredTtlMs?: CacheConfiguredTtlMs;
73
+ }
74
+ export interface CacheTtlEstimate {
75
+ /**
76
+ * configured: the host-configured `cache.ttl` for a configurable route; documented:
77
+ * vendor documentation; empirical: owner-approved observed retention; observed: Claude Agent 1-hour-only cache writes matched to this call; fallback:
78
+ * the generic 5-minute window for unknown, gateway, and OpenAI-family routes.
79
+ */
80
+ kind: "configured" | "documented" | "empirical" | "observed" | "fallback";
81
+ ttlMs: CacheSupportedTtlMs;
82
+ source: string;
83
+ reference: string;
84
+ assumption: string;
85
+ /** Omitted when the source has no valid request-start timestamp. */
86
+ dispatchAtMs?: number;
87
+ /** Estimated boundary only; this is not proof of physical eviction. */
88
+ deadlineAtMs?: number;
89
+ }
90
+ export interface CacheObserverScope {
91
+ /** Each child session is classified independently; no tree roll-up occurs. */
92
+ sessionId: string;
93
+ route?: CacheRouteProvenance;
94
+ }
95
+ /** Immutable-by-convention value state; update helpers return a new bounded state. */
96
+ export interface CacheObserverState {
97
+ readonly scope: CacheObserverScope;
98
+ readonly invocations: readonly CacheInvocationObservation[];
99
+ }
100
+ export interface CachePrimaryRatio {
101
+ /** Host-reported usage telemetry only; not protocol, cache-validity, or TTL evidence. */
102
+ value: number;
103
+ messageId: string;
104
+ /** Source assistant-message completion time; no age/staleness threshold is inferred. */
105
+ observedAtMs: number;
106
+ numerator: "cache-read";
107
+ denominator: "fresh+read+write";
108
+ basis: CacheEvidenceBasis;
109
+ }
110
+ export type CacheObserverColor = "gray" | "green" | "yellow" | "red";
111
+ /**
112
+ * The reason union is the Native pill's reason vocabulary. Members this model no
113
+ * longer produces are retained only so the pill's exhaustive reason mapping still
114
+ * type-checks; they should be pruned with that consumer.
115
+ */
116
+ export type CacheObserverReason = "insufficient-evidence" | "observed-reuse-with-active-ttl" | "observed-write-with-active-ttl" | "ambiguous-invocation" | "history-truncated" | "ttl-unverified" | "ttl-expired" | "dispatch-time-unavailable" | "estimated-reuse-within-ttl" | "estimated-write-within-ttl" | "estimated-within-ttl" | "estimated-ttl-near-expiry" | "estimated-ttl-expired" | "out-of-order-invocation" | "observation-gap" | "route-unverified" | "invalidation-unverified" | "known-invalidation" | "compaction-boundary-uncertain" | "assumed-route-risk";
117
+ export interface CacheObserverClassification {
118
+ color: CacheObserverColor;
119
+ reason: CacheObserverReason;
120
+ ttlEstimate?: CacheTtlEstimate;
121
+ primaryCacheReadRatio?: CachePrimaryRatio;
122
+ /** Distinguishes received but unusable usage counters from no observed step telemetry. */
123
+ primaryCacheReadTelemetry?: "available" | "unavailable";
124
+ /** Earliest instant to reconsider the estimate without a newer event. */
125
+ recheckAtMs?: number;
126
+ }
127
+ export declare function createCacheObserverState(scope: CacheObserverScope): CacheObserverState;
128
+ export declare function observeCacheInvocation(state: CacheObserverState, observation: CacheInvocationObservation): CacheObserverState;
129
+ export declare function classifyCacheObserverState(state: CacheObserverState, nowMs: number, routeConfiguration?: CacheRouteConfiguration): CacheObserverClassification;
130
+ /**
131
+ * The host's `cache.ttl` value (`<number><ms|s|m|h|d>`, models.dev duration format)
132
+ * as one of the windows the observer accepts. Any other value is unsupported and
133
+ * yields undefined, so the route's default applies.
134
+ */
135
+ export declare function cacheConfiguredTtlMsFromHostValue(value: unknown): CacheConfiguredTtlMs | undefined;
136
+ /** Providers whose host `cache.ttl` the observer reads: direct Anthropic and Kimi. */
137
+ export declare function isCacheConfigurableProviderId(providerId: string): boolean;
138
+ //# sourceMappingURL=cache-observer.d.ts.map
@@ -0,0 +1,317 @@
1
+ /**
2
+ * Pure, bounded retention-estimate model for cache observation. This module does
3
+ * not read storage, subscribe to host events, issue requests, or observe provider
4
+ * cache validity. Every colour is an estimate: the retention window starts at the
5
+ * request start of the newest successful primary LLM call on the scoped route,
6
+ * plus a route-scoped retention policy, regardless of its cache read or write
7
+ * counters.
8
+ */
9
+ export const CACHE_OBSERVER_MAX_INVOCATIONS = 128;
10
+ export function createCacheObserverState(scope) {
11
+ if (!scope.sessionId.trim())
12
+ throw new TypeError("cache observer sessionId must be non-empty");
13
+ return {
14
+ scope: {
15
+ ...scope,
16
+ ...(scope.route === undefined
17
+ ? {}
18
+ : { route: { ...scope.route, basis: { ...scope.route.basis } } }),
19
+ },
20
+ invocations: [],
21
+ };
22
+ }
23
+ export function observeCacheInvocation(state, observation) {
24
+ assertSession(state, observation.sessionId);
25
+ // A missing route is retained so a newer unrouted invocation cannot leave an
26
+ // older estimate looking current; it classifies as route-unverified.
27
+ if (observation.route !== undefined)
28
+ assertRoute(state.scope.route, observation.route);
29
+ assertOrder(observation.order);
30
+ const withoutRevision = state.invocations.filter((entry) => entry.order.messageId !== observation.order.messageId);
31
+ const invocations = [...withoutRevision, cloneInvocation(observation)].sort((a, b) => compareOrder(a.order, b.order));
32
+ return {
33
+ ...state,
34
+ invocations: invocations.slice(-CACHE_OBSERVER_MAX_INVOCATIONS),
35
+ };
36
+ }
37
+ export function classifyCacheObserverState(state, nowMs, routeConfiguration = {}) {
38
+ const latest = last(state.invocations);
39
+ if (latest === undefined)
40
+ return { color: "gray", reason: "insufficient-evidence" };
41
+ // The cache share belongs to the newest successful call and stays independent
42
+ // of the retention estimate, so a route-unverified estimate still shows it.
43
+ const telemetry = primaryRatioOf(latest);
44
+ const reported = {
45
+ primaryCacheReadTelemetry: telemetry.status,
46
+ ...optionalRatio(telemetry.ratio),
47
+ };
48
+ if (!Number.isFinite(nowMs) || !hasValidRouteProvenance(state.scope.route)) {
49
+ return { color: "gray", reason: "route-unverified", ...reported };
50
+ }
51
+ if (!hasValidRouteProvenance(latest.route)) {
52
+ return { color: "gray", reason: "route-unverified", ...reported };
53
+ }
54
+ const policy = retentionPolicy(latest.route, latest.configuredTtlMs === undefined
55
+ ? routeConfiguration
56
+ : { configuredTtlMs: latest.configuredTtlMs }, latest.connectionMethod, latest.observedTtlMs);
57
+ const ttlEstimate = {
58
+ kind: policy.kind,
59
+ ttlMs: policy.ttlMs,
60
+ source: policy.source,
61
+ reference: policy.reference,
62
+ assumption: policy.assumption,
63
+ };
64
+ if (!hasValidDispatchTime(latest, nowMs)) {
65
+ return { color: "gray", reason: "dispatch-time-unavailable", ttlEstimate, ...reported };
66
+ }
67
+ const dispatchAtMs = latest.dispatchAtMs;
68
+ const deadlineAtMs = dispatchAtMs + policy.ttlMs;
69
+ const warningAtMs = dispatchAtMs + Math.floor(policy.ttlMs * 0.8);
70
+ const estimate = { ...ttlEstimate, dispatchAtMs, deadlineAtMs };
71
+ if (deadlineAtMs <= nowMs) {
72
+ return { color: "red", reason: "estimated-ttl-expired", ttlEstimate: estimate, ...reported };
73
+ }
74
+ if (warningAtMs <= nowMs) {
75
+ return {
76
+ color: "yellow",
77
+ reason: "estimated-ttl-near-expiry",
78
+ ttlEstimate: estimate,
79
+ recheckAtMs: deadlineAtMs,
80
+ ...reported,
81
+ };
82
+ }
83
+ return {
84
+ color: "green",
85
+ reason: greenReasonFor(latest.counts),
86
+ ttlEstimate: estimate,
87
+ recheckAtMs: warningAtMs,
88
+ ...reported,
89
+ };
90
+ }
91
+ const DURATION_UNIT_MS = {
92
+ ms: 1,
93
+ s: 1_000,
94
+ m: 60_000,
95
+ h: 3_600_000,
96
+ d: 86_400_000,
97
+ };
98
+ /**
99
+ * The host's `cache.ttl` value (`<number><ms|s|m|h|d>`, models.dev duration format)
100
+ * as one of the windows the observer accepts. Any other value is unsupported and
101
+ * yields undefined, so the route's default applies.
102
+ */
103
+ export function cacheConfiguredTtlMsFromHostValue(value) {
104
+ if (typeof value !== "string")
105
+ return undefined;
106
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/.exec(value.trim());
107
+ if (match === null)
108
+ return undefined;
109
+ const ttlMs = Number(match[1]) * DURATION_UNIT_MS[match[2]];
110
+ return ttlMs === 300_000 || ttlMs === 3_600_000 ? ttlMs : undefined;
111
+ }
112
+ /** Providers whose host `cache.ttl` the observer reads: direct Anthropic and Kimi. */
113
+ export function isCacheConfigurableProviderId(providerId) {
114
+ return providerId === "anthropic" || KIMI_PROVIDER_IDS.has(providerId);
115
+ }
116
+ function assertSession(state, sessionId) {
117
+ if (sessionId !== state.scope.sessionId) {
118
+ throw new TypeError("cache observer evidence belongs to a different session");
119
+ }
120
+ }
121
+ function assertRoute(expected, observed) {
122
+ if (!sameRoute(expected, observed)) {
123
+ throw new TypeError("cache observer evidence belongs to a different or unknown route");
124
+ }
125
+ }
126
+ function assertOrder(order) {
127
+ if (!Number.isFinite(order.completedAtMs) || !order.messageId.trim()) {
128
+ throw new TypeError("cache observer ordering requires a finite completion time and message id");
129
+ }
130
+ }
131
+ function cloneInvocation(entry) {
132
+ return {
133
+ ...entry,
134
+ order: { ...entry.order },
135
+ ...(entry.route === undefined
136
+ ? {}
137
+ : { route: { ...entry.route, basis: { ...entry.route.basis } } }),
138
+ basis: { ...entry.basis },
139
+ counts: { ...entry.counts },
140
+ };
141
+ }
142
+ function compareOrder(a, b) {
143
+ if (a.completedAtMs !== b.completedAtMs)
144
+ return a.completedAtMs - b.completedAtMs;
145
+ return compareText(a.messageId, b.messageId);
146
+ }
147
+ function compareText(a, b) {
148
+ return a < b ? -1 : a > b ? 1 : 0;
149
+ }
150
+ function last(entries) {
151
+ return entries[entries.length - 1];
152
+ }
153
+ function greenReasonFor(counts) {
154
+ if (isPositiveFinite(counts.read))
155
+ return "estimated-reuse-within-ttl";
156
+ if (isPositiveFinite(counts.write))
157
+ return "estimated-write-within-ttl";
158
+ return "estimated-within-ttl";
159
+ }
160
+ function isPositiveFinite(value) {
161
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
162
+ }
163
+ function isNonNegativeFinite(value) {
164
+ return typeof value === "number" && Number.isFinite(value) && value >= 0;
165
+ }
166
+ /**
167
+ * Cache share of one successful call: read / (fresh + read + write). A reported
168
+ * zero read is a valid 0%; a call with missing counters, or with no input at
169
+ * all, has no usable share.
170
+ */
171
+ function primaryRatioOf(invocation) {
172
+ const { fresh, read, write } = invocation.counts;
173
+ if (!isNonNegativeFinite(fresh) || !isNonNegativeFinite(read) || !isNonNegativeFinite(write)) {
174
+ return { status: "unavailable" };
175
+ }
176
+ const denominator = fresh + read + write;
177
+ if (!(denominator > 0) || !Number.isFinite(denominator))
178
+ return { status: "unavailable" };
179
+ return {
180
+ status: "available",
181
+ ratio: {
182
+ value: read / denominator,
183
+ messageId: invocation.order.messageId,
184
+ observedAtMs: invocation.order.completedAtMs,
185
+ numerator: "cache-read",
186
+ denominator: "fresh+read+write",
187
+ basis: { ...invocation.basis },
188
+ },
189
+ };
190
+ }
191
+ const ROUTE_DEFAULT_ASSUMPTION = "assuming direct standard route/default TTL; custom endpoint, gateway, changed configuration or provider eviction may cause miss";
192
+ const GENERIC_FALLBACK_ASSUMPTION = "generic 5-minute fallback; no vendor retention is inferred for this route; gateway, custom endpoint, changed configuration or provider eviction may cause a miss";
193
+ const KIMI_PROVIDER_IDS = new Set([
194
+ "moonshotai",
195
+ "moonshotai-cn",
196
+ "kimi-code-plan-global",
197
+ "kimi-code-plan-cn",
198
+ "kimi-for-coding",
199
+ "kimi",
200
+ "kimi-code",
201
+ ]);
202
+ /**
203
+ * Route-scoped retention policy, matched by exact provider id (and model for the
204
+ * one empirical OpenCode Go entry), so a gateway never inherits a vendor window.
205
+ * A host-configured `cache.ttl` applies only to a configurable route; every other
206
+ * route keeps its policy default.
207
+ */
208
+ function retentionPolicy(route, routeConfiguration, connectionMethod, observedTtlMs) {
209
+ if (route.providerId === "claude-agent" && observedTtlMs === 3_600_000) {
210
+ return {
211
+ kind: "observed",
212
+ ttlMs: 3_600_000,
213
+ source: "Claude Agent session transcript cache-write split",
214
+ reference: "cache-observer-policy:claude-agent-observed-1h",
215
+ assumption: "Estimated from this call's 1-hour-only cache writes in the Claude Agent session record; physical retention is not observable and provider eviction may cause a miss.",
216
+ };
217
+ }
218
+ const configuredTtlMs = routeConfiguration.configuredTtlMs;
219
+ if (configuredTtlMs !== undefined && isCacheConfigurableProviderId(route.providerId)) {
220
+ return {
221
+ kind: "configured",
222
+ ttlMs: configuredTtlMs,
223
+ source: "Current host settings snapshot",
224
+ reference: "opencode-config:provider-settings.cache.ttl",
225
+ assumption: "Best-effort current host cache.ttl snapshot; may differ from dispatch settings or effective route. Physical provider expiry is not observable.",
226
+ };
227
+ }
228
+ if (route.providerId === "anthropic") {
229
+ return {
230
+ kind: "documented",
231
+ ttlMs: 300_000,
232
+ source: "Anthropic prompt caching documentation",
233
+ reference: "https://platform.claude.com/docs/en/build-with-claude/prompt-caching",
234
+ assumption: ROUTE_DEFAULT_ASSUMPTION,
235
+ };
236
+ }
237
+ if (KIMI_PROVIDER_IDS.has(route.providerId)) {
238
+ return {
239
+ kind: "documented",
240
+ ttlMs: 300_000,
241
+ source: "Kimi context caching documentation",
242
+ reference: "https://platform.kimi.ai/docs/guide/context-caching",
243
+ assumption: ROUTE_DEFAULT_ASSUMPTION,
244
+ };
245
+ }
246
+ if (route.providerId === "deepseek") {
247
+ return {
248
+ kind: "empirical",
249
+ ttlMs: 86_400_000,
250
+ source: "DeepSeek direct retention (owner-approved empirical policy)",
251
+ reference: "cache-observer-policy:deepseek-direct-24h",
252
+ assumption: "Empirical 24-hour estimate for direct DeepSeek; physical retention is not observable and provider eviction may cause a miss.",
253
+ };
254
+ }
255
+ if (route.providerId === "opencode-go" && route.modelId === "deepseek-v4.1-flash") {
256
+ return {
257
+ kind: "empirical",
258
+ ttlMs: 3_600_000,
259
+ source: "OpenCode Go deepseek-v4.1-flash retention (owner-approved empirical policy)",
260
+ reference: "cache-observer-policy:opencode-go-deepseek-v4.1-flash-60m",
261
+ assumption: "Empirical 60-minute estimate for this OpenCode Go model; physical retention is not observable and provider eviction may cause a miss.",
262
+ };
263
+ }
264
+ const version = /^gpt-(\d+)(?:\.(\d+))?(?:-[a-z0-9]+)*$/i.exec(route.modelId);
265
+ if (route.providerId === "openai" &&
266
+ connectionMethod === "oauth" &&
267
+ version !== null &&
268
+ (Number(version[1]) > 5 || (Number(version[1]) === 5 && Number(version[2] ?? 0) >= 6))) {
269
+ return {
270
+ kind: "empirical",
271
+ ttlMs: 1_800_000,
272
+ source: "Estimated ChatGPT subscription sign-in retention",
273
+ reference: "cache-observer-policy:chatgpt-oauth-30m",
274
+ assumption: "Owner-approved estimate based on the active OpenAI connection, not per-request proof or a retention guarantee.",
275
+ };
276
+ }
277
+ return {
278
+ kind: "fallback",
279
+ ttlMs: 300_000,
280
+ source: "Generic 5-minute fallback for unknown, gateway, or OpenAI-family routes",
281
+ reference: "cache-observer-policy:generic-5m-fallback",
282
+ assumption: GENERIC_FALLBACK_ASSUMPTION,
283
+ };
284
+ }
285
+ function hasValidDispatchTime(invocation, nowMs) {
286
+ return (typeof invocation.dispatchAtMs === "number" &&
287
+ Number.isFinite(invocation.dispatchAtMs) &&
288
+ invocation.dispatchAtMs >= 0 &&
289
+ invocation.dispatchAtMs <= invocation.order.completedAtMs &&
290
+ invocation.dispatchAtMs <= nowMs);
291
+ }
292
+ function hasValidBasis(basis) {
293
+ return (typeof basis?.source === "string" &&
294
+ basis.source.trim().length > 0 &&
295
+ typeof basis.reference === "string" &&
296
+ basis.reference.trim().length > 0);
297
+ }
298
+ function hasValidRouteProvenance(route) {
299
+ return (typeof route?.providerId === "string" &&
300
+ route.providerId.trim().length > 0 &&
301
+ typeof route.modelId === "string" &&
302
+ route.modelId.trim().length > 0 &&
303
+ hasValidBasis(route.basis));
304
+ }
305
+ function sameRoute(left, right) {
306
+ return left === undefined
307
+ ? right === undefined
308
+ : right !== undefined &&
309
+ left.providerId === right.providerId &&
310
+ left.modelId === right.modelId &&
311
+ left.variantId === right.variantId &&
312
+ left.protocolId === right.protocolId;
313
+ }
314
+ function optionalRatio(ratio) {
315
+ return ratio === undefined ? {} : { primaryCacheReadRatio: ratio };
316
+ }
317
+ //# sourceMappingURL=cache-observer.js.map
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Serialize cooperating in-process writers of the same canonical file, even
3
+ * when separate GUI and proposal-store instances perform asynchronous edits.
4
+ * External editors/processes do not participate in this lock. Config document
5
+ * writes recheck bytes and target after staging and immediately before rename,
6
+ * which narrows but cannot eliminate a race with noncooperating writers.
7
+ */
8
+ export declare function withCanonicalConfigLock<T>(path: string, run: () => Promise<T>): Promise<T>;
9
+ //# sourceMappingURL=canonical-config-lock.d.ts.map
@@ -0,0 +1,36 @@
1
+ import { resolve } from "node:path";
2
+ const CANONICAL_CONFIG_LOCKS = Symbol.for("opencode-quota-gui.canonical-config-locks.v1");
3
+ function registry() {
4
+ const globalState = globalThis;
5
+ const existing = globalState[CANONICAL_CONFIG_LOCKS];
6
+ if (existing)
7
+ return existing;
8
+ const created = new Map();
9
+ globalState[CANONICAL_CONFIG_LOCKS] = created;
10
+ return created;
11
+ }
12
+ function lockKey(path) {
13
+ const absolute = resolve(path);
14
+ return process.platform === "win32" ? absolute.toLowerCase() : absolute;
15
+ }
16
+ /**
17
+ * Serialize cooperating in-process writers of the same canonical file, even
18
+ * when separate GUI and proposal-store instances perform asynchronous edits.
19
+ * External editors/processes do not participate in this lock. Config document
20
+ * writes recheck bytes and target after staging and immediately before rename,
21
+ * which narrows but cannot eliminate a race with noncooperating writers.
22
+ */
23
+ export function withCanonicalConfigLock(path, run) {
24
+ const locks = registry();
25
+ const key = lockKey(path);
26
+ const prior = locks.get(key) ?? Promise.resolve();
27
+ const next = prior.then(run, run);
28
+ const tail = next.then(() => undefined, () => undefined);
29
+ locks.set(key, tail);
30
+ void tail.then(() => {
31
+ if (locks.get(key) === tail)
32
+ locks.delete(key);
33
+ });
34
+ return next;
35
+ }
36
+ //# sourceMappingURL=canonical-config-lock.js.map
@@ -5,7 +5,8 @@
5
5
  * https://api.chutes.ai/users/me/quota_usage/me
6
6
  */
7
7
  import { providerFailureCategoryForHttpStatus } from "../contracts/provider-failure.js";
8
- import { resolveChutesApiKey, } from "./chutes-config.js";
8
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
9
+ import { resolveChutesApiKey } from "./chutes-config.js";
9
10
  import { sanitizeDisplaySnippet, sanitizeDisplayText } from "./display-sanitize.js";
10
11
  import { clampPercent } from "./format-utils.js";
11
12
  import { fetchWithTimeout } from "./http.js";
@@ -15,63 +16,73 @@ function getNextDailyResetUtc() {
15
16
  return reset.toISOString();
16
17
  }
17
18
  const CHUTES_QUOTA_URL = "https://api.chutes.ai/users/me/quota_usage/me";
19
+ const guard = createApiKeyRetryGuard((retryAtMs) => ({
20
+ success: false,
21
+ error: "Chutes API error 429",
22
+ failureCategory: "provider_api",
23
+ retryAtMs,
24
+ }));
18
25
  export { getChutesKeyDiagnostics, hasChutesApiKey as hasChutesApiKeyConfigured, } from "./chutes-config.js";
19
26
  export async function queryChutesQuota(options = {}) {
20
27
  const resolved = await resolveChutesApiKey();
21
28
  if (!resolved)
22
29
  return null;
23
- let responseStatus;
24
- try {
25
- return await fetchWithTimeout(CHUTES_QUOTA_URL, {
26
- request: {
27
- method: "GET",
28
- headers: {
29
- Authorization: `Bearer ${resolved.key}`,
30
- "User-Agent": "opencode-quota-gui/1.0",
30
+ return guard(resolved.key, async () => {
31
+ let responseStatus;
32
+ try {
33
+ return await fetchWithTimeout(CHUTES_QUOTA_URL, {
34
+ request: {
35
+ method: "GET",
36
+ headers: {
37
+ Authorization: `Bearer ${resolved.key}`,
38
+ "User-Agent": "opencode-quota-gui/1.0",
39
+ },
31
40
  },
32
- },
33
- timeoutMs: options.requestTimeoutMs,
34
- consume: async (resp) => {
35
- responseStatus = resp.status;
36
- if (!resp.ok) {
37
- const text = await resp.text();
41
+ timeoutMs: options.requestTimeoutMs,
42
+ consume: async (resp) => {
43
+ responseStatus = resp.status;
44
+ if (!resp.ok) {
45
+ const retryAtMs = retryAfterDeadline(resp);
46
+ const text = await resp.text().catch(() => "");
47
+ return {
48
+ success: false,
49
+ error: `Chutes API error ${resp.status}: ${sanitizeDisplaySnippet(text, 120)}`,
50
+ failureCategory: providerFailureCategoryForHttpStatus(resp.status),
51
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
52
+ };
53
+ }
54
+ const data = (await resp.json());
55
+ if (typeof data.used !== "number" ||
56
+ !Number.isFinite(data.used) ||
57
+ typeof data.quota !== "number" ||
58
+ !Number.isFinite(data.quota)) {
59
+ return {
60
+ success: false,
61
+ error: "Chutes API response returned an unexpected response shape",
62
+ failureCategory: "provider_api",
63
+ };
64
+ }
65
+ // Chutes returns used and quota.
66
+ const used = data.used;
67
+ const quota = data.quota;
68
+ const percentRemaining = quota > 0 ? clampPercent(((quota - used) / quota) * 100) : 0;
38
69
  return {
39
- success: false,
40
- error: `Chutes API error ${resp.status}: ${sanitizeDisplaySnippet(text, 120)}`,
41
- failureCategory: providerFailureCategoryForHttpStatus(resp.status),
70
+ success: true,
71
+ percentRemaining,
72
+ resetTimeIso: getNextDailyResetUtc(),
42
73
  };
43
- }
44
- const data = (await resp.json());
45
- if (typeof data.used !== "number" ||
46
- !Number.isFinite(data.used) ||
47
- typeof data.quota !== "number" ||
48
- !Number.isFinite(data.quota)) {
49
- return {
50
- success: false,
51
- error: "Chutes API response returned an unexpected response shape",
52
- failureCategory: "provider_api",
53
- };
54
- }
55
- // Chutes returns used and quota.
56
- const used = data.used;
57
- const quota = data.quota;
58
- const percentRemaining = quota > 0 ? clampPercent(((quota - used) / quota) * 100) : 0;
59
- return {
60
- success: true,
61
- percentRemaining,
62
- resetTimeIso: getNextDailyResetUtc(),
63
- };
64
- },
65
- });
66
- }
67
- catch (err) {
68
- return {
69
- success: false,
70
- error: sanitizeDisplayText(err instanceof Error ? err.message : String(err)),
71
- failureCategory: responseStatus === undefined
72
- ? "provider_api"
73
- : providerFailureCategoryForHttpStatus(responseStatus),
74
- };
75
- }
74
+ },
75
+ });
76
+ }
77
+ catch (err) {
78
+ return {
79
+ success: false,
80
+ error: sanitizeDisplayText(err instanceof Error ? err.message : String(err)),
81
+ failureCategory: responseStatus === undefined
82
+ ? "provider_api"
83
+ : providerFailureCategoryForHttpStatus(responseStatus),
84
+ };
85
+ }
86
+ }, options.requestTimeoutMs);
76
87
  }
77
88
  //# sourceMappingURL=chutes.js.map