worktrust 0.11.11 → 0.11.13

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/remote-run.mjs CHANGED
@@ -15,7 +15,7 @@ import { fileURLToPath } from "node:url";
15
15
  import * as P from "./remote-protocol.mjs";
16
16
  import { loadPreviewGrants, loadRoots } from "./remote-store.mjs";
17
17
  import { sessionProjects } from "./remote-projects.mjs";
18
- import { ensureRemoteDir, gatewayOf, issuerKeys, loadDeskMarks, loadIdentity, loadKeys, loadPipelineReviews, loadProjects, loadSettings, readJson, remotePath, random, saveIdentity } from "./remote-store.mjs";
18
+ import { ensureRemoteDir, gatewayOf, isLoopbackGateway, issuerKeys, loadDeskMarks, loadIdentity, loadKeys, loadPipelineReviews, loadProjects, loadSettings, readJson, remotePath, random, saveIdentity } from "./remote-store.mjs";
19
19
  import { openJournal } from "./remote-journal.mjs";
20
20
  import { inventory as listAgents, offered } from "./remote-inventory.mjs";
21
21
 
@@ -34,7 +34,9 @@ import { createLivePreview } from "./remote-live-preview.mjs";
34
34
  import { SETTING_WORDS } from "./remote-admin.mjs";
35
35
  import { appendPipelineMark } from "./remote-steered.mjs";
36
36
  import { createDaemonCore } from "./remote-daemon.mjs";
37
+ import { createDesk } from "./remote-desk-sessions.mjs";
37
38
  import { connectGateway, webSocketAvailable } from "./remote-transport.mjs";
39
+ import { createHealthMonitor, fixtureReaders, HEALTH_REFUSAL, healthLine, keepHealth } from "./remote-health.mjs";
38
40
 
39
41
  const HERE = dirname(fileURLToPath(import.meta.url));
40
42
  const log = (kind, fields = {}) => process.stderr.write(`${JSON.stringify({ at: new Date().toISOString(), kind, ...fields })}\n`);
