@slkiser/opencode-quota 3.1.0 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,7 +22,8 @@ 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";
@@ -82,13 +83,30 @@ async function readBasicApiKeyDiagnostics(read) {
82
83
  return getDefaultBasicApiKeyDiagnostics();
83
84
  }
84
85
  }
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(" | ")}` : ""}`;
86
+ function formatInlineApiKeyDiagnosticsValue(diagnostics) {
87
+ return `configured=${diagnostics.configured ? "true" : "false"}${diagnostics.source ? ` source=${diagnostics.source}` : ""}${diagnostics.checkedPaths.length > 0 ? ` checked=${diagnostics.checkedPaths.join(" | ")}` : ""}`;
87
88
  }
88
- function appendBasicApiKeySection(params) {
89
- params.lines.push("");
90
- params.lines.push(params.section);
91
- params.lines.push(formatInlineApiKeyDiagnostics(params.label, params.diagnostics));
89
+ function createKvSection(id, title, rows) {
90
+ return {
91
+ id,
92
+ title,
93
+ blocks: [{ kind: "kv", rows }],
94
+ };
95
+ }
96
+ function createLinesSection(id, title, lines) {
97
+ return {
98
+ id,
99
+ title,
100
+ blocks: [{ kind: "lines", lines }],
101
+ };
102
+ }
103
+ function buildBasicApiKeySection(params) {
104
+ return createKvSection(params.id, params.section, [
105
+ {
106
+ key: params.label,
107
+ value: formatInlineApiKeyDiagnosticsValue(params.diagnostics),
108
+ },
109
+ ]);
92
110
  }
93
111
  function getDefaultNanoGptApiKeyDiagnostics() {
94
112
  return {
@@ -104,14 +122,6 @@ async function readNanoGptApiKeyDiagnostics(read) {
104
122
  return getDefaultNanoGptApiKeyDiagnostics();
105
123
  }
106
124
  }
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
125
  function fmtNanoGptMetric(value) {
116
126
  if (!Number.isFinite(value))
117
127
  return "0";
@@ -256,20 +266,8 @@ function supportedProviderPricingRow(params) {
256
266
  };
257
267
  }
258
268
  export async function buildQuotaStatusReport(params) {
259
- const lines = [];
260
269
  const version = await getPackageVersion();
261
270
  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
271
  const modelDisplay = params.currentModel
274
272
  ? params.currentModel
275
273
  : params.sessionModelLookup === "not_found"
@@ -277,18 +275,26 @@ export async function buildQuotaStatusReport(params) {
277
275
  : params.sessionModelLookup === "no_session"
278
276
  ? "(no session available)"
279
277
  : "(unknown)";
280
- lines.push(`- currentModel: ${modelDisplay}`);
278
+ const sections = [];
279
+ // === toast diagnostics ===
280
+ const toastLines = [
281
+ `- configSource: ${params.configSource}${params.configPaths.length ? ` (${params.configPaths.join(" | ")})` : ""}`,
282
+ `- network_setting_sources: ${formatNetworkSettingSources(params.networkSettingSources)}`,
283
+ `- enabledProviders: ${params.enabledProviders === "auto" ? "(auto)" : params.enabledProviders.length ? params.enabledProviders.join(",") : "(none)"}`,
284
+ `- onlyCurrentModel: ${params.onlyCurrentModel ? "true" : "false"}`,
285
+ `- currentModel: ${modelDisplay}`,
286
+ ];
281
287
  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:");
288
+ toastLines.push("");
289
+ toastLines.push("tui:");
290
+ toastLines.push(`- config_configured: ${params.tuiDiagnostics.configured ? "true" : "false"}`);
291
+ toastLines.push(`- inferred_selected_config_path: ${params.tuiDiagnostics.inferredSelectedPath ?? "(none)"}`);
292
+ toastLines.push(`- present_config_paths: ${joinOrNone(params.tuiDiagnostics.presentPaths)}`);
293
+ toastLines.push(`- candidate_config_paths: ${joinOrNone(params.tuiDiagnostics.candidatePaths)}`);
294
+ toastLines.push(`- quota_plugin_configured: ${params.tuiDiagnostics.quotaPluginConfigured ? "true" : "false"}`);
295
+ toastLines.push(`- quota_plugin_paths: ${joinOrNone(params.tuiDiagnostics.quotaPluginConfigPaths)}`);
296
+ }
297
+ toastLines.push("- providers:");
292
298
  for (const p of params.providerAvailability) {
293
299
  const bits = [];
294
300
  bits.push(p.enabled ? "enabled" : "disabled");
@@ -296,12 +302,16 @@ export async function buildQuotaStatusReport(params) {
296
302
  if (p.matchesCurrentModel !== undefined) {
297
303
  bits.push(`matchesCurrentModel=${p.matchesCurrentModel ? "yes" : "no"}`);
298
304
  }
299
- lines.push(` - ${p.id}: ${bits.join(" ")}`);
305
+ toastLines.push(` - ${p.id}: ${bits.join(" ")}`);
300
306
  }
301
- lines.push("");
302
- lines.push("paths:");
307
+ sections.push(createLinesSection("toast", "toast:", toastLines));
308
+ // === paths ===
309
+ const pathsRows = [];
303
310
  const runtime = getOpencodeRuntimeDirs();
304
- lines.push(`- opencode_dirs: data=${runtime.dataDir} config=${runtime.configDir} cache=${runtime.cacheDir} state=${runtime.stateDir}`);
311
+ pathsRows.push({
312
+ key: "opencode_dirs",
313
+ value: `data=${runtime.dataDir} config=${runtime.configDir} cache=${runtime.cacheDir} state=${runtime.stateDir}`,
314
+ });
305
315
  const authCandidates = getAuthPaths();
306
316
  const authPresent = [];
307
317
  await Promise.all(authCandidates.map(async (p) => {
@@ -313,7 +323,10 @@ export async function buildQuotaStatusReport(params) {
313
323
  // ignore missing/unreadable
314
324
  }
315
325
  }));
316
- lines.push(`- auth.json: preferred=${getAuthPath()} present=${joinOrNone(authPresent)} candidates=${joinOrNone(authCandidates)}`);
326
+ pathsRows.push({
327
+ key: "auth.json",
328
+ value: `preferred=${getAuthPath()} present=${joinOrNone(authPresent)} candidates=${joinOrNone(authCandidates)}`,
329
+ });
317
330
  const authData = await readAuthFileCached({ maxAgeMs: 5_000 });
318
331
  const qwenAuthConfigured = hasQwenOAuthAuth(authData);
319
332
  const qwenLocalPlan = resolveQwenLocalPlan(authData);
@@ -326,55 +339,129 @@ export async function buildQuotaStatusReport(params) {
326
339
  maxAgeMs: DEFAULT_ALIBABA_AUTH_CACHE_MAX_AGE_MS,
327
340
  fallbackTier: params.alibabaCodingPlanTier,
328
341
  });
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)"}`);
342
+ pathsRows.push({ key: "qwen oauth auth configured", value: qwenAuthConfigured ? "true" : "false" });
343
+ pathsRows.push({
344
+ key: "qwen_oauth_source",
345
+ value: qwenLocalPlan.state === "qwen_free" ? qwenLocalPlan.sourceKey : "(none)",
346
+ });
347
+ pathsRows.push({
348
+ key: "qwen_local_plan",
349
+ value: qwenLocalPlan.state === "qwen_free" ? "qwen-code/free" : "(none)",
350
+ });
351
+ pathsRows.push({
352
+ key: "alibaba auth configured",
353
+ value: alibabaAuthDiagnostics.state === "none" ? "false" : "true",
354
+ });
355
+ pathsRows.push({ key: "alibaba_api_key_source", value: alibabaAuthDiagnostics.source ?? "(none)" });
356
+ pathsRows.push({
357
+ key: "alibaba_api_key_checked_paths",
358
+ value: joinOrNone(alibabaAuthDiagnostics.checkedPaths),
359
+ });
360
+ pathsRows.push({
361
+ key: "alibaba_api_key_auth_paths",
362
+ value: joinOrNone(alibabaAuthDiagnostics.authPaths),
363
+ });
364
+ pathsRows.push({
365
+ key: "alibaba coding plan fallback tier",
366
+ value: params.alibabaCodingPlanTier,
367
+ });
368
+ pathsRows.push({
369
+ key: "alibaba_coding_plan",
370
+ value: alibabaAuthDiagnostics.state === "configured"
371
+ ? alibabaAuthDiagnostics.tier
372
+ : alibabaAuthDiagnostics.state === "invalid"
373
+ ? "invalid"
374
+ : "(none)",
375
+ });
338
376
  if (alibabaAuthDiagnostics.state === "invalid") {
339
- lines.push(`- alibaba_auth_error: ${sanitizeDisplayText(alibabaAuthDiagnostics.error)}`);
377
+ pathsRows.push({
378
+ key: "alibaba_auth_error",
379
+ value: sanitizeDisplayText(alibabaAuthDiagnostics.error),
380
+ });
340
381
  }
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)"}`);
382
+ sections.push(createKvSection("paths", "paths:", pathsRows));
383
+ // === openai ===
384
+ const openaiRows = [
385
+ { key: "auth_configured", value: openaiAuth.state === "configured" ? "true" : "false" },
386
+ {
387
+ key: "auth_source",
388
+ value: openaiAuth.state === "configured" ? openaiAuth.sourceKey : "(none)",
389
+ },
390
+ ];
345
391
  const openaiTokenStatus = openaiAuth.state !== "configured"
346
392
  ? "(none)"
347
393
  : openaiAuth.expiresAt && openaiAuth.expiresAt < Date.now()
348
394
  ? "expired"
349
395
  : "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:");
