worktrust 0.11.0 → 0.11.2

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-run.mjs CHANGED
@@ -22,16 +22,23 @@ import { inventory as listAgents, offered } from "./remote-inventory.mjs";
22
22
  const inventory = (o) => offered(listAgents(o), loadSettings());
23
23
  import { createApprovals } from "./remote-approvals.mjs";
24
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";
25
28
  import { createReleases } from "./remote-releases.mjs";
26
29
  import { createPipelines } from "./remote-pipeline.mjs";
27
30
  import { createAttachments } from "./remote-attachments.mjs";
28
31
  import { createPreview } from "./remote-preview.mjs";
32
+ import { createLivePreview } from "./remote-live-preview.mjs";
29
33
  import { appendPipelineMark } from "./remote-steered.mjs";
30
34
  import { createDaemonCore } from "./remote-daemon.mjs";
31
35
  import { connectGateway, webSocketAvailable } from "./remote-transport.mjs";
32
36
 
33
37
  const HERE = dirname(fileURLToPath(import.meta.url));
34
38
  const log = (kind, fields = {}) => process.stderr.write(`${JSON.stringify({ at: new Date().toISOString(), kind, ...fields })}\n`);
39
+ // A browser a phone added (2026-11-09, remote-endorse.mjs) is said in words too, so it is never news only in a JSON line.
40
+ const notice = (kind, fields) => { if (kind === "browser_endorsed") process.stderr.write(` ! A browser was added by your phone ${fields.by}: ${fields.fingerprint}. See or remove it: npx worktrust remote phones\n`); };
41
+ const logged = (kind, fields = {}) => { log(kind, fields); notice(kind, fields); };
35
42
 
36
43
  export function agentEnv(settings, base = process.env) {
37
44
  const env = {};
@@ -117,7 +124,10 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
117
124
  const attachments = createAttachments({ journal, now: Date.now, emit: (...a) => core.emit(...a), log,
118
125
  sessionProject: (id) => { const s = journal.session(id); return s ? loadProjects().find((p) => p.project_id === s.project_id) ?? null : null; } });
119
126
  const preview = createPreview({ emit: (...a) => core.emit(...a), projects: loadProjects, grants: loadPreviewGrants, env: () => agentEnv(loadSettings()), log });
120
- const core = createDaemonCore({ local, issuerKeys: keysOf, journal, projectSecret: keys.projectSecret, attachments, preview, now: Date.now, random, log, send: (f) => transport?.send(f) ?? false, inventory: (refresh) => inventory({ env: agentEnv(loadSettings()), refresh }), online: () => transport?.ready() ?? false, approvals: null });
127
+ // The live preview (release 19): the session's granted page, live, over the browser's pipe; one per computer.
128
+ const live = createLivePreview({ emit: (...a) => core.emit(...a), grants: loadPreviewGrants, env: () => agentEnv(loadSettings()), log, now: Date.now,
129
+ sessionProject: (id) => { const s = journal.session(id); return s ? loadProjects().find((p) => p.project_id === s.project_id) ?? null : null; } });
130
+ const core = createDaemonCore({ local, issuerKeys: keysOf, journal, projectSecret: keys.projectSecret, attachments, preview, live, now: Date.now, random, log: logged, send: (f) => transport?.send(f) ?? false, inventory: (refresh) => inventory({ env: agentEnv(loadSettings()), refresh }), online: () => transport?.ready() ?? false, approvals: null });
121
131
  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 };
122
132
  const approvals = createApprovals(ctx);
123
133
  const socket = await approvals.listen(runDir);
@@ -127,6 +137,13 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
127
137
  onTaskEnded: (id, outcome) => releases.taskEnded(id, outcome), onActivity: () => releases?.activity(),
128
138
  onSessionsChanged: () => core.emit(null, "device.inventory", core.inventoryBody(false)), attachments });
129
139
  ctx.onApprovalOpened = sessions.onApprovalOpened; ctx.onApprovalSettled = sessions.onApprovalSettled;
