worktrust 0.10.37 → 0.11.0

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 (43) hide show
  1. package/LICENSE +43 -18
  2. package/README.md +59 -2
  3. package/SECURITY.md +25 -0
  4. package/chat-exports.mjs +20 -20
  5. package/engine-release.json +1 -1
  6. package/export-facts.mjs +71 -0
  7. package/log-session.mjs +15 -15
  8. package/package-release.json +1 -1
  9. package/package.json +36 -2
  10. package/remote-adapter-claude-code.mjs +111 -0
  11. package/remote-adapter-codex.mjs +119 -0
  12. package/remote-approval-bridge.mjs +122 -0
  13. package/remote-approvals.mjs +124 -0
  14. package/remote-attachments.mjs +129 -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 +325 -0
  19. package/remote-coalesce.mjs +40 -0
  20. package/remote-codex-events.mjs +153 -0
  21. package/remote-daemon.mjs +205 -0
  22. package/remote-inventory.mjs +132 -0
  23. package/remote-journal.mjs +155 -0
  24. package/remote-pairing.mjs +104 -0
  25. package/remote-pipeline-config.mjs +177 -0
  26. package/remote-pipeline-parsers.mjs +121 -0
  27. package/remote-pipeline.mjs +234 -0
  28. package/remote-policy.mjs +199 -0
  29. package/remote-preview.mjs +146 -0
  30. package/remote-projects.mjs +87 -0
  31. package/remote-protocol.mjs +3881 -0
  32. package/remote-qr.mjs +175 -0
  33. package/remote-release-plans.mjs +88 -0
  34. package/remote-releases.mjs +297 -0
  35. package/remote-run.mjs +174 -0
  36. package/remote-service.mjs +101 -0
  37. package/remote-session-list.mjs +25 -0
  38. package/remote-sessions.mjs +348 -0
  39. package/remote-steered.mjs +114 -0
  40. package/remote-steering.mjs +97 -0
  41. package/remote-store.mjs +123 -0
  42. package/remote-transport.mjs +88 -0
  43. package/worktrust.mjs +13 -6
