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
@@ -127,6 +127,14 @@ export interface OpenCodeRawAssistantRow {
127
127
  providerID?: string;
128
128
  modelID?: string;
129
129
  agent?: string;
130
+ /** Reasoning effort as stored (`model.variant`); absent when not recorded. */
131
+ variant?: string;
132
+ /**
133
+ * The stored message had no numeric cache counter. `tokens.cacheRead/Write`
134
+ * still read 0 for accounting, but the 0 is unknown, not an observed zero.
135
+ */
136
+ cacheReadMissing?: true;
137
+ cacheWriteMissing?: true;
130
138
  }
131
139
  /**
132
140
  * True when a completed assistant row carries at least one non-zero additive
@@ -152,6 +160,7 @@ export interface OpenCodeCompactionMarker {
152
160
  messageId: string;
153
161
  }
154
162
  export interface ReadCompletedAssistantRowsParams {
163
+ createdSinceMs?: number;
155
164
  completedSinceMs?: number;
156
165
  completedUntilMs?: number;
157
166
  /**
@@ -185,6 +194,11 @@ export interface OpenCodeMessageRevision {
185
194
  updatedAtMs: number | null;
186
195
  /** Positive parsed `$.time.completed`; null when unfinished or unavailable. */
187
196
  completedAtMs: number | null;
197
+ /**
198
+ * Assistant `$.parentID`: the user message this reply answers, when the
199
+ * stored JSON records it. Absent on user rows and on schemas without JSON.
200
+ */
201
+ parentID?: string;
188
202
  }