140
+ // Terminal sessions (release 19, off until `worktrust remote terminal on`): Claude Code in tmux on WorkTrust's own socket.
141
+ const tmuxFile = listAgents({ env: agentEnv(loadSettings()) }).files.tmux;
142
+ const tmux = tmuxFile ? createTmux({ file: tmuxFile, config: writeTmuxConfig(runDir), env: agentEnv(loadSettings()) }) : NO_TMUX;
143
+ const terminal = createTerminalSessions({ journal, now: Date.now, emit: core.emit, settings: loadSettings, projects: loadProjects, inventory: () => inventory({ env: agentEnv(loadSettings()) }),
144
+ tmux, claudeFile: () => listAgents({ env: agentEnv(loadSettings()) }).files["claude-code"], replay: core.replay, running: () => sessions.runningCount(), detect: (lines) => detectScreen("claude-code", lines), approvals,
145
+ onSessionsChanged: () => core.emit(null, "device.inventory", core.inventoryBody(false)) });
146
+ const registry = withTerminal(sessions, terminal);
130
147
  // Releases and pipelines (2026-11-07): one queue for every release's tasks, the reviewed pipeline of each project.
131
148
  const pipelines = createPipelines({ journal, now: Date.now, random, emit: core.emit, projects: loadProjects, reviews: loadPipelineReviews, log, logDir: remotePath("pipelines"),
132
149
  markLedger: appendPipelineMark, env: (prepend) => stageEnv(loadSettings(), prepend), onEnded: (p) => releases?.pipelineEnded(p), commandOf });
@@ -136,7 +153,7 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
136
153
  ctx.plan = (session, op, args) => releases.plan(session, op, args);
137
154
  releases.recover(); // tasks an earlier daemon left running: interrupted, never run again
138
155
  pipelines.recover(); // and its pipeline runs
139
- core.attach(sessions, approvals, releases);
156
+ core.attach(registry, approvals, releases);
140
157
 
