ai-usagebar 1.32.0

Omarchy/Waybar widgets + TUI for tracking multi-provider AI plan usage
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
// Pure data shaping for the Omarchy Quattro widget. Keep this file free of
// QML globals so the exact report contract and selection behavior can also be
// exercised by Node in CI.

function cleanText(value, maxLength) {
  var text = value === undefined || value === null ? "" : String(value)
  // The Rust projection already strips terminal controls. This second, cheap
  // boundary keeps hand-authored/older JSON from putting controls in a
  // long-lived shell process.
  text = text.replace(/[\t\r]/g, " ")
    .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g, "")
    .replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/g, "")
  var limit = Number(maxLength) || 2048
  if (text.length <= limit) return text
  var end = limit - 1
  var finalCodeUnit = text.charCodeAt(end - 1)
  if (finalCodeUnit >= 0xd800 && finalCodeUnit <= 0xdbff) end--
  return text.slice(0, end) + "…"
}

// Shared Omarchy components use Text.AutoText. Replace angle brackets before
// passing provider-controlled labels into those components so they can never
// be reclassified as rich text (including an image tag with a remote URL).
function autoTextSafe(value) {
  return cleanText(value, 1000)
    .replace(/[\n\u2028\u2029]/g, " ")
    .replace(/</g, "‹")
    .replace(/>/g, "›")
}

function finitePercent(value) {
  var number = Number(value)
  if (!isFinite(number)) return null
  return Math.max(0, Math.min(100, Math.round(number)))
}

function normalizeSection(raw) {
  if (!raw || typeof raw !== "object") return null
  var type = String(raw.type || "")
  if (type === "spacer") return { type: "spacer" }
  if (type === "metric") {
    var percent = finitePercent(raw.percent)
    if (percent === null) return null
    var severity = String(raw.severity || "")
    if (["low", "mid", "high", "critical"].indexOf(severity) < 0)
      severity = percent >= 90 ? "critical" : percent >= 75 ? "high" : percent >= 50 ? "mid" : "low"
    var windowSecs = Math.floor(Number(raw.window_secs))
    if (!isFinite(windowSecs) || windowSecs <= 0) windowSecs = null
    // Which number the bar draws. Anything but an explicit "value" — including
    // a report old enough not to carry the field — leaves it a percentage.
    var headline = raw.headline === "value" ? "value" : "percent"
    return {
      type: "metric",
      label: cleanText(raw.label, 160),
      percent: percent,
      value: cleanText(raw.value, 240),
      detail: cleanText(raw.detail, 1000),
      headline: headline,
      severity: severity,
      reset_at: cleanText(raw.reset_at, 80),
      window_secs: windowSecs,
      group: cleanText(raw.group, 80)
    }
  }
  if (type === "text") {
    var text = {
      type: "text",
      label: cleanText(raw.label, 160),
      value: cleanText(raw.value, 1000)
    }
    // Cursor's On-Demand row. Kept only as safe integers so a report cannot
    // smuggle a string or a float in where the meter expects cents.
    var used = minorUnits(raw.used_cents)
    var limit = minorUnits(raw.limit_cents)
    var consumed = minorUnits(raw.percent)
    if (used !== null) text.used_cents = used
    if (limit !== null && limit > 0) text.limit_cents = limit
    if (consumed !== null && consumed >= 0) text.percent = consumed
    return text
  }
  if (type === "block") {
    var body = Array.isArray(raw.body) ? raw.body : []
    var lines = []
    for (var i = 0; i < body.length && i < 24; i++) lines.push(cleanText(body[i], 1000))
    return { type: "block", label: cleanText(raw.label, 160), body: lines }
  }
  return null
}

function normalizeEntry(raw) {
  if (!raw || typeof raw !== "object") return null
  var id = cleanText(raw.id, 180).trim()
  if (id === "") return null
  var sourceSections = Array.isArray(raw.sections) ? raw.sections : []
  var sections = []
  for (var i = 0; i < sourceSections.length && i < 96; i++) {
    var section = normalizeSection(sourceSections[i])
    if (section) sections.push(section)
  }
  var error = raw.error === undefined || raw.error === null ? "" : cleanText(raw.error, 1200)
  return {
    id: id,
    name: cleanText(raw.name, 240),
    display_name: cleanText(raw.display_name, 240),
    short_name: cleanText(raw.short_name, 24),
    icon: cleanText(raw.icon, 8).trim(),
    brand: cleanText(raw.brand, 32).trim(),
    plan: cleanText(raw.plan, 240),
    status: error !== "" || raw.status === "error" ? "error" : "ready",
    error: error,
    stale: raw.stale === true,
    fetched_at: cleanText(raw.fetched_at, 80),
    sections: sections
  }
}

function parseReport(raw) {
  try {
    var parsed = JSON.parse(String(raw || ""))
    if (!parsed || !Array.isArray(parsed.entries))
      return { ok: false, error: "The usage command returned an unsupported report.", primary: "", entries: [] }
    var entries = []
    for (var i = 0; i < parsed.entries.length && i < 64; i++) {
      var entry = normalizeEntry(parsed.entries[i])
      if (entry) entries.push(entry)
    }
    if (parsed.entries.length > 0 && entries.length === 0)
      return { ok: false, error: "The usage report did not contain a valid provider entry.", primary: "", entries: [] }
    return { ok: true, error: "", primary: cleanText(parsed.primary, 180).trim(), entries: entries }
  } catch (error) {
    return { ok: false, error: "The usage command returned invalid JSON.", primary: "", entries: [] }
  }
}