@@ -42,6 +44,7 @@ const log = (kind, fields = {}) => process.stderr.write(`${JSON.stringify({ at:
42
44
  const notice = (kind, fields) => {
43
45
  if (kind === "browser_endorsed") process.stderr.write(` ! A browser was added by your phone ${fields.by}: ${fields.fingerprint}. See or remove it: npx worktrust remote phones\n`);
44
46
  // Part B: a change approved in the app or on the web with the authenticator, signed by WorkTrust and verified here.
47
+ if (kind === "session_refused") process.stderr.write(` ! A new session from a phone or browser was refused: ${HEALTH_REFUSAL}. Running sessions continue.\n`);
45
48
  if (kind === "settings_changed") process.stderr.write(` ! ${SETTING_WORDS[fields.setting] ?? "a remote setting"} changed from ${fields.by}, approved there with your authenticator. To keep every change at this keyboard: npx worktrust remote admin off\n`);
46
49
  };
47
50
  const logged = (kind, fields = {}) => { log(kind, fields); notice(kind, fields); };
@@ -135,7 +138,10 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
135
138
  // The live preview (release 19): the session's granted page, live, over the browser's pipe; one per computer.
136
139
  const live = createLivePreview({ emit: (...a) => core.emit(...a), grants: loadPreviewGrants, env: () => agentEnv(loadSettings()), log, now: Date.now,
137
140
  sessionProject: (id) => { const s = journal.session(id); return s ? loadProjects().find((p) => p.project_id === s.project_id) ?? null : null; } });
138
- const core = createDaemonCore({ local, issuerKeys: keysOf, journal, projectSecret: keys.projectSecret, attachments, preview, live, now: Date.now, random, log: logged, send: (f) => transport?.send(f) ?? false, inventory: (refresh) => inventory({ env: agentEnv(loadSettings()), refresh }), online: () => transport?.ready() ?? false, approvals: null });
141
+ // Continue a session on this computer (release 36): its own Claude Code sessions in the projects a phone may reach.
142
+ const desk = createDesk({ projects: () => sessionProjects({ projects: loadProjects, roots: loadRoots, projectSecret: keys.projectSecret }), journal });
143
+ let health = null; // the sampler below (remote-health.mjs): every 15 s, local numbers, no model
144
+ const core = createDaemonCore({ local, issuerKeys: keysOf, journal, projectSecret: keys.projectSecret, attachments, preview, live, desk, now: Date.now, random, log: logged, health: () => health?.latest() ?? null, send: (f) => transport?.send(f) ?? false, inventory: (refresh) => inventory({ env: agentEnv(loadSettings()), refresh }), online: () => transport?.ready() ?? false, approvals: null });
139
145
  const ctx = { journal, now: Date.now, random, deviceId: identity.device_id, emit: core.emit, paused: () => loadSettings().paused !== null || !loadSettings().enabled, phoneOnline: core.phoneOnline, controllers: core.controllers };
140
146
  const approvals = createApprovals(ctx);
141
147
  const socket = await approvals.listen(runDir);
@@ -144,13 +150,13 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
144
150
  // A session runs in a granted project or in an existing project inside a root (0.11.7), each by the inventory's id.
145
151
  settings: loadSettings, projects: () => sessionProjects({ projects: loadProjects, roots: loadRoots, projectSecret: keys.projectSecret }), inventory: () => inventory({ env: agentEnv(loadSettings()) }), agentEnv: () => agentEnv(loadSettings()), replay: core.replay,
146
152
  onTaskEnded: (id, outcome) => releases.taskEnded(id, outcome), onActivity: () => releases?.activity(),
147
- onSessionsChanged: () => core.emit(null, "device.inventory", core.inventoryBody(false)), attachments });
153
+ onSessionsChanged: () => core.emit(null, "device.inventory", core.inventoryBody(false)), attachments, desk });
148
154
  ctx.onApprovalOpened = sessions.onApprovalOpened; ctx.onApprovalSettled = sessions.onApprovalSettled;
149
155
  // Terminal sessions (release 19, off until `worktrust remote terminal on`): Claude Code in tmux on WorkTrust's own socket.
150
156
  const tmuxFile = listAgents({ env: agentEnv(loadSettings()) }).files.tmux;
151
157
  const tmux = tmuxFile ? createTmux({ file: tmuxFile, config: writeTmuxConfig(runDir), env: agentEnv(loadSettings()) }) : NO_TMUX;
152
158
  const terminal = createTerminalSessions({ journal, now: Date.now, emit: core.emit, settings: loadSettings, projects: loadProjects, inventory: () => inventory({ env: agentEnv(loadSettings()) }),
153
- tmux, claudeFile: () => listAgents({ env: agentEnv(loadSettings()) }).files["claude-code"], replay: core.replay, running: () => sessions.runningCount(), detect: (lines) => detectScreen("claude-code", lines), approvals,
159
+ tmux, claudeFile: () => listAgents({ env: agentEnv(loadSettings()) }).files["claude-code"], replay: core.replay, running: () => sessions.runningCount(), detect: (lines) => detectScreen("claude-code", lines), approvals, desk,
154
160
  onSessionsChanged: () => core.emit(null, "device.inventory", core.inventoryBody(false)) });
155
161
  const registry = withTerminal(sessions, terminal);
156
162
  // Releases and pipelines (2026-11-07): one queue for every release's tasks, the reviewed pipeline of each project.
@@ -168,8 +174,22 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
168
174
  if (frame.frame === "hello") core.receiveHello(frame.hello);
169
175
  else if (frame.frame === "command") await core.receiveCommand(frame.envelope);
170
176
  else if (frame.frame === "relay") { log("relay", { type: frame.event?.type ?? null }); if (frame.event?.type === "device.revoked") core.peerRevoked(frame.event); }
171
- else if (frame.frame === "error") log("gateway_error", { reason: typeof frame.reason === "string" ? frame.reason.slice(0, 40) : null });
177
+ else if (frame.frame === "error") {
178
+ log("gateway_error", { reason: typeof frame.reason === "string" ? frame.reason.slice(0, 40) : null });
179
+ // A gateway older than device.health answers it `error: shape` (and closes nothing): rest the samples half an hour.
180
+ if (frame.reason === "shape" && Date.now() - healthSentAt < 5000) { healthRestUntil = Date.now() + 30 * 60_000; log("health_rested", { minutes: 30 }); }
181
+ }
172
182
  };
183
+ // THE COMPUTER'S HEALTH (2026-11-15): kept here for `remote status` and the menu, said in the run terminal when it turns
184
+ // red or back, and sealed for the paired phones and browsers on the transient lane (the gateway keeps none of it).
185
+ let healthSentAt = 0, healthRestUntil = 0, healthSaid = null;
186
+ const healthFixture = isLoopbackGateway(gateway) ? process.env.WORKTRUST_REMOTE_HEALTH_FIXTURE ?? null : null; // tests on the dev relay only
187
+ health = createHealthMonitor({ log, ...(healthFixture ? fixtureReaders(healthFixture) : {}), onSample: (body) => {
188
+ keepHealth(body);
189
+ if (body.level !== healthSaid && (body.level === "red" || healthSaid === "red")) process.stderr.write(`${healthLine(body)}\n`);
190
+ healthSaid = body.level;
191
+ if (Date.now() >= healthRestUntil && transport?.ready()) { healthSentAt = Date.now(); core.emitHealth(body); }
192
+ } });
173
193
  let sentCode = null;
174
194
  const registerCode = (again = false) => {
175
195
  const invite = readJson("invite.json");
@@ -186,6 +206,7 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
186
206
  if (stopping) return;
187
207
  stopping = true;
188
208
  approvals.close();
209
+ health.stop();
189
210
  await pipelines.stopAll();
190
211
  await live.stopAll(); // the browser ended, its profile removed
191
212
  await registry.stopAll(); // the structured agents; a terminal session lives on in tmux
@@ -195,7 +216,13 @@ export async function runDaemon({ say = (l) => process.stdout.write(`${l}\n`) }
195
216
  };
196
217
  process.on("SIGINT", () => stop(0));
197
218
  process.on("SIGTERM", () => stop(0));
198
- setInterval(() => { const s = loadSettings(); if (!s.enabled) stop(0); registerCode(); releases.poll(); }, 3000).unref();
219
+ // WHAT A PHONE MAY REACH, TOLD AT ONCE (0.11.12, owner 2026-11-15): a grant made at this keyboard (the access step after
220
+ // "Phone linked", Remote Agent › Roots or › Projects) changes the lists another process wrote; the next tick sends the
221
+ // inventory again, sealed, so a phone waiting on "Choose access at your computer" learns it from this computer, not a server.
222
+ let grants = null;
223
+ const grantsChanged = () => { const now = [...loadRoots().map((r) => r.root_id), "|", ...loadProjects().map((p) => p.project_id)].join(","); const changed = grants !== null && now !== grants; grants = now; return changed; };
224
+ setInterval(() => { const s = loadSettings(); if (!s.enabled) stop(0); registerCode(); releases.poll(); try { if (grantsChanged()) core.emit(null, "device.inventory", core.inventoryBody(false)); } catch { /* an unreadable list: told at the next ask */ } }, 3000).unref();
199
225
  releases.schedule(); // queued tasks a restart kept
226
+ health.start();
200
227
  return new Promise(() => {});
201
228
  }
@@ -32,7 +32,6 @@ const LEDGER_EVERY_MS = 10 * 60_000;
32
32
  /** Per agent: the shape of its own session id (a resume names one), and a fresh stream state. */
33
33
  const AGENT_ID = { "claude-code": isClaudeSessionId, codex: isCodexThreadId, opencode: isOpenCodeSessionId };
34
34
  const FRESH_STATE = { "claude-code": emptyClaudeState, codex: emptyCodexState, opencode: emptyOpenCodeState };
35
-
36
35
  export { createCoalescer } from "./remote-coalesce.mjs"; // kept here for the modules that import it from sessions
37
36
 
38
37
  export function createSessions(ctx) {
@@ -216,9 +215,10 @@ export function createSessions(ctx) {
216
215
  const refused = P.checkStart(payload, adapterOf(ctx.inventory(), payload.adapter)); if (refused) return refused;
217
216
  const choice = startChoice(payload, project.project_id, ctx.inventory(), ctx.settings(), known); if (typeof choice === "string") return choice;
218
217
  if (!AGENT_ID[payload.adapter] || (payload.resume !== null && !AGENT_ID[payload.adapter](payload.resume))) return "unsupported";
218
+ const desk = payload.resume !== null && env.task !== true ? (ctx.desk ? ctx.desk.resumable(payload.resume, project.project_id) : "not_found") : null; if (desk) return desk; // release 36: only a session of the computer's own list, free
219
219
  if (deskGranted(payload.adapter, project.path)) return "not_allowed"; // S0: Codex's own allow rules cannot be denied per session
220
220
  const s = { session_id: env.session_id, project_id: project.project_id, projectPath: project.path, adapter: payload.adapter, model: payload.model, mode: payload.permission_mode,
221
- agent_ref: payload.resume ?? (payload.adapter === "codex" ? null : payload.adapter === "opencode" ? mintOpenCodeSessionId(ctx.now(), ctx.random) : randomUUID()), how: "started", first: ctx.now(), queue: [], state: FRESH_STATE[payload.adapter](),
221
+ agent_ref: payload.resume ?? (payload.adapter === "codex" ? null : payload.adapter === "opencode" ? mintOpenCodeSessionId(ctx.now(), ctx.random) : randomUUID()), how: payload.resume !== null && env.task !== true ? "attached" : "started", first: ctx.now(), queue: [], state: FRESH_STATE[payload.adapter](),
222
222
  coalesce: createCoalescer({ now: ctx.now }), attention: null, command_id: null, waiting: null, turnOpen: false, run: null, steers: [], interrupting: false, ownTurn: null, task: env.task === true, tokens: P.NO_TOKENS, subagents: new Map(), turnStartedAt: null, name: payload.name ?? null, active: 0, countedTurn: null,
223
223
  agentMode: payload.agent_mode ?? null, effort: choice.effort, extraIds: choice.extraProjectIds, extraPaths: choice.extras.map((p) => p.path) };
224
224
  live.set(s.session_id, s);
@@ -85,6 +85,7 @@ export function createTerminalSessions(ctx) {
85
85
  const project = ctx.projects().find((p) => p.project_id === env.project_id);
86
86
  if (!project) return "not_found";
87
87
  if (payload.resume !== null && !UUID.test(payload.resume)) return "unsupported";
88
+ const held = payload.resume !== null ? (ctx.desk ? ctx.desk.resumable(payload.resume, project.project_id) : "not_found") : null; if (held) return held; // release 36: the computer's own list, free
88
89
  const s = sessionOf({ session_id: env.session_id, project_id: project.project_id, projectPath: project.path, name: payload.name ?? null, model: payload.model, origin: "phone", how: "started",
89
90
  tmux: tmuxNameOf(env.session_id), agent_ref: payload.resume ?? randomUUID(), command_id: env.command_id });
90
91
  let argv;
package/worktrust.mjs CHANGED
@@ -69,7 +69,7 @@ import { execFileSync, spawn, spawnSync } from "node:child_process";
69
69
  import { createHash, createPublicKey, generateKeyPairSync, randomBytes, sign } from "node:crypto";
70
70
  import { createServer } from "node:http";
71
71
  import { chmodSync, closeSync, copyFileSync, existsSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
72
- import { homedir, hostname, platform } from "node:os";
72
+ import { homedir, hostname, platform, userInfo } from "node:os";
73
73
  import { dirname, join, basename } from "node:path";
74
74
  import { createInterface } from "node:readline/promises";
75
75
  import { createInterface as lines } from "node:readline";
@@ -83,7 +83,7 @@ const command = args.includes("--help") ? "help" : args.includes("--version") ?
83
83
  const flag = (name) => { const at = args.indexOf(`--${name}`); return at >= 0 ? args[at + 1] : undefined; };
84
84
  const has = (name) => args.includes(`--${name}`);
85
85
  /** This CLI's version, said to the door so the app can tell which computer runs an old one (check-cli-package holds it equal to package.json). */
86
- const CLI_VERSION = "0.11.11";
86
+ const CLI_VERSION = "0.11.13";
87
87
  /**
88
88
  * HOW THIS CLI MEASURES, AS A NUMBER OF ITS OWN (0.10.31; owner, 2026-10-28: 0.10.30 offered a re-measure it had no reason
89
89
  * to offer). Raised ONLY when what is measured changes: the timeline, the seconds, the tokens, the steering, the session
@@ -119,7 +119,7 @@ const ORIGIN = (flag("origin") ?? process.env.WORKTRUST_ORIGIN ?? "https://app.w
119
119
  const MCP = flag("url") ?? process.env.WORKTRUST_MCP_URL ?? `${ORIGIN}/api/mcp`;
120
120
  const HOME_DIR = join(homedir(), ".worktrust");
121
121
  const HERE = dirname(fileURLToPath(import.meta.url));
122
- const SCRIPTS = ["credential-store.mjs", "remote-protocol.mjs", "remote-store.mjs", "remote-policy.mjs", "remote-journal.mjs", "remote-steered.mjs", "remote-inventory.mjs", "remote-claude-events.mjs", "remote-claude-progress.mjs", "remote-attachments.mjs", "remote-preview.mjs", "remote-coalesce.mjs", "remote-steering.mjs", "remote-codex-events.mjs", "remote-adapter-codex.mjs", "remote-opencode-events.mjs", "remote-adapter-opencode.mjs", "remote-opencode-session.mjs", "remote-adapter-terminal.mjs", "remote-terminal-sessions.mjs", "remote-terminal-cli.mjs", "remote-screen-states.mjs", "remote-screen-approvals.mjs", "remote-screen-push.mjs", "remote-cdp.mjs", "remote-live-preview.mjs", "remote-projects.mjs", "remote-pipeline-config.mjs", "remote-pipeline-parsers.mjs", "remote-pipeline.mjs", "remote-releases.mjs", "remote-release-plans.mjs", "remote-adapter-claude-code.mjs", "remote-approval-bridge.mjs", "remote-approvals.mjs", "remote-sessions.mjs", "remote-session-list.mjs", "remote-changes.mjs", "remote-endorse.mjs", "remote-daemon.mjs", "remote-transport.mjs", "remote-run.mjs", "remote-service.mjs", "remote-pairing.mjs", "remote-qr.mjs", "remote-cli.mjs", "remote-agent-switch.mjs", "remote-settings.mjs", "folder-picker.mjs", "cli-menu.mjs", "cli-menu-remote.mjs", "cli-colour.mjs", "cli-look.mjs", "node-guide.mjs", "remote-countdown.mjs", "remote-connections.mjs", "remote-admin.mjs", "credential-vault.mjs", "credential-vault-scripts.mjs", "history-outbox.mjs", "setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "transcript-readers.mjs", "session-readers.mjs", "session-databases.mjs", "session-local-models.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "export-facts.mjs", "stack-rules.mjs", "runtime-install.mjs", "orchestration-contract.mjs", "orchestration-evidence.mjs", "orchestration-report.mjs", "claude-mod.mjs", "package-integrity.mjs", "worktrust-launch.mjs", "project-modes.mjs", "commit-rules.mjs", "git-commits.mjs", "self-update.mjs", "history-progress.mjs"];
122
+ const SCRIPTS = ["credential-store.mjs", "remote-protocol.mjs", "remote-store.mjs", "remote-policy.mjs", "remote-journal.mjs", "remote-steered.mjs", "remote-inventory.mjs", "remote-claude-events.mjs", "remote-claude-progress.mjs", "remote-attachments.mjs", "remote-preview.mjs", "remote-coalesce.mjs", "remote-steering.mjs", "remote-codex-events.mjs", "remote-adapter-codex.mjs", "remote-opencode-events.mjs", "remote-adapter-opencode.mjs", "remote-opencode-session.mjs", "remote-adapter-terminal.mjs", "remote-terminal-sessions.mjs", "remote-terminal-cli.mjs", "remote-screen-states.mjs", "remote-screen-approvals.mjs", "remote-screen-push.mjs", "remote-cdp.mjs", "remote-live-preview.mjs", "remote-projects.mjs", "remote-pipeline-config.mjs", "remote-pipeline-parsers.mjs", "remote-pipeline.mjs", "remote-releases.mjs", "remote-release-plans.mjs", "remote-adapter-claude-code.mjs", "remote-approval-bridge.mjs", "remote-approvals.mjs", "remote-sessions.mjs", "remote-session-list.mjs", "remote-desk-sessions.mjs", "remote-changes.mjs", "remote-endorse.mjs", "remote-daemon.mjs", "remote-transport.mjs", "remote-run.mjs", "remote-service.mjs", "remote-pairing.mjs", "remote-qr.mjs", "remote-cli.mjs", "remote-agent-switch.mjs", "remote-settings.mjs", "folder-picker.mjs", "cli-menu.mjs", "cli-menu-remote.mjs", "cli-colour.mjs", "cli-stop.mjs", "cli-look.mjs", "node-guide.mjs", "remote-countdown.mjs", "remote-connections.mjs", "remote-admin.mjs", "remote-health.mjs", "credential-vault.mjs", "credential-vault-scripts.mjs", "credential-decoy.mjs", "history-outbox.mjs", "setup-mcp.mjs", "log-session.mjs", "count-behaviour.mjs", "transcript-readers.mjs", "session-readers.mjs", "session-databases.mjs", "session-local-models.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "export-facts.mjs", "stack-rules.mjs", "runtime-install.mjs", "orchestration-contract.mjs", "orchestration-evidence.mjs", "orchestration-report.mjs", "claude-mod.mjs", "package-integrity.mjs", "worktrust-launch.mjs", "project-modes.mjs", "commit-rules.mjs", "git-commits.mjs", "self-update.mjs", "history-progress.mjs"];
123
123
  /** The modules the scripts import by name from beside them; a download keeps that name. */
124
124
  const IMPORTED = new Set(["project-modes.mjs", "transcript-readers.mjs", "session-readers.mjs", "session-databases.mjs", "session-local-models.mjs", "config-edits.mjs", "stretch-evidence.mjs", "chat-exports.mjs", "export-facts.mjs", "stack-rules.mjs", "runtime-install.mjs", "orchestration-contract.mjs", "orchestration-evidence.mjs", "orchestration-report.mjs", "commit-rules.mjs", "git-commits.mjs"]);
125
125
  const downloaded = (name) => (IMPORTED.has(name) ? name : `${name}.download.mjs`);
@@ -130,6 +130,11 @@ const PLACEHOLDER = `wt_${"0".repeat(43)}`;
130
130
  // painted, whatever the environment says. Colours off (a pipe, NO_COLOR, --no-color, CI), every byte is as before 0.11.8.
131
131
  const MACHINE = command === "hook" || command === "self-update" || (command === "mcp" && !["on", "off", "status"].includes(args[args.indexOf("mcp") + 1]));
132
132
  const { coloursFor, busyWith = (words, work) => work() } = await import("./cli-colour.mjs").catch(() => ({}));
133
+ // STOP WITH ESC (0.11.12, cli-stop.mjs): a command the menu started reads Esc while it is busy, and a stop never lands inside
134
+ // a write step (critical). Direct use is untouched: every one of these is a plain pass-through there.
135
+ const { critical = (work) => work(), watched = (work) => work(), track = (child) => child, superviseChild = null, menuKeys = () => () => {}, readsOnly = () => false, STOPPED = -130 } = await import("./cli-stop.mjs").catch(() => ({}));
136
+ /** A spinner whose phase reads Esc in a menu child (raw mode: a typed key is not echoed into the spinner's line). */
137
+ const busy = (words, work) => watched(() => busyWith(words, work));
133
138
  const PAINT = coloursFor?.(process.stdout, { machine: MACHINE }) ?? { status: (line) => line }, PAINT_ERR = coloursFor?.(process.stderr, { machine: MACHINE }) ?? { status: (line) => line };
134
139
  const say = (line = "") => process.stdout.write(`${PAINT.status(line)}\n`);
135
140
  // A reader that closed the pipe (`worktrust status | head`) wants no more: stop quietly, never an EPIPE stack (0.6.16, audit L4).
@@ -190,6 +195,7 @@ function historyQueueScope(token) {
190
195
  function run(path, scriptArgs, token, collect = false, extraEnv = {}, watch = null) {
191
196
  return new Promise((resolve) => {
192
197
  const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, basename(path), scriptArgs)], { stdio: collect ? ["ignore", "pipe", "pipe"] : "inherit", detached: Boolean(watch) && OS !== "windows", env: { ...process.env, WORKTRUST_MCP_URL: MCP, WORKTRUST_MCP_TOKEN: token, WORKTRUST_NODE: NODE, WORKTRUST_NODE_ARGS: JSON.stringify(NODE_ARGS), WORKTRUST_CLI_VERSION: CLI_VERSION, WORKTRUST_MEASURE_RULES: String(MEASURE_RULES), WORKTRUST_HISTORY_SCOPE: historyQueueScope(token), ...extraEnv } });
198
+ track(child);
193
199
  let out = "", pending = "", stops = 0, said = ""; // watched, stderr is kept apart and put first: the last line stays the script's own answer on stdout
194
200
  const heard = (text) => { if (!watch.line(text)) out += `${text}\n`; };
195
201
  const stop = (signal) => { stops += 1; try { child.kill(signal); } catch { /* already gone */ } if (stops > 1) watch.now?.(); };
@@ -215,7 +221,7 @@ async function sendShown(paths, scriptArgs, token, extraEnv, words = {}) {
215
221
  let shown = null;
216
222
  try { shown = (await import(pathToFileURL(paths["history-progress.mjs"]).href)).historyProgress?.({ stream: process.stdout }) ?? null; } catch { shown = null; }
217
223
  const leave = () => { shown?.stop(words); process.stdout.write("", () => process.exit(130)); };
218
- const sent = await run(paths["log-session.mjs"], scriptArgs, token, true, { ...extraEnv, ...(shown ? { WORKTRUST_HISTORY_PROGRESS: "1" } : {}) }, { line: (line) => shown?.line(line) ?? false, now: leave });
224
+ const sent = await watched(() => run(paths["log-session.mjs"], scriptArgs, token, true, { ...extraEnv, ...(shown ? { WORKTRUST_HISTORY_PROGRESS: "1" } : {}) }, { line: (line) => shown?.line(line) ?? false, now: leave }));
219
225
  if (sent.stopped) { leave(); return new Promise(() => {}); } // the command ends here, 130
220
226
  shown?.end();
221
227
  return sent;
@@ -377,10 +383,29 @@ function saveStableEntry() {
377
383
  /** Existing file credentials remain readable until the person explicitly protects them.
378
384
  * The OS wrapping key is never written into an AI app or the encrypted credential file.
379
385
  */
380
- const { createCredentialStore } = await import("./credential-store.mjs").catch(() => ({}));
386
+ const { createCredentialStore, protectByDefault = () => "kept" } = await import("./credential-store.mjs").catch(() => ({}));
381
387
  // A PROJECT'S MODE (2026-11-09, docs/CONFIDENTIAL-WORK.md): `worktrust project` writes it, the bridge honours it for an AI app's own calls.
382
388
  const { sealToolCall, projectCommand } = await import("./project-modes.mjs").catch(() => ({}));
383
389
  const keyStore = createCredentialStore?.(KEY_FILE);
390
+ // DECOY CREDENTIALS (B18, owner 2026-11-15; credential-decoy.mjs, SECURITY.md §Decoy credentials): planted on connect, once on update.
391
+ const { plantDecoys } = await import("./credential-decoy.mjs").catch(() => ({}));
392
+ /**
393
+ * THE KEY INTO THE OS VAULT BY ITSELF (0.11.12, owner 2026-11-15): after a new coupling, and once at an update, the same
394
+ * protect() as `protect-key` (credential-store.mjs protectByDefault, which says why no prompt can follow). Never fails the
395
+ * command: where the vault is not there, refuses, or may be locked when the hook runs (SSH, Linux without a desktop), the
396
+ * private file stays and one line says so, with the command to try again.
397
+ */
398
+ const VAULT_NAME = { macos: "macOS Keychain", windows: "Windows Credential Manager", linux: "Secret Service" }[OS] ?? "OS vault";
399
+ function keyIntoVault() {
400
+ const remote = Boolean(process.env.SSH_CONNECTION || process.env.SSH_TTY) || (OS === "linux" && !process.env.DISPLAY && !process.env.WAYLAND_DISPLAY);
401
+ const done = protectByDefault(keyStore, { remote, elsewhere: homedir() !== userInfo().homedir }); // another HOME: the vault is still the account's
402
+ if (done === "protected") say(` ✓ Key protected by the ${VAULT_NAME}; the file holds it encrypted`);
403
+ else if (done === "already") say(` ✓ Key protected by the ${VAULT_NAME}, as before`);
404
+ else if (done === "elsewhere") say(" ! The key stays in its private file: this HOME is not this account's own, and the OS vault is the account's. Retry from your own home: npx -y worktrust protect-key");
405
+ else if (done === "remote") say(" ! The key stays in its private file: over SSH the OS vault can be locked when your AI apps start. In this computer's own session: npx -y worktrust protect-key");
406
+ else say(` ! The key stays in its private file (~/.worktrust/key.json): the ${VAULT_NAME} was not available. Retry: npx -y worktrust protect-key`);
407
+ return done;
408
+ }
384
409
  async function protectKey() {
385
410
  say(" Protect the WorkTrust token and signing key with this OS account's credential vault.");
386
411
  say(" Quit AI apps first; restart them after this finishes. Older bridges cannot read protected credentials.");
@@ -719,7 +744,7 @@ async function update() {
719
744
  const paths = await scripts();
720
745
  if (!doorState() && !has("dry-run")) saveDoorState({ mode: await chooseDoor(), asked: new Date().toISOString() }); // once, for a computer coupled before 0.10.37
721
746
  const doorIsOff = doorOff();
722
- const plan = await busyWith("Reading the AI apps on this computer", () => run(paths["setup-mcp.mjs"], ["--bridge", STABLE], PLACEHOLDER, true));
747
+ const plan = await busy("Reading the AI apps on this computer", () => run(paths["setup-mcp.mjs"], ["--bridge", STABLE], PLACEHOLDER, true));
723
748
  // AGREED BEFORE, REFRESHED WITHOUT A QUESTION (0.10.30): an app or hook the person said yes to is brought onto this
724
749
  // version's launcher; only what is NEW here is shown in full and asked about, and --yes leaves the new ones as they are.
725
750
  const agreed = await consent();
@@ -746,6 +771,9 @@ async function update() {
746
771
  say(` The session hook and ${STABLE} are brought to ${CLI_VERSION}.`);
747
772
  say(hookFresh ? ` + Session hook: ${join(homedir(), ".claude", "settings.json")} → SessionStart, SessionEnd, PreCompact and (at most once an hour) Stop run it · new` : ` ✓ Session hook: refreshed (${agreed.said("session-hook")}; since 0.10.32 it also runs after an answer, at most once an hour, so a long session's finished days arrive the same day)`);
748
773
  say(" The key stays as it is: no new pairing, the same computer in WorkTrust.");
774
+ // ONCE, AND SAID FIRST (0.11.12): a key still in its plain private file moves into the OS vault; --keep-key-file keeps it.
775
+ const moveKey = !keyStore.protected();
776
+ if (moveKey) say(has("keep-key-file") ? " The key stays in its private file (--keep-key-file); npx -y worktrust protect-key moves it later." : ` The key moves from its private file into the ${VAULT_NAME}, once (--keep-key-file keeps the file).`);
749
777
  say();
750
778
  if (has("dry-run")) { say(" Dry run: nothing was written and nothing was sent."); return; }
751
779
  const newOnes = [...fresh, ...(hookFresh ? ["Session hook"] : [])];
@@ -754,6 +782,8 @@ async function update() {
754
782
  else if (newOnes.length > 0) takeNew = await ask(`Couple the new ${newOnes.length === 1 ? "one" : "ones"} marked "new" (${newOnes.join(", ")})?`, false);
755
783
  if (newOnes.length > 0 && !takeNew && !has("yes")) say(" The new ones stay as they are. npx worktrust update asks again.");
756
784
  const skip = takeNew ? [] : fresh, hookOn = !hookFresh || takeNew;
785
+ // ONE WRITE STEP (0.11.12): the copy, every door out and in, the hook and the consent record; a stop waits for its end.
786
+ await critical(async () => {
757
787
  await prepareBundledRuntime();
758
788
  ensureHome();
759
789
  saveStableEntry();
@@ -768,10 +798,13 @@ async function update() {
768
798
  if (hookOn && (await run(paths["log-session.mjs"], hookArgs, key.token, false)).code !== 0) fail("installing the session hook failed; the output above says where.");
769
799
  for (const name of [...apps.filter((app) => !skip.includes(app)).map((app) => `door:${app}`), ...(hookOn ? ["session-hook"] : [])]) agreed.agree(name, "typed");
770
800
  agreed.save();
801
+ if (moveKey && !has("keep-key-file")) keyIntoVault(); // after this release's copy is in place, so the hook that reads it is this one
802
+ await plantDecoys?.({ dir: HOME_DIR, key, protectedMode: keyStore.protected(), proof, agent: `worktrust-cli/${CLI_VERSION}`, once: true });
803
+ });
771
804
  // Codex installed since, or a No said at connect: the one question, asked again (or "already set").
772
805
  await offerCodex();
773
806
  await offerAntigravity();
774
- const reported = await busyWith("Telling WorkTrust the version", () => accepted(key.url, key.token, key.device, doorModeAgent()));
807
+ const reported = await busy("Telling WorkTrust the version", () => accepted(key.url, key.token, key.device, doorModeAgent()));
775
808
  say(reported === true ? ` ✓ WorkTrust received CLI version ${CLI_VERSION}.` : " ! Installed locally. WorkTrust could not confirm the version yet; it will be reported on the next connection.");
776
809
  await offerRebuild(previous, paths, key);
777
810
  doubleDoorNotice();
@@ -812,7 +845,7 @@ async function connect() {
812
845
  const foundApps = planLines(plan.out, true).filter((line) => !line.includes("not on this machine"));
813
846
  for (const line of foundApps) say(line);
814
847
  if (foundApps.length === 0) say(" (no AI app found here yet; run connect again after installing one)");
815
- if (!direct) say(` 3. The key is kept in ${KEY_PLACE}, works only on this computer (every call is signed) and is renewed every week.`);
848
+ if (!direct) say(` 3. The key is kept in ${KEY_PLACE}, protected by the ${VAULT_NAME} where it can be, works only on this computer (every call is signed) and is renewed every week.`);
816
849
  say(` ${direct ? 3 : 4}. The session hook is installed:`);
817
850
  say(" + The hook and counter from the checked release, retained outside the package-manager cache");
818
851
  say(` + ${join(homedir(), ".claude", "settings.json")} → SessionStart, SessionEnd, PreCompact and (at most once an hour) Stop run it`);
@@ -832,12 +865,14 @@ async function connect() {
832
865
  // Claude Code is coupled through its own command, so its plan line reads "! … couple with": it is coupled all the same (0.10.4).
833
866
  const apps = foundApps.map((line) => /^\s*(?:[↻+✓] ([^:]+):|! ([^:]+): couple with)/.exec(line)).map((match) => match?.[1] ?? match?.[2]).filter(Boolean).slice(0, 12);
834
867
  const extra = { apps, ...computerIds(), ...(device ? { device_key: device.publicKey.export({ format: "jwk" }).x } : {}) };
835
- const pairing = useDevice() ? await pairByCode(host, extra) : await pairByBrowser(host, extra);
868
+ const pairing = await watched(() => (useDevice() ? pairByCode(host, extra) : pairByBrowser(host, extra))); // a wait: Esc in the menu ends it, nothing is written yet
836
869
  const { token } = pairing;
837
870
  // ANOTHER ACCOUNT THAN BEFORE: told by the opaque account names. Unknown counts as another, the safe side.
838
871
  const switched = Boolean(before) && !(before.accountRef && pairing.accountRef && before.accountRef === pairing.accountRef);
839
872
 
840
873
  say();
874
+ // ONE WRITE STEP (0.11.12): from the old doors out to the consent record; a stop waits for its end (cli-stop.mjs).
875
+ await critical(async () => {
841
876
  // Out first, then in: an app that already held a WorkTrust key moves to the new one.
842
877
  await run(paths["setup-mcp.mjs"], ["--remove", "--write"], token, true);
843
878
  if (!direct) {
@@ -846,6 +881,8 @@ async function connect() {
846
881
  ensureHome();
847
882
  saveStableEntry();
848
883
  say(` ✓ Key kept in ${KEY_PLACE}`);
884
+ keyIntoVault(); // 0.11.12: into the OS vault by default; where it cannot be, the file stays and one line says so
885
+ await plantDecoys?.({ dir: HOME_DIR, key: keyStore.load(), protectedMode: keyStore.protected(), proof, agent: `worktrust-cli/${CLI_VERSION}` });
849
886
  }
850
887
  saveDoorState({ mode: doorChoice, asked: new Date().toISOString() });
851
888
  if (doorChoice === "hours_only") say(` ✓ Hours only: no AI app gets the WorkTrust door (${DOOR_SWITCH})`);
@@ -861,6 +898,7 @@ async function connect() {
861
898
  // WHAT WAS AGREED HERE (0.10.30): the apps and the hook this "Continue?" covered; another account starts with none from before.
862
899
  if (switched) agreed.reset();
863
900
  for (const name of (doorChoice === "hours_only" ? [] : [...new Set(foundApps.map(labelOf).filter(Boolean))].map((app) => `door:${app}`)).concat("session-hook")) agreed.agree(name, has("yes") ? "flag" : "typed");
901
+ });
864
902
  await offerCodex();
865
903
  await offerAntigravity();
866
904
  if (switched) { say(); say(" Earlier work on this computer is not offered: it was coupled to another account before. Only work from now on goes to this account."); }
@@ -1036,7 +1074,7 @@ async function again() {
1036
1074
  * run was planned. Held-for-review batches stay held. Quiet when nothing was pending.
1037
1075
  */
1038
1076
  async function resendHistory(key) {
1039
- const paths = await scripts(), sent = await busyWith("Checking for earlier history still waiting", () => run(paths["log-session.mjs"], ["--history", "--resume"], key.token, true, { WORKTRUST_MCP_URL: key.url, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) }));
1077
+ const paths = await scripts(), sent = await busy("Checking for earlier history still waiting", () => critical(() => run(paths["log-session.mjs"], ["--history", "--resume"], key.token, true, { WORKTRUST_MCP_URL: key.url, ...(key.device ? { WORKTRUST_DEVICE_KEY: key.device } : {}) }))); // sends batches: a stop waits for the end
1040
1078
  let did = null;
1041
1079
  try { did = JSON.parse(sent.out.trim().split("\n").reverse().find((line) => line.startsWith('{"resumed"')) ?? "null"); } catch { /* nothing pending, or an older hook */ }
1042
1080
  if (Number(did?.resumed) > 0) { say(); say(` ✓ ${did.resumed} lines of earlier history that had not reached WorkTrust were sent; WorkTrust keeps them and rebuilds the days itself.`); }
@@ -1336,6 +1374,7 @@ async function disconnect() {
1336
1374
  say();
1337
1375
  if (has("dry-run")) { say(" Dry run: nothing was changed."); return; }
1338
1376
  if (!(await ask("Continue?"))) { say(" Stopped. Nothing was changed."); return; }
1377
+ await critical(async () => { // ONE WRITE STEP (0.11.12): doors, hook, credentials, consent and the copies; a stop waits for its end
1339
1378
  await run(paths["setup-mcp.mjs"], ["--remove", "--write"], PLACEHOLDER);
1340
1379
  await run(paths["log-session.mjs"], ["--uninstall", "--purge"], PLACEHOLDER);
1341
1380
  // 0.10.15: the WorkTrust mod goes with the coupling, and what it counted with it.
@@ -1349,6 +1388,7 @@ async function disconnect() {
1349
1388
  // Everything of ours on this computer goes; the folder too, when nothing else is left in it.
1350
1389
  for (const name of [STABLE_FILE, ...SCRIPTS.map((script) => join(HOME_DIR, downloaded(script))), join(HOME_DIR, "pinned")]) { try { rmSync(name); } catch { /* gone */ } }
1351
1390
  try { rmSync(HOME_DIR, { recursive: false }); } catch { /* not empty, or gone */ }
1391
+ });
1352
1392
  say();
1353
1393
  say(" Done. Revoke the key in WorkTrust to finish.");
1354
1394
  }
@@ -1427,7 +1467,7 @@ async function measuredHere() {
1427
1467
  const hook = join(HERE, "log-session.mjs");
1428
1468
  if (!hook) return;
1429
1469
  // Through the CLI's one way of starting a script (never a synchronous child: check-computer-pairing), with no door to send to.
1430
- const read = await busyWith("Counting what this computer measured", () => run(hook, ["--evidence-summary"], "", true, { WORKTRUST_MCP_URL: "", WORKTRUST_HOOK_INPUT: "" }));
1470
+ const read = await busy("Counting what this computer measured", () => run(hook, ["--evidence-summary"], "", true, { WORKTRUST_MCP_URL: "", WORKTRUST_HOOK_INPUT: "" }));
1431
1471
  let m = null;
1432
1472
  try { m = JSON.parse(read.out.trim().split("\n").filter((text) => text.startsWith("{")).pop()); } catch { return; }
1433
1473
  // 0.11.10: the lines are cli-look.mjs's measuredLines (pure; the changed files and the classes now say what they count).
@@ -1475,6 +1515,7 @@ async function preserve() {
1475
1515
  if (!existsSync(script)) fail("preserve runs from the package: npx worktrust@latest preserve");
1476
1516
  const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "preserve.mjs", args.filter((arg) => arg !== "preserve"))], { stdio: "inherit", env: { ...process.env, WORKTRUST_COLLECTOR: `worktrust-cli/${CLI_VERSION}` } });
1477
1517
  const pass = (signal) => { try { child.kill(signal); } catch { /* already gone */ } }; process.on("SIGINT", pass); process.on("SIGTERM", pass); // preserve.mjs stops safely, 130
1518
+ track(child);
1478
1519
  process.exitCode = await new Promise((resolve) => child.on("exit", (code, signal) => resolve(code ?? (signal ? 130 : 1))));
1479
1520
  }
1480
1521
 
@@ -1681,6 +1722,7 @@ async function doorCommand(sub) {
1681
1722
  const key = await freshKey();
1682
1723
  if (!key) fail("this computer has no WorkTrust key file yet. Run npx worktrust connect.");
1683
1724
  const paths = await scripts();
1725
+ await critical(async () => { // ONE WRITE STEP (0.11.12): the doors and the recorded mode; a stop waits for its end
1684
1726
  if (sub === "off") {
1685
1727
  if ((await run(paths["setup-mcp.mjs"], ["--remove", "--write"], key.token)).code !== 0) fail("taking the door out failed; the output above says where. Nothing was recorded.");
1686
1728
  saveDoorState({ mode: "hours_only", asked: doorState()?.asked ?? new Date().toISOString() });
@@ -1693,6 +1735,7 @@ async function doorCommand(sub) {
1693
1735
  saveDoorState({ mode: "work_lines", asked: doorState()?.asked ?? new Date().toISOString() });
1694
1736
  say(" ✓ The WorkTrust door is back: your AI can log finished work from now on. Nothing from the time it was off is sent.");
1695
1737
  }
1738
+ });
1696
1739
  const reported = await accepted(key.url, key.token, key.device, doorModeAgent());
1697
1740
  say(reported === true ? " ✓ WorkTrust was told the mode (shown under Sources, Devices)." : " ! Kept here; WorkTrust is told on the next connection.");
1698
1741
  doubleDoorNotice();
@@ -1704,6 +1747,7 @@ function help() {
1704
1747
  say();
1705
1748
  say(" worktrust in your terminal: the menu (every command below, with the short form it runs)");
1706
1749
  say(" npx -y worktrust skips npm's own \"Ok to proceed?\" question; --no-color (or NO_COLOR) turns colours off");
1750
+ say(" in the menu, Esc stops a running command; typed directly, Ctrl+C stops it, as always");
1707
1751
  say(" without a terminal, or with any option: couple this computer: show the plan, ask,");
1708
1752
  say(" approve in your browser (already coupled: shows what is coupled here)");
1709
1753
  say(" --dry-run the plan only: nothing is written, nothing is sent");
@@ -1717,6 +1761,7 @@ function help() {
1717
1761
  say(" refreshed without a question, a new AI app or hook is asked about (--yes: skipped)");
1718
1762
  say(" already on this version with nothing waiting: says so and changes nothing");
1719
1763
  say(" --force set everything up again all the same (the repair road)");
1764
+ say(" --keep-key-file keep the key in its private file (update moves it into the OS vault once, and says so)");
1720
1765
  say(" --rebuild yes in advance to the re-measure update offers after a new version (the plan is still shown)");
1721
1766
  say(" --codex yes in advance to letting Codex wake the session hook (also for connect)");
1722
1767
  say(" --antigravity yes in advance to letting Antigravity wake the session hook (also for connect)");
@@ -1751,7 +1796,8 @@ function help() {
1751
1796
  say(" the session hook keeps measuring your hours, and update leaves the door out");
1752
1797
  say(" worktrust mcp on the door back in, so your AI can log finished work (about 40 tokens per session)");
1753
1798
  say(" worktrust mcp which of the two this computer is in");
1754
- say(" worktrust protect-key after update: move credential protection into the OS vault (asks first)");
1799
+ say(" worktrust protect-key move credential protection into the OS vault (asks first); connect and update do it by");
1800
+ say(" themselves where the vault is there, and this is the retry when it was not");
1755
1801
  say(" worktrust orchestration report --file recording.jsonl inspect local agent metadata; sends nothing");
1756
1802
  say(" worktrust mod the WorkTrust mod for Claude Code: what it counts, and whether it is on");
1757
1803
  say(" install turn it on: counts permission answers, effort levels, context peaks and subagents (asks first)");
@@ -1821,10 +1867,18 @@ if (command === "default" && BUNDLED && (await import("./cli-menu.mjs")).menuWan
1821
1867
  catch { fail("The local WorkTrust key file is unsafe or damaged, or the OS vault is locked or unavailable. Unlock your OS vault and retry. Do not delete the key file or reset the keychain."); }
1822
1868
  let latest, latestKnown = false; // 0.11.9: whether the registry answered at all (no answer is not "up to date")
1823
1869
  let account = null, accountAt = 0; // 0.11.10: the account's type and Remote Agent's access, asked again after a minute or an upgrade
1870
+ // STOP WITH ESC (0.11.12, cli-stop.mjs): the child gets a channel to the menu. A command that asks questions reads Esc
1871
+ // itself while it is busy and asks the menu to stop it; for one that only reads, the menu reads the keys. Either way the
1872
+ // menu stops it (SIGINT, SIGTERM, SIGKILL as the last resort) and answers STOPPED, which runShown turns into one line.
1873
+ // The channel only where the child is Node itself (the Python launcher would not pass it on): elsewhere, as before.
1874
+ const stoppable = Boolean(superviseChild) && moduleExecutable(HERE) === process.execPath;
1824
1875
  const runCli = (cliArgs) => new Promise((resolve) => {
1825
- const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "worktrust.mjs", cliArgs)], { stdio: "inherit", env: { ...process.env, WORKTRUST_MENU: "off", WORKTRUST_RELAYED: "1", ...(has("no-color") || has("no-colour") ? { NO_COLOR: "1" } : {}) } });
1826
- child.on("error", () => resolve(1));
1827
- child.on("exit", (code, signal) => resolve(code ?? (signal ? 130 : 1))); // stopped by Ctrl+C: 130, which the first menu reads as cancelled
1876
+ const keys = readsOnly(cliArgs) ? { WORKTRUST_MENU_KEYS: "menu" } : {};
1877
+ const child = spawn(moduleExecutable(HERE), [...moduleArgs(HERE, "worktrust.mjs", cliArgs)], { stdio: stoppable ? ["inherit", "inherit", "inherit", "ipc"] : "inherit", env: { ...process.env, WORKTRUST_MENU: "off", WORKTRUST_RELAYED: "1", ...(stoppable ? { WORKTRUST_MENU_CHILD: "1", ...keys } : {}), ...(has("no-color") || has("no-colour") ? { NO_COLOR: "1" } : {}) } });
1878
+ const watch = stoppable ? superviseChild(child) : null;
1879
+ const release = watch && keys.WORKTRUST_MENU_KEYS ? menuKeys(process.stdin, { onEsc: watch.stop, onCtrlC: () => { try { child.kill("SIGINT"); } catch { /* gone */ } } }) : () => {};
1880
+ child.on("error", () => { release(); resolve(1); });
1881
+ child.on("exit", (code, signal) => { release(); resolve(watch?.stopped() ? STOPPED : code ?? (signal ? 130 : 1)); }); // stopped by Ctrl+C: 130, which the first menu reads as cancelled
1828
1882
  });
1829
1883
  const state = async () => {
1830
1884
  if (latest === undefined) { const v = await newestVersion(); latestKnown = v !== null; latest = v && semverNewer(v, CLI_VERSION) ? v : null; }