worktrust 0.10.38 → 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.
@@ -0,0 +1,205 @@
1
+ /**
2
+ * THE REMOTE DAEMON'S CORE (2026-11-07, docs/remote-agents/PROTOCOL.md). One per computer, `worktrust remote run`.
3
+ *
4
+ * It answers phones' handshakes (a scanned invite confirms the phone; otherwise a confirmed phone is required and a new
5
+ * one is listed as pending for `worktrust remote phones`), opens their commands, and runs the agents. A command is taken in
6
+ * this order, and scripts/check-remote-cli.mjs refuses a change to it:
7
+ * 1. validate the outer shape; 2. look it up in the journal WITHOUT admitting it (a duplicate is answered from the
8
+ * journal: its receipts again, nothing run again; another command under the same id is a conflict, dropped);
9
+ * 3. open it (signature, time, replay window, seal, payload) - a failure never touches the journal;
10
+ * 4. admit it to the journal, flushed to disk; 5. command.device_received; 6. only then dispatch it to an agent.
11
+ * Events are journaled with their event_seq, then sealed once per open channel. Logs carry ids and types, never a body.
12
+ */
13
+ import { basename } from "node:path";
14
+ import * as P from "./remote-protocol.mjs";
15
+ import { confirmedFingerprints, controllerKeys, loadChannels, loadPhones, loadProjects, loadRoots, loadSettings, readJson, saveChannels, savePhones, saveProjects, saveSettings, writeJson } from "./remote-store.mjs";
16
+ import { createProject, rootLabel, worktreeMain } from "./remote-projects.mjs";
17
+
18
+ // What a paused computer still answers: reading, configuring, disconnecting, and taking work away (a pipeline's cancel).
19
+ const DEVICE_COMMANDS = new Set(["inventory.get", "device.configure", "status.get", "pairing.revoke", "release.list", "pipeline.cancel"]);
20
+ const KEEP_REMOVED = 20;
21
+ const MAX_PENDING_PHONES = 10;
22
+
23
+ export function createDaemonCore(o) {
24
+ // o: { local, issuerKeys, journal, now, random, send(frame), inventory(refresh), log(kind, fields), sessions?, approvals? }
25
+ const channels = new Map(loadChannels().map((c) => [c.channel_id, c]));
26
+ const confirmed = () => confirmedFingerprints(loadPhones());
27
+ const self = o.local.claims.device_id;
28
+ const persist = () => saveChannels([...channels.values()]);
29
+ let sessions = null, approvals = o.approvals ?? null, releases = null;
30
+
31
+ function sealAll(record) {
32
+ for (const [id, channel] of channels) {
33
+ if (!confirmed().has(channel.peer_fingerprint)) { channels.delete(id); continue; } // a revoked phone hears nothing
34
+ const draft = { protocol_version: channel.protocol_version, session_id: record.session_id, device_id: self, event_seq: record.event_seq, type: record.type, occurred_at: record.occurred_at, command_id: record.command_id, notify: record.notify };
35
+ const sealed = P.sealEvent(channel, draft, record.body, o.random);
36
+ if (!sealed.ok) { o.log("seal_refused", { type: record.type, code: sealed.code }); continue; }
37
+ channels.set(id, sealed.value.channel);
38
+ o.send({ frame: "event", envelope: sealed.value.envelope });
39
+ }
40
+ persist();
41
+ }
42
+
43
+ function emit(sessionId, type, body, commandId = null, notify = "none") {
44
+ let shaped = P.validateEventBody(type, body);
45
+ if (!shaped.ok && type === "agent.completed" && body.result) {
46
+ // A result over its caps keeps the reply and names the files; the diffs are said to be cut.
47
+ const files = body.result.files.map((f) => ({ ...f, diff: null, diff_cut: f.diff !== null || f.diff_cut }));
48
+ body = { ...body, result: { ...body.result, files } };
49
+ shaped = P.validateEventBody(type, body);
50
+ }
51
+ if (!shaped.ok) { o.log("event_refused", { type, detail: shaped.code }); return; }
52
+ const record = { session_id: sessionId, event_seq: o.journal.nextSeq(sessionId), type, occurred_at: o.now(), command_id: commandId, notify, body };
53
+ o.journal.recordEvent(record);
54
+ sealAll(record);
55
+ }
56
+
57
+ /** Re-seal what the journal holds for a session after `after` (session.attach): same event_seq, so the phone dedups. */
58
+ const replay = (sessionId, after) => { for (const record of o.journal.eventsAfter(sessionId, after)) sealAll(record); };
59
+
60
+ function inventoryBody(refresh) {
61
+ const settings = loadSettings();
62
+ return {
63
+ remote_enabled: settings.enabled && settings.paused === null,
64
+ default_adapter: settings.default_adapter ?? null,
65
+ default_model: settings.default_model ?? null,
66
+ adapters: o.inventory(refresh).reports,
67
+ // A worktree names its main repository (`main`), only when it is one: a phone groups its sessions under that project.
68
+ projects: loadProjects().slice(0, 30).map((p) => {
69
+ const main = worktreeMain(p.path);
70
+ return { project_id: p.project_id, label: (basename(p.path) || p.path).slice(0, 256), path: p.path.slice(0, 4096), last_used_at: null, root_id: p.root_id ?? null, ...(main ? { main: main.slice(0, 4096) } : {}) };
71
+ }),
72
+ roots: loadRoots().slice(0, 20).map((r) => ({ root_id: r.root_id, label: rootLabel(r.path), git_init: r.git_init === true })),
73
+ // Every session this computer knows, live or in the journal, newest activity first, with its name and its release task.
74
+ sessions: (sessions?.listAll?.() ?? sessions?.list() ?? []).map((s) => ({ ...s, ...(releases?.ownerOf(s.session_id) ?? {}) })).slice(0, 100),
75
+ };
76
+ }
77
+
78
+ function resendReceipts(entry) {
79
+ const meta = o.journal.meta(entry.command_id) ?? {};
80
+ emit(meta.session_id ?? null, "command.device_received", {}, entry.command_id);
81
+ if (entry.state === "REJECTED" || entry.state === "EXPIRED") emit(meta.session_id ?? null, "command.rejected", { reason: meta.reason ?? (entry.state === "EXPIRED" ? "expired" : "conflict") }, entry.command_id);
82
+ else if (P.DELIVERY_RANK[entry.state] >= P.DELIVERY_RANK.AGENT_ACCEPTED) emit(meta.session_id ?? null, "command.agent_accepted", {}, entry.command_id);
83
+ }
84
+
85
+ function reject(env, reason) {
86
+ o.journal.advance(env.command_id, { kind: "device_rejected", expired: reason === "expired" }, o.now(), reason);
87
+ emit(env.session_id, "command.rejected", { reason }, env.command_id);
88
+ }
89
+
90
+ async function configure(payload) {
91
+ const settings = loadSettings();
92
+ if (payload.remote_enabled === true && settings.paused === "desk") return "remote_paused"; // the desk's pause is the person's, at the keyboard
93
+ const next = { ...settings };
94
+ if (payload.remote_enabled !== undefined) next.paused = payload.remote_enabled ? null : settings.paused ?? "phone";
95
+ if (payload.default_adapter !== undefined) next.default_adapter = payload.default_adapter;
96
+ if (payload.default_model !== undefined) {
97
+ const report = o.inventory(false).reports.find((r) => r.adapter === (next.default_adapter ?? "claude-code"));
98
+ if (payload.default_model !== null && !(report && P.isModelReported(report, payload.default_model))) return "unknown_model";
99
+ next.default_model = payload.default_model;
100
+ }
101
+ saveSettings(next);
102
+ emit(null, "device.inventory", inventoryBody(false));
103
+ return "taken";
104
+ }
105
+
106
+ /**
107
+ * A phone goes (owner, 2026-11-07): it disconnected itself (its sealed pairing.revoke, or the gateway's device.revoked
108
+ * after it), or the Passport revoked it. It leaves the confirmed and pending lists for `removed`, which `remote phones`
109
+ * shows, and every channel with it closes now. Dropping a phone only ever takes power away, so the relay's word suffices.
110
+ */
111
+ function dropPhone(deviceId, how) {
112
+ const phones = loadPhones();
113
+ const gone = [...phones.confirmed, ...phones.pending].find((p) => p.device_id === deviceId);
114
+ for (const [id, c] of channels) if (c.peer_device_id === deviceId) channels.delete(id);
115
+ persist();
116
+ if (!gone) return false;
117
+ savePhones({ ...phones, confirmed: phones.confirmed.filter((p) => p.device_id !== deviceId), pending: phones.pending.filter((p) => p.device_id !== deviceId),
118
+ removed: [...(phones.removed ?? []).filter((p) => p.device_id !== deviceId), { device_id: deviceId, fingerprint: gone.fingerprint, how, removed_at: o.now() }].slice(-KEEP_REMOVED) });
119
+ o.log("phone_removed", { how });
120
+ return true;
121
+ }
122
+
123
+ async function dispatch(env, payload) {
124
+ const settings = loadSettings();
125
+ if (!settings.enabled) return "remote_paused";
126
+ if (settings.paused !== null && !DEVICE_COMMANDS.has(env.type)) return "remote_paused";
127
+ if (env.type === "inventory.get") { emit(null, "device.inventory", inventoryBody(payload.refresh_models)); return "taken"; }
128
+ if (env.type === "device.configure") return configure(payload);
129
+ if (env.type === "status.get" && payload.scope === "device") { emit(null, "device.inventory", inventoryBody(false)); return "taken"; }
130
+ if (env.type === "pairing.revoke") return "taken";
131
+ if (env.type === "project.create") {
132
+ const made = createProject({ name: payload.name, root: loadRoots().find((r) => r.root_id === payload.root_id), projectSecret: o.projectSecret, projects: loadProjects, saveProjects, now: o.now });
133
+ if (!made.ok) return made.reason;
134
+ emit(null, "project.created", { ...made.project, git: made.git }, env.command_id);
135
+ emit(null, "device.inventory", inventoryBody(false));
136
+ o.log("project_created", { git: made.git });
137
+ return "taken";
138
+ }
139
+ if (env.type === "approval.decision") return approvals.decide(payload.decision_token).ok ? "taken" : "approval_invalid";
140
+ if (P.RELEASE_COMMANDS.has(env.type)) return releases ? releases.handle(env, payload) : "unsupported"; // remote-releases.mjs
141
+ if (env.type === "attachment.put" || env.type === "attachment.clear") return o.attachments ? o.attachments.handle(env, payload) : "unsupported"; // remote-attachments.mjs
142
+ if (env.type === "preview.targets" || env.type === "preview.render") return o.preview ? o.preview.handle(env, payload) : "unsupported"; // remote-preview.mjs
143
+ return sessions.handle(env, payload);
144
+ }
145
+
146
+ /** The order of this function is the at-most-once rule (see the header). */
147
+ async function receiveCommand(envelope) {
148
+ const shaped = P.validateCommandEnvelope(envelope);
149
+ if (!shaped.ok) return o.log("command_dropped", { code: shaped.code });
150
+ const channel = channels.get(envelope.payload_ciphertext.channel_id);
151
+ if (!channel) return o.log("command_dropped", { code: "wrong_channel" });
152
+ if (!confirmed().has(channel.peer_fingerprint)) { channels.delete(channel.channel_id); persist(); return o.log("command_dropped", { code: "not_confirmed" }); }
153
+ const input = { command_id: envelope.command_id, idempotency_key: envelope.idempotency_key, sender_device_id: envelope.sender_device_id, digest: P.envelopeDigest(envelope) };
154
+ const found = o.journal.find(input);
155
+ if (found === "conflict") return o.log("command_dropped", { code: "conflict", command_id: envelope.command_id });
156
+ if (found !== "unknown") return resendReceipts(found.duplicate);
157
+ const opened = P.openCommand(channel, envelope, o.now());
158
+ if (!opened.ok && opened.code !== "expired") return o.log("command_dropped", { code: opened.code, command_id: envelope.command_id });
159
+ if (opened.ok) { channels.set(channel.channel_id, opened.value.channel); persist(); }
160
+ const admitted = o.journal.admit(input, { type: envelope.type, session_id: envelope.session_id, now: o.now() });
161
+ if (admitted.verdict !== "new") return resendReceipts(admitted.entry);
162
+ emit(envelope.session_id, "command.device_received", {}, envelope.command_id);
163
+ if (!opened.ok) return reject(envelope, "expired"); // authentic (the signature verified first) but late
164
+ const outcome = await dispatch(opened.value.envelope, opened.value.payload);
165
+ if (outcome === "taken") { o.journal.advance(envelope.command_id, { kind: "agent_accepted" }, o.now()); emit(envelope.session_id, "command.agent_accepted", {}, envelope.command_id); }
166
+ else if (outcome !== null) reject(envelope, outcome);
167
+ if (outcome === "taken" && envelope.type === "pairing.revoke") dropPhone(envelope.sender_device_id, "phone");
168
+ }
169
+
170
+ function receiveHello(hello) {
171
+ const inspected = P.inspectHello(hello, o.local, { issuerKeys: o.issuerKeys, now: o.now() });
172
+ if (!inspected.ok) return o.log("hello_refused", { code: inspected.code });
173
+ const invite = readJson("invite.json");
174
+ const live = invite && !invite.used && invite.e * 1000 > o.now() ? invite : null;
175
+ const accepted = P.acceptHello({ self: o.local, hello, issuerKeys: o.issuerKeys, now: o.now(), random: o.random, knownChannels: new Set(channels.keys()), confirmedPhones: confirmed(), ...(live ? { psk: P.pairingPsk(live.s) } : {}) });
176
+ const phones = loadPhones();
177
+ const phone = { device_id: inspected.value.phone.device_id, fingerprint: inspected.value.fingerprint, ed25519_pub: inspected.value.phone.ed25519_pub, x25519_pub: inspected.value.phone.x25519_pub };
178
+ if (!accepted.ok) {
179
+ if (accepted.code === "not_confirmed" && hello.pair_proof === undefined && !phones.pending.some((p) => p.fingerprint === phone.fingerprint)) {
180
+ savePhones({ ...phones, pending: [...phones.pending, { ...phone, seen_at: o.now() }].slice(-MAX_PENDING_PHONES) });
181
+ }
182
+ return o.log("hello_refused", { code: accepted.code });
183
+ }
184
+ if (accepted.value.paired) {
185
+ // Spent before the welcome leaves: an invite pairs one phone, once.
186
+ writeJson("invite.json", { ...live, used: true, used_at: o.now(), used_by: phone.fingerprint });
187
+ savePhones({ ...phones, removed: phones.removed.filter((p) => p.device_id !== phone.device_id), pending: phones.pending.filter((p) => p.fingerprint !== phone.fingerprint), confirmed: [...phones.confirmed.filter((p) => p.fingerprint !== phone.fingerprint), { ...phone, how: "qr", confirmed_at: o.now() }] });
188
+ }
189
+ for (const [id, c] of channels) if (c.peer_device_id === phone.device_id) channels.delete(id);
190
+ channels.set(accepted.value.channel.channel_id, accepted.value.channel);
191
+ persist();
192
+ o.send({ frame: "welcome", welcome: accepted.value.welcome });
193
+ emit(null, "device.inventory", inventoryBody(false));
194
+ }
195
+
196
+ return {
197
+ emit, replay, receiveCommand, receiveHello, inventoryBody,
198
+ /** The gateway's device.revoked: a phone this computer will no longer hear from. */
199
+ peerRevoked(event) { return dropPhone(event.device_id, event.reason === "unpaired" ? "phone" : "revoked"); },
200
+ attach(s, a, r = null) { sessions = s; approvals = a; releases = r; },
201
+ controllers: () => controllerKeys(loadPhones()),
202
+ phoneOnline: () => channels.size > 0 && (o.online?.() ?? true),
203
+ channels: () => [...channels.values()],
204
+ };
205
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * WHAT THIS COMPUTER'S AGENTS CAN DO, MEASURED (2026-11-07; "adapters report; the UI believes only reports"). Each agent
3
+ * CLI is found on the agents' PATH and asked for its version and its own help; a capability is reported only when the
4
+ * help names it, and a model list only when the agent has a lister its help names (`codex debug models`, `opencode models`,
5
+ * `cursor-agent models`). Claude Code has no lister: since 2026-11-08 (owner: the phone chooses Claude's models as it
6
+ * does Codex's) its models are the ALIASES its own --model help names ("an alias for the latest model (e.g. 'fable',
7
+ * 'opus', or 'sonnet')"), read from this computer's version, each a value `claude --model` takes; a help without that
8
+ * line lists nothing ("not listed"), never a guess. Claude Code and Codex have adapters; the others report "installed, no
9
+ * adapter yet" (every capability false).
10
+ *
11
+ * No shell: each probe is execFile with fixed arguments, a timeout and no input. Nothing here leaves the computer except
12
+ * inside a sealed device.inventory.
13
+ */
14
+ import { spawnSync } from "node:child_process";
15
+ import { existsSync, statSync } from "node:fs";
16
+ import { delimiter, join } from "node:path";
17
+ import * as P from "./remote-protocol.mjs";
18
+ import { codexReport } from "./remote-adapter-codex.mjs";
19
+
20
+ const NO = Object.freeze({ start: false, attach: false, prompt: false, steer: false, pause: false, resume: false, stop: false, structured_events: false, screen: false, focus: false, resume_by_id: false, permission_modes: ["ask"], approvals: "none", acceptance: "acknowledged" });
21
+ export const AGENTS = Object.freeze({ "claude-code": "claude", codex: "codex", "cursor-agent": "cursor-agent", opencode: "opencode" });
22
+
23
+ export function findOnPath(bin, path = process.env.PATH ?? "") {
24
+ for (const dir of path.split(delimiter)) {
25
+ if (!dir) continue;
26
+ for (const name of process.platform === "win32" ? [`${bin}.cmd`, `${bin}.exe`, bin] : [bin]) {
27
+ const file = join(dir, name);
28
+ try { if (existsSync(file) && statSync(file).isFile()) return file; } catch { /* unreadable */ }
29
+ }
30
+ }
31
+ return null;
32
+ }
33
+
34
+ function probe(file, args, env, timeout = 10_000) {
35
+ const out = spawnSync(file, args, { encoding: "utf8", timeout, env, stdio: ["ignore", "pipe", "pipe"], maxBuffer: 4 * 1024 * 1024, windowsHide: true });
36
+ return out.status === 0 ? `${out.stdout ?? ""}` : null;
37
+ }
38
+
39
+ /** The --permission-mode choices Claude Code's help lists. */
40
+ export const permissionChoices = (help) => (/--permission-mode <mode>[\s\S]*?\(choices: ([^)]*)\)/.exec(help ?? "")?.[1].match(/"([a-zA-Z]+)"/g) ?? []).map((q) => q.slice(1, -1));
41
+
42
+ /**
43
+ * Claude Code, from its own help: the flags the adapter needs, each read, never assumed. `askMode` is the mode that asks
44
+ * for every permission the person's rules do not decide ("manual" in 2.1.x, "default" before), `planMode` the read-only one.
45
+ */
46
+ export function claudeFeatures(help) {
47
+ const h = help ?? "", choices = permissionChoices(h);
48
+ return {
49
+ askMode: choices.includes("manual") ? "manual" : choices.includes("default") ? "default" : null,
50
+ planMode: choices.includes("plan") ? "plan" : null,
51
+ streamJson: /--input-format[\s\S]{0,200}stream-json/.test(h) && /--output-format[\s\S]{0,300}stream-json/.test(h),
52
+ permissionTool: /--permission-prompt-tool/.test(h),
53
+ mcpConfig: /--mcp-config/.test(h),
54
+ sessionId: /--session-id/.test(h),
55
+ resume: /--resume/.test(h),
56
+ partial: /--include-partial-messages/.test(h),
57
+ disallowed: /--disallowedTools/.test(h),
58
+ settingSources: /--setting-sources/.test(h),
59
+ replay: /--replay-user-messages/.test(h),
60
+ // The agent's planning tools run without a prompt (they only write a plan), and one line says to use them (2026-11-08).
61
+ allowed: /--allowedTools/.test(h),
62
+ appendPrompt: /--append-system-prompt/.test(h),
63
+ };
64
+ }
65
+
66
+ /** The model aliases Claude Code's own --model help names, in its order; none when the help names none. */
67
+ export function claudeAliases(help) {
68
+ const block = /--model <model>([\s\S]*?)(?=\n\s{2}-|\n\s*\n|$)/.exec(help ?? "")?.[1]?.replace(/\s+/g, " ") ?? "";
69
+ const named = /\balias\b[^(]*\(e\.g\.([^)]*)\)/i.exec(block)?.[1] ?? "";
70
+ return [...new Set([...named.matchAll(/'([a-z][a-z0-9.-]{0,39})'/g)].map((m) => m[1]))].slice(0, P.MAX_MODELS_PER_ADAPTER);
71
+ }
72
+
73
+ export function claudeReport(version, help, now = Date.now()) {
74
+ const f = claudeFeatures(help);
75
+ // The adapter starts only when every piece it relies on is there: stream-json both ways, approvals routed to our tool,
76
+ // the session id chosen before the start (so the steered ledger names it first), and an asking mode.
77
+ const usable = Boolean(f.askMode && f.streamJson && f.permissionTool && f.mcpConfig && f.sessionId && f.disallowed && f.settingSources);
78
+ const capabilities = usable
79
+ ? { ...NO, start: true, prompt: true, stop: true, structured_events: true, resume_by_id: f.resume, permission_modes: f.planMode ? ["ask", "plan"] : ["ask"], approvals: "structured",
80
+ // A live steer needs the replay that confirms it was read; the interrupt is stream-json's control request (2.1.286).
81
+ steer: true, steer_mode: f.replay ? "live" : "queued", interrupt: f.replay }
82
+ : NO;
83
+ const aliases = claudeAliases(help);
84
+ const models = aliases.length ? { models: aliases, models_status: "listed", models_at: now } : { models: null, models_status: "not_listed", models_at: null };
85
+ return { adapter: "claude-code", mode: "structured", installed: true, version: version ? version.trim().slice(0, 200) : null, signed_in: null, capabilities, ...models, default_model: null };
86
+ }
87
+
88
+ function listModels(adapter, file, env, now) {
89
+ const help = adapter === "codex" ? probe(file, ["debug", "--help"], env) : probe(file, ["--help"], env);
90
+ if (!help || !/^\s+models\b/m.test(help)) return { models: null, models_status: "not_listed", models_at: null };
91
+ const out = adapter === "codex" ? probe(file, ["debug", "models"], env, 20_000) : probe(file, ["models"], env, 20_000);
92
+ if (out === null) return { models: null, models_status: "lister_failed", models_at: null };
93
+ let names = [];
94
+ if (adapter === "codex") { try { names = (JSON.parse(out).models ?? []).filter((m) => m?.visibility !== "hide").map((m) => m?.slug); } catch { return { models: null, models_status: "lister_failed", models_at: null }; } }
95
+ else names = out.split("\n").map((l) => l.trim()).filter((l) => l && !/\s/.test(l));
96
+ const models = [...new Set(names.filter((n) => typeof n === "string" && n.length > 0 && n.length <= 128))].slice(0, P.MAX_MODELS_PER_ADAPTER);
97
+ return { models, models_status: "listed", models_at: now };
98
+ }
99
+
100
+ let cache = null;
101
+ /** Every known agent: installed or not, version, capabilities, models. `refresh` re-runs the probes and the listers. */
102
+ export function inventory({ env = process.env, refresh = false, now = Date.now() } = {}) {
103
+ if (cache && !refresh) return cache;
104
+ const reports = [], features = {};
105
+ for (const [adapter, bin] of Object.entries(AGENTS)) {
106
+ const file = findOnPath(bin, env.PATH);
107
+ if (!file) { reports.push({ adapter, mode: "structured", installed: false, version: null, signed_in: null, capabilities: NO, models: null, models_status: "not_listed", models_at: null, default_model: null }); continue; }
108
+ const version = probe(file, ["--version"], env);
109
+ if (adapter === "claude-code") { const help = probe(file, ["--help"], env); features["claude-code"] = claudeFeatures(help); reports.push(claudeReport(version, help, now)); continue; }
110
+ // Codex (2026-11-07): its app-server, when this version has one (remote-adapter-codex.mjs); models from `codex debug models`.
111
+ const codex = adapter === "codex" ? codexReport(version, probe(file, ["app-server", "--help"], env)) : null;
112
+ reports.push({ adapter, mode: "structured", installed: true, version: version ? version.trim().slice(0, 200) : null, signed_in: null, capabilities: codex?.usable ? { ...NO, ...codex.capabilities } : NO, ...listModels(adapter, file, env, now), default_model: null });
113
+ }
114
+ for (const report of reports) {
115
+ const checked = P.validateAdapterReport(report);
116
+ if (!checked.ok) throw new Error(`inventory: ${report.adapter}: ${checked.detail}`);
117
+ }
118
+ cache = { reports, features, files: Object.fromEntries(Object.keys(AGENTS).map((a) => [a, findOnPath(AGENTS[a], env.PATH)])), at: now };
119
+ return cache;
120
+ }
121
+ export const adapterOf = (inv, id) => inv.reports.find((r) => r.adapter === id);
122
+
123
+ /**
124
+ * What this computer OFFERS a phone (review 2026-11-07, P1-3): Codex runs the reads it deems safe without asking, so
125
+ * a phone's prompt could have it read a secret file before the computer can refuse it. Codex is offered only after the
126
+ * person turned it on at the keyboard (`worktrust remote codex on`, settings.codex), the gap stated; until then it is
127
+ * listed as installed and offered nothing.
128
+ */
129
+ export function offered(inv, settings) {
130
+ if (settings?.codex === true) return inv;
131
+ return { ...inv, reports: inv.reports.map((r) => (r.adapter === "codex" && r.capabilities.start ? { ...r, capabilities: NO } : r)) };
132
+ }
@@ -0,0 +1,155 @@
1
+ /**
2
+ * THE COMMAND JOURNAL: AT MOST ONCE, AND NO LOST NEWS (2026-11-07, docs/remote-agents/PROTOCOL.md "At most once").
3
+ *
4
+ * ~/.worktrust/remote/journal.jsonl, mode 0600, one JSON record per line, each appended with O_APPEND and flushed to disk
5
+ * (fsync) before the call returns. The rules it holds, with the protocol's own ledger functions (findCommand,
6
+ * admitCommand, advanceCommand) over the records it reads back:
7
+ *
8
+ * 1. A command is written here BEFORE any agent is invoked for it (`admit` returns only after the fsync). The daemon's
9
+ * order, held by scripts/check-remote-cli.mjs: find, open, admit, receipt, then the agent.
10
+ * 2. A duplicate (same id and bytes, or the same sender's idempotency key under another id) returns the stored entry:
11
+ * its receipts are sent again and nothing runs again. The same id with other bytes is a conflict.
12
+ * 3. A command the journal holds in a non-final state when the daemon starts was interrupted: it is closed as FAILED
13
+ * (`interrupted`), never run again. A daemon killed between the journal write and the agent's start therefore never
14
+ * runs that command twice, and never silently.
15
+ * 4. Every event the daemon sends is kept with its event_seq, so the stream continues where it was after a restart and
16
+ * a phone that attaches can be sent what it missed (`eventsAfter`).
17
+ * 5. An approval decision is spent once, across restarts (`spend`).
18
+ * 6. Releases, their tasks (a queued task's prompt until it starts) and pipeline runs (2026-11-07, PROTOCOL.md "Releases"),
19
+ * each written whole on every change, the latest record winning: a task is journaled `running` before its agent is
20
+ * started, so a restart closes it `interrupted` and never starts it twice. Compaction keeps every release (the
21
+ * backlog the phone scrolls back through) and the last 200 pipeline runs. The file is mode 0600, not encrypted.
22
+ *
23
+ * A torn last line (a crash mid-write) is skipped and counted; the journal is compacted above 8 MB to the last 500 events
24
+ * per stream and a week of commands.
25
+ */
26
+ import { closeSync, existsSync, fsyncSync, openSync, readFileSync, renameSync, statSync, writeSync, constants, chmodSync, rmSync } from "node:fs";
27
+ import * as P from "./remote-protocol.mjs";
28
+
29
+ const MAX_BYTES = 8 * 1024 * 1024;
30
+ const KEEP_EVENTS = 500;
31
+ const KEEP_COMMANDS_MS = 7 * 24 * 3600_000;
32
+ const KEEP_PIPELINES = 200;
33
+ export const DEVICE_STREAM = "device";
34
+
35
+ function appendLine(file, record) {
36
+ const fd = openSync(file, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0), 0o600);
37
+ try { writeSync(fd, `${P.canonicalJson(record)}\n`); fsyncSync(fd); } finally { closeSync(fd); }
38
+ }
39
+
40
+ export function openJournal(file) {
41
+ let ledger = P.emptyLedger();
42
+ const meta = new Map(); // command_id -> { type, session_id, at }
43
+ const events = new Map(); // stream -> [record]
44
+ const seq = new Map(); // stream -> last event_seq
45
+ const decided = new Set();
46
+ const sessions = new Map();
47
+ const releases = new Map(); // release_id -> its latest record
48
+ const pipelines = new Map(); // pipeline_run_id -> its latest body
49
+ let releaseOrder = [];
50
+ const pipelinePids = new Map(); // pipeline_run_id -> { pid, file } of its running stage
51
+ let unreadable = 0;
52
+
53
+ const apply = (r) => {
54
+ if (r.t === "cmd") {
55
+ const admitted = P.admitCommand(ledger, { command_id: r.command_id, idempotency_key: r.idempotency_key, sender_device_id: r.sender_device_id, digest: r.digest }, r.state);
56
+ if (admitted.verdict === "new") { ledger = admitted.ledger; meta.set(r.command_id, { type: r.type, session_id: r.session_id, at: r.at }); }
57
+ } else if (r.t === "state") {
58
+ const entry = ledger.entries[r.command_id];
59
+ if (entry) ledger = { ...ledger, entries: { ...ledger.entries, [r.command_id]: { ...entry, state: r.state } } };
60
+ if (entry && r.reason) meta.set(r.command_id, { ...meta.get(r.command_id), reason: r.reason });
61
+ } else if (r.t === "event") {
62
+ const stream = r.session_id ?? DEVICE_STREAM;
63
+ const list = events.get(stream) ?? [];
64
+ list.push(r);
65
+ if (list.length > KEEP_EVENTS * 2) list.splice(0, list.length - KEEP_EVENTS);
66
+ events.set(stream, list);
67
+ seq.set(stream, Math.max(seq.get(stream) ?? 0, r.event_seq));
68
+ } else if (r.t === "decided") decided.add(r.approval_id);
69
+ else if (r.t === "session") sessions.set(r.session_id, { ...(sessions.get(r.session_id) ?? {}), ...r });
70
+ else if (r.t === "release" && r.release?.release_id) releases.set(r.release.release_id, structuredClone(r.release)); // what was written, not the caller's live object
71
+ else if (r.t === "pipeline" && r.pipeline?.pipeline_run_id) { pipelines.delete(r.pipeline.pipeline_run_id); pipelines.set(r.pipeline.pipeline_run_id, structuredClone(r.pipeline)); }
72
+ else if (r.t === "release_order" && Array.isArray(r.ids)) releaseOrder = r.ids;
73
+ else if (r.t === "pipeline_pid" && r.pipeline_run_id) pipelinePids.set(r.pipeline_run_id, { pid: r.pid, file: r.file });
74
+ };
75
+
76
+ if (existsSync(file)) {
77
+ for (const line of readFileSync(file, "utf8").split("\n")) {
78
+ if (line.trim() === "") continue;
79
+ let record;
80
+ try { record = JSON.parse(line); } catch { unreadable += 1; continue; }
81
+ if (record && typeof record === "object" && typeof record.t === "string") apply(record); else unreadable += 1;
82
+ }
83
+ try { chmodSync(file, 0o600); } catch { /* Windows */ }
84
+ }
85
+ const write = (record) => { appendLine(file, record); apply(record); };
86
+
87
+ const journal = {
88
+ file,
89
+ get unreadable() { return unreadable; },
90
+ find: (input) => P.findCommand(ledger, input),
91
+ entry: (commandId) => ledger.entries[commandId] ?? null,
92
+ meta: (commandId) => meta.get(commandId) ?? null,
93
+ /** Rule 1: the command is on disk when this returns "new". */
94
+ admit(input, { type, session_id, now }) {
95
+ const admitted = P.admitCommand(ledger, input, "DEVICE_RECEIVED");
96
+ if (admitted.verdict !== "new") return admitted;
97
+ write({ t: "cmd", ...input, type, session_id, at: now, state: "DEVICE_RECEIVED" });
98
+ return { verdict: "new", entry: ledger.entries[input.command_id] };
99
+ },
100
+ advance(commandId, input, now, reason = null) {
101
+ const entry = ledger.entries[commandId];
102
+ if (!entry) return null;
103
+ const next = P.transition(entry.state, input);
104
+ if (next.changed) write({ t: "state", command_id: commandId, state: next.state, at: now, ...(reason ? { reason } : {}) });
105
+ return ledger.entries[commandId].state;
106
+ },
107
+ /** Rule 3: commands left mid-way by an earlier daemon. */
108
+ interrupted: () => Object.values(ledger.entries).filter((e) => !P.isTerminal(e.state)).map((e) => e.command_id),
109
+ commandsOf: (sessionId) => [...meta.entries()].filter(([, m]) => m.session_id === sessionId).map(([id]) => ({ command_id: id, state: ledger.entries[id].state })),
110
+ nextSeq: (stream) => (seq.get(stream ?? DEVICE_STREAM) ?? 0) + 1,
111
+ lastSeq: (stream) => seq.get(stream ?? DEVICE_STREAM) ?? 0,
112
+ /** When the stream's latest kept event happened, or null: a session's "last run" on the phone's project tree. */
113
+ lastAt: (stream) => (events.get(stream ?? DEVICE_STREAM) ?? []).reduce((at, e) => Math.max(at ?? 0, e.occurred_at ?? 0), null),
114
+ recordEvent: (record) => write({ t: "event", ...record }),
115
+ eventsAfter: (stream, after) => (events.get(stream ?? DEVICE_STREAM) ?? []).filter((e) => e.event_seq > after).sort((a, b) => a.event_seq - b.event_seq),
116
+ isDecided: (approvalId) => decided.has(approvalId),
117
+ decidedSet: () => new Set(decided),
118
+ /** Rule 5. */
119
+ spend: (approvalId, now) => { if (!decided.has(approvalId)) write({ t: "decided", approval_id: approvalId, at: now }); },
120
+ recordSession: (record) => write({ t: "session", ...record }),
121
+ session: (sessionId) => sessions.get(sessionId) ?? null,
122
+ sessions: () => [...sessions.values()],
123
+ /** Rule 6: on disk when this returns. */
124
+ recordRelease: (release) => write({ t: "release", release }),
125
+ releases: () => [...releases.values()],
126
+ recordPipeline: (pipeline) => write({ t: "pipeline", pipeline }),
127
+ /** Oldest first (by the order they were first written, an update keeping its place last). */
128
+ pipelines: () => [...pipelines.values()].sort((a, b) => a.started_at - b.started_at),
129
+ recordReleaseOrder: (ids) => write({ t: "release_order", ids }),
130
+ /** The running stage's process, so a later daemon can end it (review 2026-11-07, P2-4). */
131
+ recordPipelinePid: (pipeline_run_id, { pid, file }) => write({ t: "pipeline_pid", pipeline_run_id, pid, file }),
132
+ pipelinePid: (pipelineRunId) => pipelinePids.get(pipelineRunId) ?? null,
133
+ releaseOrder: () => [...releaseOrder],
134
+ compact(now) {
135
+ if (!existsSync(file) || statSync(file).size < MAX_BYTES) return false;
136
+ const keepCmd = new Set([...meta.entries()].filter(([id, m]) => now - m.at < KEEP_COMMANDS_MS || !P.isTerminal(ledger.entries[id].state)).map(([id]) => id));
137
+ const lines = [];
138
+ for (const [id, m] of meta) if (keepCmd.has(id)) { const e = ledger.entries[id]; lines.push({ t: "cmd", command_id: id, idempotency_key: e.idempotency_key, sender_device_id: e.sender_device_id, digest: e.digest, type: m.type, session_id: m.session_id, at: m.at, state: e.state }); }
139
+ for (const s of sessions.values()) lines.push({ t: "session", ...s });
140
+ for (const id of decided) lines.push({ t: "decided", approval_id: id, at: now });
141
+ for (const list of events.values()) for (const e of list.slice(-KEEP_EVENTS)) lines.push(e);
142
+ for (const release of releases.values()) lines.push({ t: "release", release });
143
+ for (const pipeline of journal.pipelines().slice(-KEEP_PIPELINES)) lines.push({ t: "pipeline", pipeline });
144
+ if (releaseOrder.length > 0) lines.push({ t: "release_order", ids: releaseOrder });
145
+ for (const p of journal.pipelines()) if (!P.isFinalPipelineState(p.state) && pipelinePids.has(p.pipeline_run_id)) lines.push({ t: "pipeline_pid", pipeline_run_id: p.pipeline_run_id, ...pipelinePids.get(p.pipeline_run_id) });
146
+ const temporary = `${file}.${process.pid}.tmp`;
147
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC, 0o600);
148
+ try { writeSync(fd, lines.map((l) => `${P.canonicalJson(l)}\n`).join("")); fsyncSync(fd); } finally { closeSync(fd); }
149
+ renameSync(temporary, file);
150
+ rmSync(temporary, { force: true });
151
+ return true;
152
+ },
153
+ };
154
+ return journal;
155
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * BINDING THIS COMPUTER'S REMOTE KEYS TO THE PERSON'S ACCOUNT (2026-11-07; docs/remote-agents/ISSUER.md is the contract).
3
+ *
4
+ * The same shape as `worktrust connect`, on its own audience and with its own key: this terminal listens on 127.0.0.1 for
5
+ * one answer, holds a PKCE verifier, and sends only the PUBLIC halves of a fresh remote key pair with a proof that it holds
6
+ * them. The person approves in the Passport app, signed in, with their second factor; the browser comes back to
7
+ * 127.0.0.1 with a one-time code that only this terminal, with its verifier, can exchange for the issuer's signed binding.
8
+ * Without a browser (`--device`, SSH) a typed code instead. The binding is verified against the issuer keys pinned in this
9
+ * release before anything is saved. A Passport app without the issuer answers 404, and this says so and changes nothing.
10
+ * The measurement key is never read, sent or used here.
11
+ */
12
+ import { createHash, randomBytes } from "node:crypto";
13
+ import { createServer } from "node:http";
14
+ import * as P from "./remote-protocol.mjs";
15
+
16
+ const PROOF = P.utf8Encode("worktrust-remote/v1/pair-request\n");
17
+ const RENEW = P.utf8Encode("worktrust-remote/v1/renew\n");
18
+ export const pairProofBytes = (body) => P.concatBytes(PROOF, P.canonicalBytes(body));
19
+ export const renewBytes = (body) => P.concatBytes(RENEW, P.canonicalBytes(body));
20
+
21
+ export class IssuerMissing extends Error {}
22
+ export class PairingRefused extends Error {}
23
+
24
+ async function post(origin, path, body) {
25
+ const response = await fetch(`${origin}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(20_000) });
26
+ return { status: response.status, json: await response.json().catch(() => ({})) };
27
+ }
28
+
29
+ /** Pair, and return the verified binding. `keys` holds the secret pair (never sent), `issuerKeys` the pinned keys. */
30
+ export async function pairComputer({ origin, secret, publicKeys, host, os, device = false, issuerKeys, say, openBrowser, now = Date.now }) {
31
+ const verifier = randomBytes(32).toString("base64url");
32
+ const code_challenge = createHash("sha256").update(verifier).digest("base64url");
33
+ const state = randomBytes(24).toString("base64url");
34
+ const claim = { code_challenge, ed25519_pub: publicKeys.ed25519_pub, kind: "computer", x25519_pub: publicKeys.x25519_pub };
35
+ const proof = P.toBase64Url(P.ed25519Sign(pairProofBytes(claim), secret.ed25519));
36
+ let server = null, deliver = null;
37
+ const answer = new Promise((resolve) => { deliver = resolve; });
38
+ if (!device) {
39
+ server = createServer((request, response) => {
40
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
41
+ if (url.pathname !== "/callback" || url.searchParams.get("state") !== state || !url.searchParams.get("code")) { response.writeHead(404).end(); return; }
42
+ response.writeHead(200, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" }).end("This computer is approved for WorkTrust remote. Return to your terminal.");
43
+ deliver(url.searchParams.get("code"));
44
+ });
45
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
46
+ }
47
+ try {
48
+ const pairing = await post(origin, "/api/remote/pair", { flow: device ? "device" : "loopback", host, os, ...claim, code_challenge_method: "S256", proof, ...(device ? {} : { port: server.address().port, state }) }).catch(() => null);
49
+ if (!pairing) throw new PairingRefused(`cannot reach ${origin}`);
50
+ if (pairing.status === 404) throw new IssuerMissing(`${origin} has no remote-key issuer yet (POST /api/remote/pair answered 404). Nothing was changed; remote control needs a Passport app with the issuer (docs/remote-agents/ISSUER.md).`);
51
+ if (pairing.status !== 200) throw new PairingRefused(`pairing refused (${pairing.json.error ?? pairing.status})`);
52
+ const { device_code, user_code, expires_in = 600, interval = 3, authorize_url, verification_uri, features = [] } = pairing.json;
53
+ if (!features.includes("remote-binding-v1")) throw new PairingRefused(`${origin} does not offer remote bindings (remote-binding-v1)`);
54
+ const fingerprint = P.deviceFingerprint(publicKeys);
55
+ say(` Your code: ${user_code} This computer's remote key: ${fingerprint}`);
56
+ say(" Approve only if the WorkTrust page shows the same code and key.");
57
+ let exchanged = null;
58
+ if (!device) {
59
+ say(` Approve in your browser (opening it). If it does not open: ${authorize_url}`);
60
+ openBrowser(authorize_url);
61
+ const timer = setTimeout(() => deliver(null), expires_in * 1000);
62
+ const code = await answer;
63
+ clearTimeout(timer);
64
+ if (!code) throw new PairingRefused("no approval arrived in time");
65
+ exchanged = await post(origin, "/api/remote/token", { device_code, code, code_verifier: verifier });
66
+ } else {
67
+ say(` On any device open ${verification_uri} and type the code.`);
68
+ const until = now() + expires_in * 1000;
69
+ let wait = interval * 1000;
70
+ while (now() < until) {
71
+ await new Promise((resolve) => setTimeout(resolve, wait));
72
+ const reply = await post(origin, "/api/remote/token", { device_code, code_verifier: verifier }).catch(() => null);
73
+ if (reply?.status === 200) { exchanged = reply; break; }
74
+ if (reply?.json?.error === "slow_down") wait += 2000;
75
+ else if (reply?.json?.error && reply.json.error !== "authorization_pending") throw new PairingRefused(`pairing ended (${reply.json.error})`);
76
+ }
77
+ }
78
+ if (!exchanged || exchanged.status !== 200 || typeof exchanged.json.binding !== "string") throw new PairingRefused(`the approval could not be exchanged (${exchanged?.json?.error ?? "no answer"})`);
79
+ if (Object.keys(issuerKeys).length === 0) throw new PairingRefused("this release pins no WorkTrust issuer key yet, so the binding cannot be verified; nothing was saved");
80
+ const verified = P.verifyBinding(exchanged.json.binding, { issuerKeys, now: now(), kind: "computer", deviceId: exchanged.json.device_id });
81
+ if (!verified.ok) throw new PairingRefused(`the binding does not verify (${verified.code}); nothing was saved`);
82
+ if (verified.value.ed25519_pub !== publicKeys.ed25519_pub || verified.value.x25519_pub !== publicKeys.x25519_pub) throw new PairingRefused("the binding names other keys; nothing was saved");
83
+ return { binding: exchanged.json.binding, device_id: verified.value.device_id, sub: verified.value.sub, exp: verified.value.exp, account: typeof exchanged.json.account === "string" ? exchanged.json.account.slice(0, 120) : null };
84
+ } finally { server?.close(); }
85
+ }
86
+
87
+ /** A fresh binding for the same keys before the old one ends (POST /api/remote/renew). Null when the issuer has none. */
88
+ export async function renewBinding({ origin, identity, secret, now = Date.now }) {
89
+ const jti = JSON.parse(Buffer.from(identity.binding.split(".")[1], "base64url").toString("utf8")).jti;
90
+ const body = { binding_jti: jti, device_id: identity.device_id, iat: now() };
91
+ const reply = await post(origin, "/api/remote/renew", { binding: identity.binding, iat: body.iat, signature: P.toBase64Url(P.ed25519Sign(renewBytes(body), secret.ed25519)) }).catch(() => null);
92
+ return reply?.status === 200 && typeof reply.json.binding === "string" ? reply.json.binding : null;
93
+ }
94
+
95
+ /**
96
+ * A FIVE-MINUTE GATEWAY ASSERTION (POST /api/remote/assertion, ISSUER.md §5): asked fresh for every gateway challenge,
97
+ * signed by this computer's REMOTE key over its device id, the time and a fresh nonce. Null when the issuer refuses or is
98
+ * unreachable: the gateway then refuses this connection and the transport backs off; nothing else changes.
99
+ */
100
+ export async function requestAssertion({ origin, deviceId, secret, now = Date.now, random = (n) => new Uint8Array(randomBytes(n)) }) {
101
+ const body = { device_id: deviceId, iat: now(), nonce: P.toBase64Url(random(32)) };
102
+ const reply = await post(origin, "/api/remote/assertion", { ...body, signature: P.toBase64Url(P.ed25519Sign(P.assertionRequestBytes(body), secret.ed25519)) }).catch(() => null);
103
+ return reply?.status === 200 && typeof reply.json.assertion === "string" && reply.json.assertion.length <= 4096 ? reply.json.assertion : null;
104
+ }