function baseProvider(id) {
  return String(id || "").split("@")[0]
}

function providerName(entry) {
  if (!entry) return "AI usage"
  // The Rust report owns canonical product names. `name` is the compatible
  // fallback for older binaries; the machine id is only a last resort.
  var title = cleanText(entry.display_name || entry.name, 240).trim()
  if (title === "") title = baseProvider(entry.id).replace(/_/g, " ") || "AI usage"
  return autoTextSafe(title)
}

// The Waybar-style provider tag. `VendorId::short_name` in Rust owns the codes
// and ships them as `short_name`; a binary older than that field has none, so
// the machine id's vendor half stands in rather than a table living here.
function providerShort(entry) {
  if (!entry) return ""
  var code = cleanText(entry.short_name, 24).trim()
  if (code === "") code = baseProvider(entry.id).replace(/_/g, "-")
  return autoTextSafe(code).trim()
}

function providerIcon(entry) {
  if (!entry) return "ó°š©"
  var icon = autoTextSafe(cleanText(entry.icon, 8).trim())
  return icon === "" ? "ó°š©" : icon
}

function filteredEntries(entries, configuredProvider) {
  var list = Array.isArray(entries) ? entries : []
  var wanted = String(configuredProvider || "").trim().toLowerCase()
  if (wanted === "") return list.slice()
  var exact = list.filter(function(entry) { return String(entry.id).toLowerCase() === wanted })
  if (exact.length > 0) return exact
  return list.filter(function(entry) { return baseProvider(entry.id).toLowerCase() === wanted })
}

function selectedIndex(entries, selectedId) {
  var list = Array.isArray(entries) ? entries : []
  for (var i = 0; i < list.length; i++) if (list[i].id === selectedId) return i
  return list.length > 0 ? 0 : -1
}

function preferredEntryId(entries, primaryProvider, rememberedEntryId) {
  var list = Array.isArray(entries) ? entries : []
  if (list.length === 0) return ""
  var remembered = cleanText(rememberedEntryId, 180).trim().toLowerCase()
  for (var r = 0; r < list.length; r++)
    if (String(list[r].id).toLowerCase() === remembered) return list[r].id
  var primary = String(primaryProvider || "").toLowerCase()
  for (var i = 0; i < list.length; i++)
    if (String(list[i].id).toLowerCase() === primary) return list[i].id
  for (var j = 0; j < list.length; j++)
    if (baseProvider(list[j].id).toLowerCase() === primary) return list[j].id
  return list[0].id
}

function settingsWithOverrides(settings, moduleName, overrides) {
  var moduleId = cleanText(moduleName, 180).trim()
  if (moduleId === "" || !overrides || typeof overrides !== "object" || Array.isArray(overrides))
    return null

  var next = { id: moduleId }
  var current = settings && typeof settings === "object" && !Array.isArray(settings)
    ? settings : {}
  for (var key in current) {
    if (key === "id" || key === "__proto__" || key === "constructor" || key === "prototype")
      continue
    next[key] = current[key]
  }
  for (var overrideKey in overrides) {
    if (overrideKey === "id" || overrideKey === "__proto__" || overrideKey === "constructor"
        || overrideKey === "prototype") continue
    next[overrideKey] = overrides[overrideKey]
  }
  return next
}

function settingsWithSelectedEntry(settings, moduleName, entryId) {
  var selected = cleanText(entryId, 180).trim()
  if (selected === "") return null
  return settingsWithOverrides(settings, moduleName, { lastSelectedEntryId: selected })
}

function booleanSetting(value, fallback) {
  if (value === true || value === false) return value
  var normalized = String(value === undefined || value === null ? "" : value).trim().toLowerCase()
  if (["true", "1", "yes", "on"].indexOf(normalized) >= 0) return true
  if (["false", "0", "no", "off"].indexOf(normalized) >= 0) return false
  return fallback === true
}

// `providerLabel` is already resolved by the caller: empty when the opt-in
// provider switch is off, so the icon-and-value label is unchanged for everyone
// who never turns it on. A vertical bar has no width for either field and
// keeps showing the icon alone.
function barLabel(alarming, vertical, showValue, loading, hasEntry, summaryText,
                  providerLabel, icon) {
  icon = autoTextSafe(icon || "").trim() || "ó°š©"
  if (vertical) return alarming ? "ó°…™" : icon
  if (loading && !hasEntry) return icon + "  …"
  if (!hasEntry) return alarming ? "ó°…™" : icon
  var provider = autoTextSafe(providerLabel).trim()
  var summary = showValue ? autoTextSafe(summaryText).trim() : ""
  if (provider === "") return summary === "" ? icon : icon + "  " + summary
  // One space between tag and value, matching Waybar's
  // `{vendor_short} {session_pct}%`; the wider gap stays next to the icon.
  return summary === "" ? icon + "  " + provider
    : icon + "  " + provider + " " + summary
}

function barChip(entry, showValue, showProvider, barWindow) {
  if (!entry) return ""
  var icon = providerIcon(entry)
  var provider = showProvider ? providerShort(entry) : ""
  var summary = ""
  if (showValue) {
    if (entry.error) summary = "!"
    else summary = autoTextSafe(headline(entry, barWindow).text).trim()
  }
  if (provider === "") return summary === "" ? icon : icon + "  " + summary
  return summary === "" ? icon + "  " + provider : icon + "  " + provider + " " + summary
}

