agent-dag 1.48.0 → 3.0.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.
@@ -18,7 +18,7 @@
18
18
  // readout the loudest producer in the application. So this is a plain poll
19
19
  // endpoint, exactly like /api/quota and /api/codex-usage already are.
20
20
  import { spawn } from "node:child_process";
21
- import { readFile } from "node:fs/promises";
21
+ import { readdir, readFile } from "node:fs/promises";
22
22
  import os from "node:os";
23
23
 
24
24
  /** CPU is the metric with spikes, so it is sampled often enough to catch one. */
@@ -41,6 +41,18 @@ let swap = null;
41
41
  const cpuHistory = [];
42
42
  let memory = null;
43
43
  let memInFlight = false;
44
+ let thermal = null;
45
+ let thermalTimer = null;
46
+ let thermalInFlight = false;
47
+ /** Consecutive readings that came back with nothing. See THERMAL_GIVE_UP. */
48
+ let thermalMisses = 0;
49
+ /** Whether this machine has EVER answered. See sampleThermal. */
50
+ let thermalEverAnswered = false;
51
+ /** Minute buckets, oldest first, for every section that keeps a history.
52
+ * See HISTORY_MINUTES. */
53
+ const history = [];
54
+ /** When sampling started, so a modal can say what "since" means. */
55
+ let historySince = 0;
44
56
 
45
57
  /** Total and idle jiffies across every core, as one pair. */
