agent-usage-all-in-one 0.2.2 → 0.3.0

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.
package/dist/cli.js CHANGED
@@ -643,6 +643,41 @@ function xaiEntry(options) {
643
643
  source: XAI_PRICING_SOURCE
644
644
  };
645
645
  }
646
+ function openCodeLocalHistoryEntries(entries) {
647
+ return entries.flatMap((entry) => {
648
+ const modelPrefix = openCodeLocalModelPrefix(entry);
649
+ if (!modelPrefix) return [];
650
+ const localModel = (model) => model.includes("/") ? model : `${modelPrefix}/${model}`;
651
+ const canonicalModel = localModel(entry.canonicalModel);
652
+ return [
653
+ {
654
+ ...entry,
655
+ id: `opencode-local-${entry.id}`,
656
+ providerId: "opencode",
657
+ billingDomainId: "local-history",
658
+ canonicalModel,
659
+ aliases: [
660
+ ...new Set(
661
+ [entry.canonicalModel, ...entry.aliases].map(localModel).filter((model) => model !== canonicalModel)
662
+ )
663
+ ]
664
+ }
665
+ ];
666
+ });
667
+ }
668
+ function openCodeLocalModelPrefix(entry) {
669
+ if (entry.providerId === "claude-code" && entry.billingDomainId === "subscription") {
670
+ return "anthropic";
671
+ }
672
+ if (entry.providerId === "codex" && entry.billingDomainId === "subscription") {
673
+ return "openai";
674
+ }
675
+ if (entry.providerId === "grok" && entry.billingDomainId === "xai-api") return "xai";
676
+ if (entry.providerId === "opencode-go" && entry.billingDomainId === "go-subscription") {
677
+ return "opencode-go";
678
+ }
679
+ return null;
680
+ }
646
681
  function deriveRetailEquivalentCosts(snapshot2, catalog = ANTHROPIC_PRICING_CATALOG, calculatedAt = snapshot2.observedAt) {
647
682
  const costs = [];
648
683
  const decisions = [];
@@ -806,7 +841,7 @@ function matchContext(rule, observation) {
806
841
  function preciseMoney(value) {
807
842
  return Number(value.toFixed(12));
808
843
  }
809
- var ANTHROPIC_PRICING_CATALOG, OPENCODE_GO_SOURCE, XAI_PRICING_SOURCE, OPENAI_GPT_56_SOURCE, OPEN_CODE_GO_SOURCE_PATH, openCodeHistory, OPEN_CODE_BASE_HISTORY, OPEN_CODE_PRICE_HISTORY, OPEN_CODE_FLAT_MODELS, OPEN_CODE_CONTEXT_MODELS, DEEPSEEK_GO_MODELS, WEEKDAY_PEAK_RANGES, OFFICIAL_PRICING_CATALOG;
844
+ var ANTHROPIC_PRICING_CATALOG, OPENCODE_GO_SOURCE, XAI_PRICING_SOURCE, OPENAI_GPT_56_SOURCE, OPEN_CODE_GO_SOURCE_PATH, openCodeHistory, OPEN_CODE_BASE_HISTORY, OPEN_CODE_PRICE_HISTORY, OPEN_CODE_FLAT_MODELS, OPEN_CODE_CONTEXT_MODELS, DEEPSEEK_GO_MODELS, WEEKDAY_PEAK_RANGES, DIRECT_OFFICIAL_PRICING_CATALOG, OFFICIAL_PRICING_CATALOG;
810
845
  var init_retail_pricing = __esm({
811
846
  "src/core/retail-pricing.ts"() {
812
847
  "use strict";
@@ -1004,7 +1039,7 @@ var init_retail_pricing = __esm({
1004
1039
  { startHour: 1, endHour: 4 },
1005
1040
  { startHour: 6, endHour: 10 }
1006
1041
  ];
1007
- OFFICIAL_PRICING_CATALOG = {
1042
+ DIRECT_OFFICIAL_PRICING_CATALOG = {
1008
1043
  version: "2026-08-28-grok-4.6-build",
1009
1044
  entries: [
1010
1045
  ...ANTHROPIC_PRICING_CATALOG.entries,
@@ -1139,6 +1174,13 @@ var init_retail_pricing = __esm({
1139
1174
  })
1140
1175
  ]
1141
1176
  };
1177
+ OFFICIAL_PRICING_CATALOG = {
1178
+ version: "2026-08-29-opencode-local-history",
1179
+ entries: [
1180
+ ...DIRECT_OFFICIAL_PRICING_CATALOG.entries,
1181
+ ...openCodeLocalHistoryEntries(DIRECT_OFFICIAL_PRICING_CATALOG.entries)
1182
+ ]
1183
+ };
1142
1184
  }
1143
1185
  });
1144
1186
 
@@ -1933,9 +1975,9 @@ var init_catalog = __esm({
1933
1975
  },
1934
1976
  {
1935
1977
  id: "opencode-go",
1936
- displayName: "OpenCode Go",
1978
+ displayName: "OpenCode",
1937
1979
  command: "opencode",
1938
- permissionDescription: "Read account quota and local exports through official OpenCode surfaces.",
1980
+ permissionDescription: "Read local usage and optional Go account quota through official OpenCode surfaces.",
1939
1981
  credentialOwner: "official-client",
1940
1982
  experimental: false,
1941
1983
  expectedCoverage: ["quota", "tokens", "history"],
@@ -1990,6 +2032,7 @@ function mapQuota(quota) {
1990
2032
  billingDomainId: "subscription",
1991
2033
  label: quota.label,
1992
2034
  usedPercent: quota.usedPercent,
2035
+ windowDurationMinutes: quota.windowDurationMinutes,
1993
2036
  resetsAt: quota.resetsAt,
1994
2037
  authority: "official-client",
1995
2038
  scope: "account-wide"
@@ -2294,6 +2337,7 @@ function parseClaudeUsageScreen(text, now) {
2294
2337
  id,
2295
2338
  label: displayLabel(heading),
2296
2339
  usedPercent: Number(match[1]),
2340
+ windowDurationMinutes: windowDurationMinutes(heading),
2297
2341
  resetsAt: resetLine ? parseReset(resetLine, now) : null
2298
2342
  });
2299
2343
  }
@@ -2326,6 +2370,11 @@ function displayLabel(heading) {
2326
2370
  const weekly = heading.match(/^Weekly\s*[·—-]\s*(.+)$/i);
2327
2371
  return weekly ? `Week \xB7 ${weekly[1]}` : heading;
2328
2372
  }
2373
+ function windowDurationMinutes(heading) {
2374
+ if (/^(5[- ]hour limit|current session)$/i.test(heading)) return 300;
2375
+ if (/^(Current week\s*\(.+\)|Weekly\s*[·—-]\s*.+)$/i.test(heading)) return 10080;
2376
+ return null;
2377
+ }
2329
2378
  function parseReset(line, now) {
2330
2379
  const relative = line.match(/Resets\s+in\s+(?:(\d+)d\s*)?(?:(\d+)h\s*)?(?:(\d+)m)?/i);
2331
2380
  if (relative) {
@@ -2652,6 +2701,7 @@ function mapQuotaBuckets(response) {
2652
2701
  billingDomainId: "subscription",
2653
2702
  label: multipleLimits ? `${baseLabel} \xB7 ${windowLabel}` : windowLabel,
2654
2703
  usedPercent: window.usedPercent,
2704
+ windowDurationMinutes: window.windowDurationMins,
2655
2705
  resetsAt: window.resetsAt === null ? null : new Date(window.resetsAt * 1e3).toISOString(),
2656
2706
  authority: "official-account"
2657
2707
  });
@@ -2989,6 +3039,119 @@ var init_stdio_codex_account_client = __esm({
2989
3039
  }
2990
3040
  });
2991
3041
 
3042
+ // src/connectors/opencode-local/opencode-local-connector.ts
3043
+ function mapLocalUsage(request) {
3044
+ return {
3045
+ id: `opencode-local-request:${request.id}`,
3046
+ billingDomainId: "local-history",
3047
+ model: request.model,
3048
+ observedAt: new Date(request.observedAtMs).toISOString(),
3049
+ inputTokens: request.inputTokens,
3050
+ outputTokens: request.outputTokens,
3051
+ reasoningTokens: request.reasoningTokens,
3052
+ cacheReadTokens: request.cacheReadTokens,
3053
+ cacheWriteTokens: request.cacheWriteTokens,
3054
+ tokenSemantics: {
3055
+ reasoning: "separate",
3056
+ cacheRead: "separate",
3057
+ cacheWrite: "separate"
3058
+ },
3059
+ modelAttribution: "known",
3060
+ timePrecision: "event",
3061
+ usageScope: "this-mac",
3062
+ aggregationTemporality: "delta",
3063
+ authority: "local-observation"
3064
+ };
3065
+ }
3066
+ function mapLocalCost(request, cost) {
3067
+ const usageObservationId = `opencode-local-request:${request.id}`;
3068
+ return {
3069
+ id: `opencode-local-request-cost:${request.id}`,
3070
+ sourceId: usageObservationId,
3071
+ billingDomainId: "local-history",
3072
+ observedAt: new Date(request.observedAtMs).toISOString(),
3073
+ kind: "reported-estimate",
3074
+ amount: cost,
3075
+ currency: "USD",
3076
+ authority: "local-observation",
3077
+ model: request.model,
3078
+ usageObservationId,
3079
+ priceSnapshot: {
3080
+ id: "opencode-local-message-reported-cost-v1",
3081
+ version: "2026-08-29",
3082
+ source: "OpenCode local message history reported cost",
3083
+ canonicalModel: request.model,
3084
+ effectiveAt: "2026-08-29T00:00:00.000Z",
3085
+ effectiveUntil: null,
3086
+ currency: "USD",
3087
+ ratesPerMillion: {
3088
+ input: null,
3089
+ output: null,
3090
+ reasoning: null,
3091
+ "cache-read": null,
3092
+ "cache-write": null
3093
+ }
3094
+ }
3095
+ };
3096
+ }
3097
+ function safeFailure3(error) {
3098
+ if (error instanceof Error && "code" in error && typeof error.code === "string" && "recovery" in error && typeof error.recovery === "string") {
3099
+ return { code: error.code, message: error.message, recovery: error.recovery };
3100
+ }
3101
+ return {
3102
+ code: "opencode-local-refresh-failed",
3103
+ message: "OpenCode local history coverage is incomplete.",
3104
+ recovery: "Run agent-usage doctor, then retry refresh."
3105
+ };
3106
+ }
3107
+ var OpenCodeLocalConnector;
3108
+ var init_opencode_local_connector = __esm({
3109
+ "src/connectors/opencode-local/opencode-local-connector.ts"() {
3110
+ "use strict";
3111
+ OpenCodeLocalConnector = class {
3112
+ id = "opencode";
3113
+ displayName = "OpenCode";
3114
+ consentId = "opencode-go";
3115
+ #localHistoryClient;
3116
+ #clock;
3117
+ constructor(options) {
3118
+ this.#localHistoryClient = options.localHistoryClient;
3119
+ this.#clock = options.clock ?? (() => /* @__PURE__ */ new Date());
3120
+ }
3121
+ async collect() {
3122
+ const observedAt = this.#clock().toISOString();
3123
+ try {
3124
+ const requests = await this.#localHistoryClient.readHistory();
3125
+ return {
3126
+ provider: { id: this.id, displayName: this.displayName },
3127
+ billingDomains: [{ id: "local-history", displayName: "Local history" }],
3128
+ quotaBuckets: [],
3129
+ usage: requests.map(mapLocalUsage),
3130
+ usageReconciliation: {
3131
+ authoritativeIdPrefix: "opencode-local-request:",
3132
+ retiredIdPrefixes: []
3133
+ },
3134
+ costs: requests.flatMap(
3135
+ (request) => request.cost === null ? [] : [mapLocalCost(request, request.cost)]
3136
+ ),
3137
+ observedAt
3138
+ };
3139
+ } catch (error) {
3140
+ return {
3141
+ provider: { id: this.id, displayName: this.displayName },
3142
+ billingDomains: [{ id: "local-history", displayName: "Local history" }],
3143
+ quotaBuckets: [],
3144
+ usage: [],
3145
+ costs: [],
3146
+ warnings: [safeFailure3(error)],
3147
+ observedAt
3148
+ };
3149
+ }
3150
+ }
3151
+ };
3152
+ }
3153
+ });
3154
+
2992
3155
  // src/connectors/opencode-go/local-opencode-history-client.ts
2993
3156
  import { execFile as execFileCallback } from "child_process";
2994
3157
  import { createHash } from "crypto";
@@ -3077,12 +3240,27 @@ var init_local_opencode_history_client = __esm({
3077
3240
  #command;
3078
3241
  #execFile;
3079
3242
  #readDatabase;
3243
+ #activeRead = null;
3080
3244
  constructor(options = {}) {
3081
3245
  this.#command = options.command ?? "opencode";
3082
3246
  this.#execFile = options.execFile ?? executeOpenCode;
3083
3247
  this.#readDatabase = options.readDatabase ?? readDatabase;
3084
3248
  }
3085
- async readHistory() {
3249
+ readHistory() {
3250
+ if (this.#activeRead) return this.#activeRead;
3251
+ const activeRead = this.#readHistory();
3252
+ this.#activeRead = activeRead;
3253
+ activeRead.then(
3254
+ () => {
3255
+ if (this.#activeRead === activeRead) this.#activeRead = null;
3256
+ },
3257
+ () => {
3258
+ if (this.#activeRead === activeRead) this.#activeRead = null;
3259
+ }
3260
+ );
3261
+ return activeRead;
3262
+ }
3263
+ async #readHistory() {
3086
3264
  let databasePath;
3087
3265
  try {
3088
3266
  const { stdout } = await this.#execFile(this.#command, ["db", "path"]);
@@ -3113,8 +3291,9 @@ var init_local_opencode_history_client = __esm({
3113
3291
  { cause: error }
3114
3292
  );
3115
3293
  }
3116
- return completedAssistantRows.filter((row) => row.providerId === "opencode-go").filter(hasCategorizedTokens).map((row) => ({
3294
+ return completedAssistantRows.filter(hasCategorizedTokens).map((row) => ({
3117
3295
  id: `v2:${createHash("sha256").update(row.sourceId).digest("hex")}`,
3296
+ providerId: row.providerId,
3118
3297
  model: `${row.providerId}/${row.modelId}`,
3119
3298
  cost: row.cost,
3120
3299
  inputTokens: row.inputTokens,
@@ -3317,6 +3496,7 @@ function mapQuota2(response) {
3317
3496
  billingDomainId: "go-subscription",
3318
3497
  label: LIMITS[id].label,
3319
3498
  usedPercent: response.usage[id].percent,
3499
+ windowDurationMinutes: LIMITS[id].windowDurationMinutes,
3320
3500
  resetsAt: response.usage[id].resetsAt,
3321
3501
  authority: "official-account",
3322
3502
  scope: "account-wide",
@@ -3326,61 +3506,7 @@ function mapQuota2(response) {
3326
3506
  fallbackStatus: "unknown"
3327
3507
  }));
3328
3508
  }
3329
- function mapLocalUsage(request) {
3330
- return {
3331
- id: `opencode-request:${request.id}`,
3332
- billingDomainId: "go-subscription",
3333
- model: request.model,
3334
- observedAt: new Date(request.observedAtMs).toISOString(),
3335
- inputTokens: request.inputTokens,
3336
- outputTokens: request.outputTokens,
3337
- reasoningTokens: request.reasoningTokens,
3338
- cacheReadTokens: request.cacheReadTokens,
3339
- cacheWriteTokens: request.cacheWriteTokens,
3340
- tokenSemantics: {
3341
- reasoning: "separate",
3342
- cacheRead: "separate",
3343
- cacheWrite: "separate"
3344
- },
3345
- modelAttribution: "known",
3346
- timePrecision: "event",
3347
- usageScope: "this-mac",
3348
- aggregationTemporality: "delta",
3349
- authority: "local-observation"
3350
- };
3351
- }
3352
- function mapLocalCost(request, cost) {
3353
- const usageObservationId = `opencode-request:${request.id}`;
3354
- return {
3355
- id: `opencode-request-cost:${request.id}`,
3356
- sourceId: usageObservationId,
3357
- billingDomainId: "go-subscription",
3358
- observedAt: new Date(request.observedAtMs).toISOString(),
3359
- kind: "reported-estimate",
3360
- amount: cost,
3361
- currency: "USD",
3362
- authority: "local-observation",
3363
- model: request.model,
3364
- usageObservationId,
3365
- priceSnapshot: {
3366
- id: "opencode-message-reported-cost-v2",
3367
- version: "2026-08-28",
3368
- source: "OpenCode local message history reported cost",
3369
- canonicalModel: request.model,
3370
- effectiveAt: "2026-08-28T00:00:00.000Z",
3371
- effectiveUntil: null,
3372
- currency: "USD",
3373
- ratesPerMillion: {
3374
- input: null,
3375
- output: null,
3376
- reasoning: null,
3377
- "cache-read": null,
3378
- "cache-write": null
3379
- }
3380
- }
3381
- };
3382
- }
3383
- function safeFailure3(error) {
3509
+ function safeFailure4(error) {
3384
3510
  if (error instanceof Error && "code" in error && typeof error.code === "string" && "recovery" in error && typeof error.recovery === "string") {
3385
3511
  return { code: error.code, message: error.message, recovery: error.recovery };
3386
3512
  }
@@ -3395,9 +3521,9 @@ var init_opencode_go_connector = __esm({
3395
3521
  "src/connectors/opencode-go/opencode-go-connector.ts"() {
3396
3522
  "use strict";
3397
3523
  LIMITS = {
3398
- rolling: { label: "5 hour", amount: 12 },
3399
- weekly: { label: "Week", amount: 30 },
3400
- monthly: { label: "Month", amount: 60 }
3524
+ rolling: { label: "5 hour", amount: 12, windowDurationMinutes: 300 },
3525
+ weekly: { label: "Week", amount: 30, windowDurationMinutes: 10080 },
3526
+ monthly: { label: "Month", amount: 60, windowDurationMinutes: 43200 }
3401
3527
  };
3402
3528
  OpenCodeGoConnector = class {
3403
3529
  id = "opencode-go";
@@ -3418,24 +3544,21 @@ var init_opencode_go_connector = __esm({
3418
3544
  this.#localHistoryClient.readHistory()
3419
3545
  ]);
3420
3546
  const warnings = [];
3421
- if (accountResult.status === "rejected") warnings.push(safeFailure3(accountResult.reason));
3422
- if (localResult.status === "rejected") warnings.push(safeFailure3(localResult.reason));
3547
+ if (accountResult.status === "rejected") warnings.push(safeFailure4(accountResult.reason));
3548
+ if (localResult.status === "rejected") warnings.push(safeFailure4(localResult.reason));
3423
3549
  const account = accountResult.status === "fulfilled" ? accountResult.value : null;
3424
- const local = localResult.status === "fulfilled" ? localResult.value : [];
3425
3550
  return {
3426
3551
  provider: { id: this.id, displayName: this.displayName },
3427
3552
  billingDomains: [{ id: "go-subscription", displayName: "OpenCode Go subscription" }],
3428
3553
  quotaBuckets: account ? mapQuota2(account) : [],
3429
- usage: local.map(mapLocalUsage),
3554
+ usage: [],
3430
3555
  ...localResult.status === "fulfilled" ? {
3431
3556
  usageReconciliation: {
3432
3557
  authoritativeIdPrefix: "opencode-request:",
3433
3558
  retiredIdPrefixes: ["opencode-session:"]
3434
3559
  }
3435
3560
  } : {},
3436
- costs: local.flatMap(
3437
- (request) => request.cost === null ? [] : [mapLocalCost(request, request.cost)]
3438
- ),
3561
+ costs: [],
3439
3562
  warnings,
3440
3563
  observedAt
3441
3564
  };
@@ -3473,6 +3596,11 @@ function mapBillingQuota(billing) {
3473
3596
  billingDomainId: "grok-build-subscription",
3474
3597
  label: period.label,
3475
3598
  usedPercent,
3599
+ windowDurationMinutes: nativeWindowDurationMinutes(
3600
+ config.currentPeriod?.start ?? config.billingPeriodStart,
3601
+ resetsAt,
3602
+ period.id
3603
+ ),
3476
3604
  resetsAt,
3477
3605
  authority: "official-client",
3478
3606
  scope: "account-wide",
@@ -3480,6 +3608,16 @@ function mapBillingQuota(billing) {
3480
3608
  }
3481
3609
  ];
3482
3610
  }
3611
+ function nativeWindowDurationMinutes(startsAt, resetsAt, period) {
3612
+ const start = startsAt ? Date.parse(startsAt) : Number.NaN;
3613
+ const end = resetsAt ? Date.parse(resetsAt) : Number.NaN;
3614
+ if (Number.isFinite(start) && Number.isFinite(end) && end > start) {
3615
+ return Math.round((end - start) / 6e4);
3616
+ }
3617
+ if (period === "weekly") return 10080;
3618
+ if (period === "monthly") return 43200;
3619
+ return null;
3620
+ }
3483
3621
  function nativePeriod(type, fallback) {
3484
3622
  if (type === "USAGE_PERIOD_TYPE_WEEKLY") return { id: "weekly", label: "Weekly limit" };
3485
3623
  if (type === "USAGE_PERIOD_TYPE_MONTHLY" || fallback === "monthly") {
@@ -3491,7 +3629,7 @@ function derivePercent(used, limit) {
3491
3629
  if (used === void 0 || limit === void 0 || limit <= 0) return null;
3492
3630
  return Math.min(100, Math.max(0, used / limit * 100));
3493
3631
  }
3494
- function safeFailure4(error) {
3632
+ function safeFailure5(error) {
3495
3633
  if (error instanceof Error && "code" in error && typeof error.code === "string" && "recovery" in error && typeof error.recovery === "string") {
3496
3634
  return { code: error.code, message: error.message, recovery: error.recovery };
3497
3635
  }
@@ -3554,7 +3692,7 @@ var init_grok_build_connector = __esm({
3554
3692
  });
3555
3693
  }
3556
3694
  } catch (error) {
3557
- warnings.push(safeFailure4(error));
3695
+ warnings.push(safeFailure5(error));
3558
3696
  }
3559
3697
  const history = this.#historyClient ? await this.#historyClient.readUsage(options) : { usage: [], costs: [], complete: true };
3560
3698
  if (!history.complete) warnings.push(incompleteTranscriptFailure3());
@@ -3698,6 +3836,50 @@ import { open } from "fs/promises";
3698
3836
  import { homedir as homedir2 } from "os";
3699
3837
  import { join as join3 } from "path";
3700
3838
  import { z as z7 } from "zod";
3839
+ function billingIsFresh(billing, now) {
3840
+ if (!billing.sourceObservedAt) return false;
3841
+ const observedAt = Date.parse(billing.sourceObservedAt);
3842
+ if (!Number.isFinite(observedAt)) return false;
3843
+ return now.getTime() - observedAt <= GROK_BILLING_FRESHNESS_MS;
3844
+ }
3845
+ async function refreshBillingLogViaDashboard(command, timeoutMs) {
3846
+ if (process.platform !== "darwin") return;
3847
+ const refreshTimeoutMs = Math.min(timeoutMs, 6e3);
3848
+ const expectScript2 = [
3849
+ `set timeout ${Math.max(1, Math.ceil(refreshTimeoutMs / 1e3))}`,
3850
+ "log_user 0",
3851
+ "set command $env(AGENT_USAGE_GROK_REFRESH_COMMAND)",
3852
+ "spawn -noecho $command dashboard",
3853
+ `after ${Math.min(2e3, Math.max(250, refreshTimeoutMs - 1e3))}`,
3854
+ 'send "\\021\\021"',
3855
+ "expect eof"
3856
+ ].join("\n");
3857
+ await new Promise((resolve5) => {
3858
+ const dashboard = spawn3("/usr/bin/expect", ["-c", expectScript2], {
3859
+ env: {
3860
+ ...process.env,
3861
+ AGENT_USAGE_GROK_REFRESH_COMMAND: command,
3862
+ TERM: process.env.TERM ?? "xterm-256color"
3863
+ },
3864
+ stdio: ["ignore", "pipe", "pipe"]
3865
+ });
3866
+ dashboard.stdout.resume();
3867
+ dashboard.stderr.resume();
3868
+ let settled = false;
3869
+ const stopTimer = setTimeout(() => {
3870
+ dashboard.kill("SIGTERM");
3871
+ finish();
3872
+ }, refreshTimeoutMs);
3873
+ const finish = () => {
3874
+ if (settled) return;
3875
+ settled = true;
3876
+ clearTimeout(stopTimer);
3877
+ resolve5();
3878
+ };
3879
+ dashboard.once("error", finish);
3880
+ dashboard.once("exit", finish);
3881
+ });
3882
+ }
3701
3883
  function parseLatestBillingLog(text) {
3702
3884
  const lines = text.split(/\r?\n/);
3703
3885
  for (let index = lines.length - 1; index >= 0; index -= 1) {
@@ -3748,7 +3930,7 @@ function unavailableError3(cause) {
3748
3930
  { cause }
3749
3931
  );
3750
3932
  }
3751
- var GrokBillingAdapterError, StdioGrokBillingClient, JsonRpcError, JsonLinePeer2;
3933
+ var GrokBillingAdapterError, StdioGrokBillingClient, GROK_BILLING_FRESHNESS_MS, JsonRpcError, JsonLinePeer2;
3752
3934
  var init_stdio_grok_billing_client = __esm({
3753
3935
  "src/connectors/grok-build/stdio-grok-billing-client.ts"() {
3754
3936
  "use strict";
@@ -3768,6 +3950,8 @@ var init_stdio_grok_billing_client = __esm({
3768
3950
  #timeoutMs;
3769
3951
  #spawnProcess;
3770
3952
  #readUnifiedLog;
3953
+ #refreshBillingLog;
3954
+ #clock;
3771
3955
  constructor(options = {}) {
3772
3956
  this.#command = options.command ?? "grok";
3773
3957
  this.#timeoutMs = options.timeoutMs ?? 8e3;
@@ -3777,13 +3961,15 @@ var init_stdio_grok_billing_client = __esm({
3777
3961
  this.#readUnifiedLog = options.readUnifiedLog ?? (() => readLogTail(
3778
3962
  join3(process.env.GROK_HOME ?? join3(homedir2(), ".grok"), "logs", "unified.jsonl")
3779
3963
  ));
3964
+ this.#refreshBillingLog = options.refreshBillingLog ?? (options.readUnifiedLog ? async () => void 0 : () => refreshBillingLogViaDashboard(this.#command, this.#timeoutMs));
3965
+ this.#clock = options.clock ?? (() => /* @__PURE__ */ new Date());
3780
3966
  }
3781
3967
  async readBilling() {
3782
3968
  let process2;
3783
3969
  try {
3784
3970
  process2 = this.#spawnProcess(this.#command, ["agent", "--no-leader", "stdio"]);
3785
3971
  } catch (error) {
3786
- const fallback = await this.#readLogFallback();
3972
+ const fallback = await this.#readFreshLogFallback();
3787
3973
  if (fallback) return fallback;
3788
3974
  throw unavailableError3(error);
3789
3975
  }
@@ -3815,7 +4001,7 @@ var init_stdio_grok_billing_client = __esm({
3815
4001
  }
3816
4002
  return billing.data;
3817
4003
  } catch (error) {
3818
- const fallback = await this.#readLogFallback();
4004
+ const fallback = await this.#readFreshLogFallback();
3819
4005
  if (fallback) return fallback;
3820
4006
  if (error instanceof GrokBillingAdapterError) throw error;
3821
4007
  if (error instanceof JsonRpcError && error.code === -32601) {
@@ -3846,7 +4032,18 @@ var init_stdio_grok_billing_client = __esm({
3846
4032
  return null;
3847
4033
  }
3848
4034
  }
4035
+ async #readFreshLogFallback() {
4036
+ const cached = await this.#readLogFallback();
4037
+ if (cached && billingIsFresh(cached, this.#clock())) return cached;
4038
+ try {
4039
+ await this.#refreshBillingLog();
4040
+ } catch {
4041
+ return cached;
4042
+ }
4043
+ return await this.#readLogFallback() ?? cached;
4044
+ }
3849
4045
  };
4046
+ GROK_BILLING_FRESHNESS_MS = 5 * 60 * 1e3;
3850
4047
  JsonRpcError = class extends Error {
3851
4048
  code;
3852
4049
  constructor(body) {
@@ -4133,7 +4330,7 @@ function endpointFailure(error, label) {
4133
4330
  recovery: "Check network access and xAI status, then retry."
4134
4331
  };
4135
4332
  }
4136
- function safeFailure5(error) {
4333
+ function safeFailure6(error) {
4137
4334
  if (error instanceof Error && "code" in error && typeof error.code === "string" && "recovery" in error && typeof error.recovery === "string") {
4138
4335
  return { code: error.code, message: error.message, recovery: error.recovery };
4139
4336
  }
@@ -4388,7 +4585,7 @@ var init_xai_api_connector = __esm({
4388
4585
  costs: [],
4389
4586
  balances: [],
4390
4587
  invoices: [],
4391
- warnings: [safeFailure5(error)],
4588
+ warnings: [safeFailure6(error)],
4392
4589
  observedAt
4393
4590
  };
4394
4591
  }
@@ -5677,6 +5874,16 @@ async function runDatabaseWorker(workerData) {
5677
5874
  if (workerData.operation === 'indexes') {
5678
5875
  database.exec(workerData.indexesSql);
5679
5876
  parentPort.postMessage({ ok: true, data: null });
5877
+ } else if (workerData.operation === 'delete-demo-data') {
5878
+ database.exec('BEGIN IMMEDIATE');
5879
+ try {
5880
+ database.exec(workerData.deleteDemoDataSql);
5881
+ database.exec('COMMIT');
5882
+ parentPort.postMessage({ ok: true, data: null });
5883
+ } catch (error) {
5884
+ database.exec('ROLLBACK');
5885
+ throw error;
5886
+ }
5680
5887
  } else if (workerData.operation === 'delete-derived-costs') {
5681
5888
  database.prepare(workerData.deleteDerivedCostsSql).run();
5682
5889
  parentPort.postMessage({ ok: true, data: null });
@@ -5844,6 +6051,7 @@ function mapQuotaRow(row) {
5844
6051
  billingDomainId: row.billing_domain_id,
5845
6052
  label: row.label,
5846
6053
  usedPercent: row.used_percent,
6054
+ windowDurationMinutes: row.window_duration_minutes,
5847
6055
  resetsAt: row.resets_at,
5848
6056
  authority: row.authority,
5849
6057
  observedAt: row.observed_at,
@@ -6477,9 +6685,9 @@ function buildWorkbenchModelRanking(histories, buckets, comparisonCurrency, reco
6477
6685
  )
6478
6686
  );
6479
6687
  return {
6480
- byTokens: byTokens.slice(0, 5).map((entry) => entry.id),
6481
- byCost: byCost.slice(0, 5).map((entry) => entry.id),
6482
- byRetailEquivalent: byRetailEquivalent.slice(0, 5).map((entry) => entry.id),
6688
+ byTokens: byTokens.map((entry) => entry.id),
6689
+ byCost: byCost.map((entry) => entry.id),
6690
+ byRetailEquivalent: byRetailEquivalent.map((entry) => entry.id),
6483
6691
  entries: byTokens,
6484
6692
  unclassified
6485
6693
  };
@@ -6931,7 +7139,7 @@ function freshnessStatus(lastSuccessAt, now) {
6931
7139
  if (!lastSuccessAt) return "unavailable";
6932
7140
  return now.getTime() - new Date(lastSuccessAt).getTime() <= FRESHNESS_WINDOW_MS ? "fresh" : "stale";
6933
7141
  }
6934
- var FRESHNESS_WINDOW_MS, QUERY_INDEXES_SQL, DELETE_DERIVED_RETAIL_COSTS_SQL, DatabaseSync2, RETENTION_AGGREGATE_SQL, SqliteUsageRepository;
7142
+ var FRESHNESS_WINDOW_MS, QUERY_INDEXES_SQL, DELETE_DERIVED_RETAIL_COSTS_SQL, DELETE_DEMO_PROVIDER_DATA_SQL, DatabaseSync2, RETENTION_AGGREGATE_SQL, SqliteUsageRepository;
6935
7143
  var init_sqlite_usage_repository = __esm({
6936
7144
  "src/server/sqlite-usage-repository.ts"() {
6937
7145
  "use strict";
@@ -6964,6 +7172,12 @@ var init_sqlite_usage_repository = __esm({
6964
7172
  WHERE usage.provider_id = cost_records.provider_id
6965
7173
  AND usage.id = cost_records.usage_observation_id
6966
7174
  )
7175
+ `;
7176
+ DELETE_DEMO_PROVIDER_DATA_SQL = `
7177
+ DELETE FROM connector_diagnostics WHERE provider_id = 'demo';
7178
+ DELETE FROM connector_runtime WHERE id = 'demo';
7179
+ DELETE FROM connector_settings WHERE id = 'demo';
7180
+ DELETE FROM providers WHERE id = 'demo';
6967
7181
  `;
6968
7182
  ({ DatabaseSync: DatabaseSync2 } = createRequire2(import.meta.url)(
6969
7183
  "node:sqlite"
@@ -6992,8 +7206,10 @@ var init_sqlite_usage_repository = __esm({
6992
7206
  SqliteUsageRepository = class {
6993
7207
  #database;
6994
7208
  #databasePath;
6995
- constructor(databasePath) {
7209
+ #hideDemoProvider;
7210
+ constructor(databasePath, options = {}) {
6996
7211
  this.#databasePath = databasePath;
7212
+ this.#hideDemoProvider = options.hideDemoProvider ?? false;
6997
7213
  mkdirSync(dirname3(databasePath), { recursive: true });
6998
7214
  this.#database = new DatabaseSync2(databasePath);
6999
7215
  this.#database.exec("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
@@ -7041,13 +7257,15 @@ var init_sqlite_usage_repository = __esm({
7041
7257
  }
7042
7258
  const quotaStatement = this.#database.prepare(
7043
7259
  `INSERT INTO quota_buckets (
7044
- provider_id, id, billing_domain_id, label, used_percent, resets_at, authority, observed_at,
7260
+ provider_id, id, billing_domain_id, label, used_percent, window_duration_minutes,
7261
+ resets_at, authority, observed_at,
7045
7262
  scope, status, limit_amount, limit_currency, fallback_status
7046
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7263
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
7047
7264
  ON CONFLICT(provider_id, id) DO UPDATE SET
7048
7265
  billing_domain_id = excluded.billing_domain_id,
7049
7266
  label = excluded.label,
7050
7267
  used_percent = excluded.used_percent,
7268
+ window_duration_minutes = excluded.window_duration_minutes,
7051
7269
  resets_at = excluded.resets_at,
7052
7270
  authority = excluded.authority,
7053
7271
  observed_at = excluded.observed_at,
@@ -7064,6 +7282,7 @@ var init_sqlite_usage_repository = __esm({
7064
7282
  bucket.billingDomainId,
7065
7283
  bucket.label,
7066
7284
  bucket.usedPercent,
7285
+ bucket.windowDurationMinutes ?? null,
7067
7286
  bucket.resetsAt,
7068
7287
  bucket.authority,
7069
7288
  snapshot2.observedAt,
@@ -7480,7 +7699,10 @@ var init_sqlite_usage_repository = __esm({
7480
7699
  `SELECT id, display_name, last_success_at, last_error, last_error_code, last_recovery
7481
7700
  FROM providers ORDER BY id`
7482
7701
  ).all();
7483
- const overviews = providers.map((provider) => this.#getProviderOverview(provider, now, query));
7702
+ const visibleProviders = this.#hideDemoProvider ? providers.filter((provider) => provider.id !== "demo") : providers;
7703
+ const overviews = visibleProviders.map(
7704
+ (provider) => this.#getProviderOverview(provider, now, query)
7705
+ );
7484
7706
  const riskSummary = buildRiskSummary(overviews);
7485
7707
  return {
7486
7708
  generatedAt: now.toISOString(),
@@ -7720,6 +7942,13 @@ var init_sqlite_usage_repository = __esm({
7720
7942
  throw error;
7721
7943
  }
7722
7944
  }
7945
+ async deleteDemoProviderDataAsync() {
7946
+ await runDatabaseWorker({
7947
+ databasePath: this.#databasePath,
7948
+ operation: "delete-demo-data",
7949
+ deleteDemoDataSql: DELETE_DEMO_PROVIDER_DATA_SQL
7950
+ });
7951
+ }
7723
7952
  deleteDerivedRetailCosts() {
7724
7953
  this.#database.prepare(DELETE_DERIVED_RETAIL_COSTS_SQL).run();
7725
7954
  }
@@ -7823,7 +8052,8 @@ var init_sqlite_usage_repository = __esm({
7823
8052
  }
7824
8053
  #getBillingDomainOverview(providerId, domain, now, query, forecasts, forecastCoverage, degradedDiagnostic, legacyProviderFailure = null) {
7825
8054
  const quotaRows = this.#database.prepare(
7826
- `SELECT id, billing_domain_id, label, used_percent, resets_at, authority, observed_at,
8055
+ `SELECT id, billing_domain_id, label, used_percent, window_duration_minutes, resets_at,
8056
+ authority, observed_at,
7827
8057
  scope, status, limit_amount, limit_currency, fallback_status
7828
8058
  FROM quota_buckets WHERE provider_id = ? AND billing_domain_id = ? ORDER BY id`
7829
8059
  ).all(providerId, domain.id);
@@ -8238,6 +8468,7 @@ var init_sqlite_usage_repository = __esm({
8238
8468
  billing_domain_id TEXT NOT NULL,
8239
8469
  label TEXT NOT NULL,
8240
8470
  used_percent REAL,
8471
+ window_duration_minutes INTEGER,
8241
8472
  resets_at TEXT,
8242
8473
  authority TEXT NOT NULL,
8243
8474
  observed_at TEXT NOT NULL,
@@ -8581,6 +8812,7 @@ var init_sqlite_usage_repository = __esm({
8581
8812
  for (const [name, type] of [
8582
8813
  ["scope", "TEXT"],
8583
8814
  ["status", "TEXT"],
8815
+ ["window_duration_minutes", "INTEGER"],
8584
8816
  ["limit_amount", "REAL"],
8585
8817
  ["limit_currency", "TEXT"],
8586
8818
  ["fallback_status", "TEXT"]
@@ -8606,17 +8838,21 @@ import { isAbsolute as isAbsolute3, join as join8, resolve as resolve3 } from "p
8606
8838
  import { fileURLToPath } from "url";
8607
8839
  async function runDaemon(home) {
8608
8840
  await mkdir4(home, { recursive: true, mode: 448 });
8609
- const repository = new SqliteUsageRepository(join8(home, "usage.sqlite"));
8841
+ const demoEnabled = process.env.AGENT_USAGE_DEMO === "1";
8842
+ const repository = new SqliteUsageRepository(join8(home, "usage.sqlite"), {
8843
+ hideDemoProvider: !demoEnabled
8844
+ });
8610
8845
  const keychainService = process.env.AGENT_USAGE_KEYCHAIN_SERVICE;
8611
8846
  const launchAgentLabel = process.env.AGENT_USAGE_LAUNCH_AGENT_LABEL;
8612
8847
  const nodeImport = process.env.AGENT_USAGE_NODE_IMPORT;
8613
8848
  const secretStore = new MacOsKeychainSecretStore(void 0, {
8614
8849
  service: keychainService
8615
8850
  });
8851
+ const openCodeLocalHistoryClient = new CliOpenCodeLocalHistoryClient();
8616
8852
  const application = new UsageApplication({
8617
8853
  repository,
8618
8854
  connectors: [
8619
- ...process.env.AGENT_USAGE_DEMO === "1" ? [createDemoConnector()] : [],
8855
+ ...demoEnabled ? [createDemoConnector()] : [],
8620
8856
  new CodexConnector(
8621
8857
  new StdioCodexAccountClient(),
8622
8858
  void 0,
@@ -8630,8 +8866,9 @@ async function runDaemon(home) {
8630
8866
  accountClient: new OfficialOpenCodeGoClient({
8631
8867
  authReader: new OpenCodeAuthFileReader()
8632
8868
  }),
8633
- localHistoryClient: new CliOpenCodeLocalHistoryClient()
8869
+ localHistoryClient: openCodeLocalHistoryClient
8634
8870
  }),
8871
+ new OpenCodeLocalConnector({ localHistoryClient: openCodeLocalHistoryClient }),
8635
8872
  new GrokBuildConnector({
8636
8873
  billingClient: new StdioGrokBillingClient(),
8637
8874
  historyClient: localTranscriptClient("grok", home)
@@ -8655,11 +8892,11 @@ async function runDaemon(home) {
8655
8892
  ...keychainService ? { AGENT_USAGE_KEYCHAIN_SERVICE: keychainService } : {},
8656
8893
  ...launchAgentLabel ? { AGENT_USAGE_LAUNCH_AGENT_LABEL: launchAgentLabel } : {},
8657
8894
  ...nodeImport ? { AGENT_USAGE_NODE_IMPORT: nodeImport } : {},
8658
- ...process.env.AGENT_USAGE_DEMO === "1" ? { AGENT_USAGE_DEMO: "1" } : {}
8895
+ ...demoEnabled ? { AGENT_USAGE_DEMO: "1" } : {}
8659
8896
  }
8660
8897
  }),
8661
8898
  connectorPolicies: Object.fromEntries(
8662
- ["codex", "claude-code", "opencode-go", "grok", "xai-api"].map((id) => [
8899
+ ["codex", "claude-code", "opencode-go", "opencode", "grok", "xai-api"].map((id) => [
8663
8900
  id,
8664
8901
  { minimumIntervalMs: 5 * 60 * 1e3, timeoutMs: id === "claude-code" ? 25e3 : 2e4 }
8665
8902
  ])
@@ -8687,6 +8924,13 @@ async function runDaemon(home) {
8687
8924
  origin: server.origin,
8688
8925
  apiToken: server.apiToken
8689
8926
  });
8927
+ if (!demoEnabled) {
8928
+ void repository.deleteDemoProviderDataAsync().catch(() => {
8929
+ process.stderr.write(
8930
+ "Agent Usage: stale demo data remains hidden and will be cleaned on a later startup.\n"
8931
+ );
8932
+ });
8933
+ }
8690
8934
  process.stderr.write(`Agent Usage: web service ready at ${server.origin}
8691
8935
  `);
8692
8936
  process.stderr.write("Agent Usage: updating cached usage in the background\u2026\n");
@@ -8788,6 +9032,7 @@ var init_runtime = __esm({
8788
9032
  init_claude_usage_screen_client();
8789
9033
  init_codex_connector();
8790
9034
  init_stdio_codex_account_client();
9035
+ init_opencode_local_connector();
8791
9036
  init_local_opencode_history_client();
8792
9037
  init_official_opencode_go_client();
8793
9038
  init_opencode_auth_reader();