396
+ openaiRows.push({ key: "token_status", value: openaiTokenStatus });
397
+ openaiRows.push({
398
+ key: "token_expires_at",
399
+ value: openaiAuth.state === "configured" && openaiAuth.expiresAt
400
+ ? new Date(openaiAuth.expiresAt).toISOString()
401
+ : "(none)",
402
+ });
403
+ openaiRows.push({
404
+ key: "account_email",
405
+ value: openaiAuth.state === "configured" && openaiAuth.email
406
+ ? sanitizeDisplayText(openaiAuth.email)
407
+ : "(none)",
408
+ });
409
+ openaiRows.push({
410
+ key: "account_id",
411
+ value: openaiAuth.state === "configured" && openaiAuth.accountId
412
+ ? sanitizeDisplayText(openaiAuth.accountId)
413
+ : "(none)",
414
+ });
415
+ sections.push(createKvSection("openai", "openai:", openaiRows));
416
+ // === anthropic ===
417
+ const anthropicRows = [];
356
418
  try {
357
419
  const anthropicDiagnostics = await getAnthropicDiagnostics({
358
420
  binaryPath: params.anthropicBinaryPath,
359
421
  });
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)"}`);
422
+ anthropicRows.push({
423
+ key: "cli_installed",
424
+ value: anthropicDiagnostics.installed ? "true" : "false",
425
+ });
426
+ anthropicRows.push({ key: "cli_version", value: anthropicDiagnostics.version ?? "(none)" });
427
+ anthropicRows.push({ key: "auth_status", value: anthropicDiagnostics.authStatus });
428
+ anthropicRows.push({
429
+ key: "quota_supported",
430
+ value: anthropicDiagnostics.quotaSupported ? "true" : "false",
431
+ });
432
+ anthropicRows.push({
433
+ key: "quota_source",
434
+ value: anthropicDiagnostics.quotaSource === "none" ? "(none)" : anthropicDiagnostics.quotaSource,
435
+ });
436
+ anthropicRows.push({
437
+ key: "checked_commands",
438
+ value: anthropicDiagnostics.checkedCommands.length > 0
439
+ ? anthropicDiagnostics.checkedCommands.join(" | ")
440
+ : "(none)",
441
+ });
366
442
  if (anthropicDiagnostics.message) {
367
- lines.push(`- message: ${anthropicDiagnostics.message}`);
443
+ anthropicRows.push({ key: "message", value: anthropicDiagnostics.message });
368
444
  }
369
445
  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)"}`);
446
+ anthropicRows.push({
447
+ key: "five_hour_remaining",
448
+ value: `${anthropicDiagnostics.quota.five_hour.percentRemaining}% reset_at=${anthropicDiagnostics.quota.five_hour.resetTimeIso ?? "(none)"}`,
449
+ });
450
+ anthropicRows.push({
451
+ key: "seven_day_remaining",
452
+ value: `${anthropicDiagnostics.quota.seven_day.percentRemaining}% reset_at=${anthropicDiagnostics.quota.seven_day.resetTimeIso ?? "(none)"}`,
453
+ });
372
454
  }
373
455
  }
374
456
  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))}` : ""}`);
457
+ anthropicRows.push({ key: "cli_installed", value: "false" });
458
+ anthropicRows.push({
459
+ key: "message",
460
+ value: `failed to probe Claude CLI${err ? `: ${sanitizeDisplayText(err instanceof Error ? err.message : String(err))}` : ""}`,
461
+ });
377
462
  }
463
+ sections.push(createKvSection("anthropic", "anthropic:", anthropicRows));
464
+ // === cursor ===
378
465
  const cursorPlanLabel = getCursorPlanDisplayName(params.cursorPlan);