// Every visible entry as its own icon+value chip. A vertical bar has no
// width for the strip and keeps a single glyph, same as `barLabel`.
function barStrip(entries, alarming, vertical, showValue, showProvider, loading, barWindow) {
  var list = Array.isArray(entries) ? entries : []
  if (vertical) return alarming ? "ó°…™" : "ó°š©"
  if (loading && list.length === 0) return "󰚩  …"
  if (list.length === 0) return alarming ? "ó°…™" : "ó°š©"
  var chips = []
  for (var i = 0; i < list.length; i++) {
    var chip = barChip(list[i], showValue, showProvider, barWindow)
    if (chip !== "") chips.push(chip)
  }
  return chips.length === 0 ? "ó°š©" : chips.join("  ")
}

function anyAlarming(entries) {
  var list = Array.isArray(entries) ? entries : []
  for (var i = 0; i < list.length; i++) {
    if (isAlarming(list[i])) return true
  }
  return false
}

// The mark an entry is drawn with. The report names the provider — its own
// for a built-in, the one a `[[custom]]` provider borrowed through `brand` —
// and this file owns the artwork, because each frontend ships its own. An
// older binary sends no `brand`, so the id still resolves the built-ins.
function brandIconFile(entry) {
  var declared = cleanText(entry && entry.brand, 32).trim()
  return brandFileFor(declared !== "" ? declared : baseProvider(entry && entry.id))
}

// Official brand marks shipped next to this file. A missing file falls back
// to the nerd-font glyph from the Rust report — the table is asset lookup,
// not a second copy of provider names.
function brandFileFor(provider) {
  switch (provider) {
    case "anthropic":
      return "claude.svg"
    case "anthropic_api":
      return "anthropic.svg"
    case "openai":
      return "openai.svg"
    case "copilot":
      return "copilot.svg"
    case "zai":
      return "zhipu.svg"
    case "openrouter":
      return "openrouter.svg"
    case "deepseek":
      return "deepseek.svg"
    case "kimi":
      return "kimi.svg"
    case "kilo":
      return "kilo.svg"
    case "novita":
      return "novita.svg"
    case "moonshot":
      return "moonshot.svg"
    case "grok":
    case "supergrok":
      return "grok.svg"
    case "grokbot":
      return "grokbot.svg"
    case "antigravity":
      return "antigravity.svg"
    case "cursor":
      return "cursor.svg"
    case "minimax":
      return "minimax.svg"
    case "kiro":
      return "kiro.svg"
    case "nous":
      return "nous.svg"
    case "opencode-go":
      return "opencode.svg"
    default:
      return ""
  }
}

function barChips(entries, selected, showAll, showValue, showProvider, loading, alarming, vertical, barWindow) {
  var list = Array.isArray(entries) ? entries : []
  if (vertical) {
    return [{ brand: "", icon: alarming ? "ó°…™" : "ó°š©", label: "", alarming: alarming === true }]
  }
  if (loading && list.length === 0) {
    return [{ brand: "", icon: "󰚩", label: "…", alarming: false }]
  }
  if (list.length === 0) {
    return [{ brand: "", icon: alarming ? "ó°…™" : "ó°š©", label: "", alarming: alarming === true }]
  }
  var shown = showAll ? list : list.filter(function(entry) { return selected && entry.id === selected.id })
  if (shown.length === 0) shown = [list[0]]
  var chips = []
  for (var i = 0; i < shown.length; i++) {
    var entry = shown[i]
    var label = ""
    if (showProvider) label = providerShort(entry)
    if (showValue) {
      var summary = entry.error ? "!" : autoTextSafe(headline(entry, barWindow).text).trim()
      label = label === "" ? summary : (summary === "" ? label : label + " " + summary)
    }
    var brand = brandIconFile(entry)
    chips.push({
      // The bar turns each chip into a target for its own entry.
      id: entry.id,
      brand: brand,
      icon: brand !== "" ? providerIcon(entry) : providerShort(entry),
      label: label,
      // Alert state always follows the highest-percent window, never the
      // pinned one: barWindow changes only the displayed value.
      alarming: isAlarming(entry)
    })
  }
  return chips
}

// The bar presses a slot's widget by geometry: it maps the point into every
// registered click target and takes the newest one whose rect contains it,
// falling back to the slot's button. A chip that registered only its glyph left
// the button to swallow the rest of the slot, so a press aimed at a chip above,
// below or beside it toggled whichever entry was already selected. Each chip
// therefore registers its whole column of the slot, and the gaps between chips
// split at their midpoint: the first and last chips own half of the gap beside
// them, a middle chip a whole one. The outer columns also own the button's
// padding at either end (`edge`), so the columns tile the whole widget and its
// width stays exactly what the plain spacing and padding produced.
function chipHitGaps(index, count, gap, edge) {
  var half = (Number(gap) || 0) / 2
  var outer = Number(edge) || 0
  var chips = Number(count) || 0
  var position = Number(index) || 0
  return {
    left: position === 0 ? outer : half,
    right: position >= chips - 1 ? outer : half
  }
}

// Which usage window the top bar shows. "auto" keeps the historical
// highest-percent metric; the rest pin one window class across vendors.
// Unknown, empty, and legacy values fall back to "auto" so an existing
// shell.json never goes blank after an update.
function normalizeBarWindow(value) {
  var text = cleanText(value, 24).trim().toLowerCase()
  if (text === "" || text === "auto" || text === "highest" || text === "max") return "auto"
  if (text === "session" || text === "5h" || text === "5-hour" || text === "5hour"
      || text === "5hr" || text === "five-hour" || text === "rolling"
      || text === "shortest" || text === "session-5h") return "session"
  if (text === "weekly" || text === "week" || text === "7d" || text === "7-day"
      || text === "weekly-7d") return "weekly"
  if (text === "monthly" || text === "month" || text === "30d" || text === "monthly-cycle") return "monthly"
  return "auto"
}

