JSON-RPC API
The app, the CLI and your own tools all use one API: JSON-RPC 2.0 on a Unix domain socket, one message per line. Call Describe to get the schema from the running daemon.
Transport
| Mode | Socket | Access |
|---|---|---|
| Full (root) | /var/run/pguard/daemon.sock | Group admin, mode 0660. The daemon also checks each caller and accepts only root and members of admin. |
| Limited (user) | ~/.pguard/daemon.sock | Mode 0600. The owner and root. |
A refused caller is disconnected without a reply. Requests and responses are newline-delimited; after Subscribe the server also pushes notifications.
Client: {"jsonrpc":"2.0","method":"GetStatus","params":{},"id":1}\n
Server: {"jsonrpc":"2.0","result":{...},"id":1}\n
Push: {"jsonrpc":"2.0","method":"ProcessSnapshot","params":[...]}\n
Quick test
echo '{"jsonrpc":"2.0","method":"Describe","params":{},"id":1}' | nc -U /var/run/pguard/daemon.sock
Python client
import json, socket
def call(method, params=None, path="/var/run/pguard/daemon.sock"):
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
s.connect(path)
s.sendall((json.dumps({"jsonrpc": "2.0", "method": method,
"params": params or {}, "id": 1}) + "\n").encode())
buf = b""
while not buf.endswith(b"\n"):
buf += s.recv(65536)
reply = json.loads(buf)
if "error" in reply:
raise RuntimeError(reply["error"])
return reply["result"]
for p in call("GetProcesses", {"top_n": 5}):
print(p["sample"]["name"], p["severity"]["level"], p["score"]["total"])
Common parameters
| Parameter | Meaning |
|---|---|
window | "LastHour" (default, 30 s buckets), "Last6Hours" (2 min), "Last24Hours" (5 min), "Last7Days" (30 min). |
pid, start_time | Together they name one run. start_time is mach absolute time since boot. A present but unusable value (not an integer, PID outside 1..2147483647, negative start time) is -32602, never treated as absent. null counts as absent. |
top_n | Result count. Default 10, maximum 500. |
limit | Result count for ranked queries. Default per method, maximum 500. |
Methods at a glance
| Group | Methods |
|---|---|
| Discovery and health | Describe, GetStatus |
| Live system | GetSystemState, GetMemoryPressure, GetDiagnosis |
| Live processes | GetProcesses, GetProcessDetail, GetProcessThreads, GetProcessInspect, GetProcessTree |
| AI and builds | GetAgentSessions, GetLeftBehindProcesses, GetModelRuntimes, GetBuildWarning, SetBuildWarning |
| History | GetProcessInstances, GetProcessHistory, GetBatteryHistory, GetTopConsumers, GetSystemStateHistory, GetSystemResourceHistory, GetClassBreakdown, GetScanCorrelation |
| Watches | AddWatch, RemoveWatch, ListWatches |
| Network | GetConnections, GetHostTraffic, LookupGeo, GetNewNetworks, GetNetworkDetail, SetNetworkDetail |
| Control signed app/CLI | ApplyAction, GetActionSettings, SetActionSettings, GetActionLog, Restart, SampleProcess |
| Push | Subscribe |
Discovery and health
Describe
A short, machine-readable summary of the API, served by the running daemon. Start here when you write a client or give the socket to an AI assistant. Params: none.
{
"name": "ProcessGuard",
"protocol": "JSON-RPC 2.0 over Unix Domain Socket (newline-delimited)",
"methods": [ { "name": "GetStatus", "params": {}, "returns": "...", "errors": "..." } ],
"time_windows": ["LastHour", "Last6Hours", "Last24Hours", "Last7Days"],
"example": "..."
}
GetStatus
Daemon health. Params: none.
{
"version": "0.9.0",
"battery": { "current_capacity": 80, "max_capacity": 100, ... },
"process_count": 142,
"uptime_secs": 3600,
"boot_session": "8C1F...",
"privileged": true,
"collector": {
"sample_interval_secs": 5, "stale": false, "stale_after_secs": 15,
"last_sample_at": 1779366690, "last_sample_age_secs": 2,
"last_sample_duration_ms": 41, "last_sample_interval_secs": 5.003,
"pids_listed": 612, "pids_sampled": 598,
"last_sample_failure": null, "last_store_at": 1779366680, "last_store_failure": null,
"subscriber_lagged_events": 0,
"network": { "state": "ok", "reason": null, "since": 1779366600 }
},
"last_new_network": null
}
version: the daemon build. The app compares it with its own to show that an old daemon still runs.privileged:truein full mode;falsemeans root processes have no samples and no connections.collector.stale: no successful observation yet, or the last is older thanstale_after_secs(three intervals). While stale,GetProcessesreturns the last good list.pids_listedvspids_sampled: processes that exited mid-scan or are out of reach.last_sample_failure,last_store_failure:{ at, reason }, kept after a later success; compareatwithlast_sample_at/last_store_at.network.state:ok,unavailableorbroken(see Network health).last_new_network: the newestGetNewNetworksentry, ornull.severity_factors: the current multipliers of the warning thresholds (see Concepts).parallel_builds: the state of the parallel builds warning (see GetBuildWarning).
Live system
GetSystemState
RAM, swap, load, thermal state, CPU temperature and GPU. Params: none.
{
"total_ram": 17179869184, "available_ram": 8589934592,
"swap_used": 536870912, "swap_total": 4294967296,
"load_avg": [2.5, 1.8, 1.2], "thermal_state": "Nominal", "timestamp": 1779366690,
"active_ram": 4294967296, "wired_ram": 2147483648,
"compressed_ram": 1073741824, "purgeable_ram": 536870912,
"cpu_temp_celsius": 42.5, "gpu_utilization": 0.25
}
thermal_state: Nominal, Fair, Serious, Critical or Unknown. Unknown means the kernel did not answer; never render it as Nominal.
GetMemoryPressure
Live RAM breakdown with free RAM and pressure. Params: none. Returns total_ram, active_ram, wired_ram, compressed_ram, purgeable_ram, free_ram, swap_used, swap_total, pressure_pct, thermal_state, cpu_temp_celsius, gpu_utilization.
pressure_pct = (active + wired + compressed) / total × 100. free_ram = total − (active + wired + compressed).
GetDiagnosis
Why the machine is slow, in one call. Read-only, computed from data in memory. Params: none.
{
"observed_at": 1700000000,
"causes": [{
"kind": "memory", "level": "Warning",
"summary": "kernel memory pressure warning; swap grew 3072 MiB in 120 s; Ollama (pid 100) grew 6144 MiB over the same span",
"unit": "bytes", "consumers": [],
"evidence": { "memory_pressure_level": 2, "swap_used_bytes": 3221225472, "swap_growth_bytes": 3221225472,
"span_secs": 120.0, "compressed_bytes": 0, "swap_cause": { ... }, "processes_past_threshold": 0 }
}],
"limitations": ["A cause is a reading past its threshold, or a growth that coincides with swap growth: evidence, not proof of why the machine is slow."]
}
| Kind | When |
|---|---|
thermal | Thermal state Serious (Warning) or Critical (Critical). |
memory | Kernel memory pressure warning (2) or critical (4), swap growth of at least 256 MiB over the trend (with the runtime swap cause when there is one), or processes past the memory threshold. |
gpu | System GPU utilization of 90% or more (Warning). |
cpu, disk, energy, wakeups, network | Processes whose smoothed reading is past its threshold. |
At most 5 causes, worst level first, then in the order thermal, memory, cpu, gpu, disk, energy, wakeups, network. At most 3 consumers each: pid, start_time, name, value, level, group (agent session or model runtime). Empty causes when nothing is past its threshold: no cause is made up from the largest process.
Live processes
GetProcesses
The live snapshot, worst severity first, then impact score. Params: top_n (default 10).
Each entry has sample (the raw interval counters and gauges), score (total 0–100 and the six components), severity (level, dominant, and readings per resource) and rates (every counter per second).
{
"sample": {
"pid": 84787, "name": "tuicommander", "class": "Background",
"cpu_time_delta": 155419969, "disk_read_delta": 13094912, "disk_write_delta": 81920,
"net_io_delta": 0, "mem_resident": 1793097728, "virtual_mem": 453425709056,
"thread_count": 154, "start_time": 8634849296941, "ppid": 1,
"command": "/usr/local/bin/tuicommander",
"phys_footprint": 1500000000, "peak_footprint": 1800000000,
"instructions": 500000000, "cycles": 300000000, "energy_nj": 12500,
"gpu_time_delta": 0, "pageins_delta": 0, "logical_writes_delta": 98304,
"interval_max_phys_footprint": 1520000000, "running_threads": 3, "priority": 31,
"task": { "context_switches": 18422, "faults": 9310, "cow_faults": 412, "syscalls_mach": 51203,
"syscalls_unix": 8874, "messages_sent": 25100, "messages_received": 25098 },
"wakeups": { "interrupt": 4120, "pkg_idle": 311 },
"child": { "user_time_ns": 0, "system_time_ns": 0, "pageins": 0,
"interrupt_wkups": 0, "pkg_idle_wkups": 0, "elapsed_ns": 0 },
"qos": { "default_ns": 12000000, "maintenance_ns": 0, "background_ns": 140000000, "utility_ns": 3419969,
"legacy_ns": 0, "user_initiated_ns": 0, "user_interactive_ns": 0 },
"cores": { "performance_ns": 12000000, "efficiency_ns": 143419969 }
},
"score": { "total": 94, "cpu_component": 1.0, "gpu_component": 0.0, "io_component": 0.75,
"mem_component": 1.0, "net_component": 0.0, "energy_component": 0.8 },
"severity": { "level": "Warning", "dominant": "cpu",
"readings": [ { "resource": "cpu", "level": "Warning", "value": 160.6 }, ... ] }
}
sample.observed_atis wall-clock time for display.sample.interval_secsis the monotonic time since the previous successful observation; every*_deltacovers exactly that span, sorate = delta / interval_secs.rateskeys end in_per_sec:cpu_time_ns,gpu_time_ns,disk_read_bytes,disk_write_bytes,logical_write_bytes,net_io_bytes,instructions,cycles,energy_nj,pageins,wakeups_interrupt,wakeups_pkg_idle,context_switches,faults,cow_faults,syscalls_mach,syscalls_unix,messages_sent,messages_received.nullon a first observation; a group whose status is notmeasuredis left out.severity.readingsunits:cpu% of one core,memorybytes of footprint,diskandnetworkbytes/s,energyW,wakeupsper second, smoothed over about a minute.sample.statussays per group whether a value ismeasured,baseline,unavailable,unsupportedorestimated. See Measurement status.coresisnullon a Mac with one kind of core.
GetProcessDetail
One live process with its lifecycle. Params: name (required without pid; with pid a cross-check; case-insensitive fallback), pid.
{
"process": { "sample": { ... }, "score": { ... }, "rates": { ... } },
"lifecycle": {
"instance": { "boot_session": "3FEED9A0-...", "pid": 2533, "start_time": 1700000000 },
"name": "Safari", "first_seen": 1700000000, "last_seen": 1700003600,
"peak_rss": 800000000, "peak_phys_footprint": 600000000, "alive": true
}
}
Lifecycle is per run: a restart does not inherit the peaks of the run it replaced. An exited run is kept 5 minutes. Errors: -32602 missing name, -32001 nothing matches, -32004 several processes match and no pid was given (error.data.candidates lists pid, start_time, ppid, command, score).
GetProcessThreads reads the OS
Per-thread breakdown, read from the kernel at the moment of the call. One syscall per thread, so it is never part of the sampling loop. Params: pid (required, positive), start_time (optional, checked).
{
"pid": 765, "start_time": 91827364, "boot_session": "3FEED9A0-...",
"threads": [{
"tid": 8503157344, "name": "com.apple.main-thread",
"user_time_ns": 35915800000, "system_time_ns": 10251200000, "cpu_usage_pct": 12.5,
"run_state": "Running", "qos_band": "UserInteractive",
"base_priority": 47, "current_priority": 46, "sleep_time_secs": 0, "idle": false
}]
}
- Sorted by total CPU time, hottest first. CPU times are cumulative;
cpu_usage_pctis an instant. run_state:Running,Stopped,Waiting,Uninterruptible,Halted,Unknown. Uninterruptible on an idle-looking process is usually a wedged I/O or an unresponsive mount.qos_bandis an estimate from the base priority (macOS has no public per-thread QoS query for another process):UserInteractive47,UserInitiated37,Default31,Utility20,Background4 (also maintenance),Unspecifiedotherwise.- The identity is read before and after the walk, so a PID reused mid-call is
-32005. An exited PID is-32001, a PID you may not read-32002, never an empty list.
GetProcessInspect reads the OS
Params: pid, start_time (optional). Returns { pid, start_time, usage, files, files_truncated }: lifetime counters (CPU time, context switches, faults, page-ins, Mach messages, system calls, memory) and up to 500 open files and sockets. The run is checked before and after the reads.
GetProcessTree
Processes grouped by parent PID. Params: none. Returns an array of { parent_pid, parent_name, children: [ScoredProcess] }, sorted by parent_pid. parent_name is null when the parent is not tracked. The tree aggregates no counters (see reaped children in Concepts).
AI and builds
GetAgentSessions
Each running AI agent with its descendants, as one consumer. Params: none.
[{ "agent": "Claude Code", "pid": 100, "start_time": 412345678901, "pids": [100, 101, 102],
"cpu_pct_of_core": 95.0, "footprint_bytes": 1320000000, "energy_watts": 5.5 }]
Busiest CPU first. See Agent sessions for the membership rules.
GetLeftBehindProcesses
Live processes an exited agent started that still use at least 1% of a core or 50 MiB. Params: none.
[{ "pid": 101, "start_time": 412345678901, "name": "node", "command": "/opt/homebrew/bin/node",
"agent": "Claude Code", "agent_pid": 100, "cpu_pct_of_core": 30.0, "footprint_bytes": 209715200 }]
GetModelRuntimes
Each local model runtime (Ollama, LM Studio, llama.cpp) as one row, and the runtime that pushed the Mac into swap, if one did. Params: none.
{
"runtimes": [{ "runtime": "Ollama", "pid": 100, "start_time": 412345678901, "pids": [100, 101],
"footprint_bytes": 7650000000, "gpu_pct": 40.0, "cpu_pct_of_core": 20.0,
"footprint_growth_bytes": 6440000000 }],
"swap_used_bytes": 3220000000, "swap_growth_bytes": 3220000000, "span_secs": 120.0,
"swap_cause": { "runtime": "Ollama", "pid": 100, "start_time": 412345678901,
"footprint_growth_bytes": 6440000000, "swap_growth_bytes": 3220000000, "span_secs": 120.0 }
}
swap_cause: the runtime whose footprint grew most, by at least 512 MiB, while swap grew by at least 256 MiB over the same span; else null. The trend keeps one point per 30-second write, for at most 5 minutes.
GetBuildWarning, SetBuildWarning
SetBuildWarning params: min_builds (2–32), min_minutes (1–240), or both. The app and the CLI may change them; other peers may only read.
{
"min_builds": 3, "min_minutes": 10,
"warning": { "since": 1779366600, "builds": [
{ "pid": 4100, "start_time": 412345678901, "name": "cargo",
"cwd": "/Users/u/src/a", "compilers": 12, "active_secs": 1260 } ] }
}
warning is null while the condition does not hold; since stays the same for one episode.
History
GetProcessInstances
The runs of a program that left history under a name. Params: name (required), window.
[{ "instance": { "boot_session": "3FEED9A0-...", "pid": 998, "start_time": 91998112 },
"pid": 998, "name": "node", "first_seen": 1779366600, "last_seen": 1779366690, "samples": 4 }]
Most recently seen first. "instance": null: rows written before identity was recorded; never merged with an identified run.
GetProcessHistory
Time-bucketed history for a name, or for one run. Params: name (required), window, pid + start_time (together, or neither).
{
"name": "node", "grouping": "by_name",
"points": [{ "timestamp": 1779366600, "resolution_secs": 300, "avg_score": 32.0, "max_score": 32,
"cpu_ns": 689117940, "io_bytes": 14622720, "covered_secs": 300.0,
"cpu_ns_per_sec": 2297059.8, "io_bytes_per_sec": 48742.4, "mem_resident": 1793179648.0,
"counters": { "...": { "total": 0, "per_sec": 0 } }, "gauges": { "...": 0 } }]
}
grouping:by_name(every process with the name, together) orby_instance(one run, raw rows only, back 24 hours).- Counters are summed per bucket; rates use
covered_secs, so they do not depend on how often rows were stored. counters: every other counter as{ total, per_sec }.gauges: the highest value in the bucket. A total isnull, not partial, when any row predates the counter.- Each stretch of the window is read from exactly one tier;
resolution_secscan exceed the asked width for older history. The window end is inclusive.
GetBatteryHistory
Params: window. Returns [{ timestamp, capacity_pct, amperage, is_charging }].
GetTopConsumers
Top energy-consuming processes as series. Params: window, limit (default 5). Returns [{ name, points: [[timestamp, score], ...] }].
GetSystemStateHistory
Params: window. Returns time-bucketed SystemState objects, values averaged per bucket. A bucket reports the worst thermal level actually read, and Unknown only with no reading at all.
GetSystemResourceHistory
What the monitored processes did together. Params: window.
[{ "timestamp": 1779366690, "total_cpu_ns": 500000000.0, "total_disk_read": 1048576.0,
"total_disk_write": 524288.0, "total_net_io": 0.0, "monitored_mem_avg": 8589934592.0,
"monitored_score_avg": 250.0, "resolution_secs": 30 }]
total_* are counters summed over every process and interval. monitored_*_avg are gauges: the sum across processes at one instant, averaged over the instants in the bucket. These are sums over sampled processes, not host measurements.
GetClassBreakdown
Params: window. Returns [{ class, total_score, process_count }].
GetScanCorrelation
Params: scanners (names), window. Returns { bucket_secs, scanners, scanner_cpu, suspects, note }: the scanner processes summed as one consumer per bucket (% of one core), and up to 10 processes whose disk rate correlates with it (Pearson r ≥ 0.3 over every bucket, at least 6 buckets). A co-movement, not a cause.
Watches
AddWatch, RemoveWatch, ListWatches
A watch stores its target at every 30-second write, whatever its score.
| AddWatch param | Meaning |
|---|---|
pid + start_time | One run. A PID alone is rejected. |
name | A group: every process with that name, now or later. |
ttl_secs | 1 to 86 400, default 3600. Every watch expires. |
{ "id": 3, "target": { "kind": "instance", "boot_session": "...", "pid": 998, "start_time": 91998112 },
"created_at": 1779366600, "expires_at": 1779370200 }
A group target is { "kind": "group", "name": "node" }. At most 16 active (-32007). RemoveWatch { id } returns { removed } or -32006. ListWatches returns each with samples, first_sample_at, last_sample_at. Watches survive a restart.
Network
GetConnections
The latest successful socket scan. Params: process (optional name filter). The scan runs every 10 s only while a client is subscribed; check observed_at or subscribe first.
{
"observed_at": 1759400000, "pids_scanned": 612, "pids_failed": 41, "last_failure": null,
"connections": [{ "pid": 2533, "process_name": "Spotify Helper (Renderer)", "remote_ip": "35.186.224.25",
"remote_port": 443, "local_port": 54321, "protocol": "Tcp", "state": "Established" }]
}
An empty list proves no open sockets only when pids_failed is 0. A failed scan never replaces connections; it is reported in last_failure.
GetHostTraffic
Bytes per process and remote host, from 5-minute buckets. Params: since (default until − 3600, raised to the 7-day limit), until (default now), process, limit (default 100, max 500).
Returns [{ process, remote_ip, bytes_in, bytes_out, scope, country, asn, org, cdn, ai_provider }], largest first. A bucket is counted whole when any part of it is in range. Empty while network detail is off.
LookupGeo
Country and network of addresses, from the offline IPLocate file in the app bundle. No address leaves the Mac. Params: ips (at most 512; one invalid address fails the call with -32602).
| Field | Meaning |
|---|---|
scope | local (loopback, private, link-local, CGNAT, unique-local, multicast; never looked up) or public. |
country | ISO 3166-1 alpha-2, or null. |
asn, org | Autonomous system number and its owner, or null. |
cdn | true for a CDN or anycast network. |
ai_provider | The AI provider that owns the network, else null. CDN traffic is never labelled AI. |
GetNewNetworks
Processes that used a network (AS) they did not use in the 7 days before. Params: none. Returns [{ at, process, asn, org }], newest first, at most 100. Kept in memory; a restart clears it. See New networks.
GetNetworkDetail, SetNetworkDetail set: signed app/CLI
GetNetworkDetail → { on }. SetNetworkDetail { on } is stored and applied at the next sample tick (5 s). Off: totals per process only, no host map, no scan, and the last scan is dropped.
Control
ApplyAction, GetActionSettings, SetActionSettings, GetActionLog signed app/CLI
ApplyAction { action, pid?, start_time? }, action one of background, foreground, terminate, pause, resume, stop_backup, purge. The daemon checks the caller's code signature (from the socket's audit token), the action's setting (and its CLI switch for the CLI), the target run, and the protected list. Every attempt is logged.
GetActionSettings→{ settings: { kind: { enabled, cli } }, caller }.SetActionSettings { kind, enabled, cli }: from the signed app only.GetActionLog { limit? }→ attempts, newest first (the last 10 000 are kept).
Restart signed app/CLI
No params → { restarting: true }. The daemon replies, writes pending host traffic, removes its socket and PID file and exits 0; launchd starts it again. Another peer gets -32010.
SampleProcess signed app/CLI
{ pid?, name?, seconds? } → { pid, seconds, report }. Runs /usr/bin/sample (absolute path, no shell) and returns the call graph. Neither pid nor name: the daemon itself. Both: -32602. seconds default 10, clamped to 1..60. A report above 16 MiB is cut. One at a time (-32012). The sample runs on a blocking thread, so the monitor continues.
Push events
Subscribe
No params → { "subscribed": true }. The server then sends notifications (no id) on this connection:
| Method | Payload | When |
|---|---|---|
ProcessSnapshot | ScoredProcess[] (with interval_secs, no rates) | Every sample |
BatteryUpdate | BatteryState | Battery change |
SystemStateUpdate | SystemState | System state change |
ConnectionUpdate | { observed_at, pids_scanned, pids_failed, connections } | Every successful socket scan, empty ones included |
NewNetwork | { at, process, asn, org } | An app used a new network |
A slow subscriber misses events; they are counted in GetStatus.collector.subscriber_lagged_events.
Error codes
| Code | Meaning |
|---|---|
-32700 | Parse error (invalid JSON). |
-32601 | Method not found. |
-32602 | Invalid params. |
-32000 | Platform failure not covered by a more specific code. |
-32001 | Process not found: it exited, or never existed. Drop it. |
-32002 | Permission denied: out of reach for this user. Ask for privileges. |
-32003 | Not supported on this platform. |
-32004 | Ambiguous name; error.data.candidates lists the runs. |
-32005 | Wrong process: the PID belongs to another run; error.data has expected_start_time and actual_start_time. Re-resolve the name. |
-32006 | Watch not found. |
-32007 | Too many active watches. |
-32008 | Storage failure: a daemon defect, not missing data. |
-32010 | Refused: not the signed app or CLI, action off or not allowed from the CLI, or a protected target. |
-32011 | Action failed: the OS refused. |
-32012 | Busy: another sample is running. |