opencode-quota-gui 1.3.0 → 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 (238) hide show
  1. package/README.md +34 -20
  2. package/dist/bin/opencode-quota-gui.js +0 -0
  3. package/dist/contracts/build-identity.js +1 -1
  4. package/dist/contracts/card-order.d.ts +2 -0
  5. package/dist/contracts/card-order.js +2 -2
  6. package/dist/contracts/card-visibility.d.ts +2 -1
  7. package/dist/contracts/card-visibility.js +2 -1
  8. package/dist/contracts/dashboard.d.ts +95 -6
  9. package/dist/contracts/dashboard.js +10 -0
  10. package/dist/contracts/dto-guards.d.ts +4 -0
  11. package/dist/contracts/dto-guards.js +31 -7
  12. package/dist/contracts/guards.js +3 -1
  13. package/dist/contracts/identity.d.ts +37 -5
  14. package/dist/contracts/identity.js +43 -0
  15. package/dist/contracts/openai-quota.d.ts +3 -0
  16. package/dist/contracts/openai-quota.js +3 -0
  17. package/dist/contracts/provider-auto-resume.d.ts +9 -0
  18. package/dist/contracts/provider-auto-resume.js +24 -0
  19. package/dist/contracts/provider-failure.d.ts +22 -0
  20. package/dist/contracts/provider-failure.js +25 -1
  21. package/dist/contracts/row-order.d.ts +13 -0
  22. package/dist/contracts/row-order.js +34 -0
  23. package/dist/contracts/row-visibility.d.ts +53 -0
  24. package/dist/contracts/row-visibility.js +130 -0
  25. package/dist/data/modelsdev-pricing.min.json +1 -1
  26. package/dist/data/modelsdev-temporal.min.json +60 -634
  27. package/dist/gui/aggregation.d.ts +29 -1
  28. package/dist/gui/aggregation.js +157 -4
  29. package/dist/gui/analytics-bridge.d.ts +8 -9
  30. package/dist/gui/analytics-bridge.js +197 -54
  31. package/dist/gui/analytics-engine.d.ts +7 -15
  32. package/dist/gui/analytics-engine.js +246 -106
  33. package/dist/gui/analytics-model.d.ts +7 -0
  34. package/dist/gui/analytics-model.js +75 -9
  35. package/dist/gui/analytics-pricing-upkeep.d.ts +21 -0
  36. package/dist/gui/analytics-pricing-upkeep.js +23 -0
  37. package/dist/gui/analytics-protocol.d.ts +17 -7
  38. package/dist/gui/analytics-protocol.js +1 -0
  39. package/dist/gui/analytics-service.d.ts +10 -0
  40. package/dist/gui/analytics-service.js +30 -9
  41. package/dist/gui/analytics-state.d.ts +30 -5
  42. package/dist/gui/analytics-state.js +46 -7
  43. package/dist/gui/analytics-worker-runtime.d.ts +5 -0
  44. package/dist/gui/analytics-worker-runtime.js +9 -1
  45. package/dist/gui/analytics-worker.js +11 -0
  46. package/dist/gui/config.d.ts +3 -3
  47. package/dist/gui/config.js +77 -7
  48. package/dist/gui/identity.d.ts +6 -20
  49. package/dist/gui/identity.js +6 -54
  50. package/dist/gui/lifecycle.d.ts +5 -3
  51. package/dist/gui/lifecycle.js +3 -3
  52. package/dist/gui/primary-quota-windows.js +67 -44
  53. package/dist/gui/provider-cards.d.ts +20 -8
  54. package/dist/gui/provider-cards.js +42 -55
  55. package/dist/gui/quota-notification-detector.d.ts +29 -6
  56. package/dist/gui/quota-notification-detector.js +136 -47
  57. package/dist/gui/quota-notification-observer.d.ts +3 -4
  58. package/dist/gui/quota-notification-observer.js +73 -20
  59. package/dist/gui/quota-observation.d.ts +4 -0
  60. package/dist/gui/quota-observation.js +18 -0
  61. package/dist/gui/rpc.d.ts +2 -0
  62. package/dist/gui/rpc.js +14 -3
  63. package/dist/gui/server.js +17 -3
  64. package/dist/gui/snapshot-service.d.ts +3 -15
  65. package/dist/gui/snapshot-service.js +281 -23
  66. package/dist/gui/sources.js +179 -64
  67. package/dist/gui/temporal-status.d.ts +3 -2
  68. package/dist/gui/temporal-status.js +10 -6
  69. package/dist/gui-experimental.cjs +230 -225
  70. package/dist/lib/accounting-format.d.ts +8 -0
  71. package/dist/lib/accounting-format.js +20 -2
  72. package/dist/lib/alibaba-coding-plan-cli.d.ts +79 -0
  73. package/dist/lib/alibaba-coding-plan-cli.js +539 -0
  74. package/dist/lib/anthropic-api-auth.d.ts +7 -0
  75. package/dist/lib/anthropic-api-auth.js +27 -0
  76. package/dist/lib/anthropic-api-rate-limits.d.ts +47 -0
  77. package/dist/lib/anthropic-api-rate-limits.js +92 -0
  78. package/dist/lib/anthropic-auth.d.ts +2 -3
  79. package/dist/lib/anthropic-auth.js +2 -3
  80. package/dist/lib/anthropic-oauth-throttle.d.ts +76 -0
  81. package/dist/lib/anthropic-oauth-throttle.js +379 -0
  82. package/dist/lib/anthropic.d.ts +68 -14
  83. package/dist/lib/anthropic.js +1016 -363
  84. package/dist/lib/api-key-retry-after.d.ts +7 -0
  85. package/dist/lib/api-key-retry-after.js +62 -0
  86. package/dist/lib/atomic-json.d.ts +2 -0
  87. package/dist/lib/atomic-json.js +1 -0
  88. package/dist/lib/cache-observer-ingestion.d.ts +90 -0
  89. package/dist/lib/cache-observer-ingestion.js +1008 -0
  90. package/dist/lib/cache-observer.d.ts +141 -0
  91. package/dist/lib/cache-observer.js +323 -0
  92. package/dist/lib/canonical-config-lock.d.ts +9 -0
  93. package/dist/lib/canonical-config-lock.js +36 -0
  94. package/dist/lib/chutes.js +62 -51
  95. package/dist/lib/claude-agent-transcript-ttl.d.ts +48 -0
  96. package/dist/lib/claude-agent-transcript-ttl.js +154 -0
  97. package/dist/lib/claude-agent-ttl-tracker.d.ts +21 -0
  98. package/dist/lib/claude-agent-ttl-tracker.js +152 -0
  99. package/dist/lib/cli-show.d.ts +5 -0
  100. package/dist/lib/cli-show.js +21 -8
  101. package/dist/lib/cli-status.js +3 -6
  102. package/dist/lib/config-write-target.d.ts +1 -1
  103. package/dist/lib/config-write-target.js +5 -2
  104. package/dist/lib/config.d.ts +2 -1
  105. package/dist/lib/config.js +257 -4
  106. package/dist/lib/copilot.js +171 -86
  107. package/dist/lib/dashboard-visibility.d.ts +5 -0
  108. package/dist/lib/dashboard-visibility.js +11 -10
  109. package/dist/lib/dashboard-web-policy.d.ts +4 -4
  110. package/dist/lib/dashboard-web-policy.js +2 -2
  111. package/dist/lib/deepseek.js +25 -13
  112. package/dist/lib/display-sanitize.js +2 -0
  113. package/dist/lib/entries.d.ts +33 -1
  114. package/dist/lib/entries.js +6 -0
  115. package/dist/lib/glm-coding-plan.js +98 -74
  116. package/dist/lib/google-agy.js +90 -12
  117. package/dist/lib/google-gemini-cli.js +84 -11
  118. package/dist/lib/grouped-entry-normalization.js +1 -1
  119. package/dist/lib/http.d.ts +4 -0
  120. package/dist/lib/http.js +16 -2
  121. package/dist/lib/init-installer.js +5 -3
  122. package/dist/lib/kilo.js +37 -18
  123. package/dist/lib/kimi.js +35 -18
  124. package/dist/lib/maintainer-announcements.js +2 -2
  125. package/dist/lib/mimo.d.ts +2 -0
  126. package/dist/lib/mimo.js +36 -0
  127. package/dist/lib/modelsdev-pricing.d.ts +74 -2
  128. package/dist/lib/modelsdev-pricing.js +457 -63
  129. package/dist/lib/modelsdev-temporal.d.ts +6 -0
  130. package/dist/lib/modelsdev-temporal.js +16 -2
  131. package/dist/lib/nanogpt.d.ts +1 -0
  132. package/dist/lib/nanogpt.js +26 -3
  133. package/dist/lib/ollama-cloud.d.ts +1 -1
  134. package/dist/lib/ollama-cloud.js +48 -35
  135. package/dist/lib/openai.js +84 -38
  136. package/dist/lib/opencode-auth-sqlite.d.ts +2 -2
  137. package/dist/lib/opencode-auth-sqlite.js +2 -2
  138. package/dist/lib/opencode-config-editor.d.ts +1 -0
  139. package/dist/lib/opencode-config-editor.js +6 -1
  140. package/dist/lib/opencode-config-providers.js +2 -2
  141. package/dist/lib/opencode-go.js +29 -2
  142. package/dist/lib/opencode-storage.d.ts +20 -0
  143. package/dist/lib/opencode-storage.js +89 -2
  144. package/dist/lib/opencode-version-core.d.ts +30 -0
  145. package/dist/lib/opencode-version-core.js +59 -0
  146. package/dist/lib/opencode-version.d.ts +2 -22
  147. package/dist/lib/opencode-version.js +4 -48
  148. package/dist/lib/opencode-warming-refresh.d.ts +19 -0
  149. package/dist/lib/opencode-warming-refresh.js +95 -0
  150. package/dist/lib/opencode-zen.d.ts +3 -0
  151. package/dist/lib/opencode-zen.js +71 -5
  152. package/dist/lib/provider-add.js +5 -2
  153. package/dist/lib/provider-metadata.d.ts +11 -3
  154. package/dist/lib/provider-metadata.js +20 -2
  155. package/dist/lib/provider-registration.d.ts +358 -9
  156. package/dist/lib/provider-registration.js +423 -30
  157. package/dist/lib/quota-auto-resume.d.ts +74 -0
  158. package/dist/lib/quota-auto-resume.js +539 -0
  159. package/dist/lib/quota-command-format.js +23 -10
  160. package/dist/lib/quota-exhaustion-projection.d.ts +11 -0
  161. package/dist/lib/quota-exhaustion-projection.js +25 -0
  162. package/dist/lib/quota-identity.d.ts +64 -0
  163. package/dist/lib/quota-identity.js +111 -0
  164. package/dist/lib/quota-providers-remote.d.ts +2 -1
  165. package/dist/lib/quota-providers-remote.js +59 -3
  166. package/dist/lib/quota-providers.d.ts +1 -1
  167. package/dist/lib/quota-providers.js +14 -37
  168. package/dist/lib/quota-render-data.d.ts +6 -0
  169. package/dist/lib/quota-render-data.js +45 -19
  170. package/dist/lib/quota-reset-notifications.js +11 -155
  171. package/dist/lib/quota-retry-wait.d.ts +106 -5
  172. package/dist/lib/quota-retry-wait.js +301 -34
  173. package/dist/lib/quota-runtime-context.js +1 -0
  174. package/dist/lib/quota-state-codec.d.ts +2 -0
  175. package/dist/lib/quota-state-codec.js +31 -2
  176. package/dist/lib/quota-state.d.ts +8 -2
  177. package/dist/lib/quota-state.js +253 -47
  178. package/dist/lib/quota-stats.d.ts +26 -0
  179. package/dist/lib/quota-stats.js +40 -1
  180. package/dist/lib/quota-status.js +3 -51
  181. package/dist/lib/quota-surface-data.js +18 -3
  182. package/dist/lib/quota-telemetry.js +2 -2
  183. package/dist/lib/resolved-auth-identity.d.ts +19 -0
  184. package/dist/lib/resolved-auth-identity.js +44 -0
  185. package/dist/lib/scoped-update.d.ts +1 -1
  186. package/dist/lib/state-file-lock.d.ts +26 -0
  187. package/dist/lib/state-file-lock.js +205 -0
  188. package/dist/lib/synthetic.js +65 -54
  189. package/dist/lib/toast-format-grouped.js +7 -4
  190. package/dist/lib/tui-compact-format.js +29 -16
  191. package/dist/lib/types.d.ts +51 -1
  192. package/dist/lib/types.js +17 -1
  193. package/dist/lib/xai.js +48 -22
  194. package/dist/plugin.js +328 -14
  195. package/dist/provider-logos/NOTICE.md +1 -1
  196. package/dist/provider-logos/OPENCODE-NOTICE.md +4 -3
  197. package/dist/providers/alibaba-coding-plan.js +125 -104
  198. package/dist/providers/alibaba-token-plan.js +9 -5
  199. package/dist/providers/anthropic.d.ts +16 -3
  200. package/dist/providers/anthropic.js +172 -220
  201. package/dist/providers/cache-policies.d.ts +11 -4
  202. package/dist/providers/cache-policies.js +19 -13
  203. package/dist/providers/chutes.js +2 -0
  204. package/dist/providers/claude-agent.d.ts +19 -0
  205. package/dist/providers/claude-agent.js +215 -0
  206. package/dist/providers/copilot.js +7 -4
  207. package/dist/providers/glm-coding-plan-provider.d.ts +1 -0
  208. package/dist/providers/glm-coding-plan-provider.js +30 -23
  209. package/dist/providers/google-account-format.js +1 -0
  210. package/dist/providers/google-agy.d.ts +6 -5
  211. package/dist/providers/google-agy.js +43 -15
  212. package/dist/providers/google-gemini-cli.js +1 -0
  213. package/dist/providers/kilo.js +1 -0
  214. package/dist/providers/kimi-code.js +2 -0
  215. package/dist/providers/mimo.js +1 -0
  216. package/dist/providers/nanogpt.js +1 -0
  217. package/dist/providers/ollama-cloud.js +10 -0
  218. package/dist/providers/openai.js +24 -23
  219. package/dist/providers/opencode-go.js +10 -6
  220. package/dist/providers/opencode-zen.js +3 -1
  221. package/dist/providers/openrouter.js +1 -0
  222. package/dist/providers/quota-providers.js +16 -5
  223. package/dist/providers/registry.js +2 -0
  224. package/dist/providers/result-helpers.d.ts +6 -2
  225. package/dist/providers/result-helpers.js +7 -1
  226. package/dist/providers/synthetic.js +4 -0
  227. package/dist/providers/xai.js +9 -8
  228. package/dist/rpc.d.ts +129 -8
  229. package/dist/rpc.js +219 -14
  230. package/dist/ui/assets/{index-cDd9jUVY.css → index-6_g1FHs-.css} +1 -1
  231. package/dist/ui/assets/index-sZnGUuML.js +10 -0
  232. package/dist/ui/assets/{popover-BGkgv9s0.js → popover-C4ZLYe9E.js} +1 -1
  233. package/dist/ui/assets/providers/claude-agent.svg +3 -0
  234. package/dist/ui/index.html +2 -2
  235. package/package.json +45 -46
  236. package/dist/lib/alibaba-coding-plan-local-quota.d.ts +0 -47
  237. package/dist/lib/alibaba-coding-plan-local-quota.js +0 -146
  238. package/dist/ui/assets/index-DLHeXYff.js +0 -9
