worktrust 0.10.38 → 0.11.1

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.
Files changed (49) hide show
  1. package/LICENSE +43 -18
  2. package/README.md +55 -2
  3. package/SECURITY.md +25 -0
  4. package/engine-release.json +1 -1
  5. package/log-session.mjs +6 -6
  6. package/package-release.json +1 -1
  7. package/package.json +43 -2
  8. package/remote-adapter-claude-code.mjs +113 -0
  9. package/remote-adapter-codex.mjs +159 -0
  10. package/remote-adapter-terminal.mjs +248 -0
  11. package/remote-approval-bridge.mjs +145 -0
  12. package/remote-approvals.mjs +134 -0
  13. package/remote-attachments.mjs +129 -0
  14. package/remote-cdp.mjs +60 -0
  15. package/remote-changes.mjs +94 -0
  16. package/remote-claude-events.mjs +212 -0
  17. package/remote-claude-progress.mjs +328 -0
  18. package/remote-cli.mjs +330 -0
  19. package/remote-coalesce.mjs +40 -0
  20. package/remote-codex-events.mjs +153 -0
  21. package/remote-daemon.mjs +220 -0
  22. package/remote-inventory.mjs +143 -0
  23. package/remote-journal.mjs +155 -0
  24. package/remote-live-preview.mjs +205 -0
  25. package/remote-pairing.mjs +104 -0
  26. package/remote-pipeline-config.mjs +177 -0
  27. package/remote-pipeline-parsers.mjs +121 -0
  28. package/remote-pipeline.mjs +234 -0
  29. package/remote-policy.mjs +199 -0
  30. package/remote-preview.mjs +146 -0
  31. package/remote-projects.mjs +87 -0
  32. package/remote-protocol.mjs +4010 -0
  33. package/remote-qr.mjs +175 -0
  34. package/remote-release-plans.mjs +88 -0
  35. package/remote-releases.mjs +297 -0
  36. package/remote-run.mjs +189 -0
  37. package/remote-screen-approvals.mjs +79 -0
  38. package/remote-screen-push.mjs +76 -0
  39. package/remote-screen-states.mjs +113 -0
  40. package/remote-service.mjs +101 -0
  41. package/remote-session-list.mjs +48 -0
  42. package/remote-sessions.mjs +337 -0
  43. package/remote-steered.mjs +114 -0
  44. package/remote-steering.mjs +97 -0
  45. package/remote-store.mjs +124 -0
  46. package/remote-terminal-cli.mjs +85 -0
  47. package/remote-terminal-sessions.mjs +291 -0
  48. package/remote-transport.mjs +88 -0
  49. package/worktrust.mjs +11 -4