379
466
  const cursorIncludedApiUsd = getEffectiveCursorIncludedApiUsd({
380
467
  plan: params.cursorPlan,
@@ -382,54 +469,83 @@ export async function buildQuotaStatusReport(params) {
382
469
  });
383
470
  const cursorAuth = await inspectCursorAuthPresence();
384
471
  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)}`);
472
+ const cursorRows = [
473
+ { key: "plan", value: cursorPlanLabel ?? "none" },
474
+ {
475
+ key: "included_api_usd",
476
+ value: typeof cursorIncludedApiUsd === "number" ? fmtUsdAmount(cursorIncludedApiUsd) : "(none)",
477
+ },
478
+ {
479
+ key: "billing_cycle_start_day",
480
+ value: typeof params.cursorBillingCycleStartDay === "number"
481
+ ? String(params.cursorBillingCycleStartDay)
482
+ : "(calendar month)",
483
+ },
484
+ { key: "auth_state", value: cursorAuth.state },
485
+ { key: "auth_selected_path", value: cursorAuth.selectedPath ?? "(none)" },
486
+ { key: "auth_present_paths", value: joinOrNone(cursorAuth.presentPaths) },
487
+ { key: "auth_candidate_paths", value: joinOrNone(cursorAuth.candidatePaths) },
488
+ ];
394
489
  if (cursorAuth.error) {
395
- lines.push(`- auth_error: ${cursorAuth.error}`);
490
+ cursorRows.push({ key: "auth_error", value: cursorAuth.error });
396
491
  }
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)}`);
492
+ cursorRows.push({ key: "plugin_enabled", value: cursorIntegration.pluginEnabled ? "true" : "false" });
493
+ cursorRows.push({ key: "canonical_plugin_package", value: CURSOR_CANONICAL_PLUGIN_PACKAGE });
494
+ cursorRows.push({
495
+ key: "provider_configured",
496
+ value: cursorIntegration.providerConfigured ? "true" : "false",
497
+ });
498
+ cursorRows.push({ key: "config_matches", value: joinOrNone(cursorIntegration.matchedPaths) });
499
+ cursorRows.push({ key: "config_checked_paths", value: joinOrNone(cursorIntegration.checkedPaths) });
402
500
  try {
403
501
  const cursorUsage = await getCurrentCursorUsageSummary({
404
502
  billingCycleStartDay: params.cursorBillingCycleStartDay,
405
503
  });
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)}`);
504
+ cursorRows.push({ key: "cycle_source", value: cursorUsage.window.source });
505
+ cursorRows.push({ key: "cycle_reset_at", value: cursorUsage.window.resetTimeIso });
506
+ cursorRows.push({
507
+ key: "api_usage",
508
+ value: `${fmtUsdAmount(cursorUsage.api.costUsd)} across ${fmtInt(cursorUsage.api.messageCount)} messages`,
509
+ });
510
+ cursorRows.push({
511
+ key: "auto_composer_usage",
512
+ value: `${fmtUsdAmount(cursorUsage.autoComposer.costUsd)} across ${fmtInt(cursorUsage.autoComposer.messageCount)} messages`,
513
+ });
514
+ cursorRows.push({
515
+ key: "total_cursor_usage",
516
+ value: `${fmtUsdAmount(cursorUsage.total.costUsd)} across ${fmtInt(cursorUsage.total.messageCount)} messages`,
517
+ });
518
+ cursorRows.push({ key: "unknown_cursor_models", value: fmtInt(cursorUsage.unknownModels.length) });
412
519
  }
413
520
  catch (err) {
414
521
  const msg = err instanceof Error ? err.message : String(err);
415
- lines.push(`- usage_error: ${msg}`);
522
+ cursorRows.push({ key: "usage_error", value: msg });
416
523
  }
417
524
  const qwenLocalQuotaPath = getQwenLocalQuotaPath();
418
525
  const qwenLocalQuotaExists = await pathExists(qwenLocalQuotaPath);
419
- lines.push(`- qwen free local quota: path=${qwenLocalQuotaPath} exists=${qwenLocalQuotaExists ? "true" : "false"}`);
526
+ cursorRows.push({
527
+ key: "qwen free local quota",
528
+ value: `path=${qwenLocalQuotaPath} exists=${qwenLocalQuotaExists ? "true" : "false"}`,
529
+ });
420
530
  try {
421
531
  const qwenState = await readQwenLocalQuotaState();
422
532
  const qwenQuota = computeQwenQuota({ state: qwenState });
423
533
  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}`);
534
+ cursorRows.push({
535
+ key: "qwen free local usage",
536
+ value: `daily=${qwenQuota.day.used}/${qwenQuota.day.limit} rpm=${qwenQuota.rpm.used}/${qwenQuota.rpm.limit}${qwenUsageSuffix}`,
537
+ });
425
538
  }
426
539
  catch (err) {
427
540
  const msg = err instanceof Error ? err.message : String(err);
428
- lines.push(`- qwen free local usage: error (${msg})`);
541
+ cursorRows.push({ key: "qwen free local usage", value: `error (${msg})` });
429
542
  }
430
543
  const alibabaLocalQuotaPath = getAlibabaCodingPlanQuotaPath();
431
544
  const alibabaLocalQuotaExists = await pathExists(alibabaLocalQuotaPath);
432
- lines.push(`- alibaba coding plan local quota: path=${alibabaLocalQuotaPath} exists=${alibabaLocalQuotaExists ? "true" : "false"}`);
545
+ cursorRows.push({
546
+ key: "alibaba coding plan local quota",
547
+ value: `path=${alibabaLocalQuotaPath} exists=${alibabaLocalQuotaExists ? "true" : "false"}`,
548
+ });
433
549
  if (alibabaCodingPlanAuth.state === "configured") {
434
550
  try {
435
551
  const alibabaState = await readAlibabaCodingPlanQuotaState();
@@ -438,280 +554,366 @@ export async function buildQuotaStatusReport(params) {
438
554
  tier: alibabaCodingPlanAuth.tier,
439
555
  });
440
556
  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}`);
557
+ cursorRows.push({
558
+ key: "alibaba coding plan usage",
559
+ 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}`,
560
+ });
442
561
  }
443
562
  catch (err) {
444
563
  const msg = err instanceof Error ? err.message : String(err);
445
- lines.push(`- alibaba coding plan usage: error (${msg})`);
564
+ cursorRows.push({ key: "alibaba coding plan usage", value: `error (${msg})` });
446
565
  }
447
566
  }
448
567
  else if (alibabaCodingPlanAuth.state === "invalid") {
449
- lines.push(`- alibaba coding plan error: ${alibabaCodingPlanAuth.error}`);
568
+ cursorRows.push({ key: "alibaba coding plan error", value: alibabaCodingPlanAuth.error });
450
569
  }