// The two window lengths the report states exactly. Same values as the Rust
// constants that publish them: openai/types.rs SESSION_WINDOW_SECS /
// WEEKLY_WINDOW_SECS, opencode_go/vendor.rs and kimi/vendor.rs ROLLING_WINDOW /
// WEEKLY_WINDOW, anthropic/types.rs SESSION / WEEKLY. A vendor that states any
// other length falls through to label matching instead of being forced into
// one of these classes.
var SESSION_WINDOW_SECS = 18000
var WEEKLY_WINDOW_SECS = 604800

function metricMatchesWindow(section, want) {
  if (!section || section.type !== "metric") return false
  var label = String(section.label || "")
  var secs = Math.floor(Number(section.window_secs))
  var hasSecs = isFinite(secs) && secs > 0
  var knownSize = hasSecs && (secs === SESSION_WINDOW_SECS || secs === WEEKLY_WINDOW_SECS)
  // A known size is authoritative; an unknown positive size is treated as
  // missing so labels decide. Labels only cover older reports that predate
  // window_secs.
  if (want === "session") {
    if (knownSize) return secs === SESSION_WINDOW_SECS
    return /(\b5\s*-?\s*h(?:ours?|rs?)?\b|\bsessions?\b|\brolling\b)/i.test(label)
  }
  if (want === "weekly") {
    if (knownSize) return secs === WEEKLY_WINDOW_SECS
    return /(\bweek(?:ly|s)?\b|\b7\s*-?\s*d(?:ays?)?\b)/i.test(label)
  }
  if (want === "monthly") {
    // Monthly pools have no single fixed length (opencode-go publishes
    // none; Z.AI uses 30d; Cursor/custom vary), so no secs value is
    // authoritative here — except known 5h/7d sizes, which exclude.
    if (knownSize) return false
    return /(\bmonthly\b|\bmonth(?:ly|s)?\b|\bspend\s*\(mo\)|\b30\s*-?\s*d(?:ays?)?\b)/i.test(label)
  }
  return false
}

function maxPercent(sections) {
  var best = null
  for (var i = 0; i < sections.length; i++) {
    var section = sections[i]
    if (section.type === "metric" && (!best || section.percent > best.percent)) best = section
  }
  return best
}

function selectMetric(entry, barWindow) {
  var sections = entry && Array.isArray(entry.sections) ? entry.sections : []
  var metrics = []
  var grouped = []
  for (var i = 0; i < sections.length; i++) {
    var section = sections[i]
    if (!section || section.type !== "metric") continue
    // A grouped row sits under its own heading below the meters (the Claude
    // entry's context sessions, SuperGrok's product slices). It is not a
    // quota window, so it stands in only when the entry has nothing else.
    if (section.group) grouped.push(section)
    else metrics.push(section)
  }
  if (metrics.length === 0) metrics = grouped
  if (metrics.length === 0) return null
  var want = normalizeBarWindow(barWindow)
  if (want === "auto") return maxPercent(metrics)
  var candidates = []
  for (var j = 0; j < metrics.length; j++) {
    if (metricMatchesWindow(metrics[j], want)) candidates.push(metrics[j])
  }
  // A pinned window that a vendor does not offer (a balance-only provider,
  // a weekly-only response, no monthly pool) falls back to the historical
  // highest-percent value rather than blanking the bar.
  if (candidates.length === 0) return maxPercent(metrics)
  return maxPercent(candidates)
}

function severityRank(severity) {
  if (severity === "critical") return 3
  if (severity === "high") return 2
  if (severity === "mid") return 1
  return 0
}

// One Dark defaults — same hexes as src/theme.rs when colors.toml is missing.
var ONE_DARK_PALETTE = {
  green: "#98c379",
  yellow: "#e5c07b",
  orange: "#d19a66",
  red: "#e06c75"
}

