worktrust 0.11.0 → 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.
@@ -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
@@ -65,7 +65,7 @@ export function loadKeys() {
65
65
  export const loadIdentity = () => readJson("identity.json");
66
66
  export const saveIdentity = (identity) => writeJson("identity.json", identity);
67
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 });
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
69
  export const loadSettings = () => ({ ...DEFAULT_SETTINGS, ...(readJson("settings.json") ?? {}) });
70
70
  export const saveSettings = (settings) => writeJson("settings.json", { ...DEFAULT_SETTINGS, ...settings });
71
71
 
@@ -101,11 +101,12 @@ export const saveChannels = (channels) => writeJson("channels.json", channels.ma
101
101
 
102
102
  /**
103
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. The Passport app's issuer is not live yet, so no key is pinned and `remote enable` refuses plainly.
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.
105
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
106
107
  * the gateway is this computer's own loopback address, and never otherwise (devIssuerAllowed).
107
108
  */
108
- export const PINNED_ISSUER_KEYS = Object.freeze({});
109
+ export const PINNED_ISSUER_KEYS = Object.freeze({ "wtr-2026-11": "Xlsn0fDsC0u3bmXj7FVg1uePKmOlV2yXV3ep9BaRmnA" });
109
110
  export const isLoopbackGateway = (url) => {
110
111
  try {
111
112
  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
+ }