451
- lines.push("");
452
- lines.push("minimax:");
570
+ sections.push(createKvSection("cursor", "cursor:", cursorRows));
571
+ // === minimax ===
572
+ const minimaxRows = [];
453
573
  const minimaxAuth = await getMiniMaxAuthDiagnostics({
454
574
  maxAgeMs: DEFAULT_MINIMAX_AUTH_CACHE_MAX_AGE_MS,
455
575
  });
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)}`);
576
+ minimaxRows.push({ key: "auth_state", value: minimaxAuth.state });
577
+ minimaxRows.push({
578
+ key: "api_key_configured",
579
+ value: minimaxAuth.state === "configured" ? "true" : "false",
580
+ });
581
+ minimaxRows.push({ key: "api_key_source", value: minimaxAuth.source ?? "(none)" });
582
+ minimaxRows.push({ key: "api_key_checked_paths", value: joinOrNone(minimaxAuth.checkedPaths) });
583
+ minimaxRows.push({ key: "api_key_auth_paths", value: joinOrNone(minimaxAuth.authPaths) });
461
584
  if (minimaxAuth.state === "invalid") {
462
- lines.push(`- auth_error: ${sanitizeDisplayText(minimaxAuth.error)}`);
585
+ minimaxRows.push({ key: "auth_error", value: sanitizeDisplayText(minimaxAuth.error) });
463
586
  }
464
587
  if (minimaxAuth.state === "configured") {
465
588
  const resolvedMiniMaxAuth = await resolveMiniMaxAuthCached({
466
589
  maxAgeMs: DEFAULT_MINIMAX_AUTH_CACHE_MAX_AGE_MS,
467
590
  });
468
591
  if (resolvedMiniMaxAuth.state !== "configured") {
469
- lines.push("- live_fetch_error: MiniMax API key became unavailable before fetch");
592
+ minimaxRows.push({
593
+ key: "live_fetch_error",
594
+ value: "MiniMax API key became unavailable before fetch",
595
+ });
470
596
  }
471
597
  else {
472
598
  const minimaxQuota = await queryMiniMaxQuota(resolvedMiniMaxAuth.apiKey);
473
599
  if (!minimaxQuota.success) {
474
- lines.push(`- live_fetch_error: ${minimaxQuota.error}`);
600
+ minimaxRows.push({ key: "live_fetch_error", value: minimaxQuota.error });
475
601
  }
476
602
  else {
477
603
  const fiveHourEntry = minimaxQuota.entries.find((entry) => entry.window === "five_hour");
478
604
  const weeklyEntry = minimaxQuota.entries.find((entry) => entry.window === "weekly");
479
605
  if (fiveHourEntry) {
480
- lines.push(`- five_hour_usage: ${fiveHourEntry.right ?? "(none)"} percent_remaining=${fiveHourEntry.percentRemaining} reset_at=${fiveHourEntry.resetTimeIso ?? "(none)"}`);
606
+ minimaxRows.push({
607
+ key: "five_hour_usage",
608
+ value: `${fiveHourEntry.right ?? "(none)"} percent_remaining=${fiveHourEntry.percentRemaining} reset_at=${fiveHourEntry.resetTimeIso ?? "(none)"}`,
609
+ });
481
610
  }
482
611
  if (weeklyEntry) {
483
- lines.push(`- weekly_usage: ${weeklyEntry.right ?? "(none)"} percent_remaining=${weeklyEntry.percentRemaining} reset_at=${weeklyEntry.resetTimeIso ?? "(none)"}`);
612
+ minimaxRows.push({
613
+ key: "weekly_usage",
614
+ value: `${weeklyEntry.right ?? "(none)"} percent_remaining=${weeklyEntry.percentRemaining} reset_at=${weeklyEntry.resetTimeIso ?? "(none)"}`,
615
+ });
484
616
  }
485
617
  if (!fiveHourEntry && !weeklyEntry) {
486
- lines.push("- live_state: no reportable MiniMax Coding Plan quota");
618
+ minimaxRows.push({ key: "live_state", value: "no reportable MiniMax Coding Plan quota" });
487
619
  }
488
620
  }
489
621
  }
490
622
  }
491
- lines.push("");
492
- lines.push("kimi:");
623
+ sections.push(createKvSection("minimax", "minimax:", minimaxRows));
624
+ // === kimi ===
625
+ const kimiRows = [];
493
626
  const kimiAuth = await getKimiAuthDiagnostics({
494
627
  maxAgeMs: DEFAULT_KIMI_AUTH_CACHE_MAX_AGE_MS,
495
628
  });
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)}`);
629
+ kimiRows.push({ key: "auth_state", value: kimiAuth.state });
630
+ kimiRows.push({
631
+ key: "api_key_configured",
632
+ value: kimiAuth.state === "configured" ? "true" : "false",
633
+ });
634
+ kimiRows.push({ key: "api_key_source", value: kimiAuth.source ?? "(none)" });
635
+ kimiRows.push({ key: "api_key_checked_paths", value: joinOrNone(kimiAuth.checkedPaths) });
636
+ kimiRows.push({ key: "api_key_auth_paths", value: joinOrNone(kimiAuth.authPaths) });
501
637
  if (kimiAuth.state === "invalid") {
502
- lines.push(`- auth_error: ${sanitizeDisplayText(kimiAuth.error)}`);
638
+ kimiRows.push({ key: "auth_error", value: sanitizeDisplayText(kimiAuth.error) });
503
639
  }
504
640
  if (kimiAuth.state === "configured") {
505
641
  const kimiQuota = await queryKimiQuota();
506
642
  if (!kimiQuota) {
507
- lines.push("- live_fetch_error: Kimi API key became unavailable before fetch");
643
+ kimiRows.push({
644
+ key: "live_fetch_error",
645
+ value: "Kimi API key became unavailable before fetch",
646
+ });
508
647
  }
509
648
  else if (!kimiQuota.success) {
510
- lines.push(`- live_fetch_error: ${kimiQuota.error}`);
649
+ kimiRows.push({ key: "live_fetch_error", value: kimiQuota.error });
511
650
  }
512
651
  else {
513
652
  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)"}`);
653
+ kimiRows.push({
654
+ key: window.label.toLowerCase().replace(/\s+/g, "_"),
655
+ value: `used=${window.used}/${window.limit} percent_remaining=${window.percentRemaining} reset_at=${window.resetTimeIso ?? "(none)"}`,
656
+ });
515
657
  }
516
658
  if (kimiQuota.windows.length === 0) {
517
- lines.push("- live_state: no reportable Kimi quota");
659
+ kimiRows.push({ key: "live_state", value: "no reportable Kimi quota" });
518
660
  }
519
661
  }
520
662
  }
521
- lines.push("");
522
- lines.push("opencode_go:");
663
+ sections.push(createKvSection("kimi", "kimi:", kimiRows));
664
+ // === opencode_go ===
665
+ const openCodeGoRows = [];
523
666
  const openCodeGoDiag = await getOpenCodeGoConfigDiagnostics();
524
- lines.push(`- config_state: ${openCodeGoDiag.state}`);
525
- lines.push(`- config_source: ${openCodeGoDiag.source ?? "(none)"}`);
667
+ openCodeGoRows.push({ key: "config_state", value: openCodeGoDiag.state });
668
+ openCodeGoRows.push({ key: "config_source", value: openCodeGoDiag.source ?? "(none)" });
526
669
  if (openCodeGoDiag.missing) {
527
- lines.push(`- config_missing: ${openCodeGoDiag.missing}`);
670
+ openCodeGoRows.push({ key: "config_missing", value: openCodeGoDiag.missing });
528
671
  }
529
672
  if (openCodeGoDiag.error) {
530
- lines.push(`- config_error: ${sanitizeDisplayText(openCodeGoDiag.error)}`);
673
+ openCodeGoRows.push({ key: "config_error", value: sanitizeDisplayText(openCodeGoDiag.error) });
531
674
  }
532
- lines.push(`- config_checked_paths: ${joinOrNone(openCodeGoDiag.checkedPaths)}`);
675
+ openCodeGoRows.push({ key: "config_checked_paths", value: joinOrNone(openCodeGoDiag.checkedPaths) });
533
676
  if (openCodeGoDiag.state === "configured") {
534
677
  const openCodeGoConfig = await resolveOpenCodeGoConfigCached({
535
678
  maxAgeMs: DEFAULT_OPENCODE_GO_CONFIG_CACHE_MAX_AGE_MS,
536
679
  });
537
680
  if (openCodeGoConfig.state !== "configured") {
538
- lines.push("- live_fetch_error: OpenCode Go config became unavailable before fetch");
681
+ openCodeGoRows.push({
682
+ key: "live_fetch_error",
683
+ value: "OpenCode Go config became unavailable before fetch",
684
+ });
539
685
  }
540
686
  else {
541
687
  const openCodeGoQuota = await queryOpenCodeGoQuota(openCodeGoConfig.config.workspaceId, openCodeGoConfig.config.authCookie);
542
688
  if (!openCodeGoQuota) {
543
- lines.push("- live_fetch_error: OpenCode Go returned null");
689
+ openCodeGoRows.push({ key: "live_fetch_error", value: "OpenCode Go returned null" });
544
690
  }
545
691
  else if (!openCodeGoQuota.success) {
546
- lines.push(`- live_fetch_error: ${openCodeGoQuota.error}`);
692
+ openCodeGoRows.push({ key: "live_fetch_error", value: openCodeGoQuota.error });
547
693
  }
548
694
  else {
549
- lines.push(`- monthly_usage: percent_used=${openCodeGoQuota.usagePercent} percent_remaining=${openCodeGoQuota.percentRemaining} reset_in_sec=${openCodeGoQuota.resetInSec} reset_at=${openCodeGoQuota.resetTimeIso}`);
695
+ openCodeGoRows.push({
696
+ key: "monthly_usage",
697
+ value: `percent_used=${openCodeGoQuota.usagePercent} percent_remaining=${openCodeGoQuota.percentRemaining} reset_in_sec=${openCodeGoQuota.resetInSec} reset_at=${openCodeGoQuota.resetTimeIso}`,
698
+ });
550
699
  }
551
700
  }
552
701
  }
