worktrust 0.11.12 → 0.11.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +57 -0
- package/README.md +19 -4
- package/SECURITY.md +13 -0
- package/cli-menu-remote.mjs +8 -4
- package/engine-release.json +1 -1
- package/package-release.json +1 -1
- package/package.json +4 -2
- package/remote-cli.mjs +5 -3
- package/remote-connections.mjs +5 -3
- package/remote-daemon.mjs +59 -6
- package/remote-desk-sessions.mjs +192 -0
- package/remote-health.mjs +220 -0
- package/remote-protocol.mjs +189 -16
- package/remote-run.mjs +27 -5
- package/remote-sessions.mjs +2 -2
- package/remote-settings.mjs +49 -1
- package/remote-terminal-sessions.mjs +1 -0
- package/worktrust.mjs +2 -2
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CONTINUE A SESSION ON THIS COMPUTER (release 36, owner 2026-11-15: "via the remote link, get into the current session, so
|
|
3
|
+
* we don't have to scan tomorrow"; docs/remote-agents/DESK-SESSIONS.md). The phone or the browser lists this computer's
|
|
4
|
+
* recent Claude Code sessions and continues one through the daemon's own start (`agent.start` with `resume`).
|
|
5
|
+
*
|
|
6
|
+
* WHAT IS READ: Claude Code's own transcript store, `~/.claude/projects/<the folder, encoded>/<session uuid>.jsonl`, and only
|
|
7
|
+
* the folders of GRANTED projects (the inventory's own list, roots' projects included): the encoded folder of each granted
|
|
8
|
+
* path is opened, never the store as a whole, and a transcript whose recorded `cwd` is not that project's path is dropped.
|
|
9
|
+
* Of a file only its first and last 64 KB are read, for the working folder, a title and the model.
|
|
10
|
+
*
|
|
11
|
+
* WHAT IS SENT, sealed in device.inventory and only to a phone that asked `desk_sessions` (remote-daemon.mjs): per session
|
|
12
|
+
* its uuid, its project's id, the last activity time, a title (Claude Code's own name or summary line when the transcript
|
|
13
|
+
* has one, else the first line the person typed, cut to 80 characters) and the model when one is recorded. Never more of the
|
|
14
|
+
* transcript. The last 20 by activity; sessions the remote already runs or ran (its journal) are its own rows.
|
|
15
|
+
*
|
|
16
|
+
* ONE OWNER PER CONVERSATION: a resume is refused (`in_use`) while the session is held on the computer: its transcript was
|
|
17
|
+
* written in the last 30 seconds, a Claude Code process names its id (`--resume <id>`, `--session-id <id>`), or a Claude
|
|
18
|
+
* Code process that names no session (an open interactive window, `--continue`) works in that project folder and started
|
|
19
|
+
* before the transcript's last line. A computer whose processes cannot be read counts as holding it (fails closed).
|
|
20
|
+
*/
|
|
21
|
+
import { spawnSync } from "node:child_process";
|
|
22
|
+
import { closeSync, fstatSync, lstatSync, openSync, readdirSync, readSync, readlinkSync, realpathSync } from "node:fs";
|
|
23
|
+
import { homedir } from "node:os";
|
|
24
|
+
import { join } from "node:path";
|
|
25
|
+
import * as P from "./remote-protocol.mjs";
|
|
26
|
+
|
|
27
|
+
export const HELD_WINDOW_MS = 30_000;
|
|
28
|
+
const SLICE = 64 * 1024;
|
|
29
|
+
const MAX_READS = 60; // transcripts opened per listing at most, newest first
|
|
30
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
31
|
+
const UUIDS = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
|
|
32
|
+
|
|
33
|
+
/** Claude Code's name for a project's folder in its store: every character that is not a letter or a digit becomes "-". */
|
|
34
|
+
export const encodeProjectDir = (path) => path.replace(/[^A-Za-z0-9]/g, "-");
|
|
35
|
+
const real = (path) => { try { return realpathSync(path); } catch { return path; } };
|
|
36
|
+
const samePath = (a, b) => typeof a === "string" && typeof b === "string" && (a === b || real(a) === real(b));
|
|
37
|
+
|
|
38
|
+
/** The first and the last 64 KB of a file, as whole JSON lines (a line cut at a slice's edge is left out). */
|
|
39
|
+
function headAndTail(file) {
|
|
40
|
+
const fd = openSync(file, "r");
|
|
41
|
+
try {
|
|
42
|
+
const size = fstatSync(fd).size;
|
|
43
|
+
const read = (at, length) => { const buf = Buffer.alloc(length); const n = readSync(fd, buf, 0, length, at); return buf.subarray(0, n).toString("utf8"); };
|
|
44
|
+
const head = read(0, Math.min(size, SLICE));
|
|
45
|
+
const tail = size > SLICE ? read(Math.max(SLICE, size - SLICE), Math.min(SLICE, size - SLICE)) : "";
|
|
46
|
+
const lines = (text, cutFirst, cutLast) => { const all = text.split("\n"); if (cutFirst) all.shift(); if (cutLast) all.pop(); return all; };
|
|
47
|
+
const parse = (all) => all.map((l) => { try { const v = JSON.parse(l); return v && typeof v === "object" ? v : null; } catch { return null; } }).filter(Boolean);
|
|
48
|
+
return { head: parse(lines(head, false, size > SLICE)), tail: parse(lines(tail, true, false)) };
|
|
49
|
+
} finally { closeSync(fd); }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const oneLine = (text) => text.replace(/\s+/g, " ").trim();
|
|
53
|
+
const cut = (text, max) => { const t = oneLine(text); return t.length > max ? `${t.slice(0, max - 1).trimEnd()}…` : t; };
|
|
54
|
+
/** The words of a person's own message: a string, or its text blocks; never a tool result, a command's output or a caveat. */
|
|
55
|
+
function typed(line) {
|
|
56
|
+
if (line.type !== "user" || line.isMeta === true || line.isSidechain === true || line.message?.role !== "user") return null;
|
|
57
|
+
const c = line.message.content;
|
|
58
|
+
const text = typeof c === "string" ? c : Array.isArray(c) && c.every((b) => b?.type === "text") ? c.map((b) => b.text ?? "").join(" ") : null;
|
|
59
|
+
if (!text || /^\s*<(command-|local-command-|bash-|system-reminder)/.test(text) || /^\s*Caveat:/.test(text)) return null;
|
|
60
|
+
return oneLine(text) || null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** What one transcript tells: its working folder, a title and the model. Nothing else is kept. */
|
|
64
|
+
export function transcriptFacts(file) {
|
|
65
|
+
const { head, tail } = headAndTail(file);
|
|
66
|
+
const all = [...head, ...tail];
|
|
67
|
+
const cwd = head.find((l) => typeof l.cwd === "string")?.cwd ?? null;
|
|
68
|
+
const named = all.filter((l) => l.type === "custom-title" && typeof l.customTitle === "string").at(-1)?.customTitle
|
|
69
|
+
?? all.filter((l) => l.type === "summary" && typeof l.summary === "string").at(-1)?.summary ?? null;
|
|
70
|
+
const first = head.map(typed).find(Boolean) ?? null;
|
|
71
|
+
const title = named && oneLine(named) ? cut(named, P.MAX_DESK_TITLE) : first ? cut(first, P.MAX_DESK_TITLE) : null;
|
|
72
|
+
const models = all.filter((l) => l.type === "assistant" && typeof l.message?.model === "string" && /^[A-Za-z0-9._:@\[\]-]{1,128}$/.test(l.message.model) && l.message.model !== "<synthetic>");
|
|
73
|
+
return { cwd, title, model: models.at(-1)?.message.model ?? null };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The newest Claude Code sessions of the granted projects, at most MAX_DESK_SESSIONS: `{ session_ref, project_id,
|
|
78
|
+
* last_activity_at, title, model }` plus, kept on this computer, the transcript's file and the project's path.
|
|
79
|
+
* `exclude`: the agent ids the remote's own journal holds. `cache`: facts by file, size and time, so a listing rereads none.
|
|
80
|
+
*/
|
|
81
|
+
export function deskSessions({ home = homedir(), projects, exclude = new Set(), cache = new Map() }) {
|
|
82
|
+
const store = join(home, ".claude", "projects"), found = [];
|
|
83
|
+
for (const project of projects) {
|
|
84
|
+
const dir = join(store, encodeProjectDir(project.path));
|
|
85
|
+
let names = [];
|
|
86
|
+
try { if (!lstatSync(dir).isDirectory()) continue; names = readdirSync(dir); } catch { continue; }
|
|
87
|
+
for (const name of names) {
|
|
88
|
+
const ref = name.endsWith(".jsonl") ? name.slice(0, -6) : null;
|
|
89
|
+
if (!ref || !UUID.test(ref) || exclude.has(ref)) continue;
|
|
90
|
+
try { const st = lstatSync(join(dir, name)); if (st.isFile()) found.push({ ref, file: join(dir, name), project, mtime: Math.floor(st.mtimeMs), size: st.size }); } catch { /* gone */ }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
found.sort((a, b) => b.mtime - a.mtime);
|
|
94
|
+
const out = [], seen = new Set();
|
|
95
|
+
for (const f of found.slice(0, MAX_READS)) {
|
|
96
|
+
if (out.length >= P.MAX_DESK_SESSIONS) break;
|
|
97
|
+
if (seen.has(f.ref)) continue; // two granted paths, one folder
|
|
98
|
+
const key = `${f.file}|${f.size}|${f.mtime}`;
|
|
99
|
+
let facts = cache.get(key);
|
|
100
|
+
if (!facts) { try { facts = transcriptFacts(f.file); } catch { continue; } cache.set(key, facts); }
|
|
101
|
+
if (!samePath(facts.cwd, f.project.path)) continue; // another folder whose name encodes the same: not this project
|
|
102
|
+
seen.add(f.ref);
|
|
103
|
+
out.push({ session_ref: f.ref, project_id: f.project.project_id, last_activity_at: f.mtime, title: facts.title, model: facts.model, file: f.file, projectPath: f.project.path });
|
|
104
|
+
}
|
|
105
|
+
if (cache.size > 200) for (const k of [...cache.keys()].slice(0, cache.size - 200)) cache.delete(k);
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** What leaves the computer, field by field: never the file or the path. */
|
|
110
|
+
export const deskRow = (d) => ({ session_ref: d.session_ref, project_id: d.project_id, last_activity_at: d.last_activity_at, title: d.title, model: d.model });
|
|
111
|
+
|
|
112
|
+
/** "[[dd-]hh:]mm:ss" from ps, in milliseconds. */
|
|
113
|
+
export function elapsedMs(text) {
|
|
114
|
+
const m = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(String(text).trim());
|
|
115
|
+
return m ? ((Number(m[1] ?? 0) * 24 + Number(m[2] ?? 0)) * 3600 + Number(m[3]) * 60 + Number(m[4])) * 1000 : null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const CLAUDE_BIN = /(^|[/\\])claude(\.exe)?$/i;
|
|
119
|
+
/** Whether a command line is Claude Code: its `claude` program, its npm package, or a native build in its versions folder. */
|
|
120
|
+
export const isClaudeCommand = (args) => {
|
|
121
|
+
const first = String(args).trim().split(/\s+/)[0] ?? "";
|
|
122
|
+
return CLAUDE_BIN.test(first) || /@anthropic-ai[/\\]claude-code[/\\]/.test(args) || /[/\\]claude[/\\]versions[/\\][^\s/\\]+(\s|$)/.test(args);
|
|
123
|
+
};
|
|
124
|
+
/** One process as the held rule reads it: the session ids its command line names, whether it continues the newest one. */
|
|
125
|
+
export const processOf = (pid, args, startedAt, cwd) => ({ pid, startedAt, cwd, ids: [...new Set((String(args).match(UUIDS) ?? []).map((u) => u.toLowerCase()))], continues: /(^|\s)(-c|--continue)(\s|$)/.test(args) });
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* The Claude Code processes running on this computer, or null when they cannot be read. Fixed arguments, no shell: `ps`
|
|
129
|
+
* (and the working folder from /proc on Linux, `lsof` on macOS). Windows has no process list without a shell, so there the
|
|
130
|
+
* answer is null: nothing can be shown free, and the desk lists nothing (createDesk).
|
|
131
|
+
*/
|
|
132
|
+
export function claudeProcesses({ platform = process.platform, now = Date.now(), run = spawnSync } = {}) {
|
|
133
|
+
if (platform === "win32") return null;
|
|
134
|
+
const output = (file, args) => { const r = run(file, args, { encoding: "utf8", timeout: 5_000, stdio: ["ignore", "pipe", "ignore"], maxBuffer: 8 * 1024 * 1024, windowsHide: true }); return r.status === 0 ? `${r.stdout ?? ""}` : null; };
|
|
135
|
+
const out = output("ps", ["axww", "-o", "pid=,etime=,args="]);
|
|
136
|
+
if (out === null) return null;
|
|
137
|
+
const procs = [];
|
|
138
|
+
for (const line of out.split("\n")) {
|
|
139
|
+
const m = /^\s*(\d+)\s+(\S+)\s+(.*)$/.exec(line);
|
|
140
|
+
if (!m || Number(m[1]) === process.pid || !isClaudeCommand(m[3])) continue;
|
|
141
|
+
const age = elapsedMs(m[2]);
|
|
142
|
+
procs.push(processOf(Number(m[1]), m[3], age === null ? 0 : now - age, null));
|
|
143
|
+
}
|
|
144
|
+
if (procs.length === 0) return procs;
|
|
145
|
+
if (platform === "linux") for (const p of procs) { try { p.cwd = readlinkSync(`/proc/${p.pid}/cwd`); } catch { /* not ours to read: unknown */ } }
|
|
146
|
+
else {
|
|
147
|
+
const lsof = output("lsof", ["-a", "-d", "cwd", "-Fn", "-p", procs.map((p) => p.pid).join(",")]);
|
|
148
|
+
let pid = null;
|
|
149
|
+
for (const l of (lsof ?? "").split("\n")) { if (l.startsWith("p")) pid = Number(l.slice(1)); else if (l.startsWith("n") && pid !== null) { const p = procs.find((x) => x.pid === pid); if (p) p.cwd = l.slice(1); } }
|
|
150
|
+
}
|
|
151
|
+
return procs;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Why a session is held on the computer, or null when it is free to continue here. */
|
|
155
|
+
export function heldBy(entry, { now, procs }) {
|
|
156
|
+
if (now - entry.last_activity_at < HELD_WINDOW_MS) return "recent";
|
|
157
|
+
if (procs === null) return "unknown";
|
|
158
|
+
for (const p of procs) {
|
|
159
|
+
if (p.ids.includes(entry.session_ref)) return "process";
|
|
160
|
+
if (p.ids.length === 0 && (p.cwd === null || samePath(p.cwd, entry.projectPath)) && (p.continues || p.startedAt <= entry.last_activity_at)) return "window";
|
|
161
|
+
}
|
|
162
|
+
return null;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* The daemon's desk: `list()` the inventory's rows, `resumable(ref, projectId)` → null, `not_found` (not in this computer's
|
|
167
|
+
* own list, or not under that project) or `in_use` (held). Both read the store afresh; nothing from a phone is trusted.
|
|
168
|
+
*/
|
|
169
|
+
export function createDesk({ projects, journal, now = Date.now, home = homedir(), processes = () => claudeProcesses(), platform = process.platform }) {
|
|
170
|
+
const cache = new Map();
|
|
171
|
+
const own = () => new Set(journal.sessions().map((j) => j.agent_session_ref).filter((r) => typeof r === "string"));
|
|
172
|
+
const scan = () => deskSessions({ home, projects: projects(), exclude: own(), cache });
|
|
173
|
+
return {
|
|
174
|
+
list: () => (platform === "win32" ? [] : scan().map(deskRow)), // Windows: no process list without a shell, so none is shown free
|
|
175
|
+
resumable(ref, projectId) {
|
|
176
|
+
const found = typeof ref === "string" ? scan().find((d) => d.session_ref === ref) : null;
|
|
177
|
+
if (!found || found.project_id !== projectId) return "not_found";
|
|
178
|
+
return heldBy(found, { now: now(), procs: processes() }) ? "in_use" : null;
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* What a channel hears of the desk (remote-daemon.mjs bodyFor): a phone that asked `desk_sessions` hears all of it; any
|
|
185
|
+
* other never receives the key it would refuse, and a refusal it does not know (`in_use`) reaches it as `busy`.
|
|
186
|
+
*/
|
|
187
|
+
export function deskBodyFor(asked, type, body) {
|
|
188
|
+
if (asked) return body;
|
|
189
|
+
if (type === "device.inventory" && body && "desk_sessions" in body) { const { desk_sessions: _drop, ...rest } = body; return rest; }
|
|
190
|
+
if (type === "command.rejected" && body?.reason === "in_use") return { ...body, reason: "busy" };
|
|
191
|
+
return body;
|
|
192
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* THE COMPUTER'S HEALTH, MEASURED HERE (owner, 2026-11-15: "the computer sometimes crashes from RAM/GPU load").
|
|
3
|
+
* The Remote daemon reads a few numbers of this machine every 15 seconds, without a model (no tokens) and without sudo,
|
|
4
|
+
* keeps the newest in ~/.worktrust/remote/health.json (0600, this computer only) for `remote status` and the menu, and
|
|
5
|
+
* seals it for the paired phones and browsers on the transient lane (remote-protocol health.ts): the server never sees
|
|
6
|
+
* or stores a sample. While red, the daemon starts no new session (remote-daemon.mjs); running sessions continue.
|
|
7
|
+
*
|
|
8
|
+
* What is run, each through execFile with FIXED arguments, a fixed PATH, a timeout and an output cap; nothing from a
|
|
9
|
+
* phone, a file or the environment reaches an argument:
|
|
10
|
+
* macOS /usr/sbin/sysctl kern.memorystatus_vm_pressure_level kern.memorystatus_level vm.swapusage hw.memsize
|
|
11
|
+
* (the kernel's own pressure level 1/2/4 and the share of memory available, which `memory_pressure` prints
|
|
12
|
+
* too; sysctl reads them in one call without sudo, where `memory_pressure` runs a slower test of its own)
|
|
13
|
+
* /usr/sbin/ioreg -r -d 1 -cIOAccelerator ("Device Utilization %" of the Apple GPU; null when absent)
|
|
14
|
+
* /bin/ps -axo rss=,comm= (resident memory and the program, never `args` or `command`)
|
|
15
|
+
* Linux /proc/meminfo, /proc/pressure/memory (when the kernel has PSI), /proc/loadavg, and ps -eo rss=,comm=
|
|
16
|
+
* Windows free memory (os.freemem) and the load from the CPU times between two samples; nothing is run
|
|
17
|
+
* A program is named by its BASENAME only (a path is cut to its last part), summed over its processes; a name the
|
|
18
|
+
* protocol would refuse (an argument, a setting, a URL) is left out. A read that failed is null, never 0.
|
|
19
|
+
*/
|
|
20
|
+
import { execFile } from "node:child_process";
|
|
21
|
+
import { readFileSync } from "node:fs";
|
|
22
|
+
import os from "node:os";
|
|
23
|
+
import * as P from "./remote-protocol.mjs";
|
|
24
|
+
import { readJson, writeJson } from "./remote-store.mjs";
|
|
25
|
+
|
|
26
|
+
const TIMEOUT_MS = 4000, MAX_BUFFER = 4 * 1024 * 1024;
|
|
27
|
+
const SAFE_ENV = { PATH: "/usr/bin:/bin:/usr/sbin:/sbin", LC_ALL: "C" };
|
|
28
|
+
/** Every command this module may run, whole. check-remote-cli rule H reads this list: no `args`, no `command`. */
|
|
29
|
+
export const HEALTH_COMMANDS = Object.freeze({
|
|
30
|
+
sysctl: Object.freeze(["/usr/sbin/sysctl", Object.freeze(["kern.memorystatus_vm_pressure_level", "kern.memorystatus_level", "vm.swapusage", "hw.memsize"])]),
|
|
31
|
+
ioreg: Object.freeze(["/usr/sbin/ioreg", Object.freeze(["-r", "-d", "1", "-cIOAccelerator"])]),
|
|
32
|
+
psMac: Object.freeze(["/bin/ps", Object.freeze(["-axo", "rss=,comm="])]),
|
|
33
|
+
psLinux: Object.freeze(["ps", Object.freeze(["-eo", "rss=,comm="])]),
|
|
34
|
+
});
|
|
35
|
+
export const HEALTH_REFUSAL = "This computer is under heavy memory load";
|
|
36
|
+
const MB = 1024 * 1024;
|
|
37
|
+
|
|
38
|
+
/** One fixed command; its output, or null (failed, timed out, too long). A command that printed and exited non-zero still counts. */
|
|
39
|
+
export function runFixed(key) {
|
|
40
|
+
const [file, args] = HEALTH_COMMANDS[key];
|
|
41
|
+
return new Promise((done) => {
|
|
42
|
+
execFile(file, [...args], { timeout: TIMEOUT_MS, maxBuffer: MAX_BUFFER, windowsHide: true, env: SAFE_ENV, encoding: "utf8" }, (error, stdout) => {
|
|
43
|
+
done(error && (error.killed || typeof error.code !== "number" || !stdout) ? null : String(stdout ?? ""));
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const int = (v) => (Number.isFinite(v) ? Math.round(v) : null);
|
|
49
|
+
|
|
50
|
+
/** `sysctl` (names shown) on macOS: by name, so one missing key leaves the others readable. */
|
|
51
|
+
export function parseMacSysctl(text) {
|
|
52
|
+
const out = { pressure: null, memory_total_mb: null, memory_free_mb: null, swap_used_mb: null };
|
|
53
|
+
if (typeof text !== "string") return out;
|
|
54
|
+
const value = (name) => text.match(new RegExp(`^${name.replace(/\./g, "\\.")}:\\s*(.+)$`, "m"))?.[1]?.trim() ?? null;
|
|
55
|
+
out.pressure = { 1: "normal", 2: "warn", 4: "critical" }[Number(value("kern.memorystatus_vm_pressure_level"))] ?? null;
|
|
56
|
+
const bytes = Number(value("hw.memsize"));
|
|
57
|
+
if (Number.isSafeInteger(bytes) && bytes > 0) out.memory_total_mb = int(bytes / MB);
|
|
58
|
+
const level = Number(value("kern.memorystatus_level"));
|
|
59
|
+
if (out.memory_total_mb !== null && value("kern.memorystatus_level") !== null && level >= 0 && level <= 100) out.memory_free_mb = int((out.memory_total_mb * level) / 100);
|
|
60
|
+
out.swap_used_mb = parseSwapUsage(value("vm.swapusage"));
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** "total = 10240.00M used = 8911.38M free = 1328.62M (encrypted)" → 8911. */
|
|
65
|
+
export function parseSwapUsage(text) {
|
|
66
|
+
const m = typeof text === "string" ? text.match(/used\s*=\s*([\d.]+)([KMG])/) : null;
|
|
67
|
+
if (!m) return null;
|
|
68
|
+
return int(Number(m[1]) * { K: 1 / 1024, M: 1, G: 1024 }[m[2]]);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The highest "Device Utilization %" of any accelerator, 0 to 100; null when none reports one. */
|
|
72
|
+
export function parseIoreg(text) {
|
|
73
|
+
if (typeof text !== "string") return null;
|
|
74
|
+
const all = [...text.matchAll(/"Device Utilization %"\s*=\s*(\d+)/g)].map((m) => Number(m[1])).filter((n) => n >= 0 && n <= 100);
|
|
75
|
+
return all.length ? Math.max(...all) : null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** A program's name for the sample: the basename, without control characters, at most 64; null when the protocol refuses it. */
|
|
79
|
+
export function programName(comm) {
|
|
80
|
+
const base = String(comm).trim().split(/[/\\]/).pop().replace(/[\u0000-\u001f\u007f]/g, "").trim().slice(0, P.MAX_PROCESS_NAME);
|
|
81
|
+
return base && P.processNameRefusal(base) === null ? base : null;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** `ps -o rss=,comm=`: the three programs holding the most memory, summed over their processes, largest first. */
|
|
85
|
+
export function parsePs(text) {
|
|
86
|
+
if (typeof text !== "string") return [];
|
|
87
|
+
const sums = new Map();
|
|
88
|
+
for (const line of text.split("\n")) {
|
|
89
|
+
const m = line.match(/^\s*(\d+)\s+(.+)$/);
|
|
90
|
+
if (!m) continue;
|
|
91
|
+
const name = programName(m[2]);
|
|
92
|
+
if (name) sums.set(name, (sums.get(name) ?? 0) + Number(m[1]));
|
|
93
|
+
}
|
|
94
|
+
return [...sums].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, 3).map(([name, kb]) => ({ name, memory_mb: Math.round(kb / 1024) }))
|
|
95
|
+
.filter((p, n, all) => n === 0 || p.memory_mb <= all[n - 1].memory_mb);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** /proc/meminfo: total, available, swap used (MB). */
|
|
99
|
+
export function parseMeminfo(text) {
|
|
100
|
+
const kb = (key) => { const m = typeof text === "string" ? text.match(new RegExp(`^${key}:\\s+(\\d+) kB`, "m")) : null; return m ? Number(m[1]) : null; };
|
|
101
|
+
const total = kb("MemTotal"), available = kb("MemAvailable"), swapTotal = kb("SwapTotal"), swapFree = kb("SwapFree");
|
|
102
|
+
return { memory_total_mb: total === null ? null : int(total / 1024), memory_free_mb: available === null ? null : int(available / 1024), swap_used_mb: swapTotal === null || swapFree === null ? null : int((swapTotal - swapFree) / 1024) };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** /proc/pressure/memory (PSI): critical when tasks were fully stalled 10 % of the last 10 s, warn when some were; else normal. */
|
|
106
|
+
export function parsePsi(text) {
|
|
107
|
+
const avg = (kind) => { const m = typeof text === "string" ? text.match(new RegExp(`^${kind} avg10=([\\d.]+)`, "m")) : null; return m ? Number(m[1]) : null; };
|
|
108
|
+
const some = avg("some"), full = avg("full");
|
|
109
|
+
if (some === null && full === null) return null;
|
|
110
|
+
if ((full ?? 0) >= 10) return "critical";
|
|
111
|
+
return (some ?? 0) >= 10 ? "warn" : "normal";
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export const parseLoadavg = (text) => { const n = typeof text === "string" ? Number(text.trim().split(/\s+/)[0]) : NaN; return Number.isFinite(n) && n >= 0 ? n : null; };
|
|
115
|
+
|
|
116
|
+
const cpuTimes = (cpus) => cpus.reduce((t, c) => { const v = c.times; const all = v.user + v.nice + v.sys + v.idle + v.irq; return { busy: t.busy + all - v.idle, all: t.all + all }; }, { busy: 0, all: 0 });
|
|
117
|
+
|
|
118
|
+
/** Swap used now minus the newest reading at least SWAP_GROWTH_WINDOW_MS old; null until there is one. */
|
|
119
|
+
export function swapGrowth(history, now, used) {
|
|
120
|
+
if (used === null) return null;
|
|
121
|
+
const old = history.filter((h) => h.at <= now - P.SWAP_GROWTH_WINDOW_MS && h.used !== null).at(-1);
|
|
122
|
+
return old ? used - old.used : null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* ONE SAMPLE. `o`: { platform, run(key) → text | null, read(path) → text | null, os: { totalmem, freemem, loadavg, cpus },
|
|
127
|
+
* now, swapHistory[] (kept by the caller), lastCpu (kept by the caller) }. Returns the protocol's body and the CPU times for the next.
|
|
128
|
+
*/
|
|
129
|
+
export async function sampleHealth(o) {
|
|
130
|
+
const now = o.now();
|
|
131
|
+
let reading = { pressure: null, memory_total_mb: null, memory_free_mb: null, swap_used_mb: null }, load = null, gpu = null, top = [];
|
|
132
|
+
const cores = o.os.cpus()?.length || null;
|
|
133
|
+
if (o.platform === "darwin") {
|
|
134
|
+
const [sys, io, ps] = await Promise.all([o.run("sysctl"), o.run("ioreg"), o.run("psMac")]);
|
|
135
|
+
reading = parseMacSysctl(sys);
|
|
136
|
+
gpu = parseIoreg(io);
|
|
137
|
+
top = parsePs(ps);
|
|
138
|
+
const avg = o.os.loadavg()[0];
|
|
139
|
+
load = Number.isFinite(avg) ? avg : null;
|
|
140
|
+
} else if (o.platform === "linux") {
|
|
141
|
+
const mem = parseMeminfo(o.read("/proc/meminfo"));
|
|
142
|
+
reading = { pressure: parsePsi(o.read("/proc/pressure/memory")), ...mem };
|
|
143
|
+
load = parseLoadavg(o.read("/proc/loadavg"));
|
|
144
|
+
top = parsePs(await o.run("psLinux"));
|
|
145
|
+
} else {
|
|
146
|
+
const total = o.os.totalmem(), free = o.os.freemem();
|
|
147
|
+
reading = { ...reading, memory_total_mb: total > 0 ? int(total / MB) : null, memory_free_mb: total > 0 && free >= 0 ? int(free / MB) : null };
|
|
148
|
+
}
|
|
149
|
+
// The load where no load average exists (Windows): the share of CPU time busy since the last sample, times the cores.
|
|
150
|
+
const cpu = cpuTimes(o.os.cpus() ?? []);
|
|
151
|
+
if (o.platform === "win32" && o.lastCpu && cpu.all > o.lastCpu.all && cores) load = ((cpu.busy - o.lastCpu.busy) / (cpu.all - o.lastCpu.all)) * cores;
|
|
152
|
+
if (reading.memory_free_mb !== null && reading.memory_total_mb !== null) reading.memory_free_mb = Math.min(reading.memory_free_mb, reading.memory_total_mb);
|
|
153
|
+
const swap_growth_mb = swapGrowth(o.swapHistory ?? [], now, reading.swap_used_mb);
|
|
154
|
+
const judged = P.healthLevel({ ...reading, swap_growth_mb });
|
|
155
|
+
const body = { sampled_at: now, level: judged.level, reasons: [...judged.reasons], ...reading, swap_growth_mb,
|
|
156
|
+
load_centi: load === null ? null : Math.min(100_000_000, int(load * 100)), cores, gpu_busy: gpu, top, refusing: judged.level === "red" };
|
|
157
|
+
return { body, cpu };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* The daemon's sampler: every HEALTH_SAMPLE_MS, one sample, never two at once. `onSample(body)` sends and keeps it.
|
|
162
|
+
* Readers are parameters so tests stub them with recorded output.
|
|
163
|
+
*/
|
|
164
|
+
export function createHealthMonitor({ onSample, platform = process.platform, run = runFixed, read = (p) => { try { return readFileSync(p, "utf8"); } catch { return null; } }, osInfo = os, now = Date.now, log = () => {}, intervalMs = P.HEALTH_SAMPLE_MS } = {}) {
|
|
165
|
+
let swapHistory = [], lastCpu = null, latest = null, busy = false, timer = null;
|
|
166
|
+
const tick = async () => {
|
|
167
|
+
if (busy) return;
|
|
168
|
+
busy = true;
|
|
169
|
+
try {
|
|
170
|
+
const { body, cpu } = await sampleHealth({ platform, run, read, os: osInfo, now, swapHistory, lastCpu });
|
|
171
|
+
lastCpu = cpu;
|
|
172
|
+
swapHistory = [...swapHistory.filter((h) => h.at > body.sampled_at - P.SWAP_GROWTH_WINDOW_MS * 2), { at: body.sampled_at, used: body.swap_used_mb }];
|
|
173
|
+
const checked = P.validateEventBody("device.health", body);
|
|
174
|
+
if (!checked.ok) { log("health_refused", { code: checked.code }); return; }
|
|
175
|
+
latest = body;
|
|
176
|
+
onSample(body);
|
|
177
|
+
} catch (e) { log("health_failed", { name: e?.name ?? "Error" }); } finally { busy = false; }
|
|
178
|
+
};
|
|
179
|
+
return {
|
|
180
|
+
start() { void tick(); timer = setInterval(tick, intervalMs); timer.unref?.(); },
|
|
181
|
+
stop() { clearInterval(timer); timer = null; },
|
|
182
|
+
tick,
|
|
183
|
+
latest: () => latest,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** The newest sample, kept on this computer only (0600) for `remote status` and the menu; a minute old at most counts. */
|
|
188
|
+
export const HEALTH_FILE = "health.json";
|
|
189
|
+
export const HEALTH_FRESH_MS = 60_000;
|
|
190
|
+
export function keepHealth(body) { try { writeJson(HEALTH_FILE, body); } catch { /* the next sample tries again */ } }
|
|
191
|
+
export function keptHealth(now = Date.now()) {
|
|
192
|
+
try { const b = readJson(HEALTH_FILE); return b && P.validateEventBody("device.health", b).ok && now - b.sampled_at <= HEALTH_FRESH_MS ? b : null; } catch { return null; }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* RECORDED OUTPUT FOR TESTS AGAINST THE DEV RELAY (remote-run.mjs honours WORKTRUST_REMOTE_HEALTH_FIXTURE only for a
|
|
197
|
+
* loopback gateway): { platform, outputs: { sysctl, ioreg, psMac, psLinux }, files: { "/proc/meminfo": … } }, read again
|
|
198
|
+
* at every sample, so an end-to-end test never depends on (or is refused by) the memory of the computer it runs on.
|
|
199
|
+
*/
|
|
200
|
+
export function fixtureReaders(path) {
|
|
201
|
+
const load = () => { try { return JSON.parse(readFileSync(path, "utf8")); } catch { return {}; } };
|
|
202
|
+
return { platform: load().platform ?? "darwin", run: async (key) => load().outputs?.[key] ?? null, read: (p) => load().files?.[p] ?? null };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const gb = (mb) => (mb >= 1024 ? `${(mb / 1024).toFixed(1)} GB` : `${mb} MB`);
|
|
206
|
+
/** The one line the menu and `remote status` show; red starts with ✗ (the painter makes it red), yellow with !. */
|
|
207
|
+
export function healthLine(body) {
|
|
208
|
+
if (!body) return " Health: not known (the remote service has not measured yet)";
|
|
209
|
+
const parts = [];
|
|
210
|
+
if (body.memory_total_mb && body.memory_free_mb !== null) parts.push(`memory ${Math.round((1 - body.memory_free_mb / body.memory_total_mb) * 100)} % in use`);
|
|
211
|
+
if (body.pressure) parts.push(`pressure ${body.pressure}`);
|
|
212
|
+
if (body.swap_used_mb !== null) parts.push(`swap ${gb(body.swap_used_mb)}${body.swap_growth_mb !== null && body.swap_growth_mb > 0 ? ` (+${gb(body.swap_growth_mb)} in 2 min)` : ""}`);
|
|
213
|
+
if (body.load_centi !== null && body.cores) parts.push(`CPU load ${(body.load_centi / 100 / body.cores).toFixed(2)} per core`);
|
|
214
|
+
if (body.gpu_busy !== null) parts.push(`GPU ${body.gpu_busy} %`);
|
|
215
|
+
if (body.top[0]) parts.push(`largest ${body.top[0].name} ${gb(body.top[0].memory_mb)}`);
|
|
216
|
+
const facts = parts.length ? parts.join(", ") : "nothing could be read";
|
|
217
|
+
if (body.level === "red") return ` ✗ Health: red. ${HEALTH_REFUSAL}: ${facts}. New sessions wait; running ones continue.`;
|
|
218
|
+
if (body.level === "yellow") return ` ! Health: yellow: ${facts}`;
|
|
219
|
+
return ` Health: ${body.level === "green" ? "green" : "not known"}: ${facts}`;
|
|
220
|
+
}
|