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.
- package/LICENSE +43 -18
- package/README.md +55 -2
- package/SECURITY.md +25 -0
- package/engine-release.json +1 -1
- package/log-session.mjs +6 -6
- package/package-release.json +1 -1
- package/package.json +43 -2
- package/remote-adapter-claude-code.mjs +113 -0
- package/remote-adapter-codex.mjs +159 -0
- package/remote-adapter-terminal.mjs +248 -0
- package/remote-approval-bridge.mjs +145 -0
- package/remote-approvals.mjs +134 -0
- package/remote-attachments.mjs +129 -0
- package/remote-cdp.mjs +60 -0
- package/remote-changes.mjs +94 -0
- package/remote-claude-events.mjs +212 -0
- package/remote-claude-progress.mjs +328 -0
- package/remote-cli.mjs +330 -0
- package/remote-coalesce.mjs +40 -0
- package/remote-codex-events.mjs +153 -0
- package/remote-daemon.mjs +220 -0
- package/remote-inventory.mjs +143 -0
- package/remote-journal.mjs +155 -0
- package/remote-live-preview.mjs +205 -0
- package/remote-pairing.mjs +104 -0
- package/remote-pipeline-config.mjs +177 -0
- package/remote-pipeline-parsers.mjs +121 -0
- package/remote-pipeline.mjs +234 -0
- package/remote-policy.mjs +199 -0
- package/remote-preview.mjs +146 -0
- package/remote-projects.mjs +87 -0
- package/remote-protocol.mjs +4010 -0
- package/remote-qr.mjs +175 -0
- package/remote-release-plans.mjs +88 -0
- package/remote-releases.mjs +297 -0
- package/remote-run.mjs +189 -0
- package/remote-screen-approvals.mjs +79 -0
- package/remote-screen-push.mjs +76 -0
- package/remote-screen-states.mjs +113 -0
- package/remote-service.mjs +101 -0
- package/remote-session-list.mjs +48 -0
- package/remote-sessions.mjs +337 -0
- package/remote-steered.mjs +114 -0
- package/remote-steering.mjs +97 -0
- package/remote-store.mjs +124 -0
- package/remote-terminal-cli.mjs +85 -0
- package/remote-terminal-sessions.mjs +291 -0
- package/remote-transport.mjs +88 -0
- package/worktrust.mjs +11 -4
|
@@ -0,0 +1,220 @@
|
|
|
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 LIVE_COMMANDS = new Set(["preview.live_start", "preview.live_input", "preview.live_viewport", "preview.live_follow"]);
|
|
20
|
+
const DEVICE_COMMANDS = new Set(["inventory.get", "device.configure", "status.get", "pairing.revoke", "release.list", "pipeline.cancel"]);
|
|
21
|
+
const KEEP_REMOVED = 20;
|
|
22
|
+
const MAX_PENDING_PHONES = 10;
|
|
23
|
+
|
|
24
|
+
export function createDaemonCore(o) {
|
|
25
|
+
// o: { local, issuerKeys, journal, now, random, send(frame), inventory(refresh), log(kind, fields), sessions?, approvals? }
|
|
26
|
+
const channels = new Map(loadChannels().map((c) => [c.channel_id, c]));
|
|
27
|
+
const confirmed = () => confirmedFingerprints(loadPhones());
|
|
28
|
+
const self = o.local.claims.device_id;
|
|
29
|
+
const persist = () => saveChannels([...channels.values()]);
|
|
30
|
+
let sessions = null, approvals = o.approvals ?? null, releases = null;
|
|
31
|
+
|
|
32
|
+
function sealAll(record) {
|
|
33
|
+
for (const [id, channel] of channels) {
|
|
34
|
+
if (!confirmed().has(channel.peer_fingerprint)) { channels.delete(id); continue; } // a revoked phone hears nothing
|
|
35
|
+
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, ...(record.lane ? { lane: record.lane } : {}) };
|
|
36
|
+
const sealed = P.sealEvent(channel, draft, record.body, o.random);
|
|
37
|
+
if (!sealed.ok) { o.log("seal_refused", { type: record.type, code: sealed.code }); continue; }
|
|
38
|
+
channels.set(id, sealed.value.channel);
|
|
39
|
+
o.send({ frame: "event", envelope: sealed.value.envelope });
|
|
40
|
+
}
|
|
41
|
+
persist();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* `transient` (release 19; a pushed terminal screen, remote-screen-push.mjs): the session's TRANSIENT LANE
|
|
46
|
+
* (envelopes.ts), sealed for the phones and never journaled, so a replay never brings back a stale screen and the
|
|
47
|
+
* session's own sequence has no number missing. Its numbers rise per session from this computer's clock.
|
|
48
|
+
*/
|
|
49
|
+
const laneSeq = new Map();
|
|
50
|
+
function emit(sessionId, type, body, commandId = null, notify = "none", { transient = false } = {}) {
|
|
51
|
+
let shaped = P.validateEventBody(type, body);
|
|
52
|
+
if (!shaped.ok && type === "agent.completed" && body.result) {
|
|
53
|
+
// A result over its caps keeps the reply and names the files; the diffs are said to be cut.
|
|
54
|
+
const files = body.result.files.map((f) => ({ ...f, diff: null, diff_cut: f.diff !== null || f.diff_cut }));
|
|
55
|
+
body = { ...body, result: { ...body.result, files } };
|
|
56
|
+
shaped = P.validateEventBody(type, body);
|
|
57
|
+
}
|
|
58
|
+
if (!shaped.ok) { o.log("event_refused", { type, detail: shaped.code }); return; }
|
|
59
|
+
if (transient) {
|
|
60
|
+
const seq = Math.max((laneSeq.get(sessionId) ?? 0) + 1, o.now());
|
|
61
|
+
laneSeq.set(sessionId, seq);
|
|
62
|
+
return sealAll({ session_id: sessionId, event_seq: seq, type, occurred_at: o.now(), command_id: null, notify: "none", lane: "transient", body });
|
|
63
|
+
}
|
|
64
|
+
const record = { session_id: sessionId, event_seq: o.journal.nextSeq(sessionId), type, occurred_at: o.now(), command_id: commandId, notify, body };
|
|
65
|
+
o.journal.recordEvent(record);
|
|
66
|
+
sealAll(record);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Re-seal what the journal holds for a session after `after` (session.attach): same event_seq, so the phone dedups. */
|
|
70
|
+
const replay = (sessionId, after) => { for (const record of o.journal.eventsAfter(sessionId, after)) sealAll(record); };
|
|
71
|
+
|
|
72
|
+
function inventoryBody(refresh) {
|
|
73
|
+
const settings = loadSettings();
|
|
74
|
+
return {
|
|
75
|
+
remote_enabled: settings.enabled && settings.paused === null,
|
|
76
|
+
default_adapter: settings.default_adapter ?? null,
|
|
77
|
+
default_model: settings.default_model ?? null,
|
|
78
|
+
adapters: o.inventory(refresh).reports,
|
|
79
|
+
// A worktree names its main repository (`main`), only when it is one: a phone groups its sessions under that project.
|
|
80
|
+
projects: loadProjects().slice(0, 30).map((p) => {
|
|
81
|
+
const main = worktreeMain(p.path);
|
|
82
|
+
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) } : {}) };
|
|
83
|
+
}),
|
|
84
|
+
roots: loadRoots().slice(0, 20).map((r) => ({ root_id: r.root_id, label: rootLabel(r.path), git_init: r.git_init === true })),
|
|
85
|
+
// Every session this computer knows, live or in the journal, newest activity first, with its name and its release task.
|
|
86
|
+
sessions: (sessions?.listAll?.() ?? sessions?.list() ?? []).map((s) => ({ ...s, ...(releases?.ownerOf(s.session_id) ?? {}) })).slice(0, 100),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function resendReceipts(entry) {
|
|
91
|
+
const meta = o.journal.meta(entry.command_id) ?? {};
|
|
92
|
+
emit(meta.session_id ?? null, "command.device_received", {}, entry.command_id);
|
|
93
|
+
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);
|
|
94
|
+
else if (P.DELIVERY_RANK[entry.state] >= P.DELIVERY_RANK.AGENT_ACCEPTED) emit(meta.session_id ?? null, "command.agent_accepted", {}, entry.command_id);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function reject(env, reason) {
|
|
98
|
+
o.journal.advance(env.command_id, { kind: "device_rejected", expired: reason === "expired" }, o.now(), reason);
|
|
99
|
+
emit(env.session_id, "command.rejected", { reason }, env.command_id);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async function configure(payload) {
|
|
103
|
+
const settings = loadSettings();
|
|
104
|
+
if (payload.remote_enabled === true && settings.paused === "desk") return "remote_paused"; // the desk's pause is the person's, at the keyboard
|
|
105
|
+
const next = { ...settings };
|
|
106
|
+
if (payload.remote_enabled !== undefined) next.paused = payload.remote_enabled ? null : settings.paused ?? "phone";
|
|
107
|
+
if (payload.default_adapter !== undefined) next.default_adapter = payload.default_adapter;
|
|
108
|
+
if (payload.default_model !== undefined) {
|
|
109
|
+
const report = o.inventory(false).reports.find((r) => r.adapter === (next.default_adapter ?? "claude-code"));
|
|
110
|
+
if (payload.default_model !== null && !(report && P.isModelReported(report, payload.default_model))) return "unknown_model";
|
|
111
|
+
next.default_model = payload.default_model;
|
|
112
|
+
}
|
|
113
|
+
saveSettings(next);
|
|
114
|
+
emit(null, "device.inventory", inventoryBody(false));
|
|
115
|
+
return "taken";
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* A phone goes (owner, 2026-11-07): it disconnected itself (its sealed pairing.revoke, or the gateway's device.revoked
|
|
120
|
+
* after it), or the Passport revoked it. It leaves the confirmed and pending lists for `removed`, which `remote phones`
|
|
121
|
+
* shows, and every channel with it closes now. Dropping a phone only ever takes power away, so the relay's word suffices.
|
|
122
|
+
*/
|
|
123
|
+
function dropPhone(deviceId, how) {
|
|
124
|
+
const phones = loadPhones();
|
|
125
|
+
const gone = [...phones.confirmed, ...phones.pending].find((p) => p.device_id === deviceId);
|
|
126
|
+
for (const [id, c] of channels) if (c.peer_device_id === deviceId) channels.delete(id);
|
|
127
|
+
persist();
|
|
128
|
+
if (!gone) return false;
|
|
129
|
+
savePhones({ ...phones, confirmed: phones.confirmed.filter((p) => p.device_id !== deviceId), pending: phones.pending.filter((p) => p.device_id !== deviceId),
|
|
130
|
+
removed: [...(phones.removed ?? []).filter((p) => p.device_id !== deviceId), { device_id: deviceId, fingerprint: gone.fingerprint, how, removed_at: o.now() }].slice(-KEEP_REMOVED) });
|
|
131
|
+
o.log("phone_removed", { how });
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function dispatch(env, payload) {
|
|
136
|
+
const settings = loadSettings();
|
|
137
|
+
if (!settings.enabled) return "remote_paused";
|
|
138
|
+
if (settings.paused !== null && !DEVICE_COMMANDS.has(env.type)) return "remote_paused";
|
|
139
|
+
if (env.type === "inventory.get") { emit(null, "device.inventory", inventoryBody(payload.refresh_models)); return "taken"; }
|
|
140
|
+
if (env.type === "device.configure") return configure(payload);
|
|
141
|
+
if (env.type === "status.get" && payload.scope === "device") { emit(null, "device.inventory", inventoryBody(false)); return "taken"; }
|
|
142
|
+
if (env.type === "pairing.revoke") return "taken";
|
|
143
|
+
if (env.type === "project.create") {
|
|
144
|
+
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 });
|
|
145
|
+
if (!made.ok) return made.reason;
|
|
146
|
+
emit(null, "project.created", { ...made.project, git: made.git }, env.command_id);
|
|
147
|
+
emit(null, "device.inventory", inventoryBody(false));
|
|
148
|
+
o.log("project_created", { git: made.git });
|
|
149
|
+
return "taken";
|
|
150
|
+
}
|
|
151
|
+
if (env.type === "approval.decision") return approvals.decide(payload.decision_token).ok ? "taken" : "approval_invalid";
|
|
152
|
+
if (P.RELEASE_COMMANDS.has(env.type)) return releases ? releases.handle(env, payload) : "unsupported"; // remote-releases.mjs
|
|
153
|
+
if (env.type === "attachment.put" || env.type === "attachment.clear") return o.attachments ? o.attachments.handle(env, payload) : "unsupported"; // remote-attachments.mjs
|
|
154
|
+
if (env.type === "preview.targets" || env.type === "preview.render") return o.preview ? o.preview.handle(env, payload) : "unsupported"; // remote-preview.mjs
|
|
155
|
+
if (LIVE_COMMANDS.has(env.type)) return o.live ? o.live.handle(env, payload) : "unsupported"; // remote-live-preview.mjs
|
|
156
|
+
const handled = await sessions.handle(env, payload);
|
|
157
|
+
if (env.type === "session.close") await o.live?.sessionClosed(env.session_id); // its live preview ends with it
|
|
158
|
+
return handled;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** The order of this function is the at-most-once rule (see the header). */
|
|
162
|
+
async function receiveCommand(envelope) {
|
|
163
|
+
const shaped = P.validateCommandEnvelope(envelope);
|
|
164
|
+
if (!shaped.ok) return o.log("command_dropped", { code: shaped.code });
|
|
165
|
+
const channel = channels.get(envelope.payload_ciphertext.channel_id);
|
|
166
|
+
if (!channel) return o.log("command_dropped", { code: "wrong_channel" });
|
|
167
|
+
if (!confirmed().has(channel.peer_fingerprint)) { channels.delete(channel.channel_id); persist(); return o.log("command_dropped", { code: "not_confirmed" }); }
|
|
168
|
+
const input = { command_id: envelope.command_id, idempotency_key: envelope.idempotency_key, sender_device_id: envelope.sender_device_id, digest: P.envelopeDigest(envelope) };
|
|
169
|
+
const found = o.journal.find(input);
|
|
170
|
+
if (found === "conflict") return o.log("command_dropped", { code: "conflict", command_id: envelope.command_id });
|
|
171
|
+
if (found !== "unknown") return resendReceipts(found.duplicate);
|
|
172
|
+
const opened = P.openCommand(channel, envelope, o.now());
|
|
173
|
+
if (!opened.ok && opened.code !== "expired") return o.log("command_dropped", { code: opened.code, command_id: envelope.command_id });
|
|
174
|
+
if (opened.ok) { channels.set(channel.channel_id, opened.value.channel); persist(); }
|
|
175
|
+
const admitted = o.journal.admit(input, { type: envelope.type, session_id: envelope.session_id, now: o.now() });
|
|
176
|
+
if (admitted.verdict !== "new") return resendReceipts(admitted.entry);
|
|
177
|
+
emit(envelope.session_id, "command.device_received", {}, envelope.command_id);
|
|
178
|
+
if (!opened.ok) return reject(envelope, "expired"); // authentic (the signature verified first) but late
|
|
179
|
+
const outcome = await dispatch(opened.value.envelope, opened.value.payload);
|
|
180
|
+
if (outcome === "taken") { o.journal.advance(envelope.command_id, { kind: "agent_accepted" }, o.now()); emit(envelope.session_id, "command.agent_accepted", {}, envelope.command_id); }
|
|
181
|
+
else if (outcome !== null) reject(envelope, outcome);
|
|
182
|
+
if (outcome === "taken" && envelope.type === "pairing.revoke") dropPhone(envelope.sender_device_id, "phone");
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function receiveHello(hello) {
|
|
186
|
+
const inspected = P.inspectHello(hello, o.local, { issuerKeys: o.issuerKeys, now: o.now() });
|
|
187
|
+
if (!inspected.ok) return o.log("hello_refused", { code: inspected.code });
|
|
188
|
+
const invite = readJson("invite.json");
|
|
189
|
+
const live = invite && !invite.used && invite.e * 1000 > o.now() ? invite : null;
|
|
190
|
+
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) } : {}) });
|
|
191
|
+
const phones = loadPhones();
|
|
192
|
+
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 };
|
|
193
|
+
if (!accepted.ok) {
|
|
194
|
+
if (accepted.code === "not_confirmed" && hello.pair_proof === undefined && !phones.pending.some((p) => p.fingerprint === phone.fingerprint)) {
|
|
195
|
+
savePhones({ ...phones, pending: [...phones.pending, { ...phone, seen_at: o.now() }].slice(-MAX_PENDING_PHONES) });
|
|
196
|
+
}
|
|
197
|
+
return o.log("hello_refused", { code: accepted.code });
|
|
198
|
+
}
|
|
199
|
+
if (accepted.value.paired) {
|
|
200
|
+
// Spent before the welcome leaves: an invite pairs one phone, once.
|
|
201
|
+
writeJson("invite.json", { ...live, used: true, used_at: o.now(), used_by: phone.fingerprint });
|
|
202
|
+
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() }] });
|
|
203
|
+
}
|
|
204
|
+
for (const [id, c] of channels) if (c.peer_device_id === phone.device_id) channels.delete(id);
|
|
205
|
+
channels.set(accepted.value.channel.channel_id, accepted.value.channel);
|
|
206
|
+
persist();
|
|
207
|
+
o.send({ frame: "welcome", welcome: accepted.value.welcome });
|
|
208
|
+
emit(null, "device.inventory", inventoryBody(false));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
return {
|
|
212
|
+
emit, replay, receiveCommand, receiveHello, inventoryBody,
|
|
213
|
+
/** The gateway's device.revoked: a phone this computer will no longer hear from. */
|
|
214
|
+
peerRevoked(event) { return dropPhone(event.device_id, event.reason === "unpaired" ? "phone" : "revoked"); },
|
|
215
|
+
attach(s, a, r = null) { sessions = s; approvals = a; releases = r; },
|
|
216
|
+
controllers: () => controllerKeys(loadPhones()),
|
|
217
|
+
phoneOnline: () => channels.size > 0 && (o.online?.() ?? true),
|
|
218
|
+
channels: () => [...channels.values()],
|
|
219
|
+
};
|
|
220
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
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
|
+
import { terminalReport, tmuxVersion } from "./remote-adapter-terminal.mjs";
|
|
20
|
+
import { typingTrusted } from "./remote-screen-states.mjs";
|
|
21
|
+
|
|
22
|
+
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" });
|
|
23
|
+
export const AGENTS = Object.freeze({ "claude-code": "claude", codex: "codex", "cursor-agent": "cursor-agent", opencode: "opencode" });
|
|
24
|
+
|
|
25
|
+
export function findOnPath(bin, path = process.env.PATH ?? "") {
|
|
26
|
+
for (const dir of path.split(delimiter)) {
|
|
27
|
+
if (!dir) continue;
|
|
28
|
+
for (const name of process.platform === "win32" ? [`${bin}.cmd`, `${bin}.exe`, bin] : [bin]) {
|
|
29
|
+
const file = join(dir, name);
|
|
30
|
+
try { if (existsSync(file) && statSync(file).isFile()) return file; } catch { /* unreadable */ }
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function probe(file, args, env, timeout = 10_000) {
|
|
37
|
+
const out = spawnSync(file, args, { encoding: "utf8", timeout, env, stdio: ["ignore", "pipe", "pipe"], maxBuffer: 4 * 1024 * 1024, windowsHide: true });
|
|
38
|
+
return out.status === 0 ? `${out.stdout ?? ""}` : null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The --permission-mode choices Claude Code's help lists. */
|
|
42
|
+
export const permissionChoices = (help) => (/--permission-mode <mode>[\s\S]*?\(choices: ([^)]*)\)/.exec(help ?? "")?.[1].match(/"([a-zA-Z]+)"/g) ?? []).map((q) => q.slice(1, -1));
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Claude Code, from its own help: the flags the adapter needs, each read, never assumed. `askMode` is the mode that asks
|
|
46
|
+
* for every permission the person's rules do not decide ("manual" in 2.1.x, "default" before), `planMode` the read-only one.
|
|
47
|
+
*/
|
|
48
|
+
export function claudeFeatures(help) {
|
|
49
|
+
const h = help ?? "", choices = permissionChoices(h);
|
|
50
|
+
return {
|
|
51
|
+
askMode: choices.includes("manual") ? "manual" : choices.includes("default") ? "default" : null,
|
|
52
|
+
planMode: choices.includes("plan") ? "plan" : null,
|
|
53
|
+
streamJson: /--input-format[\s\S]{0,200}stream-json/.test(h) && /--output-format[\s\S]{0,300}stream-json/.test(h),
|
|
54
|
+
permissionTool: /--permission-prompt-tool/.test(h),
|
|
55
|
+
mcpConfig: /--mcp-config/.test(h),
|
|
56
|
+
sessionId: /--session-id/.test(h),
|
|
57
|
+
resume: /--resume/.test(h),
|
|
58
|
+
partial: /--include-partial-messages/.test(h),
|
|
59
|
+
disallowed: /--disallowedTools/.test(h),
|
|
60
|
+
settingSources: /--setting-sources/.test(h),
|
|
61
|
+
replay: /--replay-user-messages/.test(h),
|
|
62
|
+
// The agent's planning tools run without a prompt (they only write a plan), and one line says to use them (2026-11-08).
|
|
63
|
+
allowed: /--allowedTools/.test(h),
|
|
64
|
+
appendPrompt: /--append-system-prompt/.test(h),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** The model aliases Claude Code's own --model help names, in its order; none when the help names none. */
|
|
69
|
+
export function claudeAliases(help) {
|
|
70
|
+
const block = /--model <model>([\s\S]*?)(?=\n\s{2}-|\n\s*\n|$)/.exec(help ?? "")?.[1]?.replace(/\s+/g, " ") ?? "";
|
|
71
|
+
const named = /\balias\b[^(]*\(e\.g\.([^)]*)\)/i.exec(block)?.[1] ?? "";
|
|
72
|
+
return [...new Set([...named.matchAll(/'([a-z][a-z0-9.-]{0,39})'/g)].map((m) => m[1]))].slice(0, P.MAX_MODELS_PER_ADAPTER);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function claudeReport(version, help, now = Date.now()) {
|
|
76
|
+
const f = claudeFeatures(help);
|
|
77
|
+
// The adapter starts only when every piece it relies on is there: stream-json both ways, approvals routed to our tool,
|
|
78
|
+
// the session id chosen before the start (so the steered ledger names it first), and an asking mode.
|
|
79
|
+
const usable = Boolean(f.askMode && f.streamJson && f.permissionTool && f.mcpConfig && f.sessionId && f.disallowed && f.settingSources);
|
|
80
|
+
const capabilities = usable
|
|
81
|
+
? { ...NO, start: true, prompt: true, stop: true, structured_events: true, resume_by_id: f.resume, permission_modes: f.planMode ? ["ask", "plan"] : ["ask"], approvals: "structured",
|
|
82
|
+
// A live steer needs the replay that confirms it was read; the interrupt is stream-json's control request (2.1.286).
|
|
83
|
+
steer: true, steer_mode: f.replay ? "live" : "queued", interrupt: f.replay }
|
|
84
|
+
: NO;
|
|
85
|
+
const aliases = claudeAliases(help);
|
|
86
|
+
const models = aliases.length ? { models: aliases, models_status: "listed", models_at: now } : { models: null, models_status: "not_listed", models_at: null };
|
|
87
|
+
return { adapter: "claude-code", mode: "structured", installed: true, version: version ? version.trim().slice(0, 200) : null, signed_in: null, capabilities, ...models, default_model: null };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function listModels(adapter, file, env, now) {
|
|
91
|
+
const help = adapter === "codex" ? probe(file, ["debug", "--help"], env) : probe(file, ["--help"], env);
|
|
92
|
+
if (!help || !/^\s+models\b/m.test(help)) return { models: null, models_status: "not_listed", models_at: null };
|
|
93
|
+
const out = adapter === "codex" ? probe(file, ["debug", "models"], env, 20_000) : probe(file, ["models"], env, 20_000);
|
|
94
|
+
if (out === null) return { models: null, models_status: "lister_failed", models_at: null };
|
|
95
|
+
let names = [];
|
|
96
|
+
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 }; } }
|
|
97
|
+
else names = out.split("\n").map((l) => l.trim()).filter((l) => l && !/\s/.test(l));
|
|
98
|
+
const models = [...new Set(names.filter((n) => typeof n === "string" && n.length > 0 && n.length <= 128))].slice(0, P.MAX_MODELS_PER_ADAPTER);
|
|
99
|
+
return { models, models_status: "listed", models_at: now };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
let cache = null;
|
|
103
|
+
/** Every known agent: installed or not, version, capabilities, models. `refresh` re-runs the probes and the listers. */
|
|
104
|
+
export function inventory({ env = process.env, refresh = false, now = Date.now() } = {}) {
|
|
105
|
+
if (cache && !refresh) return cache;
|
|
106
|
+
const reports = [], features = {};
|
|
107
|
+
for (const [adapter, bin] of Object.entries(AGENTS)) {
|
|
108
|
+
const file = findOnPath(bin, env.PATH);
|
|
109
|
+
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; }
|
|
110
|
+
const version = probe(file, ["--version"], env);
|
|
111
|
+
if (adapter === "claude-code") { const help = probe(file, ["--help"], env); features["claude-code"] = claudeFeatures(help); reports.push(claudeReport(version, help, now)); continue; }
|
|
112
|
+
// Codex (2026-11-07): its app-server, when this version has one (remote-adapter-codex.mjs); models from `codex debug models`.
|
|
113
|
+
const codex = adapter === "codex" ? codexReport(version, probe(file, ["app-server", "--help"], env)) : null;
|
|
114
|
+
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 });
|
|
115
|
+
}
|
|
116
|
+
for (const report of reports) {
|
|
117
|
+
const checked = P.validateAdapterReport(report);
|
|
118
|
+
if (!checked.ok) throw new Error(`inventory: ${report.adapter}: ${checked.detail}`);
|
|
119
|
+
}
|
|
120
|
+
// Claude Code in a terminal (release 19): tmux on its own socket. Kept beside the reports, sent only when turned on (offered).
|
|
121
|
+
const tmux = findOnPath("tmux", env.PATH), claude = reports.find((r) => r.adapter === "claude-code");
|
|
122
|
+
const terminal = terminalReport({ claude: claude?.installed ? { ...claude, features: features["claude-code"] } : null, tmux: tmux ? tmuxVersion(probe(tmux, ["-V"], env)) : null });
|
|
123
|
+
const checkedTerminal = P.validateAdapterReport(terminal);
|
|
124
|
+
if (!checkedTerminal.ok) throw new Error(`inventory: claude-code (terminal): ${checkedTerminal.detail}`);
|
|
125
|
+
cache = { reports, features, terminal, files: { ...Object.fromEntries(Object.keys(AGENTS).map((a) => [a, findOnPath(AGENTS[a], env.PATH)])), tmux }, at: now };
|
|
126
|
+
return cache;
|
|
127
|
+
}
|
|
128
|
+
export const adapterOf = (inv, id) => inv.reports.find((r) => r.adapter === id);
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* What this computer OFFERS a phone (review 2026-11-07, P1-3): Codex runs the reads it deems safe without asking, so
|
|
132
|
+
* a phone's prompt could have it read a secret file before the computer can refuse it. Codex is offered only after the
|
|
133
|
+
* person turned it on at the keyboard (`worktrust remote codex on`, settings.codex), the gap stated; until then it is
|
|
134
|
+
* listed as installed and offered nothing.
|
|
135
|
+
*/
|
|
136
|
+
export function offered(inv, settings) {
|
|
137
|
+
const reports = settings?.codex === true ? inv.reports : inv.reports.map((r) => (r.adapter === "codex" && r.capabilities.start ? { ...r, capabilities: NO } : r));
|
|
138
|
+
// Terminal sessions (release 19) only after `worktrust remote terminal on`: an older phone refuses a second report of one adapter.
|
|
139
|
+
// Typing from a phone only on a screen detector whose fixtures were recorded from the real agent (remote-screen-states.mjs).
|
|
140
|
+
// Answering its dialogs from a phone (screen-hash approvals) needs the same: approvals "screen" only then.
|
|
141
|
+
const terminal = inv.terminal?.capabilities.start && typingTrusted("claude-code") ? { ...inv.terminal, capabilities: { ...inv.terminal.capabilities, prompt: true, approvals: "screen" } } : inv.terminal;
|
|
142
|
+
return { ...inv, reports: settings?.terminal === true && terminal ? [...reports, terminal] : reports };
|
|
143
|
+
}
|
|
@@ -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
|
+
}
|