553
- lines.push("");
554
- lines.push("zai:");
702
+ sections.push(createKvSection("opencode_go", "opencode_go:", openCodeGoRows));
703
+ // === zai ===
704
+ const zaiRows = [];
555
705
  const zaiAuth = await getZaiAuthDiagnostics({
556
706
  maxAgeMs: DEFAULT_ZAI_AUTH_CACHE_MAX_AGE_MS,
557
707
  });
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)}`);
708
+ zaiRows.push({ key: "auth_state", value: zaiAuth.state });
709
+ zaiRows.push({
710
+ key: "api_key_configured",
711
+ value: zaiAuth.state === "configured" ? "true" : "false",
712
+ });
713
+ zaiRows.push({ key: "api_key_source", value: zaiAuth.source ?? "(none)" });
714
+ zaiRows.push({ key: "api_key_checked_paths", value: joinOrNone(zaiAuth.checkedPaths) });
715
+ zaiRows.push({ key: "api_key_auth_paths", value: joinOrNone(zaiAuth.authPaths) });
563
716
  if (zaiAuth.state === "invalid") {
564
- lines.push(`- auth_error: ${sanitizeDisplayText(zaiAuth.error)}`);
717
+ zaiRows.push({ key: "auth_error", value: sanitizeDisplayText(zaiAuth.error) });
565
718
  }
566
719
  if (zaiAuth.state === "configured") {
567
720
  const zaiQuota = await queryZaiQuota();
568
721
  if (!zaiQuota) {
569
- lines.push("- live_fetch_error: Z.ai API key became unavailable before fetch");
722
+ zaiRows.push({ key: "live_fetch_error", value: "Z.ai API key became unavailable before fetch" });
570
723
  }
571
724
  else if (!zaiQuota.success) {
572
- lines.push(`- live_fetch_error: ${zaiQuota.error}`);
725
+ zaiRows.push({ key: "live_fetch_error", value: zaiQuota.error });
573
726
  }
574
727
  else {
575
728
  if (zaiQuota.windows.fiveHour) {
576
- lines.push(`- five_hour_remaining: ${zaiQuota.windows.fiveHour.percentRemaining}% reset_at=${zaiQuota.windows.fiveHour.resetTimeIso ?? "(none)"}`);
729
+ zaiRows.push({
730
+ key: "five_hour_remaining",
731
+ value: `${zaiQuota.windows.fiveHour.percentRemaining}% reset_at=${zaiQuota.windows.fiveHour.resetTimeIso ?? "(none)"}`,
732
+ });
577
733
  }
578
734
  if (zaiQuota.windows.weekly) {
579
- lines.push(`- weekly_remaining: ${zaiQuota.windows.weekly.percentRemaining}% reset_at=${zaiQuota.windows.weekly.resetTimeIso ?? "(none)"}`);
735
+ zaiRows.push({
736
+ key: "weekly_remaining",
737
+ value: `${zaiQuota.windows.weekly.percentRemaining}% reset_at=${zaiQuota.windows.weekly.resetTimeIso ?? "(none)"}`,
738
+ });
580
739
  }
581
740
  if (zaiQuota.windows.mcp) {
582
- lines.push(`- mcp_remaining: ${zaiQuota.windows.mcp.percentRemaining}% reset_at=${zaiQuota.windows.mcp.resetTimeIso ?? "(none)"}`);
741
+ zaiRows.push({
742
+ key: "mcp_remaining",
743
+ value: `${zaiQuota.windows.mcp.percentRemaining}% reset_at=${zaiQuota.windows.mcp.resetTimeIso ?? "(none)"}`,
744
+ });
583
745
  }
584
746
  if (!zaiQuota.windows.fiveHour && !zaiQuota.windows.weekly && !zaiQuota.windows.mcp) {
585
- lines.push("- live_state: no reportable Z.ai quota windows");
747
+ zaiRows.push({ key: "live_state", value: "no reportable Z.ai quota windows" });
586
748
  }
587
749
  }
588
750
  }
751
+ sections.push(createKvSection("zai", "zai:", zaiRows));
752
+ // === simple API key sections ===
589
753
  const syntheticDiag = await readBasicApiKeyDiagnostics(getSyntheticKeyDiagnostics);
590
- appendBasicApiKeySection({
591
- lines,
754
+ sections.push(buildBasicApiKeySection({
755
+ id: "synthetic",
592
756
  section: "synthetic:",
593
757
  label: "synthetic api key",
594
758
  diagnostics: syntheticDiag,
595
- });
759
+ }));
596
760
  const chutesDiag = await readBasicApiKeyDiagnostics(getChutesKeyDiagnostics);
597
- appendBasicApiKeySection({
598
- lines,
761
+ sections.push(buildBasicApiKeySection({
762
+ id: "chutes",
599
763
  section: "chutes:",
600
764
  label: "chutes api key",
601
765
  diagnostics: chutesDiag,
602
- });
766
+ }));
767
+ // === nanogpt ===
603
768
  const nanoGptDiag = await readNanoGptApiKeyDiagnostics(getNanoGptKeyDiagnostics);
604
- appendNanoGptApiKeySection(lines, nanoGptDiag);
769
+ const nanoGptRows = [
770
+ { key: "api_key_configured", value: nanoGptDiag.configured ? "true" : "false" },
771
+ { key: "api_key_source", value: nanoGptDiag.source ?? "(none)" },
772
+ { key: "api_key_checked_paths", value: joinOrNone(nanoGptDiag.checkedPaths) },
773
+ { key: "api_key_auth_paths", value: joinOrNone(nanoGptDiag.authPaths) },
774
+ ];
605
775
  if (nanoGptDiag.configured) {
606
776
  try {
607
777
  const nanoGptQuota = await queryNanoGptQuota();
608
778
  if (!nanoGptQuota) {
609
- lines.push("- live_fetch_error: NanoGPT API key became unavailable before fetch");
779
+ nanoGptRows.push({
780
+ key: "live_fetch_error",
781
+ value: "NanoGPT API key became unavailable before fetch",
782
+ });
610
783
  }
611
784
  else if (!nanoGptQuota.success) {
612
- lines.push(`- live_fetch_error: ${nanoGptQuota.error}`);
785
+ nanoGptRows.push({ key: "live_fetch_error", value: nanoGptQuota.error });
613
786
  }
614
787
  else {
615
788
  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"}`);
789
+ nanoGptRows.push({
790
+ key: "subscription_active",
791
+ value: nanoGptQuota.subscription.active ? "true" : "false",
792
+ });
793
+ nanoGptRows.push({ key: "subscription_state", value: nanoGptQuota.subscription.state });
794
+ nanoGptRows.push({
795
+ key: "enforce_daily_limit",
796
+ value: nanoGptQuota.subscription.enforceDailyLimit ? "true" : "false",
797
+ });
619
798
  if (nanoGptQuota.subscription.daily) {
620
799
  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)"}`);
