Repository navigation
Expand file tree
/
Copy pathagentbox.py
More file actions
executable file
·2712 lines (2441 loc) · 110 KB
/
Copy pathagentbox.py
File metadata and controls
executable file
·2712 lines (2441 loc) · 110 KB
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
#!/usr/bin/env python3
"""
agentbox - a one-file, zero-dependency status probe for a Linux box used as an
AI agent environment (opencode / llama.cpp / ollama).
Design rule: --json is the real interface. The human text output is just a
pretty-printer over the same dict, so an LLM agent can consume the JSON and a
human can read the text.
Usage:
./agentbox.py # full snapshot, human readable
./agentbox.py status # same
./agentbox.py cpu | mem | gpu | disk | services | procs | opencode
./agentbox.py --json # machine readable, for agents / logging
./agentbox.py --watch 5 # refresh every 5s
./agentbox.py opencode --days 7
License: MIT
"""
from __future__ import annotations
import argparse
import glob
import hashlib
import ipaddress
import json
import math
import os
import re
import shutil
import sqlite3
import subprocess
import sys
import time
from collections import defaultdict
from datetime import datetime, timedelta, timezone
# Units that matter on an AI box. Edit for your machine.
WATCHED_UNITS = [
"ssh", "sshd", "tailscaled", "wg-quick@wg0", "docker",
"ollama", "llama-server", "opencode", "nvidia-persistenced",
]
SAMPLE_INTERVAL = 0.4 # seconds, for CPU delta sampling
JSON_SCHEMA_VERSION = 1
AVAILABILITY_AVAILABLE = "available"
AVAILABILITY_UNSUPPORTED = "unsupported"
AVAILABILITY_UNAVAILABLE = "unavailable"
AVAILABILITY_PARTIAL = "partial"
AVAILABILITY_UNVERIFIED = "unverified"
CONTROL_CHARS = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]")
ANSI_CSI = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
# --------------------------------------------------------------------------- #
# helpers
# --------------------------------------------------------------------------- #
def human_bytes(n: float) -> str:
for unit in ("B", "K", "M", "G", "T"):
if abs(n) < 1024 or unit == "T":
return f"{n:.0f}{unit}" if unit == "B" else f"{n:.1f}{unit}"
n /= 1024
return f"{n:.1f}T"
def human_count(n: float) -> str:
if n >= 1_000_000:
return f"{n / 1_000_000:.2f}M"
if n >= 1_000:
return f"{n / 1_000:.1f}k"
return str(int(n))
def human_delta(seconds: float) -> str:
seconds = int(seconds)
if seconds < 60:
return f"{seconds}s"
if seconds < 3600:
return f"{seconds // 60}m"
if seconds < 86400:
return f"{seconds // 3600}h{(seconds % 3600) // 60:02d}m"
return f"{seconds // 86400}d{(seconds % 86400) // 3600}h"
def bar(pct: float, width: int = 20) -> str:
pct = max(0.0, min(100.0, pct))
filled = int(round(pct / 100 * width))
return "[" + "#" * filled + "." * (width - filled) + "]"
def run(cmd: list[str], timeout: int = 5) -> str:
"""Run a command, return stdout or '' on any failure. Never raises."""
return run_result(cmd, timeout)[0]
def run_result(cmd: list[str], timeout: int = 5) -> tuple[str, str | None]:
"""Run a command and preserve why its output may be unavailable."""
exe = shutil.which(cmd[0])
if not exe:
for prefix in ("/usr/bin", "/bin", "/usr/sbin", "/sbin", "/opt/homebrew/bin"):
candidate = os.path.join(prefix, cmd[0])
if os.path.exists(candidate) and os.access(candidate, os.X_OK):
exe = candidate
break
if not exe:
return "", f"{cmd[0]} not found"
try:
out = subprocess.run(
[exe, *cmd[1:]], capture_output=True, text=True, errors="replace",
timeout=timeout, check=False
)
if out.returncode:
reason = out.stderr.strip() or f"{cmd[0]} exited {out.returncode}"
return out.stdout, reason
return out.stdout, None
except subprocess.TimeoutExpired:
return "", f"{cmd[0]} timed out after {timeout}s"
except OSError as exc:
return "", f"{cmd[0]} failed: {exc}"
def read(path: str) -> str:
try:
with open(path, "r", errors="replace") as fh:
return fh.read()
except OSError:
return ""
def _platform_id() -> str:
if sys.platform.startswith("linux"):
return "linux"
if sys.platform == "darwin":
return "macos"
return sys.platform
def platform_info() -> dict:
system = _platform_id()
return {
"system": system,
"sys_platform": sys.platform,
"machine": os.uname().machine,
"release": os.uname().release,
"capabilities": {
"procfs": system == "linux" and os.path.isdir("/proc"),
"pressure": system == "linux" and os.path.isdir("/proc/pressure"),
"systemd": system == "linux" and shutil.which("systemctl") is not None,
"macos_vm_stat": system == "macos" and shutil.which("vm_stat") is not None,
"macos_lsof": system == "macos" and shutil.which("lsof") is not None,
},
}
def unavailable(reason: str, availability: str = AVAILABILITY_UNAVAILABLE,
source: str | None = None) -> dict:
out = {"available": False, "availability": availability, "reason": reason}
if source:
out["source"] = source
return out
def is_unsupported(section: dict | None) -> bool:
return bool(section and section.get("availability") == AVAILABILITY_UNSUPPORTED)
def clean_text(value: object) -> str:
text = str(value)
text = ANSI_CSI.sub("", text)
return CONTROL_CHARS.sub("", text)
# --------------------------------------------------------------------------- #
# collectors
# --------------------------------------------------------------------------- #
def _parse_pressure(text: str) -> dict | None:
result = {}
for line in text.splitlines():
parts = line.split()
if not parts or parts[0] not in ("some", "full"):
continue
values = {}
for token in parts[1:]:
key, sep, value = token.partition("=")
if not sep:
continue
try:
values["total_us" if key == "total" else key] = (
int(value) if key == "total" else float(value))
except ValueError:
return None
if not {"avg10", "avg60", "avg300", "total_us"} <= values.keys():
return None
result[parts[0]] = values
return result if "some" in result else None
def collect_pressure(resources=("cpu", "memory", "io")) -> dict:
if _platform_id() != "linux":
out = unavailable("pressure stall information is Linux-only",
AVAILABILITY_UNSUPPORTED, "procfs")
out.update({"cpu": None, "memory": None, "io": None})
return out
out = {"available": True, "reason": None}
errors = []
for resource in resources:
path = f"/proc/pressure/{resource}"
try:
with open(path, errors="replace") as fh:
parsed = _parse_pressure(fh.read())
except OSError as exc:
parsed = None
errors.append(f"{resource}: {exc.strerror or exc}")
if parsed is None:
if not any(error.startswith(f"{resource}:") for error in errors):
errors.append(f"{resource}: invalid pressure data")
out[resource] = parsed
out["available"] = not errors
out["reason"] = "; ".join(errors) or None
return out
def _cpu_totals() -> tuple[int, int]:
"""Return (idle_jiffies, total_jiffies) from /proc/stat."""
line = read("/proc/stat").split("\n", 1)[0]
parts = [int(x) for x in line.split()[1:]]
idle = parts[3] + (parts[4] if len(parts) > 4 else 0) # idle + iowait
return idle, sum(parts)
def _proc_times() -> dict[int, tuple[int, str]]:
"""pid -> (utime+stime jiffies, comm)."""
out: dict[int, tuple[int, str]] = {}
for entry in os.listdir("/proc"):
if not entry.isdigit():
continue
stat = read(f"/proc/{entry}/stat")
if not stat:
continue
# comm can contain spaces and parens; split on the LAST ')'
try:
close = stat.rindex(")")
comm = stat[stat.index("(") + 1:close]
fields = stat[close + 2:].split()
out[int(entry)] = (int(fields[11]) + int(fields[12]), comm)
except (ValueError, IndexError):
continue
return out
def collect_linux_cpu_and_procs(top_n: int = 6) -> dict:
"""Sample CPU + per-process usage over SAMPLE_INTERVAL for real numbers."""
ncpu = os.cpu_count() or 1
hz = os.sysconf("SC_CLK_TCK")
idle0, total0 = _cpu_totals()
procs0 = _proc_times()
time.sleep(SAMPLE_INTERVAL)
idle1, total1 = _cpu_totals()
procs1 = _proc_times()
d_total = max(1, total1 - total0)
cpu_pct = 100.0 * (1 - (idle1 - idle0) / d_total)
# per-process share of one whole machine (0-100)
deltas = []
for pid, (jiff1, comm) in procs1.items():
jiff0 = procs0.get(pid, (jiff1, comm))[0]
used = (jiff1 - jiff0) / hz # cpu-seconds
pct = 100.0 * used / (SAMPLE_INTERVAL * ncpu)
if pct > 0.5:
rss = 0
m = re.search(r"VmRSS:\s+(\d+) kB", read(f"/proc/{pid}/status"))
if m:
rss = int(m.group(1)) * 1024
cmdline = read(f"/proc/{pid}/cmdline").replace("\0", " ").strip()
deltas.append({
"pid": pid, "name": comm, "cpu_pct": round(pct, 1),
"rss_bytes": rss, "cmdline": cmdline[:120] or comm,
})
deltas.sort(key=lambda p: p["cpu_pct"], reverse=True)
load1, load5, load15 = os.getloadavg()
uptime = float((read("/proc/uptime").split() or ["0"])[0])
return {
"cores": ncpu,
"usage_pct": round(cpu_pct, 1),
"load": [round(load1, 2), round(load5, 2), round(load15, 2)],
"load_per_core": round(load1 / ncpu, 2),
"uptime_seconds": int(uptime),
"temp_c": _cpu_temp(),
"top": deltas[:top_n],
}
def _sysctl_int(name: str) -> int | None:
out, error = run_result(["sysctl", "-n", name])
if error:
return None
try:
return int(out.strip())
except ValueError:
return None
def _macos_cpu_usage(interval: float = SAMPLE_INTERVAL) -> tuple[float | None, str | None, float]:
# macOS `top -s` only accepts whole seconds. A fractional delay is a usage
# error with no output, which would push every snapshot onto the ps
# fallback below and report an `unverified` lifetime average instead of
# the current load. Round up, never below one second.
delay = max(1, math.ceil(interval))
start = time.monotonic()
out, error = run_result(["top", "-l", "2", "-s", str(delay), "-n", "0"], timeout=5)
elapsed = max(0.001, time.monotonic() - start)
if error and not out:
ps_out, ps_error = run_result(["ps", "-A", "-o", "%cpu="])
if ps_error:
return None, error, elapsed
total = 0.0
for line in ps_out.splitlines():
try:
total += float(line.strip())
except ValueError:
continue
cores = os.cpu_count() or 1
return round(max(0.0, min(100.0, total / cores)), 1), (
f"{error}; fell back to ps %cpu"), elapsed
matches = re.findall(r"CPU usage:\s+.*?([0-9.]+)% idle", out)
if not matches:
return None, "top CPU output schema unsupported", elapsed
idle = float(matches[-1])
return round(max(0.0, min(100.0, 100.0 - idle)), 1), None, elapsed
def _macos_top_processes(top_n: int = 6) -> list[dict]:
out, error = run_result(["ps", "-axo", "pid=,pcpu=,rss=,comm="])
if error:
return []
procs = []
for line in out.splitlines():
parts = line.strip().split(None, 3)
if len(parts) < 4:
continue
try:
pid = int(parts[0])
cpu_pct = float(parts[1])
rss = int(parts[2]) * 1024
except ValueError:
continue
if cpu_pct <= 0.5:
continue
procs.append({
"pid": pid,
"name": os.path.basename(parts[3]),
"cpu_pct": round(cpu_pct, 1),
"rss_bytes": rss,
"cmdline": parts[3][:120],
})
procs.sort(key=lambda p: p["cpu_pct"], reverse=True)
return procs[:top_n]
def collect_macos_cpu_and_procs(top_n: int = 6) -> dict:
ncpu = _sysctl_int("hw.ncpu") or os.cpu_count() or 1
usage_pct, reason, elapsed = _macos_cpu_usage()
load1, load5, load15 = os.getloadavg()
boot = _sysctl_int("kern.boottime")
uptime = None
if boot is None:
out, _ = run_result(["sysctl", "-n", "kern.boottime"])
m = re.search(r"sec\s*=\s*(\d+)", out)
boot = int(m.group(1)) if m else None
if boot:
uptime = max(0, int(time.time() - boot))
result = {
"available": usage_pct is not None,
"availability": (AVAILABILITY_AVAILABLE if usage_pct is not None and not reason
else AVAILABILITY_UNVERIFIED if usage_pct is not None
else AVAILABILITY_UNAVAILABLE),
"reason": reason,
"source": "top+ps+sysctl",
"sample_seconds": round(elapsed, 3),
"cores": ncpu,
"usage_pct": usage_pct if usage_pct is not None else 0.0,
"load": [round(load1, 2), round(load5, 2), round(load15, 2)],
"load_per_core": round(load1 / ncpu, 2),
"uptime_seconds": uptime or 0,
"temp_c": None,
"top": _macos_top_processes(top_n),
}
return result
def collect_cpu_and_procs(top_n: int = 6) -> dict:
if _platform_id() == "macos":
return collect_macos_cpu_and_procs(top_n)
if _platform_id() != "linux" or not os.path.isdir("/proc"):
out = unavailable("CPU collector unsupported on this platform",
AVAILABILITY_UNSUPPORTED)
out.update({"cores": os.cpu_count() or 1, "usage_pct": 0.0,
"load": [0, 0, 0], "load_per_core": 0,
"uptime_seconds": 0, "temp_c": None, "top": []})
return out
try:
result = collect_linux_cpu_and_procs(top_n)
result.setdefault("available", True)
result.setdefault("availability", AVAILABILITY_AVAILABLE)
result.setdefault("reason", None)
result.setdefault("source", "procfs")
result.setdefault("sample_seconds", SAMPLE_INTERVAL)
return result
except (OSError, ValueError, IndexError) as exc:
out = unavailable(f"CPU data unavailable: {exc}", source="procfs")
out.update({"cores": os.cpu_count() or 1, "usage_pct": 0.0,
"load": [0, 0, 0], "load_per_core": 0,
"uptime_seconds": 0, "temp_c": None, "top": []})
return out
def _cpu_temp() -> float | None:
best = None
for zone in glob.glob("/sys/class/thermal/thermal_zone*"):
kind = read(f"{zone}/type").strip()
if kind in ("x86_pkg_temp", "acpitz", "cpu-thermal", "k10temp"):
raw = read(f"{zone}/temp").strip()
if raw.isdigit():
best = max(best or 0, int(raw) / 1000)
return round(best, 1) if best else None
def collect_linux_mem() -> dict:
info = {}
for line in read("/proc/meminfo").splitlines():
k, _, v = line.partition(":")
num = v.strip().split(" ")[0]
if num.isdigit():
info[k] = int(num) * 1024
total = info.get("MemTotal", 0)
avail = info.get("MemAvailable", 0)
used = total - avail
swap_total = info.get("SwapTotal", 0)
swap_used = swap_total - info.get("SwapFree", 0)
return {
"total_bytes": total,
"used_bytes": used,
"available_bytes": avail,
"used_pct": round(100 * used / total, 1) if total else 0.0,
"cached_bytes": info.get("Cached", 0),
"swap_total_bytes": swap_total,
"swap_used_bytes": swap_used,
"swap_used_pct": round(100 * swap_used / swap_total, 1) if swap_total else 0.0,
}
def _parse_vm_stat(text: str) -> tuple[int | None, dict[str, int]]:
first = text.splitlines()[0] if text.splitlines() else ""
m = re.search(r"page size of (\d+) bytes", first)
page_size = int(m.group(1)) if m else None
pages = {}
for line in text.splitlines()[1:]:
key, sep, value = line.partition(":")
if not sep:
continue
raw = value.strip().rstrip(".")
try:
pages[key.strip()] = int(raw)
except ValueError:
continue
return page_size, pages
def collect_macos_mem() -> dict:
total = _sysctl_int("hw.memsize") or 0
text, error = run_result(["vm_stat"])
page_size, pages = _parse_vm_stat(text)
if not total and page_size:
try:
total = os.sysconf("SC_PHYS_PAGES") * page_size
except (ValueError, OSError, AttributeError):
total = 0
if error or not page_size or not pages:
out = unavailable(error or "vm_stat output schema unsupported", source="vm_stat")
out.update({
"total_bytes": total, "used_bytes": 0, "available_bytes": 0,
"used_pct": 0.0, "cached_bytes": 0,
"swap_total_bytes": 0, "swap_used_bytes": 0, "swap_used_pct": 0.0,
"basis": "macos_vm_stat",
})
return out
free_pages = pages.get("Pages free", 0)
inactive_pages = pages.get("Pages inactive", 0)
speculative_pages = pages.get("Pages speculative", 0)
wired_pages = pages.get("Pages wired down", pages.get("Pages wired", 0))
compressed_pages = pages.get("Pages occupied by compressor", 0)
available = (free_pages + inactive_pages + speculative_pages) * page_size
used = max(0, total - available) if total else 0
cached = inactive_pages * page_size
swap_total = swap_used = 0
swap, _ = run_result(["sysctl", "-n", "vm.swapusage"])
numbers = re.findall(r"([0-9.]+)M", swap)
if len(numbers) >= 2:
try:
swap_total = int(float(numbers[0]) * 1024 ** 2)
swap_used = int(float(numbers[1]) * 1024 ** 2)
except ValueError:
pass
return {
"available": True,
"availability": AVAILABILITY_AVAILABLE,
"reason": None,
"source": "vm_stat+sysctl",
"basis": "free+inactive+speculative pages; not Linux MemAvailable",
"total_bytes": total,
"used_bytes": used,
"available_bytes": available,
"used_pct": round(100 * used / total, 1) if total else 0.0,
"cached_bytes": cached,
"wired_bytes": wired_pages * page_size,
"compressed_bytes": compressed_pages * page_size,
"swap_total_bytes": swap_total,
"swap_used_bytes": swap_used,
"swap_used_pct": round(100 * swap_used / swap_total, 1) if swap_total else 0.0,
}
def collect_mem() -> dict:
if _platform_id() == "macos":
return collect_macos_mem()
if _platform_id() != "linux" or not os.path.exists("/proc/meminfo"):
out = unavailable("memory collector unsupported on this platform",
AVAILABILITY_UNSUPPORTED)
out.update({"total_bytes": 0, "used_bytes": 0, "available_bytes": 0,
"used_pct": 0.0, "cached_bytes": 0, "swap_total_bytes": 0,
"swap_used_bytes": 0, "swap_used_pct": 0.0})
return out
result = collect_linux_mem()
if result["total_bytes"] <= 0:
result.update(unavailable("/proc/meminfo missing or unreadable", source="procfs"))
else:
result.setdefault("available", True)
result.setdefault("availability", AVAILABILITY_AVAILABLE)
result.setdefault("reason", None)
result.setdefault("source", "procfs")
return result
def collect_gpu() -> dict:
if _platform_id() == "macos":
out = unavailable("Apple GPU telemetry is not implemented yet",
AVAILABILITY_UNSUPPORTED, "macos")
out.update({"vendor": None, "gpus": [], "processes": []})
return out
gpus: list[dict] = []
vendor = None
# --- NVIDIA ---
q = ("name,utilization.gpu,memory.used,memory.total,temperature.gpu,"
"power.draw,power.limit")
out, nvidia_error = run_result(
["nvidia-smi", f"--query-gpu={q}", "--format=csv,noheader,nounits"])
if out.strip():
vendor = "nvidia"
for idx, line in enumerate(out.strip().splitlines()):
f = [x.strip() for x in line.split(",")]
def num(i):
try:
return float(f[i])
except (ValueError, IndexError):
return None
gpus.append({
"index": idx, "name": f[0], "util_pct": num(1),
"mem_used_bytes": (num(2) or 0) * 1024 ** 2,
"mem_total_bytes": (num(3) or 0) * 1024 ** 2,
"temp_c": num(4), "power_w": num(5), "power_limit_w": num(6),
})
procs = run(["nvidia-smi",
"--query-compute-apps=pid,process_name,used_memory",
"--format=csv,noheader,nounits"])
apps = []
for line in procs.strip().splitlines():
f = [x.strip() for x in line.split(",")]
if len(f) >= 3:
apps.append({
"pid": int(f[0]) if f[0].isdigit() else None,
"name": os.path.basename(f[1]),
"mem_bytes": (float(f[2]) if f[2].replace(".", "").isdigit() else 0) * 1024 ** 2,
})
return {"available": True, "reason": None, "vendor": vendor,
"gpus": gpus, "processes": apps}
# --- AMD (amdgpu sysfs) ---
for card in sorted(glob.glob("/sys/class/drm/card*/device/gpu_busy_percent")):
vendor = "amd"
dev = os.path.dirname(card)
busy = read(card).strip()
used = read(f"{dev}/mem_info_vram_used").strip()
total = read(f"{dev}/mem_info_vram_total").strip()
temp = None
for hw in glob.glob(f"{dev}/hwmon/hwmon*/temp1_input"):
t = read(hw).strip()
if t.isdigit():
temp = int(t) / 1000
gpus.append({
"index": len(gpus), "name": "amdgpu",
"util_pct": float(busy) if busy.isdigit() else None,
"mem_used_bytes": int(used) if used.isdigit() else 0,
"mem_total_bytes": int(total) if total.isdigit() else 0,
"temp_c": temp, "power_w": None, "power_limit_w": None,
})
available = bool(gpus) or nvidia_error == "nvidia-smi not found"
return {"available": available, "reason": None if available else nvidia_error,
"vendor": vendor, "gpus": gpus, "processes": []}
def _unescape_mountinfo(value: str) -> str:
return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), value)
def _parse_mountinfo(text: str) -> list[dict]:
mounts = []
for line in text.splitlines():
left, sep, right = line.partition(" - ")
before, after = left.split(), right.split()
if not sep or len(before) < 6 or len(after) < 3:
continue
mounts.append({
"device": before[2],
"root": _unescape_mountinfo(before[3]),
"mount_point": _unescape_mountinfo(before[4]),
"mount_options": before[5].split(","),
"filesystem": after[0],
"mount_source": _unescape_mountinfo(after[1]),
"super_options": after[2].split(","),
})
return mounts
def _mount_for_path(path: str, mounts: list[dict]) -> dict | None:
path = os.path.realpath(path) if os.path.exists(path) else os.path.abspath(path)
matches = [m for m in mounts
if path == m["mount_point"] or
path.startswith(m["mount_point"].rstrip("/") + "/")]
return max(matches, key=lambda m: len(m["mount_point"])) if matches else None
def _diskstats() -> dict[str, tuple[int, int, int]]:
stats = {}
for line in read("/proc/diskstats").splitlines():
fields = line.split()
if len(fields) < 14:
continue
try:
stats[f"{fields[0]}:{fields[1]}"] = (
int(fields[5]), int(fields[9]), int(fields[12]))
except ValueError:
continue
return stats
def collect_linux_disk(paths=("/", "/home"), io_interval: float = 0.1,
deep: bool = False) -> list[dict]:
mounts = _parse_mountinfo(read("/proc/self/mountinfo"))
io0 = _diskstats() if io_interval else {}
if io_interval:
time.sleep(io_interval)
io1 = _diskstats() if io_interval else {}
seen, out = set(), []
for p in paths:
if not os.path.isdir(p):
continue
try:
st = os.statvfs(p)
device = os.stat(p).st_dev
except OSError:
continue
mount = _mount_for_path(p, mounts)
key = (device, mount["mount_point"] if mount else None)
if key in seen:
continue
seen.add(key)
total = st.f_blocks * st.f_frsize
free = st.f_bavail * st.f_frsize
inode_total = st.f_files
inode_used = max(0, inode_total - st.f_ffree)
item = {
"path": p, "total_bytes": total, "used_bytes": total - free,
"free_bytes": free,
"used_pct": round(100 * (total - free) / total, 1) if total else 0.0,
"inode_total": inode_total,
"inode_used": inode_used,
"inode_free": st.f_ffree,
"inode_available": st.f_favail,
"inode_used_pct": (round(100 * inode_used / inode_total, 1)
if inode_total else None),
"read_only": bool(st.f_flag & getattr(os, "ST_RDONLY", 1)),
"operational": True,
"filesystem": mount["filesystem"] if mount else None,
"mount_source": mount["mount_source"] if mount else None,
"mount_point": mount["mount_point"] if mount else None,
"mount_options": mount["mount_options"] if mount else [],
"device": mount["device"] if mount else None,
"read_bytes_per_sec": None,
"write_bytes_per_sec": None,
"io_busy_pct": None,
}
if mount and mount["device"] in io0 and mount["device"] in io1:
before, after = io0[mount["device"]], io1[mount["device"]]
item["read_bytes_per_sec"] = max(0, after[0] - before[0]) * 512 / io_interval
item["write_bytes_per_sec"] = max(0, after[1] - before[1]) * 512 / io_interval
item["io_busy_pct"] = round(
min(100.0, max(0, after[2] - before[2]) / (io_interval * 10)), 1)
out.append(item)
if deep:
if out:
out[0]["deep"] = collect_deep_storage()
return out
def _parse_macos_mounts(text: str) -> list[dict]:
mounts = []
pattern = re.compile(r"^(.*?) on (.*?) \((.*?)\)$")
for line in text.splitlines():
match = pattern.match(line)
if not match:
continue
source, mount_point, opts = match.groups()
options = [opt.strip() for opt in opts.split(",")]
filesystem = options[0] if options else None
mounts.append({
"device": None,
"root": "/",
"mount_point": mount_point,
"mount_options": options,
"filesystem": filesystem,
"mount_source": source,
"super_options": options,
})
return mounts
def collect_macos_disk(paths: tuple[str, ...] | None = None,
deep: bool = False) -> list[dict]:
if paths is None:
paths = (os.path.expanduser("~"),)
mounts = _parse_macos_mounts(run(["mount"]))
seen, out = set(), []
for p in paths:
p = os.path.abspath(os.path.expanduser(p))
if not os.path.isdir(p):
continue
try:
st = os.statvfs(p)
device = os.stat(p).st_dev
except OSError:
continue
mount = _mount_for_path(p, mounts)
if _platform_id() == "macos" and p.startswith("/Users/"):
data_mount = next((m for m in mounts
if m.get("mount_point") == "/System/Volumes/Data"), None)
if data_mount:
mount = data_mount
key = (device, mount["mount_point"] if mount else p)
if key in seen:
continue
seen.add(key)
total = st.f_blocks * st.f_frsize
free = st.f_bavail * st.f_frsize
inode_total = st.f_files
inode_used = max(0, inode_total - st.f_ffree)
options = mount["mount_options"] if mount else []
sealed_root = p == "/" and "sealed" in options and "read-only" in options
item = {
"available": True,
"availability": AVAILABILITY_AVAILABLE,
"reason": None,
"source": "statvfs+mount",
"path": p, "total_bytes": total, "used_bytes": total - free,
"free_bytes": free,
"used_pct": round(100 * (total - free) / total, 1) if total else 0.0,
"inode_total": inode_total,
"inode_used": inode_used,
"inode_free": st.f_ffree,
"inode_available": st.f_favail,
"inode_used_pct": (round(100 * inode_used / inode_total, 1)
if inode_total else None),
"read_only": bool(st.f_flag & getattr(os, "ST_RDONLY", 1)) or "read-only" in options,
"operational": not sealed_root,
"filesystem": mount["filesystem"] if mount else None,
"mount_source": mount["mount_source"] if mount else None,
"mount_point": mount["mount_point"] if mount else p,
"mount_options": options,
"device": mount["device"] if mount else None,
"read_bytes_per_sec": None,
"write_bytes_per_sec": None,
"io_busy_pct": None,
}
out.append(item)
if deep and out:
out[0]["deep"] = collect_deep_storage()
return out
def collect_disk(paths=None, io_interval: float = 0.1,
deep: bool = False) -> list[dict]:
if _platform_id() == "macos":
return collect_macos_disk(paths, deep=deep)
if paths is None:
paths = ("/", "/home")
if _platform_id() != "linux" or not os.path.isdir("/proc"):
return []
return collect_linux_disk(paths=paths, io_interval=io_interval, deep=deep)
DEEP_STORAGE_ROOTS = (
("ollama", "~/.ollama"),
("claude", "~/.claude"),
("opencode", "~/.local/share/opencode"),
("huggingface", "~/.cache/huggingface"),
("llama", "~/.cache/llama.cpp"),
("docker", "/var/lib/docker"),
)
CONFIG_PATH = "~/.config/agentbox/config.json"
def load_config() -> tuple[dict, str | None]:
path = os.path.expanduser(CONFIG_PATH)
if not os.path.exists(path):
return {}, None
try:
with open(path, encoding="utf-8") as fh:
value = json.load(fh)
except (OSError, json.JSONDecodeError):
return {}, "cannot read config"
if not isinstance(value, dict):
return {}, "config must contain a JSON object"
sanitized = dict(value)
errors = []
for key in ("disk_warning_pct", "inode_warning_pct"):
if key in value:
try:
if isinstance(value[key], bool):
raise ValueError
number = float(value[key])
if not math.isfinite(number) or not 0 <= number <= 100:
errors.append(f"{key} must be between 0 and 100")
sanitized.pop(key, None)
except (TypeError, ValueError, OverflowError):
errors.append(f"{key} must be numeric")
sanitized.pop(key, None)
for key in ("capacity_min_ram_bytes", "capacity_min_disk_bytes"):
if key in value:
try:
if isinstance(value[key], bool):
raise ValueError
number = float(value[key])
if not math.isfinite(number) or number <= 0 or not number.is_integer():
errors.append(f"{key} must be positive")
sanitized.pop(key, None)
except (TypeError, ValueError, OverflowError):
errors.append(f"{key} must be a positive integer")
sanitized.pop(key, None)
usage = value.get("usage", {})
if usage is not None and not isinstance(usage, dict):
errors.append("usage must be an object")
sanitized.pop("usage", None)
elif isinstance(usage, dict):
sanitized_usage = dict(usage)
for key, item in usage.items():
if not key.endswith("_daily_tokens"):
errors.append(f"unknown usage key: {key}")
sanitized_usage.pop(key, None)
else:
try:
if isinstance(item, bool):
raise ValueError
number = float(item)
if not math.isfinite(number) or number <= 0 or not number.is_integer():
errors.append(f"{key} must be a positive integer")
sanitized_usage.pop(key, None)
except (TypeError, ValueError, OverflowError):
errors.append(f"{key} must be a positive integer")
sanitized_usage.pop(key, None)
sanitized["usage"] = sanitized_usage
allowed_providers = {"opencode", "claude", "ollama"}
if "expected_providers" in value:
providers = value.get("expected_providers")
if not isinstance(providers, list) or not all(isinstance(p, str) for p in providers):
errors.append("expected_providers must be a list of provider names")
sanitized.pop("expected_providers", None)
else:
unknown = sorted(set(providers) - allowed_providers)
if unknown:
errors.append(f"unknown expected provider: {', '.join(unknown)}")
sanitized.pop("expected_providers", None)
else:
sanitized["expected_providers"] = sorted(set(providers))
if "expected_services" in value:
services = value.get("expected_services")
if not isinstance(services, list) or not all(isinstance(s, str) and s for s in services):
errors.append("expected_services must be a list of service names")
sanitized.pop("expected_services", None)
else:
sanitized["expected_services"] = sorted(set(services))
return sanitized, "; ".join(errors) or None
def _daily_budget(config: dict, provider: str) -> int | None:
usage = config.get("usage")
if not isinstance(usage, dict):
return None
value = usage.get(f"{provider}_daily_tokens")
try:
value = int(value)
return value if value > 0 else None
except (TypeError, ValueError, OverflowError):
return None
def _config_number(config: dict, key: str, default: float,
minimum: float = 0) -> float:
try:
value = float(config.get(key, default))
return value if math.isfinite(value) and value >= minimum else default
except (TypeError, ValueError, OverflowError):
return default
def _path_hash(path: str) -> str:
return hashlib.sha256(path.encode()).hexdigest()[:16]
def _parse_du_size(raw: str) -> int | None:
try:
return int(raw)
except ValueError:
return None
def collect_deep_storage(timeout: int = 15) -> dict:
roots = []
largest = []
errors = []
deadline = time.monotonic() + timeout
for label, configured in DEEP_STORAGE_ROOTS:
if time.monotonic() >= deadline:
errors.append("deep storage scan timed out")
break
root = os.path.abspath(os.path.expanduser(configured))
if not os.path.isdir(root):
continue
roots.append({"name": label, "path": root})
remaining = max(1, int(deadline - time.monotonic()))
output, error = run_result(
["du", "-B1", "--max-depth=2", "--one-file-system", root],
timeout=remaining)
if error:
errors.append(f"{label}: {error}")
continue
for line in output.splitlines():
size, sep, path = line.partition("\t")
if not sep:
continue
bytes_used = _parse_du_size(size)
if bytes_used is None:
continue
largest.append({"name": label, "path": path, "bytes": bytes_used})
largest.sort(key=lambda item: (-item["bytes"], item["path"]))
return {
"available": not errors,
"reason": "; ".join(errors) or None,
"roots": roots,
"largest": largest[:30],
"partial": bool(errors),
}
def collect_linux_services() -> dict:
"""Running systemd units + explicit status for the ones we care about."""
running = []
out, list_error = run_result(
["systemctl", "list-units", "--type=service", "--state=running",
"--no-legend", "--no-pager", "--plain"])
for line in out.splitlines():
parts = line.split(None, 4)
if parts and parts[0].endswith(".service"):
running.append({
"unit": parts[0].removesuffix(".service"),
"description": parts[4] if len(parts) > 4 else "",
})