// Parse Omarchy theme/colors.toml keys used for RAG (Waybar Theme's source).
// Named keys win over the older color1–3 aliases, matching theme.rs
// merged_with_omarchy after #289 (red.or(color1), not last-occurrence-wins).
// orange falls back to the resolved red when absent.
function parseThemePalette(raw) {
  var greenNamed = ""
  var greenAlias = ""
  var yellowNamed = ""
  var yellowAlias = ""
  var orangeNamed = ""
  var redNamed = ""
  var redAlias = ""
  var lines = String(raw || "").split("\n")
  for (var i = 0; i < lines.length; i++) {
    var match = lines[i].match(/^\s*([A-Za-z0-9_-]+)\s*=\s*["']?(#[0-9A-Fa-f]{6})/)
    if (!match) continue
    var key = match[1]
    var hex = match[2]
    if (key === "green") greenNamed = hex
    else if (key === "color2") greenAlias = hex
    else if (key === "yellow") yellowNamed = hex
    else if (key === "color3") yellowAlias = hex
    else if (key === "orange") orangeNamed = hex
    else if (key === "red") redNamed = hex
    else if (key === "color1") redAlias = hex
  }
  var red = redNamed || redAlias
  var green = greenNamed || greenAlias
  var yellow = yellowNamed || yellowAlias
  var orange = orangeNamed || red
  return {
    green: green || ONE_DARK_PALETTE.green,
    yellow: yellow || ONE_DARK_PALETTE.yellow,
    orange: orange || ONE_DARK_PALETTE.orange,
    red: red || ONE_DARK_PALETTE.red
  }
}

function severityColor(severity, palette) {
  var p = palette || ONE_DARK_PALETTE
  if (severity === "critical") return p.red
  if (severity === "high") return p.orange
  if (severity === "mid") return p.yellow
  if (severity === "low") return p.green
  return p.green
}

// Older reports print On-Demand as "$0.00 / $5.00" and nothing else. A
// current report carries used_cents, limit_cents, and percent, which win.
// This parser stays for a binary that predates those fields.
function parseMoneyToken(token) {
  var text = String(token || "").trim()
  var match = text.match(/^(-)?(\D*?)(\d+(?:\.\d+)?)(\D*)$/)
  if (!match) return null
  var amount = Number(match[3])
  if (!isFinite(amount)) return null
  if (match[1] === "-") amount = -amount
  var places = (match[3].split(".")[1] || "").length
  return { amount: amount, prefix: match[2], suffix: match[4], places: places }
}

function minorUnits(value) {
  if (typeof value !== "number" || !isFinite(value) || !Number.isSafeInteger(value)) return null
  return value
}

// USD cents, matching fmt_minor(..., 2, "USD"): the sign sits ahead of the
// symbol, and a zero amount is never "-$0.00".
function formatUsdCents(cents) {
  var negative = cents < 0
  var abs = negative ? -cents : cents
  var dollars = Math.floor(abs / 100)
  var frac = abs % 100
  var body = dollars + "." + (frac < 10 ? "0" : "") + frac
  if (dollars === 0 && frac === 0) negative = false
  return (negative ? "-" : "") + "$" + body
}

function formatMoney(sample, amount) {
  var negative = amount < 0
  var abs = Math.abs(amount)
  var body = sample.places > 0 ? abs.toFixed(sample.places) : String(Math.round(abs))
  return (negative ? "-" : "") + sample.prefix + body + sample.suffix
}

function usageSeverity(percent) {
  if (percent >= 90) return "critical"
  if (percent >= 75) return "high"
  if (percent >= 50) return "mid"
  return "low"
}

function onDemandView(usedPct, usedText, limitText, leftText) {
  return {
    bar: usedPct + "%",
    usedPct: usedPct,
    severity: usageSeverity(usedPct),
    display: leftText,
    detail: usedText + " of " + limitText + " used (" + usedPct + "%)",
    tooltip: "On-demand " + usedText + " of " + limitText + " used (" + usedPct + "%)"
  }
}

// Same reading as OpenRouter's credit chip: the percentage is how much of
// the prepaid balance is already used. The dollars still left stay beside
// the meter in the panel. Cents from the report are the contract; the
// formatted value is only read when those fields are absent.
function onDemandFromCents(section) {
  var used = minorUnits(section.used_cents)
  var limit = minorUnits(section.limit_cents)
  if (used === null || limit === null || !(limit > 0)) return null
  var usedPct = minorUnits(section.percent)
  if (usedPct === null || usedPct < 0)
    usedPct = Math.round((Math.max(0, used) / limit) * 100)
  var spent = Math.max(0, used)
  var left = Math.max(0, limit - used)
  return onDemandView(usedPct, formatUsdCents(spent), formatUsdCents(limit), formatUsdCents(left))
}

function onDemandFromText(value) {
  var text = String(value || "")
  var slash = text.indexOf("/")
  if (slash < 0) return null
  var used = parseMoneyToken(text.slice(0, slash))
  var limit = parseMoneyToken(text.slice(slash + 1))
  if (!used || !limit || !(limit.amount > 0)) return null
  var factor = Math.pow(10, limit.places)
  var left = Math.max(0, Math.round((limit.amount - used.amount) * factor) / factor)
  var usedPct = Math.round((Math.max(0, used.amount) / limit.amount) * 100)
  var usedText = formatMoney(used, Math.max(0, used.amount))
  var limitText = formatMoney(limit, limit.amount)
  var leftText = formatMoney(limit, left)
  return onDemandView(usedPct, usedText, limitText, leftText)
}

function onDemandRemaining(section) {
  if (section && typeof section === "object") {
    var fromCents = onDemandFromCents(section)
    if (fromCents) return fromCents
    return onDemandFromText(section.value)
  }
  return onDemandFromText(section)
}

function cursorOnDemand(entry) {
  var sections = entry && Array.isArray(entry.sections) ? entry.sections : []
  for (var i = 0; i < sections.length; i++) {
    var section = sections[i]
    if (section && section.type === "text" && section.label === "On-Demand")
      return onDemandRemaining(section)
  }
  return null
}

function cursorPoolPresence(entry) {
  var sections = entry && Array.isArray(entry.sections) ? entry.sections : []
  var models = false
  var other = false
  for (var i = 0; i < sections.length; i++) {
    var section = sections[i]
    if (!section || section.type !== "metric") continue
    if (section.label === "Cursor Models") models = true
    else if (section.label === "Other Models") other = true
  }
  return {
    models: models,
    other: other,
    demand: cursorOnDemand(entry) !== null,
    credits: cursorGrantMeters(sections).length > 0
  }
}

// Fixed display order. A missing or unknown flag stays on, and turning the
// last one off is refused so the bar never goes blank.
function cursorPoolVisibility(flags) {
  var models = !(flags && flags.models === false)
  var other = !(flags && flags.other === false)
  var demand = !(flags && flags.demand === false)
  var credits = !(flags && flags.credits === false)
  if (!models && !other && !demand && !credits) models = true
  return { models: models, other: other, demand: demand, credits: credits }
}

function toggleCursorPool(flags, id) {
  var current = cursorPoolVisibility(flags)
  var next = {
    models: current.models,
    other: current.other,
    demand: current.demand,
    credits: current.credits
  }
  if (id === "models") next.models = !next.models
  else if (id === "other") next.other = !next.other
  else if (id === "demand") next.demand = !next.demand
  else if (id === "credits") next.credits = !next.credits
  else return current
  if (!next.models && !next.other && !next.demand && !next.credits) return current
  return next
}

// Flags the chip can actually draw. A switch whose pool is absent (on-demand
// with no prepaid row) does not count, and when that would leave the bar
// blank the first pool that does exist stays on. Models win that fallback.
function cursorBarFlags(entry, flags) {
  var show = cursorPoolVisibility(flags)
  var has = cursorPoolPresence(entry)
  var visible = {
    models: show.models && has.models,
    other: show.other && has.other,
    demand: show.demand && has.demand,
    credits: show.credits && has.credits
  }
  if (!visible.models && !visible.other && !visible.demand && !visible.credits) {
    if (has.models) visible.models = true
    else if (has.other) visible.other = true
    else if (has.demand) visible.demand = true
    else if (has.credits) visible.credits = true
  }
  return visible
}

// A spending-page grant is a meter beside the two model pools and On-Demand.
// Its label is the grant's own name, so it is every Cursor metric that is
// not one of those two pools.
function cursorGrantMeters(sections) {
  var parts = []
  for (var i = 0; i < sections.length; i++) {
    var section = sections[i]
    if (!section || section.type !== "metric") continue
    if (section.label === "Cursor Models" || section.label === "Other Models") continue
    var label = section.label ? String(section.label) : "Credits"
    parts.push({
      text: section.percent + "%",
      line: label + " · " + section.percent + "%",
      percent: section.percent,
      severity: section.severity
    })
  }
  return parts
}

// Cursor's included usage is two model pools, not two time windows, so the
// 5-hour / weekly / monthly pin does not describe them. Visible pools stay in
// dashboard order: Cursor Models, then Other Models, then prepaid on-demand
// as a used percentage, the same way OpenRouter shows a credit balance.
// Severity follows whichever visible pool is furthest along.
function cursorDualHeadline(entry, flags) {
  if (baseProvider(entry && entry.id) !== "cursor") return null
  var sections = Array.isArray(entry.sections) ? entry.sections : []
  var auto = null
  var api = null
  for (var i = 0; i < sections.length; i++) {
    var section = sections[i]
    if (!section || section.type !== "metric") continue
    if (section.label === "Cursor Models") auto = section
    else if (section.label === "Other Models") api = section
  }
  if (!auto || !api) return null
  var show = cursorBarFlags(entry, flags)
  var demand = cursorOnDemand(entry)
  var parts = []
  if (show.models) parts.push({
    text: auto.percent + "%",
    line: "Cursor Models · " + auto.percent + "%",
    percent: auto.percent,
    severity: auto.severity,
    pool: "models"
  })
  if (show.other) parts.push({
    text: api.percent + "%",
    line: "Cursor Other Models · " + api.percent + "%",
    percent: api.percent,
    severity: api.severity,
    pool: "other"
  })
  if (show.demand && demand) parts.push({
    text: demand.bar,
    line: "Cursor On Demand · " + demand.usedPct + "%",
    percent: demand.usedPct,
    severity: demand.severity,
    pool: "demand"
  })
  if (show.credits) {
    var grants = cursorGrantMeters(sections)
    for (var g = 0; g < grants.length; g++) parts.push(grants[g])
  }
  if (parts.length === 0) {
    parts.push({
      text: auto.percent + "%",
      line: "Cursor Models · " + auto.percent + "%",
      percent: auto.percent,
      severity: auto.severity,
      pool: "models"
    })
  }
  var worse = parts[0]
  for (var p = 1; p < parts.length; p++) {
    var part = parts[p]
    if (part.percent > worse.percent
        || (part.percent === worse.percent && severityRank(part.severity) > severityRank(worse.severity)))
      worse = part
  }
  var texts = []
  var lines = []
  var segments = []
  var tooltipRows = []
  for (var n = 0; n < parts.length; n++) {
    texts.push(parts[n].text)
    lines.push(parts[n].line)
    if (n > 0) segments.push({ text: " · ", severity: "" })
    segments.push({ text: parts[n].text, severity: parts[n].severity })
    tooltipRows.push({
      text: parts[n].line,
      severity: parts[n].severity,
      pool: parts[n].pool || "",
      percent: parts[n].percent
    })
  }
  var text = texts.join(" · ")
  var tooltip = lines.join("\n")
  var allCritical = parts.length > 0
  for (var c = 0; c < parts.length; c++) {
    if (parts[c].severity !== "critical") {
      allCritical = false
      break
    }
  }
  return {
    text: text,
    tooltip: tooltip,
    segments: segments,
    tooltipRows: tooltipRows,
    percent: worse.percent,
    severity: worse.severity,
    // Icon / button chrome: only when every visible pool is critical, so a
    // single exhausted pool does not paint the brand mark while siblings are fine.
    allCritical: allCritical,
    label: "Cursor Models · Other Models"
  }
}

function headline(entry, barWindow) {
  if (!entry) return { text: "", percent: null, severity: "low", label: "" }
  var dual = cursorDualHeadline(entry)
  if (dual) return dual
  var best = selectMetric(entry, barWindow)
  if (best) {
    // The metric names which of its two numbers goes on the bar; the other one
    // stays in the detail. Reading that beats guessing from the label, which
    // put OpenRouter's dollar figure on the bar and hid its consumed percent.
    // An older report omits the field, and a metric is a percentage by default.
    var bestText = best.headline === "value" && best.value !== ""
      ? best.value : best.percent + "%"
    return {
      text: bestText,
      percent: best.percent,
      severity: best.severity,
      label: best.label
    }
  }
  var sections = entry.sections || []
  for (var j = 0; j < sections.length; j++) {
    var row = sections[j]
    if (row.type === "text" && /(balance|available|spend|prepaid)/i.test(row.label) && row.value !== "")
      return { text: row.value, percent: null, severity: "low", label: row.label }
  }
  return { text: entry.status === "error" ? "Error" : "Ready", percent: null, severity: "low", label: "" }
}

function isAlarming(entry) {
  if (!entry) return false
  var summary = headline(entry)
  // Cached and failed fetches stay visible without turning the bar red on their own.
  return summary.severity === "critical"
}

function formatDuration(milliseconds) {
  if (!(milliseconds > 0)) return "now"
  var minutes = Math.floor(milliseconds / 60000)
  var hours = Math.floor(minutes / 60)
  var days = Math.floor(hours / 24)
  if (days > 0) return days + "d " + (hours % 24) + "h"
  if (hours > 0) return hours + "h " + (minutes % 60) + "m"
  return Math.max(1, minutes) + "m"
}

var MONTH_NAMES = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
                   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

function pad2(value) {
  return ("0" + value).slice(-2)
}

function isSameLocalDay(a, b) {
  return a.getFullYear() === b.getFullYear()
    && a.getMonth() === b.getMonth()
    && a.getDate() === b.getDate()
}

function formatReset(resetAt, nowMs) {
  if (!resetAt) return ""
  var resetMs = new Date(String(resetAt)).getTime()
  if (!isFinite(resetMs)) return ""
  var remaining = resetMs - Number(nowMs)
  if (remaining <= 0) return "Reset due"
  // Show the real local clock time the window reopens, so the absolute
  // reset moment is visible next to the countdown. Date it whenever it
  // lands on another day: a bare "03:00" on an 18h countdown reads as a
  // time that has already passed, which is the ambiguity this row exists
  // to remove. Keyed on the calendar day rather than on "is it 24h away",
  // because tonight's reset crosses midnight long before it crosses 24h.
  var at = new Date(resetMs)
  var clock = pad2(at.getHours()) + ":" + pad2(at.getMinutes())
  if (!isSameLocalDay(at, new Date(Number(nowMs))))
    clock = MONTH_NAMES[at.getMonth()] + " " + at.getDate() + " " + clock
  return "Resets in " + formatDuration(remaining) + " · " + clock
}

function formatUpdated(fetchedAt, nowMs) {
  if (!fetchedAt) return "Updated time unavailable"
  var fetchedMs = new Date(String(fetchedAt)).getTime()
  if (!isFinite(fetchedMs)) return "Updated time unavailable"
  var elapsed = Math.max(0, Number(nowMs) - fetchedMs)
  if (elapsed < 60000) return "Updated just now"
  return "Updated " + formatDuration(elapsed) + " ago"
}

function metricDetail(row) {
  var detail = cleanText(row && row.detail, 1000)
  if (!row || !row.reset_at) return detail
  // Older human-readable reset text remains useful to CLI consumers. Strip
  // just that fragment in the native panel, which renders a live countdown.
  detail = detail.replace(/^Resets in [^·]+\s*(?:·\s*)?/i, "")
  detail = detail.replace(/\s*·\s*reset\s+[^·]+$/i, "")
  return detail.trim()
}

// The report marks sub-rows with a group (SuperGrok's product slices under
// "Breakdown"). Render each group as a heading row — an empty-value text row,
// which DetailRow draws through its section-header path — followed by that
// group's metrics, so slices read as a breakdown of the meter above them
// instead of peers of it. Ungrouped sections pass through untouched, and a
// group heading appears once no matter how many rows carry it.
function groupedSections(sections) {
  var rows = Array.isArray(sections) ? sections : []
  var out = []
  var seen = {}
  for (var i = 0; i < rows.length; i++) {
    var row = rows[i]
    if (row && row.type === "metric") {
      var group = String(row.group || "")
      if (group !== "" && !seen[group]) {
        seen[group] = true
        out.push({ type: "text", label: group, value: "" })
      }
    }
    if (row && row.type === "text" && row.label === "On-Demand") {
      var left = onDemandRemaining(row)
      if (left) row = {
        type: "metric",
        label: row.label,
        percent: left.usedPct,
        value: left.display,
        headline: "percent",
        detail: left.detail,
        severity: left.severity,
        reset_at: "",
        window_secs: null,
        group: ""
      }
    }
    out.push(row)
  }
  return out
}

function errorMessage(value) {
  var message = cleanText(value, 500).trim()
  return message === "" ? "The usage command failed without an error message." : message
}

// The panel launches ai-usagebar through /usr/bin/env, so a missing binary
// comes back as exit 127 instead of the process simply never starting.
// Quickshell does not emit `exited` when it cannot launch a binary directly --
// it only logs an internal warning -- which used to leave the widget stuck on
// its loading state with no way to explain that the binary was not installed.
function launchErrorMessage(exitCode, stderrText) {
  if (Number(exitCode) === 127)
    return "ai-usagebar is not installed. The plugin is only the display frontend. Install the binary with: omarchy pkg aur add ai-usagebar-bin"
  return errorMessage(stderrText)
}

function settingsId(value) {
  var id = cleanText(value, 80).trim()
  if (!/^[a-z0-9_-]+$/.test(id)
      || id === "__proto__" || id === "constructor" || id === "prototype") return ""
  return id
}

// The Rust bridge deliberately returns only key-presence booleans. Keep this
// parser strict so a compromised/older helper cannot smuggle rich text or an
// unbounded model into the long-lived shell process.
function parseSettingsSnapshot(raw) {
  try {
    var parsed = JSON.parse(String(raw || ""))
    if (!parsed || Number(parsed.schema_version) !== 1
        || !Array.isArray(parsed.primary_choices) || !Array.isArray(parsed.keys))
      return { ok: false, error: "The settings command returned an unsupported response.", primary: "", primary_choices: [], keys: [], vendors: [] }

    var choices = []
    for (var i = 0; i < parsed.primary_choices.length && i < 64; i++) {
      var choice = parsed.primary_choices[i]
      var choiceId = settingsId(choice && choice.id)
      if (choiceId === "") continue
      choices.push({ id: choiceId, value: choiceId, label: cleanText(choice.label, 120) || choiceId })
    }

    var keys = []
    for (var j = 0; j < parsed.keys.length && j < 32; j++) {
      var key = parsed.keys[j]
      var keyId = settingsId(key && key.id)
      if (keyId === "") continue
      keys.push({
        id: keyId,
        label: cleanText(key.label, 120) || keyId,
        environment: cleanText(key.environment, 160),
        secret_label: cleanText(key.secret_label, 120),
        note: cleanText(key.note, 240),
        configured: key.configured === true,
        inline_configured: key.inline_configured === true,
        environment_configured: key.environment_configured === true
      })
    }

    // Provider on/off switches (#244). An older binary sends no vendors list;
    // the section simply stays hidden rather than failing the whole form.
    var vendors = []
    if (Array.isArray(parsed.vendors)) {
      for (var v = 0; v < parsed.vendors.length && v < 64; v++) {
        var vendor = parsed.vendors[v]
        var vendorId = settingsId(vendor && vendor.id)
        if (vendorId === "") continue
        vendors.push({
          id: vendorId,
          label: cleanText(vendor.label, 120) || vendorId,
          enabled: vendor.enabled === true
        })
      }
    }

    var primary = settingsId(parsed.primary)
    var primaryAvailable = false
    for (var k = 0; k < choices.length; k++) {
      if (choices[k].id === primary) {
        primaryAvailable = true
        break
      }
    }
    if (!primaryAvailable) primary = choices.length > 0 ? choices[0].id : ""
    return { ok: true, error: "", primary: primary, primary_choices: choices, keys: keys, vendors: vendors }
  } catch (error) {
    return { ok: false, error: "The settings command returned invalid JSON.", primary: "", primary_choices: [], keys: [], vendors: [] }
  }
}

// Build the stdin patch for `settings apply`. `vendorToggles` (#244) is an
// optional array of {id, enabled}; it is included in the payload only when a
// toggle is pending, so a display-only save keeps the older patch shape a
// pre-#244 binary still accepts.
function buildSettingsPatch(primary, changes, vendorToggles) {
  var primaryId = settingsId(primary)
  var rawPrimary = String(primary || "").trim()
  if (rawPrimary !== "" && primaryId === "")
    return { ok: false, error: "Choose a valid primary provider.", payload: "" }
  var keys = {}
  var list = Array.isArray(changes) ? changes : []
  var seen = []
  for (var i = 0; i < list.length; i++) {
    var change = list[i] || {}
    var id = settingsId(change.id)
    if (id === "" || seen.indexOf(id) >= 0)
      return { ok: false, error: "A settings row has an invalid provider id.", payload: "" }
    seen.push(id)
    if (change.action === "clear") {
      keys[id] = { action: "clear" }
    } else if (change.action === "set") {
      var value = String(change.value || "")
      if (value === "") return { ok: false, error: "An edited credential is empty.", payload: "" }
      if (value.length > 16384) return { ok: false, error: "A credential is too long.", payload: "" }
      keys[id] = { action: "set", value: value }
    } else return { ok: false, error: "A settings row has an invalid action.", payload: "" }
  }
  var vendors = {}
  var toggles = Array.isArray(vendorToggles) ? vendorToggles : []
  var seenVendors = []
  for (var t = 0; t < toggles.length; t++) {
    var toggle = toggles[t] || {}
    var vendorId = settingsId(toggle.id)
    if (vendorId === "" || seenVendors.indexOf(vendorId) >= 0)
      return { ok: false, error: "A provider switch has an invalid provider id.", payload: "" }
    if (toggle.enabled !== true && toggle.enabled !== false)
      return { ok: false, error: "A provider switch needs an on or off state.", payload: "" }
    seenVendors.push(vendorId)
    vendors[vendorId] = toggle.enabled
  }
  if (primaryId === "" && seen.length === 0 && seenVendors.length === 0)
    return { ok: false, error: "There are no settings changes to save.", payload: "" }
  var patch = { schema_version: 1, keys: keys }
  if (primaryId !== "") patch.primary = primaryId
  if (seenVendors.length > 0) patch.vendors = vendors
  return {
    ok: true,
    error: "",
    payload: JSON.stringify(patch)
  }
}

function parseSettingsApplyResult(raw) {
  try {
    var parsed = JSON.parse(String(raw || ""))
    return parsed && parsed.ok === true
  } catch (error) {
    return false
  }
}