800
+ nanoGptRows.push({
801
+ key: "daily_usage",
802
+ value: `${fmtNanoGptMetric(daily.used)}/${fmtNanoGptMetric(daily.limit)} remaining=${fmtNanoGptMetric(daily.remaining)} percent_remaining=${daily.percentRemaining} reset_at=${daily.resetTimeIso ?? "(none)"}`,
803
+ });
622
804
  }
623
805
  if (nanoGptQuota.subscription.monthly) {
624
806
  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)"}`);
807
+ nanoGptRows.push({
808
+ key: "monthly_usage",
809
+ value: `${fmtNanoGptMetric(monthly.used)}/${fmtNanoGptMetric(monthly.limit)} remaining=${fmtNanoGptMetric(monthly.remaining)} percent_remaining=${monthly.percentRemaining} reset_at=${monthly.resetTimeIso ?? "(none)"}`,
810
+ });
626
811
  }
627
- lines.push(`- billing_period_end: ${nanoGptQuota.subscription.currentPeriodEndIso ?? "(none)"}`);
812
+ nanoGptRows.push({
813
+ key: "billing_period_end",
814
+ value: nanoGptQuota.subscription.currentPeriodEndIso ?? "(none)",
815
+ });
628
816
  if (nanoGptQuota.subscription.graceUntilIso) {
629
- lines.push(`- grace_until: ${nanoGptQuota.subscription.graceUntilIso}`);
817
+ nanoGptRows.push({ key: "grace_until", value: nanoGptQuota.subscription.graceUntilIso });
630
818
  }
631
819
  }
632
- lines.push(`- balance_usd: ${typeof nanoGptQuota.balance?.usdBalance === "number" ? fmtUsdAmount(nanoGptQuota.balance.usdBalance) : "(none)"}`);
633
- lines.push(`- balance_nano: ${nanoGptQuota.balance?.nanoBalanceRaw ?? "(none)"}`);
820
+ nanoGptRows.push({
821
+ key: "balance_usd",
822
+ value: typeof nanoGptQuota.balance?.usdBalance === "number"
823
+ ? fmtUsdAmount(nanoGptQuota.balance.usdBalance)
824
+ : "(none)",
825
+ });
826
+ nanoGptRows.push({ key: "balance_nano", value: nanoGptQuota.balance?.nanoBalanceRaw ?? "(none)" });
634
827
  for (const entry of nanoGptQuota.endpointErrors ?? []) {
635
- lines.push(`- live_error_${entry.endpoint}: ${entry.message}`);
828
+ nanoGptRows.push({ key: `live_error_${entry.endpoint}`, value: entry.message });
636
829
  }
637
830
  }
638
831
  }
639
832
  catch (err) {
640
833
  const msg = err instanceof Error ? err.message : String(err);
641
- lines.push(`- live_fetch_error: ${msg}`);
834
+ nanoGptRows.push({ key: "live_fetch_error", value: msg });
642
835
  }
643
836
  }
837
+ sections.push(createKvSection("nanogpt", "nanogpt:", nanoGptRows));
838
+ // === copilot auth ===
644
839
  const copilotDiag = getCopilotQuotaAuthDiagnostics(authData);
645
- lines.push("");
646
- lines.push("copilot_quota_auth:");
647
- lines.push(`- pat_state: ${copilotDiag.pat.state}`);
840
+ const copilotRows = [{ key: "pat_state", value: copilotDiag.pat.state }];
648
841
  if (copilotDiag.pat.selectedPath) {
649
- lines.push(`- pat_path: ${copilotDiag.pat.selectedPath}`);
842
+ copilotRows.push({ key: "pat_path", value: copilotDiag.pat.selectedPath });
650
843
  }
651
844
  if (copilotDiag.pat.tokenKind) {
652
- lines.push(`- pat_token_kind: ${copilotDiag.pat.tokenKind}`);
845
+ copilotRows.push({ key: "pat_token_kind", value: copilotDiag.pat.tokenKind });
653
846
  }
654
847
  if (copilotDiag.pat.config?.tier) {
655
- lines.push(`- pat_tier: ${copilotDiag.pat.config.tier}`);
848
+ copilotRows.push({ key: "pat_tier", value: copilotDiag.pat.config.tier });
656
849
  }
657
850
  if (copilotDiag.pat.config?.organization) {
658
- lines.push(`- pat_organization: ${copilotDiag.pat.config.organization}`);
851
+ copilotRows.push({ key: "pat_organization", value: copilotDiag.pat.config.organization });
659
852
  }
660
853
  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}`);
854
+ copilotRows.push({ key: "pat_enterprise", value: copilotDiag.pat.config.enterprise });
855
+ }
856
+ copilotRows.push({ key: "billing_mode", value: copilotDiag.billingMode });
857
+ copilotRows.push({ key: "billing_scope", value: copilotDiag.billingScope });
858
+ copilotRows.push({ key: "quota_api", value: copilotDiag.quotaApi });
859
+ copilotRows.push({
860
+ key: "billing_api_access_likely",
861
+ value: copilotDiag.billingApiAccessLikely ? "true" : "false",
862
+ });
863
+ copilotRows.push({ key: "remaining_totals_state", value: copilotDiag.remainingTotalsState });
668
864
  if (copilotDiag.queryPeriod) {
669
- lines.push(`- billing_period: ${copilotDiag.queryPeriod.year}-${String(copilotDiag.queryPeriod.month).padStart(2, "0")}`);
865
+ copilotRows.push({
866
+ key: "billing_period",
867
+ value: `${copilotDiag.queryPeriod.year}-${String(copilotDiag.queryPeriod.month).padStart(2, "0")}`,
868
+ });
670
869
  }
671
870
  if (copilotDiag.usernameFilter) {
672
- lines.push(`- username_filter: ${copilotDiag.usernameFilter}`);
871
+ copilotRows.push({ key: "username_filter", value: copilotDiag.usernameFilter });
673
872
  }
674
873
  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");
874
+ copilotRows.push({
875
+ key: "billing_usage_note",
876
+ value: "organization premium usage for the current billing period",
877
+ });
878
+ copilotRows.push({
879
+ key: "remaining_quota_note",
880
+ value: "valid PAT access can query billing usage, but pooled org usage does not provide a true per-user remaining quota",
881
+ });
677
882
  }
678
883
  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");
884
+ copilotRows.push({
885
+ key: "billing_usage_note",
886
+ value: "enterprise premium usage for the current billing period",
887
+ });
888
+ copilotRows.push({
889
+ key: "remaining_quota_note",
890
+ value: "valid enterprise billing access can query pooled enterprise usage, but it does not provide a true per-user remaining quota",
891
+ });
681
892
  }
682
893
  if (copilotDiag.billingTargetError) {
683
- lines.push(`- billing_target_error: ${copilotDiag.billingTargetError}`);
894
+ copilotRows.push({ key: "billing_target_error", value: copilotDiag.billingTargetError });
684
895
  }
685
896
  if (copilotDiag.tokenCompatibilityError) {
686
- lines.push(`- token_compatibility_error: ${copilotDiag.tokenCompatibilityError}`);
897
+ copilotRows.push({ key: "token_compatibility_error", value: copilotDiag.tokenCompatibilityError });
687
898
  }
688
899
  if (copilotDiag.pat.error) {
689
- lines.push(`- pat_error: ${copilotDiag.pat.error}`);
900
+ copilotRows.push({ key: "pat_error", value: copilotDiag.pat.error });
690
901
  }
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}`);
902
+ copilotRows.push({
903
+ key: "pat_checked_paths",
904
+ value: copilotDiag.pat.checkedPaths.length ? copilotDiag.pat.checkedPaths.join(" | ") : "(none)",
905
+ });
906
+ copilotRows.push({
907
+ key: "oauth_configured",
908
+ value: `${copilotDiag.oauth.configured ? "true" : "false"} key=${copilotDiag.oauth.keyName ?? "(none)"} refresh=${copilotDiag.oauth.hasRefreshToken ? "true" : "false"} access=${copilotDiag.oauth.hasAccessToken ? "true" : "false"}`,
909
+ });
910
+ copilotRows.push({ key: "effective_source", value: copilotDiag.effectiveSource });
911
+ copilotRows.push({ key: "override", value: copilotDiag.override });
912
+ sections.push(createKvSection("copilot_quota_auth", "copilot_quota_auth:", copilotRows));
913
+ // === google antigravity + db path ===
695
914
  const googleTokenCachePath = getGoogleTokenCachePath();