package/remote-cli.mjs ADDED
@@ -0,0 +1,325 @@
1
+ /**
2
+ * `npx worktrust remote ...`: STEER THIS COMPUTER'S AGENTS FROM YOUR PHONE (2026-11-07). Opt-in, at this keyboard only (an
3
+ * AI agent's shell is refused by worktrust.mjs, `status` excepted). docs/remote-agents/PROTOCOL.md is the contract.
4
+ *
5
+ * remote enable [--gateway <wss://…>] [--device] pair this computer's REMOTE keys (not the measurement key) in the
6
+ * Passport app, start the service, show a pairing QR
7
+ * remote pair a new QR for a phone (five minutes, one phone, once)
8
+ * remote status [--json] what is on, paired, running, granted and installed
9
+ * remote pause | resume refuse every command for now | take them again
10
+ * remote disable [--forget] the hard off: the service removed; --forget also deletes the keys
11
+ * remote phones [confirm <id> | remove <id>] phones: pending ones are confirmed here, at the keyboard
12
+ * remote projects add <folder> | remove <id> | list the folders a phone may steer an agent in
13
+ * remote run the daemon in the foreground (Windows runs only this way)
14
+ * remote pipeline review <folder> | status read a granted folder's .worktrust/pipeline.json, show every stage
15
+ * and command, and on a typed yes let a phone start it (pins a hash)
16
+ * remote roots add <dir> [--git-init] | remove <id|dir> | list parent folders where a phone may create ONE new, empty
17
+ * project folder (project.create); --git-init runs `git init` in it
18
+ * remote preview allow|deny <port|file> <folder> | list what a phone may preview: a dev-server port on 127.0.0.1 or a
19
+ * built HTML file, per granted folder (rendered with your Chrome)
20
+ * remote codex on | off offer Codex to a phone (off by default): Codex runs the reads it
21
+ * deems safe without asking, which the person accepts here
22
+ * remote releases [released <number>] the releases on this computer; mark a ready one released (the
23
+ * phone never can: publishing stays at the desk)
24
+ */
25
+ import { basename } from "node:path";
26
+ import { hostname } from "node:os";
27
+ import { createInterface } from "node:readline/promises";
28
+ import * as P from "./remote-protocol.mjs";
29
+ import { ensureRemoteDir, isLoopbackGateway, issuerKeys, loadIdentity, loadKeys, loadPhones, loadProjects, loadSettings, newKeys, projectIdOf, random, readJson, removeFile, saveIdentity, saveKeys, savePhones, saveProjects, saveSettings, writeJson } from "./remote-store.mjs";
30
+ import { canonicalProject } from "./remote-policy.mjs";
31
+ import { IssuerMissing, PairingRefused, pairComputer } from "./remote-pairing.mjs";
32
+ import { installService, removeService, serviceState, servicePlatform } from "./remote-service.mjs";
33
+ import { qrMatrix, renderQr } from "./remote-qr.mjs";
34
+ import { webSocketAvailable } from "./remote-transport.mjs";
35
+ import { inventory } from "./remote-inventory.mjs";
36
+ import { allowCommand, parsePipelineConfig, PIPELINE_FILE } from "./remote-pipeline-config.mjs";
37
+ import { pipelineState, projectReviewHash, readProjectFile } from "./remote-pipeline.mjs";
38
+ import { openJournal } from "./remote-journal.mjs";
39
+ import { loadPreviewGrants, savePreviewGrants } from "./remote-store.mjs";
40
+ import { loadDeskMarks, loadPipelineReviews, loadRoots, remotePath, saveDeskMarks, savePipelineReviews, saveRoots } from "./remote-store.mjs";
41
+ import { checkRoot, MAX_ROOTS, rootIdOf, rootLabel } from "./remote-projects.mjs";
42
+
43
+ const fingerprintOf = (keys) => P.deviceFingerprint(keys.public);
44
+ const pretty = (code) => `${code.slice(0, 4)}-${code.slice(4)}`;
45
+ /** A question only a person at this keyboard answers: a terminal, a typed "yes"; --yes and Enter are No. */
46
+ async function askTyped(question) {
47
+ if (!process.stdin.isTTY) return false;
48
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
49
+ const answer = (await prompt.question(` ${question} Type yes to confirm: `)).trim().toLowerCase();
50
+ prompt.close();
51
+ return answer === "yes";
52
+ }
53
+
54
+ function needPaired(io) {
55
+ const keys = loadKeys(), identity = loadIdentity();
56
+ if (!keys || !identity) io.fail("this computer is not paired for remote yet: run `npx worktrust remote enable`");
57
+ return { keys, identity };
58
+ }
59
+
60
+ async function enable(io) {
61
+ if (!webSocketAvailable()) io.fail(`remote needs Node 22.4 or later for its connection (this is ${process.versions.node}); the Python package bundles one`);
62
+ const settings = loadSettings();
63
+ const gateway = io.flag("gateway") ?? process.env.WORKTRUST_REMOTE_GATEWAY ?? settings.gateway;
64
+ if (gateway && !P.isGatewayOrigin(gateway)) io.fail("--gateway is an origin: wss://host[:port], or ws://127.0.0.1:<port> for the dev relay");
65
+ io.say();
66
+ io.say(" WorkTrust remote lets your phone steer the AI agents on this computer. It will:");
67
+ io.say(" - make a REMOTE key pair for this computer (not the measurement key), approved in WorkTrust with your second factor");
68
+ io.say(" - run a small service while you are logged in, holding one outbound connection; it opens no port");
69
+ io.say(" - let a phone steer agents only in folders you grant here, and approve only edits inside them, reviewed test,");
70
+ io.say(" build and lint commands, and messages shown whole; everything else is decided at this keyboard");
71
+ io.say(" - mark every session it steers, so remote work never counts as your AI Hours");
72
+ if (!(await io.ask("Continue?"))) return;
73
+ ensureRemoteDir();
74
+ let identity = loadIdentity();
75
+ if (!identity || io.has("repair")) {
76
+ const keys = newKeys();
77
+ const pub = P.publicKeysOf(P.importSecretKeys(keys));
78
+ try {
79
+ const paired = await pairComputer({ origin: io.origin, secret: P.importSecretKeys(keys), publicKeys: pub, host: hostname(), os: io.os, device: io.has("device"), issuerKeys: issuerKeys(gateway), say: io.say, openBrowser: io.openBrowser });
80
+ saveKeys(keys);
81
+ identity = { v: 1, device_id: paired.device_id, binding: paired.binding, sub: paired.sub, origin: io.origin, paired_at: Date.now() };
82
+ saveIdentity(identity);
83
+ io.say(` ✓ Paired${paired.account ? ` for ${paired.account}` : ""}. This computer's remote key: ${P.deviceFingerprint(pub)}`);
84
+ } catch (error) {
85
+ if (error instanceof IssuerMissing || error instanceof PairingRefused) io.fail(error.message);
86
+ throw error;
87
+ }
88
+ } else io.say(` Already paired (${identity.device_id}); --repair pairs again with new keys.`);
89
+ saveSettings({ ...settings, enabled: true, paused: null, gateway: gateway ?? null, agent_path: process.env.PATH ?? null });
90
+ if (loadProjects().length === 0) io.say(" No folder is granted yet: npx worktrust remote projects add <folder>");
91
+ if (!gateway) { io.say(" No gateway is set: the production gateway is not live yet. Nothing runs until one is (--gateway)."); return; }
92
+ if (servicePlatform() === "foreground") { io.say(" Windows: there is no service; run `npx worktrust remote run` and keep that terminal open."); return; }
93
+ const runtime = await io.prepare();
94
+ const service = installService({ program: [runtime.node, ...runtime.nodeArgs, runtime.entry, "remote", "run"], path: process.env.PATH ?? "" });
95
+ io.say(service.started ? ` ✓ The service runs (${service.kind}, while you are logged in; linger stays off).` : ` ! The service file was written (${service.file}) but did not start; run \`npx worktrust remote run\` to see why.`);
96
+ if (!io.has("no-pair")) await pair(io);
97
+ }
98
+
99
+ async function pair(io) {
100
+ const { keys, identity } = needPaired(io);
101
+ const settings = loadSettings();
102
+ if (!settings.enabled || !settings.gateway) io.fail("remote is off or has no gateway: run `npx worktrust remote enable`");
103
+ const started = Date.now();
104
+ const invite = P.createPairingInvite({ gateway: settings.gateway, deviceId: identity.device_id, ed25519_pub: keys.public.ed25519_pub, x25519_pub: keys.public.x25519_pub, nowMs: started, random });
105
+ const code = P.generatePairingCode(random);
106
+ writeJson("invite.json", { ...invite, code, used: false, created_at: started });
107
+ const link = P.encodePairingInvite(invite);
108
+ io.say();
109
+ io.say(" Scan this with the WorkTrust app (or the phone's camera):");
110
+ io.say(renderQr(qrMatrix(link).modules, { color: Boolean(process.stdout.isTTY) && !process.env.NO_COLOR }));
111
+ io.say(` Link: ${link}`);
112
+ io.say(` No camera? Type this code in the app: ${pretty(code)} (then confirm the phone here with \`npx worktrust remote phones\`)`);
113
+ io.say(" The code and the QR work once, for five minutes. Ctrl+C cancels.");
114
+ const cancel = () => { removeFile("invite.json"); process.exit(130); };
115
+ process.once("SIGINT", cancel);
116
+ const before = new Set(loadPhones().pending.map((p) => p.fingerprint));
117
+ while (Date.now() < invite.e * 1000) {
118
+ await new Promise((resolve) => setTimeout(resolve, 1000));
119
+ const phones = loadPhones();
120
+ const paired = phones.confirmed.find((p) => p.how === "qr" && p.confirmed_at >= started);
121
+ if (paired) { process.off("SIGINT", cancel); io.say(` ✓ Paired: phone · ${paired.fingerprint}`); return; }
122
+ const asked = phones.pending.find((p) => !before.has(p.fingerprint));
123
+ if (asked) { process.off("SIGINT", cancel); io.say(` A phone asked by code (${asked.fingerprint}). Confirm it at this keyboard: npx worktrust remote phones confirm ${asked.fingerprint}`); return; }
124
+ }
125
+ process.off("SIGINT", cancel);
126
+ removeFile("invite.json");
127
+ io.say(" The pairing code expired. Run `npx worktrust remote pair` for a new one.");
128
+ }
129
+
130
+ async function phones(io, rest) {
131
+ const list = loadPhones();
132
+ const find = (key) => [...list.pending, ...list.confirmed].find((p) => p.fingerprint === key?.toUpperCase() || p.device_id === key);
133
+ if (rest[0] === "confirm") {
134
+ const phone = list.pending.find((p) => p === find(rest[1]));
135
+ if (!phone) io.fail("no pending phone by that fingerprint or id (`npx worktrust remote phones` lists them)");
136
+ if (!process.stdin.isTTY) io.fail("a phone is confirmed at this keyboard, in a terminal");
137
+ io.say(` Your phone should show this computer's key and its own: ${phone.fingerprint}`);
138
+ if (!(await askTyped(`Is ${phone.fingerprint} the fingerprint your phone shows?`))) { io.say(" Not confirmed."); return; }
139
+ savePhones({ ...list, pending: list.pending.filter((p) => p !== phone), confirmed: [...list.confirmed.filter((p) => p.fingerprint !== phone.fingerprint), { ...phone, how: "keyboard", confirmed_at: Date.now() }] });
140
+ io.say(` ✓ Confirmed: phone · ${phone.fingerprint}`);
141
+ return;
142
+ }
143
+ if (rest[0] === "remove") {
144
+ const phone = find(rest[1]);
145
+ if (!phone) io.fail("no phone by that fingerprint or id");
146
+ savePhones({ ...list, pending: list.pending.filter((p) => p.fingerprint !== phone.fingerprint), confirmed: list.confirmed.filter((p) => p.fingerprint !== phone.fingerprint),
147
+ removed: [...list.removed.filter((p) => p.device_id !== phone.device_id), { device_id: phone.device_id, fingerprint: phone.fingerprint, how: "keyboard", removed_at: Date.now() }].slice(-20) });
148
+ io.say(` ✓ Removed ${phone.fingerprint}: it can no longer steer this computer. Revoke it in WorkTrust too.`);
149
+ return;
150
+ }
151
+ io.say(` Confirmed phones (${list.confirmed.length}):`);
152
+ for (const p of list.confirmed) io.say(` ${p.fingerprint} ${p.device_id} (${p.how === "qr" ? "scanned the QR" : "confirmed at the keyboard"})`);
153
+ io.say(` Pending phones (${list.pending.length}):`);
154
+ for (const p of list.pending) io.say(` ${p.fingerprint} ${p.device_id} confirm: npx worktrust remote phones confirm ${p.fingerprint}`);
155
+ if (list.removed.length > 0) {
156
+ const WHY = { phone: "disconnected from the phone", revoked: "revoked in WorkTrust", keyboard: "removed here" };
157
+ io.say(` Removed phones (${list.removed.length}):`);
158
+ for (const p of list.removed) io.say(` ${p.fingerprint} ${p.device_id} (${WHY[p.how] ?? "removed"}, ${new Date(p.removed_at).toISOString().slice(0, 16).replace("T", " ")})`);
159
+ }
160
+ }
161
+
162
+ function projects(io, rest) {
163
+ const list = loadProjects();
164
+ if (rest[0] === "add") {
165
+ const { keys } = needPaired(io);
166
+ const canonical = canonicalProject(rest[1]);
167
+ if (!canonical.ok) io.fail(`not granted: ${canonical.reason}`);
168
+ const project_id = projectIdOf(keys.projectSecret, canonical.path);
169
+ if (!list.some((p) => p.project_id === project_id)) saveProjects([...list, { project_id, path: canonical.path, added_at: Date.now() }]);
170
+ io.say(` ✓ Granted: ${canonical.path}`);
171
+ return;
172
+ }
173
+ if (rest[0] === "remove") {
174
+ const canonical = canonicalProject(rest[1] ?? "");
175
+ const kept = list.filter((p) => p.project_id !== rest[1] && p.path !== rest[1] && !(canonical.ok && p.path === canonical.path));
176
+ if (kept.length === list.length) io.fail("no granted folder by that path or id");
177
+ saveProjects(kept);
178
+ io.say(" ✓ Removed.");
179
+ return;
180
+ }
181
+ io.say(` Granted folders (${list.length}):`);
182
+ for (const p of list) io.say(` ${p.path} (${basename(p.path)})`);
183
+ }
184
+
185
+ /** `remote roots …`: where a phone may create a new project folder, added here at the keyboard only. */
186
+ function roots(io, rest) {
187
+ const list = loadRoots();
188
+ if (rest[0] === "add") {
189
+ const { keys } = needPaired(io);
190
+ const root = checkRoot(rest[1] ?? "");
191
+ if (!root.ok) io.fail(`not added: ${root.reason}`);
192
+ if (list.length >= MAX_ROOTS && !list.some((r) => r.path === root.path)) io.fail(`at most ${MAX_ROOTS} roots`);
193
+ const root_id = rootIdOf(keys.projectSecret, root.path);
194
+ saveRoots([...list.filter((r) => r.root_id !== root_id), { root_id, path: root.path, git_init: io.has("git-init"), added_at: Date.now() }]);
195
+ io.say(` ✓ Root: ${root.path} (${rootLabel(root.path)}). A phone may create one new, empty folder in it per request${io.has("git-init") ? ", with git init" : ""}.`);
196
+ return;
197
+ }
198
+ if (rest[0] === "remove") {
199
+ const kept = list.filter((r) => r.root_id !== rest[1] && r.path !== rest[1] && r.path !== checkRoot(rest[1] ?? "").path);
200
+ if (kept.length === list.length) io.fail("no root by that path or id");
201
+ saveRoots(kept);
202
+ io.say(" ✓ Removed. Projects made in it stay granted: npx worktrust remote projects remove <folder>.");
203
+ return;
204
+ }
205
+ io.say(` Roots (${list.length}):`);
206
+ for (const r of list) io.say(` ${r.path} (${rootLabel(r.path)}${r.git_init ? ", git init" : ""})`);
207
+ }
208
+
209
+ /** `remote pipeline review <folder>`: the person reads every stage and command, then a typed yes pins what they read. */
210
+ async function pipeline(io, rest) {
211
+ const reviews = loadPipelineReviews();
212
+ if (rest[0] === "status" || rest[0] === undefined) {
213
+ for (const p of loadProjects()) io.say(` ${p.path} ${pipelineState(p, reviews).state}`);
214
+ return;
215
+ }
216
+ if (rest[0] !== "review") io.fail("npx worktrust remote pipeline review <folder> | status");
217
+ const canonical = canonicalProject(rest[1] ?? "");
218
+ const project = canonical.ok ? loadProjects().find((p) => p.path === canonical.path) : null;
219
+ if (!project) io.fail("that folder is not granted: npx worktrust remote projects add <folder>");
220
+ const text = readProjectFile(project.path, PIPELINE_FILE, 65_536);
221
+ if (text === null) io.fail(`no ${PIPELINE_FILE} in ${project.path}`);
222
+ let scripts = null;
223
+ try { scripts = JSON.parse(readProjectFile(project.path, "package.json", 1_048_576) ?? "null")?.scripts ?? null; } catch { scripts = null; }
224
+ const parsed = parsePipelineConfig(text, scripts);
225
+ if (!parsed.ok) io.fail(`${PIPELINE_FILE}: ${parsed.detail}`);
226
+ io.say(` ${project.path}: ${parsed.config.stages.length} stages, run one after another${parsed.config.run_after_tasks ? " once a release's tasks are done" : " when you start them"}`);
227
+ for (const s of parsed.config.stages) {
228
+ if (s.desk) { io.say(` ${s.id} ${s.label} (${s.kind}): at your desk, never run from a phone`); continue; }
229
+ const argv = allowCommand(s.run, scripts);
230
+ io.say(` ${s.id} ${s.label} (${s.kind}, ${s.parser}): ${[argv.file, ...argv.args].join(" ")}${argv.form === "script" ? ` → ${scripts[argv.script]}` : ""}`);
231
+ if (argv.form === "script") for (const hook of [`pre${argv.script}`, `post${argv.script}`]) if (typeof scripts[hook] === "string") io.say(` and first/after it, ${hook} → ${scripts[hook]}`);
232
+ }
233
+ if (readProjectFile(project.path, ".npmrc", 65_536) !== null) io.say(" The project has an .npmrc: it is part of what you review (script-shell, node-options).");
234
+ io.say(" What you review: this file, every package.json script, the .npmrc and the files the node stages run. A change to any needs a new review.");
235
+ if (parsed.config.path_prepend.length > 0) io.say(` PATH first: ${parsed.config.path_prepend.join(", ")}`);
236
+ if (!(await askTyped(" A phone may start these stages on this computer, as you. Type yes to allow: "))) io.fail("not reviewed");
237
+ savePipelineReviews({ ...reviews, [project.project_id]: { sha256: projectReviewHash(project), reviewed_at: Date.now(), stages: parsed.config.stages.length } });
238
+ io.say(" ✓ Reviewed. A change to the file or to a script it names needs a new review.");
239
+ }
240
+
241
+ /** `remote releases [released <n>]`: read from the journal; the mark is a file the daemon reads, never a phone's. */
242
+ function releasesCommand(io, rest) {
243
+ const list = openJournal(remotePath("journal.jsonl")).releases().sort((a, b) => b.number - a.number);
244
+ if (rest[0] === "released") {
245
+ const n = Number(rest[1]);
246
+ const r = list.find((x) => x.number === n);
247
+ if (!r) io.fail("no release by that number on this computer");
248
+ if (r.state !== "ready") io.fail(`release ${n} is ${r.state}; only a ready release (its tasks and its pipeline passed) can be marked released`);
249
+ saveDeskMarks([...loadDeskMarks(), n]);
250
+ io.say(` ✓ Release ${n} is marked released; the running daemon tells the phone.`);
251
+ return;
252
+ }
253
+ io.say(` Releases (${list.length}):`);
254
+ for (const r of list) io.say(` ${r.number} ${r.state.padEnd(11)} ${r.tasks.filter((t) => t.state === "done").length}/${r.tasks.length} tasks ${r.title}`);
255
+ }
256
+
257
+ function status(io) {
258
+ const settings = loadSettings(), identity = loadIdentity(), keys = identity ? loadKeys() : null, phonesList = loadPhones(), service = serviceState();
259
+ const agents = inventory({ env: { ...process.env, PATH: settings.agent_path ?? process.env.PATH } }).reports.filter((r) => r.installed);
260
+ const summary = { enabled: settings.enabled, paused: settings.paused, paired: Boolean(identity), device_id: identity?.device_id ?? null, fingerprint: keys ? fingerprintOf(keys) : null,
261
+ gateway: settings.gateway, service, node_websocket: webSocketAvailable(), phones: { confirmed: phonesList.confirmed.length, pending: phonesList.pending.length }, projects: loadProjects().length,
262
+ agents: agents.map((a) => ({ adapter: a.adapter, version: a.version, adapter_ready: a.capabilities.start, models: a.models === null ? "not listed" : a.models.length })), invite_open: Boolean(readJson("invite.json")?.used === false) };
263
+ if (io.has("json")) { io.say(JSON.stringify(summary, null, 2)); return; }
264
+ io.say(` Remote: ${settings.enabled ? (settings.paused ? `paused (${settings.paused === "desk" ? "here" : "from a phone"})` : "on") : "off"}`);
265
+ io.say(` Paired: ${identity ? `${identity.device_id} · key ${summary.fingerprint}` : "no"}`);
266
+ io.say(` Gateway: ${settings.gateway ?? "none set"}${settings.gateway && isLoopbackGateway(settings.gateway) ? " (this computer: dev relay)" : ""}`);
267
+ io.say(` Service: ${service.kind === "foreground" ? "none on this system: run `npx worktrust remote run`" : `${service.installed ? "installed" : "not installed"}, ${service.running ? "running" : "not running"}`}`);
268
+ io.say(` Phones: ${summary.phones.confirmed} confirmed, ${summary.phones.pending} pending · Folders granted: ${summary.projects}`);
269
+ for (const a of summary.agents) io.say(` Agent: ${a.adapter} ${a.version ?? ""} · ${a.adapter_ready ? "remote adapter ready" : "installed, no adapter yet"} · models: ${a.models}`);
270
+ }
271
+
272
+ export async function remoteCommand(args, io) {
273
+ const [sub = "help", ...rest] = args;
274
+ if (sub === "enable") return enable(io);
275
+ if (sub === "pair") return pair(io);
276
+ if (sub === "status") return status(io);
277
+ if (sub === "pause" || sub === "resume") { const s = loadSettings(); saveSettings({ ...s, paused: sub === "pause" ? "desk" : null }); io.say(sub === "pause" ? " Paused: every command from a phone is refused until `npx worktrust remote resume`." : " Resumed."); return; }
278
+ if (sub === "disable") {
279
+ const s = loadSettings();
280
+ saveSettings({ ...s, enabled: false, paused: null });
281
+ io.say(` Off. The service is removed (${removeService()}); the daemon stops by itself within seconds.`);
282
+ if (io.has("forget")) { for (const f of ["remote-keys.json", "identity.json", "channels.json", "phones.json", "invite.json", "journal.jsonl", "projects.json", "pipelines.json", "released.json", "roots.json", "previews.json"]) removeFile(f); io.say(" The remote keys, phones, folders and journal are deleted. The steered-session ledger stays, so earlier remote work stays out of your AI Hours."); }
283
+ return;
284
+ }
285
+ if (sub === "phones") return phones(io, rest);
286
+ if (sub === "projects") return projects(io, rest);
287
+ if (sub === "run") return (await import("./remote-run.mjs")).runDaemon({ say: io.say });
288
+ if (sub === "pipeline") return pipeline(io, rest);
289
+ if (sub === "roots") return roots(io, rest);
290
+ if (sub === "preview") {
291
+ const grants = loadPreviewGrants();
292
+ if (rest[0] === "allow" || rest[0] === "deny") {
293
+ const canonical = canonicalProject(rest[2] ?? process.cwd());
294
+ const project = canonical.ok ? loadProjects().find((p) => p.path === canonical.path) : null;
295
+ if (!project) io.fail("name a granted folder: npx worktrust remote preview allow <port|file> <folder>");
296
+ const port = /^\d{1,5}$/.test(rest[1] ?? "") ? Number(rest[1]) : null;
297
+ const file = port === null && /^(?!\/)(?!.*\.\.)[A-Za-z0-9._/-]+\.html?$/.test(rest[1] ?? "") ? rest[1] : null;
298
+ if ((port === null || port < 1 || port > 65_535) && file === null) io.fail("a port (1-65535) or an .html file inside the folder");
299
+ const g = grants[project.project_id] ?? { ports: [], files: [] };
300
+ const next = rest[0] === "allow"
301
+ ? { ports: port ? [...new Set([...g.ports, port])].slice(0, 20) : g.ports, files: file ? [...new Set([...g.files, file])].slice(0, 50) : g.files }
302
+ : { ports: g.ports.filter((x) => x !== port), files: g.files.filter((x) => x !== file) };
303
+ savePreviewGrants({ ...grants, [project.project_id]: next });
304
+ io.say(` ✓ ${rest[0] === "allow" ? "A phone may preview" : "No longer previewed:"} ${port ? `http://127.0.0.1:${port}` : file} in ${project.path}.`);
305
+ return;
306
+ }
307
+ for (const p of loadProjects()) { const g = grants[p.project_id]; if (g) io.say(` ${p.path}: ports ${g.ports.join(", ") || "none"} · files ${g.files.join(", ") || "none"}`); }
308
+ return;
309
+ }
310
+ if (sub === "codex") {
311
+ const s = loadSettings();
312
+ if (rest[0] === "off") { saveSettings({ ...s, codex: false }); io.say(" Codex is no longer offered to a phone."); return; }
313
+ if (rest[0] !== "on") { io.say(` Codex is ${s.codex ? "on" : "off"} for remote. npx worktrust remote codex on | off`); return; }
314
+ io.say(" Codex from a phone: it asks before every command it does not trust and every edit, and the computer classifies those.");
315
+ io.say(" But it runs the reads it deems safe (cat, rg, head, sed -n) WITHOUT asking. This computer ends a turn as soon as a");
316
+ io.say(" command reads a secret path (keys, .env, credentials), but by then the read has started. MCP servers a Codex plugin");
317
+ io.say(" brings still start. Claude Code has deny rules for those reads; Codex has none on this version.");
318
+ if (!(await askTyped(" Offer Codex to your phones anyway? Type yes: "))) io.fail("Codex stays off");
319
+ saveSettings({ ...s, codex: true });
320
+ io.say(" ✓ Codex is offered to your phones. npx worktrust remote codex off takes it back.");
321
+ return;
322
+ }
323
+ if (sub === "releases") return releasesCommand(io, rest);
324
+ io.say(" npx worktrust remote enable | pair | status | pause | resume | disable [--forget] | phones [confirm|remove <id>] | projects add|remove|list | run | pipeline review <folder>|status | roots add|remove|list | preview allow|deny|list | codex on|off | releases [released <n>]");
325
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * AT MOST ONE EVENT PER KEY PER WINDOW (moved from remote-sessions.mjs, 2026-11-07, unchanged). Used for tokens, a running
3
+ * subagent's counts, a pipeline's live counts and the live feed.
4
+ */
5
+ import * as P from "./remote-protocol.mjs";
6
+
7
+ /**
8
+ * AT MOST ONE EVENT PER KEY PER WINDOW (docs/remote-agents/PROTOCOL.md, "Progress the phone can trust"). `offer` sends at
9
+ * once when the key's window has passed, else keeps the latest and sends it when the window ends; `now` sends at once and
10
+ * drops what waited (a turn's final total, a subagent's end); `flush` sends everything that waits (before a turn's end).
11
+ */
12
+ export function createCoalescer({ now, windowMs = P.USAGE_MIN_INTERVAL_MS, setTimer = setTimeout, clearTimer = clearTimeout }) {
13
+ const keys = new Map(); // key -> { last, pending, timer }
14
+ const fire = (key) => {
15
+ const k = keys.get(key);
16
+ if (!k) return;
17
+ k.timer = null;
18
+ if (!k.pending) return;
19
+ const go = k.pending;
20
+ k.pending = null; k.last = now();
21
+ go();
22
+ };
23
+ return {
24
+ offer(key, go) {
25
+ const k = keys.get(key) ?? { last: -Infinity, pending: null, timer: null };
26
+ keys.set(key, k);
27
+ if (k.timer === null && now() - k.last >= windowMs) { k.last = now(); go(); return; }
28
+ k.pending = go;
29
+ if (k.timer === null) { k.timer = setTimer(() => fire(key), Math.max(0, k.last + windowMs - now())); k.timer?.unref?.(); }
30
+ },
31
+ now(key, go) {
32
+ const k = keys.get(key);
33
+ if (k?.timer) clearTimer(k.timer);
34
+ keys.set(key, { last: now(), pending: null, timer: null });
35
+ go();
36
+ },
37
+ flush() { for (const [key, k] of keys) { if (k.timer) clearTimer(k.timer); fire(key); } },
38
+ waiting: () => [...keys.values()].filter((k) => k.pending).length,
39
+ };
40
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * CODEX'S APP-SERVER STREAM, MAPPED TO THE PROTOCOL (2026-11-07; owner: "for Codex there must be specific steering").
3
+ * Pure: one JSON-RPC notification in, the protocol's events out. Read from Codex 0.154.0 on this machine
4
+ * (`codex app-server generate-json-schema`, and a recorded session: scripts/fixtures/remote/codex-0.154.0-app-server.jsonl).
5
+ *
6
+ * thread/started the agent's own session id (the thread id: what the steered ledger names)
7
+ * turn/started a turn began (acceptance; started_at on the computer's clock)
8
+ * item/started commandExecution agent.step_started { kind: command | test, label: the command }
9
+ * fileChange agent.step_started { kind: edit, label: the paths }
10
+ * mcpToolCall, dynamicToolCall, webSearch, imageView agent.step_started { kind: tool | search }
11
+ * userMessage a message entered the turn: the first is the turn's prompt, any later one a
12
+ * live steer that landed (`landed` counts them)
13
+ * item/completed agent.step_completed { ok | failed }; an agentMessage keeps the turn's answer
14
+ * item/agentMessage/delta agent.output_delta { assistant }
15
+ * turn/plan/updated agent.plan, item ids stable by the step's words
16
+ * thread/tokenUsage/updated agent.usage: the turn's own counts (the thread total minus its total when the
17
+ * turn began) and the thread's; input excludes the cached part
18
+ * turn/completed completed agent.completed with the answer; interrupted: agent.stopped; failed: agent.failed
19
+ * Anything else is counted and sends nothing. Words are cut to the protocol's sizes.
20
+ */
21
+ import { isAbsolute, relative, resolve } from "node:path";
22
+ import * as P from "./remote-protocol.mjs";
23
+
24
+ const cut = (text, max) => (typeof text === "string" ? (text.length > max ? text.slice(0, max) : text) : "");
25
+ const TEST = /(^|\s)(pnpm|npm|yarn|bun)\s+(run\s+)?test\b|(^|\s)(pytest|vitest|jest|go\s+test|cargo\s+test|node\s+--test)\b/;
26
+ const STEP_KIND = { commandExecution: "command", fileChange: "edit", mcpToolCall: "tool", dynamicToolCall: "tool", webSearch: "search", imageView: "read" };
27
+ const PLAN_STATE = { pending: "pending", inProgress: "in_progress", completed: "completed" };
28
+
29
+ export const emptyCodexState = () => ({ threadId: null, turnId: null, turnStartedAt: null, items: {}, started: 0, completed: 0, offset: 0, answer: null, userMessages: 0, landed: 0,
30
+ planIds: {}, planVersion: 0, plan: null, totalAtTurn: null, total: null, ignored: 0 });
31
+
32
+ const commandOf = (item) => cut(unwrapShell(item.command ?? ""), 500) || "command";
33
+ function labelOf(item) {
34
+ if (item.type === "commandExecution") return commandOf(item);
35
+ if (item.type === "fileChange") return cut((item.changes ?? []).map((c) => c?.path).filter(Boolean).join(", "), 500) || "file change";
36
+ if (item.type === "mcpToolCall") return cut(`${item.server ?? "mcp"}.${item.tool ?? "tool"}`, 500);
37
+ if (item.type === "webSearch") return cut(item.query ?? "web search", 500);
38
+ return cut(item.type, 500);
39
+ }
40
+
41
+ const tokens = (t) => {
42
+ if (!t || typeof t !== "object") return P.NO_TOKENS;
43
+ const n = (v) => (Number.isSafeInteger(v) && v >= 0 ? v : null);
44
+ const input = n(t.inputTokens), cached = n(t.cachedInputTokens);
45
+ return { input: input !== null && cached !== null ? Math.max(0, input - cached) : null, output: n(t.outputTokens), cache_read: cached, cache_creation: n(t.cacheWriteInputTokens ?? 0) };
46
+ };
47
+ const minus = (a, b) => Object.fromEntries(P.TOKEN_FIELDS.map((f) => [f, a[f] === null || b?.[f] === null || b?.[f] === undefined ? (b ? null : a[f]) : Math.max(0, a[f] - b[f])]));
48
+ const steps = (s) => ({ kind: "steps", started: s.started, completed: s.completed });
49
+
50
+ /** One notification → { state, events, turn: "started" | "ended" | null, sessionRef? }. `mint(prefix)` makes ids. */
51
+ export function mapCodexMessage(state, msg, mint, now) {
52
+ const s = { ...state, items: { ...state.items }, planIds: { ...state.planIds } };
53
+ const m = msg?.method, p = msg?.params ?? {};
54
+ const events = [];
55
+ if (m === "thread/started") { s.threadId = typeof p.thread?.id === "string" ? p.thread.id : s.threadId; return { state: s, events, turn: null, sessionRef: s.threadId }; }
56
+ if (m === "turn/started") {
57
+ Object.assign(s, { turnId: p.turn?.id ?? null, turnStartedAt: now, items: {}, started: 0, completed: 0, offset: 0, answer: null, userMessages: 0, landed: 0, totalAtTurn: s.total });
58
+ return { state: s, events, turn: "started" };
59
+ }
60
+ if (m === "item/started" && p.item) {
61
+ if (p.item.type === "userMessage") { s.userMessages += 1; if (s.userMessages > 1) s.landed += 1; return { state: s, events, turn: null, landed: s.userMessages > 1 }; }
62
+ const kind = STEP_KIND[p.item.type];
63
+ if (!kind) { s.ignored += 1; return { state: s, events, turn: null }; }
64
+ const step_id = mint("stp");
65
+ s.items[p.item.id] = { step_id, at: now };
66
+ s.started += 1;
67
+ const label = labelOf(p.item);
68
+ events.push({ type: "agent.step_started", body: { step_id, label, kind: kind === "command" && TEST.test(label) ? "test" : kind, progress: steps(s) } });
69
+ return { state: s, events, turn: null };
70
+ }
71
+ if (m === "item/completed" && p.item) {
72
+ if (p.item.type === "agentMessage" && typeof p.item.text === "string") s.answer = p.item.text;
73
+ const open = s.items[p.item.id];
74
+ if (!open) return { state: s, events, turn: null };
75
+ delete s.items[p.item.id];
76
+ s.completed += 1;
77
+ const failed = p.item.status === "failed" || p.item.status === "declined" || (Number.isSafeInteger(p.item.exitCode) && p.item.exitCode !== 0);
78
+ events.push({ type: "agent.step_completed", body: { step_id: open.step_id, outcome: failed ? "failed" : "ok", progress: steps(s), duration_ms: Math.max(0, now - open.at) } });
79
+ return { state: s, events, turn: null };
80
+ }
81
+ if (m === "item/agentMessage/delta" && typeof p.delta === "string" && p.delta.length > 0) {
82
+ const text = cut(p.delta, 65_536);
83
+ events.push({ type: "agent.output_delta", body: { stream: "assistant", offset: s.offset, text } });
84
+ s.offset += text.length;
85
+ return { state: s, events, turn: null };
86
+ }
87
+ if (m === "turn/plan/updated" && Array.isArray(p.plan)) {
88
+ const items = p.plan.slice(0, P.MAX_PLAN_ITEMS).filter((x) => typeof x?.step === "string" && x.step.trim()).map((x) => {
89
+ const label = cut(x.step.trim(), P.MAX_PLAN_LABEL);
90
+ s.planIds[label] ??= mint("pli");
91
+ const st = PLAN_STATE[x.status] ?? "pending";
92
+ return { item_id: s.planIds[label], label, state: st, active: st === "in_progress" ? label : null };
93
+ }).filter((x, i, all) => all.findIndex((y) => y.item_id === x.item_id) === i);
94
+ const plan = { plan_version: s.planVersion + 1, change: "created", items, items_cut: p.plan.length > P.MAX_PLAN_ITEMS };
95
+ plan.change = P.planChange(s.plan, plan);
96
+ s.plan = plan; s.planVersion = plan.plan_version;
97
+ events.push({ type: "agent.plan", body: plan });
98
+ return { state: s, events, turn: null };
99
+ }
100
+ if (m === "thread/tokenUsage/updated" && p.tokenUsage?.total) {
101
+ s.total = tokens(p.tokenUsage.total);
102
+ events.push({ type: "agent.usage", body: { model: null, turn: minus(s.total, s.totalAtTurn), turn_final: false, session: s.total } });
103
+ return { state: s, events, turn: null };
104
+ }
105
+ if (m === "turn/completed") {
106
+ const status = p.turn?.status;
107
+ const time = s.turnStartedAt !== null ? { started_at: s.turnStartedAt, duration_ms: Math.max(0, now - s.turnStartedAt) } : {};
108
+ if (s.total) events.push({ type: "agent.usage", body: { model: null, turn: minus(s.total, s.totalAtTurn), turn_final: true, session: s.total } });
109
+ if (status === "completed") {
110
+ const answer = s.answer ?? p.turn?.items?.findLast?.((i) => i.type === "agentMessage")?.text ?? null;
111
+ events.push({ type: "agent.completed", body: { summary: answer ? cut(answer, 4000) : null, progress: steps(s), result: { answer: answer ? cut(answer, P.MAX_ANSWER_CHARS) : null, answer_cut: (answer?.length ?? 0) > P.MAX_ANSWER_CHARS, source: "none", files: [], files_cut: false, tests: [] }, ...time } });
112
+ } else if (status === "interrupted") events.push({ type: "agent.stopped", body: {} });
113
+ else events.push({ type: "agent.failed", body: { reason: "adapter_error", message: p.turn?.error?.message ? cut(String(p.turn.error.message), 4000) : null, ...time } });
114
+ Object.assign(s, { turnId: null, turnStartedAt: null, items: {} });
115
+ return { state: s, events, turn: "ended" };
116
+ }
117
+ s.ignored += 1;
118
+ return { state: s, events, turn: null };
119
+ }
120
+
121
+ const inside = (root, path) => { const rel = relative(root, path); return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel)); };
122
+ /** A shell wrapper Codex puts around a command, removed only when it is exactly that wrapper. */
123
+ export const unwrapShell = (command) => String(command).replace(/^\/bin\/(zsh|bash|sh) -lc '([^']*)'$/s, "$2");
124
+ /** Every path a file change touches: its own and, for a move, its destination (review 2026-11-07, P1-2). */
125
+ export const changePaths = (changes) => (Array.isArray(changes) ? changes : []).flatMap((c) => [c?.path, c?.kind?.move_path, c?.move_path]).filter((p) => typeof p === "string" && p.length > 0);
126
+
127
+ /**
128
+ * A Codex approval request → the tool calls the computer's policy classifies (remote-policy.mjs), every one of which must
129
+ * be approvable, or null (declined here). Review 2026-11-07: the WHOLE command Codex will run (never its `commandActions`
130
+ * summary, which drops a leading `cd … &&`), refused when it runs outside the project (`cwd`); a file change by every path
131
+ * it touches, a move's destination included; a request that asks to widen the writable root (`grantRoot`) is refused.
132
+ */
133
+ export function codexApprovalAsTool(method, params, fileChanges, projectPath) {
134
+ const cwd = typeof params?.cwd === "string" ? params.cwd : null;
135
+ if (cwd !== null && (typeof projectPath !== "string" || !inside(projectPath, resolve(projectPath, cwd)))) return null;
136
+ if (method === "item/commandExecution/requestApproval" || method === "execCommandApproval") {
137
+ const command = Array.isArray(params?.command) ? params.command.join(" ") : params?.command;
138
+ return typeof command === "string" && command.trim() ? [{ tool: "Bash", input: { command: unwrapShell(command) } }] : null;
139
+ }
140
+ if (method === "item/fileChange/requestApproval" || method === "applyPatchApproval") {
141
+ if (params?.grantRoot !== undefined && params?.grantRoot !== null) return null;
142
+ const legacy = Object.entries(params?.fileChanges ?? {}).flatMap(([path, change]) => [path, change?.move_path].filter((p) => typeof p === "string"));
143
+ const paths = [...new Set([...(fileChanges?.[params?.itemId] ?? []), ...legacy])];
144
+ return paths.length > 0 ? paths.map((file_path) => ({ tool: "Edit", input: { file_path } })) : null;
145
+ }
146
+ return null; // permissions, elicitations, anything new: not classifiable here, so denied
147
+ }
148
+
149
+ /** The answer Codex takes for a refusal: `decline` where the request lists it, else `cancel` (which also ends the turn). */
150
+ export function refusalFor(params) {
151
+ const offered = Array.isArray(params?.availableDecisions) ? params.availableDecisions.filter((d) => typeof d === "string") : null;
152
+ return offered === null || offered.includes("decline") ? "decline" : "cancel";
153
+ }