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
@@ -0,0 +1,124 @@
1
+ /**
2
+ * WHERE REMOTE AGENTS KEEP THEIR STATE ON THIS COMPUTER (2026-11-07, docs/remote-agents/PROTOCOL.md).
3
+ *
4
+ * Everything lives in ~/.worktrust/remote/ (a directory of mode 0700, never a symlink), each file 0600, written by
5
+ * temporary file, fsync and rename. Nothing here is the measurement key: the remote device keys are their own pair
6
+ * (Ed25519 to sign, X25519 to agree keys), in their own file, for their own audience. scripts/check-remote-cli.mjs refuses
7
+ * a remote module that names the measurement credentials.
8
+ *
9
+ * remote-keys.json the remote device keys and the secret that derives project ids (never leaves the computer)
10
+ * identity.json this computer's device id and the issuer's binding of its keys
11
+ * settings.json on or off, paused (and by whom), the gateway address, default agent and model, PATH for agents
12
+ * phones.json phones pending a keyboard confirmation, and the confirmed ones with their fingerprints
13
+ * projects.json the folders a phone may steer an agent in, canonical paths
14
+ * channels.json the open end-to-end channels (their keys are secrets)
15
+ * journal.jsonl the command journal (remote-journal.mjs); steered.jsonl the steered ledger (remote-steered.mjs)
16
+ */
17
+ import { createHmac, randomBytes } from "node:crypto";
18
+ import { existsSync, lstatSync, mkdirSync, chmodSync, rmSync } from "node:fs";
19
+ import { homedir } from "node:os";
20
+ import { join } from "node:path";
21
+ import { readPrivateFile, writePrivateFile } from "./package-integrity.mjs";
22
+ import * as P from "./remote-protocol.mjs";
23
+
24
+ export const remoteDir = () => join(homedir(), ".worktrust", "remote");
25
+ export const remotePath = (name) => join(remoteDir(), name);
26
+
27
+ export function ensureRemoteDir() {
28
+ const base = join(homedir(), ".worktrust"), dir = remoteDir();
29
+ for (const path of [base, dir]) {
30
+ if (existsSync(path)) {
31
+ const stat = lstatSync(path);
32
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`${path} must be a directory, not a link`);
33
+ } else mkdirSync(path, { mode: 0o700 });
34
+ try { chmodSync(path, 0o700); } catch { /* Windows */ }
35
+ }
36
+ return dir;
37
+ }
38
+
39
+ export function readJson(name, fallback = null) {
40
+ const file = remotePath(name);
41
+ if (!existsSync(file)) return fallback;
42
+ try { return JSON.parse(readPrivateFile(file)); } catch { throw new Error(`${file} is unreadable or not private (mode 0600)`); }
43
+ }
44
+
45
+ export function writeJson(name, value) {
46
+ ensureRemoteDir();
47
+ writePrivateFile(remotePath(name), `${JSON.stringify(value, null, 2)}\n`);
48
+ }
49
+
50
+ export const removeFile = (name) => rmSync(remotePath(name), { force: true });
51
+
52
+ /** The remote device keys: a fresh pair, kept in memory until a pairing succeeded (then saveKeys). */
53
+ export function newKeys(random = P.systemRandom) {
54
+ return { ...P.exportSecretKeys(P.generateDeviceKeys(random)), project_secret: P.toBase64Url(random(32)) };
55
+ }
56
+ export const saveKeys = (keys) => writeJson("remote-keys.json", { v: 1, ...keys });
57
+ export function loadKeys() {
58
+ const stored = readJson("remote-keys.json");
59
+ if (!stored) return null;
60
+ const secret = P.importSecretKeys(stored);
61
+ if (!secret || typeof stored.project_secret !== "string") throw new Error("remote-keys.json is malformed");
62
+ return { secret, public: P.publicKeysOf(secret), projectSecret: P.fromBase64Url(stored.project_secret) };
63
+ }
64
+
65
+ export const loadIdentity = () => readJson("identity.json");
66
+ export const saveIdentity = (identity) => writeJson("identity.json", identity);
67
+
68
+ export const DEFAULT_SETTINGS = Object.freeze({ v: 1, enabled: false, paused: null, gateway: null, default_adapter: "claude-code", default_model: null, agent_path: null, codex: false, terminal: false });
69
+ export const loadSettings = () => ({ ...DEFAULT_SETTINGS, ...(readJson("settings.json") ?? {}) });
70
+ export const saveSettings = (settings) => writeJson("settings.json", { ...DEFAULT_SETTINGS, ...settings });
71
+
72
+ export const loadPhones = () => ({ pending: [], confirmed: [], removed: [], ...(readJson("phones.json") ?? {}) });
73
+ export const savePhones = (phones) => writeJson("phones.json", phones);
74
+ export const confirmedFingerprints = (phones = loadPhones()) => new Set(phones.confirmed.map((p) => p.fingerprint));
75
+ /** The signing keys of the confirmed phones, by device id: the only keys whose approval decisions count. */
76
+ export const controllerKeys = (phones = loadPhones()) => Object.fromEntries(phones.confirmed.map((p) => [p.device_id, P.fromBase64Url(p.ed25519_pub)]));
77
+
78
+ export const loadProjects = () => readJson("projects.json", []);
79
+ /** Parent folders where a phone may create a new project (remote-projects.mjs): [{ root_id, path, git_init, added_at }]. */
80
+ export const loadRoots = () => readJson("roots.json", []) ?? [];
81
+ /** What a phone may preview per project, granted at the keyboard (remote-preview.mjs): { [project_id]: { ports, files } }. */
82
+ export const loadPreviewGrants = () => readJson("previews.json", {}) ?? {};
83
+ export const savePreviewGrants = (grants) => writeJson("previews.json", grants);
84
+ export const saveRoots = (roots) => writeJson("roots.json", roots);
85
+ /** The pipeline reviews made at the keyboard: { [project_id]: { sha256, reviewed_at, stages } } (remote-pipeline-config.mjs). */
86
+ export const loadPipelineReviews = () => readJson("pipelines.json", {}) ?? {};
87
+ export const savePipelineReviews = (reviews) => writeJson("pipelines.json", reviews);
88
+ /** Release numbers the person marked released at the desk (`worktrust remote releases released <n>`); the phone cannot. */
89
+ export const loadDeskMarks = () => (readJson("released.json", []) ?? []).filter((n) => Number.isSafeInteger(n) && n > 0);
90
+ export const saveDeskMarks = (numbers) => writeJson("released.json", [...new Set(numbers)].sort((a, b) => a - b));
91
+ export const saveProjects = (projects) => writeJson("projects.json", projects);
92
+ /** A stable opaque id for a folder: an HMAC of its canonical path under a key that never leaves this computer. */
93
+ export const projectIdOf = (projectSecret, canonicalPath) =>
94
+ `prj_${P.toBase64Url(createHmac("sha256", Buffer.from(projectSecret)).update(`worktrust-remote/v1/project\n${canonicalPath}`).digest().subarray(0, 16))}`;
95
+
96
+ export function loadChannels() {
97
+ const stored = readJson("channels.json", []);
98
+ return stored.map((c) => P.importChannel(c)).filter(Boolean);
99
+ }
100
+ export const saveChannels = (channels) => writeJson("channels.json", channels.map((c) => P.exportChannel(c)));
101
+
102
+ /**
103
+ * THE ISSUER KEYS THIS RELEASE TRUSTS. Bindings are verified against keys pinned in the build, never against a key a
104
+ * server hands over. Pinned 2026-11-09 from https://app.worktrust.io/api/remote/keys (live since release 18; GATEWAY.md
105
+ * §10 step 8): kid wtr-2026-11, Ed25519. A rotation pins the next key in a later release before the issuer uses it.
106
+ * For a gateway on this computer only (scripts/dev-remote-relay.mjs, the tests): WORKTRUST_REMOTE_DEV_ISSUER="<kid>:<base64url key>" is read when
107
+ * the gateway is this computer's own loopback address, and never otherwise (devIssuerAllowed).
108
+ */
109
+ export const PINNED_ISSUER_KEYS = Object.freeze({ "wtr-2026-11": "Xlsn0fDsC0u3bmXj7FVg1uePKmOlV2yXV3ep9BaRmnA" });
110
+ export const isLoopbackGateway = (url) => {
111
+ try {
112
+ const u = new URL(url);
113
+ return (u.protocol === "ws:" || u.protocol === "wss:") && ["127.0.0.1", "[::1]", "localhost"].includes(u.hostname);
114
+ } catch { return false; }
115
+ };
116
+ export function issuerKeys(gateway) {
117
+ const keys = Object.fromEntries(Object.entries(PINNED_ISSUER_KEYS).map(([kid, key]) => [kid, P.fromBase64Url(key)]));
118
+ const dev = /^([A-Za-z0-9._-]{1,64}):([A-Za-z0-9_-]{43})$/.exec(process.env.WORKTRUST_REMOTE_DEV_ISSUER ?? "");
119
+ if (dev && gateway && isLoopbackGateway(gateway)) keys[dev[1]] = P.fromBase64Url(dev[2]);
120
+ return keys;
121
+ }
122
+
123
+ /** The fresh random bytes the daemon needs (ids, nonces, ephemeral keys). */
124
+ export const random = (length) => new Uint8Array(randomBytes(length));
@@ -0,0 +1,85 @@
1
+ /**
2
+ * TERMINAL SESSIONS AT THE DESK (release 19, 2026-11-09). Called from remote-cli.mjs:
3
+ *
4
+ * remote terminal on | off offer terminal sessions to a phone (off by default), the gaps said first
5
+ * remote terminal list the sessions on WorkTrust's own tmux socket, each with its attach line
6
+ * remote terminal start [<folder>] Claude Code in a new terminal session in a granted folder, attached here
7
+ * (--detached leaves it running without attaching)
8
+ * remote attach <id> this terminal joins a session (started here or from a phone); tmux's own
9
+ * detach (Ctrl-b d) leaves it running
10
+ *
11
+ * Every tmux call names WorkTrust's socket and config (remote-adapter-terminal.mjs); the person's own tmux is never
12
+ * touched. A session started here is the person's own work: it writes nothing to the steered ledger. A phone that later
13
+ * types into it names it there first (remote-terminal-sessions.mjs).
14
+ */
15
+ import { spawnSync } from "node:child_process";
16
+ import { randomUUID } from "node:crypto";
17
+ import * as P from "./remote-protocol.mjs";
18
+ import { loadProjects, loadSettings, random, remotePath, saveSettings } from "./remote-store.mjs";
19
+ import { canonicalProject } from "./remote-policy.mjs";
20
+ import { inventory } from "./remote-inventory.mjs";
21
+ import { attachTarget, createTmux, terminalClaudeArgs, tmuxNameOf, writeTmuxConfig } from "./remote-adapter-terminal.mjs";
22
+
23
+ function tmuxFor(io) {
24
+ const settings = loadSettings();
25
+ const env = { ...process.env, PATH: settings.agent_path ?? process.env.PATH };
26
+ const inv = inventory({ env, refresh: true });
27
+ if (!inv.files.tmux) io.fail("tmux is not installed: `brew install tmux` on macOS, your package manager on Linux (Windows: WSL only)");
28
+ return { inv, tmux: createTmux({ file: inv.files.tmux, config: writeTmuxConfig(remotePath("run")), env }) };
29
+ }
30
+
31
+ function attachHere(io, inv, tmux, name) {
32
+ if (!process.stdin.isTTY || !process.stdout.isTTY) io.fail("attach needs a terminal");
33
+ const r = spawnSync(inv.files.tmux, tmux.attachArgs(name), { stdio: "inherit", env: tmux.env });
34
+ process.exitCode = r.status ?? 1;
35
+ }
36
+
37
+ export async function attachCommand(io, rest) {
38
+ const name = attachTarget(rest[0]);
39
+ if (!name) io.fail("name a terminal session: npx worktrust remote attach <ses_...> (npx worktrust remote terminal list shows them)");
40
+ const { inv, tmux } = tmuxFor(io);
41
+ if (!(await tmux.state(name)).exists) io.fail(`no terminal session ${name.slice(3)} on this computer`);
42
+ attachHere(io, inv, tmux, name);
43
+ }
44
+
45
+ export async function terminalCommand(io, rest, askTyped) {
46
+ const s = loadSettings();
47
+ if (rest[0] === "off") { saveSettings({ ...s, terminal: false }); io.say(" Terminal sessions are no longer offered to a phone. Sessions still running stay; `npx worktrust remote attach <id>` reaches them."); return; }
48
+ if (rest[0] === "list") {
49
+ const { tmux } = tmuxFor(io);
50
+ const projects = loadProjects(), sessions = await tmux.list();
51
+ if (sessions.length === 0) io.say(" No terminal sessions on this computer.");
52
+ for (const t of sessions) {
53
+ const project = projects.find((p) => p.path === t.path);
54
+ io.say(` ${t.session_id} ${project ? project.path : "(not a granted folder: a phone does not see it)"}${t.dead ? " (ended)" : ""}${t.ref ? "" : " (no agent session id: a phone cannot steer it)"}`);
55
+ io.say(` npx worktrust remote attach ${t.session_id}`);
56
+ }
57
+ return;
58
+ }
59
+ if (rest[0] === "start") {
60
+ const { inv, tmux } = tmuxFor(io);
61
+ const canonical = canonicalProject(rest[1] && !rest[1].startsWith("--") ? rest[1] : process.cwd());
62
+ const project = canonical.ok ? loadProjects().find((p) => p.path === canonical.path) : null;
63
+ if (!project) io.fail("start in a granted folder: npx worktrust remote projects add <folder> first");
64
+ const report = inv.terminal;
65
+ if (!report?.capabilities.start) io.fail("this computer cannot run Claude Code in a terminal session (tmux 3.0 or later and a Claude Code with --session-id, --disallowedTools and --setting-sources)");
66
+ const sessionId = P.mintId("ses", random), ref = randomUUID();
67
+ const argv = [inv.files["claude-code"], ...terminalClaudeArgs({ features: inv.features["claude-code"], mode: "ask", model: null, resume: null, sessionRef: ref })];
68
+ if (!(await tmux.start({ name: tmuxNameOf(sessionId), cwd: project.path, argv, ref }))) io.fail("tmux did not start the session");
69
+ io.say(` ✓ Terminal session ${sessionId} in ${project.path}.${s.terminal ? " Your phone sees it." : " Your phone sees it once `npx worktrust remote terminal on`."}`);
70
+ io.say(` Detach with Ctrl-b d; come back with npx worktrust remote attach ${sessionId}`);
71
+ if (!io.has("detached")) attachHere(io, inv, tmux, tmuxNameOf(sessionId));
72
+ return;
73
+ }
74
+ if (rest[0] !== "on") { io.say(` Terminal sessions are ${s.terminal ? "on" : "off"} for remote. npx worktrust remote terminal on | off | list | start [<folder>]`); return; }
75
+ io.say(" Terminal sessions: Claude Code runs in tmux on WorkTrust's own socket, never your own tmux server or ~/.tmux.conf.");
76
+ io.say(" You attach at this desk with npx worktrust remote attach <id>; your phone sees the same screen and can stop it.");
77
+ io.say(" Not yet: typing from the phone. The screen's state (working, a dialog) is not read yet, so a phone sends no words.");
78
+ io.say(" Hours: a session started from your phone is marked remote-steered before it starts, and that includes what you");
79
+ io.say(" then do in it at this desk: none of it counts as your AI Hours. A session you start here stays yours.");
80
+ io.say(" Every terminal session carries the remote deny rules (no git push, installs or deploys by the agent), also here.");
81
+ io.say(" A phone with an app older than this release refuses the computer's agent list while this is on: update it first.");
82
+ if (!(await askTyped("Offer terminal sessions to your phones?"))) io.fail("terminal sessions stay off");
83
+ saveSettings({ ...s, terminal: true });
84
+ io.say(" ✓ Terminal sessions are offered to your phones. npx worktrust remote terminal off takes them back.");
85
+ }
@@ -0,0 +1,291 @@
1
+ /**
2
+ * TERMINAL SESSIONS, BESIDE THE STRUCTURED ONES (release 19, 2026-11-09). A terminal session is Claude Code, interactive,
3
+ * in a tmux session on WorkTrust's own socket (remote-adapter-terminal.mjs): started from a phone (`agent.start` with
4
+ * `mode: "terminal"`) or at the desk (`worktrust remote terminal start`), seen on both, attached at the desk with
5
+ * `worktrust remote attach <id>`. It outlives the daemon: a restart finds it again by its name, and stopping the daemon
6
+ * never ends it.
7
+ *
8
+ * The rules this file holds (test-remote-terminal):
9
+ * - OFF unless the person turned it on at the keyboard (`worktrust remote terminal on`, settings.terminal): no report,
10
+ * no start, no desk session listed. A session it already knows stays its own (never revived as a structured one).
11
+ * - The steered ledger names the agent's session BEFORE tmux starts it (a phone start), and BEFORE the first word a phone
12
+ * types into a desk session. Reading a desk session's screen is not steering it and writes nothing.
13
+ * - A desk session is offered only in a granted project folder and only when it carries its agent's session id
14
+ * (@worktrust_ref): a session the ledger could not name is never steered.
15
+ * - Nothing is typed unless the adapter reports prompts AND the screen's state says idle (promptAllowed); a typed prompt
16
+ * is accepted only when that state is seen to change afterwards (PROTOCOL.md, delivery rule 5). In this slice no
17
+ * screen detector exists, so the report says `prompt: false` and every prompt is refused.
18
+ */
19
+ import { randomUUID } from "node:crypto";
20
+ import { basename } from "node:path";
21
+ import * as P from "./remote-protocol.mjs";
22
+ import { appendSteered } from "./remote-steered.mjs";
23
+ import { terminalClaudeArgs, terminalTextOk, tmuxNameOf } from "./remote-adapter-terminal.mjs";
24
+ import { createScreenApprovals } from "./remote-screen-approvals.mjs";
25
+ import { createScreenPush } from "./remote-screen-push.mjs";
26
+
27
+ const UNKNOWN = Object.freeze({ activity: "unknown", needs: null, state_change_seq: 0, completion_seq: null });
28
+ const NO_ETA = { kind: "unavailable", source: "none", reason: "no_source" };
29
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
30
+ export const TERMINAL_POLL_MS = 2000;
31
+ /** With control mode, a change is looked at this long after tmux reported it (a burst of output is one look). */
32
+ export const CONTROL_DEBOUNCE_MS = 150;
33
+ /** With control mode alive, the poll still looks at each session every this many rounds (a missed event costs 10 s). */
34
+ const CONTROL_SAFETY_ROUNDS = 5;
35
+ const CONTROL_TRIES = 3;
36
+ const STOP_GRACE_MS = 1500;
37
+
38
+ // ctx: { journal, now, emit, settings(), projects(), inventory() (offered), tmux, claudeFile(), replay, onSessionsChanged?,
39
+ // running() (structured sessions running), detect?(lines) -> { activity, needs } | null, sleep?(ms), markLedger?,
40
+ // approvals? (remote-approvals.mjs: screen dialogs), control? (false: never control mode, the poll only),
41
+ // pushMs?, followMs?, setTimer?, clearTimer? (remote-screen-push.mjs, for tests) }
42
+ export function createTerminalSessions(ctx) {
43
+ const live = new Map();
44
+ let desk = [];
45
+ let recovered = false;
46
+ const on = () => ctx.settings().terminal === true;
47
+ const markLedger = ctx.markLedger ?? appendSteered;
48
+ const sleep = ctx.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
49
+ const report = () => ctx.inventory().reports.find((r) => r.adapter === "claude-code" && r.mode === "terminal") ?? null;
50
+ const push = createScreenPush({ now: ctx.now, emit: ctx.emit, pushMs: ctx.pushMs, followMs: ctx.followMs, setTimer: ctx.setTimer, clearTimer: ctx.clearTimer });
51
+ const screen = ctx.approvals ? createScreenApprovals({ approvals: ctx.approvals, emit: ctx.emit, tmux: ctx.tmux, report, agent: "claude-code" }) : null;
52
+ const projectAt = (path) => ctx.projects().find((p) => p.path === path) ?? null;
53
+ const owns = (id) => live.has(id) || ctx.journal.session(id)?.terminal === true || desk.some((d) => d.session_id === id);
54
+ const advance = (id, kind) => { if (id) ctx.journal.advance(id, { kind }, ctx.now()); };
55
+ const mark = (s) => { markLedger({ v: 1, steered: "remote", adapter: "claude-code", agent_session_ref: s.agent_ref, remote_session_id: s.session_id, project_id: s.project_id, how: s.how, first_steered_at: s.first, last_steered_at: ctx.now() }); s.steered = true; };
56
+
57
+ function attention(s, activity, needs = null) {
58
+ const prev = s.attention;
59
+ if (prev && prev.activity === activity && prev.needs === needs) return false;
60
+ const next = { activity, needs, state_change_seq: (prev?.state_change_seq ?? 0) + 1, completion_seq: prev?.completion_seq ?? null };
61
+ s.attention = next;
62
+ ctx.emit(s.session_id, "agent.attention", next, s.command_id, P.notifyHint(prev, next));
63
+ return true;
64
+ }
65
+
66
+ const sessionOf = (fields) => ({ adapter: "claude-code", attention: null, command_id: null, closed: false, stopping: false, pending: null, steered: false, name: null, model: null, first: ctx.now(), ...fields });
67
+ const created = (s, command_id) => ctx.emit(s.session_id, "session.created", { adapter: "claude-code", model: s.model, origin: s.origin, title: null, project_label: basename(s.projectPath).slice(0, 256) || null, name: s.name, mode: "terminal" }, command_id);
68
+
69
+ function close(s) {
70
+ s.closed = true;
71
+ s.watch?.close(); clearTimeout(s.soon); push.stop(s);
72
+ ctx.approvals?.withdraw(s.session_id, "the session ended");
73
+ live.delete(s.session_id);
74
+ ctx.journal.recordSession({ session_id: s.session_id, closed: true });
75
+ ctx.onSessionsChanged?.();
76
+ }
77
+
78
+ async function start(env, payload) {
79
+ if (!on()) return "unsupported";
80
+ const refused = P.checkStart(payload, report() ?? undefined);
81
+ if (refused) return refused;
82
+ if (payload.prompt !== null) return "unsupported"; // nothing is typed until the screen's state is read
83
+ if (live.has(env.session_id) || ctx.journal.session(env.session_id)) return "conflict";
84
+ if (ctx.running() + live.size >= (ctx.settings().max_sessions ?? 4)) return "busy";
85
+ const project = ctx.projects().find((p) => p.project_id === env.project_id);
86
+ if (!project) return "not_found";
87
+ if (payload.resume !== null && !UUID.test(payload.resume)) return "unsupported";
88
+ const s = sessionOf({ session_id: env.session_id, project_id: project.project_id, projectPath: project.path, name: payload.name ?? null, model: payload.model, origin: "phone", how: "started",
89
+ tmux: tmuxNameOf(env.session_id), agent_ref: payload.resume ?? randomUUID(), command_id: env.command_id });
90
+ let argv;
91
+ try { argv = [ctx.claudeFile(), ...terminalClaudeArgs({ features: ctx.inventory().features["claude-code"], mode: payload.permission_mode, model: payload.model, resume: payload.resume, sessionRef: s.agent_ref })]; } catch { return "unsupported"; }
92
+ if (typeof argv[0] !== "string") return "unsupported";
93
+ live.set(s.session_id, s);
94
+ ctx.journal.recordSession({ session_id: s.session_id, adapter: "claude-code", terminal: true, origin: "phone", project_id: s.project_id, agent_session_ref: s.agent_ref, model: s.model, mode: payload.permission_mode, at: ctx.now(), name: s.name });
95
+ mark(s); // the ledger names the agent's session before tmux starts it
96
+ created(s, env.command_id);
97
+ if (!(await ctx.tmux.start({ name: s.tmux, cwd: project.path, argv, ref: s.agent_ref }))) {
98
+ advance(env.command_id, "failed");
99
+ ctx.emit(s.session_id, "agent.failed", { reason: "adapter_error", message: null }, env.command_id);
100
+ close(s);
101
+ return null;
102
+ }
103
+ advance(env.command_id, "agent_accepted");
104
+ ctx.emit(s.session_id, "command.agent_accepted", {}, env.command_id);
105
+ attention(s, "unknown");
106
+ watch(s);
107
+ ctx.onSessionsChanged?.();
108
+ return null;
109
+ }
110
+
111
+ /** A desk session the phone opened: known from now on (journal), read-only until a word is typed into it. */
112
+ function adopt(d) {
113
+ const project = projectAt(d.path);
114
+ if (!project || !d.ref) return null;
115
+ const s = sessionOf({ session_id: d.session_id, project_id: project.project_id, projectPath: project.path, origin: "desk", how: "attached", tmux: d.name, agent_ref: d.ref });
116
+ live.set(s.session_id, s);
117
+ desk = desk.filter((x) => x.session_id !== d.session_id);
118
+ ctx.journal.recordSession({ session_id: s.session_id, adapter: "claude-code", terminal: true, origin: "desk", project_id: s.project_id, agent_session_ref: s.agent_ref, model: null, mode: "ask", at: ctx.now(), name: null });
119
+ created(s, null);
120
+ attention(s, "unknown");
121
+ watch(s);
122
+ return s;
123
+ }
124
+
125
+ async function stop(s) {
126
+ s.stopping = true;
127
+ await ctx.tmux.sendKey(s.tmux, "interrupt").catch(() => false);
128
+ for (let waited = 0; waited < STOP_GRACE_MS; waited += 250) { if ((await ctx.tmux.state(s.tmux)).dead) break; await sleep(250); }
129
+ await ctx.tmux.kill(s.tmux);
130
+ advance(s.command_id, "cancelled");
131
+ ctx.emit(s.session_id, "agent.stopped", {}, s.command_id);
132
+ close(s);
133
+ }
134
+
135
+ function ended(s, state) {
136
+ if (s.stopping) return;
137
+ if (state.status === 0) ctx.emit(s.session_id, "agent.stopped", {}, s.command_id);
138
+ else ctx.emit(s.session_id, "agent.failed", { reason: "agent_exited", message: state.status === null ? null : `The agent exited (${state.status}).` }, s.command_id);
139
+ ctx.tmux.kill(s.tmux).catch(() => false); // the dead pane remain-on-exit kept to read its status
140
+ close(s);
141
+ }
142
+
143
+ /**
144
+ * What the screen says now (remote-screen-states.mjs). A prompt typed before is accepted only once the agent is SEEN
145
+ * taking it afterwards: working, or waiting for the person; a change to unknown (the words still in the input line, a
146
+ * redraw) proves nothing.
147
+ */
148
+ function seen(s, looked) {
149
+ if (!looked) return;
150
+ const changed = attention(s, looked.activity, looked.activity === "needs_you" ? looked.needs ?? "dialog" : null);
151
+ if (changed && s.pending && s.attention.state_change_seq > s.pending.seq && (looked.activity === "working" || looked.activity === "needs_you")) {
152
+ advance(s.pending.command_id, "agent_accepted");
153
+ ctx.emit(s.session_id, "command.agent_accepted", {}, s.pending.command_id);
154
+ s.command_id = s.pending.command_id;
155
+ s.pending = null;
156
+ }
157
+ }
158
+
159
+ /** One look at a session: its end, then what its screen says, then a dialog a phone may answer. Never two at once. */
160
+ async function look(s) {
161
+ if (s.looking) { s.again = true; return; }
162
+ s.looking = true;
163
+ try {
164
+ do {
165
+ s.again = false;
166
+ const state = await ctx.tmux.state(s.tmux);
167
+ if (!state.exists || state.dead) { ended(s, state); return; }
168
+ // What the followers asked for, at least what the detector reads; a follower is pushed the screen when it changed.
169
+ const want = push.linesFor(s);
170
+ if (ctx.detect || want > 0) {
171
+ const cap = await ctx.tmux.capture(s.tmux, Math.max(100, want));
172
+ if (cap && ctx.detect) { seen(s, ctx.detect(cap.lines)); screen?.consider(s, cap.lines); }
173
+ if (cap && want > 0) push.offer(s, cap.lines.length > want ? { lines: cap.lines.slice(-want), cut: true } : cap);
174
+ }
175
+ } while (s.again && !s.closed);
176
+ } finally { s.looking = false; }
177
+ }
178
+
179
+ /** tmux's control mode says WHEN to look (remote-adapter-terminal.mjs control); without it the poll looks every round. */
180
+ function watch(s) {
181
+ if (ctx.control === false || s.closed || s.watch?.alive() || (s.tries ?? 0) >= CONTROL_TRIES) return;
182
+ s.tries = (s.tries ?? 0) + 1;
183
+ s.watch = ctx.tmux.control?.(s.tmux, (kind) => {
184
+ if (kind === "exit") { look(s); return; }
185
+ clearTimeout(s.soon);
186
+ s.soon = setTimeout(() => look(s), CONTROL_DEBOUNCE_MS);
187
+ s.soon.unref?.();
188
+ }) ?? null;
189
+ }
190
+
191
+ async function poll() {
192
+ if (!recovered) { recovered = true; await recover(); }
193
+ for (const s of [...live.values()]) {
194
+ watch(s);
195
+ s.rounds = (s.rounds ?? 0) + 1;
196
+ if (!s.watch?.alive() || s.rounds % CONTROL_SAFETY_ROUNDS === 0) await look(s);
197
+ }
198
+ const before = desk.map((d) => d.session_id).join(",");
199
+ desk = on() ? (await ctx.tmux.list()).filter((d) => !d.dead && d.ref && !owns(d.session_id) && projectAt(d.path)) : [];
200
+ if (desk.map((d) => d.session_id).join(",") !== before) ctx.onSessionsChanged?.();
201
+ }
202
+
203
+ /** After a restart: a known session whose tmux session is still there is live again; one that is gone is closed. */
204
+ async function recover() {
205
+ const ours = new Map((await ctx.tmux.list()).map((d) => [d.session_id, d]));
206
+ for (const j of ctx.journal.sessions()) {
207
+ if (j.terminal !== true || j.closed || live.has(j.session_id)) continue;
208
+ const d = ours.get(j.session_id), project = ctx.projects().find((p) => p.project_id === j.project_id);
209
+ if (!d || d.dead || !project) { ctx.journal.recordSession({ session_id: j.session_id, closed: true }); continue; }
210
+ live.set(j.session_id, sessionOf({ session_id: j.session_id, project_id: project.project_id, projectPath: project.path, origin: j.origin ?? "phone", how: j.origin === "desk" ? "attached" : "started",
211
+ tmux: d.name, agent_ref: j.agent_session_ref, model: j.model ?? null, name: j.name ?? null, attention: { ...UNKNOWN } }));
212
+ }
213
+ }
214
+
215
+ async function words(s, type, payload, command_id) {
216
+ if (!on() || !report()?.capabilities.prompt || type === "agent.steer" || payload.interrupt === true || payload.attachments?.length) return "unsupported";
217
+ if (ctx.detect) { const cap = await ctx.tmux.capture(s.tmux, 100); seen(s, cap ? ctx.detect(cap.lines) : { activity: "unknown", needs: null }); } // the screen again, just before the keys
218
+ if (!P.promptAllowed(s.attention)) return s.attention?.activity === "needs_you" ? "agent_blocked" : "busy";
219
+ if (!terminalTextOk(payload.text)) return "unsupported"; // a control character is never typed
220
+ mark(s); // the ledger names the session before a phone's word reaches it
221
+ if (!(await ctx.tmux.sendText(s.tmux, payload.text)) || !(await ctx.tmux.sendKey(s.tmux, "enter"))) return "not_found";
222
+ s.pending = { command_id, seq: s.attention.state_change_seq };
223
+ return null;
224
+ }
225
+
226
+ const statusOf = (s) => {
227
+ const commands = ctx.journal.commandsOf(s.session_id).slice(-100);
228
+ return { state: commands.at(-1)?.state ?? "DEVICE_RECEIVED", control: "none", attention: s.attention, last_event_seq: ctx.journal.lastSeq(s.session_id),
229
+ progress: { kind: "indeterminate" }, eta: NO_ETA, pending_approvals: [], commands };
230
+ };
231
+ const row = (s) => ({ session_id: s.session_id, project_id: s.project_id, adapter: "claude-code", mode: "terminal", origin: s.origin, attention: s.attention ?? UNKNOWN, title: null,
232
+ name: s.name, model: s.model, state: s.attention?.activity === "working" ? "running" : "idle", last_activity_at: ctx.journal.lastAt(s.session_id) ?? s.first });
233
+
234
+ return {
235
+ owns, start, poll, statusOf,
236
+ get: (id) => live.get(id) ?? null,
237
+ runningCount: () => live.size,
238
+ /** The daemon stops: its control clients go, the tmux sessions stay. */
239
+ release() { for (const s of live.values()) { s.watch?.close(); clearTimeout(s.soon); } },
240
+ rows: () => [...[...live.values()].map(row),
241
+ ...desk.map((d) => ({ session_id: d.session_id, project_id: projectAt(d.path)?.project_id ?? null, adapter: "claude-code", mode: "terminal", origin: "desk", attention: UNKNOWN, title: null, name: null, model: null, state: "idle", last_activity_at: d.created_at }))],
242
+ async handle(env, payload) {
243
+ const type = env.type;
244
+ let s = live.get(env.session_id) ?? null;
245
+ if (type === "session.rename") { if (!s && !ctx.journal.session(env.session_id)) return "not_found"; if (s) s.name = payload.name; ctx.journal.recordSession({ session_id: env.session_id, name: payload.name }); ctx.onSessionsChanged?.(); return "taken"; }
246
+ if (!s && type === "session.attach" && on()) { const d = desk.find((x) => x.session_id === env.session_id); if (d) s = adopt(d); }
247
+ if (!s) return "not_found";
248
+ if (type === "session.attach") { ctx.replay(s.session_id, 0); return "taken"; }
249
+ if (type === "screen.read") {
250
+ push.follow(s, env.sender_device_id, payload.follow, payload.lines); // remote-screen-push.mjs
251
+ const cap = await ctx.tmux.capture(s.tmux, payload.lines);
252
+ if (!cap) return "not_found";
253
+ ctx.emit(s.session_id, "agent.screen", cap, env.command_id);
254
+ push.answered(s, cap);
255
+ return "taken";
256
+ }
257
+ if (type === "status.get") { ctx.emit(s.session_id, "status.report", statusOf(s), env.command_id); return "taken"; }
258
+ if (type === "agent.stop" || type === "session.close") { await stop(s); return "taken"; }
259
+ if (type === "agent.prompt" || type === "agent.steer") return words(s, type, payload, env.command_id);
260
+ if (type === "question.answer") return "not_found";
261
+ return "unsupported"; // pause, resume, focus (tmux cannot raise a window: the phone shows `worktrust remote attach <id>`)
262
+ },
263
+ };
264
+ }
265
+
266
+ /**
267
+ * One registry for the daemon: terminal sessions answered by their own module, every other one by remote-sessions.mjs.
268
+ * The daemon stopping ends the structured agents and never a terminal session (it lives in tmux, perhaps at the desk).
269
+ */
270
+ export function withTerminal(structured, terminal, { pollMs = TERMINAL_POLL_MS } = {}) {
271
+ const timer = setInterval(() => { terminal.poll().catch(() => {}); }, pollMs);
272
+ timer.unref?.();
273
+ const merged = () => {
274
+ const rows = terminal.rows(), ids = new Set(rows.map((r) => r.session_id));
275
+ const rest = structured.listAll().filter((r) => !ids.has(r.session_id)).map((r) => (terminal.owns(r.session_id) ? { ...r, mode: "terminal" } : r));
276
+ return [...rows, ...rest].sort((a, b) => (b.last_activity_at ?? 0) - (a.last_activity_at ?? 0));
277
+ };
278
+ return {
279
+ ...structured,
280
+ async handle(env, payload) {
281
+ if (env.type === "agent.start") return payload.mode === "terminal" ? terminal.start(env, payload) : structured.handle(env, payload);
282
+ return terminal.owns(env.session_id) ? terminal.handle(env, payload) : structured.handle(env, payload);
283
+ },
284
+ list: () => [...structured.list().filter((r) => !terminal.owns(r.session_id)), ...terminal.rows()],
285
+ listAll: merged,
286
+ get: (id) => structured.get(id) ?? terminal.get(id),
287
+ statusOf: (s) => (terminal.get(s.session_id) === s ? terminal.statusOf(s) : structured.statusOf(s)),
288
+ runningCount: () => structured.runningCount() + terminal.runningCount(),
289
+ async stopAll() { clearInterval(timer); terminal.release?.(); await structured.stopAll(); },
290
+ };
291
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * THE ONE OUTBOUND CONNECTION (2026-11-07). The daemon holds a single WebSocket to the gateway (wss://, or ws:// on this
3
+ * computer's loopback for the dev relay): no inbound port, nothing listening beyond this user's approval socket. It works
4
+ * from anywhere the computer has a network. A same-Wi-Fi direct path is a later optimisation behind this same interface
5
+ * (connect, send, close, onFrame); it is not built.
6
+ *
7
+ * Frames are JSON text, at most 2 MiB. The gateway opens with { frame: "challenge", nonce }; the daemon answers with its
8
+ * binding and an Ed25519 signature by its REMOTE key over the nonce, its device id and the gateway's origin, under the
9
+ * domain "worktrust-remote/v1/relay-auth" (so a signature made for one gateway opens no other). Heartbeat: a ping every
10
+ * 20 seconds; nothing heard for 45 seconds closes and reconnects. Reconnects back off from 1 to 30 seconds with full
11
+ * jitter, or the gateway's own hint when it said `closing` (a restart, a drain). Close codes 4001 (revoked) and 4003
12
+ * (protocol) stop the reconnects: the person acts at the keyboard. The production gateway also wants a five-minute
13
+ * assertion from the issuer with every answer to a challenge, and challenges again before it ends (`authorize`).
14
+ * Node 22.4 or later has the WebSocket this uses; older Node refuses plainly (`webSocketAvailable`).
15
+ */
16
+ import * as P from "./remote-protocol.mjs";
17
+
18
+ export const MAX_FRAME = 2 * 1024 * 1024;
19
+ const PING_MS = 20_000, SILENCE_MS = 45_000, BASE_MS = 1000, CAP_MS = 30_000;
20
+ export const STOP_CODES = P.GATEWAY_STOP_CODES;
21
+ export const webSocketAvailable = () => typeof globalThis.WebSocket === "function";
22
+ export const backoffMs = (attempt, random = Math.random) => Math.floor(random() * Math.min(CAP_MS, BASE_MS * 2 ** Math.min(attempt, 10)));
23
+
24
+ export const relayAuthBytes = (deviceId, nonce, origin) => P.relayAuthBytes({ device_id: deviceId, nonce, origin });
25
+ export function authFrame({ deviceId, binding, signingSecret, nonce, origin, assertion = null }) {
26
+ return { frame: "auth", device_id: deviceId, binding, nonce, signature: P.toBase64Url(P.ed25519Sign(relayAuthBytes(deviceId, nonce, origin), signingSecret)), ...(assertion ? { assertion } : {}) };
27
+ }
28
+
29
+ export function connectGateway({ url, identity, signingSecret, onFrame, onState = () => {}, log = () => {}, authorize = async () => null, WebSocketImpl = globalThis.WebSocket }) {
30
+ const origin = new URL(url).origin.replace(/^http/, "ws");
31
+ let socket = null, attempt = 0, stopped = false, ready = false, lastHeard = 0, ping = null, retry = null, hint = null;
32
+ const send = (frame) => {
33
+ if (!ready || socket?.readyState !== 1) return false;
34
+ const text = JSON.stringify(frame);
35
+ if (text.length > MAX_FRAME) { log("frame_too_large", { frame: frame.frame }); return false; }
36
+ socket.send(text);
37
+ return true;
38
+ };
39
+ const schedule = () => {
40
+ if (stopped) return;
41
+ const wait = hint !== null ? hint + backoffMs(0) : backoffMs(attempt++);
42
+ hint = null;
43
+ onState("waiting", { wait });
44
+ retry = setTimeout(open, wait);
45
+ };
46
+ function open() {
47
+ if (stopped) return;
48
+ ready = false;
49
+ try { socket = new WebSocketImpl(url); } catch { schedule(); return; }
50
+ socket.onopen = () => { lastHeard = Date.now(); onState("open"); };
51
+ socket.onmessage = (event) => {
52
+ lastHeard = Date.now();
53
+ const text = typeof event.data === "string" ? event.data : "";
54
+ if (text.length > MAX_FRAME) { socket.close(4003, "too large"); return; }
55
+ let frame = null;
56
+ try { frame = JSON.parse(text); } catch { frame = null; }
57
+ if (!frame || typeof frame.frame !== "string") return;
58
+ if (frame.frame === "challenge" && typeof frame.nonce === "string") {
59
+ const asked = socket;
60
+ authorize().catch(() => null).then((assertion) => {
61
+ if (asked !== socket || asked.readyState !== 1) return;
62
+ asked.send(JSON.stringify(authFrame({ deviceId: identity.device_id, binding: identity.binding, signingSecret, nonce: frame.nonce, origin, assertion })));
63
+ });
64
+ return;
65
+ }
66
+ if (frame.frame === "closing" && Number.isSafeInteger(frame.retry_after_ms)) { hint = Math.min(frame.retry_after_ms, 3_600_000); return; }
67
+ if (frame.frame === "ready") { ready = true; attempt = 0; onState("ready"); }
68
+ if (frame.frame === "pong") return;
69
+ onFrame(frame);
70
+ };
71
+ socket.onclose = (event) => {
72
+ ready = false;
73
+ clearInterval(ping);
74
+ onState("closed", { code: event?.code ?? null });
75
+ if (STOP_CODES.has(event?.code)) { stopped = true; onState("stopped", { code: event.code }); return; }
76
+ schedule();
77
+ };
78
+ socket.onerror = () => {};
79
+ clearInterval(ping);
80
+ ping = setInterval(() => {
81
+ if (Date.now() - lastHeard > SILENCE_MS) { try { socket.close(); } catch { /* closed */ } return; }
82
+ if (socket.readyState === 1) socket.send(JSON.stringify({ frame: "ping" }));
83
+ }, PING_MS);
84
+ ping.unref?.();
85
+ }
86
+ open();
87
+ return { send, ready: () => ready, close() { stopped = true; clearTimeout(retry); clearInterval(ping); try { socket?.close(1000, "bye"); } catch { /* closed */ } } };
88
+ }