141
158
  const dispatchFrame = async (frame) => {
142
159
  if (frame.frame === "hello") core.receiveHello(frame.hello);
@@ -161,7 +178,8 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
161
178
  stopping = true;
162
179
  approvals.close();
163
180
  await pipelines.stopAll();
164
- await sessions.stopAll();
181
+ await live.stopAll(); // the browser ended, its profile removed
182
+ await registry.stopAll(); // the structured agents; a terminal session lives on in tmux
165
183
  transport.close();
166
184
  release();
167
185
  process.exit(code);
@@ -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";
@@ -1,7 +1,30 @@
1
1
  /**
2
- * THE PROJECT TREE'S SESSION LIST, split out of remote-sessions.mjs (its size), unchanged: the journal's sessions and the
3
- * live ones, as device.inventory lists them.
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
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
+ });
5
28
 
6
29
  /**
7
30
  * The project tree (2026-11-07): every session this computer knows, live first in its state, then those the journal
@@ -16,16 +16,15 @@ import { adapterOf } from "./remote-inventory.mjs";
16
16
  import { claudeArgs, isClaudeSessionId, removeQuietly, startClaude, writeMcpConfig } from "./remote-adapter-claude-code.mjs";
17
17
  import { backgroundJobs, emptyClaudeState, endClaudeRun, mapClaudeLine } from "./remote-claude-events.mjs";
18
18
  import { collectChanges, snapshotChanges } from "./remote-changes.mjs";
19
- import { isCodexThreadId, startCodex } from "./remote-adapter-codex.mjs";
19
+ import { isCodexThreadId, startCodex, writeBridgeSession } from "./remote-adapter-codex.mjs";
20
20
  import { emptyCodexState, mapCodexMessage, unwrapShell } from "./remote-codex-events.mjs";
21
21
  import { createCoalescer } from "./remote-coalesce.mjs";
22
22
  import { accept, announceQueue, claudeReplay, codexLanded, dropWaiting, interruptedEnd, interruptOf, steerLive, steerModeOf } from "./remote-steering.mjs";
23
23
  import { classifyAction } from "./remote-policy.mjs";
24
- import { listSessions } from "./remote-session-list.mjs";
24
+ import { activeRows, listSessions, statusReport } from "./remote-session-list.mjs";
25
25
 
26
26
  export const DEFAULT_MAX_SESSIONS = 4;
27
27
  const LEDGER_EVERY_MS = 10 * 60_000;
28
- const NO_ETA = { kind: "unavailable", source: "none", reason: "no_source" };
29
28
 
30
29
  export { createCoalescer } from "./remote-coalesce.mjs"; // kept here for the modules that import it from sessions
31
30
 
@@ -171,10 +170,14 @@ export function createSessions(ctx) {
171
170
  ctx.onActivity?.();
172
171
  }
173
172
 
174
- /** Codex: the thread id reaches the ledger before its first turn (startCodex calls onThread before turn/start). */
173
+ /**
174
+ * Codex: the thread id reaches the ledger before its first turn (startCodex calls onThread before turn/start). Its
175
+ * planning tools are the session's own bridge, its token in a 0600 file beside Claude Code's MCP config (2026-11-09).
176
+ */
175
177
  function spawnCodex(s, resume) {
176
178
  s.token = ctx.approvals.register(s); // so its open approvals are denied when it ends (P3-8)
177
- s.run = startCodex({ file: ctx.inventory().files.codex, cwd: s.projectPath, env: ctx.agentEnv(), model: s.model, mode: s.mode, resume,
179
+ const plans = ctx.bridgePath && ctx.socket ? { node: ctx.node, bridge: ctx.bridgePath, session: s.mcpFile = writeBridgeSession(join(ctx.runDir, `${s.session_id}.codex.json`), { socket: ctx.socket(), token: s.token }) } : null;
180
+ s.run = startCodex({ file: ctx.inventory().files.codex, cwd: s.projectPath, env: ctx.agentEnv(), model: s.model, mode: s.mode, resume, plans,
178
181
  onMessage: (msg) => onCodex(s, msg), onExit: (how) => onExit(s, how),
179
182
  onThread: (id) => { s.agent_ref = id; mark(s); ctx.journal.recordSession({ session_id: s.session_id, agent_session_ref: id }); },
180
183
  approve: async (tool, input) => (await ctx.approvals.request(s, tool, input))?.behavior === "allow" });
@@ -277,17 +280,7 @@ export function createSessions(ctx) {
277
280
  return null;
278
281
  }
279
282
 
280
- /** The agent's own plan as the denominator when it has one; otherwise the steps counted (never a percentage). */
281
- const progressOf = (s) => {
282
- const plan = P.planProgress(s.state.progress?.plan ?? null);
283
- return plan.kind === "measured" ? plan : { kind: "steps", started: s.state.started, completed: s.state.completed };
284
- };
285
-
286
- const statusOf = (s) => {
287
- const commands = ctx.journal.commandsOf(s.session_id).slice(-100);
288
- return { state: commands.at(-1)?.state ?? "DEVICE_RECEIVED", control: "none", attention: s.attention, last_event_seq: ctx.journal.lastSeq(s.session_id),
289
- progress: progressOf(s), eta: NO_ETA, pending_approvals: ctx.approvals.pendingOf(s.session_id).slice(0, 16), commands };
290
- };
283
+ const statusOf = (s) => statusReport(ctx, s);
291
284
 
292
285
  return {
293
286
  list: () => [...live.values()].filter((s) => !s.closed).map((s) => ({ 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 })),
@@ -338,11 +331,7 @@ export function createSessions(ctx) {
338
331
  },
339
332
  runningCount: () => [...live.values()].filter((s) => s.run).length,
340
333
  /** The live feed's rows (live.ts), without the release mapping the scheduler adds. */
341
- activeList: () => [...live.values()].filter((s) => s.run && !s.closed).map((s) => {
342
- const open = [...s.subagents.values()].filter((a) => !P.isFinalSubagentState(a.state));
343
- 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,
344
- started_at: s.turnOpen ? s.turnStartedAt : null, subagents: open.slice(0, P.MAX_ACTIVE_SUBAGENTS), subagents_cut: open.length > P.MAX_ACTIVE_SUBAGENTS };
345
- }),
334
+ activeList: () => activeRows(live),
346
335
  async stopAll() { for (const s of live.values()) if (s.run) { s.stopping = true; await s.run.stop(500); } },
347
336
  };
348
337
  }
package/remote-store.mjs CHANGED
@@ -9,7 +9,9 @@
9
9
  * remote-keys.json the remote device keys and the secret that derives project ids (never leaves the computer)
10
10
  * identity.json this computer's device id and the issuer's binding of its keys
11
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
12
+ * phones.json phones pending a keyboard confirmation, and the confirmed ones with their fingerprints (and, for a
13
+ * browser a phone added, which phone and when)
14
+ * endorsements.json the one-time nonces of browser endorsements already taken, kept a little past their expiry
13
15
  * projects.json the folders a phone may steer an agent in, canonical paths
14
16
  * channels.json the open end-to-end channels (their keys are secrets)
15
17
  * journal.jsonl the command journal (remote-journal.mjs); steered.jsonl the steered ledger (remote-steered.mjs)
@@ -65,12 +67,16 @@ export function loadKeys() {
65
67
  export const loadIdentity = () => readJson("identity.json");
66
68
  export const saveIdentity = (identity) => writeJson("identity.json", identity);
67
69
 
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 });
70
+ // allow_endorse (2026-11-09): may a confirmed phone add a browser it scanned (remote-endorse.mjs)? Off until the person says so
71
+ // here, at the keyboard (`worktrust remote phones allow-endorse on`).
72
+ 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, allow_endorse: false });
69
73
  export const loadSettings = () => ({ ...DEFAULT_SETTINGS, ...(readJson("settings.json") ?? {}) });