696
915
  const googleAuthPresence = await inspectAntigravityAccountsPresence();
697
916
  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
917
  const dbCandidates = getOpenCodeDbPathCandidates();
716
918
  const dbSelected = getOpenCodeDbPath();
717
919
  const dbPresent = [];
@@ -719,41 +921,75 @@ export async function buildQuotaStatusReport(params) {
719
921
  if (await pathExists(p))
720
922
  dbPresent.push(p);
721
923
  }));
722
- lines.push(`- opencode db: preferred=${dbSelected} present=${joinOrNone(dbPresent)} candidates=${joinOrNone(dbCandidates)}`);
924
+ const googleRows = [
925
+ { key: "auth_state", value: googleAuthPresence.state },
926
+ { key: "selected_accounts_path", value: googleAuthPresence.selectedPath ?? "(none)" },
927
+ { key: "present_accounts_paths", value: joinOrNone(googleAuthPresence.presentPaths) },
928
+ { key: "candidate_accounts_paths", value: joinOrNone(googleAuthPresence.candidatePaths) },
929
+ { key: "account_count", value: String(googleAuthPresence.accountCount) },
930
+ { key: "valid_account_count", value: String(googleAuthPresence.validAccountCount) },
931
+ { key: "companion_package_state", value: googleCompanionPresence.state },
932
+ {
933
+ key: "companion_package_path",
934
+ value: googleCompanionPresence.state === "present" || googleCompanionPresence.state === "invalid"
935
+ ? googleCompanionPresence.resolvedPath ?? "(none)"
936
+ : "(none)",
937
+ },
938
+ ];
939
+ if (googleCompanionPresence.state !== "present") {
940
+ googleRows.push({
941
+ key: "companion_error",
942
+ value: sanitizeDisplayText(googleCompanionPresence.error),
943
+ });
944
+ }
945
+ googleRows.push({
946
+ key: "token_cache_path",
947
+ value: `${googleTokenCachePath} exists=${(await pathExists(googleTokenCachePath)) ? "true" : "false"}`,
948
+ });
949
+ if (googleAuthPresence.state === "invalid" && googleAuthPresence.error) {
950
+ googleRows.push({ key: "auth_error", value: sanitizeDisplayText(googleAuthPresence.error) });
951
+ }
952
+ googleRows.push({
953
+ key: "opencode db",
954
+ value: `preferred=${dbSelected} present=${joinOrNone(dbPresent)} candidates=${joinOrNone(dbCandidates)}`,
955
+ });
956
+ sections.push(createKvSection("google_antigravity", "google_antigravity:", googleRows));
723
957
  if (params.googleRefresh?.attempted) {
724
- lines.push("");
725
- lines.push("google_token_refresh:");
958
+ const googleRefreshRows = [];
726
959
  if (typeof params.googleRefresh.total === "number" &&
727
960
  typeof params.googleRefresh.successCount === "number") {
728
- lines.push(`- refreshed: ${params.googleRefresh.successCount}/${params.googleRefresh.total}`);
961
+ googleRefreshRows.push({
962
+ key: "refreshed",
963
+ value: `${params.googleRefresh.successCount}/${params.googleRefresh.total}`,
964
+ });
729
965
  }
730
966
  else {
731
- lines.push("- attempted");
967
+ googleRefreshRows.push({ key: "attempted" });
732
968
  }
733
969
  for (const f of params.googleRefresh.failures ?? []) {
734
- lines.push(`- ${f.email ?? "Unknown"}: ${f.error}`);
970
+ googleRefreshRows.push({ key: f.email ?? "Unknown", value: f.error });
735
971
  }
972
+ sections.push(createKvSection("google_token_refresh", "google_token_refresh:", googleRefreshRows));
736
973
  }
737
974
  // === session token errors ===
738
975
  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}`);
976
+ const sessionTokenErrorRows = [
977
+ { key: "session_id", value: params.sessionTokenError.sessionID },
978
+ { key: "error", value: params.sessionTokenError.error },
979
+ ];
743
980
  if (params.sessionTokenError.checkedPath) {
744
- lines.push(`- checked_path: ${params.sessionTokenError.checkedPath}`);
981
+ sessionTokenErrorRows.push({ key: "checked_path", value: params.sessionTokenError.checkedPath });
745
982
  }
983
+ sections.push(createKvSection("session_tokens_error", "session_tokens_error:", sessionTokenErrorRows));
746
984
  }
747
985
  // === storage scan ===
748
986
  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)}`);
987
+ sections.push(createKvSection("storage", "storage:", [
988
+ { key: "sessions_in_db", value: fmtInt(dbStats.sessionCount) },
989
+ { key: "messages_in_db", value: fmtInt(dbStats.messageCount) },
990
+ { key: "assistant_messages_in_db", value: fmtInt(dbStats.assistantMessageCount) },
991
+ ]));
754
992
  // === 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
993
  const agg = await aggregateUsage({});
758
994
  const meta = getPricingSnapshotMeta();
759
995
  const providers = listProviders();
@@ -767,73 +1003,113 @@ export async function buildQuotaStatusReport(params) {
767
1003
  const runtimeSnapshotPath = getRuntimePricingSnapshotPath();
768
1004
  const refreshStatePath = getRuntimePricingRefreshStatePath();
769
1005
  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}`);
1006
+ const pricingRows = [
1007
+ {
1008
+ key: "pricing",
1009
+ value: `source=${meta.source} active_source=${snapshotSource} generated_at=${new Date(meta.generatedAt).toISOString()} units=${meta.units}`,
1010
+ },
1011
+ {
1012
+ key: "selection",
1013
+ value: `configured=${params.pricingSnapshotSource} active=${snapshotSource}`,
1014
+ },
1015
+ ];
774
1016
  if (params.pricingSnapshotSource === "bundled") {
775
- lines.push("- selection_note: bundled config pins the packaged snapshot and ignores runtime refresh for active pricing");
1017
+ pricingRows.push({
1018
+ key: "selection_note",
1019
+ value: "bundled config pins the packaged snapshot and ignores runtime refresh for active pricing",
1020
+ });
776
1021
  }
777
1022
  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");
1023
+ pricingRows.push({
1024
+ key: "selection_note",
1025
+ value: "runtime config requested the local runtime snapshot, but bundled fallback is active because no valid runtime snapshot is available",
1026
+ });
779
1027
  }
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)}`);
1028
+ pricingRows.push({
1029
+ key: "runtime_paths",
1030
+ value: `snapshot=${runtimeSnapshotPath} refresh_state=${refreshStatePath}`,
1031
+ });
1032
+ pricingRows.push({
1033
+ key: "staleness",
1034
+ value: `age_ms=${fmtInt(health.ageMs)} max_age_ms=${fmtInt(health.maxAgeMs)} stale=${health.stale ? "true" : "false"}`,
1035
+ });
1036
+ pricingRows.push({
1037
+ key: "refresh_policy",
1038
+ value: `auto_refresh_days=${fmtInt(autoRefreshDays)}`,
1039
+ });
783
1040
  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)"}`);
