worktrust 0.11.7 → 0.11.9
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/CHANGELOG.md +380 -0
- package/LICENSE +2 -0
- package/README.md +213 -307
- package/cli-colour.mjs +86 -0
- package/cli-menu-remote.mjs +131 -55
- package/cli-menu.mjs +245 -68
- package/engine-release.json +1 -1
- package/node-guide.mjs +134 -0
- package/package-release.json +1 -1
- package/package.json +4 -1
- package/remote-cli.mjs +2 -1
- package/worktrust.mjs +61 -23
package/cli-menu.mjs
CHANGED
|
@@ -8,63 +8,142 @@
|
|
|
8
8
|
* Each item runs the direct command it shows in its muted line, as a child of this CLI with the terminal handed over
|
|
9
9
|
* (io.runCli), so people learn the short form and every command keeps its own questions and its own guards. Keys: ↑/↓
|
|
10
10
|
* move, Enter opens, Esc or ← goes back one level, q quits from the top, 1 to 9 jump, Ctrl+C quits. Raw mode and the
|
|
11
|
-
* cursor are restored on every way out (quit, Ctrl+C, an error).
|
|
11
|
+
* cursor are restored on every way out (quit, Ctrl+C, an error).
|
|
12
|
+
*
|
|
13
|
+
* 0.11.8 (owner, 2026-11-13): Update comes first and says whether there is something to update; every item carries one plain
|
|
14
|
+
* sentence under it; the menu is redrawn IN PLACE (createTerminal) and never left in the scrollback; colours carry meaning
|
|
15
|
+
* and are off wherever cli-colour.mjs says so (NO_COLOR, --no-color, a pipe). A terminal without cursor addressing
|
|
16
|
+
* (TERM=dumb) gets no menu: the bare command runs as it always did.
|
|
17
|
+
*
|
|
18
|
+
* 0.11.9 (owner, 2026-11-14): a computer that is NOT connected gets a short menu (firstItems: Connect, Preserve, Help, Quit),
|
|
19
|
+
* and the full one the moment Connect succeeds, without running anything again (menuLoop reads the state after every command).
|
|
20
|
+
* And an Update with nothing to update is still drawn, dimmed and in words, and cannot be chosen (updateNote's `settled`).
|
|
21
|
+
* ONE ROW PER ITEM (owner, 2026-11-14: "the text under 1 is annoying"): number, action, command, explanation on one line
|
|
22
|
+
* where the terminal is wide enough, else the chosen row's explanation on one fixed line under the list (menuFrame). No row
|
|
23
|
+
* moves when the choice moves. A ROW THAT CANNOT BE CHOSEN is one mechanism for every menu: `disabled`, with `quiet`, the
|
|
24
|
+
* line its digit answers; the arrows pass it, it is dimmed, and its words say why (a note beside its name), never colour alone.
|
|
25
|
+
* Esc quits at the top like q and goes back one level below it. The head of a connected computer is a summary (headerLines):
|
|
26
|
+
* account, this computer, Remote Agent and its connections, and what this computer shares, from local files only.
|
|
12
27
|
*/
|
|
13
28
|
import { emitKeypressEvents } from "node:readline";
|
|
14
29
|
import { createInterface } from "node:readline/promises";
|
|
15
|
-
import {
|
|
30
|
+
import { busyWith, clip, coloursFor, visibleLength } from "./cli-colour.mjs";
|
|
31
|
+
import { loadIdentity, loadPhones, loadSettings } from "./remote-store.mjs";
|
|
16
32
|
|
|
17
33
|
/** Whether bare `npx worktrust` opens the menu here. Pure: the caller passes what it knows. */
|
|
18
|
-
export function menuWanted({ args = [], env = {}, stdinTTY = false, stdoutTTY = false, agentShell = null } = {}) {
|
|
34
|
+
export function menuWanted({ args: given = [], env = {}, stdinTTY = false, stdoutTTY = false, agentShell = null } = {}) {
|
|
35
|
+
const args = given.filter((arg) => arg !== "--no-color" && arg !== "--no-colour"); // how it looks, not what it does
|
|
19
36
|
if (args.length !== 0 || !stdinTTY || !stdoutTTY || agentShell) return false;
|
|
20
37
|
if (env.WORKTRUST_MENU === "off" || env.WORKTRUST_RELAYED === "1" || env.WORKTRUST_HOOK_INPUT || env.WORKTRUST_MCP_TOKEN) return false;
|
|
38
|
+
if (env.TERM === "dumb") return false; // no cursor addressing: the menu could only be printed again and again
|
|
21
39
|
return true;
|
|
22
40
|
}
|
|
23
41
|
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
export const muted = (text) => paint(
|
|
27
|
-
const strong = (text) => paint("1", text);
|
|
28
|
-
const chosen = (text) => (colour() ? `\x1b[7m${text}\x1b[0m` : `> ${text}`);
|
|
42
|
+
/** The menu's painters: by this process's own terminal, environment and arguments (cli-colour.mjs colourWanted). */
|
|
43
|
+
let paint = coloursFor(process.stdout);
|
|
44
|
+
export const muted = (text) => paint.dim(text);
|
|
29
45
|
|
|
30
|
-
/**
|
|
46
|
+
/**
|
|
47
|
+
* The terminal, in raw mode while a list waits for a key; restore() always puts it back.
|
|
48
|
+
*
|
|
49
|
+
* THE MENU IS REDRAWN IN PLACE (0.11.8, owner 2026-11-13: the whole menu stood four times in the scrollback before the chosen
|
|
50
|
+
* command ran). 0.11.7 cleared the screen for every redraw, and a terminal keeps a cleared screen in its scrollback: each arrow
|
|
51
|
+
* key and each return from a command left one more copy. Now draw() remembers how many lines the menu took and the next
|
|
52
|
+
* draw goes the cursor up that many, clears to the end of the screen and writes the new lines, in ONE write (no flicker).
|
|
53
|
+
* erase() takes the menu's own lines away before anything else speaks (a command's output, a question), so what stays in
|
|
54
|
+
* the scrollback is what happened, never a menu. A resize cannot trust the count (lines may have wrapped): reset() clears
|
|
55
|
+
* the visible screen once and the menu is drawn once. No line ever wraps: draw() cuts each to the terminal's width.
|
|
56
|
+
*/
|
|
31
57
|
export function createTerminal(input = process.stdin, output = process.stdout) {
|
|
32
|
-
let raw = false;
|
|
33
|
-
const
|
|
34
|
-
const
|
|
35
|
-
const
|
|
58
|
+
let raw = false, drawn = 0;
|
|
59
|
+
const size = () => ({ columns: output.columns || 80, rows: output.rows || 24 });
|
|
60
|
+
const up = () => (drawn > 0 ? `\x1b[${drawn}A\r\x1b[J` : "");
|
|
61
|
+
const draw = (lines) => { const { columns } = size(); output.write(`${up()}${lines.map((line) => clip(line, columns - 1)).join("\n")}\n`); drawn = lines.length; };
|
|
62
|
+
const erase = () => { if (drawn > 0) output.write(up()); drawn = 0; };
|
|
63
|
+
const reset = () => { output.write("\x1b[H\x1b[J"); drawn = 0; };
|
|
64
|
+
/** Text that is not the menu (a reason, a result): the menu's lines go first, and the next draw starts below it. */
|
|
65
|
+
const write = (text) => { erase(); output.write(text); };
|
|
66
|
+
const enter = () => { emitKeypressEvents(input); if (input.isTTY && !raw) { input.setRawMode(true); raw = true; } input.resume(); output.write("\x1b[?25l"); };
|
|
67
|
+
const restore = () => { if (input.isTTY && raw) { try { input.setRawMode(false); } catch { /* gone */ } raw = false; } input.pause(); output.write("\x1b[?25h"); };
|
|
68
|
+
/** The next key, or { name: "resize" } once the terminal's size has settled (many resize events, one answer). */
|
|
36
69
|
const key = () => new Promise((resolve) => {
|
|
37
|
-
|
|
38
|
-
input.
|
|
70
|
+
let timer = null;
|
|
71
|
+
const done = (value) => { input.off("keypress", onKey); output.off?.("resize", onResize); clearTimeout(timer); resolve(value); };
|
|
72
|
+
const onKey = (str, k = {}) => done({ str, name: k.name ?? str, ctrl: Boolean(k.ctrl) });
|
|
73
|
+
const onResize = () => { clearTimeout(timer); timer = setTimeout(() => done({ name: "resize" }), 60); };
|
|
74
|
+
input.on("keypress", onKey);
|
|
75
|
+
output.on?.("resize", onResize);
|
|
39
76
|
});
|
|
40
|
-
|
|
77
|
+
/** A real key: a resize while "Press any key" stands is not one. */
|
|
78
|
+
const anyKey = async () => { for (;;) { const k = await key(); if (k.name !== "resize") return k; } };
|
|
79
|
+
return { write, draw, erase, reset, size, enter, restore, key, anyKey };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const wrap = (text, width) => { const out = []; let line = ""; for (const word of text.split(" ")) { if (line && line.length + 1 + word.length > width) { out.push(line); line = word; } else line = line ? `${line} ${word}` : word; } return line ? [...out, line] : out; };
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* The lines of one list, as text. Pure: `view` is what choose holds, `columns` and `rows` the terminal's size. ONE ROW PER
|
|
86
|
+
* ITEM (0.11.9), and the rows never move when the choice moves:
|
|
87
|
+
* wide four columns on one line: number, action, command (dim), explanation (dim). Only when EVERY row's explanation
|
|
88
|
+
* fits whole (no sentence is ever cut), so the form does not depend on which row is chosen.
|
|
89
|
+
* narrower three columns, and the chosen row's explanation on fixed lines under the list, above the keys: as many lines as
|
|
90
|
+
* the longest explanation of this list needs at this width, always, so nothing jumps. 80 columns is this form.
|
|
91
|
+
* < 60 the command column goes too; and at any width a command that would not fit whole on its row is left out.
|
|
92
|
+
* The chosen item is marked by `>` and by its ground, never by colour alone. `asked` is the row whose digit was pressed
|
|
93
|
+
* though it cannot be chosen: its `quiet` line (and its explanation, where that is not on its row) is said under the list.
|
|
94
|
+
* A list taller than the terminal shows the items around the chosen one: a menu taller than the screen could not be redrawn in place.
|
|
95
|
+
*/
|
|
96
|
+
export function menuFrame({ header = [], title = null, items, at = 0, ticked = new Set(), multi = false, top = false, footer = null, asked = null }, { rows = 24, columns = 100, p = paint } = {}) {
|
|
97
|
+
const width = columns - 1;
|
|
98
|
+
const heads = (lines) => [...lines, ...(title ? ["", ` ${p.bold(title)}`] : []), ""];
|
|
99
|
+
const keys = ` ${p.dim(footer ?? (multi ? "↑/↓ move · Space tick · Enter confirm · Esc back" : `↑/↓ move · Enter open · Esc ${top ? "quit" : "back"} · 1-9 jump`))}`;
|
|
100
|
+
const box = (item) => (multi && item.tick ? `[${ticked.has(item.label) ? "x" : " "}] ` : "");
|
|
101
|
+
const size = (item) => visibleLength(`${box(item)}${item.label}${item.note ? ` · ${item.note.text}` : ""}`);
|
|
102
|
+
// The commands stand in one column beside the names (a name longer than 64 pushes only its own command; a table row is a name).
|
|
103
|
+
const nameCol = Math.min(64, Math.max(0, ...items.map(size))), hintCol = Math.max(0, ...items.map((item) => (item.hint ?? "").length));
|
|
104
|
+
const upTo = (item) => 6 + Math.max(nameCol, size(item)) + 3; // where this row's command starts
|
|
105
|
+
const wide = columns >= 60 && items.every((item) => !item.info || upTo(item) + hintCol + 3 + item.info.length <= width);
|
|
106
|
+
const line = (item, i) => {
|
|
107
|
+
const label = ` ${i < 9 ? i + 1 : " "} ${box(item)}${item.label} `;
|
|
108
|
+
const note = item.note ? `· ${p[item.note.tone]?.(item.note.text) ?? item.note.text}` : "";
|
|
109
|
+
const name = i === at ? p.inverse(label) : item.disabled ? p.dim(label) : p.bold(label);
|
|
110
|
+
const gap = " ".repeat(Math.max(0, nameCol - size(item)) + (item.note ? 3 : 2)); // a name without a note ends in its own space
|
|
111
|
+
if (wide) return `${i === at ? ">" : " "} ${name}${note}${gap}${p.dim(item.info ? (item.hint ?? "").padEnd(hintCol) : item.hint ?? "")}${item.info ? ` ${p.dim(item.info)}` : ""}`;
|
|
112
|
+
return `${i === at ? ">" : " "} ${name}${note}${columns >= 60 && item.hint && upTo(item) + item.hint.length <= width ? `${gap}${p.dim(item.hint)}` : ""}`;
|
|
113
|
+
};
|
|
114
|
+
// Under the list: what the chosen row does or, after the digit of a row that cannot be chosen, why not.
|
|
115
|
+
const told = (item, refused) => [refused ? item.quiet : null, item.info].filter(Boolean).join(" ");
|
|
116
|
+
const need = Math.max(1, ...items.map((item) => wrap(told(item, item.disabled), width - 2).length));
|
|
117
|
+
const said = wrap(asked === null ? told(items[at], false) : told(items[asked], true), width - 2).map((part) => ` ${part}`);
|
|
118
|
+
const foot = wide ? ["", keys, ...(asked === null ? [] : [` ${p.dim(items[asked].quiet ?? items[asked].info ?? "")}`])] : ["", ...said, ...Array(Math.max(0, need - said.length)).fill(""), "", keys];
|
|
119
|
+
// A terminal too short for the list under the whole head keeps the head's first line only: the list matters more than the summary.
|
|
120
|
+
const all = items.map(line), fits = (lines) => all.length <= rows - 1 - lines.length - foot.length;
|
|
121
|
+
const head = fits(heads(header)) ? heads(header) : heads(header.slice(0, 1)), room = Math.max(3, rows - 1 - head.length - foot.length);
|
|
122
|
+
if (all.length <= room) return [...head, ...all, ...foot];
|
|
123
|
+
const span = Math.max(1, room - 2), from = Math.max(0, Math.min(at - Math.floor(span / 2), items.length - span));
|
|
124
|
+
return [...head, ` ${p.dim(from > 0 ? "↑ more" : "")}`, ...all.slice(from, from + span), ` ${p.dim(from + span < items.length ? "↓ more" : "")}`, ...foot];
|
|
41
125
|
}
|
|
42
126
|
|
|
43
127
|
/**
|
|
44
128
|
* One list: → { item } (Enter or a digit), "back" (Esc, ←), "quit" (q at the top, Ctrl+C). `items`: { label, hint?, info?,
|
|
45
|
-
* disabled? }.
|
|
129
|
+
* note?, disabled?, quiet? }. A disabled item is never chosen: the arrows pass it, the list opens on the first item that can
|
|
130
|
+
* be, and its digit only says its `quiet` line. `multi`: Space ticks an item that has `tick: true`; the ticked items come back as `ticked`. `header`:
|
|
131
|
+
* the lines, or a function giving them, asked at every draw so a state a command just changed shows at once.
|
|
46
132
|
*/
|
|
47
133
|
export async function choose(term, { header = [], title, items, top = false, multi = false, footer = null }) {
|
|
48
134
|
let at = Math.max(0, items.findIndex((i) => !i.disabled));
|
|
49
135
|
const ticked = new Set(items.filter((i) => i.ticked).map((i) => i.label));
|
|
136
|
+
let asked = null; // the row whose digit was pressed though it cannot be chosen (0.11.9), said under the list until the next key
|
|
50
137
|
for (;;) {
|
|
51
|
-
term.
|
|
52
|
-
for (const line of header) term.write(`${line}\n`);
|
|
53
|
-
if (title) term.write(`\n ${strong(title)}\n`);
|
|
54
|
-
term.write("\n");
|
|
55
|
-
items.forEach((item, i) => {
|
|
56
|
-
const n = i < 9 ? `${i + 1}` : " ";
|
|
57
|
-
const box = multi && item.tick ? `[${ticked.has(item.label) ? "x" : " "}] ` : "";
|
|
58
|
-
const label = `${n} ${box}${item.label}`;
|
|
59
|
-
term.write(` ${i === at ? chosen(` ${label} `) : item.disabled ? muted(` ${label} `) : ` ${label} `}\n`);
|
|
60
|
-
if (item.hint) term.write(` ${muted(item.hint)}\n`);
|
|
61
|
-
});
|
|
62
|
-
term.write(`\n ${muted(footer ?? (multi ? "↑/↓ move · Space tick · Enter confirm · Esc back" : `↑/↓ move · Enter open · ${top ? "q quit" : "Esc back"} · 1-9 jump`))}\n`);
|
|
138
|
+
term.draw(menuFrame({ header: typeof header === "function" ? header() : header, title, items, at, ticked, multi, top, footer, asked }, term.size()));
|
|
63
139
|
const k = await term.key();
|
|
140
|
+
if (k.name === "resize") { term.reset(); continue; }
|
|
141
|
+
asked = /^[1-9]$/.test(k.str ?? "") && items[Number(k.str) - 1]?.disabled ? Number(k.str) - 1 : null;
|
|
64
142
|
if (k.ctrl && k.name === "c") return "quit";
|
|
65
143
|
if (k.name === "up" || k.name === "k") { do at = (at - 1 + items.length) % items.length; while (items[at].disabled); continue; }
|
|
66
144
|
if (k.name === "down" || k.name === "j") { do at = (at + 1) % items.length; while (items[at].disabled); continue; }
|
|
67
|
-
if (k.name === "escape"
|
|
145
|
+
if (k.name === "escape") return top ? "quit" : "back"; // 0.11.9: Esc leaves the top like q (a lone Esc: readline tells it from an arrow's sequence)
|
|
146
|
+
if (k.name === "left") { if (!top) return "back"; continue; }
|
|
68
147
|
if (k.name === "q" && top) return "quit";
|
|
69
148
|
if (multi && k.name === "space" && items[at].tick) { ticked.has(items[at].label) ? ticked.delete(items[at].label) : ticked.add(items[at].label); continue; }
|
|
70
149
|
if (/^[1-9]$/.test(k.str ?? "") && items[Number(k.str) - 1] && !items[Number(k.str) - 1].disabled) { at = Number(k.str) - 1; if (!multi) return { item: items[at] }; continue; }
|
|
@@ -74,6 +153,7 @@ export async function choose(term, { header = [], title, items, top = false, mul
|
|
|
74
153
|
|
|
75
154
|
/** A line of text typed at the keyboard (out of raw mode), the default already there to edit; null when left empty. */
|
|
76
155
|
export async function typed(term, question, value = "") {
|
|
156
|
+
term.erase();
|
|
77
157
|
term.restore();
|
|
78
158
|
const prompt = createInterface({ input: process.stdin, output: process.stdout });
|
|
79
159
|
const answer = prompt.question(` ${question} `);
|
|
@@ -86,65 +166,162 @@ export async function typed(term, question, value = "") {
|
|
|
86
166
|
/** While a command runs, Ctrl+C is the command's (it reaches the child too); the menu stays. */
|
|
87
167
|
let busy = false;
|
|
88
168
|
|
|
89
|
-
/**
|
|
169
|
+
/**
|
|
170
|
+
* Run one direct command with the terminal handed over, then wait for a key before the menu comes back. The menu's own
|
|
171
|
+
* lines are taken away first, so the scrollback reads: the command, its output, how it ended. The menu is then drawn once
|
|
172
|
+
* below (the next draw starts fresh).
|
|
173
|
+
*/
|
|
90
174
|
export async function runShown(term, io, args, label = null) {
|
|
91
175
|
term.restore();
|
|
92
176
|
busy = true;
|
|
93
|
-
term.
|
|
94
|
-
process.stdout.write(` ${muted(`› npx worktrust ${args.join(" ")}`.trimEnd())}${label ? ` ${label}` : ""}\n\n`);
|
|
177
|
+
term.write(` ${muted(`› npx worktrust ${args.join(" ")}`.trimEnd())}${label ? ` ${label}` : ""}\n\n`);
|
|
95
178
|
let code = 1;
|
|
96
179
|
try { code = await io.runCli(args); } catch { code = 1; } finally { busy = false; }
|
|
97
180
|
term.enter();
|
|
98
|
-
term.write(`\n ${
|
|
99
|
-
const k = await term.
|
|
181
|
+
term.write(`\n ${code === 0 ? paint.green("✓ Done.") : paint.yellow("! It ended with a message above.")} ${muted("Press any key for the menu.")}\n`);
|
|
182
|
+
const k = await term.anyKey();
|
|
100
183
|
return !(k.ctrl && k.name === "c");
|
|
101
184
|
}
|
|
102
185
|
|
|
103
|
-
/**
|
|
186
|
+
/** What the Remote Agent item says where this Node has no WebSocket; Enter opens the ways forward (node-guide.mjs). */
|
|
187
|
+
export const REMOTE_NEEDS = "Needs Node 22.4 or later. Enter shows the ways to get it.";
|
|
188
|
+
|
|
189
|
+
const newer = (a, b) => { const x = String(a).split(".").map(Number), y = String(b).split(".").map(Number); for (let i = 0; i < 3; i += 1) if (x[i] !== y[i]) return x[i] > y[i]; return false; };
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* What the Update item says beside its name (owner, 2026-11-13), from the state read again after every command, so it is
|
|
193
|
+
* true the moment an update finishes: this computer's installed version behind this CLI's ("0.11.7 → 0.11.8 available"),
|
|
194
|
+
* a newer CLI published than the one running, or "up to date (0.11.8)". Null when this computer is not connected.
|
|
195
|
+
*
|
|
196
|
+
* THREE STATES, NEVER TWO (0.11.9, owner 2026-11-14: "now you can do the update twice"). Something to update; nothing to
|
|
197
|
+
* update and KNOWN so (`settled`: this computer runs this CLI's version and the registry answered that none is newer), which
|
|
198
|
+
* is the one state where the item cannot be chosen; and not known (the registry did not answer, or this computer's version
|
|
199
|
+
* is not this CLI's): that one says what it knows, claims no "up to date", and can still be chosen.
|
|
200
|
+
*/
|
|
201
|
+
export function updateNote(state) {
|
|
202
|
+
if (!state.connected) return null;
|
|
203
|
+
if (state.installed && newer(state.version, state.installed)) return { text: `${state.installed} → ${state.version} available`, tone: "yellow", behind: "computer" };
|
|
204
|
+
if (state.latest && newer(state.latest, state.version)) return { text: `${state.version} → ${state.latest} available`, tone: "yellow", behind: "cli" };
|
|
205
|
+
if (!state.latestKnown) return { text: "newest not checked", tone: "dim", behind: null };
|
|
206
|
+
return { text: `up to date (${state.version})`, tone: state.installed === state.version ? "dim" : "green", behind: null, settled: state.installed === state.version };
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Remote Agent here, in one word, with its confirmed connections; from this computer's own files. A file that cannot be read
|
|
211
|
+
* is "not known", never "not set up" (remote-store readJson refuses an unreadable or non-private one).
|
|
212
|
+
*/
|
|
213
|
+
export function remoteState() {
|
|
214
|
+
try { const s = loadSettings(), links = loadPhones().confirmed.length; return { links, word: !loadIdentity() ? "not set up" : !s.enabled ? "off" : s.paused ? "paused" : "approved" }; }
|
|
215
|
+
catch { return { links: null, word: "not known" }; }
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The head. Not connected: the version and the one fact. Connected (0.11.9, owner 2026-11-14): a summary, label and value,
|
|
220
|
+
* of what this computer's own files say; never the key, never a secret; a date not recorded is a dash, a state that could
|
|
221
|
+
* not be read is "not known". `state`: version, latest, account, host, since, hook, door, apps (worktrust.mjs).
|
|
222
|
+
*/
|
|
104
223
|
export function headerLines(state) {
|
|
105
|
-
const
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
224
|
+
const title = ` ${paint.bold(`WorkTrust CLI ${state.version}`)}${state.latest ? ` ${paint.yellow(`! ${state.latest} is out: quit, then npx -y worktrust@latest`)}` : ""}`;
|
|
225
|
+
if (!state.connected) return [title, " Not connected yet"];
|
|
226
|
+
const row = (label, value) => ` ${paint.dim(label.padEnd(14))} ${value}`, remote = remoteState(), host = String(state.host ?? "this computer");
|
|
227
|
+
const known = (value, yes, no) => (value === true ? yes : value === false ? no : "not known");
|
|
228
|
+
return [
|
|
229
|
+
title,
|
|
230
|
+
row("Account", state.account ?? "not recorded: run Check this computer"),
|
|
231
|
+
row("This computer", `${host.length > 28 ? `${host.slice(0, 27)}…` : host} · connected since ${/^\d{4}-\d{2}-\d{2}/.test(String(state.since ?? "")) ? String(state.since).slice(0, 10) : "-"}`),
|
|
232
|
+
row("Remote Agent", remote.links === null || ["not set up", "off"].includes(remote.word) ? remote.word : `${remote.word}, ${remote.links} connection${remote.links === 1 ? "" : "s"}`),
|
|
233
|
+
row("Sharing", `session hook ${known(state.hook, "on", "not installed")} · AI apps ${state.door === "off" ? "off" : state.door === "on" ? `on${Number.isInteger(state.apps) ? ` (${state.apps})` : ""}` : "not known"} · Remote Agent ${remote.word === "not set up" ? "off" : remote.word}`),
|
|
234
|
+
];
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const HELP = (open) => ({ label: "Help · all commands", hint: "npx worktrust help", info: "Lists all commands. npx -y worktrust skips npm's question.", run: () => open(["help"]) });
|
|
238
|
+
const QUIT = { label: "Quit", hint: "q", info: "Leaves the menu. Nothing keeps running.", quit: true };
|
|
239
|
+
const PRESERVE = (sub, info) => ({ label: "Preserve evidence ›", hint: "npx worktrust preserve …", info, run: () => sub.preserve?.() });
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* THE FIRST MENU (0.11.9, owner 2026-11-14): what a computer that is not connected can do, and nothing that needs a
|
|
243
|
+
* connected one (no Update, Remote Agent, Import, AI apps switch, Status, Disconnect). Preserve needs no account, no key
|
|
244
|
+
* and no network at any of its levels (preserve.mjs; worktrust.mjs loads no key for it), so all of it stays.
|
|
245
|
+
*/
|
|
246
|
+
export function firstItems(open = () => true, sub = {}) {
|
|
112
247
|
return [
|
|
113
|
-
|
|
114
|
-
|
|
248
|
+
{ label: "Connect this computer", hint: "npx worktrust connect", info: "Asks before it writes; your browser signs in to WorkTrust.", run: () => open(["connect"]) },
|
|
249
|
+
PRESERVE(sub, "Keep your AI history here. No account; nothing is sent."),
|
|
250
|
+
HELP(open), QUIT,
|
|
115
251
|
];
|
|
116
252
|
}
|
|
117
253
|
|
|
118
|
-
/**
|
|
254
|
+
/** Why the first menu still stands after Connect ran, in one line, by how the command ended (0 without a key: a No or a dry run). */
|
|
255
|
+
export function connectReason(code) {
|
|
256
|
+
if (code === 0) return "Connect stopped before the sign-in; nothing was written. 1 tries again.";
|
|
257
|
+
if (code === 130) return "Connect was cancelled; this computer is not connected. 1 tries again.";
|
|
258
|
+
return "Connect ended with the message above; not connected. 1 tries again.";
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* The top list (owner, 2026-11-13): Update first, then Check, then the rest as before. Pure but for the `run` closures.
|
|
263
|
+
* `open(args)` runs one direct command; `sub` holds the deeper levels.
|
|
264
|
+
*/
|
|
265
|
+
export function topItems(state, open = () => true, sub = {}) {
|
|
266
|
+
if (!state.connected) return firstItems(open, sub);
|
|
267
|
+
const note = updateNote(state);
|
|
268
|
+
const same = state.installed === state.version; // then `update` changes nothing and says so (worktrust.mjs update, 0.11.9)
|
|
269
|
+
const updateInfo = note.behind === "cli" ? "Newer CLI: quit, then npx -y worktrust@latest update."
|
|
270
|
+
: note.behind === "computer" ? `Brings this computer from ${state.installed} to ${state.version}. Your key stays.`
|
|
271
|
+
: note.settled ? "Nothing to update: this computer runs the latest version."
|
|
272
|
+
: same ? "Newest version not checked. Enter changes nothing here."
|
|
273
|
+
: "Sets up this computer's hook and AI-app doors again.";
|
|
274
|
+
return [
|
|
275
|
+
{ label: "Update WorkTrust", note, hint: "npx worktrust update", info: updateInfo, run: () => open(["update"]), ...(note.settled ? { disabled: true, quiet: "Already up to date." } : {}) },
|
|
276
|
+
{ label: "Check this computer", hint: "npx worktrust", info: "Shows what is coupled here and finishes what waits.", run: () => open([]) },
|
|
277
|
+
// Node before 22.4 has no WebSocket (0.11.8): the item stays, says why, and Enter opens the ways forward, not the levels.
|
|
278
|
+
state.remoteBlocked
|
|
279
|
+
? { label: "Remote Agent", note: { text: "needs Node 22.4+", tone: "yellow" }, hint: "npx worktrust remote …", info: REMOTE_NEEDS, run: () => open(["remote"]) }
|
|
280
|
+
: { label: "Remote Agent ›", hint: "npx worktrust remote …", info: "Steer this computer's agents from your phone.", run: () => sub.remote?.() },
|
|
281
|
+
{ label: "Import earlier history ›", hint: "npx worktrust history …", info: "Send earlier sessions as history. Each way asks first.", run: () => sub.history?.() },
|
|
282
|
+
PRESERVE(sub, "Keep your AI history on this computer. Nothing is sent."),
|
|
283
|
+
{ label: "Sharing ›", hint: "npx worktrust mcp …", info: "What this computer sends, and the switches for it.", run: () => sub.sharing?.() },
|
|
284
|
+
{ label: "Status", hint: "npx worktrust status", info: "Shows the key, the hook and the door. It only reads.", run: () => open(["status"]) },
|
|
285
|
+
{ label: "Disconnect this computer", hint: "npx worktrust disconnect", info: "Takes WorkTrust out and ends this computer's key. It asks.", run: () => open(["disconnect"]) },
|
|
286
|
+
HELP(open), QUIT,
|
|
287
|
+
];
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* The menu's loop, apart from the process (0.11.9) so a test can drive it. The state is read again after every command: the
|
|
292
|
+
* version line and the Update item say the new state the moment an update ends, and the first menu becomes the full one the
|
|
293
|
+
* moment Connect leaves a key. When Connect ran and there is still no key, the first menu stays and its header says why.
|
|
294
|
+
*/
|
|
295
|
+
export async function menuLoop(term, io, levels) {
|
|
296
|
+
let last = null, state = null; // the command the top level ran last and how it ended; this computer's state as last read
|
|
297
|
+
const read = async () => (state = { ...(await busyWith("Reading this computer's state", () => io.state())), remoteBlocked: typeof globalThis.WebSocket !== "function" });
|
|
298
|
+
// A deeper level reads the state again after each of its commands (inner.state), so the head above it is true at once.
|
|
299
|
+
const inner = { runCli: (args) => io.runCli(args), state: read };
|
|
300
|
+
for (;;) {
|
|
301
|
+
await read();
|
|
302
|
+
const why = !state.connected && last?.args[0] === "connect" ? connectReason(last.code) : null;
|
|
303
|
+
const header = () => [...headerLines(state), ...(why ? [` ${paint.yellow(`! ${why}`)}`] : [])];
|
|
304
|
+
const open = (args) => { const ran = { args, code: 1 }; last = ran; return runShown(term, { runCli: async (given) => (ran.code = await io.runCli(given)) }, args); };
|
|
305
|
+
const items = topItems(state, open, Object.fromEntries(["remote", "history", "preserve", "sharing"].map((name) => [name, () => levels[`${name}Menu`](term, inner, header)])));
|
|
306
|
+
const picked = await choose(term, { header, items, top: true });
|
|
307
|
+
if (picked === "quit" || picked === "back" || picked.item.quit) break;
|
|
308
|
+
last = null;
|
|
309
|
+
if ((await picked.item.run()) === false) break;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** The top of the menu. `io`: { runCli(args) → Promise<code>, state() → { version, installed, latest, latestKnown, account, connected, door, host, since, hook, apps } }. */
|
|
314
|
+
// (remoteBlocked is added here: whether this Node lacks the WebSocket Remote Agent needs.)
|
|
119
315
|
export async function runMenu(io) {
|
|
316
|
+
paint = coloursFor(process.stdout);
|
|
120
317
|
const term = createTerminal();
|
|
121
|
-
const quit = () => { term.
|
|
318
|
+
const quit = () => { term.erase(); term.restore(); };
|
|
122
319
|
const onSignal = () => { if (busy) return; quit(); process.exit(130); };
|
|
123
320
|
process.on("SIGINT", onSignal);
|
|
124
321
|
process.on("SIGTERM", onSignal);
|
|
125
322
|
try {
|
|
126
323
|
term.enter();
|
|
127
|
-
|
|
128
|
-
for (;;) {
|
|
129
|
-
const state = await io.state();
|
|
130
|
-
const header = headerLines(state);
|
|
131
|
-
const door = state.door === "off" ? "Off" : "On";
|
|
132
|
-
const items = [
|
|
133
|
-
{ label: "Check this computer", hint: state.connected ? "npx worktrust what is coupled here" : "npx worktrust connect this computer", run: () => runShown(term, io, []) },
|
|
134
|
-
{ label: "Update WorkTrust", hint: "npx worktrust update", run: () => runShown(term, io, ["update"]) },
|
|
135
|
-
{ label: "Remote Agent ›", hint: "npx worktrust remote …", run: () => remoteMenu(term, io, header) },
|
|
136
|
-
{ label: "Import earlier history ›", hint: "npx worktrust history …", run: () => historyMenu(term, io, header) },
|
|
137
|
-
{ label: "Preserve evidence ›", hint: "npx worktrust preserve …", run: () => preserveMenu(term, io, header) },
|
|
138
|
-
{ label: `WorkTrust in your AI apps: ${door}`, hint: `npx worktrust mcp ${door === "On" ? "off" : "on"} your hours stay measured by the session hook`, run: () => runShown(term, io, ["mcp", door === "On" ? "off" : "on"]) },
|
|
139
|
-
{ label: "Status", hint: "npx worktrust status", run: () => runShown(term, io, ["status"]) },
|
|
140
|
-
{ label: "Disconnect this computer", hint: "npx worktrust disconnect asks first", run: () => runShown(term, io, ["disconnect"]) },
|
|
141
|
-
{ label: "Help · all commands", hint: "npx worktrust help", run: () => runShown(term, io, ["help"]) },
|
|
142
|
-
{ label: "Quit", hint: "q", quit: true },
|
|
143
|
-
];
|
|
144
|
-
const picked = await choose(term, { header, items, top: true });
|
|
145
|
-
if (picked === "quit" || picked === "back" || picked.item.quit) break;
|
|
146
|
-
if ((await picked.item.run()) === false) break;
|
|
147
|
-
}
|
|
324
|
+
await menuLoop(term, io, await import("./cli-menu-remote.mjs"));
|
|
148
325
|
} finally {
|
|
149
326
|
process.off("SIGINT", onSignal);
|
|
150
327
|
process.off("SIGTERM", onSignal);
|
package/engine-release.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"chat-exports.mjs":"f026c5a063f62c22ba6f25474a9d9fdbb6074beebbfe1faff2a876c437a1a000","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","cli-menu-remote.mjs":"
|
|
1
|
+
{"keyId":"608168ccdef72562fc91f9c0f9f2c2d6876bece7f7362cb545b818f7947da6b5","payload":{"files":{"chat-exports.mjs":"f026c5a063f62c22ba6f25474a9d9fdbb6074beebbfe1faff2a876c437a1a000","claude-mod.mjs":"02d86b0cdddf39879efc5194c0a5be6b41456faedec28963dc123a4e88dc3942","cli-colour.mjs":"fa16b61ad179999c5c5365255182acf69bcba1eb5f5ce7b0e1e18c11f56130ae","cli-menu-remote.mjs":"4f7284911d86e4463797e7dec976c4c10f46e6fdb3053c5ad211210e1efe25e5","cli-menu.mjs":"09eed126c220ffdfba8fedd7f2730ddcbc75471c31dcb5ce066c02592aa3b3b9","commit-rules.mjs":"e94cc32a5415f6d9e978145ab9505ac4ae0bac9431e6e9104b9b37155260b51f","config-edits.mjs":"527a7674f9d52b284bfda3b8089eb4b930a709bf14aedbec7f6eef1e59ef52ee","count-behaviour.mjs":"06b0ecbc222087160dc64c0b302391631e8e799038364c317c6cd28449c5044d","credential-store.mjs":"a4b3540a61f4ce19e535c7f1d260c0d817686cd066d559a76db2ab108144abba","credential-vault-scripts.mjs":"7e42fe1db3885c2dec6f1de87bebfbefe2292d29179a68f3da87d19eb6c7704b","credential-vault.mjs":"279baabb217e2a3f170e8d7f2b271a88484531f9031c441360ea91561a70da99","export-facts.mjs":"3bbb46c80e8678b5cea7e15dcbfc456a2b48595053241c2b3cea508092f9b917","folder-picker.mjs":"daeb379626d5716f91f588064c6b4083618279320c006c177960cc93f056d96a","git-commits.mjs":"af0ed45a2a42c8e17cabfb3649a2f524dbf80230f8a6ec1c6b775fed7d34dc9c","history-outbox.mjs":"85c70389effc5b4ec9d9b33af9192314e67f47af2752515b42a7959344ce2354","history-progress.mjs":"dcc25ee94b727f2605a763349a4d8764640335d6cf0043fb6108cebeed16dcb9","log-session.mjs":"167fe3718415fe690c9e4f7a3a993520e8c652edcf61184cc14cfec2db67d7bc","node-guide.mjs":"5bf52c5028b07a80ec4d41be365eb025dfce74328f41f928a26ce6737b1f9cc4","orchestration-contract.mjs":"ec08f303a166365b99e70b675de4cfe76c6156c2567e14b5569f6d992f0231b7","orchestration-evidence.mjs":"d0d06cecf0eb08e5c6e653c62a4f45b1eddf2119c2acb8341056b34f488d214a","orchestration-report.mjs":"d4e0a9ad8e4a01b462d22c6b1866aac291565c533ff476085d3367cb6d59bc1b","package-integrity.mjs":"a8210c9494a56bfb9a5ea3d10064c7a269f0b6330c0af7c0700e706c3c0224e3","preserve-lines.mjs":"2df64a69687aa51219bf7b86b88d175cc50990fa29574b31897e41a9ebeecf43","preserve-summary.mjs":"137f781ed7021596a3f0ea67afcf2ab8616ac293f833dbb8f176e838e0ed8321","preserve.mjs":"cd111cae0f53a25a2d878a158479abfb1ace353361454843f91a16d241101d46","project-modes.mjs":"ada26e68297fbeb90e4e91d75a90fd2d7cc107b999a9702840675b5a7529463e","remote-adapter-claude-code.mjs":"6db24891f7b0c56c00b337e52f4d4aeb8c9a0413b3bf46d0fc8a45328ea71b3e","remote-adapter-codex.mjs":"d2fd6c61d9e3c4a45e9b10da1aa3c15d45c86629d6456e4a8d25ad95b13eb209","remote-adapter-opencode.mjs":"ddd7f3ec0b4ba92f4744453d60fda338b63550e3ec7b23fa3acc668df1d64eb7","remote-adapter-terminal.mjs":"9237d3747a25126fcdad42c0eab10e69393754388a6014b30fb0890b9c735888","remote-admin.mjs":"ac4d434c0a374159b27accac3fdd0324ff96ffe32227fba054cc62d00e58d35b","remote-agent-switch.mjs":"7ff5448f29f05a47d7298d730b21243a1bcf8a215b434a0c7fbf5f3cb0889041","remote-approval-bridge.mjs":"092f17b7969e4f35bea064315d04dcde1faa6a3fd3e737dcc05aece82c7a37c4","remote-approvals.mjs":"63847226e398f9eb5b8d3989ba2b2436fbedd898385eb5f2f63bbdf07fbe6852","remote-attachments.mjs":"2e9c1277329a45cf26c0c62abda632cf0ab9fad78d0504416ecee9805220e16c","remote-cdp.mjs":"70e333a1ebe845e872cc3a703a0a507391f8ce59640bdbd662bdad55eeff216b","remote-changes.mjs":"2141fece4961a5bc1bb1b046f78222812617457b1ba6452275eac6a897e62e19","remote-claude-events.mjs":"58822471203c6a1b66cf81c115c4d713657c3dea5c7b98df959f894ee5b2e704","remote-claude-progress.mjs":"2ca626d3dbc16d8d570abe1df6477b7e44ffb43c1d9145228ec5ea1928e415ca","remote-cli.mjs":"651a7f16e7475029985007ea97f4b838f8378ab620d3f3c2ab718da155fce94d","remote-coalesce.mjs":"cb0967d9cfe81e3892bcade8349d6814db98be8c2adbdb54df0b8d1b142f65d1","remote-codex-events.mjs":"58657d6070a50c837737cb85f5a1eaf9c2cbc4e1adfe3e970748ab3b2af94631","remote-connections.mjs":"e24ff04ed61647e164b6f055d4f691366f3204fe445140afc5f34abbed5d4080","remote-countdown.mjs":"85cf2d01fe5ca49895e08a3d5de346bb5e4a8dd31b9fda3fd9f9534d9e1e47cf","remote-daemon.mjs":"94d4896b0e1203f7a5bc7224a6221a36f4c20be89caee78b3ab37b9b6a2dac1d","remote-endorse.mjs":"89eda4883567176703e01e44d83e987271bc2a6134e108f517b3b213719a21f9","remote-inventory.mjs":"a8245604d41373819738eaf06ec1d2242cb5f7b2e60aa316f31d2f8742b8c70d","remote-journal.mjs":"907ebd48c53162b22dc743ef95b53c1a6be6886a7495605b5cfa820b8de9d330","remote-live-preview.mjs":"faa70f9260ac05037204c2a0c3facf4ffe42f68408948390b341b453a2932289","remote-opencode-events.mjs":"3108375501ead2c2c78bce1435cc2a9fe6d2af1d7ff1fb42e12ff3e0f5d9af9c","remote-opencode-session.mjs":"681b201d833a7d7d025122b3a79663bcdc0a989aefd39d8018a28113d8810caf","remote-pairing.mjs":"d8c2aba394fe73d850ea000c758e6b926c87b122eaf5c6aa92ec1183e90f90e1","remote-pipeline-config.mjs":"00cde6a61ce21144c51ac56fce42fee159aa9dba6586218a7ea790ce4a6bd40b","remote-pipeline-parsers.mjs":"43ca0d332d7bc883c4759a754a555815ae5dfe133446b91ba9f2e48a350fa20f","remote-pipeline.mjs":"b856ead989b29ddb618ef69bbacd104bae2b02c9d1c5214291d08ce469a8b24e","remote-policy.mjs":"16ea015ad5de3c357bce730ea8ea98571dc981d8591fb5156b1941b2c557a381","remote-preview.mjs":"fe504ad6f83dcb4a4ebdcc018686a9a5a900c47cdf8c45b75e7d02e2f3056155","remote-projects.mjs":"ec8c530ad3e880bca21a4d4078ecd68b6aaafcc442b50087127868d952034d5f","remote-protocol.mjs":"93f8c2031895d4e01006a1951d7c0e79ef71b86b2777eed5dfa966ab131e446d","remote-qr.mjs":"b80e2b4a5bc020cf6ed92e91d06b327cb5197de1c35b3445a0fc2c7a3bf1ab3f","remote-release-plans.mjs":"11884a62b7d6dcccb5e154a26603bdf650f7b40f946329fb174d8c13729bec74","remote-releases.mjs":"fb08b72593ea00013c8b679e0c0d7dee95b0fd7cc5fd31b80ac575d0e340927d","remote-run.mjs":"c180c401613e0c01dfc471bb6226ebb035a7299839f81c6e38ff714d75d68c3f","remote-screen-approvals.mjs":"c43ab286d36a38d17639d155782ffa017f1a9b6806a09b82ed0142a1290b6000","remote-screen-push.mjs":"4ee8bd48d24b2c87581e9f33d8354a86381f7febd82f89ed509a7a87c1442608","remote-screen-states.mjs":"7c3c86a584bebf52461f3cab39c05ea2a13910061704d48fc622956e842940f7","remote-service.mjs":"a3a5502e0f6f43b04e37ee778f43d88f4c219776439cfed0d8fa0b511e0c9637","remote-session-list.mjs":"494fdbe20f0542806ac6c42ad149c52e2d3ace23a3a7567f96dc7e80d092c727","remote-sessions.mjs":"1efb7869cef6090cbbeae15ff1e5ffe99dca3742f9c245686d6758bb705587d6","remote-settings.mjs":"ca16f39416a457bd5ceb1df847596e1b4bcd2894310eb6514664a619dee4981f","remote-steered.mjs":"d7afde92c62c87abbdb84b0cfea2eea4752e90a2e453e52a54812c4fe0395190","remote-steering.mjs":"7ba22e6110cea3ac75a4f084f8f92a5bd90c31a19d3ce58a88a0843bdadea834","remote-store.mjs":"7226d006d03788ea2a8de30226ab5f6bf45b1bcbb10ee7d4e28bf2c3cca5a2a7","remote-terminal-cli.mjs":"82a048b75e412d0b6db076afbb84cab7c754dec72b6c8b6af4d4906b38e988a7","remote-terminal-sessions.mjs":"6ab51824890a18768d23cedc499f3840b2b02a8ed651463c1fe2d74dd352a361","remote-transport.mjs":"68650fd77ea09b5762377f87cabdc1c73a34d77324aa5bf0cd9742094a50c32b","runtime-install.mjs":"aab47b52c79d726ef428a24f982c648fa3f1c2dc2b574f633611d02924864e5f","self-update.mjs":"378e3620d48c72cf0bf812be408883b995cdb2223de34a20f762dd73eeffb258","session-databases.mjs":"a16ffbc50ccc0e78f370ebe07f871d1a80f1977472e478e3599e7abfdc90c1b7","session-local-models.mjs":"bacd38ff8dd3056b552982ec52eb57c7b8ca86e1a46cd4cba30fc340e3e28fd4","setup-mcp.mjs":"b732e3dd9b3e522b7cc8acf167ce28ba8f1a8dee797ee15bd7c3b02919b13e6f","stack-rules.mjs":"b23c56e72ec56ba02b17ed895f869172d988c468a697e8d6026b0e268f61e489","stretch-evidence.mjs":"5f5667b92adf11b1a5a6330a0f26dd6db73d56fe60823d9a5246dab71d27d380","transcript-readers.mjs":"e9f20415c2b5d62a09f35a63075002ebd1da56edb32f242d52822d58ecbd8ac3","worktrust-launch.mjs":"84801bd29d472d48188c126b9ebe3989a3132b54e13cc4fe534ff7c383a294ee","worktrust.mjs":"e2ac72ef0f14bb8b8f756f67c65b6adc88bc899e2794e8f0edcf305290ab7f33"},"format":"worktrust-package/1","kind":"engine","version":"0.11.9"},"signature":"vilYSSAd3p9Wk5pNj5taYk3DnUCz4-61GN1ZTCqMFxyo4dqt9vMVrIwcb7P5ksJZxu8ZP9WnP0lCwuA-ezOIDA"}
|
package/node-guide.mjs
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* REMOTE AGENT ON A NODE THAT IS TOO OLD: THE WAYS FORWARD (CLI 0.11.8, owner 2026-11-13). package.json promises Node 18
|
|
3
|
+
* for measuring; Remote Agent's one live connection needs the WebSocket Node has from 22.4. A `remote` command there does
|
|
4
|
+
* not end at a refusal: it says so plainly, says measuring keeps working, and shows the ways to a working Remote Agent,
|
|
5
|
+
* each with its exact command.
|
|
6
|
+
*
|
|
7
|
+
* WHAT THIS MODULE MAY RUN, AND HOW (held by check-cli-package's node-guide rule):
|
|
8
|
+
* - only a command from its OWN CLOSED LIST below (RUNNABLE): never a word from a person's input, a file or the network;
|
|
9
|
+
* - as an argv array handed to spawn, never a shell string, never `shell: true`;
|
|
10
|
+
* - only a user-level tool (fnm, volta, Homebrew, pipx): never sudo, never a system package manager, never an installer
|
|
11
|
+
* that asks for an administrator; those are printed for the person to run;
|
|
12
|
+
* - only after the exact command was shown and the person typed yes (Enter is No). Without a terminal, or with --yes,
|
|
13
|
+
* nothing is asked and nothing runs: the text is printed and the command ends with a failure code.
|
|
14
|
+
* nvm is a shell function and asdf's words differ per version: both are printed, never run. There is no "newer Node just
|
|
15
|
+
* for WorkTrust through npx": that Node would come from npm's `node` package, which nothing here verifies; the Python
|
|
16
|
+
* package is that way, with the official Node it locks by hash.
|
|
17
|
+
*/
|
|
18
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
19
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
20
|
+
import { delimiter, join } from "node:path";
|
|
21
|
+
import { createInterface } from "node:readline/promises";
|
|
22
|
+
|
|
23
|
+
export const NODE_FLOOR = [22, 4];
|
|
24
|
+
/** The one sentence a script reads (stderr, exit 1); null where this Node can hold the connection. */
|
|
25
|
+
export const remoteNeedsNode = (has = typeof globalThis.WebSocket === "function", version = process.versions.node) =>
|
|
26
|
+
(has ? null : `remote needs Node 22.4 or later for its connection (this is ${version}); the Python package bundles one`);
|
|
27
|
+
export const nodeIsEnough = (version) => { const [a, b] = String(version).replace(/^v/, "").split(".").map(Number); return a > NODE_FLOOR[0] || (a === NODE_FLOOR[0] && b >= NODE_FLOOR[1]); };
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Whether a `remote <sub>` command stops at the ways forward on this Node (asked by remote-cli.mjs before anything is read,
|
|
31
|
+
* asked, written or sent). Node before 22.4 has no WebSocket, so nothing that starts, links, allows or changes something
|
|
32
|
+
* runs. The ways to LOOK and to STOP stay: a person who moved to an older Node can still see the state, pause it, turn it
|
|
33
|
+
* off and close its connections.
|
|
34
|
+
*/
|
|
35
|
+
const REMOTE_WITHOUT = new Set(["status", "pause", "disable", "disconnect"]);
|
|
36
|
+
export const remoteStopsHere = (sub, has = typeof globalThis.WebSocket === "function") => !REMOTE_WITHOUT.has(sub) && !has;
|
|
37
|
+
|
|
38
|
+
/** The closed list: every command this module can run. A way's `argv` is built from these words and nothing else. */
|
|
39
|
+
const RUNNABLE = Object.freeze({
|
|
40
|
+
fnm: [["fnm", "install", "22"], ["fnm", "default", "22"]],
|
|
41
|
+
volta: [["volta", "install", "node@22"]],
|
|
42
|
+
brew: [["brew", "upgrade", "node"]],
|
|
43
|
+
});
|
|
44
|
+
const shown = (argvs) => argvs.map((argv) => argv.join(" ")).join(" && ");
|
|
45
|
+
|
|
46
|
+
/** An executable of this name on PATH (its full path), or null. Reads directories only; runs nothing. */
|
|
47
|
+
export function onPath(name, env = process.env, platform = process.platform) {
|
|
48
|
+
const exts = platform === "win32" ? (env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";") : [""];
|
|
49
|
+
for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter).filter(Boolean)) for (const ext of exts) { const file = join(dir, name + ext); if (existsSync(file)) return file; }
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* How this computer's Node is installed, by where the running Node lives, and the command that updates it. Pure: `has(name)`
|
|
55
|
+
* says whether a tool is on PATH. `argv` is set only for a user-level manager this module may run; otherwise the command
|
|
56
|
+
* is for the person (`argv: null`).
|
|
57
|
+
*/
|
|
58
|
+
export function nodeManager({ execPath = process.execPath, env = process.env, platform = process.platform, has = (name) => Boolean(onPath(name)) } = {}) {
|
|
59
|
+
const path = String(execPath).replace(/\\/g, "/");
|
|
60
|
+
const way = (id, name, text, argv = null) => ({ id, name, shown: text, argv });
|
|
61
|
+
if (path.includes("/.nvm/") || (env.NVM_DIR && path.startsWith(String(env.NVM_DIR).replace(/\\/g, "/")))) return way("nvm", "nvm", "nvm install 22 && nvm alias default 22");
|
|
62
|
+
if (/\/fnm(_multishells)?\/|\/\.fnm\//.test(path) || (env.FNM_DIR && path.startsWith(String(env.FNM_DIR).replace(/\\/g, "/")))) return way("fnm", "fnm", shown(RUNNABLE.fnm), has("fnm") ? RUNNABLE.fnm : null);
|
|
63
|
+
if (path.includes("/.volta/") || (env.VOLTA_HOME && path.startsWith(String(env.VOLTA_HOME).replace(/\\/g, "/")))) return way("volta", "Volta", shown(RUNNABLE.volta), has("volta") ? RUNNABLE.volta : null);
|
|
64
|
+
if (path.includes("/.asdf/")) return way("asdf", "asdf", "asdf install nodejs latest:22 (then make it your default: asdf set -u nodejs latest:22, or asdf global on asdf before 0.16)");
|
|
65
|
+
if (/^\/opt\/homebrew\/|^\/usr\/local\/(Cellar|opt)\/|^\/home\/linuxbrew\//.test(path)) {
|
|
66
|
+
if (/\/node@\d+\//.test(path)) return way("brew", "Homebrew", "brew install node@22 && brew link --overwrite --force node@22");
|
|
67
|
+
return way("brew", "Homebrew", shown(RUNNABLE.brew), has("brew") ? RUNNABLE.brew : null);
|
|
68
|
+
}
|
|
69
|
+
if (platform === "win32") return way("windows", "the Windows installer", "winget upgrade OpenJS.NodeJS.LTS (or the installer from https://nodejs.org/en/download)");
|
|
70
|
+
return way("system", "your system's own package", "install Node 22 from https://nodejs.org/en/download (or your distribution's NodeSource package)");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** The Python package: run through pipx where pipx is, else the line that installs it. */
|
|
74
|
+
export function pythonWay(args, has = (name) => Boolean(onPath(name))) {
|
|
75
|
+
if (has("pipx")) return { id: "pipx", shown: `pipx run worktrust ${args.join(" ")}`.trimEnd(), argv: [["pipx", "run", "worktrust", ...args]] };
|
|
76
|
+
if (has("python3") || has("python")) return { id: "pip", shown: `${has("python3") ? "python3" : "python"} -m pip install worktrust (then: worktrust ${args.join(" ")})`.replace(/ \)$/, ")"), argv: null };
|
|
77
|
+
return { id: "none", shown: "install Python 3.10 or later, then: pip install worktrust", argv: null };
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** What is said, the same bytes with or without a terminal. */
|
|
81
|
+
export function guidanceLines({ version = process.versions.node, manager, python }) {
|
|
82
|
+
return [
|
|
83
|
+
"",
|
|
84
|
+
` Remote Agent needs Node 22.4 or later for its live connection. This computer runs Node ${version}.`,
|
|
85
|
+
" Measuring your work keeps working as it is.",
|
|
86
|
+
"",
|
|
87
|
+
" Ways forward:",
|
|
88
|
+
` 1 Update this computer's Node (${manager.name})`,
|
|
89
|
+
` ${manager.shown}`,
|
|
90
|
+
" 2 Use the Python package, which brings its own Node",
|
|
91
|
+
` ${python.shown}`,
|
|
92
|
+
];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const runArgv = (argv) => new Promise((resolve) => {
|
|
96
|
+
const child = spawn(argv[0], argv.slice(1), { stdio: "inherit" });
|
|
97
|
+
child.on("error", () => resolve(1));
|
|
98
|
+
child.on("exit", (code) => resolve(code ?? 1));
|
|
99
|
+
});
|
|
100
|
+
const typedLine = async (question) => { const prompt = createInterface({ input: process.stdin, output: process.stdout }); const answer = (await prompt.question(question)).trim().toLowerCase(); prompt.close(); return answer; };
|
|
101
|
+
const nodeOnPath = () => { const node = onPath("node"); if (!node) return null; const asked = spawnSync(node, ["--version"], { encoding: "utf8", timeout: 10_000 }); return asked.status === 0 ? { path: realpathSync(node), version: asked.stdout.trim().replace(/^v/, "") } : null; };
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A `remote` command on a Node without the WebSocket: say it, show the ways, and (a person's terminal only) take one on a
|
|
105
|
+
* typed yes. `io`: the CLI's say, fail, ask and has. `deps` are the seams the tests hold: interactive, line, run, findNode,
|
|
106
|
+
* rerun(nodePath, args) → the exit code of this same CLI started again under that Node, connected.
|
|
107
|
+
*/
|
|
108
|
+
export async function guideToNode(io, args, deps = {}) {
|
|
109
|
+
const sentence = remoteNeedsNode(false, deps.version ?? process.versions.node);
|
|
110
|
+
const manager = deps.manager ?? nodeManager(), python = deps.python ?? pythonWay(args);
|
|
111
|
+
const interactive = deps.interactive ?? (Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY) && !io.has("yes"));
|
|
112
|
+
// Started again: this same CLI (the launcher this process was started with, verified as always) under the Node just found.
|
|
113
|
+
const rerun = deps.rerun ?? ((nodePath, cliArgs) => runArgv([nodePath, process.argv[1], ...cliArgs]));
|
|
114
|
+
const run = deps.run ?? runArgv, again = `npx worktrust ${args.join(" ")}`.trimEnd();
|
|
115
|
+
for (const line of guidanceLines({ version: deps.version, manager, python })) io.say(line);
|
|
116
|
+
const leave = (words) => { io.say(` ${words}`); io.fail(sentence); };
|
|
117
|
+
if (!interactive) leave("Nothing was installed or changed.");
|
|
118
|
+
io.say(" q Leave");
|
|
119
|
+
const pick = await (deps.line ?? typedLine)(" Choose 1 or 2, or q to leave [1]: ");
|
|
120
|
+
const way = pick === "" || pick === "1" ? manager : pick === "2" ? python : null;
|
|
121
|
+
if (!way) leave("Nothing was installed or changed.");
|
|
122
|
+
if (!way.argv) leave(`That one is yours to run: ${way.shown}. Then run \`${again}\` again. Nothing was installed or changed.`);
|
|
123
|
+
io.say(` This runs: ${way.shown}`);
|
|
124
|
+
if (!(await io.ask("Run it now?", false))) leave("Nothing was run. Nothing was installed or changed.");
|
|
125
|
+
for (const argv of way.argv) { const code = await run(argv); if (code !== 0) leave(`\`${argv.join(" ")}\` ended with code ${code}. WorkTrust changed nothing.`); }
|
|
126
|
+
if (way === python) return; // pipx ran this same command with the Python package's own Node
|
|
127
|
+
const node = (deps.findNode ?? nodeOnPath)();
|
|
128
|
+
if (!node || !nodeIsEnough(node.version)) leave(`Node on this terminal's PATH is ${node ? `still ${node.version}` : "not found"}. Open a new terminal and run \`${again}\` again.`);
|
|
129
|
+
io.say(` ✓ Node is now ${node.version}.`);
|
|
130
|
+
// The session hook and the AI-app doors name a Node by its path: `update` under the new one repairs a path that moved.
|
|
131
|
+
if (deps.connected) { io.say(" Bringing the session hook and your AI apps onto it (npx worktrust update):"); await rerun(node.path, ["update"]); }
|
|
132
|
+
io.say(` Continuing: ${again}`);
|
|
133
|
+
process.exitCode = await rerun(node.path, args);
|
|
134
|
+
}
|