@@ -0,0 +1,48 @@
1
+ import { open } from "node:fs/promises";
2
+ /**
3
+ * Observed-retention reader for one Claude Agent invocation. It stats/reads exactly one
4
+ * computed transcript path (no directory listing), keeps only numeric cache counters, and
5
+ * never returns, logs or stores transcript content, paths or ids.
6
+ */
7
+ export type ClaudeObservedTtlResult = "1h" | "unchanged" | "retry";
8
+ /** Numeric counters of one grouped API message; nothing else leaves the parser. */
9
+ export interface TranscriptUsage {
10
+ input?: number;
11
+ read?: number;
12
+ write?: number;
13
+ oneHour?: number;
14
+ fiveMinute?: number;
15
+ }
16
+ export interface ClaudeTranscriptQuery {
17
+ /** The OpenCode session directory the SDK ran in (its `cwd`). */
18
+ directory: string;
19
+ /** Claude SDK session UUID (`native.sessionID`). */
20
+ nativeSessionId: string;
21
+ /** Transcript record `uuid` (`native.messageID`). */
22
+ nativeMessageId: string;
23
+ /** The step's reported tokens.input / cache.read / cache.write. */
24
+ tokens: {
25
+ input: number;
26
+ read: number;
27
+ write: number;
28
+ };
29
+ env?: Readonly<Record<string, string | undefined>>;
30
+ home?: string;
31
+ }
32
+ /** The single candidate transcript path, or undefined when it cannot be computed safely. */
33
+ export declare function claudeTranscriptPath(query: Pick<ClaudeTranscriptQuery, "directory" | "nativeSessionId" | "env" | "home">): string | undefined;
34
+ /**
35
+ * Groups assistant records by `message.id` (records repeat it per content block; the max of
36
+ * each counter wins) and returns the group of the record whose `uuid` matches. Only text up
37
+ * to the last newline is parsed, so a partially flushed trailing line is ignored.
38
+ */
39
+ export declare function parseTranscriptTail(text: string, uuid: string): TranscriptUsage | undefined;
40
+ /**
41
+ * "1h" only when the matched message's cache writes are 1-hour-only and its grouped
42
+ * counters equal the step's reported tokens exactly; "retry" when the file or record is not
43
+ * (yet) there; "unchanged" for everything else.
44
+ */
45
+ export declare function readClaudeObservedTtl(query: ClaudeTranscriptQuery, deps?: {
46
+ open?: typeof open;
47
+ }): Promise<ClaudeObservedTtlResult>;
48
+ //# sourceMappingURL=claude-agent-transcript-ttl.d.ts.map
@@ -0,0 +1,154 @@
1
+ import { constants } from "node:fs";
2
+ import { open } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { parseClaudeConfigDirectoryCandidate } from "./anthropic.js";
6
+ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
7
+ /** Only the tail is read; a flushed final record is always near the end. */
8
+ const TAIL_BYTES = 256 * 1024;
9
+ /**
10
+ * shortcut: the SDK's long-path truncation/hash scheme could not be verified from source
11
+ * (the SDK is not available locally), so longer encoded names yield no evidence; revisit
12
+ * if the SDK's encoding becomes verifiable.
13
+ */
14
+ const MAX_ENCODED_DIRECTORY_LENGTH = 200;
15
+ /** The single candidate transcript path, or undefined when it cannot be computed safely. */
16
+ export function claudeTranscriptPath(query) {
17
+ if (!UUID_PATTERN.test(query.nativeSessionId) || query.directory.length === 0)
18
+ return undefined;
19
+ const encoded = query.directory.replace(/[^a-zA-Z0-9]/g, "-");
20
+ if (encoded.length > MAX_ENCODED_DIRECTORY_LENGTH)
21
+ return undefined;
22
+ const env = query.env ?? process.env;
23
+ // Fail closed on a present-but-invalid override (relative, padded, empty) instead of
24
+ // reading another directory; UNC/network paths are never read either.
25
+ if (env.CLAUDE_CONFIG_DIR !== undefined && /^(?:\\\\|\/\/)/.test(env.CLAUDE_CONFIG_DIR))
26
+ return undefined;
27
+ const configured = parseClaudeConfigDirectoryCandidate(env.CLAUDE_CONFIG_DIR);
28
+ if (configured === null || (configured !== undefined && /^(?:\\\\|\/\/)/.test(configured))) {
29
+ return undefined;
30
+ }
31
+ const configDir = configured ?? join(query.home ?? homedir(), ".claude");
32
+ return join(configDir, "projects", encoded, `${query.nativeSessionId}.jsonl`);
33
+ }
34
+ const counter = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
35
+ const maxOf = (a, b) => a === undefined ? b : b === undefined ? a : Math.max(a, b);
36
+ /**
37
+ * Groups assistant records by `message.id` (records repeat it per content block; the max of
38
+ * each counter wins) and returns the group of the record whose `uuid` matches. Only text up
39
+ * to the last newline is parsed, so a partially flushed trailing line is ignored.
40
+ */
41
+ export function parseTranscriptTail(text, uuid) {
42
+ const complete = text.slice(0, text.lastIndexOf("\n") + 1);
43
+ const groups = new Map();
44
+ let target;
45
+ for (const line of complete.split("\n")) {
46
+ if (line.length === 0)
47
+ continue;
48
+ let parsed;
49
+ try {
50
+ parsed = JSON.parse(line);
51
+ }
52
+ catch {
53
+ continue;
54
+ }
55
+ if (typeof parsed !== "object" || parsed === null)
56
+ continue;
57
+ const entry = parsed;
58
+ if (entry.type !== "assistant" || typeof entry.message !== "object" || entry.message === null) {
59
+ continue;
60
+ }
61
+ const message = entry.message;
62
+ if (typeof message.id !== "string" ||
63
+ typeof message.usage !== "object" ||
64
+ message.usage === null) {
65
+ continue;
66
+ }
67
+ if (entry.uuid === uuid)
68
+ target = message.id;
69
+ const usage = message.usage;
70
+ const split = typeof usage.cache_creation === "object" && usage.cache_creation !== null
71
+ ? usage.cache_creation
72
+ : {};
73
+ const group = groups.get(message.id) ?? {
74
+ input: undefined,
75
+ read: undefined,
76
+ write: undefined,
77
+ oneHour: undefined,
78
+ fiveMinute: undefined,
79
+ };
80
+ group.input = maxOf(group.input, counter(usage.input_tokens));
81
+ group.read = maxOf(group.read, counter(usage.cache_read_input_tokens));
82
+ group.write = maxOf(group.write, counter(usage.cache_creation_input_tokens));
83
+ group.oneHour = maxOf(group.oneHour, counter(split.ephemeral_1h_input_tokens));
84
+ group.fiveMinute = maxOf(group.fiveMinute, counter(split.ephemeral_5m_input_tokens));
85
+ groups.set(message.id, group);
86
+ }
87
+ const group = target === undefined ? undefined : groups.get(target);
88
+ if (group === undefined)
89
+ return undefined;
90
+ return {
91
+ ...(group.input === undefined ? {} : { input: group.input }),
92
+ ...(group.read === undefined ? {} : { read: group.read }),
93
+ ...(group.write === undefined ? {} : { write: group.write }),
94
+ ...(group.oneHour === undefined ? {} : { oneHour: group.oneHour }),
95
+ ...(group.fiveMinute === undefined ? {} : { fiveMinute: group.fiveMinute }),
96
+ };
97
+ }
98
+ /** Tail text; undefined when unreadable or absent (maybe not flushed yet); null for a non-regular file. */
99
+ async function readTail(path, openFile) {
100
+ let handle;
101
+ try {
102
+ // O_NONBLOCK keeps a FIFO from blocking the open on POSIX; it is undefined on Windows.
103
+ handle = await openFile(path, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
104
+ const stats = await handle.stat();
105
+ if (!stats.isFile())
106
+ return null;
107
+ const { size } = stats;
108
+ const start = Math.max(0, size - TAIL_BYTES);
109
+ const buffer = Buffer.alloc(size - start);
110
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, start);
111
+ const text = buffer.subarray(0, bytesRead).toString("utf8");
112
+ // A tail starting mid-file begins inside a record; drop that cut line.
113
+ return start === 0 ? text : text.slice(text.indexOf("\n") + 1);
114
+ }
115
+ catch {
116
+ return undefined;
117
+ }
118
+ finally {
119
+ await handle?.close().catch(() => undefined);
120
+ }
121
+ }
122
+ /**
123
+ * "1h" only when the matched message's cache writes are 1-hour-only and its grouped
124
+ * counters equal the step's reported tokens exactly; "retry" when the file or record is not
125
+ * (yet) there; "unchanged" for everything else.
126
+ */
127
+ export async function readClaudeObservedTtl(query, deps = {}) {
128
+ const path = claudeTranscriptPath(query);
129
+ if (path === undefined || !UUID_PATTERN.test(query.nativeMessageId))
130
+ return "unchanged";
131
+ const text = await readTail(path, deps.open ?? open);
132
+ if (text === null)
133
+ return "unchanged";
134
+ if (text === undefined)
135
+ return "retry";
136
+ const usage = parseTranscriptTail(text, query.nativeMessageId);
137
+ if (usage === undefined)
138
+ return "retry";
139
+ const { input, read, write } = query.tokens;
140
+ if (usage.input !== input || usage.read !== read || usage.write !== write)
141
+ return "unchanged";
142
+ // 1h-only: no 5m writes and the 1h count equals the total writes. Any cache read, or a
143
+ // missing read counter, means older segments of unknown TTL are in play, so the session
144
+ // estimate must not be promoted from the new writes' TTL; the SDK's own read field is
145
+ // required (OpenCode may normalize unavailable reads to 0).
146
+ return usage.read === 0 &&
147
+ usage.fiveMinute === 0 &&
148
+ usage.oneHour !== undefined &&
149
+ usage.oneHour > 0 &&
150
+ usage.oneHour === usage.write
151
+ ? "1h"
152
+ : "unchanged";
153
+ }
154
+ //# sourceMappingURL=claude-agent-transcript-ttl.js.map
@@ -0,0 +1,21 @@
1
+ import type { DashboardRpcCacheObserverEvent } from "../rpc.js";
2
+ import type { ClaudeObservedTtlResult, ClaudeTranscriptQuery } from "./claude-agent-transcript-ttl.js";
3
+ type TtlEvent = Extract<DashboardRpcCacheObserverEvent, {
4
+ type: "session.cache.ttl";
5
+ }>;
6
+ /**
7
+ * Plugin-side correlation of one completed Claude Agent step with its session transcript.
8
+ * It remembers native ids per assistant message, does one bounded read after a successful
9
+ * step.ended, at most one retry on the session's next event, and emits only the minimal
10
+ * session.cache.ttl DTO for the newest invocation. No polling, watching or logging.
11
+ */
12
+ export declare function createClaudeAgentTtlTracker(options: {
13
+ directory: string;
14
+ read: (query: ClaudeTranscriptQuery) => Promise<ClaudeObservedTtlResult>;
15
+ emit: (event: TtlEvent, at: number) => void;
16
+ }): {
17
+ observe: (raw: unknown, projected: DashboardRpcCacheObserverEvent | undefined) => void;
18
+ dispose(): void;
19
+ };
20
+ export {};
21
+ //# sourceMappingURL=claude-agent-ttl-tracker.d.ts.map
@@ -0,0 +1,152 @@
1
+ const MAX_TRACKED_STEPS = 256;
2
+ const text = (value) => typeof value === "string" && value.length > 0 ? value : undefined;
3
+ const record = (value) => typeof value === "object" && value !== null ? value : undefined;
4
+ /**
5
+ * Plugin-side correlation of one completed Claude Agent step with its session transcript.
6
+ * It remembers native ids per assistant message, does one bounded read after a successful
7
+ * step.ended, at most one retry on the session's next event, and emits only the minimal
8
+ * session.cache.ttl DTO for the newest invocation. No polling, watching or logging.
9
+ */
10
+ export function createClaudeAgentTtlTracker(options) {
11
+ const steps = new Map();
12
+ const newest = new Map();
13
+ const retries = new Map();
14
+ const keyOf = (sessionId, stepId) => JSON.stringify([sessionId, stepId]);
15
+ /** One read for the slot's step; undefined when it failed, the slot was dropped, or a newer step exists. */
16
+ async function readOnce(slot) {
17
+ let result;
18
+ try {
19
+ result = await options.read(slot.query);
20
+ }
21
+ catch {
22
+ return undefined;
23
+ }
24
+ if (retries.get(slot.sessionId) !== slot || newest.get(slot.sessionId) !== slot.stepId) {
25
+ return undefined;
26
+ }
27
+ if (result === "1h") {
28
+ try {
29
+ options.emit({
30
+ type: "session.cache.ttl",
31
+ created: slot.created,
32
+ data: { sessionID: slot.sessionId, assistantMessageID: slot.stepId, ttlMs: 3_600_000 },
33
+ }, slot.created);
34
+ }
35
+ catch {
36
+ // A failing relay must not break event handling.
37
+ }
38
+ }
39
+ return result;
40
+ }
41
+ /** At most two reads: the second only after a "retry" result and a later event of the session. */
42
+ async function run(slot) {
43
+ const first = await readOnce(slot);
44
+ if (first === "retry") {
45
+ if (slot.phase === "first-requested") {
46
+ slot.phase = "second";
47
+ await readOnce(slot);
48
+ }
49
+ else {
50
+ slot.phase = "retry-ready";
51
+ return;
52
+ }
53
+ }
54
+ if (retries.get(slot.sessionId) === slot)
55
+ retries.delete(slot.sessionId);
56
+ }
57
+ function observe(raw, projected) {
58
+ const event = record(raw);
59
+ const data = record(event?.data);
60
+ const sessionId = text(data?.sessionID);
61
+ if (event === undefined || data === undefined || sessionId === undefined)
62
+ return;
63
+ if (projected?.type === "session.step.started") {
64
+ const stepId = projected.data.assistantMessageID;
65
+ newest.delete(sessionId);
66
+ newest.set(sessionId, stepId);
67
+ while (newest.size > MAX_TRACKED_STEPS) {
68
+ const oldestSession = newest.keys().next().value;
69
+ if (oldestSession === undefined)
70
+ break;
71
+ newest.delete(oldestSession);
72
+ retries.delete(oldestSession);
73
+ }
74
+ retries.delete(sessionId);
75
+ steps.delete(keyOf(sessionId, stepId));
76
+ steps.set(keyOf(sessionId, stepId), {
77
+ claude: projected.data.model.providerID === "claude-agent",
78
+ });
79
+ while (steps.size > MAX_TRACKED_STEPS) {
80
+ const oldest = steps.keys().next().value;
81
+ if (oldest === undefined)
82
+ break;
83
+ steps.delete(oldest);
84
+ }
85
+ return;
86
+ }
87
+ if (event.type === "session.text.ended" || event.type === "session.tool.called") {
88
+ const step = steps.get(keyOf(sessionId, text(data.assistantMessageID) ?? ""));
89
+ const nativeIds = record(data.native);
90
+ const nativeSession = text(nativeIds?.sessionID);
91
+ const nativeMessage = text(nativeIds?.messageID);
92
+ if (step?.claude && nativeSession !== undefined && nativeMessage !== undefined) {
93
+ step.native = { sessionId: nativeSession, messageId: nativeMessage };
94
+ }
95
+ return;
96
+ }
97
+ if (projected?.type === "session.step.ended") {
98
+ const stepId = projected.data.assistantMessageID;
99
+ const step = steps.get(keyOf(sessionId, stepId));
100
+ const { input, cache } = projected.data.tokens;
101
+ if (step?.claude !== true ||
102
+ step.native === undefined ||
103
+ newest.get(sessionId) !== stepId ||
104
+ input === undefined ||
105
+ cache?.read === undefined ||
106
+ cache.write === undefined) {
107
+ return;
108
+ }
109
+ const slot = {
110
+ phase: "first-inflight",
111
+ sessionId,
112
+ stepId,
113
+ created: projected.created,
114
+ query: {
115
+ directory: options.directory,
116
+ nativeSessionId: step.native.sessionId,
117
+ nativeMessageId: step.native.messageId,
118
+ tokens: { input, read: cache.read, write: cache.write },
119
+ },
120
+ };
121
+ retries.set(sessionId, slot);
122
+ run(slot).catch(() => undefined);
123
+ return;
124
+ }
125
+ if (event.type === "session.deleted") {
126
+ newest.delete(sessionId);
127
+ retries.delete(sessionId);
128
+ return;
129
+ }
130
+ const slot = retries.get(sessionId);
131
+ if (slot?.phase === "first-inflight")
132
+ slot.phase = "first-requested";
133
+ else if (slot?.phase === "retry-ready") {
134
+ slot.phase = "second";
135
+ readOnce(slot)
136
+ .catch(() => undefined)
137
+ .then(() => {
138
+ if (retries.get(sessionId) === slot)
139
+ retries.delete(sessionId);
140
+ });
141
+ }
142
+ }
143
+ return {
144
+ observe,
145
+ dispose() {
146
+ steps.clear();
147
+ newest.clear();
148
+ retries.clear();
149
+ },
150
+ };
151
+ }
152
+ //# sourceMappingURL=claude-agent-ttl-tracker.js.map
@@ -14,6 +14,11 @@ export declare function resolveCliRoots(cwd: string): {
14
14
  export declare function createCliQuotaClient(params: {
15
15
  configRootDir: string;
16
16
  }): QuotaRuntimeClient;
17
+ /**
18
+ * Resolve an explicit `--provider` value. An unknown id is reported to stderr
19
+ * and returns null so the command exits 1; absent means no provider filter.
20
+ */
21
+ export declare function resolveCliProviderId(requested: string | undefined, stderr: Pick<NodeJS.WriteStream, "write">): string | undefined | null;
17
22
  /**
18
23
  * Builds one `show` or `status` report in this process, for the folder the command runs in,
19
24
  * and prints it. It works with OpenCode closed: logins are read read-only from OpenCode's
@@ -6,7 +6,7 @@ import { DEFAULT_KIMI_AUTH_CACHE_MAX_AGE_MS, resolveKimiCnAuthCached, resolveKim
6
6
  import { bindCredentialSource } from "./opencode-auth.js";
7
7
  import { createSqliteCredentialSource } from "./opencode-auth-sqlite.js";
8
8
  import { loadConfiguredOpenCodeConfig, loadConfiguredProviderIds, } from "./opencode-config-providers.js";
9
- import { getQuotaProviderShape } from "./provider-metadata.js";
9
+ import { getQuotaProviderRegistration } from "./provider-metadata.js";
10
10
  import { resolveQuotaRuntimeContext } from "./quota-runtime-context.js";
11
11
  const SHOW_USAGE = [
12
12
  "Usage:",
@@ -105,13 +105,15 @@ async function loadCliAuthenticatedProviderIds(config) {
105
105
  const anthropicBinaryPath = typeof quotaToast?.anthropicBinaryPath === "string"
106
106
  ? quotaToast.anthropicBinaryPath
107
107
  : undefined;
108
- const [anthropicConfigured, kimiGlobalAuth, kimiCnAuth] = await Promise.all([
109
- hasAnthropicCredentialsConfigured({ binaryPath: anthropicBinaryPath }),
108
+ const [claudeCliConfigured, kimiGlobalAuth, kimiCnAuth] = await Promise.all([
109
+ hasAnthropicCredentialsConfigured({
110
+ binaryPath: anthropicBinaryPath,
111
+ }),
110
112
  resolveKimiGlobalAuthCached({ maxAgeMs: DEFAULT_KIMI_AUTH_CACHE_MAX_AGE_MS }),
111
113
  resolveKimiCnAuthCached({ maxAgeMs: DEFAULT_KIMI_AUTH_CACHE_MAX_AGE_MS }),
112
114
  ]);
113
115
  return [
114
- ...(anthropicConfigured ? ["anthropic"] : []),
116
+ ...(claudeCliConfigured ? ["claude-agent"] : []),
115
117
  ...(kimiGlobalAuth.state === "configured" ? ["kimi-code-plan-global"] : []),
116
118
  ...(kimiCnAuth.state === "configured" ? ["kimi-code-plan-cn"] : []),
117
119
  ];
@@ -153,6 +155,19 @@ export function createCliQuotaClient(params) {
153
155
  function writeLine(stream, message) {
154
156
  stream.write(message.endsWith("\n") ? message : `${message}\n`);
155
157
  }
158
+ /**
159
+ * Resolve an explicit `--provider` value. An unknown id is reported to stderr
160
+ * and returns null so the command exits 1; absent means no provider filter.
161
+ */
162
+ export function resolveCliProviderId(requested, stderr) {
163
+ if (requested === undefined)
164
+ return undefined;
165
+ const resolved = getQuotaProviderRegistration(requested)?.id;
166
+ if (resolved !== undefined)
167
+ return resolved;
168
+ writeLine(stderr, `Unknown provider: ${requested}`);
169
+ return null;
170
+ }
156
171
  /**
157
172
  * Builds one `show` or `status` report in this process, for the folder the command runs in,
158
173
  * and prints it. It works with OpenCode closed: logins are read read-only from OpenCode's
@@ -195,11 +210,9 @@ export async function runCliShowCommand(options = {}) {
195
210
  writeLine(stdout, SHOW_USAGE);
196
211
  return 0;
197
212
  }
198
- const providerId = parsed.providerId ? getQuotaProviderShape(parsed.providerId)?.id : undefined;
199
- if (parsed.providerId && !providerId) {
200
- writeLine(stderr, `Unknown provider: ${parsed.providerId}`);
213
+ const providerId = resolveCliProviderId(parsed.providerId, stderr);
214
+ if (providerId === null)
201
215
  return 1;
202
- }
203
216
  return runCliReport({
204
217
  cwd: options.cwd ?? process.cwd(),
205
218
  failurePrefix: "Failed to show quota",
@@ -1,6 +1,5 @@
1
1
  import { buildCliStatus } from "./cli-reports.js";
2
- import { runCliReport } from "./cli-show.js";
3
- import { getQuotaProviderShape } from "./provider-metadata.js";
2
+ import { resolveCliProviderId, runCliReport } from "./cli-show.js";
4
3
  const STATUS_USAGE = [
5
4
  "Usage:",
6
5
  " npx opencode-quota-gui status [--provider <provider-id>] [--json]",
@@ -82,11 +81,9 @@ export async function runCliStatusCommand(options = {}) {
82
81
  writeLine(stdout, STATUS_USAGE);
83
82
  return 0;
84
83
  }
85
- const providerId = parsed.providerId ? getQuotaProviderShape(parsed.providerId)?.id : undefined;
86
- if (parsed.providerId && !providerId) {
87
- writeLine(stderr, `Unknown provider: ${parsed.providerId}`);
84
+ const providerId = resolveCliProviderId(parsed.providerId, stderr);
85
+ if (providerId === null)
88
86
  return 1;
89
- }
90
87
  return runCliReport({
91
88
  cwd: options.cwd ?? process.cwd(),
92
89
  failurePrefix: "Failed to generate quota status",
@@ -21,7 +21,7 @@ export declare function configWriteTargetsEqual(left: ConfigWriteTargetSnapshot,
21
21
  export declare function assertSameConfigWriteTarget(planned: ConfigWriteTargetSnapshot, current: ConfigWriteTargetSnapshot): void;
22
22
  export declare function resolveConfigWriteTarget(path: string): Promise<ConfigWriteTargetSnapshot>;
23
23
  export declare function assertNotSymlinkSource(snapshot: ConfigWriteTargetSnapshot, sourcePath: string): void;
24
- export declare function writeResolvedConfigText(snapshot: ConfigWriteTargetSnapshot, content: string): Promise<void>;
24
+ export declare function writeResolvedConfigText(snapshot: ConfigWriteTargetSnapshot, content: string, beforeRename?: () => Promise<void>): Promise<void>;
25
25
  export declare function writeConfiguredJsonAtomic(configuredPath: string, data: unknown, opts?: {
26
26
  trailingNewline?: boolean;
27
27
  }): Promise<void>;
@@ -144,8 +144,11 @@ async function configurationWriteOptions(snapshot) {
144
144
  fileMode,
145
145
  };
146
146
  }
147
- export async function writeResolvedConfigText(snapshot, content) {
148
- await writeTextAtomic(snapshot.writePath, content, await configurationWriteOptions(snapshot));
147
+ export async function writeResolvedConfigText(snapshot, content, beforeRename) {
148
+ await writeTextAtomic(snapshot.writePath, content, {
149
+ ...(await configurationWriteOptions(snapshot)),
150
+ beforeRename,
151
+ });
149
152
  }
150
153
  export async function writeConfiguredJsonAtomic(configuredPath, data, opts = {}) {
151
154
  const planned = await resolveConfigWriteTarget(configuredPath);
@@ -21,7 +21,7 @@ export declare const GUI_CONFIG_RELATIVE_PATH = "opencode-quota-gui/config.jsonc
21
21
  export declare const GUI_CONFIG_SIBLING_JSON_RELATIVE_PATH = "opencode-quota-gui/config.json";
22
22
  export declare function getGuiConfigPath(configDir: string): string;
23
23
  export declare function getGuiConfigSiblingJsonPath(configDir: string): string;
24
- export declare const QUOTA_TOAST_SETTING_SOURCE_KEYS: readonly ["enabled", "enableToast", "resetNotifications.enabled", "resetNotifications.windows", "lowQuotaThresholdRemainingPercent", "duplicateCooldownMinutes", "tuiCommandDisplay", "formatStyle", "percentDisplayMode", "quotaProjection", "percentLabelStyle", "accountingDetail", "resetTimeDecimals", "resetTimeSpaced", "minIntervalMs", "requestTimeoutMs", "debug", "enabledProviders", "quotaProviders", "anthropicBinaryPath", "cursorPlan", "cursorIncludedApiUsd", "cursorBillingCycleStartDay", "opencodeGoWindows", "opencodeMonthlyLimit", "pricingSnapshot.source", "pricingSnapshot.autoRefresh", "showOnIdle", "showOnQuestion", "showOnCompact", "showOnBothFail", "toastDurationMs", "onlyCurrentModel", "waitForQuotaReset", "showSessionTokens", "sessionTokenScope", "tuiSidebarPanel.enabled", "tuiSidebarPanel.formatStyle", "tuiSidebarPanel.opencodeGoPreferredWindow", "tuiCompactStatus.enabled", "tuiCompactStatus.homeBottom", "tuiCompactStatus.sessionPrompt", "tuiCompactStatus.maxWidth", "tuiCompactStatus.formatStyle", "tuiPromptBar.enabled", "maintainerAnnouncements.enabled", "maintainerAnnouncements.home", "maintainerAnnouncements.homeFrequency", "layout.maxWidth", "layout.narrowAt", "layout.tinyAt", "export.enabled", "export.path", "telemetry.enabled", "dashboard.enabled", "dashboard.port", "dashboard.hiddenCards", "dashboard.hiddenCardsVersion", "dashboard.hiddenRows", "dashboard.providerOrder", "dashboard.cardOrder", "dashboard.temporalProviderOverrides"];
24
+ export declare const QUOTA_TOAST_SETTING_SOURCE_KEYS: readonly ["enabled", "enableToast", "resetNotifications.enabled", "resetNotifications.windows", "nativeQuotaNotifications", "lowQuotaThresholdRemainingPercent", "duplicateCooldownMinutes", "tuiCommandDisplay", "formatStyle", "percentDisplayMode", "quotaProjection", "percentLabelStyle", "accountingDetail", "resetTimeDecimals", "resetTimeSpaced", "minIntervalMs", "claudeAgentPollIntervalMs", "requestTimeoutMs", "debug", "enabledProviders", "quotaProviders", "anthropicBinaryPath", "cursorPlan", "cursorIncludedApiUsd", "cursorBillingCycleStartDay", "opencodeGoWindows", "opencodeMonthlyLimit", "pricingSnapshot.source", "pricingSnapshot.autoRefresh", "showOnIdle", "showOnQuestion", "showOnCompact", "showOnBothFail", "toastDurationMs", "onlyCurrentModel", "waitForQuotaReset", "autoResumeOnQuotaRecovery", "showSessionTokens", "sessionTokenScope", "tuiSidebarPanel.enabled", "tuiSidebarPanel.formatStyle", "tuiSidebarPanel.opencodeGoPreferredWindow", "tuiCompactStatus.enabled", "tuiCompactStatus.homeBottom", "tuiCompactStatus.sessionPrompt", "tuiCompactStatus.maxWidth", "tuiCompactStatus.formatStyle", "tuiPromptBar.enabled", "maintainerAnnouncements.enabled", "maintainerAnnouncements.home", "maintainerAnnouncements.homeFrequency", "layout.maxWidth", "layout.narrowAt", "layout.tinyAt", "export.enabled", "export.path", "telemetry.enabled", "dashboard.enabled", "dashboard.port", "dashboard.hiddenCards", "dashboard.hiddenCardsVersion", "dashboard.hiddenRows", "dashboard.providerOrder", "dashboard.cardOrder", "dashboard.rowOrder", "dashboard.temporalProviderOverrides"];
25
25
  export type QuotaToastSettingSourceKey = (typeof QUOTA_TOAST_SETTING_SOURCE_KEYS)[number];
26
26
  export type QuotaToastSettingSources = Partial<Record<QuotaToastSettingSourceKey, string>>;
27
27
  export interface LoadConfigIssue {
@@ -70,6 +70,7 @@ export declare function isValidOpenCodeGoWindows(value: unknown): value is Array
70
70
  export declare function isValidLowQuotaThresholdRemainingPercent(value: unknown): value is number;
71
71
  /** Duplicate alert cooldown: a whole number of minutes, zero or more. */
72
72
  export declare function isValidDuplicateCooldownMinutes(value: unknown): value is number;
73
+ export declare function isValidNativeQuotaNotificationPolicy(value: unknown): value is QuotaToastConfig["nativeQuotaNotifications"];
73
74
  type NormalizedEnabledProviders = {
74
75
  value?: string[] | "auto";
75
76
  issues: string[];