1041
+ pricingRows.push({
1042
+ key: "refresh",
1043
+ 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)"}`,
1044
+ });
785
1045
  if (pricingRefreshState.lastError) {
786
- lines.push(`- refresh_error: ${pricingRefreshState.lastError}`);
1046
+ pricingRows.push({ key: "refresh_error", value: pricingRefreshState.lastError });
787
1047
  }
788
1048
  }
789
1049
  else {
790
- lines.push("- refresh: (no runtime refresh state yet)");
1050
+ pricingRows.push({ key: "refresh", value: "(no runtime refresh state yet)" });
791
1051
  }
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)}`);
1052
+ pricingRows.push({ key: "providers", value: providers.join(",") });
1053
+ pricingRows.push({
1054
+ key: "coverage_seen",
1055
+ value: `priced_keys=${fmtInt(coverage.totals.pricedKeysSeen)} mapped_but_missing=${fmtInt(coverage.totals.mappedMissingKeysSeen)} unpriced_keys=${fmtInt(coverage.totals.unpricedKeysSeen)}`,
1056
+ });
794
1057
  for (const p of providers) {
795
1058
  const c = coverage.byProvider.get(p) ?? {
796
1059
  pricedKeysSeen: 0,
797
1060
  mappedMissingKeysSeen: 0,
798
1061
  unpricedKeysSeen: 0,
799
1062
  };
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)}`);
1063
+ pricingRows.push({
1064
+ key: p,
1065
+ 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)}`,
1066
+ indent: 1,
1067
+ });
801
1068
  }
1069
+ sections.push(createKvSection("pricing_snapshot", "pricing_snapshot:", pricingRows));
802
1070
  // === supported providers pricing ===
803
1071
  const supported = getProviders().map((p) => p.id);
804
- lines.push("");
805
- lines.push("supported_providers_pricing:");
806
- for (const id of supported) {
1072
+ const supportedRows = supported.map((id) => {
807
1073
  const row = supportedProviderPricingRow({ id, agg, snapshotProviders: providers });
808
- lines.push(`- ${row.id}: pricing=${row.pricing} (${row.notes})`);
809
- }
1074
+ return {
1075
+ key: row.id,
1076
+ value: `pricing=${row.pricing} (${row.notes})`,
1077
+ };
1078
+ });
1079
+ sections.push(createKvSection("supported_providers_pricing", "supported_providers_pricing:", supportedRows));
810
1080
  // === unpriced models ===
811
- // Mapped keys that are deterministically not token-priced by our snapshot.
812
- lines.push("");
813
- lines.push("unpriced_models:");
1081
+ const unpricedRows = [];
814
1082
  if (agg.unpriced.length === 0) {
815
- lines.push("- none");
1083
+ unpricedRows.push({ key: "none" });
816
1084
  }
817
1085
  else {
818
- lines.push(`- keys: ${fmtInt(agg.unpriced.length)} tokens_total=${fmtInt(totalTokenBuckets(agg.totals.unpriced))}`);
1086
+ unpricedRows.push({
1087
+ key: "keys",
1088
+ value: `${fmtInt(agg.unpriced.length)} tokens_total=${fmtInt(totalTokenBuckets(agg.totals.unpriced))}`,
1089
+ });
819
1090
  for (const row of agg.unpriced.slice(0, STATUS_SAMPLE_LIMIT)) {
820
1091
  const src = `${row.key.sourceProviderID}/${row.key.sourceModelID}`;
821
1092
  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}`);
1093
+ unpricedRows.push({
1094
+ key: src,
1095
+ value: `mapped=${mapped} tokens=${fmtInt(totalTokenBuckets(row.tokens))} msgs=${fmtInt(row.messageCount)} reason=${row.key.reason}`,
1096
+ });
823
1097
  }
824
1098
  if (agg.unpriced.length > STATUS_SAMPLE_LIMIT) {
825
- lines.push(`- ... (${fmtInt(agg.unpriced.length - STATUS_SAMPLE_LIMIT)} more)`);
1099
+ unpricedRows.push({ key: `... (${fmtInt(agg.unpriced.length - STATUS_SAMPLE_LIMIT)} more)` });
826
1100
  }
827
1101
  }
1102
+ sections.push(createKvSection("unpriced_models", "unpriced_models:", unpricedRows));
828
1103
  // === 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:");
1104
+ const unknownRows = [];
832
1105
  if (agg.unknown.length === 0) {
833
- lines.push("- none");
1106
+ unknownRows.push({ key: "none" });
834
1107
  }
835
1108
  else {
836
- lines.push(`- keys: ${fmtInt(agg.unknown.length)} tokens_total=${fmtInt(totalTokenBuckets(agg.totals.unknown))}`);
1109
+ unknownRows.push({
1110
+ key: "keys",
1111
+ value: `${fmtInt(agg.unknown.length)} tokens_total=${fmtInt(totalTokenBuckets(agg.totals.unknown))}`,
1112
+ });
837
1113
  for (const row of agg.unknown.slice(0, STATUS_SAMPLE_LIMIT)) {
838
1114
  const src = `${row.key.sourceProviderID}/${row.key.sourceModelID}`;
839
1115
  const mappedBase = row.key.mappedProvider && row.key.mappedModel
@@ -842,12 +1118,22 @@ export async function buildQuotaStatusReport(params) {
842
1118
  const candidates = row.key.providerCandidates && row.key.providerCandidates.length > 0
843
1119
  ? ` candidates=${row.key.providerCandidates.join(",")}`
844
1120
  : "";
845
- lines.push(`- ${src} mapped=${mappedBase}${candidates} tokens=${fmtInt(totalTokenBuckets(row.tokens))} msgs=${fmtInt(row.messageCount)}`);
1121
+ unknownRows.push({
1122
+ key: src,
1123
+ value: `mapped=${mappedBase}${candidates} tokens=${fmtInt(totalTokenBuckets(row.tokens))} msgs=${fmtInt(row.messageCount)}`,
1124
+ });
846
1125
  }
847
1126
  if (agg.unknown.length > STATUS_SAMPLE_LIMIT) {
848
- lines.push(`- ... (${fmtInt(agg.unknown.length - STATUS_SAMPLE_LIMIT)} more)`);
1127
+ unknownRows.push({ key: `... (${fmtInt(agg.unknown.length - STATUS_SAMPLE_LIMIT)} more)` });
849
1128
  }
850
1129
  }
851
- return lines.join("\n");
1130
+ sections.push(createKvSection("unknown_pricing", "unknown_pricing:", unknownRows));
1131
+ return renderPlainTextReport({
1132
+ heading: {
1133
+ title: `Quota Status (opencode-quota v${v}) (/quota_status)`,
1134
+ generatedAtMs: params.generatedAtMs,
1135
+ },
1136
+ sections,
1137
+ });
852
1138
  }
853
1139
  //# sourceMappingURL=quota-status.js.map