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,159 @@
1
+ /**
2
+ * THE CODEX ADAPTER (2026-11-07; docs/remote-agents/PROTOCOL.md "Steering a running turn"). Codex runs as
3
+ * `codex app-server` (JSON-RPC over stdio, Codex 0.154.0), one process per remote session, no shell between us and it.
4
+ *
5
+ * initialize, initialized once
6
+ * thread/start | thread/resume the session (resume by the agent's own thread id); its id reaches `onThread`
7
+ * BEFORE the first turn starts, so the steered ledger names it first
8
+ * turn/start a prompt
9
+ * turn/steer { expectedTurnId } words into the RUNNING turn: measured on 0.154.0, they enter it at the next
10
+ * item boundary (a running command finishes first) and the turn's answer heeds them
11
+ * turn/interrupt end the running turn; the thread stays (measured: 0.7 s to `interrupted`)
12
+ * item/.../requestApproval Codex asks: classified by the computer's own policy as Bash or Edit actions;
13
+ * only an approvable class reaches the phone, everything else is declined here
14
+ * The approval policy is `untrusted` and the sandbox `workspace-write` (`read-only` in the plan mode): Codex asks before
15
+ * anything it does not already trust, and never writes outside the project on its own. No free argument reaches Codex.
16
+ *
17
+ * THE PLANNING TOOLS (2026-11-09), as Claude Code has them: the session's own MCP server (remote-approval-bridge.mjs,
18
+ * `--plans-only`) is the ONE server of the run, given as a `--config` override on Codex's command line, never written to
19
+ * the person's ~/.codex/config.toml. Its socket and token are in a file of this user's only (writeBridgeSession), so the
20
+ * command line, readable in a process list, names a path and no secret. Measured on Codex 0.154.0 (2026-11-09): the
21
+ * override starts the bridge, `enabled_tools` keeps it to the three, `tools.<name>.approval_mode="approve"` runs them
22
+ * without a prompt (else Codex asks by `mcpServer/elicitation/request`), and the server's instructions reach the agent.
23
+ */
24
+ import { spawn } from "node:child_process";
25
+ import { chmodSync, realpathSync, writeFileSync } from "node:fs";
26
+ import { isAbsolute } from "node:path";
27
+ import { changePaths, codexApprovalAsTool, refusalFor } from "./remote-codex-events.mjs";
28
+ import { PLAN_TOOL_NAMES } from "./remote-approval-bridge.mjs";
29
+
30
+ const MODEL = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
31
+ const THREAD = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
32
+ export const isCodexThreadId = (value) => typeof value === "string" && THREAD.test(value);
33
+
34
+ /** A TOML basic string (Codex parses a `--config` value as TOML); a value TOML could not carry is refused, never mangled. */
35
+ const toml = (value) => {
36
+ if (typeof value !== "string" || !value || /[\u0000-\u001f\u007f]/.test(value)) throw new Error("not a value Codex's config can carry");
37
+ return JSON.stringify(value);
38
+ };
39
+ const realOr = (path) => { try { return realpathSync(path); } catch { return path; } };
40
+
41
+ /**
42
+ * The fixed command line. The person's own Codex config stays (its model, its notify hook), but a remote session never
43
+ * widens the sandbox or reaches a configured MCP server (review 2026-11-07, P2-1): no extra writable roots, no network in
44
+ * the sandbox, and `mcp_servers` replaced whole: empty, or the session's own bridge alone (`plans`: { node, bridge,
45
+ * session }, absolute paths). MCP servers a Codex PLUGIN brings still start (measured on 0.154.0); that is part of the
46
+ * risk the person accepts when they turn Codex on (`worktrust remote codex on`).
47
+ * The project is named `untrusted` for this run (2026-11-09): measured on 0.154.0, a `workspace-write` thread in a
48
+ * project Codex does not know WRITES `[projects."<path>"] trust_level = "trusted"` into the person's config.toml; named
49
+ * here, nothing is written, and the repository's own .codex config stays out, as `--setting-sources user` keeps a
50
+ * repository's settings out of Claude Code.
51
+ */
52
+ export function codexArgs({ cwd, plans = null }) {
53
+ if (typeof cwd !== "string" || !isAbsolute(cwd)) throw new Error("a Codex session runs in an absolute project path");
54
+ let servers = "mcp_servers={}";
55
+ if (plans) {
56
+ if (![plans.node, plans.bridge, plans.session].every((p) => typeof p === "string" && isAbsolute(p))) throw new Error("the bridge is named by absolute paths");
57
+ const args = [plans.bridge, "--plans-only", "--session", plans.session].map(toml).join(",");
58
+ servers = `mcp_servers={worktrust_remote={command=${toml(plans.node)},args=[${args}],enabled_tools=[${PLAN_TOOL_NAMES.map(toml).join(",")}],tools={${PLAN_TOOL_NAMES.map((n) => `${n}={approval_mode="approve"}`).join(",")}}}}`;
59
+ }
60
+ const trust = `projects={${[...new Set([cwd, realOr(cwd)])].map((p) => `${toml(p)}={trust_level="untrusted"}`).join(",")}}`;
61
+ return ["app-server", "--config", "sandbox_workspace_write.network_access=false", "--config", "sandbox_workspace_write.writable_roots=[]", "--config", servers, "--config", trust];
62
+ }
63
+
64
+ /** The bridge's channel for one Codex session: its socket and token, this user only (0600), removed with the session. */
65
+ export function writeBridgeSession(file, { socket, token }) {
66
+ writeFileSync(file, JSON.stringify({ socket, token }), { mode: 0o600 });
67
+ chmodSync(file, 0o600);
68
+ return file;
69
+ }
70
+
71
+ /** thread/start or thread/resume parameters from the protocol's closed options. */
72
+ export function threadParams({ cwd, model, mode, resume }) {
73
+ if (mode !== "ask" && mode !== "plan") throw new Error("the protocol offers the ask and plan modes only");
74
+ if (model !== null && !MODEL.test(model)) throw new Error("not a model name");
75
+ if (resume !== null && !isCodexThreadId(resume)) throw new Error("a resume id is Codex's own thread id");
76
+ const common = { cwd, approvalPolicy: "untrusted", sandbox: mode === "plan" ? "read-only" : "workspace-write", ...(model ? { model } : {}) };
77
+ return resume ? { method: "thread/resume", params: { threadId: resume, ...common } } : { method: "thread/start", params: common };
78
+ }
79
+
80
+ const text = (t) => [{ type: "text", text: t }];
81
+
82
+ /**
83
+ * o: { file, cwd, env, model, mode, resume, plans?, onMessage(msg), onThread(threadId), onExit(how), approve(tool, input) → Promise<boolean> }.
84
+ * → { pid, alive, write(text), steer(text) → Promise<{ ok }>, interrupt() → Promise<boolean>, stop(), close() }.
85
+ */
86
+ export function startCodex(o) {
87
+ const child = spawn(o.file, codexArgs({ cwd: o.cwd, plans: o.plans ?? null }), { cwd: o.cwd, env: o.env, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32", windowsHide: true });
88
+ let buffer = "", exited = false, nextId = 1, threadId = null, turnId = null, ready = false;
89
+ const waiting = new Map(), queue = [], fileChanges = {};
90
+ const send = (msg) => { if (!exited) child.stdin.write(`${JSON.stringify(msg)}\n`); };
91
+ const call = (method, params) => new Promise((resolve) => { if (exited) { resolve({ error: { message: "codex exited" } }); return; } const id = nextId++; waiting.set(id, resolve); send({ id, method, params }); });
92
+ const turn = (t) => call("turn/start", { threadId, input: text(t) });
93
+ async function answer(msg) {
94
+ // An MCP server's question (a tool call to approve, a form): the planning tools never ask (approval_mode above), and
95
+ // nothing else of an MCP server is the phone's to answer. Declined in the elicitation's own shape.
96
+ if (msg.method === "mcpServer/elicitation/request") { send({ id: msg.id, result: { action: "decline", content: null } }); return; }
97
+ const asks = msg.method === "item/permissions/requestApproval" ? null : codexApprovalAsTool(msg.method, msg.params, fileChanges, o.cwd);
98
+ let allowed = false;
99
+ if (asks) { allowed = true; for (const a of asks) if (!(await o.approve(a.tool, a.input))) { allowed = false; break; } }
100
+ send({ id: msg.id, result: { decision: allowed ? "accept" : refusalFor(msg.params) } });
101
+ }
102
+ child.stdout.setEncoding("utf8");
103
+ child.stdout.on("data", (chunk) => {
104
+ buffer += chunk;
105
+ if (buffer.length > 16 * 1024 * 1024) { buffer = ""; return; }
106
+ let end;
107
+ while ((end = buffer.indexOf("\n")) >= 0) {
108
+ const raw = buffer.slice(0, end); buffer = buffer.slice(end + 1);
109
+ let msg;
110
+ try { msg = JSON.parse(raw); } catch { continue; }
111
+ if (msg.id !== undefined && msg.method === undefined) { waiting.get(msg.id)?.(msg); waiting.delete(msg.id); continue; }
112
+ if (msg.id !== undefined && typeof msg.method === "string") { answer(msg).catch(() => send({ id: msg.id, result: { decision: refusalFor(msg.params) } })); continue; }
113
+ if (msg.method === "turn/started") turnId = msg.params?.turn?.id ?? turnId;
114
+ if (msg.method === "turn/completed") turnId = null;
115
+ if (msg.method === "item/started" && msg.params?.item?.type === "fileChange") fileChanges[msg.params.item.id] = changePaths(msg.params.item.changes);
116
+ o.onMessage(msg);
117
+ }
118
+ });
119
+ child.stderr.on("data", () => {}); // never logged: it may hold the agent's words
120
+ child.stdin.on("error", () => {});
121
+ // A call never hangs on a Codex that is gone: every one waiting is answered with an error (review 2026-11-07, P2-3).
122
+ const settle = () => { for (const [id, resolve] of waiting) resolve({ id, error: { message: "codex exited" } }); waiting.clear(); };
123
+ const exit = new Promise((resolve) => child.on("exit", (code, signal) => { exited = true; settle(); o.onExit({ code, signal }); resolve(); }));
124
+ child.on("error", () => { if (!exited) { exited = true; settle(); o.onExit({ code: null, signal: null, error: true }); } });
125
+ (async () => {
126
+ await call("initialize", { clientInfo: { name: "worktrust-remote", version: "1" } });
127
+ send({ method: "initialized" });
128
+ const { method, params } = threadParams({ cwd: o.cwd, model: o.model, mode: o.mode, resume: o.resume });
129
+ const started = await call(method, params);
130
+ threadId = started.result?.thread?.id ?? null;
131
+ if (!isCodexThreadId(threadId)) { child.kill("SIGTERM"); return; }
132
+ o.onThread(threadId); // the ledger names the thread before its first turn
133
+ ready = true;
134
+ for (const t of queue.splice(0)) turn(t);
135
+ })().catch(() => child.kill("SIGTERM"));
136
+ const signal = (sig) => { try { if (process.platform === "win32") child.kill(sig); else process.kill(-child.pid, sig); } catch { /* gone */ } };
137
+ return {
138
+ pid: child.pid,
139
+ alive: () => !exited,
140
+ threadId: () => threadId,
141
+ write: (t) => { if (ready) turn(t); else queue.push(t); },
142
+ /** Words into the running turn, guarded by its id: a turn that just ended refuses them, and they wait for the next. */
143
+ async steer(t) { if (!ready || !turnId) return { ok: false }; const r = await call("turn/steer", { threadId, expectedTurnId: turnId, input: text(t) }); return { ok: !r.error }; },
144
+ async interrupt() { if (!ready || !turnId) return false; const r = await call("turn/interrupt", { threadId, turnId }); return !r.error; },
145
+ async stop(graceMs = 3000) {
146
+ if (exited) return;
147
+ if (turnId) await Promise.race([this.interrupt(), new Promise((r) => setTimeout(r, 1000))]);
148
+ for (const sig of ["SIGTERM", "SIGKILL"]) { signal(sig); if (await Promise.race([exit.then(() => true), new Promise((r) => setTimeout(() => r(false), graceMs))])) return; }
149
+ },
150
+ close: () => { try { child.stdin.end(); } catch { /* closed */ } },
151
+ };
152
+ }
153
+
154
+ /** What `codex --version` and its help say this Codex can do; the app-server's methods are fixed per version. */
155
+ export function codexReport(version, appServerHelp) {
156
+ const v = /codex-cli\s+(\d+)\.(\d+)\.(\d+)/.exec(version ?? "");
157
+ const usable = Boolean(v) && /generate-json-schema|--listen/.test(appServerHelp ?? "") && (Number(v[1]) > 0 || Number(v[2]) >= 154);
158
+ return { usable, capabilities: usable ? { start: true, prompt: true, steer: true, steer_mode: "live", interrupt: true, stop: true, structured_events: true, resume_by_id: true, permission_modes: ["ask", "plan"], approvals: "structured" } : null };
159
+ }
@@ -0,0 +1,248 @@
1
+ /**
2
+ * THE TERMINAL ADAPTER, ON tmux (release 19, 2026-11-09; docs/remote-agents/PRIOR-ART-ANALYSIS.md 2.3). A terminal session is
3
+ * one tmux session on WorkTrust's OWN socket, `tmux -L worktrust-remote -f <our config>`, so the person sees the same live
4
+ * agent at the desk (`worktrust remote attach <id>`) and on the phone. The person's own tmux server, socket and
5
+ * ~/.tmux.conf are never touched: every call names our socket and our config, and $TMUX is removed from the call's
6
+ * environment so no call can reach the server the person is sitting in.
7
+ *
8
+ * What tmux itself would do with untrusted text, and what this file does instead (each one held by test-remote-terminal):
9
+ * - A command given as ONE argument is run through the shell (`sh -c`); given as several it is exec'd directly. So an
10
+ * agent's argv has at least two elements, an absolute program first, and is passed after `--`.
11
+ * - An argument that is `;` or ends in `;` ENDS the tmux command and starts another, even after `--` (measured on 3.6a:
12
+ * `send-keys -l -- 'x;' new-session -d -s injected` made a session). Text from the phone is escaped (`\;`), and any
13
+ * other argument ending in `;` is refused.
14
+ * - A target without `=` matches by prefix; every target here is `=name` (exact).
15
+ * - Text goes in with `send-keys -l` (literal: key names are not looked up). A key is only one of KEYS, by our own word.
16
+ * - Control characters from the phone (escape sequences, newlines, Ctrl codes) are refused, never typed.
17
+ * Session names are `wt-<remote session id>`, checked against one strict pattern before any call.
18
+ *
19
+ * No shell anywhere: each call is execFile with an argv array, a timeout and no input.
20
+ */
21
+ import { execFile, spawn } from "node:child_process";
22
+ import { writeFileSync, chmodSync, mkdirSync, existsSync } from "node:fs";
23
+ import { isAbsolute, join } from "node:path";
24
+ import { REMOTE_DENY } from "./remote-adapter-claude-code.mjs";
25
+
26
+ export const SOCKET = "worktrust-remote";
27
+ /** Our socket, or a throwaway one a test names (`worktrust-remote-test-<pid>`); never "default", never a path. */
28
+ const SOCKET_NAME = /^worktrust-remote(-[a-z0-9-]{1,48})?$/;
29
+ const SESSION_NAME = /^wt-ses_[A-Za-z0-9_-]{22}$/;
30
+ const SESSION_ID = /^ses_[A-Za-z0-9_-]{22}$/;
31
+ const REF = /^[A-Za-z0-9._:-]{1,256}$/;
32
+ /**
33
+ * The keys a computer may press, by our own word: nothing from a phone is read as a key name. `dismiss` answers a
34
+ * screen dialog "no" (remote-screen-approvals.mjs, only after the screen still hashes the same).
35
+ */
36
+ export const KEYS = Object.freeze({ enter: "Enter", interrupt: "C-c", dismiss: "Escape" });
37
+ export const MIN_TMUX = [3, 0]; // multi-argument commands exec'd without a shell
38
+ export const MAX_SCREEN_LINES = 2000;
39
+ const MAX_LINE = 1000;
40
+ const MAX_SCREEN_CHARS = 256 * 1024; // well under the sealed body's 1 MiB
41
+
42
+ export const tmuxNameOf = (sessionId) => {
43
+ if (typeof sessionId !== "string" || !SESSION_ID.test(sessionId)) throw new TypeError("not a remote session id");
44
+ return `wt-${sessionId}`;
45
+ };
46
+ export const sessionIdOfName = (name) => (typeof name === "string" && SESSION_NAME.test(name) ? name.slice(3) : null);
47
+ /** What `worktrust remote attach` takes: the session id or its tmux name, nothing else. */
48
+ export const attachTarget = (id) => (typeof id === "string" && SESSION_ID.test(id) ? `wt-${id}` : sessionIdOfName(id) ? id : null);
49
+
50
+ /** This socket's own configuration, written by us and read only by our server. */
51
+ export const TMUX_CONFIG = [
52
+ "# WorkTrust remote: the configuration of WorkTrust's own tmux socket (never your ~/.tmux.conf).",
53
+ "set -g remain-on-exit on",
54
+ "set -g history-limit 5000",
55
+ "set -g mouse off",
56
+ "set -g allow-rename off",
57
+ "set -g set-clipboard off",
58
+ "set -g status-left \"[WorkTrust remote] \"",
59
+ "",
60
+ ].join("\n");
61
+
62
+ export function writeTmuxConfig(dir) {
63
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
64
+ const file = join(dir, "tmux.conf");
65
+ writeFileSync(file, TMUX_CONFIG, { mode: 0o600 });
66
+ try { chmodSync(file, 0o600); } catch { /* Windows */ }
67
+ return file;
68
+ }
69
+
70
+ /** tmux's own command separator, escaped so the text stays one argument: `x;` becomes `x\;`, which tmux reads as `x;`. */
71
+ export const escapeSeparator = (arg) => (arg.endsWith(";") ? `${arg.slice(0, -1)}\\;` : arg);
72
+ // eslint-disable-next-line no-control-regex
73
+ const CONTROL = /[\u0000-\u0008\u000a-\u001f\u007f-\u009f]/;
74
+ /** Text a phone may have typed: printable, tabs allowed, no escape sequence, no newline, no Ctrl code. */
75
+ export const terminalTextOk = (text) => typeof text === "string" && text.length > 0 && text.length <= 65_536 && !CONTROL.test(text);
76
+
77
+ /** The tmux version from `tmux -V` ("tmux 3.6a"), or null; a build without a number ("master") is not trusted. */
78
+ export function tmuxVersion(out) {
79
+ const m = /^tmux (?:next-)?(\d+)\.(\d+)/.exec(String(out ?? "").trim());
80
+ return m ? [Number(m[1]), Number(m[2])] : null;
81
+ }
82
+ export const tmuxUsable = (v) => v !== null && (v[0] > MIN_TMUX[0] || (v[0] === MIN_TMUX[0] && v[1] >= MIN_TMUX[1]));
83
+
84
+ /** The screen as lines a sealed agent.screen carries: no escape sequence, no control code, each line cut, the newest kept. */
85
+ // eslint-disable-next-line no-control-regex
86
+ const ESCAPES = /\u001b\[[0-?]*[ -/]*[@-~]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)|\u001b[@-Z\\-_]/g;
87
+ // eslint-disable-next-line no-control-regex
88
+ const RESIDUE = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g;
89
+ export function screenLines(text, want = MAX_SCREEN_LINES) {
90
+ const all = String(text ?? "").replace(ESCAPES, "").replace(RESIDUE, "").split("\n").map((l) => l.replace(/\s+$/, "").slice(0, MAX_LINE));
91
+ while (all.length > 0 && all.at(-1) === "") all.pop();
92
+ let lines = all.slice(-Math.min(Math.max(1, want), MAX_SCREEN_LINES));
93
+ let cut = lines.length < all.length;
94
+ let size = lines.reduce((n, l) => n + l.length, 0);
95
+ while (size > MAX_SCREEN_CHARS && lines.length > 0) { size -= lines[0].length; lines = lines.slice(1); cut = true; }
96
+ return { lines, cut };
97
+ }
98
+
99
+ /** The one way this file runs tmux: execFile, no shell, a timeout, the result as an exit code and its output. */
100
+ export function runTmuxFile(file, args, { cwd, env, timeout = 5000 } = {}) {
101
+ return new Promise((resolve) => {
102
+ execFile(file, args, { cwd, env, timeout, maxBuffer: 4 * 1024 * 1024, windowsHide: true, encoding: "utf8" }, (error, stdout, stderr) =>
103
+ resolve({ code: error ? (typeof error.code === "number" ? error.code : 1) : 0, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") }));
104
+ });
105
+ }
106
+
107
+ const argOk = (a) => typeof a === "string" && a.length > 0 && !a.includes("\u0000") && !a.endsWith(";");
108
+
109
+ /**
110
+ * tmux on our socket. `run(file, args, opts)` is injectable so the tests drive a fake tmux and read every argv it was handed.
111
+ * `spawnControl` (spawn, injectable likewise) starts the control-mode client `control` uses.
112
+ * → { version, start, capture, sendText, sendKey, state, list, kill, control, attachArgs, socket, config }
113
+ */
114
+ export function createTmux({ file, config, socket = SOCKET, env = process.env, run = runTmuxFile, spawnControl = spawn }) {
115
+ if (!SOCKET_NAME.test(socket)) throw new TypeError("not WorkTrust's tmux socket");
116
+ if (typeof file !== "string" || !isAbsolute(file)) throw new TypeError("tmux is named by its absolute path");
117
+ if (typeof config !== "string" || !isAbsolute(config)) throw new TypeError("our tmux config is named by its absolute path");
118
+ const clean = { ...env };
119
+ delete clean.TMUX; delete clean.TMUX_PANE; // never the server the person sits in
120
+ const base = ["-L", socket, "-f", config];
121
+ const call = (args, opts = {}) => run(file, [...base, ...args], { env: clean, ...opts });
122
+ const named = (name) => { if (typeof name !== "string" || !SESSION_NAME.test(name)) throw new TypeError("not a WorkTrust terminal session name"); return name; };
123
+ const pane = (name) => `=${named(name)}:`;
124
+
125
+ return {
126
+ socket, config,
127
+ async version() { const r = await run(file, ["-V"], { env: clean }); return r.code === 0 ? tmuxVersion(r.stdout) : null; },
128
+ /** The agent in a new detached session, in `cwd`, exec'd from `argv` (two or more, absolute program first). */
129
+ async start({ name, cwd, argv, ref = null, width = 200, height = 50 }) {
130
+ named(name);
131
+ if (typeof cwd !== "string" || !isAbsolute(cwd)) throw new TypeError("a terminal session starts in an absolute folder");
132
+ if (!Array.isArray(argv) || argv.length < 2 || !argv.every(argOk) || !isAbsolute(argv[0])) throw new TypeError("an agent's argv: two or more arguments, an absolute program first, none ending in ;");
133
+ if (ref !== null && !(typeof ref === "string" && REF.test(ref))) throw new TypeError("not an agent session ref");
134
+ const r = await call(["new-session", "-d", "-s", name, "-x", String(width), "-y", String(height), "--", ...argv], { cwd });
135
+ if (r.code !== 0) return false;
136
+ if (ref !== null) await call(["set-option", "-t", pane(name), "--", "@worktrust_ref", ref]);
137
+ return true;
138
+ },
139
+ /** The last `lines` of the pane, wrapped lines joined, as screenLines gives them; null when the session is gone. */
140
+ async capture(name, lines = 200) {
141
+ const want = Math.min(Math.max(1, Math.trunc(lines) || 1), MAX_SCREEN_LINES);
142
+ const r = await call(["capture-pane", "-p", "-J", "-t", pane(name), "-S", String(-want)]);
143
+ return r.code === 0 ? screenLines(r.stdout, want) : null;
144
+ },
145
+ /** Text, literally (`send-keys -l`): never read as key names, never ending a tmux command. */
146
+ async sendText(name, text) {
147
+ if (!terminalTextOk(text)) throw new TypeError("text with a control character is never typed into a terminal");
148
+ return (await call(["send-keys", "-t", pane(name), "-l", "--", escapeSeparator(text)])).code === 0;
149
+ },
150
+ /** One key from KEYS, by its name there (`enter`, `interrupt`); anything else is refused before tmux hears of it. */
151
+ async sendKey(name, key) {
152
+ if (!Object.hasOwn(KEYS, key)) throw new TypeError("not a key this computer presses");
153
+ return (await call(["send-keys", "-t", pane(name), KEYS[key]])).code === 0;
154
+ },
155
+ /**
156
+ * { exists, dead, status }: dead with its exit status once the agent ended (remain-on-exit keeps the pane to read it).
157
+ * display-message answers 0 with empty fields for a session that is gone (measured on 3.6a), so the name it printed
158
+ * must be the one asked for.
159
+ */
160
+ async state(name) {
161
+ const r = await call(["display-message", "-p", "-t", pane(name), "#{session_name}|#{pane_dead}|#{pane_dead_status}"]);
162
+ const [seen, dead, status] = r.stdout.trim().split("|");
163
+ if (r.code !== 0 || seen !== name) return { exists: false, dead: true, status: null };
164
+ return { exists: true, dead: dead === "1", status: /^\d+$/.test(status ?? "") ? Number(status) : null };
165
+ },
166
+ /**
167
+ * Our sessions, each { name, session_id, ref, path, created_at, dead }; foreign names are skipped; no server is none.
168
+ * Fields are split on `|` with the folder LAST (tmux prints a tab as `_`; no name, id or number holds a `|`, a path may).
169
+ */
170
+ async list() {
171
+ const r = await call(["list-sessions", "-F", "#{session_name}|#{@worktrust_ref}|#{session_created}|#{pane_dead}|#{session_path}"]);
172
+ if (r.code !== 0) return [];
173
+ return r.stdout.split("\n").filter(Boolean).map((line) => {
174
+ const [name, ref, created, dead, ...rest] = line.split("|");
175
+ const path = rest.join("|");
176
+ return { name, session_id: sessionIdOfName(name), ref: REF.test(ref ?? "") ? ref : null, path: path || null, created_at: /^\d+$/.test(created ?? "") ? Number(created) * 1000 : null, dead: dead === "1" };
177
+ }).filter((s) => s.session_id !== null);
178
+ },
179
+ async kill(name) { return (await call(["kill-session", "-t", `=${named(name)}`])).code === 0; },
180
+ /**
181
+ * WHEN the session changed, from tmux's control mode (`tmux -C attach-session -t =name`, measured on 3.6a: `%output`
182
+ * per write, `%exit` at the end, the window's size untouched). Only the line's first word is read: what the agent
183
+ * printed is dropped at once (the screen is still read with capture-pane). Nothing is ever written to the control
184
+ * client's input, so no tmux command can reach it that way; its end is reported once. → { alive(), close() } or null.
185
+ */
186
+ control(name, onEvent) {
187
+ named(name);
188
+ let child = null, open = true, head = "", skipping = false;
189
+ const end = () => { if (open) { open = false; onEvent("exit"); } };
190
+ try { child = spawnControl(file, [...base, "-C", "attach-session", "-t", `=${name}`], { env: clean, stdio: ["pipe", "pipe", "ignore"], windowsHide: true }); } catch { return null; }
191
+ const word = (line) => {
192
+ if (/^%(output|extended-output|layout-change|window-pane-changed) /.test(line)) onEvent("output");
193
+ else if (/^%exit\b/.test(line)) end();
194
+ };
195
+ child.stdout?.setEncoding?.("utf8");
196
+ child.stdout?.on("data", (chunk) => {
197
+ for (const part of String(chunk).split(/(\n)/)) {
198
+ if (part === "\n") { if (!skipping) word(head); head = ""; skipping = false; continue; }
199
+ if (skipping) continue;
200
+ head += part;
201
+ if (head.length > 40) { word(head.slice(0, 40)); skipping = true; head = ""; } // the first word told, the rest dropped
202
+ }
203
+ });
204
+ child.on("exit", end);
205
+ child.on("error", end);
206
+ return { alive: () => open, close: () => { open = false; try { child.kill("SIGTERM"); } catch { /* gone */ } } };
207
+ },
208
+ /** The argv `worktrust remote attach` runs with the terminal's own stdio. */
209
+ attachArgs: (name) => [...base, "attach-session", "-t", `=${named(name)}`],
210
+ env: clean,
211
+ };
212
+ }
213
+
214
+ /** No tmux on this computer: every call answers "nothing there", so a session it knew is closed, never run another way. */
215
+ export const NO_TMUX = Object.freeze({ socket: SOCKET, config: null, env: {}, version: async () => null, start: async () => false, capture: async () => null, sendText: async () => false, control: () => null,
216
+ sendKey: async () => false, state: async () => ({ exists: false, dead: true, status: null }), list: async () => [], kill: async () => false, attachArgs: () => { throw new Error("tmux is not installed"); } });
217
+
218
+ /**
219
+ * Claude Code, interactive, as a terminal session runs it: the same deny rules and setting sources as the structured
220
+ * adapter (a phone may steer this session), the session id chosen here so the steered ledger names it before it starts.
221
+ * No text from the phone is an argument: a model the computer listed, a mode from the closed set, a uuid.
222
+ */
223
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
224
+ export function terminalClaudeArgs({ features, mode, model, resume, sessionRef }) {
225
+ if (mode !== "ask" && mode !== "plan") throw new Error("the protocol offers the ask and plan modes only");
226
+ const permission = mode === "plan" ? features?.planMode : features?.askMode;
227
+ if (!permission) throw new Error("this Claude Code offers no such permission mode");
228
+ if (!features.disallowed || !features.settingSources || !features.sessionId) throw new Error("this Claude Code cannot take deny rules, limit its setting sources or take a session id");
229
+ if (resume !== null && !UUID.test(resume ?? "")) throw new Error("a resume id is Claude Code's own session uuid");
230
+ if (resume === null && !UUID.test(sessionRef ?? "")) throw new Error("a new session needs its uuid");
231
+ if (model !== null && (typeof model !== "string" || model.startsWith("-") || !/^[A-Za-z0-9._:@[\]-]{1,128}$/.test(model))) throw new Error("not a model name");
232
+ return ["--permission-mode", permission, "--setting-sources", "user", "--disallowedTools", ...REMOTE_DENY, ...(model ? ["--model", model] : []), ...(resume ? ["--resume", resume] : ["--session-id", sessionRef])];
233
+ }
234
+
235
+ /**
236
+ * The terminal report for Claude Code. Honest about this slice: it starts, shows its screen, stops, and is attached at the
237
+ * desk; it takes NO prompt from a phone yet (`prompt: false`) because its state (working, a dialog) is not read from the
238
+ * screen yet, and the protocol types nothing while a dialog may be on screen (attention.ts, promptAllowed).
239
+ */
240
+ export function terminalReport({ claude, tmux }) {
241
+ const f = claude?.features ?? {};
242
+ const usable = Boolean(claude?.installed && tmuxUsable(tmux) && f.askMode && f.sessionId && f.disallowed && f.settingSources);
243
+ const capabilities = { start: usable, attach: usable, prompt: false, steer: false, pause: false, resume: false, stop: usable, structured_events: false, screen: usable, focus: false,
244
+ resume_by_id: usable && Boolean(f.resume), permission_modes: f.planMode && usable ? ["ask", "plan"] : ["ask"], approvals: "none", acceptance: "state_change", steer_mode: "none", interrupt: false };
245
+ const installed = Boolean(claude?.installed);
246
+ return { adapter: "claude-code", mode: "terminal", installed, version: installed ? claude.version ?? null : null, signed_in: null, capabilities,
247
+ models: installed ? claude.models : null, models_status: installed ? claude.models_status : "not_listed", models_at: installed ? claude.models_at : null, default_model: null };
248
+ }
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * THE PERMISSION-PROMPT TOOL CLAUDE CODE CALLS IN A REMOTE SESSION (2026-11-07). A tiny MCP server on stdio, started by
4
+ * Claude Code itself from the --mcp-config the daemon wrote for one session (`--permission-prompt-tool
5
+ * mcp__worktrust_remote__approve`). Claude Code calls it whenever the person's own permission rules would have asked; the
6
+ * person's allow and deny rules still apply first, at the desk's settings.
7
+ *
8
+ * It decides nothing. It forwards each request ({ tool_name, input, tool_use_id }) over the daemon's local socket
9
+ * (~/.worktrust/remote/run/, this user only), with the session's one-time token, and answers what the daemon answers:
10
+ * { "behavior": "allow", "updatedInput": <the input, unchanged> } only after a signed phone approval of that exact input
11
+ * { "behavior": "deny", "message": "<why>" } everything else, including any failure here
12
+ * Fail closed: no daemon, a lost socket, a malformed answer or six minutes without one is a denial. This is not the
13
+ * WorkTrust MCP door and opens no network connection. It also carries the agent's PLANNING tools (plan_release,
14
+ * plan_task, plan_list; 2026-11-08), answered by the daemon's release queue for the session's own project.
15
+ *
16
+ * CODEX STARTS IT TOO (2026-11-09), for the planning tools only: `--plans-only` (no `approve`: Codex asks through its
17
+ * app-server, never here) and `--session <file>`, the session's socket and token in a file of this user's only (0600, in
18
+ * ~/.worktrust/remote/run/, removed with the session), because Codex takes the server from a `--config` on its own
19
+ * command line and a token there would be readable in any process list. Claude Code hands the same two in the env of
20
+ * the MCP config the daemon wrote. Either way, one session's token, registered by the daemon for that session alone.
21
+ */
22
+ import { readFileSync } from "node:fs";
23
+ import { createConnection } from "node:net";
24
+ import { createInterface } from "node:readline";
25
+
26
+ export const TOOL = "approve";
27
+ const ARGV = process.argv.slice(2);
28
+ /** The session's channel: `--session <file>` (Codex) or the MCP config's env (Claude Code); "" on anything unreadable. */
29
+ export function channelOf(argv = ARGV, env = process.env) {
30
+ const at = argv.indexOf("--session");
31
+ if (at < 0) return { socket: env.WORKTRUST_REMOTE_APPROVAL_SOCKET ?? "", token: env.WORKTRUST_REMOTE_APPROVAL_TOKEN ?? "" };
32
+ try {
33
+ const c = JSON.parse(readFileSync(argv[at + 1], "utf8"));
34
+ return { socket: typeof c?.socket === "string" ? c.socket : "", token: typeof c?.token === "string" ? c.token : "" };
35
+ } catch { return { socket: "", token: "" }; }
36
+ }
37
+ const { socket: SOCKET, token: TOKEN } = channelOf();
38
+ export const PLANS_ONLY = ARGV.includes("--plans-only");
39
+ const WAIT_MS = 6 * 60_000;
40
+ const deny = (message) => ({ behavior: "deny", message });
41
+
42
+ /** Ask the daemon; any failure is a denial. */
43
+ export function askDaemon(request, socket = SOCKET, token = TOKEN, waitMs = WAIT_MS) {
44
+ return new Promise((resolve) => {
45
+ if (!socket || !token) { resolve(deny("WorkTrust remote: no approval channel for this session; denied")); return; }
46
+ let settled = false, buffer = "";
47
+ const done = (answer) => { if (settled) return; settled = true; clearTimeout(timer); try { conn.destroy(); } catch { /* closed */ } resolve(answer); };
48
+ const conn = createConnection(socket);
49
+ const timer = setTimeout(() => done(deny("WorkTrust remote: no decision in time; denied")), waitMs);
50
+ conn.on("connect", () => conn.write(`${JSON.stringify({ token, ...request })}\n`));
51
+ conn.on("data", (chunk) => {
52
+ buffer += chunk;
53
+ if (buffer.length > 1_048_576) { done(deny("WorkTrust remote: malformed answer; denied")); return; }
54
+ const end = buffer.indexOf("\n");
55
+ if (end < 0) return;
56
+ let answer = null;
57
+ try { answer = JSON.parse(buffer.slice(0, end)); } catch { answer = null; }
58
+ if (answer?.behavior === "allow" && answer.updatedInput && typeof answer.updatedInput === "object") done({ behavior: "allow", updatedInput: answer.updatedInput });
59
+ else done(deny(typeof answer?.message === "string" ? answer.message.slice(0, 2000) : "WorkTrust remote: denied"));
60
+ });
61
+ conn.on("error", () => done(deny("WorkTrust remote: the daemon is not reachable; denied")));
62
+ conn.on("close", () => done(deny("WorkTrust remote: the daemon closed the request; denied")));
63
+ });
64
+ }
65
+
66
+ /** A planning call over the same socket: the daemon's answer ({ ok, ... }), or a refusal on any failure. */
67
+ export function askPlan(op, args, socket = SOCKET, token = TOKEN, waitMs = 30_000) {
68
+ return new Promise((resolve) => {
69
+ const refuse = (reason) => ({ ok: false, reason });
70
+ if (!socket || !token) { resolve(refuse("no planning channel for this session")); return; }
71
+ let settled = false, buffer = "";
72
+ const done = (answer) => { if (settled) return; settled = true; clearTimeout(timer); try { conn.destroy(); } catch { /* closed */ } resolve(answer); };
73
+ const conn = createConnection(socket);
74
+ const timer = setTimeout(() => done(refuse("no answer in time")), waitMs);
75
+ conn.on("connect", () => conn.write(`${JSON.stringify({ token, plan: { op, args } })}\n`));
76
+ conn.on("data", (chunk) => {
77
+ buffer += chunk;
78
+ if (buffer.length > 1_048_576) { done(refuse("malformed answer")); return; }
79
+ const end = buffer.indexOf("\n");
80
+ if (end < 0) return;
81
+ let answer = null;
82
+ try { answer = JSON.parse(buffer.slice(0, end)); } catch { answer = null; }
83
+ done(answer && typeof answer === "object" && typeof answer.ok === "boolean" ? answer : refuse("malformed answer"));
84
+ });
85
+ conn.on("error", () => done(refuse("the daemon is not reachable")));
86
+ conn.on("close", () => done(refuse("the daemon closed the request")));
87
+ });
88
+ }
89
+
90
+ /**
91
+ * THE PLANNING TOOLS (owner, 2026-11-08: the agent arranges its own work, the phone shows it on Status). Short on
92
+ * purpose: their descriptions travel with every turn. The project is the session's own; nothing here runs anything.
93
+ */
94
+ /** The one line that asks the agent to plan with them: Claude Code's --append-system-prompt, Codex's server instructions. */
95
+ export const PLAN_HINT = "WorkTrust remote: plan multi-step work with plan_release and report each task with plan_task; the person follows it on their phone.";
96
+ const n = (description) => ({ type: "integer", description });
97
+ const PLAN_TOOLS = [
98
+ { name: "plan_release", op: "release", description: "Plan multi-step work as a release on the phone's Status: tasks you then do yourself. Check plan_list first.",
99
+ inputSchema: { type: "object", properties: { title: { type: "string" }, label: { type: "string", description: "short name, e.g. CLI 0.11.0" }, estimate_min: n("your estimate, minutes"), after: n("release number it waits for"),
100
+ tasks: { type: "array", items: { type: "object", properties: { title: { type: "string" }, estimate_min: n("minutes") }, required: ["title"] } } }, required: ["title"] } },
101
+ { name: "plan_task", op: "task", description: "Add a task to a release, or report yours: running, done or failed (note: one line).",
102
+ inputSchema: { type: "object", properties: { release: n("release number, to add"), title: { type: "string" }, estimate_min: n("minutes"), task_id: { type: "string" }, state: { type: "string", enum: ["running", "done", "failed"] }, note: { type: "string" } } } },
103
+ { name: "plan_list", op: "list", description: "This project's open releases and tasks.", inputSchema: { type: "object", properties: {} } },
104
+ ];
105
+ export const PLAN_TOOL_NAMES = Object.freeze(PLAN_TOOLS.map((t) => t.name));
106
+
107
+ const reply = (id, result) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`);
108
+ const error = (id, code, message) => process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } })}\n`);
109
+
110
+ export async function handle(message, ask = askDaemon, plan = askPlan, plansOnly = PLANS_ONLY) {
111
+ const { id, method, params } = message ?? {};
112
+ if (method === "initialize") return { id, result: { protocolVersion: typeof params?.protocolVersion === "string" ? params.protocolVersion : "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "worktrust-remote", version: "1" },
113
+ // Codex puts a server's instructions beside its tools (measured on 0.154.0: in tool_search, "worktrust_remote: <line>"),
114
+ // so they reach the agent without replacing the person's own developer instructions. Claude Code has its line already.
115
+ ...(plansOnly ? { instructions: PLAN_HINT } : {}) } };
116
+ if (method === "ping") return { id, result: {} };
117
+ const approveTool = plansOnly ? [] : [{ name: TOOL, description: "WorkTrust remote: asks the person's confirmed phone to approve one permission request, or denies it.", inputSchema: { type: "object", properties: { tool_name: { type: "string" }, input: { type: "object" }, tool_use_id: { type: "string" } }, required: ["tool_name", "input"] } }];
118
+ if (method === "tools/list") return { id, result: { tools: [...approveTool, ...PLAN_TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema }))] } };
119
+ if (method === "tools/call") {
120
+ const planTool = PLAN_TOOLS.find((t) => t.name === params?.name);
121
+ if (planTool) {
122
+ const answer = await plan(planTool.op, params.arguments && typeof params.arguments === "object" ? params.arguments : {});
123
+ return { id, result: { content: [{ type: "text", text: JSON.stringify(answer) }], ...(answer?.ok ? {} : { isError: true }) } };
124
+ }
125
+ if (params?.name !== TOOL || plansOnly) return { id, error: { code: -32602, message: "unknown tool" } };
126
+ const a = params.arguments ?? {};
127
+ const answer = typeof a.tool_name === "string" && a.input && typeof a.input === "object"
128
+ ? await ask({ tool_name: a.tool_name, input: a.input, tool_use_id: typeof a.tool_use_id === "string" ? a.tool_use_id : null })
129
+ : deny("WorkTrust remote: malformed permission request; denied");
130
+ return { id, result: { content: [{ type: "text", text: JSON.stringify(answer) }] } };
131
+ }
132
+ if (id === undefined) return null; // a notification
133
+ return { id, error: { code: -32601, message: "method not found" } };
134
+ }
135
+
136
+ const isMain = process.argv[1] && import.meta.url.endsWith(process.argv[1].split(/[\\/]/).pop());
137
+ if (isMain) {
138
+ createInterface({ input: process.stdin }).on("line", async (line) => {
139
+ let message;
140
+ try { message = JSON.parse(line); } catch { return; }
141
+ const answer = await handle(message);
142
+ if (!answer) return;
143
+ if (answer.error) error(answer.id, answer.error.code, answer.error.message); else reply(answer.id, answer.result);
144
+ });
145
+ }