70
74
  export const saveSettings = (settings) => writeJson("settings.json", { ...DEFAULT_SETTINGS, ...settings });
71
75
 
72
76
  export const loadPhones = () => ({ pending: [], confirmed: [], removed: [], ...(readJson("phones.json") ?? {}) });
73
77
  export const savePhones = (phones) => writeJson("phones.json", phones);
78
+ export const loadEndorsements = () => readJson("endorsements.json", { spent: [] }) ?? { spent: [] };
79
+ export const saveEndorsements = (value) => writeJson("endorsements.json", value);
74
80
  export const confirmedFingerprints = (phones = loadPhones()) => new Set(phones.confirmed.map((p) => p.fingerprint));
75
81
  /** The signing keys of the confirmed phones, by device id: the only keys whose approval decisions count. */
76
82
  export const controllerKeys = (phones = loadPhones()) => Object.fromEntries(phones.confirmed.map((p) => [p.device_id, P.fromBase64Url(p.ed25519_pub)]));
@@ -101,11 +107,12 @@ export const saveChannels = (channels) => writeJson("channels.json", channels.ma
101
107
 
102
108
  /**
103
109
  * THE ISSUER KEYS THIS RELEASE TRUSTS. Bindings are verified against keys pinned in the build, never against a key a
104
- * server hands over. The Passport app's issuer is not live yet, so no key is pinned and `remote enable` refuses plainly.
110
+ * server hands over. Pinned 2026-11-09 from https://app.worktrust.io/api/remote/keys (live since release 18; GATEWAY.md
111
+ * §10 step 8): kid wtr-2026-11, Ed25519. A rotation pins the next key in a later release before the issuer uses it.
105
112
  * For a gateway on this computer only (scripts/dev-remote-relay.mjs, the tests): WORKTRUST_REMOTE_DEV_ISSUER="<kid>:<base64url key>" is read when
106
113
  * the gateway is this computer's own loopback address, and never otherwise (devIssuerAllowed).
107
114
  */
108
- export const PINNED_ISSUER_KEYS = Object.freeze({});
115
+ export const PINNED_ISSUER_KEYS = Object.freeze({ "wtr-2026-11": "Xlsn0fDsC0u3bmXj7FVg1uePKmOlV2yXV3ep9BaRmnA" });
109
116
  export const isLoopbackGateway = (url) => {
110
117
  try {
111
118
  const u = new URL(url);
@@ -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
+ }