46
58
  function readTicks() {
@@ -112,13 +124,14 @@ function cpuPercent() {
112
124
  }
113
125
 
114
126
  /**
115
- * The locale every child of this module is parsed in.
127
+ * The locale every child of this module runs in — and only the part of it that
128
+ * had to be forced.
116
129
  *
117
- * Not a preference — a correctness requirement. Every command spawned here has
118
- * its output read by a regex, and every one of those regexes reads a number
119
- * with a `.` in it. `ps` and `sysctl` honour LC_NUMERIC, so on a machine set to
120
- * de_DE, fr_FR, ru_RU or pt_BR — comma is the decimal separator for most of
121
- * Europe and Latin America — the same commands print:
130
+ * Not a preference. Every command spawned here has its output read by a regex
131
+ * and every one of those regexes reads a number with a `.` in it. `ps` and
132
+ * `sysctl` honour LC_NUMERIC, so on a machine set to de_DE, fr_FR, ru_RU or
133
+ * pt_BR — comma is the decimal separator for most of Europe and Latin America —
134
+ * the same commands print:
122
135
  *
123
136
  * ps 1 0,2 0,0 /sbin/launchd
124
137
  * sysctl total = 8192,00M used = 7189,75M free = 1002,25M
@@ -126,20 +139,42 @@ function cpuPercent() {
126
139
  * and the parsers matched nothing at all. Not partially: `parsePsProcesses`
127
140
  * `continue`s on every row, so the process panel was permanently empty, and
128
141
  * `swapFromSysctl` returned null, so the macOS swap meter was permanently
129
- * blank. Silently, with nothing in the log, on a machine where everything else
130
- * worked.
142
+ * blank. Silently, on a machine where everything else worked.
131
143
  *
132
- * Forcing the locale rather than teaching the parsers to read a comma is the
133
- * fix that scales: it makes the OUTPUT invariant, which is what every parser
134
- * here was written against and what every parser added later will assume. The
135
- * comma tolerance below is defence in depth for the case where a sandbox strips
136
- * the environment, not the primary answer.
144
+ * THIS USED TO FORCE THE WHOLE LOCALE, and forcing the whole locale also forces
145
+ * the CHARACTER SET. Under `LC_ALL=C`, `ps` escapes every byte it cannot render
146
+ * as ASCII, so an application named in Cyrillic came back as
147
+ *
148
+ * M-PM-/M-PM-=M-PM-4M-PM-5M-PM-:M-QM^A M-PM^\M-QM^CM-PM-7M-QM^KM-PM-:M-PM-0
149
+ *
150
+ * where the name is `Яндекс Музыка`. The panel truncates at 164px so it read as
151
+ * noise; the process list added in #738 has room for all ninety-one characters
152
+ * of it, which is how it was found. Every reader with a non-Latin application
153
+ * on their machine was being shown that.
154
+ *
155
+ * So only the numeric is forced now, and the character set is inherited. All
156
+ * four measured on this machine:
157
+ *
158
+ * LC_ALL=C name mangled, 0.7
159
+ * LC_ALL="" LC_NUMERIC=C Яндекс Музыка, 0.7
160
+ * LANG=de_DE + our override Яндекс Музыка, 0.7 ← the comma case
161
+ * LC_ALL=de_DE + our empty LC_ALL 0.7 ← a hostile env
162
+ *
163
+ * The empty `LC_ALL` is doing real work in the last of those: POSIX ignores an
164
+ * empty LC_ALL, so clearing it is what stops a user's own LC_ALL from
165
+ * outranking the LC_NUMERIC below. Setting LC_NUMERIC alone would not survive
166
+ * it.
167
+ *
168
+ * A reader whose own locale is C still sees the escaped form — but so does
169
+ * their terminal, so that is their machine being consistent rather than this
170
+ * module choosing for them.
137
171
  *
138
172
  * Meaningless on Windows, where the branches are PowerShell piped through
139
173
  * ConvertTo-Json and already culture-invariant — and harmless there for the
140
- * same reason.
174
+ * same reason. The comma tolerance in the parsers stays as defence in depth for
175
+ * a sandbox that strips the environment, not as the primary answer.
141
176
  */
142
- const C_LOCALE = { LC_ALL: "C", LANG: "C" };
177
+ const C_LOCALE = { LC_ALL: "", LC_NUMERIC: "C" };
143
178
 
144
179
  /** Run a command and resolve its stdout, or null. Never rejects, never inherits
145
180
  * a shell, never inherits a locale, and is killed rather than allowed to hang
@@ -299,9 +334,48 @@ async function readSwap(platform = process.platform) {
299
334
  return null;
300
335
  }
301
336
 
302
- /** How many rows the process list keeps. Enough to see what is eating the
303
- * machine, few enough that the panel never becomes a scroll. */
304
- const TOP_N = 8;
337
+ /**
338
+ * How far down each ranking the payload reaches.
339
+ *
340
+ * The panel draws eight rows and decides their order on the client (#739), so
341
+ * whichever column it ranks by has to be rankable from the rows it was handed.
342
+ * `ps` returns a CPU-sorted list, and cutting that at eight and then sorting
343
+ * those eight by memory produced a table that was honest about its rows and
344
+ * wrong about its question: the machine's heaviest memory consumer need never
345
+ * have appeared in a CPU top eight at all. Same shape as #492 — a list that is
346
+ * never empty, never errors, and is not the rows being asked for.
347
+ *
348
+ * So what goes over the wire is a candidate SET rather than a ranking.
349
+ * pickCandidates takes this many by CPU and this many by memory and sends the
350
+ * union, which makes the true top eight of either column present by
351
+ * construction. Wide enough that drawing more rows later cannot quietly
352
+ * re-break that, small enough that the whole thing stays a few kilobytes of
353
+ * four-field rows, fetched only while the panel is open.
354
+ */
355
+ const CANDIDATE_N = 40;
356
+
357
+ /**
358
+ * The rows worth sending, given that the ordering happens on the client.
359
+ *
360
+ * A union of two rankings, deduplicated by object identity rather than by pid:
361
+ * parseGetProcessJson falls back to pid 0 for a row whose `Id` did not parse,
362
+ * more than one row can do that, and a pid-keyed set would drop real processes
363
+ * in order to deduplicate a placeholder.
364
+ *
365
+ * An unknown CPU sorts last here, for the same reason the column prints a dash
366
+ * rather than a zero — a Windows first reading has no percentage yet, and
367
+ * unknown is not idle and is not busiest either. Such a row still reaches the
368
+ * payload through the memory half, which is the reading that does exist on that
369
+ * pass.
370
+ */
371
+ export function pickCandidates(rows, limit = CANDIDATE_N) {
372
+ const byCpu = [...rows].sort((a, b) => (b.cpu ?? -1) - (a.cpu ?? -1) || b.mem - a.mem);
373
+ const byMem = [...rows].sort((a, b) => b.mem - a.mem || (b.cpu ?? -1) - (a.cpu ?? -1));
374
+ const out = byCpu.slice(0, limit);
375
+ const seen = new Set(out);
376
+ for (const r of byMem.slice(0, limit)) if (!seen.has(r)) out.push(r);
377
+ return out;
378
+ }
305
379
 
306
380
  /**
307
381
  * The `ps` argument list, which is not the same list on both Unixes.
@@ -349,10 +423,17 @@ export function psArgs(platform = process.platform) {
349
423
  *
350
424
  * There is no row limit in the query because neither `ps` has one and `run`
351
425
  * deliberately never inherits a shell, so there is no `| head` to pipe into.
352
- * The loop below stops at `limit` instead, which costs one parse of a string
353
- * we have already paid to read.
426
+ *
427
+ * And there is none by default here either, which is a change: the loop used to
428
+ * stop at eight, and stopping at eight is what made the memory ranking a lie
429
+ * once the panel could ask for one (#739). Selection belongs to pickCandidates,
430
+ * which cannot rank a column out of rows this function has already thrown away.
431
+ * The cost is a regex over every line of `ps` — a few hundred on a busy
432
+ * machine, once every four seconds and only while the panel is open — against a
433
+ * string that has already been read and allocated. `limit` stays for callers
434
+ * that do want a truncation, which is now only the tests.
354
435
  */
355
- export function parsePsProcesses(text, limit = TOP_N) {
436
+ export function parsePsProcesses(text, limit = Infinity) {
356
437
  const lines = String(text ?? "").trim().split("\n");
357
438
  const out = [];
358
439
  for (const line of lines.slice(1)) { // drop the header row
@@ -430,7 +511,7 @@ export function parseGetProcessJson(json, totalMem) {
430
511
  * 0-100 convention (see cpuPercent) is a different question with a different
431
512
  * answer, and the only way this drifts back is if a core count is in reach.
432
513
  */
433
- export function cpuFromDeltas(rows, prev, elapsedMs, limit = TOP_N) {
514
+ export function cpuFromDeltas(rows, prev, elapsedMs, limit = Infinity) {
434
515
  const secs = elapsedMs / 1000;
435
516
  const out = rows.map(r => {
436
517
  const before = prev instanceof Map ? prev.get(r.pid) : undefined;
@@ -460,7 +541,7 @@ let prevProcAt = 0;
460
541
 
461
542
  /** The run producing the next list, and the last one that finished. */
462
543
  let procInFlight = null;
463
- let procLast = null; // { at, procs }
544
+ let procLast = null; // { at, read: { procs, total } }
464
545
 
465
546
  /**
466
547
  * How old a finished reading may be and still answer a caller.
@@ -494,7 +575,7 @@ const PROC_MIN_GAP_MS = 1_500;
494
575
  */
495
576
  export async function readProcesses(platform = process.platform) {
496
577
  const now = Date.now();
497
- if (procLast && now - procLast.at < PROC_MIN_GAP_MS) return procLast.procs;
578
+ if (procLast && now - procLast.at < PROC_MIN_GAP_MS) return procLast.read;
498
579
  if (procInFlight) return procInFlight;
499
580
  // Only a real reading is remembered. Every failure inside readProcessesNow —
500
581
  // a spawn that never started, a non-zero exit, the timeout — resolves to an
@@ -504,9 +585,9 @@ export async function readProcesses(platform = process.platform) {
504
585
  // instead. The in-flight share still applies, so a burst arriving during a
505
586
  // failing read is one failing child, not a burst of them.
506
587
  procInFlight = readProcessesNow(platform)
507
- .then(procs => {
508
- if (procs.length) procLast = { at: Date.now(), procs };
509
- return procs;
588
+ .then(read => {
589
+ if (read.procs.length) procLast = { at: Date.now(), read };
590
+ return read;
510
591
  })
511
592
  .finally(() => { procInFlight = null; });
512
593
  return procInFlight;
@@ -521,13 +602,593 @@ async function readProcessesNow(platform) {
521
602
  if (!out) return [];
522
603
  const rows = parseGetProcessJson(out.trim(), os.totalmem());
523
604
  const now = Date.now();
524
- const result = cpuFromDeltas(rows, prevProcCpu, now - prevProcAt);
605
+ const ranked = cpuFromDeltas(rows, prevProcCpu, now - prevProcAt);
525
606
  prevProcCpu = new Map(rows.filter(r => r.cpuSec != null).map(r => [r.pid, r.cpuSec]));
526
607
  prevProcAt = now;
527
- return result;
608
+ return { procs: pickCandidates(ranked), total: ranked.length };
528
609
  }
529
610
  const out = await run("ps", psArgs(platform), 4_000);
530
- return out ? parsePsProcesses(out) : [];
611
+ if (!out) return { procs: [], total: 0 };
612
+ const all = parsePsProcesses(out);
613
+ return { procs: pickCandidates(all), total: all.length };
614
+ }
615
+
616
+ // ---------------------------------------------------------------------------
617
+ // Thermal: is this machine getting hot, and is it being held back for it.
618
+ //
619
+ // The section the load average cannot answer. A saturated machine that is cool
620
+ // is a machine doing work; a saturated machine that is thermally limited is one
621
+ // where the next agent you launch makes everything slower, and `67.27 82.98
622
+ // 74.19` reads identically in both cases.
623
+ //
624
+ // THREE PLATFORMS ANSWER THREE DIFFERENT QUESTIONS, and on one of them the
625
+ // honest answer is not a temperature at all. Everything below was measured on
626
+ // the machines available rather than taken from documentation, and the negative
627
+ // results are recorded here because they are the reason the shape is what it
628
+ // is:
629
+ //
630
+ // Linux /sys/class/hwmon/hwmon*/temp*_input, millidegrees Celsius, with
631
+ // the chip in `name` and the sensor in `temp*_label`. A plain file
632
+ // read, exactly like /proc/meminfo — no subprocess, and the chip
633
+ // publishes its own `temp*_max` and `temp*_crit`, so the warning
634
+ // bands are the hardware's rather than ones invented here.
635
+ // /sys/class/thermal/thermal_zone*/ is the coarser fallback.
636
+ //
637
+ // macOS No CPU degrees without root, verified: `powermetrics --samplers
638
+ // smc` answers "powermetrics must be invoked as the superuser", and
639
+ // `ioreg -c AppleSMC -r -d 1` publishes no temperature key at all to
640
+ // an unprivileged process. Asking a dashboard for a password every
641
+ // ten seconds is not an option, and this deck does not ship a
642
+ // kernel driver.
643
+ //
644
+ // But the GPU driver does publish one, and nothing said so: the
645
+ // accelerator's PerformanceStatistics carries "Temperature(C)"
646
+ // beside its clock, its activity and its power. Read live on an
647
+ // Intel Mac with an AMD card — 60, 60, 61 over four seconds, from
648
+ // `ioreg -r -k PerformanceStatistics` in 51ms. Apple Silicon's
649
+ // AGXAccelerator publishes the same dictionary WITHOUT that key, so
650
+ // there the parser finds nothing and no row is drawn, which is the
651
+ // correct outcome rather than a special case.
652
+ //
653
+ // And `pmset -g therm` is unprivileged, instant, and present on
654
+ // both architectures. What it reports is not heat but the
655
+ // consequence of heat: CPU_Speed_Limit, the share of the CPU's speed
656
+ // the thermal manager is currently allowing. That is arguably the
657
+ // more useful of the two readings — a temperature is a number you
658
+ // have to interpret, a speed limit is the thing you were trying to
659
+ // interpret it into.
660
+ //
661
+ // `sysctl machdep.xcpm.cpu_thermal_level` is deliberately unused. It
662
+ // is live (33, then 42, then 41 over three seconds) but it is
663
+ // Intel-only and an undocumented scale, and printing it as though it
664
+ // were degrees would be exactly the lie this module refuses.
665
+ //
666
+ // Windows MSAcpi_ThermalZoneTemperature in root/wmi, CurrentTemperature in
667
+ // TENTHS OF A KELVIN. Published by the firmware and genuinely absent
668
+ // on a large share of desktop boards — the same lesson
669
+ // parseGetProcessJson learned about perflib, which is why absent is
670
+ // ordinary here rather than an error.
671
+ //
672
+ // NEVER INVENT A READING. No sensor means no row, and no rows at all means the
673
+ // section is not rendered: not 0°C, not a dash, not a grey empty bar. Same rule
674
+ // that keeps `cpu` null until two samples exist.
675
+
676
+ /** How often the thermal reading is refreshed. Heat moves on the scale of
677
+ * seconds, and the two platforms that cost a subprocess to ask cost 51ms
678
+ * (`ioreg`) and rather less (`pmset`), measured. Linux costs a file read. */
679
+ const THERMAL_INTERVAL_MS = 10_000;
680
+
681
+ /**
682
+ * How many consecutive empty readings before this machine is left alone.
683
+ *
684
+ * The reason is Windows, where MSAcpi_ThermalZoneTemperature is absent on a
685
+ * large share of desktops: without this, every one of those machines would pay
686
+ * a `Get-CimInstance` child every ten seconds, forever, to render a section it
687
+ * can never render. Three rather than one because a single failure can be a
688
+ * hiccup — a timeout, a machine mid-wake — and giving up on a hiccup would lose
689
+ * a reading the machine does have.
690
+ *
691
+ * Not persisted. A restart asks again, which is what should happen after the
692
+ * user installs a driver or changes a firmware setting.
693
+ */
694
+ const THERMAL_GIVE_UP = 3;
695
+
696
+ /** Bands used where the hardware publishes none of its own. Linux sensors
697
+ * carry `temp*_max` and `temp*_crit` and those win: a laptop package sensor
698
+ * and an NVMe drive do not share a comfortable range, and one scale for both
699
+ * would be a number this module made up. */
700
+ const WARN_C = 75;
701
+ const CRIT_C = 90;
702
+
703
+ /**
704
+ * How much history the panel keeps, and why it is bucketed by minute.
705
+ *
706
+ * Each section answers "what is it now"; the chart behind it answers "what did
707
+ * it do while that build was running", which is a different question and the
708
+ * reason a section opens one at all. 1440 minutes is a day, which covers "since
709
+ * the deck started" for every session anybody actually has.
710
+ *
711
+ * A bucket holds the MAXIMUM of its minute, never the mean, and that choice is
712
+ * the same one for every series here. A machine that touched 94°C for twenty
713
+ * seconds and sat at 60 for the rest of the minute averages to 66 and reads as
714
+ * calm; a load average that spiked to 114 between two quiet stretches averages
715
+ * away entirely. The spike is what somebody opens a chart to find.
716
+ *
717
+ * Kept out of systemSnapshot deliberately. That endpoint is polled every three
718
+ * seconds by a topbar meter that draws none of this; a day of buckets on every
719
+ * one of those responses would be the largest thing the deck sends, for charts
720
+ * that are usually closed. It has its own route, like the process list.
721
+ */
722
+ const HISTORY_MINUTES = 1440;
723
+ const BUCKET_MS = 60_000;
724
+
725
+ /** A reading that is not a temperature is not a misparse to be shown anyway.
726
+ * Silicon does not run below freezing or above 130°C, and both ends of that
727
+ * have been produced by reading the right file with the wrong unit. */
728
+ const plausible = c => Number.isFinite(c) && c > 0 && c < 130;
729
+
730
+ /**
731
+ * Millidegrees Celsius out of a hwmon `temp*_input`, or null.
732
+ *
733
+ * The kernel writes an integer; the divide is the whole conversion. Exported
734
+ * and pure for the reason every parser here is: a Linux answer has to be
735
+ * checkable from a Mac.
736
+ */
737
+ export function celsiusFromMilli(text) {
738
+ const n = Number(String(text ?? "").trim());
739
+ const c = Math.round(n / 1000);
740
+ return plausible(c) ? c : null;
741
+ }
742
+
743
+ /**
744
+ * Which of a machine's sensors the panel names, out of every sensor found.
745
+ *
746
+ * A real machine publishes a lot of them: the package, one per core, the NVMe
747
+ * drive, the wireless card, the chipset. Two rows is what the panel has room
748
+ * for and two rows is what somebody watching a build wants, so this picks the
749
+ * CPU and the GPU by the chip that published them and leaves the rest alone.
750
+ *
751
+ * Preference inside a chip matters as much as the chip does. coretemp exposes
752
+ * `Package id 0` beside `Core 0`..`Core N`, and the package is the reading
753
+ * — a single core's number is noisier and lower than the die it sits on.
754
+ * k10temp exposes `Tctl` and, on parts that have it, `Tdie`: Tctl is Tdie plus
755
+ * a vendor offset that exists for fan control, so Tdie is the temperature and
756
+ * Tctl is the fallback. amdgpu's `edge` is the die edge and `junction` is the
757
+ * hotspot; edge is what every other tool calls the GPU temperature.
758
+ *
759
+ * Where a chip publishes nothing recognisable, the hottest of its sensors is
760
+ * taken, because the question is "is it getting hot" and the hottest sensor is
761
+ * the one that answers it.
762
+ */
763
+ const CPU_CHIPS = ["coretemp", "k10temp", "zenpower", "cpu_thermal", "soc_thermal"];
764
+ const GPU_CHIPS = ["amdgpu", "nouveau", "i915", "xe", "radeon"];
765
+
766
+ export function pickThermalRows(sensors) {
767
+ const hottest = rows => rows.reduce((a, b) => (b.celsius > a.celsius ? b : a));
768
+ const pick = (chips, prefer, label) => {
769
+ const mine = (sensors ?? []).filter(s => chips.includes(s.chip) && plausible(s.celsius));
770
+ if (!mine.length) return null;
771
+ for (const re of prefer) {
772
+ const hit = mine.find(s => re.test(s.label ?? ""));
773
+ if (hit) return { ...hit, label };
774
+ }
775
+ return { ...hottest(mine), label };
776
+ };
777
+ return [
778
+ pick(CPU_CHIPS, [/^package id/i, /^tdie$/i, /^tctl$/i], "CPU"),
779
+ pick(GPU_CHIPS, [/^edge$/i, /^junction$/i], "GPU"),
780
+ ].filter(Boolean);
781
+ }
782
+
783
+ /**
784
+ * Every temperature sensor under /sys/class/hwmon, with the chip that owns it
785
+ * and the bands that chip publishes for it.
786
+ *
787
+ * `root` is a parameter so this can be pointed at a tree on disk. There is no
788
+ * Linux machine here and no container runtime, so the alternative would be a
789
+ * directory walk nobody has ever run — and a walk is exactly the kind of code
790
+ * that a fixture of its OUTPUT cannot check, because the walk is the part that
791
+ * is wrong.
792
+ */
793
+ export async function readHwmon(root = "/sys/class/hwmon", deps = {}) {
794
+ const dir = deps.readdir ?? readdir;
795
+ const file = deps.readFile ?? readFile;
796
+ const read = async path => { try { return String(await file(path, "utf8")).trim(); } catch { return null; } };
797
+ let chips;
798
+ try { chips = await dir(root); } catch { return []; }
799
+ const out = [];
800
+ for (const hwmon of chips) {
801
+ const base = `${root}/${hwmon}`;
802
+ const chip = (await read(`${base}/name`)) ?? hwmon;
803
+ let entries;
804
+ try { entries = await dir(base); } catch { continue; }
805
+ for (const entry of entries) {
806
+ const m = /^(temp\d+)_input$/.exec(entry);
807
+ if (!m) continue;
808
+ const celsius = celsiusFromMilli(await read(`${base}/${entry}`));
809
+ if (celsius == null) continue;
810
+ out.push({
811
+ chip,
812
+ label: await read(`${base}/${m[1]}_label`),
813
+ celsius,
814
+ // The hardware's own bands where it has them. `max` is where the chip
815
+ // says it is unhappy and `crit` is where it says it will act.
816
+ warnAt: celsiusFromMilli(await read(`${base}/${m[1]}_max`)) ?? WARN_C,
817
+ critAt: celsiusFromMilli(await read(`${base}/${m[1]}_crit`)) ?? CRIT_C,
818
+ });
819
+ }
820
+ }
821
+ return out;
822
+ }
823
+
824
+ /**
825
+ * The coarser Linux fallback, for a machine whose sensors have no hwmon driver.
826
+ *
827
+ * One row, and it is labelled with the zone's own `type` rather than "CPU",
828
+ * because a thermal zone is not a claim about what was measured. `acpitz` is
829
+ * the motherboard's idea of ambient on a lot of hardware and calling that the
830
+ * CPU would be the same lie in a different place.
831
+ */
832
+ const ZONE_ORDER = ["x86_pkg_temp", "cpu-thermal", "cpu_thermal", "soc_thermal"];
833
+
834
+ export async function readThermalZones(root = "/sys/class/thermal", deps = {}) {
835
+ const dir = deps.readdir ?? readdir;
836
+ const file = deps.readFile ?? readFile;
837
+ const read = async path => { try { return String(await file(path, "utf8")).trim(); } catch { return null; } };
838
+ let zones;
839
+ try { zones = (await dir(root)).filter(n => /^thermal_zone\d+$/.test(n)); } catch { return []; }
840
+ const found = [];
841
+ for (const zone of zones) {
842
+ const celsius = celsiusFromMilli(await read(`${root}/${zone}/temp`));
843
+ if (celsius == null) continue;
844
+ found.push({ label: (await read(`${root}/${zone}/type`)) ?? zone, celsius, warnAt: WARN_C, critAt: CRIT_C });
845
+ }
846
+ if (!found.length) return [];
847
+ const known = found.find(z => ZONE_ORDER.includes(z.label));
848
+ return [known ?? found.reduce((a, b) => (b.celsius > a.celsius ? b : a))];
849
+ }
850
+
851
+ /**
852
+ * GPU degrees out of `ioreg -r -k PerformanceStatistics`.
853
+ *
854
+ * The macOS reading nothing documented: the accelerator publishes
855
+ * "Temperature(C)" in the same dictionary as its clock and its power. The
856
+ * maximum across accelerators, because a machine with two cards is asking
857
+ * whether it is getting hot, and the hotter card is the answer.
858
+ */
859
+ export function gpuFromIoreg(text) {
860
+ let best = null;
861
+ for (const m of String(text ?? "").matchAll(/"Temperature\(C\)"\s*=\s*(-?\d+)/g)) {
862
+ const c = Number(m[1]);
863
+ if (plausible(c) && (best == null || c > best)) best = c;
864
+ }
865
+ return best;
866
+ }
867
+
868
+ /**
869
+ * The share of the CPU's speed the thermal manager is allowing, out of
870
+ * `pmset -g therm`, or null when this Mac has never recorded one.
871
+ *
872
+ * `CPU_Scheduler_Limit` sits beside it and is deliberately not read: it limits
873
+ * scheduling rather than clock, so folding the two into one percentage would
874
+ * produce a number that is neither. If scheduler throttling turns out to matter
875
+ * it is a second row, not a redefinition of this one.
876
+ */
877
+ export function throttleFromPmset(text) {
878
+ const m = /CPU_Speed_Limit\s*=\s*(\d+)/.exec(String(text ?? ""));
879
+ if (!m) return null;
880
+ const pct = Number(m[1]);
881
+ if (!Number.isFinite(pct) || pct < 0 || pct > 100) return null;
882
+ return { speedLimit: pct };
883
+ }
884
+
885
+ /**
886
+ * Windows thermal zones out of MSAcpi_ThermalZoneTemperature.
887
+ *
888
+ * CurrentTemperature is in tenths of a Kelvin, which is the single detail this
889
+ * whole branch turns on: reading it as anything else gives a number that is
890
+ * plausible-looking and wrong.
891
+ *
892
+ * The zone is labelled "Thermal zone" when there is one and by its own name
893
+ * when there are several, because ACPI does not say which zone is the CPU and
894
+ * this module does not guess. `TZ00` is not a friendly label; it is an honest
895
+ * one, and it only appears on a machine that has more than one.
896
+ */
897
+ export function tempFromMsAcpiJson(json) {
898
+ let rows;
899
+ try { rows = typeof json === "string" ? JSON.parse(json) : json; }
900
+ catch { return []; }
901
+ if (!rows) return [];
902
+ if (!Array.isArray(rows)) rows = [rows];
903
+ const found = [];
904
+ for (const r of rows) {
905
+ const k = Number(r?.CurrentTemperature);
906
+ if (!Number.isFinite(k)) continue;
907
+ const celsius = Math.round(k / 10 - 273.15);
908
+ if (!plausible(celsius)) continue;
909
+ const name = String(r?.InstanceName ?? "").split("\\").pop().replace(/_\d+$/, "");
910
+ found.push({ label: name || "Thermal zone", celsius, warnAt: WARN_C, critAt: CRIT_C });
911
+ }
912
+ if (found.length === 1) found[0].label = "Thermal zone";
913
+ return found.slice(0, 2);
914
+ }
915
+
916
+ /**
917
+ * What /api/system carries, or null when this machine says nothing at all.
918
+ *
919
+ * Two fields rather than one list, because they are two different readings and
920
+ * collapsing them would let a throttle percentage be drawn under a °C heading
921
+ * — the thing the label rule exists to prevent. `swapLabel` earned that rule
922
+ * once already.
923
+ */
924
+ export async function readThermal(platform = process.platform) {
925
+ if (platform === "linux") {
926
+ const sensors = await readHwmon();
927
+ const celsius = pickThermalRows(sensors);
928
+ const rows = celsius.length ? celsius : await readThermalZones();
929
+ return rows.length ? { celsius: rows, throttle: null } : null;
930
+ }
931
+
932
+ if (platform === "darwin") {
933
+ // Scoped by key rather than dumped whole: `ioreg -l` is 217KB and just
934
+ // under two seconds on this machine, `-r -k PerformanceStatistics` is 83KB
935
+ // and 51ms for the same number.
936
+ const [gpu, therm] = await Promise.all([
937
+ run("ioreg", ["-r", "-k", "PerformanceStatistics", "-w", "0"], 3_000),
938
+ run("pmset", ["-g", "therm"]),
939
+ ]);
940
+ const celsius = [];
941
+ const c = gpu ? gpuFromIoreg(gpu) : null;
942
+ if (c != null) celsius.push({ label: "GPU", celsius: c, warnAt: WARN_C, critAt: CRIT_C });
943
+ const throttle = therm ? throttleFromPmset(therm) : null;
944
+ return celsius.length || throttle ? { celsius, throttle } : null;
945
+ }
946
+
947
+ if (platform === "win32") {
948
+ const out = await run("powershell.exe", [
949
+ "-NoProfile", "-NonInteractive", "-Command",
950
+ "Get-CimInstance -Namespace root/wmi -ClassName MSAcpi_ThermalZoneTemperature -ErrorAction Stop | Select-Object InstanceName,CurrentTemperature | ConvertTo-Json -Compress",
951
+ ], 6_000);
952
+ if (!out) return null;
953
+ const celsius = tempFromMsAcpiJson(out.trim());
954
+ return celsius.length ? { celsius, throttle: null } : null;
955
+ }
956
+
957
+ return null;
958
+ }
959
+
960
+ /**
961
+ * Fold one reading into the minute it belongs to, under a namespaced key.
962
+ *
963
+ * Keys are namespaced by section (`thermal:GPU`, `cpu:all`, `mem:swap`) rather
964
+ * than kept in four rings, because they all share one clock: a bucket is a
965
+ * minute of this machine, and every series that has something to say about that
966
+ * minute says it in the same place. The sections sample at different rates —
967
+ * CPU every three seconds, thermal every ten, memory every thirty — and folding
968
+ * by maximum makes that difference invisible to the reader, which is what it
969
+ * should be.
970
+ */
971
+ function record(key, value, nowMs = Date.now()) {
972
+ if (!Number.isFinite(value)) return;
973
+ const minute = Math.floor(nowMs / BUCKET_MS);
974
+ let last = history[history.length - 1];
975
+ if (!last || last.m !== minute) {
976
+ last = { m: minute, v: {} };
977
+ history.push(last);
978
+ while (history.length > HISTORY_MINUTES) history.shift();
979
+ }
980
+ const prev = last.v[key];
981
+ last.v[key] = prev == null ? value : Math.max(prev, value);
982
+ }
983
+
984
+ /**
985
+ * The thermal reading, whose series are not known until the machine answers.
986
+ *
987
+ * Keyed by the row's own label rather than by position, because the rows are
988
+ * not the same on every platform and a machine can start reporting a sensor it
989
+ * was not reporting before — a GPU driver loads, a laptop is docked. A series
990
+ * that appears late simply has no points before it appeared, which is the truth
991
+ * and draws correctly.
992
+ */
993
+ function recordThermal(reading, nowMs = Date.now()) {
994
+ if (!reading) return;
995
+ for (const r of reading.celsius ?? []) record(`thermal:${r.label}`, r.celsius, nowMs);
996
+ // Stored as the share TAKEN AWAY, the same way the panel draws it, so the
997
+ // chart and the row cannot disagree about which direction is bad.
998
+ if (reading.throttle) {
999
+ record(`thermal:${THROTTLE_LABEL}`, Math.max(0, 100 - reading.throttle.speedLimit), nowMs);
1000
+ }
1001
+ }
1002
+
1003
+ /** The one thermal row that is not degrees. Named once so the recorder, the
1004
+ * route and the panel cannot drift apart on the spelling. */
1005
+ export const THROTTLE_LABEL = "Throttling";
1006
+
1007
+ /**
1008
+ * The scale a series is drawn against.
1009
+ *
1010
+ * Fixed at 100 wherever the PANEL draws the same number against a 0-100 track,
1011
+ * because two pictures of one reading that disagree about how alarming it is
1012
+ * would be worse than either alone. Load average is the exception and gets a
1013
+ * fitted top: it is genuinely unbounded — measured at 114 on a twelve-core
1014
+ * machine — and the section that shows it draws no track at all, so there is no
1015
+ * competing picture for a fitted scale to contradict. Rounded up to something a
1016
+ * person would choose, and floored at one and a half times the core count so a
1017
+ * quiet machine is not drawn as a dramatic climb.
1018
+ */
1019
+ function loadTop(points, coreCount) {
1020
+ const peak = points.reduce((a, p) => Math.max(a, p.v), 0);
1021
+ const floor = Math.max(4, Math.ceil(coreCount * 1.5));
1022
+ const want = Math.max(floor, peak * 1.15);
1023
+ const step = want <= 20 ? 5 : want <= 100 ? 10 : 50;
1024
+ return Math.ceil(want / step) * step;
1025
+ }
1026
+
1027
+ /**
1028
+ * What each section's chart is made of.
1029
+ *
1030
+ * One entry per series, each carrying its own unit, its own bands and its own
1031
+ * scale, because a percentage, a temperature and a queue depth share nothing —
1032
+ * drawing them against one axis would invite a reading of one shape against
1033
+ * another that means nothing.
1034
+ */
1035
+ function seriesFor(group) {
1036
+ const at = key => history.filter(b => b.v[key] != null)
1037
+ // Timestamps rather than indices: a bucket only exists for a minute that was
1038
+ // sampled, so a gap — the machine asleep, the process paused — stays a gap
1039
+ // rather than becoming a straight line across it.
1040
+ .map(b => ({ t: b.m * BUCKET_MS, v: b.v[key] }));
1041
+ const coreCount = os.cpus().length;
1042
+
1043
+ if (group === "thermal") {
1044
+ const bands = new Map((thermal?.celsius ?? []).map(r => [r.label, r]));
1045
+ const labels = [];
1046
+ for (const b of history) {
1047
+ for (const k of Object.keys(b.v)) {
1048
+ if (!k.startsWith("thermal:")) continue;
1049
+ const label = k.slice("thermal:".length);
1050
+ if (!labels.includes(label)) labels.push(label);
1051
+ }
1052
+ }
1053
+ return labels.map(label => ({
1054
+ label,
1055
+ unit: label === THROTTLE_LABEL ? "%" : "C",
1056
+ top: 100,
1057
+ // Throttling is the one reading here whose normal value is zero, so it
1058
+ // is the one that does not need a full-height box to be read. Said by the
1059
+ // series rather than inferred from "has no bands", which was the first
1060
+ // rule and was wrong: CPU has no bands DELIBERATELY and uses the whole
1061
+ // scale, so it was getting the short box for a reason that is not true
1062
+ // of it.
1063
+ restsAtZero: label === THROTTLE_LABEL,
1064
+ warnAt: label === THROTTLE_LABEL ? null : (bands.get(label)?.warnAt ?? WARN_C),
1065
+ critAt: label === THROTTLE_LABEL ? null : (bands.get(label)?.critAt ?? CRIT_C),
1066
+ points: at(`thermal:${label}`),
1067
+ }));
1068
+ }
1069
+
1070
+ if (group === "cores") {
1071
+ // Not one line per core: twelve lines in a 620px dialog is a picture nobody
1072
+ // can read. These two answer what the columns cannot answer over time —
1073
+ // "all cores" at 20 with "busiest" at 100 is ONE core pinned, which is a
1074
+ // different machine from twelve at 20.
1075
+ //
1076
+ // No bands, deliberately, and the reason is written at the top of
1077
+ // SystemMeter: a CPU at 90% is the machine doing the work you asked for. An
1078
+ // indicator that alarms during the normal case teaches you to stop reading
1079
+ // it.
1080
+ return [
1081
+ { label: "All cores", unit: "%", top: 100, warnAt: null, critAt: null, points: at("cpu:all"), restsAtZero: false },
1082
+ { label: "Busiest core", unit: "%", top: 100, warnAt: null, critAt: null, points: at("cpu:busiest"), restsAtZero: false },
1083
+ ].filter(s => s.points.length);
1084
+ }
1085
+
1086
+ if (group === "memory") {
1087
+ const swapLabel = process.platform === "win32" ? "Commit" : "Swap";
1088
+ return [
1089
+ // One band, not two. A `critAt` of 100 draws a rule along the top of a
1090
+ // chart whose scale ends at 100 — it is the ceiling, drawn again in red,
1091
+ // and it says nothing the edge did not.
1092
+ { label: "Physical", unit: "%", top: 100, warnAt: 90, critAt: null, restsAtZero: false, points: at("mem:physical") },
1093
+ { label: swapLabel, unit: "%", top: 100, warnAt: 90, critAt: null, restsAtZero: false, points: at("mem:swap") },
1094
+ ].filter(s => s.points.length);
1095
+ }
1096
+
1097
+ if (group === "load") {
1098
+ // One series, not three. 1m, 5m and 15m are three views of one number —
1099
+ // the longer two are the short one smoothed — so charting the 1m over an
1100
+ // hour says everything the other two would, at the resolution they hide.
1101
+ const points = at("load:1m");
1102
+ if (!points.length) return [];
1103
+ return [{
1104
+ label: "Queued work",
1105
+ unit: "",
1106
+ top: loadTop(points, coreCount),
1107
+ // Where the queue exceeds the cores there are to run it, which is the one
1108
+ // number the section's own note already draws the line at.
1109
+ warnAt: coreCount,
1110
+ critAt: null,
1111
+ restsAtZero: false,
1112
+ points,
1113
+ }];
1114
+ }
1115
+
1116
+ return [];
1117
+ }
1118
+
1119
+ /**
1120
+ * Whether this machine has been held back AT ALL since the deck started, and
1121
+ * when it last was.
1122
+ *
1123
+ * The row reports the current sample, and on a desktop that current sample is
1124
+ * `0%` essentially always — measured here: ninety seconds of AES-NI on twelve
1125
+ * cores never moved `CPU_Speed_Limit` off 100. Which is the truth, and which
1126
+ * reads as "this readout does not work" the second time somebody looks at it.
1127
+ * It was reported that way twice.
1128
+ *
1129
+ * So the note under the row gets to say the other thing. Nothing new is
1130
+ * sampled for it: the minute buckets already hold the peak of every minute, and
1131
+ * this is a scan of what is already there. A machine that has never been
1132
+ * throttled says so; one that was at lunchtime says when.
1133
+ */
1134
+ function heldBackSoFar() {
1135
+ const key = `thermal:${THROTTLE_LABEL}`;
1136
+ let peak = 0;
1137
+ let lastMs = 0;
1138
+ for (const b of history) {
1139
+ const v = b.v[key];
1140
+ if (v == null || v <= 0) continue;
1141
+ if (v > peak) peak = v;
1142
+ lastMs = b.m * BUCKET_MS;
1143
+ }
1144
+ return peak > 0 ? { peak, lastMs } : null;
1145
+ }
1146
+
1147
+ /** What /api/system/history answers, for one section. */
1148
+ export function historySnapshot(group) {
1149
+ return { ok: true, sinceMs: historySince, stepMs: BUCKET_MS, series: seriesFor(group) };
1150
+ }
1151
+
1152
+ /**
1153
+ * One reading at a time, and a machine that cannot answer is asked three times
1154
+ * rather than for the life of the process.
1155
+ *
1156
+ * `deps.read` is a seam rather than a convenience: the rule this function
1157
+ * exists for only fires on a machine that answers with nothing, and the machine
1158
+ * this was written on answers with something, so there is no other way to run
1159
+ * the branch that matters.
1160
+ */
1161
+ export async function sampleThermal(deps = {}) {
1162
+ if (thermalInFlight) return;
1163
+ // Giving up is only ever for a machine that has NEVER answered — the Windows
1164
+ // desktop with no MSAcpi class, which would otherwise pay a PowerShell child
1165
+ // every ten seconds for the life of the process. A machine that answered once
1166
+ // has a sensor, and it keeps being asked however long the silence runs.
1167
+ if (!thermalEverAnswered && thermalMisses >= THERMAL_GIVE_UP) return;
1168
+ const read = deps.read ?? readThermal;
1169
+ thermalInFlight = true;
1170
+ try {
1171
+ const next = await read();
1172
+ if (next) { thermal = next; thermalMisses = 0; thermalEverAnswered = true; recordThermal(next); }
1173
+ else if (++thermalMisses >= THERMAL_GIVE_UP) {
1174
+ // DROP THE LAST READING. It used to be kept, and that is a number from
1175
+ // four minutes ago printed as though it were now — the one thing this
1176
+ // whole section refuses. A GPU driver unloads, a laptop is docked, a
1177
+ // sensor goes away: the honest answer is that the section stops being
1178
+ // drawn, not that it freezes.
1179
+ thermal = null;
1180
+ // But keep ASKING on a machine that has answered before. The cost
1181
+ // argument for giving up was only ever about a machine that can never
1182
+ // answer — a Windows desktop with no MSAcpi class paying a PowerShell
1183
+ // child every ten seconds forever. One that answered has a sensor, and a
1184
+ // silence is a gap rather than an absence.
1185
+ if (!thermalEverAnswered && thermalTimer) {
1186
+ clearInterval(thermalTimer);
1187
+ thermalTimer = null;
1188
+ }
1189
+ }
1190
+ } catch { thermalMisses++; }
1191
+ finally { thermalInFlight = false; }
531
1192
  }
532
1193
 
533
1194
  async function sampleMemory() {
@@ -544,6 +1205,8 @@ async function sampleMemory() {
544
1205
  // Same 30s cadence as memory, and for the same reason: it moves in minutes
545
1206
  // and costs a subprocess on two of the three platforms.
546
1207
  swap = await readSwap();
1208
+ record("mem:physical", memory.usedPct);
1209
+ if (swap && swap.total > 0) record("mem:swap", Math.round((swap.used / swap.total) * 1000) / 10);
547
1210
  } catch { /* keep the previous reading rather than blanking the meter */ }
548
1211
  finally { memInFlight = false; }
549
1212
  }
@@ -555,6 +1218,13 @@ function sampleCpu() {
555
1218
  cores = per;
556
1219
  cpuHistory.push(pct);
557
1220
  while (cpuHistory.length > HISTORY) cpuHistory.shift();
1221
+ record("cpu:all", pct);
1222
+ if (per?.length) record("cpu:busiest", Math.max(...per));
1223
+ // Free — os.loadavg() reads a kernel value, no syscall worth the name — so it
1224
+ // rides the CPU tick rather than earning a timer. Windows returns [0,0,0],
1225
+ // which is not a reading and is not recorded as one.
1226
+ const load = os.loadavg();
1227
+ if (process.platform !== "win32" && load.some(n => n > 0)) record("load:1m", Math.round(load[0] * 100) / 100);
558
1228
  }
559
1229
 
560
1230
  /**
@@ -566,16 +1236,26 @@ export function startSystemMetrics() {
566
1236
  prevTicks = readTicks(); // baseline, so the first tick has a delta
567
1237
  prevCoreTicks = readCoreTicks();
568
1238
  sampleMemory();
1239
+ historySince = Date.now();
1240
+ sampleThermal();
569
1241
  cpuTimer = setInterval(sampleCpu, CPU_INTERVAL_MS);
570
1242
  memTimer = setInterval(sampleMemory, MEM_INTERVAL_MS);
1243
+ thermalTimer = setInterval(sampleThermal, THERMAL_INTERVAL_MS);
571
1244
  cpuTimer.unref?.();
572
1245
  memTimer.unref?.();
1246
+ thermalTimer.unref?.();
573
1247
  }
574
1248
 
575
1249
  export function stopSystemMetrics() {
576
1250
  if (cpuTimer) clearInterval(cpuTimer);
577
1251
  if (memTimer) clearInterval(memTimer);
578
- cpuTimer = memTimer = null;
1252
+ if (thermalTimer) clearInterval(thermalTimer);
1253
+ cpuTimer = memTimer = thermalTimer = null;
1254
+ thermal = null;
1255
+ thermalMisses = 0;
1256
+ thermalEverAnswered = false;
1257
+ history.length = 0;
1258
+ historySince = 0;
579
1259
  prevTicks = null;
580
1260
  prevCoreTicks = null;
581
1261
  cpuHistory.length = 0;
@@ -610,6 +1290,9 @@ export function systemSnapshot() {
610
1290
  memory,
611
1291
  swap,
612
1292
  perCore: cores,
1293
+ // Null on a machine that publishes nothing, and the panel draws no section
1294
+ // at all for it rather than an empty one.
1295
+ thermal: thermal ? { ...thermal, heldBack: heldBackSoFar() } : null,
613
1296
  uptimeSec: Math.round(os.uptime()),
614
1297
  platform: process.platform,
615
1298
  loadavg: hasLoad ? load.map(n => Math.round(n * 100) / 100) : null,