189
203
  export interface OpenCodeMessageRevisionSnapshot {
190
204
  /** false when `session_message` is absent or unreadable. */
@@ -287,6 +301,12 @@ export interface OpenCodeStorageSnapshot {
287
301
  readonly dbPath: string;
288
302
  /** Identity captured for the transaction that backs every reader below. */
289
303
  readonly identity: OpenCodeSourceIdentity;
304
+ /**
305
+ * Cheap source-change evidence captured before this snapshot's transaction
306
+ * began; `null` when the filesystem could not be inspected. See
307
+ * `readOpenCodeSourceChangeSignature`.
308
+ */
309
+ readonly changeSignature?: string | null;
290
310
  readAllSessionsIndex(): Record<string, OpenCodeSessionInfo>;
291
311
  readProjectsIndex(): Record<string, OpenCodeProjectInfo>;
292
312
  readCompletedAssistantRows(params?: ReadCompletedAssistantRowsParams): OpenCodeRawAssistantRow[];
@@ -107,6 +107,7 @@ const PROJECTED_MESSAGE_COLUMNS = [
107
107
  `${guardedJsonScalar("$.cost")} AS cost`,
108
108
  `${guardedJsonScalar("$.time.completed")} AS time_completed`,
109
109
  `${guardedJsonScalar("$.agent")} AS agent`,
110
+ `${guardedJsonScalar("$.model.variant")} AS variant`,
110
111
  ].join(", ");
111
112
  const ASSISTANT_FILTER = `type = 'assistant'`;
112
113
  function buildMessageQuery(params) {
@@ -203,6 +204,10 @@ function buildCompletedAssistantQuery(params, includeUpdatedAt = false) {
203
204
  `${completedExpression} > 0`,
204
205
  ];
205
206
  const args = [];
207
+ if (typeof params.createdSinceMs === "number") {
208
+ where.push("time_created >= ?");
209
+ args.push(params.createdSinceMs);
210
+ }
206
211
  if (typeof params.completedSinceMs === "number") {
207
212
  where.push(`${completedExpression} >= ?`);
208
213
  args.push(params.completedSinceMs);
@@ -594,6 +599,7 @@ function mapRawCompletedAssistantRow(row) {
594
599
  const completed = completedAt(message);
595
600
  if (completed === null)
596
601
  return null;
602
+ const variant = normalizeString(row.variant);
597
603
  return {
598
604
  sessionID: message.sessionID,
599
605
  messageID: message.id,
@@ -610,6 +616,9 @@ function mapRawCompletedAssistantRow(row) {
610
616
  providerID: message.providerID,
611
617
  modelID: message.modelID,
612
618
  agent: message.agent,
619
+ ...(variant === undefined ? {} : { variant }),
620
+ ...(normalizeNumber(row.tokens_cache_read) === undefined ? { cacheReadMissing: true } : {}),
621
+ ...(normalizeNumber(row.tokens_cache_write) === undefined ? { cacheWriteMissing: true } : {}),
613
622
  };
614
623
  }
615
624
  /**
@@ -637,6 +646,7 @@ function readCompletedAssistantRowsFrom(conn, params) {
637
646
  return [];
638
647
  const hasUpdatedAt = columns.has("time_updated");
639
648
  const reservedArgs = countDefined([
649
+ params.createdSinceMs,
640
650
  params.completedSinceMs,
641
651
  params.completedUntilMs,
642
652
  params.completedAtTimes,
@@ -658,6 +668,7 @@ function readCompletedAssistantRowsFrom(conn, params) {
658
668
  }
659
669
  else {
660
670
  const queries = scopedIdQueries(scope.ids, maxIdsPerQuery, (clause) => buildCompletedAssistantQuery({
671
+ createdSinceMs: params.createdSinceMs,
661
672
  completedSinceMs: params.completedSinceMs,
662
673
  completedUntilMs: params.completedUntilMs,
663
674
  completedAtTimes: params.completedAtTimes,
@@ -871,6 +882,7 @@ function readMessageRevisionsFrom(conn, params) {
871
882
  completedAtAvailable
872
883
  ? `${guardedJsonScalar("$.time.completed")} AS completed`
873
884
  : "NULL AS completed",
885
+ completedAtAvailable ? `${guardedJsonScalar("$.parentID")} AS parent_id` : "NULL AS parent_id",
874
886
  ].join(", ");
875
887
  const revisions = [];
876
888
  const updatedDelta = updatedAtAvailable && typeof params.updatedSinceMs === "number"
@@ -915,6 +927,7 @@ function readMessageRevisionsFrom(conn, params) {
915
927
  const createdAt = normalizeNumber(row.time_created);
916
928
  const updatedAt = normalizeNumber(row.time_updated);
917
929
  const completed = normalizeNumber(row.completed);
930
+ const parentID = normalizeString(row.parent_id);
918
931
  revisions.push({
919
932
  messageID: row.id,
920
933
  sessionID: row.session_id,
@@ -922,6 +935,7 @@ function readMessageRevisionsFrom(conn, params) {
922
935
  createdAtMs: createdAt ?? 0,
923
936
  updatedAtMs: updatedAt ?? null,
924
937
  completedAtMs: completed !== undefined && completed > 0 ? Math.trunc(completed) : null,
938
+ ...(parentID === undefined ? {} : { parentID }),
925
939
  });
926
940
  }
927
941
  };
@@ -1101,6 +1115,75 @@ function readSourceIdentityStat() {
1101
1115
  }
1102
1116
  return identity;
1103
1117
  }
1118
+ /**
1119
+ * Cheap, non-mutating evidence that the SQLite files changed since the last
1120
+ * completed analytics revision.
1121
+ *
1122
+ * The revision projection is a full scan because completion time lives in
1123
+ * message JSON. Before paying for it, the worker compares this signature with
1124
+ * the one persisted alongside the compact index. Any committed write appends to
1125
+ * the WAL (or changes the main file when a rollback journal is used), so the
1126
+ * size/mtime of `opencode.db` and `opencode.db-wal` plus the stable file
1127
+ * identity change for inserts, deletions, and in-place JSON updates. A
1128
+ * read-only connection's `PRAGMA data_version` is intentionally not used: it is
1129
+ * only comparable within one connection, and the storage snapshot opens a new
1130
+ * connection per refresh.
1131
+ *
1132
+ * The signature is captured before the snapshot transaction begins. Any write
1133
+ * counted here is therefore committed before `BEGIN`, so the same refresh can
1134
+ * persist this signature with data that already includes it. A write that lands
1135
+ * after the stat is caught by the next refresh because its file state differs.
1136
+ *
1137
+ * This is an optimization, not the correctness boundary: a same-size WAL or a
1138
+ * coarse filesystem timestamp can theoretically hide a commit, so the persisted
1139
+ * 7-day repair still re-reads the source periodically (and always overrides the
1140
+ * signature gate when due).
1141
+ */
1142
+ function readOpenCodeSourceChangeSignature() {
1143
+ const dbPath = getOpenCodeDbPath();
1144
+ if (dbPath === ":memory:")
1145
+ return null;
1146
+ let database;
1147
+ try {
1148
+ database = statSync(dbPath, { bigint: true });
1149
+ }
1150
+ catch {
1151
+ return null;
1152
+ }
1153
+ if (!database.isFile())
1154
+ return null;
1155
+ const dbMtime = typeof database.mtimeNs === "bigint" ? database.mtimeNs.toString() : String(database.mtimeMs);
1156
+ let wal = "absent";
1157
+ try {
1158
+ const walStat = statSync(`${dbPath}-wal`, { bigint: true });
1159
+ // Opening a WAL database read-only may create a zero-length `-wal`; it
1160
+ // holds no committed frames, so it must not look like a source change.
1161
+ if (walStat.isFile() && walStat.size > 0n) {
1162
+ const walMtime = typeof walStat.mtimeNs === "bigint" ? walStat.mtimeNs.toString() : String(walStat.mtimeMs);
1163
+ wal = `${walStat.size}:${walMtime}`;
1164
+ }
1165
+ }
1166
+ catch (error) {
1167
+ // Only "no WAL file" is conclusive (rollback journal). Any other stat
1168
+ // failure makes the evidence inconclusive, so return no signature and let
1169
+ // the caller scan.
1170
+ const code = typeof error === "object" && error !== null && "code" in error
1171
+ ? error.code
1172
+ : undefined;
1173
+ if (code !== "ENOENT" && code !== "ENOTDIR")
1174
+ return null;
1175
+ }
1176
+ return [
1177
+ "v1",
1178
+ dbPath,
1179
+ database.dev.toString(),
1180
+ database.ino.toString(),
1181
+ database.birthtimeNs.toString(),
1182
+ database.size.toString(),
1183
+ dbMtime,
1184
+ wal,
1185
+ ].join("|");
1186
+ }
1104
1187
  /**
1105
1188
  * Read the local source identity. `status: "ok"` means the file exists and the
1106
1189
  * schema was readable (including a successfully opened, empty database);
@@ -1128,10 +1211,11 @@ export async function readOpenCodeSourceIdentity() {
1128
1211
  conn.close();
1129
1212
  }
1130
1213
  }
1131
- function createStorageSnapshot(conn, identity) {
1214
+ function createStorageSnapshot(conn, identity, changeSignature) {
1132
1215
  return {
1133
1216
  dbPath: identity.dbPath,
1134
1217
  identity,
1218
+ changeSignature,
1135
1219
  readAllSessionsIndex: () => readAllSessionsIndexFrom(conn),
1136
1220
  readProjectsIndex: () => readProjectsIndexFrom(conn),
1137
1221
  readCompletedAssistantRows: (params = {}) => readCompletedAssistantRowsFrom(conn, params),
@@ -1183,6 +1267,9 @@ export async function withOpenCodeStorageSnapshot(read) {
1183
1267
  return { status: "missing" };
1184
1268
  if (statIdentity.status === "unreadable")
1185
1269
  return { status: "unreadable" };
1270
+ // Captured before `BEGIN`: every write counted by the signature is visible to
1271
+ // the transaction, so the refresh may persist it with data that includes it.
1272
+ const changeSignature = readOpenCodeSourceChangeSignature();
1186
1273
  let conn;
1187
1274
  try {
1188
1275
  conn = await openOpenCodeSqliteReadOnly(statIdentity.dbPath);
@@ -1210,7 +1297,7 @@ export async function withOpenCodeStorageSnapshot(read) {
1210
1297
  catch {
1211
1298
  return { status: "unreadable" };
1212
1299
  }
1213
- const value = await read(createStorageSnapshot(conn, identity));
1300
+ const value = await read(createStorageSnapshot(conn, identity, changeSignature));
1214
1301
  // Do not publish a generation if the path was replaced during the read;
1215
1302
  // the connection remains the old file while the path already points at a
1216
1303
  // different generation.
@@ -0,0 +1,30 @@
1
+ export type OpenCodeMajor = 1 | 2;
2
+ /** Numeric host version; a prerelease/build suffix is ignored. */
3
+ export interface OpenCodeVersion {
4
+ major: number;
5
+ minor: number;
6
+ patch: number;
7
+ }
8
+ /** Parses the numeric version core; a prerelease or build suffix is ignored. */
9
+ export declare function parseOpenCodeVersion(output: string): OpenCodeVersion | undefined;
10
+ /** OpenCode 1 prints a bare `1.18.32`; OpenCode 2 prints `opencode v2.0.16`. */
11
+ export declare function parseOpenCodeMajor(output: string): OpenCodeMajor | undefined;
12
+ /**
13
+ * Whether the host has the full Native GUI baseline (2.2.1+). Missing or
14
+ * unparseable versions are not assumed capable.
15
+ */
16
+ export declare function supportsNativeGui(version: string | OpenCodeVersion | undefined): boolean;
17
+ /**
18
+ * Whether the host renders the visible heading of a composer pill's custom
19
+ * `menu` popover itself. Hosts before 2.4.0 do (the popover body then starts
20
+ * below that heading); 2.4.0 moved the whole popover body, including any
21
+ * heading, to the plugin. Unknown versions are treated as the newer contract.
22
+ */
23
+ export declare function hostRendersComposerMenuHeading(version: string | OpenCodeVersion | undefined): boolean;
24
+ /**
25
+ * Whether the host predates the Native GUI and therefore keeps the compatibility
26
+ * web dashboard on by default. Only a parseable version below 2.2.1 qualifies;
27
+ * missing or unparseable versions fail closed.
28
+ */
29
+ export declare function isPreNativeGuiVersion(version: string | OpenCodeVersion | undefined): boolean;
30
+ //# sourceMappingURL=opencode-version-core.d.ts.map
@@ -0,0 +1,59 @@
1
+ /** The numeric core of `1.18.32`, `opencode v2.2.0`, or `2.2.1-beta.1`. */
2
+ const OPENCODE_VERSION_PATTERN = /^(?:opencode\s+)?v?(\d+)\.(\d+)\.(\d+)/;
3
+ /** Parses the numeric version core; a prerelease or build suffix is ignored. */
4
+ export function parseOpenCodeVersion(output) {
5
+ const match = OPENCODE_VERSION_PATTERN.exec(output.trim());
6
+ if (!match)
7
+ return undefined;
8
+ const major = Number(match[1]);
9
+ const minor = Number(match[2]);
10
+ const patch = Number(match[3]);
11
+ if (![major, minor, patch].every((part) => Number.isSafeInteger(part)))
12
+ return undefined;
13
+ return { major, minor, patch };
14
+ }
15
+ /** OpenCode 1 prints a bare `1.18.32`; OpenCode 2 prints `opencode v2.0.16`. */
16
+ export function parseOpenCodeMajor(output) {
17
+ const version = parseOpenCodeVersion(output);
18
+ if (version?.major === 1)
19
+ return 1;
20
+ if (version?.major === 2)
21
+ return 2;
22
+ return undefined;
23
+ }
24
+ /** Compares the numeric parts only; a prerelease suffix never lowers the result. */
25
+ function isAtLeast(version, major, minor, patch) {
26
+ if (version.major !== major)
27
+ return version.major > major;
28
+ if (version.minor !== minor)
29
+ return version.minor > minor;
30
+ return version.patch >= patch;
31
+ }
32
+ /**
33
+ * Whether the host has the full Native GUI baseline (2.2.1+). Missing or
34
+ * unparseable versions are not assumed capable.
35
+ */
36
+ export function supportsNativeGui(version) {
37
+ const parsed = typeof version === "string" ? parseOpenCodeVersion(version) : version;
38
+ return parsed !== undefined && isAtLeast(parsed, 2, 2, 1);
39
+ }
40
+ /**
41
+ * Whether the host renders the visible heading of a composer pill's custom
42
+ * `menu` popover itself. Hosts before 2.4.0 do (the popover body then starts
43
+ * below that heading); 2.4.0 moved the whole popover body, including any
44
+ * heading, to the plugin. Unknown versions are treated as the newer contract.
45
+ */
46
+ export function hostRendersComposerMenuHeading(version) {
47
+ const parsed = typeof version === "string" ? parseOpenCodeVersion(version) : version;
48
+ return parsed !== undefined && !isAtLeast(parsed, 2, 4, 0);
49
+ }
50
+ /**
51
+ * Whether the host predates the Native GUI and therefore keeps the compatibility
52
+ * web dashboard on by default. Only a parseable version below 2.2.1 qualifies;
53
+ * missing or unparseable versions fail closed.
54
+ */
55
+ export function isPreNativeGuiVersion(version) {
56
+ const parsed = typeof version === "string" ? parseOpenCodeVersion(version) : version;
57
+ return parsed !== undefined && !isAtLeast(parsed, 2, 2, 1);
58
+ }
59
+ //# sourceMappingURL=opencode-version-core.js.map
@@ -1,25 +1,5 @@
1
- export type OpenCodeMajor = 1 | 2;
2
- /** Numeric host version; a prerelease/build suffix is ignored. */
3
- export interface OpenCodeVersion {
4
- major: number;
5
- minor: number;
6
- patch: number;
7
- }
8
- /** Parses the numeric version core; a prerelease or build suffix is ignored. */
9
- export declare function parseOpenCodeVersion(output: string): OpenCodeVersion | undefined;
10
- /** OpenCode 1 prints a bare `1.18.32`; OpenCode 2 prints `opencode v2.0.16`. */
11
- export declare function parseOpenCodeMajor(output: string): OpenCodeMajor | undefined;
12
- /**
13
- * Whether the host has the Native GUI baseline (2.2.0+). Missing or
14
- * unparseable versions are not assumed capable.
15
- */
16
- export declare function supportsNativeGui(version: string | OpenCodeVersion | undefined): boolean;
17
- /**
18
- * Whether the host predates the Native GUI and therefore keeps the compatibility
19
- * web dashboard on by default. Only a parseable version below 2.2.0 qualifies;
20
- * missing or unparseable versions fail closed.
21
- */
22
- export declare function isPreNativeGuiVersion(version: string | OpenCodeVersion | undefined): boolean;
1
+ import { type OpenCodeMajor, type OpenCodeVersion } from "./opencode-version-core.js";
2
+ export * from "./opencode-version-core.js";
23
3
  /** Returns undefined when `opencode` is not on PATH, fails, times out, or prints an unknown version. */
24
4
  export declare function detectOpenCodeVersion(runVersion?: () => Promise<string>): Promise<OpenCodeVersion | undefined>;
25
5
  /** Returns undefined when `opencode` is not on PATH, fails, times out, or prints an unknown version. */
@@ -1,53 +1,9 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { parseOpenCodeVersion, } from "./opencode-version-core.js";
3
+ // Keep this legacy module path's public surface intact while the implementation
4
+ // of pure version helpers lives in a browser-safe module.
5
+ export * from "./opencode-version-core.js";
2
6
  const OPENCODE_VERSION_TIMEOUT_MS = 5_000;
3
- /** The numeric core of `1.18.32`, `opencode v2.2.0`, or `2.2.0-beta.1`. */
4
- const OPENCODE_VERSION_PATTERN = /^(?:opencode\s+)?v?(\d+)\.(\d+)\.(\d+)/;
5
- /** Parses the numeric version core; a prerelease or build suffix is ignored. */
6
- export function parseOpenCodeVersion(output) {
7
- const match = OPENCODE_VERSION_PATTERN.exec(output.trim());
8
- if (!match)
9
- return undefined;
10
- const major = Number(match[1]);
11
- const minor = Number(match[2]);
12
- const patch = Number(match[3]);
13
- if (![major, minor, patch].every((part) => Number.isSafeInteger(part)))
14
- return undefined;
15
- return { major, minor, patch };
16
- }
17
- /** OpenCode 1 prints a bare `1.18.32`; OpenCode 2 prints `opencode v2.0.16`. */
18
- export function parseOpenCodeMajor(output) {
19
- const version = parseOpenCodeVersion(output);
20
- if (version?.major === 1)
21
- return 1;
22
- if (version?.major === 2)
23
- return 2;
24
- return undefined;
25
- }
26
- /** Compares the numeric parts only; a prerelease suffix never lowers the result. */
27
- function isAtLeast(version, major, minor, patch) {
28
- if (version.major !== major)
29
- return version.major > major;
30
- if (version.minor !== minor)
31
- return version.minor > minor;
32
- return version.patch >= patch;
33
- }
34
- /**
35
- * Whether the host has the Native GUI baseline (2.2.0+). Missing or
36
- * unparseable versions are not assumed capable.
37
- */
38
- export function supportsNativeGui(version) {
39
- const parsed = typeof version === "string" ? parseOpenCodeVersion(version) : version;
40
- return parsed !== undefined && isAtLeast(parsed, 2, 2, 0);
41
- }
42
- /**
43
- * Whether the host predates the Native GUI and therefore keeps the compatibility
44
- * web dashboard on by default. Only a parseable version below 2.2.0 qualifies;
45
- * missing or unparseable versions fail closed.
46
- */
47
- export function isPreNativeGuiVersion(version) {
48
- const parsed = typeof version === "string" ? parseOpenCodeVersion(version) : version;
49
- return parsed !== undefined && !isAtLeast(parsed, 2, 2, 0);
50
- }
51
7
  function runOpenCodeVersion() {
52
8
  return new Promise((resolve, reject) => {
53
9
  execFile("opencode", ["--version"], { encoding: "utf8", timeout: OPENCODE_VERSION_TIMEOUT_MS, windowsHide: true }, (error, stdout) => (error ? reject(error) : resolve(stdout)));
@@ -0,0 +1,19 @@
1
+ export interface WarmingRefresh {
2
+ sessionID: string;
3
+ dispatchMs: number;
4
+ evidence: "warming-inferred";
5
+ }
6
+ export declare class OpencodeWarmingRefreshTracker {
7
+ private readonly sessions;
8
+ private session;
9
+ onModelRequest(input: {
10
+ sessionID?: unknown;
11
+ kind?: unknown;
12
+ model?: unknown;
13
+ }, nowMs: number): void;
14
+ private onStep;
15
+ onStepStarted(event: unknown): void;
16
+ onStepEnded(event: unknown): void;
17
+ onUsageUpdated(event: unknown): WarmingRefresh | undefined;
18
+ }
19
+ //# sourceMappingURL=opencode-warming-refresh.d.ts.map
@@ -0,0 +1,95 @@
1
+ const MAX_TRACKED_SESSIONS = 256;
2
+ function text(value) {
3
+ return typeof value === "string" && value.length > 0 ? value : undefined;
4
+ }
5
+ function record(value) {
6
+ return typeof value === "object" && value !== null
7
+ ? value
8
+ : undefined;
9
+ }
10
+ function modelKey(value) {
11
+ const model = record(value);
12
+ const provider = text(model?.providerID);
13
+ const id = text(model?.id) ?? text(model?.modelID);
14
+ return provider !== undefined && id !== undefined ? JSON.stringify([provider, id]) : undefined;
15
+ }
16
+ export class OpencodeWarmingRefreshTracker {
17
+ sessions = new Map();
18
+ session(id) {
19
+ let state = this.sessions.get(id);
20
+ if (state === undefined) {
21
+ state = { requests: 0, generate: false, step: false, tainted: false };
22
+ this.sessions.set(id, state);
23
+ if (this.sessions.size > MAX_TRACKED_SESSIONS) {
24
+ const oldest = this.sessions.keys().next().value;
25
+ if (oldest !== undefined)
26
+ this.sessions.delete(oldest);
27
+ }
28
+ }
29
+ return state;
30
+ }
31
+ onModelRequest(input, nowMs) {
32
+ const request = record(input);
33
+ const id = text(request?.sessionID);
34
+ if (id === undefined)
35
+ return;
36
+ const state = this.session(id);
37
+ state.requests++;
38
+ if (request?.kind === "generate") {
39
+ state.generate = true;
40
+ const model = modelKey(request.model);
41
+ if (model !== undefined && Number.isFinite(nowMs))
42
+ state.candidate = { model, dispatchMs: nowMs };
43
+ }
44
+ }
45
+ onStep(event, started) {
46
+ const data = record(record(event)?.data);
47
+ const id = text(data?.sessionID);
48
+ if (id === undefined)
49
+ return;
50
+ const state = this.session(id);
51
+ state.step = true;
52
+ if (started)
53
+ state.model = modelKey(data?.model);
54
+ else
55
+ state.tainted = false;
56
+ }
57
+ onStepStarted(event) {
58
+ this.onStep(event, true);
59
+ }
60
+ onStepEnded(event) {
61
+ this.onStep(event, false);
62
+ }
63
+ onUsageUpdated(event) {
64
+ const data = record(record(event)?.data);
65
+ const id = text(data?.sessionID);
66
+ if (id === undefined)
67
+ return undefined;
68
+ const state = this.session(id);
69
+ const read = record(record(data?.tokens)?.cache)?.read;
70
+ const cacheRead = typeof read === "number" && Number.isFinite(read) ? read : undefined;
71
+ // Cumulative, source-less usage may under-detect refreshes and should rarely over-detect them.
72
+ const accepted = !state.tainted &&
73
+ !state.step &&
74
+ state.requests === 1 &&
75
+ state.generate &&
76
+ state.candidate !== undefined &&
77
+ state.model !== undefined &&
78
+ state.candidate.model === state.model &&
79
+ state.baseline !== undefined &&
80
+ cacheRead !== undefined &&
81
+ cacheRead > state.baseline;
82
+ const result = accepted && state.candidate !== undefined
83
+ ? { sessionID: id, dispatchMs: state.candidate.dispatchMs, evidence: "warming-inferred" }
84
+ : undefined;
85
+ if (!accepted && state.generate)
86
+ state.tainted = true;
87
+ state.baseline = cacheRead;
88
+ state.requests = 0;
89
+ state.generate = false;
90
+ state.candidate = undefined;
91
+ state.step = false;
92
+ return result;
93
+ }
94
+ }
95
+ //# sourceMappingURL=opencode-warming-refresh.js.map
@@ -46,6 +46,8 @@ export interface OpenCodeZenBillingData {
46
46
  export type OpenCodeZenOptionalError = {
47
47
  message: string;
48
48
  failureCategory?: ProviderFailureCategory;
49
+ /** Deadline observed in an upstream Retry-After response. */
50
+ retryAtMs?: number;
49
51
  };
50
52
  export type OpenCodeZenResult = {
51
53
  success: true;
@@ -56,6 +58,7 @@ export type OpenCodeZenResult = {
56
58
  success: false;
57
59
  error: string;
58
60
  failureCategory?: ProviderFailureCategory;
61
+ retryAtMs?: number;
59
62
  };
60
63
  export declare function queryOpenCodeZenQuota(credential: OpenCodeConsoleCredential, options?: {
61
64
  requestTimeoutMs?: number;
@@ -1,4 +1,5 @@
1
1
  import { providerFailureCategoryForHttpStatus } from "../contracts/provider-failure.js";
2
+ import { createApiKeyRetryGuard, retryAfterDeadline } from "./api-key-retry-after.js";
2
3
  import { sanitizeDisplayText } from "./display-sanitize.js";
3
4
  import { fetchWithTimeout } from "./http.js";
4
5
  import { consoleBaseUrl, consoleHeaders, } from "./opencode-console-auth.js";
@@ -9,6 +10,20 @@ const SESSION_ERROR = "OpenCode Console session expired or invalid. Run `opencod
9
10
  * one US dollar is 100,000,000 micro-cents (billing units).
10
11
  */
11
12
  export const OPENCODE_ZEN_BILLING_UNITS_PER_DOLLAR = 100_000_000;
13
+ const routeGuard = createApiKeyRetryGuard((retryAtMs) => ({
14
+ success: false,
15
+ error: "OpenCode Console request error 429",
16
+ failureCategory: providerFailureCategoryForHttpStatus(429),
17
+ retryAtMs,
18
+ }));
19
+ // Coalesce whole queries so a waiter cannot resend optional routes that settled
20
+ // while it was waiting for the required balance route.
21
+ const quotaQueryGuard = createApiKeyRetryGuard((retryAtMs) => ({
22
+ success: false,
23
+ error: "OpenCode Console billing/status error 429",
24
+ failureCategory: providerFailureCategoryForHttpStatus(429),
25
+ retryAtMs,
26
+ }));
12
27
  function asRecord(value) {
13
28
  return value && typeof value === "object" && !Array.isArray(value)
14
29
  ? value
@@ -218,7 +233,26 @@ function sanitizeMessage(text, secrets = [], maxLength = 120) {
218
233
  }
219
234
  return (sanitized || "unknown").slice(0, maxLength);
220
235
  }
221
- async function fetchConsoleRoute(params) {
236
+ /** One cooldown per workspace credential and route; other workspaces are unaffected. */
237
+ function fetchConsoleRoute(params) {
238
+ const { credential } = params;
239
+ const identity = JSON.stringify([
240
+ credential.accessToken,
241
+ credential.orgId ?? null,
242
+ consoleBaseUrl(credential),
243
+ params.path ?? params.route,
244
+ ]);
245
+ return routeGuard(identity, () => {
246
+ params.onRequest?.();
247
+ return requestConsoleRoute(params);
248
+ }, params.timeoutMs, (retryAtMs) => ({
249
+ success: false,
250
+ error: `OpenCode Console ${params.route} error 429`,
251
+ failureCategory: providerFailureCategoryForHttpStatus(429),
252
+ retryAtMs,
253
+ }));
254
+ }
255
+ async function requestConsoleRoute(params) {
222
256
  const path = params.path ?? params.route;
223
257
  try {
224
258
  return await fetchWithTimeout(`${consoleBaseUrl(params.credential)}/api/${path}`, {
@@ -236,10 +270,12 @@ async function fetchConsoleRoute(params) {
236
270
  return { success: false, error: SESSION_ERROR, failureCategory: "credentials" };
237
271
  }
238
272
  if (!response.ok) {
273
+ const retryAtMs = retryAfterDeadline(response);
239
274
  return {
240
275
  success: false,
241
276
  error: `OpenCode Console ${params.route} error ${response.status}`,
242
277
  failureCategory: providerFailureCategoryForHttpStatus(response.status),
278
+ ...(retryAtMs !== undefined ? { retryAtMs } : {}),
243
279
  };
244
280
  }
245
281
  if (response.headers.get("content-type")?.includes("text/html")) {
@@ -293,14 +329,43 @@ function memberBudgetRequest(request) {
293
329
  parse: (json) => parseMemberBudgets(json, accountId),
294
330
  });
295
331
  }
296
- export async function queryOpenCodeZenQuota(credential, options = {}) {
332
+ export function queryOpenCodeZenQuota(credential, options = {}) {
333
+ const timeoutMs = options.requestTimeoutMs ?? CONSOLE_TIMEOUT_MS;
334
+ const now = new Date();
335
+ const identity = JSON.stringify([
336
+ credential.accessToken,
337
+ credential.orgId ?? null,
338
+ consoleBaseUrl(credential),
339
+ credential.accountId?.trim() ?? null,
340
+ currentUtcMonth(now),
341
+ ]);
342
+ return quotaQueryGuard(identity, () => queryOpenCodeZenQuotaOnce(credential, timeoutMs, now), timeoutMs);
343
+ }
344
+ async function queryOpenCodeZenQuotaOnce(credential, timeoutMs, now) {
297
345
  const request = {
298
346
  credential,
299
- timeoutMs: options.requestTimeoutMs ?? CONSOLE_TIMEOUT_MS,
347
+ timeoutMs,
300
348
  };
301
- const now = new Date();
349
+ // A fresh attempt sends every route concurrently. When billing/status did not
350
+ // start a request (an observed Retry-After block, or another in-flight
351
+ // request), settle it first: a cooldown result makes the optional routes
352
+ // pointless, so they are not sent.
353
+ let billingStarted = false;
354
+ const balancePending = fetchConsoleRoute({
355
+ ...request,
356
+ route: "billing/status",
357
+ parse: parseBalance,
358
+ onRequest: () => {
359
+ billingStarted = true;
360
+ },
361
+ });
362
+ if (!billingStarted) {
363
+ const early = await balancePending;
364
+ if (!early.success && early.retryAtMs !== undefined)
365
+ return early;
366
+ }
302
367
  const [balance, creditLimit, autoRecharge, member, monthlyUsage] = await Promise.all([
303
- fetchConsoleRoute({ ...request, route: "billing/status", parse: parseBalance }),
368
+ balancePending,
304
369
  fetchConsoleRoute({ ...request, route: "billing/account", parse: parseCreditLimit }),
305
370
  fetchConsoleRoute({ ...request, route: "billing/auto-recharge", parse: parseAutoRecharge }),
306
371
  memberBudgetRequest(request),
@@ -345,6 +410,7 @@ export async function queryOpenCodeZenQuota(credential, options = {}) {
345
410
  ...(result.failureCategory !== undefined
346
411
  ? { failureCategory: result.failureCategory }
347
412
  : {}),
413
+ ...(result.retryAtMs !== undefined ? { retryAtMs: result.retryAtMs } : {}),
348
414
  },
349
415
  ]);
350
416
  return {
@@ -101,8 +101,11 @@ function sidecarManagedComments(index, definition) {
101
101
  }
102
102
  export async function planProviderAdd(options) {
103
103
  const single = validateQuotaProviders([options.definition]);
104
- if (!single.value) {
105
- throw new Error(single.issues.map((issue) => issue.key + ": " + issue.message).join("\n"));
104
+ if (!single.value || single.value.length !== 1) {
105
+ const validationMessage = single.issues
106
+ .map((issue) => issue.key + ": " + issue.message)
107
+ .join("\n");
108
+ throw new Error(validationMessage || "definition is not a supported quota provider");
106
109
  }
107
110
  const definition = single.value[0];
108
111
  const configDir = options.configDir ?? getOpencodeRuntimeDirs().configDir;