worktrust 0.11.11 → 0.11.13

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/remote-daemon.mjs CHANGED
@@ -18,15 +18,17 @@ import { createProject, rootLabel, sessionProjects, worktreeMain } from "./remot
18
18
  import { agentOptionsOf } from "./remote-inventory.mjs";
19
19
  import { allowedModes, applySettingsChange } from "./remote-settings.mjs";
20
20
  import { adminInventory } from "./remote-admin.mjs";
21
+ import { deskBodyFor } from "./remote-desk-sessions.mjs";
21
22
 
22
23
  // What a paused computer still answers: reading, configuring, disconnecting, and taking work away (a pipeline's cancel).
23
24
  const LIVE_COMMANDS = new Set(["preview.live_start", "preview.live_input", "preview.live_viewport", "preview.live_follow"]);
24
25
  const DEVICE_COMMANDS = new Set(["inventory.get", "device.configure", "status.get", "pairing.revoke", "release.list", "pipeline.cancel"]);
26
+ const NEW_SESSIONS = new Set(["agent.start", "release.start"]);
25
27
  const KEEP_REMOVED = 20;
26
28
  const MAX_PENDING_PHONES = 10;
27
29
 
28
30
  export function createDaemonCore(o) {
29
- // o: { local, issuerKeys, journal, now, random, send(frame), inventory(refresh), log(kind, fields), sessions?, approvals? }
31
+ // o: { local, issuerKeys, journal, now, random, send(frame), inventory(refresh), log(kind, fields), sessions?, approvals?, health?() }
30
32
  const channels = new Map(loadChannels().map((c) => [c.channel_id, c]));
31
33
  const confirmed = () => confirmedFingerprints(loadPhones());
32
34
  const self = o.local.claims.device_id;
@@ -39,9 +41,10 @@ export function createDaemonCore(o) {
39
41
  * asks again on every inventory.get.
40
42
  */
41
43
  const extendedPeers = new Set(), switchPeers = new Set(); // release 33: `model_switch` only for a phone that asked for it
42
- const EXTENDED_KEYS = ["agent_options", "modes_allowed", "admin", "folders", "connections"];
44
+ const deskPeers = new Set(); // release 36: `desk_sessions` (and the `in_use` refusal) only for a phone that asked for them
45
+ const EXTENDED_KEYS = ["agent_options", "modes_allowed", "admin", "folders", "connections", "desk_sessions"];
43
46
  const withoutSwitch = (body) => (body.agent_options ? { ...body, agent_options: body.agent_options.map(({ model_switch: _drop, ...o }) => o) } : body);
44
- const bodyFor = (channel, record) => (record.type !== "device.inventory" ? record.body
47
+ const bodyFor = (channel, record) => deskBodyFor(deskPeers.has(channel.peer_device_id), record.type, record.type !== "device.inventory" ? record.body
45
48
  : extendedPeers.has(channel.peer_device_id) ? (switchPeers.has(channel.peer_device_id) ? record.body : withoutSwitch(record.body))
46
49
  : Object.fromEntries(Object.entries(record.body).filter(([key]) => !EXTENDED_KEYS.includes(key))));
47
50
 
@@ -88,7 +91,7 @@ export function createDaemonCore(o) {
88
91
  function inventoryBody(refresh) {
89
92
  const settings = loadSettings();
90
93
  const inv = o.inventory(refresh);
91
- return {
94
+ const body = {
92
95
  remote_enabled: settings.enabled && settings.paused === null,
93
96
  default_adapter: settings.default_adapter ?? null,
94
97
  default_model: settings.default_model ?? null,
@@ -108,6 +111,9 @@ export function createDaemonCore(o) {
108
111
  // Every session this computer knows, live or in the journal, newest activity first, with its name and its release task.
109
112
  sessions: (sessions?.listAll?.() ?? sessions?.list() ?? []).map((s) => ({ ...s, ...(releases?.ownerOf(s.session_id) ?? {}) })).slice(0, 100),
110
113
  };
114
+ // Release 36, read only while a phone that asked is linked: this computer's own Claude Code sessions, under the projects above.
115
+ if (o.desk && deskPeers.size > 0) { try { body.desk_sessions = o.desk.list().filter((d) => body.projects.some((p) => p.project_id === d.project_id)); } catch { o.log("desk_unreadable", {}); } }
116
+ return body;
111
117
  }
112
118
 
113
119
  function resendReceipts(entry) {
@@ -184,6 +190,7 @@ export function createDaemonCore(o) {
184
190
  if (env.type === "inventory.get") {
185
191
  if (payload.extended === true && env.sender_device_id) extendedPeers.add(env.sender_device_id);
186
192
  if (payload.extended === true && payload.model_switch === true && env.sender_device_id) switchPeers.add(env.sender_device_id); // kept, as extendedPeers
193
+ if (payload.extended === true && payload.desk_sessions === true && env.sender_device_id) deskPeers.add(env.sender_device_id);
187
194
  if (payload.device_name && env.sender_device_id) rememberName(env.sender_device_id, payload.device_name);
188
195
  emit(null, "device.inventory", inventoryBody(payload.refresh_models));
189
196
  return "taken";
@@ -208,6 +215,9 @@ export function createDaemonCore(o) {
208
215
  return "taken";
209
216
  }
210
217
  if (env.type === "approval.decision") return approvals.decide(payload.decision_token).ok ? "taken" : "approval_invalid";
218
+ // HEAVY MEMORY LOAD (remote-health.mjs, 2026-11-15): while red, no NEW session starts; running sessions continue. `busy`
219
+ // is the reason every phone already knows; the run terminal says "This computer is under heavy memory load".
220
+ if (NEW_SESSIONS.has(env.type) && o.health?.()?.refusing === true) { o.log("session_refused", { reason: "memory_load", type: env.type }); return "busy"; }
211
221
  if (P.RELEASE_COMMANDS.has(env.type)) return releases ? releases.handle(env, payload) : "unsupported"; // remote-releases.mjs
212
222
  if (env.type === "attachment.put" || env.type === "attachment.clear") return o.attachments ? o.attachments.handle(env, payload) : "unsupported"; // remote-attachments.mjs
213
223
  if (env.type === "preview.targets" || env.type === "preview.render") return o.preview ? o.preview.handle(env, payload) : "unsupported"; // remote-preview.mjs
@@ -271,6 +281,8 @@ export function createDaemonCore(o) {
271
281
 
272
282
  return {
273
283
  emit, replay, receiveCommand, receiveHello, inventoryBody,
284
+ /** The computer's health (remote-health.mjs): device-wide on the transient lane, to every open channel, never journaled. */
285
+ emitHealth(body) { if (channels.size > 0) emit(null, "device.health", body, null, "none", { transient: true }); },
274
286
  /** The gateway's device.revoked: a phone this computer will no longer hear from. */
275
287
  peerRevoked(event) { return dropPhone(event.device_id, event.reason === "unpaired" ? "phone" : "revoked"); },
276
288
  attach(s, a, r = null) { sessions = s; approvals = a; releases = r; },
@@ -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
+ }
@@ -40,7 +40,7 @@ async function post(origin, path, body) {
40
40
  /**
41
41
  * ONE SCAN (CLI 0.11.10, owner 2026-11-14: "once you have done that, do you still have to pair? Otherwise you go through the
42
42
  * same step twice"). `remote app` draws the approval link with the PAIRING material in its fragment, which no browser sends
43
- * to a server: `<authorize_url>#v=1&g=<gateway>&k=<Ed25519 pub>&x=<X25519 pub>&s=<32-byte secret>&e=<expiry>`, the pairing
43
+ * to a server: `<authorize_url>#v=1&g=<gateway>&k=<Ed25519 pub>&x=<X25519 pub>&s=<32-byte secret>&e=<expiry>` (0.11.12: the compact code, below), the pairing
44
44
  * invite of PROTOCOL.md §Pairing without `d` (the issuer names this computer's device id only when it approves). The
45
45
  * WorkTrust app's own scanner approves with the authenticator, finds this computer in the account's device list by the
46
46
  * fingerprint of `k` and `x`, and makes the invite whole with its device id; the daemon then confirms the phone by the
@@ -48,27 +48,56 @@ async function post(origin, path, body) {
48
48
  * fragment: pairing a phone is then the second step it always was (`linkPhone` shows the QR after its wait).
49
49
  */
50
50
  export const ONE_SCAN_KEYS = Object.freeze(["v", "g", "k", "x", "s", "e"]);
51
+ /**
52
+ * 0.11.12 (owner, 2026-11-15: "the QR must be about 4 x 4 cm"): for WorkTrust's own relay the fragment is the COMPACT code of
53
+ * remote-protocol pairing.ts (a 16-byte seed, a 128-bit commitment to `k` and `x`, the expiry; 58 base32 characters), the
54
+ * same one the pairing QR draws; the secret `s` is the seed expanded, so the daemon's invite is unchanged. Another relay keeps
55
+ * the long fragment above. The WorkTrust app reads both since build 17 (docs/OPEN.md: build 16 reads only the long one).
56
+ */
51
57
  export function oneScan({ gateway, publicKeys, nowMs, random }) {
52
58
  if (!gateway || !P.isGatewayOrigin(gateway)) return null;
53
- const fields = { v: 1, g: gateway, k: publicKeys.ed25519_pub, x: publicKeys.x25519_pub, s: P.toBase64Url(random(32)), e: Math.floor(nowMs / 1000) + P.PAIRING_INVITE_LIFETIME_S };
54
- return { ...fields, fragment: ONE_SCAN_KEYS.map((key) => `${key}=${encodeURIComponent(String(fields[key]))}`).join("&") };
59
+ const seed = random(P.PAIRING_SEED_BYTES);
60
+ const fields = { v: 1, g: gateway, k: publicKeys.ed25519_pub, x: publicKeys.x25519_pub, s: P.expandPairingSeed(seed), e: Math.floor(nowMs / 1000) + P.PAIRING_INVITE_LIFETIME_S };
61
+ const fragment = gateway === PRODUCTION_GATEWAY ? P.encodeCompactPairing({ seed, commitment: P.deviceCommitment(publicKeys), e: fields.e }) : ONE_SCAN_KEYS.map((key) => `${key}=${encodeURIComponent(String(fields[key]))}`).join("&");
62
+ return { ...fields, seed: P.toBase64Url(seed), fragment };
55
63
  }
56
64
  /**
57
65
  * THE QR'S OWN, SHORTER FORM OF A LINK (owner, 2026-11-14: "make the QR more compact"): `g` is left out when it names
58
66
  * WorkTrust's production relay, the one the phone assumes when `g` is missing (CLI 0.11.10 with the app's 2026-11-14
59
- * JavaScript, which reads both forms). `d`, `k`, `x`, `s` and `e` are never left out; another gateway (the dev relay) stays
60
- * named. Only the drawn code is shortened: the printed link and invite.json keep `g`, for a browser it is pasted into and
61
- * for the daemon. 36 characters fewer: the pairing QR goes from version 12 to 9 with level L.
67
+ * JavaScript, which reads both forms). Since 0.11.12 only a long link meets it (another relay, or an invite without a seed).
62
68
  */
63
69
  const DEFAULT_G = `&g=${encodeURIComponent(PRODUCTION_GATEWAY)}`;
64
70
  export const compactForQr = (link) => link.replace(DEFAULT_G, "");
71
+ /**
72
+ * A PAIRING INVITE WHOSE SECRET COMES FROM A 16-BYTE SEED (0.11.12): the long invite of PROTOCOL.md §Pairing (its `s` the seed
73
+ * expanded, ten minutes), checked by the protocol's own encoder, with the seed kept beside it for the compact QR.
74
+ */
75
+ export function seededInvite({ gateway, deviceId, publicKeys, nowMs, random }) {
76
+ const seed = random(P.PAIRING_SEED_BYTES);
77
+ const invite = { v: 1, g: gateway, d: deviceId, k: publicKeys.ed25519_pub, x: publicKeys.x25519_pub, s: P.expandPairingSeed(seed), e: Math.floor(nowMs / 1000) + P.PAIRING_INVITE_LIFETIME_S };
78
+ P.encodePairingInvite(invite);
79
+ return { ...invite, seed: P.toBase64Url(seed) };
80
+ }
81
+ /** The long link of an invite (its seven keys, whatever else it carries beside them). */
82
+ export const inviteLink = (invite) => P.encodePairingInvite({ v: invite.v, g: invite.g, d: invite.d, k: invite.k, x: invite.x, s: invite.s, e: invite.e });
83
+ /**
84
+ * WHAT THE PAIRING QR DRAWS (0.11.12): for WorkTrust's relay and an invite with its seed, the compact code
85
+ * `https://app.worktrust.io/remote/pair#<58 characters>` (version 4 at level L, 33 modules); else the long link without the
86
+ * default `g` (version 9 or more). The seed must expand to the invite's own secret, so the code can only name this invite.
87
+ */
88
+ export function pairingQrText(invite) {
89
+ const seed = typeof invite.seed === "string" ? P.fromBase64Url(invite.seed) : null;
90
+ if (seed?.length === P.PAIRING_SEED_BYTES && invite.g === PRODUCTION_GATEWAY && P.expandPairingSeed(seed) === invite.s)
91
+ return `${P.PAIRING_LINK_BASE}#${P.encodeCompactPairing({ seed, commitment: P.deviceCommitment({ ed25519_pub: invite.k, x25519_pub: invite.x }), e: invite.e })}`;
92
+ return compactForQr(inviteLink(invite));
93
+ }
65
94
  /** The approval link with the pairing material in its fragment, or the link as it was (no gateway, the browser's road). */
66
95
  export const withPairing = (url, once) => (once ? `${url}#${once.fragment}` : url);
67
96
  /** The invite the daemon reads (invite.json) once the issuer named this computer: the one-scan secret, now with its `d`; checked by the protocol's own encoder. */
68
97
  export function oneScanInvite(once, deviceId, code, nowMs) {
69
98
  const invite = { v: once.v, g: once.g, d: deviceId, k: once.k, x: once.x, s: once.s, e: once.e };
70
99
  P.encodePairingInvite(invite);
71
- return { ...invite, code, used: false, created_at: nowMs };
100
+ return { ...invite, ...(once.seed ? { seed: once.seed } : {}), code, used: false, created_at: nowMs };
72
101
  }
73
102
 
74
103
  /** Which road, the app's QR here (Enter) or the browser; not a terminal, or --yes: the browser. Since 0.11.7 the person names the road (`remote app` | `remote web`, or the menu); kept for a caller that asks. */
@@ -120,7 +149,10 @@ export async function pairComputer({ origin, secret, publicKeys, host, os, devic
120
149
  if (road === "app") {
121
150
  // One scan (0.11.10): the app's scanner approves AND links this phone; the camera app only approves.
122
151
  say(once ? " Scan this in the WorkTrust app (Scan › Connect agent): approve with your authenticator code, and the phone links too." : " Scan this with the WorkTrust app (or the phone's camera) and approve with your authenticator code:");
152
+ // Room around the code (0.11.12, owner 2026-11-15): one empty line above it and one below.
153
+ say("");
123
154
  showQr(withPairing(authorize_url, once));
155
+ say("");
124
156
  // The printed link leaves the pairing secret out (scrollback, a shared screen; review 2026-11-14, P3-7): the QR carries
125
157
  // it, and --show-link prints it whole for a phone that cannot scan.
126
158
  say(` Link: ${showLink ? withPairing(authorize_url, once) : authorize_url}`);