package/remote-run.mjs ADDED
@@ -0,0 +1,189 @@
1
+ /**
2
+ * `worktrust remote run`: THE DAEMON, WIRED (2026-11-07). The service manager starts it (remote-service.mjs), or the
3
+ * person runs it in the foreground (Windows: foreground only). It refuses to start unless remote is enabled, this computer
4
+ * is paired, a gateway is set and this Node has a WebSocket; it holds a lock so one runs per user; it closes as FAILED any
5
+ * command an earlier run left mid-way (never runs it again); it stops every agent it started when it stops, and it exits
6
+ * by itself when `worktrust remote disable` turns remote off.
7
+ *
8
+ * The agents it starts get this user's environment with every WORKTRUST_ variable removed (no measurement credential, no
9
+ * remote secret) and the PATH the person had when they enabled remote.
10
+ */
11
+ import { execFileSync } from "node:child_process";
12
+ import { closeSync, openSync, readFileSync, rmSync, writeSync, constants } from "node:fs";
13
+ import { dirname, join } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import * as P from "./remote-protocol.mjs";
16
+ import { loadPreviewGrants } from "./remote-store.mjs";
17
+ import { ensureRemoteDir, issuerKeys, loadDeskMarks, loadIdentity, loadKeys, loadPipelineReviews, loadProjects, loadSettings, readJson, remotePath, random, saveIdentity } from "./remote-store.mjs";
18
+ import { openJournal } from "./remote-journal.mjs";
19
+ import { inventory as listAgents, offered } from "./remote-inventory.mjs";
20
+
21
+ /** The agents as a phone may use them: what is installed, less what the person has not turned on (Codex). */
22
+ const inventory = (o) => offered(listAgents(o), loadSettings());
23
+ import { createApprovals } from "./remote-approvals.mjs";
24
+ import { createSessions } from "./remote-sessions.mjs";
25
+ import { createTerminalSessions, withTerminal } from "./remote-terminal-sessions.mjs";
26
+ import { createTmux, NO_TMUX, writeTmuxConfig } from "./remote-adapter-terminal.mjs";
27
+ import { detectScreen } from "./remote-screen-states.mjs";
28
+ import { createReleases } from "./remote-releases.mjs";
29
+ import { createPipelines } from "./remote-pipeline.mjs";
30
+ import { createAttachments } from "./remote-attachments.mjs";
31
+ import { createPreview } from "./remote-preview.mjs";
32
+ import { createLivePreview } from "./remote-live-preview.mjs";
33
+ import { appendPipelineMark } from "./remote-steered.mjs";
34
+ import { createDaemonCore } from "./remote-daemon.mjs";
35
+ import { connectGateway, webSocketAvailable } from "./remote-transport.mjs";
36
+
37
+ const HERE = dirname(fileURLToPath(import.meta.url));
38
+ const log = (kind, fields = {}) => process.stderr.write(`${JSON.stringify({ at: new Date().toISOString(), kind, ...fields })}\n`);
39
+
40
+ export function agentEnv(settings, base = process.env) {
41
+ const env = {};
42
+ for (const [key, value] of Object.entries(base)) if (!/^WORKTRUST_/.test(key) && !/^CLAUDE_?CODE/.test(key) && key !== "CLAUDECODE") env[key] = value;
43
+ if (settings.agent_path) env.PATH = settings.agent_path;
44
+ return env;
45
+ }
46
+
47
+ /** A pipeline stage's environment: the agents' (no WORKTRUST_ variable), the reviewed folders first on PATH, CI set. */
48
+ export function stageEnv(settings, prepend = [], base = process.env) {
49
+ const env = agentEnv(settings, base);
50
+ env.PATH = [...prepend, env.PATH ?? ""].filter(Boolean).join(process.platform === "win32" ? ";" : ":");
51
+ env.CI = "1";
52
+ return env;
53
+ }
54
+
55
+ /**
56
+ * Agents run in process groups of their own, so a daemon that crashed leaves them running. A new daemon ends every group
57
+ * an earlier one recorded whose process is still that session's agent (its command line names the session's own id),
58
+ * before it takes any command (review 2026-11-07, P2-b).
59
+ */
60
+ /** A process's command line, or "" (the reapers check it is still the process they recorded before they end it). */
61
+ export function commandOf(pid) {
62
+ try { return execFileSync("ps", ["-o", "command=", "-p", String(pid)], { encoding: "utf8", timeout: 5000 }); } catch { return ""; }
63
+ }
64
+
65
+ export function reapOrphans(journal, kill = process.kill.bind(process)) {
66
+ let reaped = 0;
67
+ for (const s of journal.sessions()) {
68
+ if (!Number.isSafeInteger(s.pid) || s.pid <= 1 || !s.agent_session_ref) continue;
69
+ let command = "";
70
+ try { command = execFileSync("ps", ["-o", "command=", "-p", String(s.pid)], { encoding: "utf8", timeout: 5000 }); } catch { command = ""; }
71
+ if (!command.includes(s.agent_session_ref)) { journal.recordSession({ session_id: s.session_id, pid: null }); continue; }
72
+ try { kill(-s.pid, "SIGTERM"); reaped += 1; } catch { /* gone */ }
73
+ journal.recordSession({ session_id: s.session_id, pid: null });
74
+ }
75
+ return reaped;
76
+ }
77
+
78
+ function lock() {
79
+ const file = remotePath("daemon.lock");
80
+ try {
81
+ const fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, 0o600);
82
+ writeSync(fd, String(process.pid)); closeSync(fd);
83
+ } catch {
84
+ const pid = Number(readFileSync(file, "utf8"));
85
+ let alive = false;
86
+ try { process.kill(pid, 0); alive = pid !== process.pid; } catch { alive = false; }
87
+ if (alive) throw new Error(`another remote daemon runs (pid ${pid})`);
88
+ rmSync(file, { force: true });
89
+ return lock();
90
+ }
91
+ return () => rmSync(file, { force: true });
92
+ }
93
+
94
+ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) } = {}) {
95
+ ensureRemoteDir();
96
+ const settings = loadSettings(), identity = loadIdentity(), keys = loadKeys();
97
+ if (!settings.enabled) throw new Error("remote is off on this computer: run `worktrust remote enable`");
98
+ if (!identity || !keys) throw new Error("this computer is not paired for remote: run `worktrust remote enable`");
99
+ if (!settings.gateway) throw new Error("no gateway is set: the production gateway is not live yet; for local tests pass --gateway ws://127.0.0.1:<port> to `worktrust remote enable`");
100
+ if (!webSocketAvailable()) throw new Error(`remote needs Node 22.4 or later (this is ${process.versions.node})`);
101
+ const keysOf = issuerKeys(settings.gateway);
102
+ const claims = P.verifyBinding(identity.binding, { issuerKeys: keysOf, now: Date.now(), kind: "computer", deviceId: identity.device_id });
103
+ if (!claims.ok) throw new Error(`this computer's binding does not verify (${claims.code}): run \`worktrust remote enable\` again`);
104
+ if (claims.value.exp * 1000 - Date.now() < 7 * 86400_000 && identity.origin) {
105
+ // A binding lives thirty days: renewed in its last week while the device is still approved (docs/remote-agents/ISSUER.md §4).
106
+ const { renewBinding } = await import("./remote-pairing.mjs");
107
+ const fresh = await renewBinding({ origin: identity.origin, identity, secret: keys.secret }).catch(() => null);
108
+ const checked = fresh && P.verifyBinding(fresh, { issuerKeys: keysOf, now: Date.now(), kind: "computer", deviceId: identity.device_id });
109
+ if (checked?.ok && checked.value.ed25519_pub === claims.value.ed25519_pub) { saveIdentity({ ...identity, binding: fresh }); identity.binding = fresh; }
110
+ else log("binding_not_renewed", {});
111
+ }
112
+ const release = lock();
113
+ const journal = openJournal(remotePath("journal.jsonl"));
114
+ for (const id of journal.interrupted()) journal.advance(id, { kind: "failed" }, Date.now(), "interrupted"); // never run again
115
+ if (process.platform !== "win32") reapOrphans(journal);
116
+ journal.compact(Date.now());
117
+ const runDir = remotePath("run");
118
+ let transport = null;
119
+ const local = { secret: keys.secret, binding: identity.binding, claims: claims.value };
120
+ // Files from the phone (into the session's project inbox) and the local preview (2026-11-07).
121
+ const attachments = createAttachments({ journal, now: Date.now, emit: (...a) => core.emit(...a), log,
122
+ sessionProject: (id) => { const s = journal.session(id); return s ? loadProjects().find((p) => p.project_id === s.project_id) ?? null : null; } });
123
+ const preview = createPreview({ emit: (...a) => core.emit(...a), projects: loadProjects, grants: loadPreviewGrants, env: () => agentEnv(loadSettings()), log });
124
+ // The live preview (release 19): the session's granted page, live, over the browser's pipe; one per computer.
125
+ const live = createLivePreview({ emit: (...a) => core.emit(...a), grants: loadPreviewGrants, env: () => agentEnv(loadSettings()), log, now: Date.now,
126
+ sessionProject: (id) => { const s = journal.session(id); return s ? loadProjects().find((p) => p.project_id === s.project_id) ?? null : null; } });
127
+ const core = createDaemonCore({ local, issuerKeys: keysOf, journal, projectSecret: keys.projectSecret, attachments, preview, live, now: Date.now, random, log, send: (f) => transport?.send(f) ?? false, inventory: (refresh) => inventory({ env: agentEnv(loadSettings()), refresh }), online: () => transport?.ready() ?? false, approvals: null });
128
+ const ctx = { journal, now: Date.now, random, deviceId: identity.device_id, emit: core.emit, paused: () => loadSettings().paused !== null || !loadSettings().enabled, phoneOnline: core.phoneOnline, controllers: core.controllers };
129
+ const approvals = createApprovals(ctx);
130
+ const socket = await approvals.listen(runDir);
131
+ let releases = null; // set below; the hooks run only once events flow
132
+ const sessions = createSessions({ ...ctx, approvals, runDir, node: process.execPath, bridgePath: join(HERE, "remote-approval-bridge.mjs"), socket: () => socket,
133
+ settings: loadSettings, projects: loadProjects, inventory: () => inventory({ env: agentEnv(loadSettings()) }), agentEnv: () => agentEnv(loadSettings()), replay: core.replay,
134
+ onTaskEnded: (id, outcome) => releases.taskEnded(id, outcome), onActivity: () => releases?.activity(),
135
+ onSessionsChanged: () => core.emit(null, "device.inventory", core.inventoryBody(false)), attachments });
136
+ ctx.onApprovalOpened = sessions.onApprovalOpened; ctx.onApprovalSettled = sessions.onApprovalSettled;
137
+ // Terminal sessions (release 19, off until `worktrust remote terminal on`): Claude Code in tmux on WorkTrust's own socket.
138
+ const tmuxFile = listAgents({ env: agentEnv(loadSettings()) }).files.tmux;
139
+ const tmux = tmuxFile ? createTmux({ file: tmuxFile, config: writeTmuxConfig(runDir), env: agentEnv(loadSettings()) }) : NO_TMUX;
140
+ const terminal = createTerminalSessions({ journal, now: Date.now, emit: core.emit, settings: loadSettings, projects: loadProjects, inventory: () => inventory({ env: agentEnv(loadSettings()) }),
141
+ tmux, claudeFile: () => listAgents({ env: agentEnv(loadSettings()) }).files["claude-code"], replay: core.replay, running: () => sessions.runningCount(), detect: (lines) => detectScreen("claude-code", lines), approvals,
142
+ onSessionsChanged: () => core.emit(null, "device.inventory", core.inventoryBody(false)) });
143
+ const registry = withTerminal(sessions, terminal);
144
+ // Releases and pipelines (2026-11-07): one queue for every release's tasks, the reviewed pipeline of each project.
145
+ const pipelines = createPipelines({ journal, now: Date.now, random, emit: core.emit, projects: loadProjects, reviews: loadPipelineReviews, log, logDir: remotePath("pipelines"),
146
+ markLedger: appendPipelineMark, env: (prepend) => stageEnv(loadSettings(), prepend), onEnded: (p) => releases?.pipelineEnded(p), commandOf });
147
+ releases = createReleases({ journal, now: Date.now, random, emit: core.emit, projects: loadProjects, settings: loadSettings, paused: ctx.paused, inventory: () => inventory({ env: agentEnv(loadSettings()) }),
148
+ sessions, pipelines, deskMarks: loadDeskMarks, log });
149
+ // The agent plans its own work (plan_* over the approval socket, 2026-11-08): the same queue, the session's own project.
150
+ ctx.plan = (session, op, args) => releases.plan(session, op, args);
151
+ releases.recover(); // tasks an earlier daemon left running: interrupted, never run again
152
+ pipelines.recover(); // and its pipeline runs
153
+ core.attach(registry, approvals, releases);
154
+
155
+ const dispatchFrame = async (frame) => {
156
+ if (frame.frame === "hello") core.receiveHello(frame.hello);
157
+ else if (frame.frame === "command") await core.receiveCommand(frame.envelope);
158
+ else if (frame.frame === "relay") { log("relay", { type: frame.event?.type ?? null }); if (frame.event?.type === "device.revoked") core.peerRevoked(frame.event); }
159
+ else if (frame.frame === "error") log("gateway_error", { reason: typeof frame.reason === "string" ? frame.reason.slice(0, 40) : null });
160
+ };
161
+ let sentCode = null;
162
+ const registerCode = (again = false) => {
163
+ const invite = readJson("invite.json");
164
+ if (invite?.code && !invite.used && invite.e * 1000 > Date.now() && (again || sentCode !== invite.code) && transport?.send({ frame: "pair_ticket", ticket: invite.code, expires_at: invite.e * 1000 })) sentCode = invite.code;
165
+ };
166
+ // The production gateway admits a computer on a five-minute assertion from the issuer, asked fresh for every challenge.
167
+ const { requestAssertion } = await import("./remote-pairing.mjs");
168
+ const authorize = () => (identity.origin ? requestAssertion({ origin: identity.origin, deviceId: identity.device_id, secret: keys.secret }) : Promise.resolve(null));
169
+ transport = connectGateway({ url: settings.gateway, identity, signingSecret: keys.secret.ed25519, log, authorize, onFrame: (f) => { dispatchFrame(f).catch((e) => log("frame_failed", { name: e?.name ?? "Error" })); },
170
+ onState: (state, info) => { log("gateway", { state, ...info }); if (state === "ready") registerCode(true); } });
171
+ say(` WorkTrust remote is running for ${identity.device_id} (gateway ${new URL(settings.gateway).host}). Ctrl+C stops it.`);
172
+ let stopping = false;
173
+ const stop = async (code = 0) => {
174
+ if (stopping) return;
175
+ stopping = true;
176
+ approvals.close();
177
+ await pipelines.stopAll();
178
+ await live.stopAll(); // the browser ended, its profile removed
179
+ await registry.stopAll(); // the structured agents; a terminal session lives on in tmux
180
+ transport.close();
181
+ release();
182
+ process.exit(code);
183
+ };
184
+ process.on("SIGINT", () => stop(0));
185
+ process.on("SIGTERM", () => stop(0));
186
+ setInterval(() => { const s = loadSettings(); if (!s.enabled) stop(0); registerCode(); releases.poll(); }, 3000).unref();
187
+ releases.schedule(); // queued tasks a restart kept
188
+ return new Promise(() => {});
189
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * A TERMINAL DIALOG, ANSWERED FROM A PHONE BY ITS SCREEN'S HASH (release 19, 2026-11-09; PRIOR-ART-ANALYSIS.md 2.3).
3
+ *
4
+ * When a terminal session's screen shows a permission dialog (remote-screen-states.mjs, claudeCodeDialog), the computer:
5
+ * 1. classifies what the dialog names (a command, a file) with its own policy (remote-policy.mjs). A dialog it cannot
6
+ * read, or of a class a phone may not decide, is never asked: it waits for the person at the computer;
7
+ * 2. asks through remote-approvals.mjs (the only sender of agent.approval_required), the action's input being the
8
+ * dialog's region exactly as drawn, so the hash the phone signs covers the very screen text it showed;
9
+ * 3. when a PHONE decided (never on a timeout, a lost phone or a session that ended), reads the screen again and presses
10
+ * the answer key only if the dialog's region still hashes the same, the key coming from the agent's allow-list
11
+ * (SCREEN_ANSWERS) and only where the dialog offers it (approve: the cursor on "1. Yes"; deny: an option with Esc).
12
+ * A changed dialog presses nothing and is asked again.
13
+ * One question per dialog: the same region is not asked twice; a dialog answered at the desk withdraws its question.
14
+ * Offered only where the adapter reports `approvals: "screen"`, which needs fixtures recorded from the real agent.
15
+ */
16
+ import { createHash } from "node:crypto";
17
+ import { isAbsolute, join } from "node:path";
18
+ import { classifyAction, phoneMayDecide } from "./remote-policy.mjs";
19
+ import { SCREEN_ANSWERS, screenDialog } from "./remote-screen-states.mjs";
20
+
21
+ const MAX_SHOWN = 16_000;
22
+ /** The dialog's region, hashed as drawn (lines joined with \n). */
23
+ export const regionHash = (region) => createHash("sha256").update(region.join("\n")).digest("base64url");
24
+
25
+ /** The dialog as an approval action: classified from what it names, shown (and hashed) as the screen draws it. */
26
+ export function screenAction(agent, dialog, projectPath) {
27
+ const args = dialog.tool === "Bash" ? { command: dialog.target ?? "" }
28
+ : dialog.tool && dialog.target ? { file_path: isAbsolute(dialog.target) ? dialog.target : join(projectPath, dialog.target) } : {};
29
+ const { action, reason } = classifyAction(agent, dialog.tool ?? "ScreenDialog", args, projectPath);
30
+ const shown = dialog.region.join("\n");
31
+ if (shown.length > MAX_SHOWN) return { action: { ...action, class: "other", input: `${shown.slice(0, MAX_SHOWN - 40)} [cut: too long to show exactly]` }, reason: "the dialog is too long to show exactly" };
32
+ return { action: { ...action, input: shown }, reason };
33
+ }
34
+
35
+ // ctx: { approvals, emit, tmux, report() (the terminal report), agent }
36
+ export function createScreenApprovals(ctx) {
37
+ const note = (s, text) => ctx.emit(s.session_id, "agent.output_delta", { stream: "tool", offset: 0, text }, s.command_id);
38
+
39
+ /** After a phone's decision: the screen again, the same hash, then the agent's own answer key, or nothing. */
40
+ async function answer(s, ask) {
41
+ if (ask.decision === null || s.closed) return; // no phone decided: nothing is pressed
42
+ ask.answering = true;
43
+ const cap = await ctx.tmux.capture(s.tmux, 100);
44
+ const now = cap ? screenDialog(ctx.agent, cap.lines) : null;
45
+ if (!now || regionHash(now.region) !== ask.hash) {
46
+ s.screenAsked = null; // the dialog now on the screen is asked again
47
+ note(s, "The dialog on the screen changed before your answer reached it: nothing was pressed.");
48
+ return;
49
+ }
50
+ const keys = ask.decision === "approve" ? (now.approve ? SCREEN_ANSWERS[ctx.agent].approve : null) : now.dismiss ? SCREEN_ANSWERS[ctx.agent].deny : null;
51
+ if (!keys) { note(s, "This dialog does not offer that answer here: nothing was pressed. Answer it at the computer."); return; }
52
+ for (const key of keys) await ctx.tmux.sendKey(s.tmux, key);
53
+ }
54
+
55
+ return {
56
+ answer,
57
+ /** One look at the screen (remote-terminal-sessions.mjs): a new dialog is asked once; a dialog gone withdraws its question. */
58
+ consider(s, lines) {
59
+ const dialog = ctx.report()?.capabilities.approvals === "screen" && Object.hasOwn(SCREEN_ANSWERS, ctx.agent) ? screenDialog(ctx.agent, lines) : null;
60
+ if (!dialog) {
61
+ if (s.screenAsk && !s.screenAsk.answering) ctx.approvals.withdraw(s.session_id, "the dialog was answered at the computer");
62
+ s.screenAsked = null;
63
+ return;
64
+ }
65
+ const hash = regionHash(dialog.region);
66
+ if (s.screenAsk?.hash === hash || s.screenAsked === hash) return;
67
+ if (s.screenAsk && !s.screenAsk.answering) ctx.approvals.withdraw(s.session_id, "the dialog changed on the screen");
68
+ s.screenAsked = hash;
69
+ const preset = screenAction(ctx.agent, dialog, s.projectPath);
70
+ if (!phoneMayDecide(preset.action)) { note(s, `This dialog is answered at the computer: ${preset.reason ?? "a phone may not decide it"}.`); return; }
71
+ const ask = { hash, decision: null, answering: false };
72
+ s.screenAsk = ask;
73
+ ctx.approvals.request(s, preset.action.tool, { screen: preset.action.input }, { ...preset, onPhone: (decision) => { ask.decision = decision; } })
74
+ .then(() => answer(s, ask))
75
+ .catch(() => {})
76
+ .finally(() => { if (s.screenAsk === ask) s.screenAsk = null; });
77
+ },
78
+ };
79
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * A TERMINAL'S SCREEN, PUSHED WHEN IT CHANGES (release 19, 2026-11-09). A phone that shows a terminal session asks with
3
+ * `screen.read { follow: true }`; from then on, for FOLLOW_MS after its latest such read, the computer sends the screen
4
+ * (agent.screen, no command) whenever a look at it (remote-terminal-sessions.mjs; tmux's control mode says when) finds it
5
+ * changed. `follow: false` stops it at once for that phone. A push travels on the session's TRANSIENT LANE (envelopes.ts):
6
+ * the computer journals none, the relay keeps none, and a phone that reconnects reads the screen again.
7
+ *
8
+ * - At most one push per PUSH_MS per session; within that time the newest screen wins (a burst is one push now and one
9
+ * at the end of the window, never one per change).
10
+ * - Nothing is pushed when the screen hashes as it was last sent (a read's answer counts as sent).
11
+ * - Nothing is pushed while no phone follows the session, and nothing after it closed.
12
+ *
13
+ * WHO RECEIVES IT. Every event of a session is one ordered stream per session, sealed for each of the person's confirmed
14
+ * phones (remote-daemon.mjs sealAll): a push to one phone only would leave a gap in the others' sequence and send each
15
+ * of them through a reconciliation. So following decides WHETHER the computer pushes; what it pushes reaches the
16
+ * person's confirmed phones like every other event of the session (as a read's answer already does).
17
+ */
18
+ import { createHash } from "node:crypto";
19
+
20
+ export const PUSH_MS = 500;
21
+ export const FOLLOW_MS = 10 * 60_000;
22
+ const DEFAULT_LINES = 200;
23
+
24
+ /** The screen's lines, hashed (not the cut flag: one screen read through two windows is still one screen). */
25
+ const hashOf = (cap) => createHash("sha256").update(cap.lines.join("\n")).digest("base64url");
26
+
27
+ // ctx: { now, emit, pushMs?, followMs?, setTimer?(fn, ms), clearTimer?(t) }
28
+ export function createScreenPush(ctx) {
29
+ const pushMs = ctx.pushMs ?? PUSH_MS, followMs = ctx.followMs ?? FOLLOW_MS;
30
+ const later = ctx.setTimer ?? ((fn, ms) => { const t = setTimeout(fn, ms); t.unref?.(); return t; });
31
+ const cancel = ctx.clearTimer ?? clearTimeout;
32
+ const state = (s) => (s.push ??= { followers: new Map(), sentHash: null, sentAt: -Infinity, waiting: null, timer: null });
33
+
34
+ /** The phones following this session now (their device ids), the expired ones dropped. */
35
+ function followers(s) {
36
+ const p = state(s), now = ctx.now();
37
+ for (const [phone, f] of p.followers) if (f.until <= now) p.followers.delete(phone);
38
+ return p.followers;
39
+ }
40
+ const following = (s) => !s.closed && followers(s).size > 0;
41
+ /** How many lines a look should read for the followers (the most any of them asked for). */
42
+ const linesFor = (s) => Math.max(0, ...[...followers(s).values()].map((f) => f.lines));
43
+
44
+ function send(s) {
45
+ const p = state(s);
46
+ const next = p.waiting;
47
+ p.waiting = null;
48
+ if (!next || !following(s) || next.hash === p.sentHash) return;
49
+ p.sentHash = next.hash; p.sentAt = ctx.now();
50
+ ctx.emit(s.session_id, "agent.screen", next.cap, null, "none", { transient: true }); // the transient lane: never journaled
51
+ }
52
+
53
+ return {
54
+ following, linesFor,
55
+ /** A screen.read from a phone: follow (renewed), unfollow, or neither. */
56
+ follow(s, phone, follow, lines = DEFAULT_LINES) {
57
+ if (typeof phone !== "string" || follow === undefined) return;
58
+ if (follow) followers(s).set(phone, { until: ctx.now() + followMs, lines });
59
+ else { followers(s).delete(phone); if (!following(s)) this.stop(s); }
60
+ },
61
+ /** A read's answer went out: the same screen is not pushed again. */
62
+ answered(s, cap) { const p = state(s); p.sentHash = hashOf(cap); p.sentAt = ctx.now(); },
63
+ /** A look found this screen: pushed now, or at the end of the window with the newest, or not at all. */
64
+ offer(s, cap) {
65
+ if (!cap || !following(s)) return;
66
+ const p = state(s), hash = hashOf(cap);
67
+ if (hash === p.sentHash) { p.waiting = null; return; }
68
+ p.waiting = { cap, hash };
69
+ const wait = p.sentAt + pushMs - ctx.now();
70
+ if (wait <= 0) { if (p.timer) { cancel(p.timer); p.timer = null; } return send(s); }
71
+ if (!p.timer) p.timer = later(() => { p.timer = null; send(s); }, wait);
72
+ },
73
+ /** The session closed or nobody follows: nothing waiting is sent. */
74
+ stop(s) { const p = state(s); p.waiting = null; if (p.timer) { cancel(p.timer); p.timer = null; } },
75
+ };
76
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * WHAT A TERMINAL SESSION'S SCREEN SAYS (release 19, 2026-11-09). One pure function per agent from the screen's last lines
3
+ * (remote-adapter-terminal.mjs capture, escapes already removed) to one of: working, idle, blocked (needs_you with a reason:
4
+ * dialog, question, trust, login) or unknown. No imports, no I/O.
5
+ *
6
+ * UNKNOWN IS THE DEFAULT. A screen is idle only on a positive match (the agent's empty input line) with no sign of anything
7
+ * else; the order is blocked, then working, then idle, so a dialog is never read as idle even when an input box is also
8
+ * drawn. A half-drawn dialog, a person's draft in the input line, a blank or unfamiliar screen, a dead pane: unknown, and
9
+ * nothing is typed into unknown (attention.ts, promptAllowed). Only the screen's BOTTOM counts (the last REGION non-empty
10
+ * lines): a dialog answered earlier and scrolled up is history, not a wait.
11
+ *
12
+ * BASIS. A detector says what its fixtures are: `recorded` (captured from the real agent) or `authored` (written by hand
13
+ * from the agent's known layout). Typing from a phone is offered only on a recorded basis (typingTrusted); the Claude
14
+ * Code fixtures are AUTHORED (its interactive start needs the person's sign-in and the network, which the recording rule
15
+ * forbids), so its detector drives what the phone SHOWS (working, needs you, idle) and never what it may type.
16
+ * Fixtures: scripts/fixtures/remote/terminal-screens/<agent>/, held by test-remote-screen-states.mjs.
17
+ */
18
+ export const REGION = 25;
19
+
20
+ const rule = (l) => /^\s*[─━]{20,}\s*$/.test(l) || /^\s*╭─{10,}/.test(l) || /^\s*╰─{10,}/.test(l);
21
+ const BOXED_INPUT = /^\s*│\s*>\s?(.*?)\s*│\s*$/;
22
+ const BARE_INPUT = /^\s*>\s?(.*?)\s*$/;
23
+ const PLACEHOLDER = /^Try "[^"]*"$/;
24
+ const MENU_FIRST = /^\s*[│|]?\s*[❯›>]\s*1\.\s+\S/;
25
+ const MENU_NEXT = /^\s*[│|]?\s*[❯›>]?\s*2\.\s+\S/;
26
+ /** Words that only a waiting screen shows; seen without the whole dialog, the screen is unknown, never idle. */
27
+ const WAITING_WORDS = /Do you want to|Do you trust|\(y\/n\)|\[y\/N\]|Enter to select|Esc to cancel|Select login method|Paste code here|Press Enter to continue/i;
28
+
29
+ const result = (activity, needs, confident, why) => ({ activity, needs, confident, why });
30
+ export const UNKNOWN_SCREEN = Object.freeze(result("unknown", null, false, "default"));
31
+
32
+ /** Claude Code's interactive screen (shaped after 2.1.x). */
33
+ export function claudeCodeScreen(lines) {
34
+ if (!Array.isArray(lines)) return result("unknown", null, false, "no screen");
35
+ const tail = lines.map((l) => String(l ?? "").replace(/\s+$/, "")).filter((l) => l.trim() !== "").slice(-REGION);
36
+ if (tail.length === 0) return result("unknown", null, false, "blank");
37
+ if (tail.some((l) => /^Pane is dead\b/.test(l))) return result("unknown", null, false, "exited");
38
+ const text = tail.join("\n");
39
+ const menu = tail.some((l) => MENU_FIRST.test(l)) && tail.some((l) => MENU_NEXT.test(l));
40
+ // blocked: what waits for a person, most specific first
41
+ if (/Do you trust the files in this folder\?/.test(text)) return menu ? result("needs_you", "trust", true, "trust") : result("unknown", null, false, "trust, half drawn");
42
+ if (/Select login method|Paste code here if prompted|Invalid API key|Please run \/login/i.test(text)) return result("needs_you", "login", true, "login");
43
+ if (menu && /Do you want to [^\n]*\?/.test(text)) return result("needs_you", "dialog", true, "permission dialog");
44
+ if (menu) return result("needs_you", "question", true, "a choice the agent asks");
45
+ if (/\(y\/n\)|\[y\/N\]/i.test(text)) return result("needs_you", "dialog", true, "yes or no");
46
+ if (WAITING_WORDS.test(text)) return result("unknown", null, false, "a waiting screen, half drawn");
47
+ // working: the agent's own line while it runs
48
+ if (tail.some((l) => /esc to interrupt/i.test(l))) return result("working", null, true, "esc to interrupt");
49
+ // idle: the input line, empty (or its placeholder), inside its box or between its rules, at the very bottom
50
+ const near = tail.slice(-6);
51
+ for (let i = near.length - 1; i >= 0; i -= 1) {
52
+ const boxed = BOXED_INPUT.exec(near[i]);
53
+ const bare = boxed ? null : BARE_INPUT.exec(near[i]);
54
+ const framed = boxed ? (rule(near[i - 1] ?? "") || rule(near[i + 1] ?? "")) : bare ? rule(near[i - 1] ?? "") && rule(near[i + 1] ?? "") : false;
55
+ if (!framed) continue;
56
+ const typed = (boxed ?? bare)[1].trim();
57
+ if (typed === "" || PLACEHOLDER.test(typed)) return result("idle", null, true, "empty input line");
58
+ return result("unknown", null, false, "a draft in the input line"); // never type into the person's half-typed words
59
+ }
60
+ return result("unknown", null, false, "unrecognised");
61
+ }
62
+
63
+ const unbox = (l) => l.replace(/^\s*│\s?/, "").replace(/\s*│\s*$/, "").trim();
64
+ const OPTION = /^\s*[│|]?\s*([❯›>])?\s*(\d)\.\s+(.*?)\s*│?\s*$/;
65
+ const HEADER = /^\s*[│|]?\s*(Bash command|Edit file|Create file|Write file)\s*│?\s*$/;
66
+
67
+ /**
68
+ * Claude Code's permission dialog on the screen, as a phone may answer it (remote-screen-approvals.mjs), or null.
69
+ * `region` is the dialog's own lines, exactly as drawn, header to last option: what the phone shows and the computer
70
+ * hashes, and hashes again just before it presses a key. `tool` and `target` are read from it (a command after
71
+ * "Bash command", a file after "Edit file" or in "create <file>?"); anything not read is null, and the computer's policy
72
+ * then refuses it. `approve` is true only while the cursor is on option 1 and that option is exactly "Yes" (never "Yes,
73
+ * and don't ask again"); `dismiss` only while an option answers with Esc.
74
+ */
75
+ export function claudeCodeDialog(lines) {
76
+ const state = claudeCodeScreen(lines);
77
+ if (state.activity !== "needs_you" || state.needs !== "dialog") return null;
78
+ const tail = lines.map((l) => String(l ?? "").replace(/\s+$/, "")).filter((l) => l.trim() !== "").slice(-REGION);
79
+ const ask = tail.findIndex((l) => /Do you want to [^\n]*\?/.test(l));
80
+ if (ask < 0) return null;
81
+ let start = ask;
82
+ for (let i = ask - 1; i >= Math.max(0, ask - 12); i -= 1) if (HEADER.test(tail[i])) { start = i; break; }
83
+ let last = ask;
84
+ for (let i = ask + 1; i < tail.length; i += 1) if (OPTION.test(tail[i])) last = i;
85
+ const region = tail.slice(start, last + 1);
86
+ const options = region.map((l) => OPTION.exec(l)).filter(Boolean).map((m) => ({ n: Number(m[2]), text: m[3], cursor: Boolean(m[1]) }));
87
+ if (options.length < 2 || options[0].n !== 1) return null;
88
+ const header = HEADER.exec(region[0])?.[1] ?? null;
89
+ const question = unbox(tail[ask]);
90
+ let tool = null, target = null;
91
+ if (header === "Bash command") { tool = "Bash"; target = region.slice(1).map(unbox).find((l) => l !== "") ?? null; }
92
+ else if (header === "Edit file" || /^Do you want to make this edit to /.test(question)) { tool = "Edit"; target = header === "Edit file" ? region.slice(1).map(unbox).find((l) => l !== "") ?? null : null; }
93
+ else if (/^Do you want to create (.+)\?$/.test(question)) { tool = "Write"; target = /^Do you want to create (.+)\?$/.exec(question)[1]; }
94
+ return { region, tool, target, approve: options[0].cursor && options[0].text === "Yes", dismiss: options.some((o) => /\(esc\)$/i.test(o.text)) };
95
+ }
96
+
97
+ /**
98
+ * The keys that answer a screen dialog, per agent, by our own names (remote-adapter-terminal.mjs KEYS), from the
99
+ * fixtures: Claude Code takes the highlighted option with Enter (the cursor on "1. Yes") and "No" with Esc.
100
+ */
101
+ export const SCREEN_ANSWERS = Object.freeze({ "claude-code": Object.freeze({ approve: Object.freeze(["enter"]), deny: Object.freeze(["dismiss"]) }) });
102
+
103
+ /** The detectors by agent, each with the basis of its fixtures. Codex has none yet: no terminal start runs it. */
104
+ export const DETECTORS = Object.freeze({ "claude-code": Object.freeze({ detect: claudeCodeScreen, dialog: claudeCodeDialog, basis: "authored", shapedAfter: "2.1.x" }) });
105
+
106
+ /** The dialog a phone may answer for an agent this file knows, or null. */
107
+ export const screenDialog = (agent, lines) => (Object.hasOwn(DETECTORS, agent) && Array.isArray(lines) ? DETECTORS[agent].dialog(lines) : null);
108
+
109
+ /** The screen's state for an agent this file knows; any other agent is unknown. */
110
+ export const detectScreen = (agent, lines) => (Object.hasOwn(DETECTORS, agent) ? DETECTORS[agent].detect(lines) : UNKNOWN_SCREEN);
111
+
112
+ /** Whether a phone may be offered typing into this agent's terminal: only on fixtures recorded from the real agent. */
113
+ export const typingTrusted = (agent) => Object.hasOwn(DETECTORS, agent) && DETECTORS[agent].basis === "recorded";
@@ -0,0 +1,101 @@
1
+ /**
2
+ * THE DAEMON AS A SERVICE OF THIS USER (2026-11-07). Off until `worktrust remote enable`; removed by `disable`.
3
+ *
4
+ * macOS a launchd agent, ~/Library/LaunchAgents/io.worktrust.remote.plist: RunAtLoad, restarted after a crash
5
+ * (KeepAlive SuccessfulExit false), so `disable` (exit 0) stays off; logs in ~/.worktrust/remote/daemon.log
6
+ * Linux a systemd user unit, ~/.config/systemd/user/worktrust-remote.service, Restart=on-failure, the agents in its
7
+ * control group (they stop with it). Linger stays OFF: it runs while this user is logged in, never as standing
8
+ * remote execution on a machine nobody is logged into. Nothing here calls loginctl.
9
+ * Windows no service: `worktrust remote run` in a terminal, in the foreground, for as long as it should run.
10
+ *
11
+ * The unit runs the verified release launcher the CLI installed, with the PATH the person had when they enabled remote
12
+ * (so the agents are found) and nothing else from their environment. Every command is execFile with fixed arguments.
13
+ */
14
+ import { execFileSync } from "node:child_process";
15
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
16
+ import { homedir, userInfo } from "node:os";
17
+ import { join } from "node:path";
18
+
19
+ export const LABEL = "io.worktrust.remote";
20
+ export const UNIT = "worktrust-remote.service";
21
+ const xml = (text) => String(text).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
22
+ const unitQuote = (text) => `"${String(text).replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%")}"`;
23
+
24
+ export const servicePlatform = (platform = process.platform) => (platform === "darwin" ? "launchd" : platform === "linux" ? "systemd" : "foreground");
25
+ export const plistPath = (home = homedir()) => join(home, "Library", "LaunchAgents", `${LABEL}.plist`);
26
+ export const unitPath = (home = homedir()) => join(home, ".config", "systemd", "user", UNIT);
27
+
28
+ export function launchdPlist({ program, path, home = homedir() }) {
29
+ const args = program.map((a) => ` <string>${xml(a)}</string>`).join("\n");
30
+ const log = xml(join(home, ".worktrust", "remote", "daemon.log"));
31
+ return `<?xml version="1.0" encoding="UTF-8"?>
32
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
33
+ <plist version="1.0">
34
+ <dict>
35
+ <key>Label</key><string>${LABEL}</string>
36
+ <key>ProgramArguments</key>
37
+ <array>
38
+ ${args}
39
+ </array>
40
+ <key>RunAtLoad</key><true/>
41
+ <key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>
42
+ <key>ThrottleInterval</key><integer>10</integer>
43
+ <key>EnvironmentVariables</key><dict><key>PATH</key><string>${xml(path)}</string><key>HOME</key><string>${xml(home)}</string></dict>
44
+ <key>StandardOutPath</key><string>${log}</string>
45
+ <key>StandardErrorPath</key><string>${log}</string>
46
+ </dict>
47
+ </plist>
48
+ `;
49
+ }
50
+
51
+ export function systemdUnit({ program, path }) {
52
+ return `[Unit]
53
+ Description=WorkTrust remote agents (steer this computer's agents from your phone)
54
+
55
+ [Service]
56
+ ExecStart=${program.map(unitQuote).join(" ")}
57
+ Environment=${unitQuote(`PATH=${path}`)}
58
+ Restart=on-failure
59
+ RestartSec=10
60
+ KillMode=control-group
61
+
62
+ [Install]
63
+ WantedBy=default.target
64
+ `;
65
+ }
66
+
67
+ const run = (file, args) => { try { execFileSync(file, args, { stdio: "ignore", timeout: 15_000 }); return true; } catch { return false; } };
68
+
69
+ /** Install and start. `program` is [node, ...nodeArgs, launcher, "remote", "run"]. Returns what was done, in words. */
70
+ export function installService({ program, path, platform = process.platform, home = homedir() }) {
71
+ const kind = servicePlatform(platform);
72
+ if (kind === "launchd") {
73
+ const file = plistPath(home);
74
+ mkdirSync(join(home, "Library", "LaunchAgents"), { recursive: true });
75
+ writeFileSync(file, launchdPlist({ program, path, home }), { mode: 0o644 });
76
+ const domain = `gui/${userInfo().uid}`;
77
+ run("launchctl", ["bootout", `${domain}/${LABEL}`]);
78
+ return { kind, file, started: run("launchctl", ["bootstrap", domain, file]) };
79
+ }
80
+ if (kind === "systemd") {
81
+ const file = unitPath(home);
82
+ mkdirSync(join(home, ".config", "systemd", "user"), { recursive: true });
83
+ writeFileSync(file, systemdUnit({ program, path }), { mode: 0o644 });
84
+ return { kind, file, started: run("systemctl", ["--user", "daemon-reload"]) && run("systemctl", ["--user", "enable", "--now", UNIT]) };
85
+ }
86
+ return { kind, file: null, started: false };
87
+ }
88
+
89
+ export function removeService({ platform = process.platform, home = homedir() } = {}) {
90
+ const kind = servicePlatform(platform);
91
+ if (kind === "launchd") { run("launchctl", ["bootout", `gui/${userInfo().uid}/${LABEL}`]); rmSync(plistPath(home), { force: true }); return kind; }
92
+ if (kind === "systemd") { run("systemctl", ["--user", "disable", "--now", UNIT]); rmSync(unitPath(home), { force: true }); run("systemctl", ["--user", "daemon-reload"]); return kind; }
93
+ return kind;
94
+ }
95
+
96
+ export function serviceState({ platform = process.platform, home = homedir() } = {}) {
97
+ const kind = servicePlatform(platform);
98
+ if (kind === "launchd") return { kind, installed: existsSync(plistPath(home)), running: run("launchctl", ["print", `gui/${userInfo().uid}/${LABEL}`]) };
99
+ if (kind === "systemd") return { kind, installed: existsSync(unitPath(home)), running: run("systemctl", ["--user", "is-active", "--quiet", UNIT]) };
100
+ return { kind, installed: false, running: false };
101
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * WHAT THE SESSIONS REPORT, split out of remote-sessions.mjs (its size), unchanged: the project tree's session list (the
3
+ * journal's sessions and the live ones, as device.inventory lists them), a session's status.report and the live feed's rows.
4
+ */
5
+ import * as P from "./remote-protocol.mjs";
6
+
7
+ const NO_ETA = { kind: "unavailable", source: "none", reason: "no_source" };
8
+
9
+ /** The agent's own plan as the denominator when it has one; otherwise the steps counted (never a percentage). */
10
+ export const progressOf = (s) => {
11
+ const plan = P.planProgress(s.state.progress?.plan ?? null);
12
+ return plan.kind === "measured" ? plan : { kind: "steps", started: s.state.started, completed: s.state.completed };
13
+ };
14
+
15
+ /** One session's status.report: its commands, attention, progress and open approvals. */
16
+ export const statusReport = (ctx, s) => {
17
+ const commands = ctx.journal.commandsOf(s.session_id).slice(-100);
18
+ return { state: commands.at(-1)?.state ?? "DEVICE_RECEIVED", control: "none", attention: s.attention, last_event_seq: ctx.journal.lastSeq(s.session_id),
19
+ progress: progressOf(s), eta: NO_ETA, pending_approvals: ctx.approvals.pendingOf(s.session_id).slice(0, 16), commands };
20
+ };
21
+
22
+ /** The live feed's rows (live.ts), without the release mapping the scheduler adds. */
23
+ export const activeRows = (live) => [...live.values()].filter((s) => s.run && !s.closed).map((s) => {
24
+ const open = [...s.subagents.values()].filter((a) => !P.isFinalSubagentState(a.state));
25
+ return { session_id: s.session_id, project_id: s.project_id, adapter: s.adapter, activity: s.attention?.activity ?? "unknown", progress: progressOf(s), tokens: s.tokens,
26
+ started_at: s.turnOpen ? s.turnStartedAt : null, subagents: open.slice(0, P.MAX_ACTIVE_SUBAGENTS), subagents_cut: open.length > P.MAX_ACTIVE_SUBAGENTS };
27
+ });
28
+
29
+ /**
30
+ * The project tree (2026-11-07): every session this computer knows, live first in its state, then those the journal
31
+ * holds (closed, or waiting to resume after a restart), newest activity first. Names and models are sealed.
32
+ */
33
+ export function listSessions(ctx, live) {
34
+ const rows = new Map();
35
+ for (const j of ctx.journal.sessions()) {
36
+ if (!j.session_id || !j.adapter) continue;
37
+ rows.set(j.session_id, { session_id: j.session_id, project_id: j.project_id ?? null, adapter: j.adapter, origin: "phone", attention: { activity: "unknown", needs: null, state_change_seq: 0, completion_seq: null }, title: null,
38
+ name: j.name ?? null, model: j.model ?? null, state: j.closed ? "closed" : "idle", last_activity_at: ctx.journal.lastAt(j.session_id) ?? j.at ?? null });
39
+ }
40
+ for (const s of live.values()) {
41
+ if (s.closed) continue;
42
+ const prior = rows.get(s.session_id);
43
+ rows.set(s.session_id, { ...(prior ?? {}), session_id: s.session_id, project_id: s.project_id, adapter: s.adapter, origin: "phone", attention: s.attention ?? { activity: "unknown", needs: null, state_change_seq: 0, completion_seq: null }, title: null,
44
+ name: s.name ?? null, model: s.model ?? null, state: s.turnOpen ? "running" : "idle", last_activity_at: ctx.journal.lastAt(s.session_id) ?? prior?.last_activity_at ?? null,
45
+ ...(s.jobs ? { background_jobs: Math.min(99, s.jobs.size) } : {}) });
46
+ }
47
+ return [...rows.values()].sort((a, b) => (b.last_activity_at ?? 0) - (a.last_activity_at ?? 0));
48
+ }