@slkiser/opencode-quota 3.1.0 → 3.1.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 (44) hide show
  1. package/README.md +12 -7
  2. package/dist/lib/display-sanitize.d.ts +4 -1
  3. package/dist/lib/display-sanitize.d.ts.map +1 -1
  4. package/dist/lib/display-sanitize.js +19 -3
  5. package/dist/lib/display-sanitize.js.map +1 -1
  6. package/dist/lib/grouped-entry-normalization.d.ts +5 -0
  7. package/dist/lib/grouped-entry-normalization.d.ts.map +1 -1
  8. package/dist/lib/grouped-entry-normalization.js +7 -3
  9. package/dist/lib/grouped-entry-normalization.js.map +1 -1
  10. package/dist/lib/quota-command-format.d.ts.map +1 -1
  11. package/dist/lib/quota-command-format.js +41 -42
  12. package/dist/lib/quota-command-format.js.map +1 -1
  13. package/dist/lib/quota-render-data.d.ts +12 -0
  14. package/dist/lib/quota-render-data.d.ts.map +1 -1
  15. package/dist/lib/quota-render-data.js +28 -0
  16. package/dist/lib/quota-render-data.js.map +1 -1
  17. package/dist/lib/quota-stats-format.d.ts.map +1 -1
  18. package/dist/lib/quota-stats-format.js +164 -121
  19. package/dist/lib/quota-stats-format.js.map +1 -1
  20. package/dist/lib/quota-status.d.ts +7 -0
  21. package/dist/lib/quota-status.d.ts.map +1 -1
  22. package/dist/lib/quota-status.js +690 -277
  23. package/dist/lib/quota-status.js.map +1 -1
  24. package/dist/lib/report-document.d.ts +36 -0
  25. package/dist/lib/report-document.d.ts.map +1 -0
  26. package/dist/lib/report-document.js +109 -0
  27. package/dist/lib/report-document.js.map +1 -0
  28. package/dist/lib/session-tokens-format.d.ts +8 -0
  29. package/dist/lib/session-tokens-format.d.ts.map +1 -1
  30. package/dist/lib/session-tokens-format.js +36 -20
  31. package/dist/lib/session-tokens-format.js.map +1 -1
  32. package/dist/lib/synthetic.d.ts.map +1 -1
  33. package/dist/lib/synthetic.js +22 -13
  34. package/dist/lib/synthetic.js.map +1 -1
  35. package/dist/lib/types.d.ts +7 -2
  36. package/dist/lib/types.d.ts.map +1 -1
  37. package/dist/lib/types.js.map +1 -1
  38. package/dist/plugin.d.ts.map +1 -1
  39. package/dist/plugin.js +39 -1
  40. package/dist/plugin.js.map +1 -1
  41. package/dist/providers/synthetic.d.ts.map +1 -1
  42. package/dist/providers/synthetic.js +18 -4
  43. package/dist/providers/synthetic.js.map +1 -1
  44. package/package.json +1 -1
@@ -22,12 +22,15 @@ import { getProviders } from "../providers/registry.js";
22
22
  import { getPackageVersion } from "./version.js";
23
23
  import { getOpenCodeDbPath, getOpenCodeDbPathCandidates, getOpenCodeDbStats, } from "./opencode-storage.js";
24
24
  import { aggregateUsage } from "./quota-stats.js";
25
- import { fmtUsdAmount, renderCommandHeading } from "./format-utils.js";
25
+ import { fmtUsdAmount } from "./format-utils.js";
26
+ import { renderPlainTextReport } from "./report-document.js";
26
27
  import { totalTokenBuckets } from "./token-buckets.js";
27
28
  import { CURSOR_CANONICAL_PLUGIN_PACKAGE, inspectCursorAuthPresence, inspectCursorOpenCodeIntegration, } from "./cursor-detection.js";
28
29
  import { getCurrentCursorUsageSummary } from "./cursor-usage.js";
29
- import { sanitizeDisplayText } from "./display-sanitize.js";
30
+ import { sanitizeSingleLineDisplaySnippet, sanitizeSingleLineDisplayText, sanitizeDisplayText, sanitizeQuotaProviderResult, } from "./display-sanitize.js";
30
31
  import { getCursorPlanDisplayName, getEffectiveCursorIncludedApiUsd } from "./cursor-pricing.js";
32
+ import { getQuotaProviderDisplayLabel } from "./provider-metadata.js";
33
+ import { isValueEntry } from "./entries.js";
31
34
  import { queryMiniMaxQuota } from "../providers/minimax-coding-plan.js";
32
35
  import { queryZaiQuota } from "./zai.js";
33
36
  import { getOpenCodeGoConfigDiagnostics, resolveOpenCodeGoConfigCached, DEFAULT_OPENCODE_GO_CONFIG_CACHE_MAX_AGE_MS, } from "./opencode-go-config.js";
@@ -45,6 +48,9 @@ function fmtInt(n) {
45
48
  return Math.trunc(n).toLocaleString("en-US");
46
49
  }
47
50
  const STATUS_SAMPLE_LIMIT = 5;
51
+ const STATUS_LIVE_ENTRY_LIMIT = 2;
52
+ const STATUS_LIVE_ERROR_LIMIT = 2;
53
+ const STATUS_LIVE_ROW_MAX_LENGTH = 120;
48
54
  function joinOrNone(values) {
49
55
  return values.length > 0 ? values.join(" | ") : "(none)";
50
56
  }
@@ -82,13 +88,120 @@ async function readBasicApiKeyDiagnostics(read) {
82
88
  return getDefaultBasicApiKeyDiagnostics();
83
89
  }
84
90
  }
85
- function formatInlineApiKeyDiagnostics(label, diagnostics) {
86
- return `- ${label}: configured=${diagnostics.configured ? "true" : "false"}${diagnostics.source ? ` source=${diagnostics.source}` : ""}${diagnostics.checkedPaths.length > 0 ? ` checked=${diagnostics.checkedPaths.join(" | ")}` : ""}`;
91
+ function formatInlineApiKeyDiagnosticsValue(diagnostics) {
92
+ return `configured=${diagnostics.configured ? "true" : "false"}${diagnostics.source ? ` source=${diagnostics.source}` : ""}${diagnostics.checkedPaths.length > 0 ? ` checked=${diagnostics.checkedPaths.join(" | ")}` : ""}`;
87
93
  }
88
- function appendBasicApiKeySection(params) {
89
- params.lines.push("");
90
- params.lines.push(params.section);
91
- params.lines.push(formatInlineApiKeyDiagnostics(params.label, params.diagnostics));
94
+ function createKvSection(id, title, rows) {
95
+ return {
96
+ id,
97
+ title,
98
+ blocks: [{ kind: "kv", rows }],
99
+ };
100
+ }
101
+ function createLinesSection(id, title, lines) {
102
+ return {
103
+ id,
104
+ title,
105
+ blocks: [{ kind: "lines", lines }],
106
+ };
107
+ }
108
+ function normalizeLiveProbeText(value) {
109
+ return sanitizeSingleLineDisplayText(value).replace(/:+$/u, "").toLowerCase();
110
+ }
111
+ function isRedundantLiveProbeDescriptor(providerId, value) {
112
+ if (!value)
113
+ return true;
114
+ const normalized = normalizeLiveProbeText(value);
115
+ if (!normalized)
116
+ return true;
117
+ return (normalized === normalizeLiveProbeText(providerId) ||
118
+ normalized === normalizeLiveProbeText(getQuotaProviderDisplayLabel(providerId)));
119
+ }
120
+ function findProviderLiveProbe(providerId, probes) {
121
+ return probes?.find((probe) => probe.providerId === providerId);
122
+ }
123
+ function appendProviderCompactLiveProbeRows(rows, providerId, probes) {
124
+ appendCompactLiveProbeRows(rows, providerId, findProviderLiveProbe(providerId, probes));
125
+ }
126
+ function createCompactLiveProbeOnlySection(params) {
127
+ const probe = findProviderLiveProbe(params.providerId, params.probes);
128
+ if (!probe) {
129
+ return null;
130
+ }
131
+ const rows = [];
132
+ appendCompactLiveProbeRows(rows, params.providerId, probe);
133
+ return createKvSection(params.id, params.title, rows);
134
+ }
135
+ function getCompactLiveProbeDescriptor(providerId, entry) {
136
+ const candidates = [entry.label, entry.name, entry.group];
137
+ for (const candidate of candidates) {
138
+ if (typeof candidate !== "string")
139
+ continue;
140
+ const cleaned = sanitizeSingleLineDisplayText(candidate);
141
+ if (!cleaned || isRedundantLiveProbeDescriptor(providerId, cleaned)) {
142
+ continue;
143
+ }
144
+ return cleaned;
145
+ }
146
+ return undefined;
147
+ }
148
+ function formatCompactLiveProbeEntry(providerId, entry) {
149
+ const parts = [];
150
+ const descriptor = getCompactLiveProbeDescriptor(providerId, entry);
151
+ if (descriptor) {
152
+ parts.push(descriptor);
153
+ }
154
+ if (isValueEntry(entry)) {
155
+ parts.push(`value=${sanitizeSingleLineDisplayText(entry.value)}`);
156
+ }
157
+ else {
158
+ if (entry.right) {
159
+ parts.push(sanitizeSingleLineDisplayText(entry.right));
160
+ }
161
+ const percentRemaining = Number.isFinite(entry.percentRemaining)
162
+ ? Math.max(0, Math.min(100, Math.round(entry.percentRemaining)))
163
+ : 0;
164
+ parts.push(`percent_remaining=${percentRemaining}`);
165
+ }
166
+ if (entry.resetTimeIso) {
167
+ parts.push(`reset_at=${sanitizeSingleLineDisplayText(entry.resetTimeIso)}`);
168
+ }
169
+ return sanitizeSingleLineDisplaySnippet(parts.join(" "), STATUS_LIVE_ROW_MAX_LENGTH);
170
+ }
171
+ function formatCompactLiveProbeError(providerId, error) {
172
+ const label = isRedundantLiveProbeDescriptor(providerId, error.label)
173
+ ? ""
174
+ : sanitizeSingleLineDisplayText(error.label);
175
+ const message = sanitizeSingleLineDisplayText(error.message);
176
+ return sanitizeSingleLineDisplaySnippet(label ? `${label}: ${message}` : message, STATUS_LIVE_ROW_MAX_LENGTH);
177
+ }
178
+ function appendCompactLiveProbeRows(rows, providerId, probe) {
179
+ if (!probe)
180
+ return;
181
+ const result = sanitizeQuotaProviderResult(probe.result);
182
+ const entryCount = Math.min(result.entries.length, STATUS_LIVE_ENTRY_LIMIT);
183
+ const errorCount = Math.min(result.errors.length, STATUS_LIVE_ERROR_LIMIT);
184
+ const state = result.entries.length > 0 ? "success" : result.errors.length > 0 ? "error" : "no_data";
185
+ rows.push({ key: "live_probe", value: state });
186
+ for (let index = 0; index < entryCount; index += 1) {
187
+ rows.push({
188
+ key: `live_entry_${index + 1}`,
189
+ value: formatCompactLiveProbeEntry(providerId, result.entries[index]),
190
+ });
191
+ }
192
+ for (let index = 0; index < errorCount; index += 1) {
193
+ rows.push({
194
+ key: `live_error_${index + 1}`,
195
+ value: formatCompactLiveProbeError(providerId, result.errors[index]),
196
+ });
197
+ }
198
+ const suppressedCount = Math.max(0, result.entries.length - entryCount) + Math.max(0, result.errors.length - errorCount);
199
+ if (suppressedCount > 0) {
200
+ rows.push({
201
+ key: "live_more",
202
+ value: `+${suppressedCount} additional rows suppressed`,
203
+ });
204
+ }
92
205
  }
93
206
  function getDefaultNanoGptApiKeyDiagnostics() {
94
207
  return {
@@ -104,14 +217,6 @@ async function readNanoGptApiKeyDiagnostics(read) {
104
217
  return getDefaultNanoGptApiKeyDiagnostics();
105
218
  }
106
219
  }
107
- function appendNanoGptApiKeySection(lines, diagnostics) {
108
- lines.push("");
109
- lines.push("nanogpt:");
110
- lines.push(`- api_key_configured: ${diagnostics.configured ? "true" : "false"}`);
111
- lines.push(`- api_key_source: ${diagnostics.source ?? "(none)"}`);
112
- lines.push(`- api_key_checked_paths: ${joinOrNone(diagnostics.checkedPaths)}`);
113
- lines.push(`- api_key_auth_paths: ${joinOrNone(diagnostics.authPaths)}`);
114
- }
115
220
  function fmtNanoGptMetric(value) {
116
221
  if (!Number.isFinite(value))
117
222
  return "0";
@@ -256,20 +361,8 @@ function supportedProviderPricingRow(params) {
256
361
  };
257
362
  }
258
363
  export async function buildQuotaStatusReport(params) {
259
- const lines = [];
260
364
  const version = await getPackageVersion();
261
365
  const v = version ?? "unknown";
262
- lines.push(renderCommandHeading({
263
- title: `Quota Status (opencode-quota v${v}) (/quota_status)`,
264
- generatedAtMs: params.generatedAtMs,
265
- }));
266
- lines.push("");
267
- // === toast diagnostics ===
268
- lines.push("toast:");
269
- lines.push(`- configSource: ${params.configSource}${params.configPaths.length ? ` (${params.configPaths.join(" | ")})` : ""}`);
270
- lines.push(`- network_setting_sources: ${formatNetworkSettingSources(params.networkSettingSources)}`);
271
- lines.push(`- enabledProviders: ${params.enabledProviders === "auto" ? "(auto)" : params.enabledProviders.length ? params.enabledProviders.join(",") : "(none)"}`);
272
- lines.push(`- onlyCurrentModel: ${params.onlyCurrentModel ? "true" : "false"}`);
273
366
  const modelDisplay = params.currentModel
274
367
  ? params.currentModel
275
368
  : params.sessionModelLookup === "not_found"
@@ -277,18 +370,26 @@ export async function buildQuotaStatusReport(params) {
277
370
  : params.sessionModelLookup === "no_session"
278
371
  ? "(no session available)"
279
372
  : "(unknown)";
280
- lines.push(`- currentModel: ${modelDisplay}`);
373
+ const sections = [];
374
+ // === toast diagnostics ===
375
+ const toastLines = [
376
+ `- configSource: ${params.configSource}${params.configPaths.length ? ` (${params.configPaths.join(" | ")})` : ""}`,
377
+ `- network_setting_sources: ${formatNetworkSettingSources(params.networkSettingSources)}`,
378
+ `- enabledProviders: ${params.enabledProviders === "auto" ? "(auto)" : params.enabledProviders.length ? params.enabledProviders.join(",") : "(none)"}`,
379
+ `- onlyCurrentModel: ${params.onlyCurrentModel ? "true" : "false"}`,
380
+ `- currentModel: ${modelDisplay}`,
381
+ ];
281
382
  if (params.tuiDiagnostics) {
282
- lines.push("");
283
- lines.push("tui:");
284
- lines.push(`- config_configured: ${params.tuiDiagnostics.configured ? "true" : "false"}`);
285
- lines.push(`- inferred_selected_config_path: ${params.tuiDiagnostics.inferredSelectedPath ?? "(none)"}`);
286
- lines.push(`- present_config_paths: ${joinOrNone(params.tuiDiagnostics.presentPaths)}`);
287
- lines.push(`- candidate_config_paths: ${joinOrNone(params.tuiDiagnostics.candidatePaths)}`);
288
- lines.push(`- quota_plugin_configured: ${params.tuiDiagnostics.quotaPluginConfigured ? "true" : "false"}`);
289
- lines.push(`- quota_plugin_paths: ${joinOrNone(params.tuiDiagnostics.quotaPluginConfigPaths)}`);
290
- }
291
- lines.push("- providers:");
383
+ toastLines.push("");
384
+ toastLines.push("tui:");
385
+ toastLines.push(`- config_configured: ${params.tuiDiagnostics.configured ? "true" : "false"}`);
386
+ toastLines.push(`- inferred_selected_config_path: ${params.tuiDiagnostics.inferredSelectedPath ?? "(none)"}`);
387
+ toastLines.push(`- present_config_paths: ${joinOrNone(params.tuiDiagnostics.presentPaths)}`);
388
+ toastLines.push(`- candidate_config_paths: ${joinOrNone(params.tuiDiagnostics.candidatePaths)}`);
389
+ toastLines.push(`- quota_plugin_configured: ${params.tuiDiagnostics.quotaPluginConfigured ? "true" : "false"}`);
390
+ toastLines.push(`- quota_plugin_paths: ${joinOrNone(params.tuiDiagnostics.quotaPluginConfigPaths)}`);
391
+ }
392
+ toastLines.push("- providers:");
292
393
  for (const p of params.providerAvailability) {
293
394
  const bits = [];
294
395
  bits.push(p.enabled ? "enabled" : "disabled");
@@ -296,12 +397,16 @@ export async function buildQuotaStatusReport(params) {
296
397
  if (p.matchesCurrentModel !== undefined) {
297
398
  bits.push(`matchesCurrentModel=${p.matchesCurrentModel ? "yes" : "no"}`);
298
399
  }
299
- lines.push(` - ${p.id}: ${bits.join(" ")}`);
400
+ toastLines.push(` - ${p.id}: ${bits.join(" ")}`);
300
401
  }
301
- lines.push("");
302
- lines.push("paths:");
402
+ sections.push(createLinesSection("toast", "toast:", toastLines));
403
+ // === paths ===
404
+ const pathsRows = [];
303
405
  const runtime = getOpencodeRuntimeDirs();
304
- lines.push(`- opencode_dirs: data=${runtime.dataDir} config=${runtime.configDir} cache=${runtime.cacheDir} state=${runtime.stateDir}`);
406
+ pathsRows.push({
407
+ key: "opencode_dirs",
408
+ value: `data=${runtime.dataDir} config=${runtime.configDir} cache=${runtime.cacheDir} state=${runtime.stateDir}`,
409
+ });
305
410
  const authCandidates = getAuthPaths();
306
411
  const authPresent = [];
307
412
  await Promise.all(authCandidates.map(async (p) => {
@@ -313,7 +418,10 @@ export async function buildQuotaStatusReport(params) {
313
418
  // ignore missing/unreadable
314
419
  }
315
420
  }));
316
- lines.push(`- auth.json: preferred=${getAuthPath()} present=${joinOrNone(authPresent)} candidates=${joinOrNone(authCandidates)}`);
421
+ pathsRows.push({
422
+ key: "auth.json",
423
+ value: `preferred=${getAuthPath()} present=${joinOrNone(authPresent)} candidates=${joinOrNone(authCandidates)}`,
424
+ });
317
425
  const authData = await readAuthFileCached({ maxAgeMs: 5_000 });
318
426
  const qwenAuthConfigured = hasQwenOAuthAuth(authData);
319
427
  const qwenLocalPlan = resolveQwenLocalPlan(authData);
@@ -326,55 +434,131 @@ export async function buildQuotaStatusReport(params) {
326
434
  maxAgeMs: DEFAULT_ALIBABA_AUTH_CACHE_MAX_AGE_MS,
327
435
  fallbackTier: params.alibabaCodingPlanTier,
328
436
  });
329
- lines.push(`- qwen oauth auth configured: ${qwenAuthConfigured ? "true" : "false"}`);
330
- lines.push(`- qwen_oauth_source: ${qwenLocalPlan.state === "qwen_free" ? qwenLocalPlan.sourceKey : "(none)"}`);
331
- lines.push(`- qwen_local_plan: ${qwenLocalPlan.state === "qwen_free" ? "qwen-code/free" : "(none)"}`);
332
- lines.push(`- alibaba auth configured: ${alibabaAuthDiagnostics.state === "none" ? "false" : "true"}`);
333
- lines.push(`- alibaba_api_key_source: ${alibabaAuthDiagnostics.source ?? "(none)"}`);
334
- lines.push(`- alibaba_api_key_checked_paths: ${joinOrNone(alibabaAuthDiagnostics.checkedPaths)}`);
335
- lines.push(`- alibaba_api_key_auth_paths: ${joinOrNone(alibabaAuthDiagnostics.authPaths)}`);
336
- lines.push(`- alibaba coding plan fallback tier: ${params.alibabaCodingPlanTier}`);
337
- lines.push(`- alibaba_coding_plan: ${alibabaAuthDiagnostics.state === "configured" ? alibabaAuthDiagnostics.tier : alibabaAuthDiagnostics.state === "invalid" ? "invalid" : "(none)"}`);
437
+ pathsRows.push({ key: "qwen oauth auth configured", value: qwenAuthConfigured ? "true" : "false" });
438
+ pathsRows.push({
439
+ key: "qwen_oauth_source",
440
+ value: qwenLocalPlan.state === "qwen_free" ? qwenLocalPlan.sourceKey : "(none)",
441
+ });
442
+ pathsRows.push({
443
+ key: "qwen_local_plan",
444
+ value: qwenLocalPlan.state === "qwen_free" ? "qwen-code/free" : "(none)",
445
+ });
446
+ pathsRows.push({
447
+ key: "alibaba auth configured",
448
+ value: alibabaAuthDiagnostics.state === "none" ? "false" : "true",
449
+ });
450
+ pathsRows.push({ key: "alibaba_api_key_source", value: alibabaAuthDiagnostics.source ?? "(none)" });
451
+ pathsRows.push({
452
+ key: "alibaba_api_key_checked_paths",
453
+ value: joinOrNone(alibabaAuthDiagnostics.checkedPaths),
454
+ });
455
+ pathsRows.push({
456
+ key: "alibaba_api_key_auth_paths",
457
+ value: joinOrNone(alibabaAuthDiagnostics.authPaths),
458
+ });
459
+ pathsRows.push({
460
+ key: "alibaba coding plan fallback tier",
461
+ value: params.alibabaCodingPlanTier,
462
+ });
463
+ pathsRows.push({
464
+ key: "alibaba_coding_plan",
465
+ value: alibabaAuthDiagnostics.state === "configured"
466
+ ? alibabaAuthDiagnostics.tier
467
+ : alibabaAuthDiagnostics.state === "invalid"
468
+ ? "invalid"
469
+ : "(none)",
470
+ });
338
471
  if (alibabaAuthDiagnostics.state === "invalid") {
339
- lines.push(`- alibaba_auth_error: ${sanitizeDisplayText(alibabaAuthDiagnostics.error)}`);
472
+ pathsRows.push({
473
+ key: "alibaba_auth_error",
474
+ value: sanitizeDisplayText(alibabaAuthDiagnostics.error),
475
+ });
340
476
  }
341
- lines.push("");
342
- lines.push("openai:");
343
- lines.push(`- auth_configured: ${openaiAuth.state === "configured" ? "true" : "false"}`);
344
- lines.push(`- auth_source: ${openaiAuth.state === "configured" ? openaiAuth.sourceKey : "(none)"}`);
477
+ sections.push(createKvSection("paths", "paths:", pathsRows));
478
+ // === openai ===
479
+ const openaiRows = [
480
+ { key: "auth_configured", value: openaiAuth.state === "configured" ? "true" : "false" },
481
+ {
482
+ key: "auth_source",
483
+ value: openaiAuth.state === "configured" ? openaiAuth.sourceKey : "(none)",
484
+ },
485
+ ];
345
486
  const openaiTokenStatus = openaiAuth.state !== "configured"
346
487
  ? "(none)"
347
488
  : openaiAuth.expiresAt && openaiAuth.expiresAt < Date.now()
348
489
  ? "expired"
349
490
  : "valid";
350
- lines.push(`- token_status: ${openaiTokenStatus}`);
351
- lines.push(`- token_expires_at: ${openaiAuth.state === "configured" && openaiAuth.expiresAt ? new Date(openaiAuth.expiresAt).toISOString() : "(none)"}`);
352
- lines.push(`- account_email: ${openaiAuth.state === "configured" && openaiAuth.email ? sanitizeDisplayText(openaiAuth.email) : "(none)"}`);
353
- lines.push(`- account_id: ${openaiAuth.state === "configured" && openaiAuth.accountId ? sanitizeDisplayText(openaiAuth.accountId) : "(none)"}`);
354
- lines.push("");
355
- lines.push("anthropic:");
491
+ openaiRows.push({ key: "token_status", value: openaiTokenStatus });
492
+ openaiRows.push({
493
+ key: "token_expires_at",
494
+ value: openaiAuth.state === "configured" && openaiAuth.expiresAt
495
+ ? new Date(openaiAuth.expiresAt).toISOString()
496
+ : "(none)",
497
+ });
498
+ openaiRows.push({
499
+ key: "account_email",
500
+ value: openaiAuth.state === "configured" && openaiAuth.email
501
+ ? sanitizeDisplayText(openaiAuth.email)
502
+ : "(none)",
503
+ });
504
+ openaiRows.push({
505
+ key: "account_id",
506
+ value: openaiAuth.state === "configured" && openaiAuth.accountId
507
+ ? sanitizeDisplayText(openaiAuth.accountId)
508
+ : "(none)",
509
+ });
510
+ appendProviderCompactLiveProbeRows(openaiRows, "openai", params.providerLiveProbes);
511
+ sections.push(createKvSection("openai", "openai:", openaiRows));
512
+ // === anthropic ===
513
+ const anthropicRows = [];
356
514
  try {
357
515
  const anthropicDiagnostics = await getAnthropicDiagnostics({
358
516
  binaryPath: params.anthropicBinaryPath,
359
517
  });
360
- lines.push(`- cli_installed: ${anthropicDiagnostics.installed ? "true" : "false"}`);
361
- lines.push(`- cli_version: ${anthropicDiagnostics.version ?? "(none)"}`);
362
- lines.push(`- auth_status: ${anthropicDiagnostics.authStatus}`);
363
- lines.push(`- quota_supported: ${anthropicDiagnostics.quotaSupported ? "true" : "false"}`);
364
- lines.push(`- quota_source: ${anthropicDiagnostics.quotaSource === "none" ? "(none)" : anthropicDiagnostics.quotaSource}`);
365
- lines.push(`- checked_commands: ${anthropicDiagnostics.checkedCommands.length > 0 ? anthropicDiagnostics.checkedCommands.join(" | ") : "(none)"}`);
518
+ anthropicRows.push({
519
+ key: "cli_installed",
520
+ value: anthropicDiagnostics.installed ? "true" : "false",
521
+ });
522
+ anthropicRows.push({ key: "cli_version", value: anthropicDiagnostics.version ?? "(none)" });
523
+ anthropicRows.push({ key: "auth_status", value: anthropicDiagnostics.authStatus });
524
+ anthropicRows.push({
525
+ key: "quota_supported",
526
+ value: anthropicDiagnostics.quotaSupported ? "true" : "false",
527
+ });
528
+ anthropicRows.push({
529
+ key: "quota_source",
530
+ value: anthropicDiagnostics.quotaSource === "none" ? "(none)" : anthropicDiagnostics.quotaSource,
531
+ });
532
+ anthropicRows.push({
533
+ key: "checked_commands",
534
+ value: anthropicDiagnostics.checkedCommands.length > 0
535
+ ? anthropicDiagnostics.checkedCommands.join(" | ")
536
+ : "(none)",
537
+ });
366
538
  if (anthropicDiagnostics.message) {
367
- lines.push(`- message: ${anthropicDiagnostics.message}`);
539
+ anthropicRows.push({ key: "message", value: anthropicDiagnostics.message });
368
540
  }
369
541
  if (anthropicDiagnostics.quotaSupported && anthropicDiagnostics.quota) {
370
- lines.push(`- five_hour_remaining: ${anthropicDiagnostics.quota.five_hour.percentRemaining}% reset_at=${anthropicDiagnostics.quota.five_hour.resetTimeIso ?? "(none)"}`);
371
- lines.push(`- seven_day_remaining: ${anthropicDiagnostics.quota.seven_day.percentRemaining}% reset_at=${anthropicDiagnostics.quota.seven_day.resetTimeIso ?? "(none)"}`);
542
+ anthropicRows.push({
543
+ key: "five_hour_remaining",
544
+ value: `${anthropicDiagnostics.quota.five_hour.percentRemaining}% reset_at=${anthropicDiagnostics.quota.five_hour.resetTimeIso ?? "(none)"}`,
545
+ });
546
+ anthropicRows.push({
547
+ key: "seven_day_remaining",
548
+ value: `${anthropicDiagnostics.quota.seven_day.percentRemaining}% reset_at=${anthropicDiagnostics.quota.seven_day.resetTimeIso ?? "(none)"}`,
549
+ });
372
550
  }
373
551
  }
374
552
  catch (err) {
375
- lines.push("- cli_installed: false");
376
- lines.push(`- message: failed to probe Claude CLI${err ? `: ${sanitizeDisplayText(err instanceof Error ? err.message : String(err))}` : ""}`);
553
+ anthropicRows.push({ key: "cli_installed", value: "false" });
554
+ anthropicRows.push({
555
+ key: "message",
556
+ value: `failed to probe Claude CLI${err ? `: ${sanitizeDisplayText(err instanceof Error ? err.message : String(err))}` : ""}`,
557
+ });
377
558
  }
559
+ appendProviderCompactLiveProbeRows(anthropicRows, "anthropic", params.providerLiveProbes);
560
+ sections.push(createKvSection("anthropic", "anthropic:", anthropicRows));
561
+ // === cursor ===
378
562
  const cursorPlanLabel = getCursorPlanDisplayName(params.cursorPlan);
379
563
  const cursorIncludedApiUsd = getEffectiveCursorIncludedApiUsd({
380
564
  plan: params.cursorPlan,
@@ -382,54 +566,83 @@ export async function buildQuotaStatusReport(params) {
382
566
  });
383
567
  const cursorAuth = await inspectCursorAuthPresence();
384
568
  const cursorIntegration = await inspectCursorOpenCodeIntegration();
385
- lines.push("");
386
- lines.push("cursor:");
387
- lines.push(`- plan: ${cursorPlanLabel ?? "none"}`);
388
- lines.push(`- included_api_usd: ${typeof cursorIncludedApiUsd === "number" ? fmtUsdAmount(cursorIncludedApiUsd) : "(none)"}`);
389
- lines.push(`- billing_cycle_start_day: ${typeof params.cursorBillingCycleStartDay === "number" ? params.cursorBillingCycleStartDay : "(calendar month)"}`);
390
- lines.push(`- auth_state: ${cursorAuth.state}`);
391
- lines.push(`- auth_selected_path: ${cursorAuth.selectedPath ?? "(none)"}`);
392
- lines.push(`- auth_present_paths: ${joinOrNone(cursorAuth.presentPaths)}`);
393
- lines.push(`- auth_candidate_paths: ${joinOrNone(cursorAuth.candidatePaths)}`);
569
+ const cursorRows = [
570
+ { key: "plan", value: cursorPlanLabel ?? "none" },
571
+ {
572
+ key: "included_api_usd",
573
+ value: typeof cursorIncludedApiUsd === "number" ? fmtUsdAmount(cursorIncludedApiUsd) : "(none)",
574
+ },
575
+ {
576
+ key: "billing_cycle_start_day",
577
+ value: typeof params.cursorBillingCycleStartDay === "number"
578
+ ? String(params.cursorBillingCycleStartDay)
579
+ : "(calendar month)",
580
+ },
581
+ { key: "auth_state", value: cursorAuth.state },
582
+ { key: "auth_selected_path", value: cursorAuth.selectedPath ?? "(none)" },
583
+ { key: "auth_present_paths", value: joinOrNone(cursorAuth.presentPaths) },
584
+ { key: "auth_candidate_paths", value: joinOrNone(cursorAuth.candidatePaths) },
585
+ ];
394
586
  if (cursorAuth.error) {
395
- lines.push(`- auth_error: ${cursorAuth.error}`);
587
+ cursorRows.push({ key: "auth_error", value: cursorAuth.error });
396
588
  }
397
- lines.push(`- plugin_enabled: ${cursorIntegration.pluginEnabled ? "true" : "false"}`);
398
- lines.push(`- canonical_plugin_package: ${CURSOR_CANONICAL_PLUGIN_PACKAGE}`);
399
- lines.push(`- provider_configured: ${cursorIntegration.providerConfigured ? "true" : "false"}`);
400
- lines.push(`- config_matches: ${joinOrNone(cursorIntegration.matchedPaths)}`);
401
- lines.push(`- config_checked_paths: ${joinOrNone(cursorIntegration.checkedPaths)}`);
589
+ cursorRows.push({ key: "plugin_enabled", value: cursorIntegration.pluginEnabled ? "true" : "false" });
590
+ cursorRows.push({ key: "canonical_plugin_package", value: CURSOR_CANONICAL_PLUGIN_PACKAGE });
591
+ cursorRows.push({
592
+ key: "provider_configured",
593
+ value: cursorIntegration.providerConfigured ? "true" : "false",
594
+ });
595
+ cursorRows.push({ key: "config_matches", value: joinOrNone(cursorIntegration.matchedPaths) });
596
+ cursorRows.push({ key: "config_checked_paths", value: joinOrNone(cursorIntegration.checkedPaths) });
402
597
  try {
403
598
  const cursorUsage = await getCurrentCursorUsageSummary({
404
599
  billingCycleStartDay: params.cursorBillingCycleStartDay,
405
600
  });
406
- lines.push(`- cycle_source: ${cursorUsage.window.source}`);
407
- lines.push(`- cycle_reset_at: ${cursorUsage.window.resetTimeIso}`);
408
- lines.push(`- api_usage: ${fmtUsdAmount(cursorUsage.api.costUsd)} across ${fmtInt(cursorUsage.api.messageCount)} messages`);
409
- lines.push(`- auto_composer_usage: ${fmtUsdAmount(cursorUsage.autoComposer.costUsd)} across ${fmtInt(cursorUsage.autoComposer.messageCount)} messages`);
410
- lines.push(`- total_cursor_usage: ${fmtUsdAmount(cursorUsage.total.costUsd)} across ${fmtInt(cursorUsage.total.messageCount)} messages`);
411
- lines.push(`- unknown_cursor_models: ${fmtInt(cursorUsage.unknownModels.length)}`);
601
+ cursorRows.push({ key: "cycle_source", value: cursorUsage.window.source });
602
+ cursorRows.push({ key: "cycle_reset_at", value: cursorUsage.window.resetTimeIso });
603
+ cursorRows.push({
604
+ key: "api_usage",
605
+ value: `${fmtUsdAmount(cursorUsage.api.costUsd)} across ${fmtInt(cursorUsage.api.messageCount)} messages`,
606
+ });
607
+ cursorRows.push({
608
+ key: "auto_composer_usage",
609
+ value: `${fmtUsdAmount(cursorUsage.autoComposer.costUsd)} across ${fmtInt(cursorUsage.autoComposer.messageCount)} messages`,
610
+ });
611
+ cursorRows.push({
612
+ key: "total_cursor_usage",
613
+ value: `${fmtUsdAmount(cursorUsage.total.costUsd)} across ${fmtInt(cursorUsage.total.messageCount)} messages`,
614
+ });
615
+ cursorRows.push({ key: "unknown_cursor_models", value: fmtInt(cursorUsage.unknownModels.length) });
412
616
  }
413
617
  catch (err) {
414
618
  const msg = err instanceof Error ? err.message : String(err);
415
- lines.push(`- usage_error: ${msg}`);
619
+ cursorRows.push({ key: "usage_error", value: msg });
416
620
  }
417
621
  const qwenLocalQuotaPath = getQwenLocalQuotaPath();
418
622
  const qwenLocalQuotaExists = await pathExists(qwenLocalQuotaPath);
419
- lines.push(`- qwen free local quota: path=${qwenLocalQuotaPath} exists=${qwenLocalQuotaExists ? "true" : "false"}`);
623
+ cursorRows.push({
624
+ key: "qwen free local quota",
625
+ value: `path=${qwenLocalQuotaPath} exists=${qwenLocalQuotaExists ? "true" : "false"}`,
626
+ });
420
627
  try {
421
628
  const qwenState = await readQwenLocalQuotaState();
422
629
  const qwenQuota = computeQwenQuota({ state: qwenState });
423
630
  const qwenUsageSuffix = qwenLocalQuotaExists ? "" : " (default state)";
424
- lines.push(`- qwen free local usage: daily=${qwenQuota.day.used}/${qwenQuota.day.limit} rpm=${qwenQuota.rpm.used}/${qwenQuota.rpm.limit}${qwenUsageSuffix}`);
631
+ cursorRows.push({
632
+ key: "qwen free local usage",
633
+ value: `daily=${qwenQuota.day.used}/${qwenQuota.day.limit} rpm=${qwenQuota.rpm.used}/${qwenQuota.rpm.limit}${qwenUsageSuffix}`,
634
+ });
425
635
  }
426
636
  catch (err) {
427
637
  const msg = err instanceof Error ? err.message : String(err);
428
- lines.push(`- qwen free local usage: error (${msg})`);
638
+ cursorRows.push({ key: "qwen free local usage", value: `error (${msg})` });
429
639
  }
430
640
  const alibabaLocalQuotaPath = getAlibabaCodingPlanQuotaPath();
431
641
  const alibabaLocalQuotaExists = await pathExists(alibabaLocalQuotaPath);
432
- lines.push(`- alibaba coding plan local quota: path=${alibabaLocalQuotaPath} exists=${alibabaLocalQuotaExists ? "true" : "false"}`);
642
+ cursorRows.push({
643
+ key: "alibaba coding plan local quota",
644
+ value: `path=${alibabaLocalQuotaPath} exists=${alibabaLocalQuotaExists ? "true" : "false"}`,
645
+ });
433
646
  if (alibabaCodingPlanAuth.state === "configured") {
434
647
  try {
435
648
  const alibabaState = await readAlibabaCodingPlanQuotaState();
@@ -438,280 +651,395 @@ export async function buildQuotaStatusReport(params) {
438
651
  tier: alibabaCodingPlanAuth.tier,
439
652
  });
440
653
  const alibabaUsageSuffix = alibabaLocalQuotaExists ? "" : " (default state)";
441
- lines.push(`- alibaba coding plan usage: tier=${alibabaCodingPlanAuth.tier} 5h=${alibabaQuota.fiveHour.used}/${alibabaQuota.fiveHour.limit} weekly=${alibabaQuota.weekly.used}/${alibabaQuota.weekly.limit} monthly=${alibabaQuota.monthly.used}/${alibabaQuota.monthly.limit}${alibabaUsageSuffix}`);
654
+ cursorRows.push({
655
+ key: "alibaba coding plan usage",
656
+ value: `tier=${alibabaCodingPlanAuth.tier} 5h=${alibabaQuota.fiveHour.used}/${alibabaQuota.fiveHour.limit} weekly=${alibabaQuota.weekly.used}/${alibabaQuota.weekly.limit} monthly=${alibabaQuota.monthly.used}/${alibabaQuota.monthly.limit}${alibabaUsageSuffix}`,
657
+ });
442
658
  }
443
659
  catch (err) {
444
660
  const msg = err instanceof Error ? err.message : String(err);
445
- lines.push(`- alibaba coding plan usage: error (${msg})`);
661
+ cursorRows.push({ key: "alibaba coding plan usage", value: `error (${msg})` });
446
662
  }
447
663
  }
448
664
  else if (alibabaCodingPlanAuth.state === "invalid") {
449
- lines.push(`- alibaba coding plan error: ${alibabaCodingPlanAuth.error}`);
665
+ cursorRows.push({ key: "alibaba coding plan error", value: alibabaCodingPlanAuth.error });
666
+ }
667
+ appendProviderCompactLiveProbeRows(cursorRows, "cursor", params.providerLiveProbes);
668
+ sections.push(createKvSection("cursor", "cursor:", cursorRows));
669
+ const qwenCodeLiveProbeSection = createCompactLiveProbeOnlySection({
670
+ id: "qwen_code",
671
+ title: "qwen_code:",
672
+ providerId: "qwen-code",
673
+ probes: params.providerLiveProbes,
674
+ });
675
+ if (qwenCodeLiveProbeSection) {
676
+ sections.push(qwenCodeLiveProbeSection);
677
+ }
678
+ const alibabaCodingPlanLiveProbeSection = createCompactLiveProbeOnlySection({
679
+ id: "alibaba_coding_plan",
680
+ title: "alibaba_coding_plan:",
681
+ providerId: "alibaba-coding-plan",
682
+ probes: params.providerLiveProbes,
683
+ });
684
+ if (alibabaCodingPlanLiveProbeSection) {
685
+ sections.push(alibabaCodingPlanLiveProbeSection);
450
686
  }
451
- lines.push("");
452
- lines.push("minimax:");
687
+ // === minimax ===
688
+ const minimaxRows = [];
453
689
  const minimaxAuth = await getMiniMaxAuthDiagnostics({
454
690
  maxAgeMs: DEFAULT_MINIMAX_AUTH_CACHE_MAX_AGE_MS,
455
691
  });
456
- lines.push(`- auth_state: ${minimaxAuth.state}`);
457
- lines.push(`- api_key_configured: ${minimaxAuth.state === "configured" ? "true" : "false"}`);
458
- lines.push(`- api_key_source: ${minimaxAuth.source ?? "(none)"}`);
459
- lines.push(`- api_key_checked_paths: ${joinOrNone(minimaxAuth.checkedPaths)}`);
460
- lines.push(`- api_key_auth_paths: ${joinOrNone(minimaxAuth.authPaths)}`);
692
+ minimaxRows.push({ key: "auth_state", value: minimaxAuth.state });
693
+ minimaxRows.push({
694
+ key: "api_key_configured",
695
+ value: minimaxAuth.state === "configured" ? "true" : "false",
696
+ });
697
+ minimaxRows.push({ key: "api_key_source", value: minimaxAuth.source ?? "(none)" });
698
+ minimaxRows.push({ key: "api_key_checked_paths", value: joinOrNone(minimaxAuth.checkedPaths) });
699
+ minimaxRows.push({ key: "api_key_auth_paths", value: joinOrNone(minimaxAuth.authPaths) });
461
700
  if (minimaxAuth.state === "invalid") {
462
- lines.push(`- auth_error: ${sanitizeDisplayText(minimaxAuth.error)}`);
701
+ minimaxRows.push({ key: "auth_error", value: sanitizeDisplayText(minimaxAuth.error) });
463
702
  }
464
703
  if (minimaxAuth.state === "configured") {
465
704
  const resolvedMiniMaxAuth = await resolveMiniMaxAuthCached({
466
705
  maxAgeMs: DEFAULT_MINIMAX_AUTH_CACHE_MAX_AGE_MS,
467
706
  });
468
707
  if (resolvedMiniMaxAuth.state !== "configured") {
469
- lines.push("- live_fetch_error: MiniMax API key became unavailable before fetch");
708
+ minimaxRows.push({
709
+ key: "live_fetch_error",
710
+ value: "MiniMax API key became unavailable before fetch",
711
+ });
470
712
  }
471
713
  else {
472
714
  const minimaxQuota = await queryMiniMaxQuota(resolvedMiniMaxAuth.apiKey);
473
715
  if (!minimaxQuota.success) {
474
- lines.push(`- live_fetch_error: ${minimaxQuota.error}`);
716
+ minimaxRows.push({ key: "live_fetch_error", value: minimaxQuota.error });
475
717
  }
476
718
  else {
477
719
  const fiveHourEntry = minimaxQuota.entries.find((entry) => entry.window === "five_hour");
478
720
  const weeklyEntry = minimaxQuota.entries.find((entry) => entry.window === "weekly");
479
721
  if (fiveHourEntry) {
480
- lines.push(`- five_hour_usage: ${fiveHourEntry.right ?? "(none)"} percent_remaining=${fiveHourEntry.percentRemaining} reset_at=${fiveHourEntry.resetTimeIso ?? "(none)"}`);
722
+ minimaxRows.push({
723
+ key: "five_hour_usage",
724
+ value: `${fiveHourEntry.right ?? "(none)"} percent_remaining=${fiveHourEntry.percentRemaining} reset_at=${fiveHourEntry.resetTimeIso ?? "(none)"}`,
725
+ });
481
726
  }
482
727
  if (weeklyEntry) {
483
- lines.push(`- weekly_usage: ${weeklyEntry.right ?? "(none)"} percent_remaining=${weeklyEntry.percentRemaining} reset_at=${weeklyEntry.resetTimeIso ?? "(none)"}`);
728
+ minimaxRows.push({
729
+ key: "weekly_usage",
730
+ value: `${weeklyEntry.right ?? "(none)"} percent_remaining=${weeklyEntry.percentRemaining} reset_at=${weeklyEntry.resetTimeIso ?? "(none)"}`,
731
+ });
484
732
  }
485
733
  if (!fiveHourEntry && !weeklyEntry) {
486
- lines.push("- live_state: no reportable MiniMax Coding Plan quota");
734
+ minimaxRows.push({ key: "live_state", value: "no reportable MiniMax Coding Plan quota" });
487
735
  }
488
736
  }
489
737
  }
490
738
  }
491
- lines.push("");
492
- lines.push("kimi:");
739
+ appendProviderCompactLiveProbeRows(minimaxRows, "minimax-coding-plan", params.providerLiveProbes);
740
+ sections.push(createKvSection("minimax", "minimax:", minimaxRows));
741
+ // === kimi ===
742
+ const kimiRows = [];
493
743
  const kimiAuth = await getKimiAuthDiagnostics({
494
744
  maxAgeMs: DEFAULT_KIMI_AUTH_CACHE_MAX_AGE_MS,
495
745
  });
496
- lines.push(`- auth_state: ${kimiAuth.state}`);
497
- lines.push(`- api_key_configured: ${kimiAuth.state === "configured" ? "true" : "false"}`);
498
- lines.push(`- api_key_source: ${kimiAuth.source ?? "(none)"}`);
499
- lines.push(`- api_key_checked_paths: ${joinOrNone(kimiAuth.checkedPaths)}`);
500
- lines.push(`- api_key_auth_paths: ${joinOrNone(kimiAuth.authPaths)}`);
746
+ kimiRows.push({ key: "auth_state", value: kimiAuth.state });
747
+ kimiRows.push({
748
+ key: "api_key_configured",
749
+ value: kimiAuth.state === "configured" ? "true" : "false",
750
+ });
751
+ kimiRows.push({ key: "api_key_source", value: kimiAuth.source ?? "(none)" });
752
+ kimiRows.push({ key: "api_key_checked_paths", value: joinOrNone(kimiAuth.checkedPaths) });
753
+ kimiRows.push({ key: "api_key_auth_paths", value: joinOrNone(kimiAuth.authPaths) });
501
754
  if (kimiAuth.state === "invalid") {
502
- lines.push(`- auth_error: ${sanitizeDisplayText(kimiAuth.error)}`);
755
+ kimiRows.push({ key: "auth_error", value: sanitizeDisplayText(kimiAuth.error) });
503
756
  }
504
757
  if (kimiAuth.state === "configured") {
505
758
  const kimiQuota = await queryKimiQuota();
506
759
  if (!kimiQuota) {
507
- lines.push("- live_fetch_error: Kimi API key became unavailable before fetch");
760
+ kimiRows.push({
761
+ key: "live_fetch_error",
762
+ value: "Kimi API key became unavailable before fetch",
763
+ });
508
764
  }
509
765
  else if (!kimiQuota.success) {
510
- lines.push(`- live_fetch_error: ${kimiQuota.error}`);
766
+ kimiRows.push({ key: "live_fetch_error", value: kimiQuota.error });
511
767
  }
512
768
  else {
513
769
  for (const window of kimiQuota.windows) {
514
- lines.push(`- ${window.label.toLowerCase().replace(/\s+/g, "_")}: used=${window.used}/${window.limit} percent_remaining=${window.percentRemaining} reset_at=${window.resetTimeIso ?? "(none)"}`);
770
+ kimiRows.push({
771
+ key: window.label.toLowerCase().replace(/\s+/g, "_"),
772
+ value: `used=${window.used}/${window.limit} percent_remaining=${window.percentRemaining} reset_at=${window.resetTimeIso ?? "(none)"}`,
773
+ });
515
774
  }
516
775
  if (kimiQuota.windows.length === 0) {
517
- lines.push("- live_state: no reportable Kimi quota");
776
+ kimiRows.push({ key: "live_state", value: "no reportable Kimi quota" });
518
777
  }
519
778
  }
520
779
  }
521
- lines.push("");
522
- lines.push("opencode_go:");
780
+ appendProviderCompactLiveProbeRows(kimiRows, "kimi-for-coding", params.providerLiveProbes);
781
+ sections.push(createKvSection("kimi", "kimi:", kimiRows));
782
+ // === opencode_go ===
783
+ const openCodeGoRows = [];
523
784
  const openCodeGoDiag = await getOpenCodeGoConfigDiagnostics();
524
- lines.push(`- config_state: ${openCodeGoDiag.state}`);
525
- lines.push(`- config_source: ${openCodeGoDiag.source ?? "(none)"}`);
785
+ openCodeGoRows.push({ key: "config_state", value: openCodeGoDiag.state });
786
+ openCodeGoRows.push({ key: "config_source", value: openCodeGoDiag.source ?? "(none)" });
526
787
  if (openCodeGoDiag.missing) {
527
- lines.push(`- config_missing: ${openCodeGoDiag.missing}`);
788
+ openCodeGoRows.push({ key: "config_missing", value: openCodeGoDiag.missing });
528
789
  }
529
790
  if (openCodeGoDiag.error) {
530
- lines.push(`- config_error: ${sanitizeDisplayText(openCodeGoDiag.error)}`);
791
+ openCodeGoRows.push({ key: "config_error", value: sanitizeDisplayText(openCodeGoDiag.error) });
531
792
  }
532
- lines.push(`- config_checked_paths: ${joinOrNone(openCodeGoDiag.checkedPaths)}`);
793
+ openCodeGoRows.push({ key: "config_checked_paths", value: joinOrNone(openCodeGoDiag.checkedPaths) });
533
794
  if (openCodeGoDiag.state === "configured") {
534
795
  const openCodeGoConfig = await resolveOpenCodeGoConfigCached({
535
796
  maxAgeMs: DEFAULT_OPENCODE_GO_CONFIG_CACHE_MAX_AGE_MS,
536
797
  });
537
798
  if (openCodeGoConfig.state !== "configured") {
538
- lines.push("- live_fetch_error: OpenCode Go config became unavailable before fetch");
799
+ openCodeGoRows.push({
800
+ key: "live_fetch_error",
801
+ value: "OpenCode Go config became unavailable before fetch",
802
+ });
539
803
  }
540
804
  else {
541
805
  const openCodeGoQuota = await queryOpenCodeGoQuota(openCodeGoConfig.config.workspaceId, openCodeGoConfig.config.authCookie);
542
806
  if (!openCodeGoQuota) {
543
- lines.push("- live_fetch_error: OpenCode Go returned null");
807
+ openCodeGoRows.push({ key: "live_fetch_error", value: "OpenCode Go returned null" });
544
808
  }
545
809
  else if (!openCodeGoQuota.success) {
546
- lines.push(`- live_fetch_error: ${openCodeGoQuota.error}`);
810
+ openCodeGoRows.push({ key: "live_fetch_error", value: openCodeGoQuota.error });
547
811
  }
548
812
  else {
549
- lines.push(`- monthly_usage: percent_used=${openCodeGoQuota.usagePercent} percent_remaining=${openCodeGoQuota.percentRemaining} reset_in_sec=${openCodeGoQuota.resetInSec} reset_at=${openCodeGoQuota.resetTimeIso}`);
813
+ openCodeGoRows.push({
814
+ key: "monthly_usage",
815
+ value: `percent_used=${openCodeGoQuota.usagePercent} percent_remaining=${openCodeGoQuota.percentRemaining} reset_in_sec=${openCodeGoQuota.resetInSec} reset_at=${openCodeGoQuota.resetTimeIso}`,
816
+ });
550
817
  }
551
818
  }
552
819
  }
553
- lines.push("");
554
- lines.push("zai:");
820
+ appendProviderCompactLiveProbeRows(openCodeGoRows, "opencode-go", params.providerLiveProbes);
821
+ sections.push(createKvSection("opencode_go", "opencode_go:", openCodeGoRows));
822
+ // === zai ===
823
+ const zaiRows = [];
555
824
  const zaiAuth = await getZaiAuthDiagnostics({
556
825
  maxAgeMs: DEFAULT_ZAI_AUTH_CACHE_MAX_AGE_MS,
557
826
  });
558
- lines.push(`- auth_state: ${zaiAuth.state}`);
559
- lines.push(`- api_key_configured: ${zaiAuth.state === "configured" ? "true" : "false"}`);
560
- lines.push(`- api_key_source: ${zaiAuth.source ?? "(none)"}`);
561
- lines.push(`- api_key_checked_paths: ${joinOrNone(zaiAuth.checkedPaths)}`);
562
- lines.push(`- api_key_auth_paths: ${joinOrNone(zaiAuth.authPaths)}`);
827
+ zaiRows.push({ key: "auth_state", value: zaiAuth.state });
828
+ zaiRows.push({
829
+ key: "api_key_configured",
830
+ value: zaiAuth.state === "configured" ? "true" : "false",
831
+ });
832
+ zaiRows.push({ key: "api_key_source", value: zaiAuth.source ?? "(none)" });
833
+ zaiRows.push({ key: "api_key_checked_paths", value: joinOrNone(zaiAuth.checkedPaths) });
834
+ zaiRows.push({ key: "api_key_auth_paths", value: joinOrNone(zaiAuth.authPaths) });
563
835
  if (zaiAuth.state === "invalid") {
564
- lines.push(`- auth_error: ${sanitizeDisplayText(zaiAuth.error)}`);
836
+ zaiRows.push({ key: "auth_error", value: sanitizeDisplayText(zaiAuth.error) });
565
837
  }
566
838
  if (zaiAuth.state === "configured") {
567
839
  const zaiQuota = await queryZaiQuota();
568
840
  if (!zaiQuota) {
569
- lines.push("- live_fetch_error: Z.ai API key became unavailable before fetch");
841
+ zaiRows.push({ key: "live_fetch_error", value: "Z.ai API key became unavailable before fetch" });
570
842
  }
571
843
  else if (!zaiQuota.success) {
572
- lines.push(`- live_fetch_error: ${zaiQuota.error}`);
844
+ zaiRows.push({ key: "live_fetch_error", value: zaiQuota.error });
573
845
  }
574
846
  else {
575
847
  if (zaiQuota.windows.fiveHour) {
576
- lines.push(`- five_hour_remaining: ${zaiQuota.windows.fiveHour.percentRemaining}% reset_at=${zaiQuota.windows.fiveHour.resetTimeIso ?? "(none)"}`);
848
+ zaiRows.push({
849
+ key: "five_hour_remaining",
850
+ value: `${zaiQuota.windows.fiveHour.percentRemaining}% reset_at=${zaiQuota.windows.fiveHour.resetTimeIso ?? "(none)"}`,
851
+ });
577
852
  }
578
853
  if (zaiQuota.windows.weekly) {
579
- lines.push(`- weekly_remaining: ${zaiQuota.windows.weekly.percentRemaining}% reset_at=${zaiQuota.windows.weekly.resetTimeIso ?? "(none)"}`);
854
+ zaiRows.push({
855
+ key: "weekly_remaining",
856
+ value: `${zaiQuota.windows.weekly.percentRemaining}% reset_at=${zaiQuota.windows.weekly.resetTimeIso ?? "(none)"}`,
857
+ });
580
858
  }
581
859
  if (zaiQuota.windows.mcp) {
582
- lines.push(`- mcp_remaining: ${zaiQuota.windows.mcp.percentRemaining}% reset_at=${zaiQuota.windows.mcp.resetTimeIso ?? "(none)"}`);
860
+ zaiRows.push({
861
+ key: "mcp_remaining",
862
+ value: `${zaiQuota.windows.mcp.percentRemaining}% reset_at=${zaiQuota.windows.mcp.resetTimeIso ?? "(none)"}`,
863
+ });
583
864
  }
584
865
  if (!zaiQuota.windows.fiveHour && !zaiQuota.windows.weekly && !zaiQuota.windows.mcp) {
585
- lines.push("- live_state: no reportable Z.ai quota windows");
866
+ zaiRows.push({ key: "live_state", value: "no reportable Z.ai quota windows" });
586
867
  }
587
868
  }
588
869
  }
870
+ appendProviderCompactLiveProbeRows(zaiRows, "zai", params.providerLiveProbes);
871
+ sections.push(createKvSection("zai", "zai:", zaiRows));
872
+ // === simple API key sections ===
589
873
  const syntheticDiag = await readBasicApiKeyDiagnostics(getSyntheticKeyDiagnostics);
590
- appendBasicApiKeySection({
591
- lines,
592
- section: "synthetic:",
593
- label: "synthetic api key",
594
- diagnostics: syntheticDiag,
595
- });
874
+ const syntheticRows = [
875
+ {
876
+ key: "synthetic api key",
877
+ value: formatInlineApiKeyDiagnosticsValue(syntheticDiag),
878
+ },
879
+ ];
880
+ appendProviderCompactLiveProbeRows(syntheticRows, "synthetic", params.providerLiveProbes);
881
+ sections.push(createKvSection("synthetic", "synthetic:", syntheticRows));
596
882
  const chutesDiag = await readBasicApiKeyDiagnostics(getChutesKeyDiagnostics);
597
- appendBasicApiKeySection({
598
- lines,
599
- section: "chutes:",
600
- label: "chutes api key",
601
- diagnostics: chutesDiag,
602
- });
883
+ const chutesRows = [
884
+ {
885
+ key: "chutes api key",
886
+ value: formatInlineApiKeyDiagnosticsValue(chutesDiag),
887
+ },
888
+ ];
889
+ appendProviderCompactLiveProbeRows(chutesRows, "chutes", params.providerLiveProbes);
890
+ sections.push(createKvSection("chutes", "chutes:", chutesRows));
891
+ // === nanogpt ===
603
892
  const nanoGptDiag = await readNanoGptApiKeyDiagnostics(getNanoGptKeyDiagnostics);
604
- appendNanoGptApiKeySection(lines, nanoGptDiag);
893
+ const nanoGptRows = [
894
+ { key: "api_key_configured", value: nanoGptDiag.configured ? "true" : "false" },
895
+ { key: "api_key_source", value: nanoGptDiag.source ?? "(none)" },
896
+ { key: "api_key_checked_paths", value: joinOrNone(nanoGptDiag.checkedPaths) },
897
+ { key: "api_key_auth_paths", value: joinOrNone(nanoGptDiag.authPaths) },
898
+ ];
605
899
  if (nanoGptDiag.configured) {
606
900
  try {
607
901
  const nanoGptQuota = await queryNanoGptQuota();
608
902
  if (!nanoGptQuota) {
609
- lines.push("- live_fetch_error: NanoGPT API key became unavailable before fetch");
903
+ nanoGptRows.push({
904
+ key: "live_fetch_error",
905
+ value: "NanoGPT API key became unavailable before fetch",
906
+ });
610
907
  }
611
908
  else if (!nanoGptQuota.success) {
612
- lines.push(`- live_fetch_error: ${nanoGptQuota.error}`);
909
+ nanoGptRows.push({ key: "live_fetch_error", value: nanoGptQuota.error });
613
910
  }
614
911
  else {
615
912
  if (nanoGptQuota.subscription) {
616
- lines.push(`- subscription_active: ${nanoGptQuota.subscription.active ? "true" : "false"}`);
617
- lines.push(`- subscription_state: ${nanoGptQuota.subscription.state}`);
618
- lines.push(`- enforce_daily_limit: ${nanoGptQuota.subscription.enforceDailyLimit ? "true" : "false"}`);
913
+ nanoGptRows.push({
914
+ key: "subscription_active",
915
+ value: nanoGptQuota.subscription.active ? "true" : "false",
916
+ });
917
+ nanoGptRows.push({ key: "subscription_state", value: nanoGptQuota.subscription.state });
918
+ nanoGptRows.push({
919
+ key: "enforce_daily_limit",
920
+ value: nanoGptQuota.subscription.enforceDailyLimit ? "true" : "false",
921
+ });
619
922
  if (nanoGptQuota.subscription.daily) {
620
923
  const daily = nanoGptQuota.subscription.daily;
621
- lines.push(`- daily_usage: ${fmtNanoGptMetric(daily.used)}/${fmtNanoGptMetric(daily.limit)} remaining=${fmtNanoGptMetric(daily.remaining)} percent_remaining=${daily.percentRemaining} reset_at=${daily.resetTimeIso ?? "(none)"}`);
924
+ nanoGptRows.push({
925
+ key: "daily_usage",
926
+ value: `${fmtNanoGptMetric(daily.used)}/${fmtNanoGptMetric(daily.limit)} remaining=${fmtNanoGptMetric(daily.remaining)} percent_remaining=${daily.percentRemaining} reset_at=${daily.resetTimeIso ?? "(none)"}`,
927
+ });
622
928
  }
623
929
  if (nanoGptQuota.subscription.monthly) {
624
930
  const monthly = nanoGptQuota.subscription.monthly;
625
- lines.push(`- monthly_usage: ${fmtNanoGptMetric(monthly.used)}/${fmtNanoGptMetric(monthly.limit)} remaining=${fmtNanoGptMetric(monthly.remaining)} percent_remaining=${monthly.percentRemaining} reset_at=${monthly.resetTimeIso ?? "(none)"}`);
931
+ nanoGptRows.push({
932
+ key: "monthly_usage",
933
+ value: `${fmtNanoGptMetric(monthly.used)}/${fmtNanoGptMetric(monthly.limit)} remaining=${fmtNanoGptMetric(monthly.remaining)} percent_remaining=${monthly.percentRemaining} reset_at=${monthly.resetTimeIso ?? "(none)"}`,
934
+ });
626
935
  }
627
- lines.push(`- billing_period_end: ${nanoGptQuota.subscription.currentPeriodEndIso ?? "(none)"}`);
936
+ nanoGptRows.push({
937
+ key: "billing_period_end",
938
+ value: nanoGptQuota.subscription.currentPeriodEndIso ?? "(none)",
939
+ });
628
940
  if (nanoGptQuota.subscription.graceUntilIso) {
629
- lines.push(`- grace_until: ${nanoGptQuota.subscription.graceUntilIso}`);
941
+ nanoGptRows.push({ key: "grace_until", value: nanoGptQuota.subscription.graceUntilIso });
630
942
  }
631
943
  }
632
- lines.push(`- balance_usd: ${typeof nanoGptQuota.balance?.usdBalance === "number" ? fmtUsdAmount(nanoGptQuota.balance.usdBalance) : "(none)"}`);
633
- lines.push(`- balance_nano: ${nanoGptQuota.balance?.nanoBalanceRaw ?? "(none)"}`);
944
+ nanoGptRows.push({
945
+ key: "balance_usd",
946
+ value: typeof nanoGptQuota.balance?.usdBalance === "number"
947
+ ? fmtUsdAmount(nanoGptQuota.balance.usdBalance)
948
+ : "(none)",
949
+ });
950
+ nanoGptRows.push({ key: "balance_nano", value: nanoGptQuota.balance?.nanoBalanceRaw ?? "(none)" });
634
951
  for (const entry of nanoGptQuota.endpointErrors ?? []) {
635
- lines.push(`- live_error_${entry.endpoint}: ${entry.message}`);
952
+ nanoGptRows.push({ key: `live_error_${entry.endpoint}`, value: entry.message });
636
953
  }
637
954
  }
638
955
  }
639
956
  catch (err) {
640
957
  const msg = err instanceof Error ? err.message : String(err);
641
- lines.push(`- live_fetch_error: ${msg}`);
958
+ nanoGptRows.push({ key: "live_fetch_error", value: msg });
642
959
  }
643
960
  }
961
+ appendProviderCompactLiveProbeRows(nanoGptRows, "nanogpt", params.providerLiveProbes);
962
+ sections.push(createKvSection("nanogpt", "nanogpt:", nanoGptRows));
963
+ // === copilot auth ===
644
964
  const copilotDiag = getCopilotQuotaAuthDiagnostics(authData);
645
- lines.push("");
646
- lines.push("copilot_quota_auth:");
647
- lines.push(`- pat_state: ${copilotDiag.pat.state}`);
965
+ const copilotRows = [{ key: "pat_state", value: copilotDiag.pat.state }];
648
966
  if (copilotDiag.pat.selectedPath) {
649
- lines.push(`- pat_path: ${copilotDiag.pat.selectedPath}`);
967
+ copilotRows.push({ key: "pat_path", value: copilotDiag.pat.selectedPath });
650
968
  }
651
969
  if (copilotDiag.pat.tokenKind) {
652
- lines.push(`- pat_token_kind: ${copilotDiag.pat.tokenKind}`);
970
+ copilotRows.push({ key: "pat_token_kind", value: copilotDiag.pat.tokenKind });
653
971
  }
654
972
  if (copilotDiag.pat.config?.tier) {
655
- lines.push(`- pat_tier: ${copilotDiag.pat.config.tier}`);
973
+ copilotRows.push({ key: "pat_tier", value: copilotDiag.pat.config.tier });
656
974
  }
657
975
  if (copilotDiag.pat.config?.organization) {
658
- lines.push(`- pat_organization: ${copilotDiag.pat.config.organization}`);
976
+ copilotRows.push({ key: "pat_organization", value: copilotDiag.pat.config.organization });
659
977
  }
660
978
  if (copilotDiag.pat.config?.enterprise) {
661
- lines.push(`- pat_enterprise: ${copilotDiag.pat.config.enterprise}`);
662
- }
663
- lines.push(`- billing_mode: ${copilotDiag.billingMode}`);
664
- lines.push(`- billing_scope: ${copilotDiag.billingScope}`);
665
- lines.push(`- quota_api: ${copilotDiag.quotaApi}`);
666
- lines.push(`- billing_api_access_likely: ${copilotDiag.billingApiAccessLikely ? "true" : "false"}`);
667
- lines.push(`- remaining_totals_state: ${copilotDiag.remainingTotalsState}`);
979
+ copilotRows.push({ key: "pat_enterprise", value: copilotDiag.pat.config.enterprise });
980
+ }
981
+ copilotRows.push({ key: "billing_mode", value: copilotDiag.billingMode });
982
+ copilotRows.push({ key: "billing_scope", value: copilotDiag.billingScope });
983
+ copilotRows.push({ key: "quota_api", value: copilotDiag.quotaApi });
984
+ copilotRows.push({
985
+ key: "billing_api_access_likely",
986
+ value: copilotDiag.billingApiAccessLikely ? "true" : "false",
987
+ });
988
+ copilotRows.push({ key: "remaining_totals_state", value: copilotDiag.remainingTotalsState });
668
989
  if (copilotDiag.queryPeriod) {
669
- lines.push(`- billing_period: ${copilotDiag.queryPeriod.year}-${String(copilotDiag.queryPeriod.month).padStart(2, "0")}`);
990
+ copilotRows.push({
991
+ key: "billing_period",
992
+ value: `${copilotDiag.queryPeriod.year}-${String(copilotDiag.queryPeriod.month).padStart(2, "0")}`,
993
+ });
670
994
  }
671
995
  if (copilotDiag.usernameFilter) {
672
- lines.push(`- username_filter: ${copilotDiag.usernameFilter}`);
996
+ copilotRows.push({ key: "username_filter", value: copilotDiag.usernameFilter });
673
997
  }
674
998
  if (copilotDiag.billingMode === "organization_usage") {
675
- lines.push("- billing_usage_note: organization premium usage for the current billing period");
676
- lines.push("- remaining_quota_note: valid PAT access can query billing usage, but pooled org usage does not provide a true per-user remaining quota");
999
+ copilotRows.push({
1000
+ key: "billing_usage_note",
1001
+ value: "organization premium usage for the current billing period",
1002
+ });
1003
+ copilotRows.push({
1004
+ key: "remaining_quota_note",
1005
+ value: "valid PAT access can query billing usage, but pooled org usage does not provide a true per-user remaining quota",
1006
+ });
677
1007
  }
678
1008
  if (copilotDiag.billingMode === "enterprise_usage") {
679
- lines.push("- billing_usage_note: enterprise premium usage for the current billing period");
680
- lines.push("- remaining_quota_note: valid enterprise billing access can query pooled enterprise usage, but it does not provide a true per-user remaining quota");
1009
+ copilotRows.push({
1010
+ key: "billing_usage_note",
1011
+ value: "enterprise premium usage for the current billing period",
1012
+ });
1013
+ copilotRows.push({
1014
+ key: "remaining_quota_note",
1015
+ value: "valid enterprise billing access can query pooled enterprise usage, but it does not provide a true per-user remaining quota",
1016
+ });
681
1017
  }
682
1018
  if (copilotDiag.billingTargetError) {
683
- lines.push(`- billing_target_error: ${copilotDiag.billingTargetError}`);
1019
+ copilotRows.push({ key: "billing_target_error", value: copilotDiag.billingTargetError });
684
1020
  }
685
1021
  if (copilotDiag.tokenCompatibilityError) {
686
- lines.push(`- token_compatibility_error: ${copilotDiag.tokenCompatibilityError}`);
1022
+ copilotRows.push({ key: "token_compatibility_error", value: copilotDiag.tokenCompatibilityError });
687
1023
  }
688
1024
  if (copilotDiag.pat.error) {
689
- lines.push(`- pat_error: ${copilotDiag.pat.error}`);
1025
+ copilotRows.push({ key: "pat_error", value: copilotDiag.pat.error });
690
1026
  }
691
- lines.push(`- pat_checked_paths: ${copilotDiag.pat.checkedPaths.length ? copilotDiag.pat.checkedPaths.join(" | ") : "(none)"}`);
692
- lines.push(`- oauth_configured: ${copilotDiag.oauth.configured ? "true" : "false"} key=${copilotDiag.oauth.keyName ?? "(none)"} refresh=${copilotDiag.oauth.hasRefreshToken ? "true" : "false"} access=${copilotDiag.oauth.hasAccessToken ? "true" : "false"}`);
693
- lines.push(`- effective_source: ${copilotDiag.effectiveSource}`);
694
- lines.push(`- override: ${copilotDiag.override}`);
1027
+ copilotRows.push({
1028
+ key: "pat_checked_paths",
1029
+ value: copilotDiag.pat.checkedPaths.length ? copilotDiag.pat.checkedPaths.join(" | ") : "(none)",
1030
+ });
1031
+ copilotRows.push({
1032
+ key: "oauth_configured",
1033
+ value: `${copilotDiag.oauth.configured ? "true" : "false"} key=${copilotDiag.oauth.keyName ?? "(none)"} refresh=${copilotDiag.oauth.hasRefreshToken ? "true" : "false"} access=${copilotDiag.oauth.hasAccessToken ? "true" : "false"}`,
1034
+ });
1035
+ copilotRows.push({ key: "effective_source", value: copilotDiag.effectiveSource });
1036
+ copilotRows.push({ key: "override", value: copilotDiag.override });
1037
+ appendProviderCompactLiveProbeRows(copilotRows, "copilot", params.providerLiveProbes);
1038
+ sections.push(createKvSection("copilot_quota_auth", "copilot_quota_auth:", copilotRows));
1039
+ // === google antigravity + db path ===
695
1040
  const googleTokenCachePath = getGoogleTokenCachePath();
696
1041
  const googleAuthPresence = await inspectAntigravityAccountsPresence();
697
1042
  const googleCompanionPresence = await inspectAntigravityCompanionPresence();
698
- lines.push("");
699
- lines.push("google_antigravity:");
700
- lines.push(`- auth_state: ${googleAuthPresence.state}`);
701
- lines.push(`- selected_accounts_path: ${googleAuthPresence.selectedPath ?? "(none)"}`);
702
- lines.push(`- present_accounts_paths: ${joinOrNone(googleAuthPresence.presentPaths)}`);
703
- lines.push(`- candidate_accounts_paths: ${joinOrNone(googleAuthPresence.candidatePaths)}`);
704
- lines.push(`- account_count: ${googleAuthPresence.accountCount}`);
705
- lines.push(`- valid_account_count: ${googleAuthPresence.validAccountCount}`);
706
- lines.push(`- companion_package_state: ${googleCompanionPresence.state}`);
707
- lines.push(`- companion_package_path: ${googleCompanionPresence.state === "present" || googleCompanionPresence.state === "invalid" ? googleCompanionPresence.resolvedPath ?? "(none)" : "(none)"}`);
708
- if (googleCompanionPresence.state !== "present") {
709
- lines.push(`- companion_error: ${sanitizeDisplayText(googleCompanionPresence.error)}`);
710
- }
711
- lines.push(`- token_cache_path: ${googleTokenCachePath} exists=${(await pathExists(googleTokenCachePath)) ? "true" : "false"}`);
712
- if (googleAuthPresence.state === "invalid" && googleAuthPresence.error) {
713
- lines.push(`- auth_error: ${sanitizeDisplayText(googleAuthPresence.error)}`);
714
- }
715
1043
  const dbCandidates = getOpenCodeDbPathCandidates();
716
1044
  const dbSelected = getOpenCodeDbPath();
717
1045
  const dbPresent = [];
@@ -719,41 +1047,76 @@ export async function buildQuotaStatusReport(params) {
719
1047
  if (await pathExists(p))
720
1048
  dbPresent.push(p);
721
1049
  }));
722
- lines.push(`- opencode db: preferred=${dbSelected} present=${joinOrNone(dbPresent)} candidates=${joinOrNone(dbCandidates)}`);
1050
+ const googleRows = [
1051
+ { key: "auth_state", value: googleAuthPresence.state },
1052
+ { key: "selected_accounts_path", value: googleAuthPresence.selectedPath ?? "(none)" },
1053
+ { key: "present_accounts_paths", value: joinOrNone(googleAuthPresence.presentPaths) },
1054
+ { key: "candidate_accounts_paths", value: joinOrNone(googleAuthPresence.candidatePaths) },
1055
+ { key: "account_count", value: String(googleAuthPresence.accountCount) },
1056
+ { key: "valid_account_count", value: String(googleAuthPresence.validAccountCount) },
1057
+ { key: "companion_package_state", value: googleCompanionPresence.state },
1058
+ {
1059
+ key: "companion_package_path",
1060
+ value: googleCompanionPresence.state === "present" || googleCompanionPresence.state === "invalid"
1061
+ ? googleCompanionPresence.resolvedPath ?? "(none)"
1062
+ : "(none)",
1063
+ },
1064
+ ];
1065
+ if (googleCompanionPresence.state !== "present") {
1066
+ googleRows.push({
1067
+ key: "companion_error",
1068
+ value: sanitizeDisplayText(googleCompanionPresence.error),
1069
+ });
1070
+ }
1071
+ googleRows.push({
1072
+ key: "token_cache_path",
1073
+ value: `${googleTokenCachePath} exists=${(await pathExists(googleTokenCachePath)) ? "true" : "false"}`,
1074
+ });
1075
+ if (googleAuthPresence.state === "invalid" && googleAuthPresence.error) {
1076
+ googleRows.push({ key: "auth_error", value: sanitizeDisplayText(googleAuthPresence.error) });
1077
+ }
1078
+ googleRows.push({
1079
+ key: "opencode db",
1080
+ value: `preferred=${dbSelected} present=${joinOrNone(dbPresent)} candidates=${joinOrNone(dbCandidates)}`,
1081
+ });
1082
+ appendProviderCompactLiveProbeRows(googleRows, "google-antigravity", params.providerLiveProbes);
1083
+ sections.push(createKvSection("google_antigravity", "google_antigravity:", googleRows));
723
1084
  if (params.googleRefresh?.attempted) {
724
- lines.push("");
725
- lines.push("google_token_refresh:");
1085
+ const googleRefreshRows = [];
726
1086
  if (typeof params.googleRefresh.total === "number" &&
727
1087
  typeof params.googleRefresh.successCount === "number") {
728
- lines.push(`- refreshed: ${params.googleRefresh.successCount}/${params.googleRefresh.total}`);
1088
+ googleRefreshRows.push({
1089
+ key: "refreshed",
1090
+ value: `${params.googleRefresh.successCount}/${params.googleRefresh.total}`,
1091
+ });
729
1092
  }
730
1093
  else {
731
- lines.push("- attempted");
1094
+ googleRefreshRows.push({ key: "attempted" });
732
1095
  }
733
1096
  for (const f of params.googleRefresh.failures ?? []) {
734
- lines.push(`- ${f.email ?? "Unknown"}: ${f.error}`);
1097
+ googleRefreshRows.push({ key: f.email ?? "Unknown", value: f.error });
735
1098
  }
1099
+ sections.push(createKvSection("google_token_refresh", "google_token_refresh:", googleRefreshRows));
736
1100
  }
737
1101
  // === session token errors ===
738
1102
  if (params.sessionTokenError) {
739
- lines.push("");
740
- lines.push("session_tokens_error:");
741
- lines.push(`- session_id: ${params.sessionTokenError.sessionID}`);
742
- lines.push(`- error: ${params.sessionTokenError.error}`);
1103
+ const sessionTokenErrorRows = [
1104
+ { key: "session_id", value: params.sessionTokenError.sessionID },
1105
+ { key: "error", value: params.sessionTokenError.error },
1106
+ ];
743
1107
  if (params.sessionTokenError.checkedPath) {
744
- lines.push(`- checked_path: ${params.sessionTokenError.checkedPath}`);
1108
+ sessionTokenErrorRows.push({ key: "checked_path", value: params.sessionTokenError.checkedPath });
745
1109
  }
1110
+ sections.push(createKvSection("session_tokens_error", "session_tokens_error:", sessionTokenErrorRows));
746
1111
  }
747
1112
  // === storage scan ===
748
1113
  const dbStats = await getOpenCodeDbStats();
749
- lines.push("");
750
- lines.push("storage:");
751
- lines.push(`- sessions_in_db: ${fmtInt(dbStats.sessionCount)}`);
752
- lines.push(`- messages_in_db: ${fmtInt(dbStats.messageCount)}`);
753
- lines.push(`- assistant_messages_in_db: ${fmtInt(dbStats.assistantMessageCount)}`);
1114
+ sections.push(createKvSection("storage", "storage:", [
1115
+ { key: "sessions_in_db", value: fmtInt(dbStats.sessionCount) },
1116
+ { key: "messages_in_db", value: fmtInt(dbStats.messageCount) },
1117
+ { key: "assistant_messages_in_db", value: fmtInt(dbStats.assistantMessageCount) },
1118
+ ]));
754
1119
  // === pricing snapshot ===
755
- // We intentionally compute all-time usage once so that pricing coverage and unknown_pricing
756
- // are consistent and do not require multiple storage scans.
757
1120
  const agg = await aggregateUsage({});
758
1121
  const meta = getPricingSnapshotMeta();
759
1122
  const providers = listProviders();
@@ -767,73 +1130,113 @@ export async function buildQuotaStatusReport(params) {
767
1130
  const runtimeSnapshotPath = getRuntimePricingSnapshotPath();
768
1131
  const refreshStatePath = getRuntimePricingRefreshStatePath();
769
1132
  const pricingRefreshState = await readPricingRefreshState();
770
- lines.push("");
771
- lines.push("pricing_snapshot:");
772
- lines.push(`- pricing: source=${meta.source} active_source=${snapshotSource} generated_at=${new Date(meta.generatedAt).toISOString()} units=${meta.units}`);
773
- lines.push(`- selection: configured=${params.pricingSnapshotSource} active=${snapshotSource}`);
1133
+ const pricingRows = [
1134
+ {
1135
+ key: "pricing",
1136
+ value: `source=${meta.source} active_source=${snapshotSource} generated_at=${new Date(meta.generatedAt).toISOString()} units=${meta.units}`,
1137
+ },
1138
+ {
1139
+ key: "selection",
1140
+ value: `configured=${params.pricingSnapshotSource} active=${snapshotSource}`,
1141
+ },
1142
+ ];
774
1143
  if (params.pricingSnapshotSource === "bundled") {
775
- lines.push("- selection_note: bundled config pins the packaged snapshot and ignores runtime refresh for active pricing");
1144
+ pricingRows.push({
1145
+ key: "selection_note",
1146
+ value: "bundled config pins the packaged snapshot and ignores runtime refresh for active pricing",
1147
+ });
776
1148
  }
777
1149
  else if (params.pricingSnapshotSource === "runtime" && snapshotSource !== "runtime") {
778
- lines.push("- selection_note: runtime config requested the local runtime snapshot, but bundled fallback is active because no valid runtime snapshot is available");
1150
+ pricingRows.push({
1151
+ key: "selection_note",
1152
+ value: "runtime config requested the local runtime snapshot, but bundled fallback is active because no valid runtime snapshot is available",
1153
+ });
779
1154
  }
780
- lines.push(`- runtime_paths: snapshot=${runtimeSnapshotPath} refresh_state=${refreshStatePath}`);
781
- lines.push(`- staleness: age_ms=${fmtInt(health.ageMs)} max_age_ms=${fmtInt(health.maxAgeMs)} stale=${health.stale ? "true" : "false"}`);
782
- lines.push(`- refresh_policy: auto_refresh_days=${fmtInt(autoRefreshDays)}`);
1155
+ pricingRows.push({
1156
+ key: "runtime_paths",
1157
+ value: `snapshot=${runtimeSnapshotPath} refresh_state=${refreshStatePath}`,
1158
+ });
1159
+ pricingRows.push({
1160
+ key: "staleness",
1161
+ value: `age_ms=${fmtInt(health.ageMs)} max_age_ms=${fmtInt(health.maxAgeMs)} stale=${health.stale ? "true" : "false"}`,
1162
+ });
1163
+ pricingRows.push({
1164
+ key: "refresh_policy",
1165
+ value: `auto_refresh_days=${fmtInt(autoRefreshDays)}`,
1166
+ });
783
1167
  if (pricingRefreshState) {
784
- lines.push(`- refresh: last_attempt_at=${pricingRefreshState.lastAttemptAt ? new Date(pricingRefreshState.lastAttemptAt).toISOString() : "(none)"} last_success_at=${pricingRefreshState.lastSuccessAt ? new Date(pricingRefreshState.lastSuccessAt).toISOString() : "(none)"} last_failure_at=${pricingRefreshState.lastFailureAt ? new Date(pricingRefreshState.lastFailureAt).toISOString() : "(none)"} last_result=${pricingRefreshState.lastResult ?? "(none)"}`);
1168
+ pricingRows.push({
1169
+ key: "refresh",
1170
+ value: `last_attempt_at=${pricingRefreshState.lastAttemptAt ? new Date(pricingRefreshState.lastAttemptAt).toISOString() : "(none)"} last_success_at=${pricingRefreshState.lastSuccessAt ? new Date(pricingRefreshState.lastSuccessAt).toISOString() : "(none)"} last_failure_at=${pricingRefreshState.lastFailureAt ? new Date(pricingRefreshState.lastFailureAt).toISOString() : "(none)"} last_result=${pricingRefreshState.lastResult ?? "(none)"}`,
1171
+ });
785
1172
  if (pricingRefreshState.lastError) {
786
- lines.push(`- refresh_error: ${pricingRefreshState.lastError}`);
1173
+ pricingRows.push({ key: "refresh_error", value: pricingRefreshState.lastError });
787
1174
  }
788
1175
  }
789
1176
  else {
790
- lines.push("- refresh: (no runtime refresh state yet)");
1177
+ pricingRows.push({ key: "refresh", value: "(no runtime refresh state yet)" });
791
1178
  }
792
- lines.push(`- providers: ${providers.join(",")}`);
793
- lines.push(`- coverage_seen: priced_keys=${fmtInt(coverage.totals.pricedKeysSeen)} mapped_but_missing=${fmtInt(coverage.totals.mappedMissingKeysSeen)} unpriced_keys=${fmtInt(coverage.totals.unpricedKeysSeen)}`);
1179
+ pricingRows.push({ key: "providers", value: providers.join(",") });
1180
+ pricingRows.push({
1181
+ key: "coverage_seen",
1182
+ value: `priced_keys=${fmtInt(coverage.totals.pricedKeysSeen)} mapped_but_missing=${fmtInt(coverage.totals.mappedMissingKeysSeen)} unpriced_keys=${fmtInt(coverage.totals.unpricedKeysSeen)}`,
1183
+ });
794
1184
  for (const p of providers) {
795
1185
  const c = coverage.byProvider.get(p) ?? {
796
1186
  pricedKeysSeen: 0,
797
1187
  mappedMissingKeysSeen: 0,
798
1188
  unpricedKeysSeen: 0,
799
1189
  };
800
- lines.push(` - ${p}: models=${fmtInt(getProviderModelCount(p))} priced_models_seen=${fmtInt(c.pricedKeysSeen)} mapped_but_missing_models_seen=${fmtInt(c.mappedMissingKeysSeen)} unpriced_models_seen=${fmtInt(c.unpricedKeysSeen)}`);
1190
+ pricingRows.push({
1191
+ key: p,
1192
+ value: `models=${fmtInt(getProviderModelCount(p))} priced_models_seen=${fmtInt(c.pricedKeysSeen)} mapped_but_missing_models_seen=${fmtInt(c.mappedMissingKeysSeen)} unpriced_models_seen=${fmtInt(c.unpricedKeysSeen)}`,
1193
+ indent: 1,
1194
+ });
801
1195
  }
1196
+ sections.push(createKvSection("pricing_snapshot", "pricing_snapshot:", pricingRows));
802
1197
  // === supported providers pricing ===
803
1198
  const supported = getProviders().map((p) => p.id);
804
- lines.push("");
805
- lines.push("supported_providers_pricing:");
806
- for (const id of supported) {
1199
+ const supportedRows = supported.map((id) => {
807
1200
  const row = supportedProviderPricingRow({ id, agg, snapshotProviders: providers });
808
- lines.push(`- ${row.id}: pricing=${row.pricing} (${row.notes})`);
809
- }
1201
+ return {
1202
+ key: row.id,
1203
+ value: `pricing=${row.pricing} (${row.notes})`,
1204
+ };
1205
+ });
1206
+ sections.push(createKvSection("supported_providers_pricing", "supported_providers_pricing:", supportedRows));
810
1207
  // === unpriced models ===
811
- // Mapped keys that are deterministically not token-priced by our snapshot.
812
- lines.push("");
813
- lines.push("unpriced_models:");
1208
+ const unpricedRows = [];
814
1209
  if (agg.unpriced.length === 0) {
815
- lines.push("- none");
1210
+ unpricedRows.push({ key: "none" });
816
1211
  }
817
1212
  else {
818
- lines.push(`- keys: ${fmtInt(agg.unpriced.length)} tokens_total=${fmtInt(totalTokenBuckets(agg.totals.unpriced))}`);
1213
+ unpricedRows.push({
1214
+ key: "keys",
1215
+ value: `${fmtInt(agg.unpriced.length)} tokens_total=${fmtInt(totalTokenBuckets(agg.totals.unpriced))}`,
1216
+ });
819
1217
  for (const row of agg.unpriced.slice(0, STATUS_SAMPLE_LIMIT)) {
820
1218
  const src = `${row.key.sourceProviderID}/${row.key.sourceModelID}`;
821
1219
  const mapped = `${row.key.mappedProvider}/${row.key.mappedModel}`;
822
- lines.push(`- ${src} mapped=${mapped} tokens=${fmtInt(totalTokenBuckets(row.tokens))} msgs=${fmtInt(row.messageCount)} reason=${row.key.reason}`);
1220
+ unpricedRows.push({
1221
+ key: src,
1222
+ value: `mapped=${mapped} tokens=${fmtInt(totalTokenBuckets(row.tokens))} msgs=${fmtInt(row.messageCount)} reason=${row.key.reason}`,
1223
+ });
823
1224
  }
824
1225
  if (agg.unpriced.length > STATUS_SAMPLE_LIMIT) {
825
- lines.push(`- ... (${fmtInt(agg.unpriced.length - STATUS_SAMPLE_LIMIT)} more)`);
1226
+ unpricedRows.push({ key: `... (${fmtInt(agg.unpriced.length - STATUS_SAMPLE_LIMIT)} more)` });
826
1227
  }
827
1228
  }
1229
+ sections.push(createKvSection("unpriced_models", "unpriced_models:", unpricedRows));
828
1230
  // === unknown pricing ===
829
- // We intentionally report unknowns for *all time* so users can see what needs mapping.
830
- lines.push("");
831
- lines.push("unknown_pricing:");
1231
+ const unknownRows = [];
832
1232
  if (agg.unknown.length === 0) {
833
- lines.push("- none");
1233
+ unknownRows.push({ key: "none" });
834
1234
  }
835
1235
  else {
836
- lines.push(`- keys: ${fmtInt(agg.unknown.length)} tokens_total=${fmtInt(totalTokenBuckets(agg.totals.unknown))}`);
1236
+ unknownRows.push({
1237
+ key: "keys",
1238
+ value: `${fmtInt(agg.unknown.length)} tokens_total=${fmtInt(totalTokenBuckets(agg.totals.unknown))}`,
1239
+ });
837
1240
  for (const row of agg.unknown.slice(0, STATUS_SAMPLE_LIMIT)) {
838
1241
  const src = `${row.key.sourceProviderID}/${row.key.sourceModelID}`;
839
1242
  const mappedBase = row.key.mappedProvider && row.key.mappedModel
@@ -842,12 +1245,22 @@ export async function buildQuotaStatusReport(params) {
842
1245
  const candidates = row.key.providerCandidates && row.key.providerCandidates.length > 0
843
1246
  ? ` candidates=${row.key.providerCandidates.join(",")}`
844
1247
  : "";
845
- lines.push(`- ${src} mapped=${mappedBase}${candidates} tokens=${fmtInt(totalTokenBuckets(row.tokens))} msgs=${fmtInt(row.messageCount)}`);
1248
+ unknownRows.push({
1249
+ key: src,
1250
+ value: `mapped=${mappedBase}${candidates} tokens=${fmtInt(totalTokenBuckets(row.tokens))} msgs=${fmtInt(row.messageCount)}`,
1251
+ });
846
1252
  }
847
1253
  if (agg.unknown.length > STATUS_SAMPLE_LIMIT) {
848
- lines.push(`- ... (${fmtInt(agg.unknown.length - STATUS_SAMPLE_LIMIT)} more)`);
1254
+ unknownRows.push({ key: `... (${fmtInt(agg.unknown.length - STATUS_SAMPLE_LIMIT)} more)` });
849
1255
  }
850
1256
  }
851
- return lines.join("\n");
1257
+ sections.push(createKvSection("unknown_pricing", "unknown_pricing:", unknownRows));
1258
+ return renderPlainTextReport({
1259
+ heading: {
1260
+ title: `Quota Status (opencode-quota v${v}) (/quota_status)`,
1261
+ generatedAtMs: params.generatedAtMs,
1262
+ },
1263
+ sections,
1264
+ });
852
1265
  }
853
1266
  //# sourceMappingURL=quota-status.js.map