worktrust 0.11.5 → 0.11.7

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "worktrust",
3
- "version": "0.11.5",
3
+ "version": "0.11.7",
4
4
  "description": "Couple this computer to WorkTrust: approve a code in your browser, and every AI app here reports what you built. Metadata only, no dependencies.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -90,7 +90,14 @@
90
90
  "remote-pairing.mjs",
91
91
  "remote-qr.mjs",
92
92
  "remote-cli.mjs",
93
- "remote-agent-switch.mjs"
93
+ "remote-agent-switch.mjs",
94
+ "remote-settings.mjs",
95
+ "folder-picker.mjs",
96
+ "cli-menu.mjs",
97
+ "cli-menu-remote.mjs",
98
+ "remote-countdown.mjs",
99
+ "remote-connections.mjs",
100
+ "remote-admin.mjs"
94
101
  ],
95
102
  "engines": {
96
103
  "node": ">=18"
@@ -2,9 +2,10 @@
2
2
  * THE CLAUDE CODE ADAPTER, STRUCTURED (2026-11-07). One managed process per remote session:
3
3
  *
4
4
  * claude -p --input-format stream-json --output-format stream-json --verbose
5
- * --permission-mode <the mode its help lists for "ask", or plan>
5
+ * --permission-mode <the mode its help lists for manual, edit (acceptEdits), plan or auto; 0.11.7>
6
6
  * --permission-prompt-tool mcp__worktrust_remote__approve --mcp-config <this session's file>
7
- * [--model <a model the computer listed>] (--session-id <uuid chosen here> | --resume <the agent's own id>)
7
+ * [--model <a model the computer listed>] [--effort <a level its help lists>] [--add-dir <extra projects the
8
+ * computer resolved from its own inventory>] (--session-id <uuid chosen here> | --resume <the agent's own id>)
8
9
  *
9
10
  * in the granted project folder, in a process group of its own. Every argument comes from this file and the closed start
10
11
  * options the computer checked again (checkStart); no text from the phone becomes an argument except a resume id that is
@@ -15,6 +16,7 @@
15
16
  */
16
17
  import { spawn } from "node:child_process";
17
18
  import { writeFileSync, rmSync } from "node:fs";
19
+ import { isAbsolute } from "node:path";
18
20
  import { PLAN_HINT } from "./remote-approval-bridge.mjs";
19
21
 
20
22
  export const APPROVAL_TOOL = "mcp__worktrust_remote__approve";
@@ -43,19 +45,37 @@ export const PLAN_TOOLS = Object.freeze(["mcp__worktrust_remote__plan_release",
43
45
  /** The one line the session's system prompt gains (owner, 2026-11-08: the agent arranges its own work); one text, the bridge's. */
44
46
  export { PLAN_HINT };
45
47
 
46
- export function claudeArgs({ features, mode, model, resume, sessionRef, mcpConfig }) {
47
- if (mode !== "ask" && mode !== "plan") throw new Error("the protocol offers the ask and plan modes only");
48
- const permission = mode === "plan" ? features.planMode : features.askMode;
48
+ /**
49
+ * WHAT A SESSION THAT EDITS WITHOUT ASKING MAY STILL NEVER EDIT (CLI 0.11.7). In `edit` (acceptEdits) and `auto` Claude Code
50
+ * writes without the permission tool, so the files the computer's policy keeps at the keyboard (remote-policy.mjs RULE_FILE
51
+ * and SCRIPT_FILE: permission rules, hooks, the repository's own config, and the files that say what a reviewed command
52
+ * runs) are denied outright: an edited package.json would turn the phone's next reviewed `npm test` into anything.
53
+ */
54
+ export const EDIT_MODE_DENY = Object.freeze(["**/.claude/**", "**/.mcp.json", "**/.claude.json", "**/.codex/**", "**/.cursor/**", "**/.git/**", "**/.husky/**", "**/.vscode/**", "**/.idea/**",
55
+ "**/.envrc", "**/.npmrc", "**/.yarnrc", "**/.yarnrc.yml", "**/.gitattributes", "**/.gitmodules", "**/package.json", "**/Makefile", "**/justfile", "**/pyproject.toml", "**/setup.py", "**/setup.cfg",
56
+ "**/tox.ini", "**/noxfile.py", "**/conftest.py", "**/pytest.ini", "**/Cargo.toml", "**/build.rs", "**/go.mod", "**/deno.json", "**/turbo.json", "**/nx.json", "**/*.config.js", "**/*.config.mjs", "**/*.config.cjs", "**/*.config.ts"]
57
+ .flatMap((glob) => [`Edit(${glob})`, `Write(${glob})`, `NotebookEdit(${glob})`]));
58
+
59
+ /** The agent mode (protocol AGENT_MODES; the older `ask` is `manual`) → Claude Code's own permission mode, from its help. */
60
+ const PERMISSION_OF = { ask: "askMode", manual: "askMode", plan: "planMode", edit: "editMode", auto: "autoMode" };
61
+
62
+ export function claudeArgs({ features, mode, model, resume, sessionRef, mcpConfig, effort = null, addDirs = [] }) {
63
+ if (!Object.hasOwn(PERMISSION_OF, mode)) throw new Error("the protocol offers the manual, edit, plan and auto modes only");
64
+ const permission = features[PERMISSION_OF[mode]];
49
65
  if (!permission) throw new Error("this Claude Code offers no such permission mode");
66
+ if (effort !== null && !(features.efforts ?? []).includes(effort)) throw new Error("this Claude Code offers no such effort level");
67
+ if (!Array.isArray(addDirs) || addDirs.some((d) => typeof d !== "string" || !isAbsolute(d))) throw new Error("an extra project is an absolute path the computer resolved");
68
+ if (addDirs.length > 0 && !features.addDir) throw new Error("this Claude Code takes no extra directories");
69
+ const unasked = mode === "edit" || mode === "auto";
50
70
  if (resume !== null && !isClaudeSessionId(resume)) throw new Error("a resume id is Claude Code's own session uuid");
51
71
  if (resume === null && !isClaudeSessionId(sessionRef)) throw new Error("a new session needs its uuid");
52
72
  if (model !== null && (typeof model !== "string" || model.startsWith("-") || !/^[A-Za-z0-9._:@\[\]-]{1,128}$/.test(model))) throw new Error("not a model name");
53
73
  if (!features.disallowed || !features.settingSources) throw new Error("this Claude Code cannot take deny rules or limit its setting sources");
54
74
  // --replay-user-messages: Claude Code echoes each user message as it reads it (isReplay), which is how a live steer is
55
75
  // known to have entered the running turn (remote-steering.mjs; measured on 2.1.286: at the next tool boundary).
56
- return ["-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", ...(features.replay ? ["--replay-user-messages"] : []), "--permission-mode", permission, "--setting-sources", "user", "--disallowedTools", ...REMOTE_DENY,
76
+ return ["-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose", ...(features.replay ? ["--replay-user-messages"] : []), "--permission-mode", permission, "--setting-sources", "user", "--disallowedTools", ...REMOTE_DENY, ...(unasked ? EDIT_MODE_DENY : []),
57
77
  ...(features.allowed ? ["--allowedTools", ...PLAN_TOOLS] : []), ...(features.appendPrompt ? ["--append-system-prompt", PLAN_HINT] : []),
58
- "--permission-prompt-tool", APPROVAL_TOOL, "--mcp-config", mcpConfig, ...(features.partial ? ["--include-partial-messages"] : []), ...(model ? ["--model", model] : []), ...(resume ? ["--resume", resume] : ["--session-id", sessionRef])];
78
+ "--permission-prompt-tool", APPROVAL_TOOL, "--mcp-config", mcpConfig, ...(features.partial ? ["--include-partial-messages"] : []), ...(model ? ["--model", model] : []), ...(effort ? ["--effort", effort] : []), ...(addDirs.length ? ["--add-dir", ...addDirs] : []), ...(resume ? ["--resume", resume] : ["--session-id", sessionRef])];
59
79
  }
60
80
 
61
81
  /** The session's MCP config: our bridge only, its socket and its one-time token. Mode 0600, removed with the session. */
@@ -0,0 +1,109 @@
1
+ /**
2
+ * THIS COMPUTER'S SETTINGS FROM THE APP OR THE WEB (part B of CLI 0.11.7, owner 2026-11-12; docs/remote-agents/PROTOCOL.md
3
+ * §Managing a computer from the app). A phone or a browser sends ONE change, sealed in `device.configure { settings_change:
4
+ * { change, proof } }`, with a proof the Passport app signed after the person's authenticator answered for that exact change
5
+ * (crypto/admin.ts). This file is the computer's half:
6
+ *
7
+ * adminRefusal the gate, in this order: `remote admin on` at the keyboard (off: refused, whatever the proof); the proof
8
+ * verified against the issuer keys PINNED in this build, for THIS computer's device id and account, for
9
+ * the change as it arrived, unexpired, and its jti never spent here (spent ones are kept in
10
+ * admin-proofs.json past their expiry). Every refusal leaves every setting as it was.
11
+ * resolveAdminChange the change in the keyboard's own terms, resolved from THIS computer's lists by id: a folder by
12
+ * the id of a folder this computer suggested (folderSuggestions, its own HMAC), a new folder by one name
13
+ * made in the home folder (makeProjectsFolder), a root by its id, a connection by its device id. No
14
+ * path is ever read from the change: there is no field to read one from, and none is looked for.
15
+ * adminInventory what the settings page draws, sealed only for a phone that asked `extended`: the admin switch, the
16
+ * suggested folders with their project counts, and the connections by name.
17
+ *
18
+ * remote-settings.mjs applySettingsChange calls adminRefusal and resolveAdminChange for a source `{ kind: "admin" }` and
19
+ * then applies the result through the SAME rules as a typed command (checkRoot, MAX_ROOTS, removePhones).
20
+ */
21
+ import { createHmac } from "node:crypto";
22
+ import { homedir } from "node:os";
23
+ import { makeProjectsFolder, suggestedFolders } from "./folder-picker.mjs";
24
+ import { connections } from "./remote-connections.mjs";
25
+ import { checkRoot, rootLabel } from "./remote-projects.mjs";
26
+ import * as P from "./remote-protocol.mjs";
27
+ import { ensureRemoteDir, loadKeys, loadRoots, readJson, writeJson } from "./remote-store.mjs";
28
+
29
+ const SPENT_FILE = "admin-proofs.json";
30
+ const MAX_SPENT = 500;
31
+
32
+ /** A stable opaque id for a folder this computer suggests: an HMAC of its path under the computer's own secret. */
33
+ export const folderIdOf = (projectSecret, path) =>
34
+ `fld_${P.toBase64Url(createHmac("sha256", Buffer.from(projectSecret)).update(`worktrust-remote/v1/folder\n${path}`).digest().subarray(0, 16))}`;
35
+
36
+ /** The folders this computer suggests for projects (its own detected ones), each with its id and the root it already is. */
37
+ export function folderSuggestions(projectSecret, home = homedir(), roots = loadRoots()) {
38
+ return suggestedFolders(home).slice(0, 12).map((f) => {
39
+ const canonical = checkRoot(f.path);
40
+ const root = canonical.ok ? roots.find((r) => r.path === canonical.path) : null;
41
+ return { folder_id: folderIdOf(projectSecret, f.path), label: rootLabel(f.path), projects: Math.min(2000, f.projects), root_id: root?.root_id ?? null, path: f.path };
42
+ });
43
+ }
44
+
45
+ /** The inventory's part-B fields (sealed for an `extended` phone only, remote-daemon.mjs bodyFor). */
46
+ export function adminInventory({ projectSecret, settings }) {
47
+ return {
48
+ admin: settings.admin !== false,
49
+ folders: projectSecret ? folderSuggestions(projectSecret).map(({ path: _path, ...f }) => f) : [],
50
+ connections: connections().slice(0, 40).map((c) => ({ device_id: c.device_id, name: String(c.name).slice(0, 64), kind: c.kind, fingerprint: c.fingerprint, state: c.state, since: c.since ?? null, last_seen: c.last_seen ?? null })),
51
+ };
52
+ }
53
+
54
+ /** One use per proof: a jti is spent here before its change is applied, and kept until its proof has expired. */
55
+ export function spendAdminJti(jti, expSeconds, now = Date.now()) {
56
+ const kept = (readJson(SPENT_FILE, { spent: [] })?.spent ?? []).filter((s) => s && typeof s.jti === "string" && Number.isFinite(s.exp) && s.exp * 1000 + P.CLOCK_SKEW_MS >= now);
57
+ if (kept.some((s) => s.jti === jti)) return "seen";
58
+ ensureRemoteDir();
59
+ writeJson(SPENT_FILE, { spent: [...kept, { jti, exp: expSeconds }].slice(-MAX_SPENT) });
60
+ return "fresh";
61
+ }
62
+
63
+ const CODE_OF = { expired: "expired", lifetime: "expired", not_yet_valid: "expired", replay: "conflict" };
64
+ const SAID = { expired: "the approval expired (five minutes): change it again", conflict: "that approval was used already", not_allowed: "the approval does not hold for this computer and this change" };
65
+
66
+ /**
67
+ * THE GATE. `source`: { kind: "admin", proof, issuerKeys, claims, now } where issuerKeys are the daemon's pinned keys and
68
+ * claims this computer's own verified binding. → null when the change may be applied, else { reason, code } (the code is
69
+ * the protocol's reject reason: not_allowed, expired, conflict).
70
+ */
71
+ export function adminRefusal(change, source, settings) {
72
+ if (settings.admin === false) return { code: "not_allowed", reason: "managing this computer from the app or the web is off here (npx worktrust remote admin on)" };
73
+ const shaped = P.validate(P.ADMIN_CHANGE_SPEC, change);
74
+ if (!shaped.ok || P.adminChangeRule(change)) return { code: "not_allowed", reason: "not a change this computer takes from the app" };
75
+ if (typeof source?.proof !== "string" || !source.claims || !source.issuerKeys) return { code: "not_allowed", reason: SAID.not_allowed };
76
+ const verified = P.verifyAdminProof(source.proof, { issuerKeys: source.issuerKeys, now: source.now ?? Date.now(), deviceId: source.claims.device_id, sub: source.claims.sub, change, spendJti: (jti, exp) => spendAdminJti(jti, exp, source.now ?? Date.now()) });
77
+ if (!verified.ok) { const code = CODE_OF[verified.code] ?? "not_allowed"; return { code, reason: SAID[code] }; }
78
+ return null;
79
+ }
80
+
81
+ /**
82
+ * The change in the keyboard's terms, resolved from this computer's own lists by id; → { ok: true, change, setting } or
83
+ * { ok: false, code: "not_found" | "unsupported", reason }.
84
+ */
85
+ export function resolveAdminChange(change, projectSecret = loadKeys()?.projectSecret) {
86
+ const missing = (reason) => ({ ok: false, code: "not_found", reason });
87
+ const setting = P.settingOf(change);
88
+ if (change.what === "modes") return { ok: true, setting, change: { what: "modes", [change.allowed ? "allow" : "deny"]: change.mode } };
89
+ if (change.what === "folder") {
90
+ const found = projectSecret ? folderSuggestions(projectSecret).find((f) => f.folder_id === change.folder_id) : null;
91
+ return found ? { ok: true, setting, change: { what: "roots", add: found.path, git_init: false } } : missing("that folder is not one this computer suggests any more");
92
+ }
93
+ if (change.what === "new_folder") {
94
+ if (!P.adminFolderNameOk(change.name)) return { ok: false, code: "unsupported", reason: "one folder name" };
95
+ const made = makeProjectsFolder(change.name);
96
+ return made.ok ? { ok: true, setting, change: { what: "roots", add: made.path, git_init: true } } : { ok: false, code: "unsupported", reason: made.reason };
97
+ }
98
+ if (change.what === "root") {
99
+ const root = loadRoots().find((r) => r.root_id === change.root_id);
100
+ if (!root) return missing("no root by that id here");
101
+ if (change.act === "remove") return { ok: true, setting, change: { what: "roots", remove: root.root_id } };
102
+ return { ok: true, setting, change: { what: "roots", add: root.path, git_init: change.act === "git_init_on" } };
103
+ }
104
+ const link = connections().find((c) => c.device_id === change.device_id);
105
+ return link ? { ok: true, setting, change: { what: "connections", remove: link.fingerprint } } : missing("no phone or browser by that id is linked here");
106
+ }
107
+
108
+ /** The words the run terminal shows for a change from the app (remote-run.mjs notice). */
109
+ export const SETTING_WORDS = Object.freeze({ modes: "This computer's allowed modes", folders: "This computer's folders", roots: "This computer's roots", connections: "This computer's connections" });
@@ -20,7 +20,7 @@ import { createServer } from "node:net";
20
20
  import { chmodSync, existsSync, mkdirSync, rmSync } from "node:fs";
21
21
  import { join } from "node:path";
22
22
  import * as P from "./remote-protocol.mjs";
23
- import { classifyAction, phoneMayDecide } from "./remote-policy.mjs";
23
+ import { classifyAction, phoneMayDecide, projectForAction } from "./remote-policy.mjs";
24
24
 
25
25
  export const APPROVAL_LIFETIME_MS = 5 * 60_000;
26
26
 
@@ -42,7 +42,7 @@ export function createApprovals(ctx) {
42
42
  /** One permission request from the bridge → the answer the bridge gives Claude Code. */
43
43
  async function request(session, toolName, input, preset = null) {
44
44
  if (ctx.paused()) return deny("WorkTrust remote is paused on this computer; denied");
45
- const { action, reason } = preset ?? classifyAction(session.adapter, toolName, input, session.projectPath);
45
+ const { action, reason } = preset ?? classifyAction(session.adapter, toolName, input, projectForAction(session, input));
46
46
  if (!phoneMayDecide(action)) {
47
47
  ctx.emit(session.session_id, "agent.output_delta", { stream: "tool", offset: 0, text: `Denied on the computer (${action.tool}): ${reason}` }, session.command_id);
48
48
  return deny(`WorkTrust remote: ${reason}`);
package/remote-cli.mjs CHANGED
@@ -2,20 +2,30 @@
2
2
  * `npx worktrust remote ...`: STEER THIS COMPUTER'S AGENTS FROM YOUR PHONE (2026-11-07). Opt-in, at this keyboard only (an
3
3
  * AI agent's shell is refused by worktrust.mjs, `status` excepted). docs/remote-agents/PROTOCOL.md is the contract.
4
4
  *
5
- * remote enable [--gateway <wss://…>] [--device] pair this computer's REMOTE keys (not the measurement key) in the
6
- * Passport app, start the service, show a pairing QR
5
+ * remote app | web [--gateway <wss://…>] [--device] make this computer's REMOTE keys (not the measurement key), have
6
+ * them approved in the WorkTrust app (a QR here, no browser) | in the
7
+ * browser's approval page, start the service, show a pairing QR.
8
+ * `remote enable`, which asked which of the two, is gone (owner,
9
+ * 2026-11-12, CLI 0.11.7): an unknown subcommand that names them
7
10
  * remote pair a new QR for a phone (five minutes, one phone, once)
8
11
  * remote status [--json] what is on, paired, running, granted and installed
9
12
  * remote pause | resume refuse every command for now | take them again
10
13
  * remote disable [--forget] the hard off: the service removed; --forget also deletes the keys
14
+ * remote connections every phone and browser linked here, and this computer's own link
15
+ * remote disconnect <n|name|fingerprint> | --all close one (y, then its short fingerprint or name typed) | every one
16
+ * (`close all` typed); remote-connections.mjs
11
17
  * remote phones [confirm <id> | remove <id>|--all] phones: pending ones are confirmed here; --all cuts every one at once
12
18
  * remote phones allow-endorse on|off may a confirmed phone add a browser it scanned (default off)
13
19
  * remote projects add <folder> | remove <id> | list the folders a phone may steer an agent in
14
20
  * remote run the daemon in the foreground (Windows runs only this way)
15
21
  * remote pipeline review <folder> | status read a granted folder's .worktrust/pipeline.json, show every stage
16
22
  * and command, and on a typed yes let a phone start it (pins a hash)
17
- * remote roots add <dir> [--git-init] | remove <id|dir> | list parent folders where a phone may create ONE new, empty
18
- * project folder (project.create); --git-init runs `git init` in it
23
+ * remote roots add <dir> [--git-init] | remove <id|dir> | list parent folders where a phone may open the git projects
24
+ * already in them (0.11.7) and create ONE new, empty project folder
25
+ * (project.create); --git-init runs `git init` in it
26
+ * remote modes allow|deny edit|auto | status the ceiling of agent modes a phone may start (0.11.7; default manual
27
+ * and plan), remote-settings.mjs
28
+ * remote admin on|off RESERVED: managing this computer from the app or the web (part B)
19
29
  * remote preview allow|deny <port|file> <folder> | list what a phone may preview: a dev-server port on 127.0.0.1 or a
20
30
  * built HTML file, per granted folder (rendered with your Chrome)
21
31
  * remote codex on | off offer Codex to a phone (off by default): Codex runs the reads it
@@ -31,9 +41,11 @@ import { basename } from "node:path";
31
41
  import { hostname } from "node:os";
32
42
  import { createInterface } from "node:readline/promises";
33
43
  import * as P from "./remote-protocol.mjs";
34
- import { ensureRemoteDir, isLoopbackGateway, issuerKeys, loadIdentity, loadKeys, loadPhones, loadProjects, loadSettings, newKeys, projectIdOf, random, readJson, removeFile, saveIdentity, saveKeys, savePhones, saveProjects, saveSettings, writeJson } from "./remote-store.mjs";
44
+ import { ensureRemoteDir, isLoopbackGateway, issuerKeys, loadIdentity, loadKeys, loadPhones, loadProjects, loadSettings, newKeys, random, readJson, removeFile, saveIdentity, saveKeys, savePhones, saveSettings, writeJson } from "./remote-store.mjs";
35
45
  import { canonicalProject } from "./remote-policy.mjs";
36
- import { IssuerMissing, PairingRefused, pairComputer } from "./remote-pairing.mjs";
46
+ import { IssuerMissing, PairingDenied, PairingExpired, PairingRefused, pairComputer } from "./remote-pairing.mjs";
47
+ import { startCountdown, waitKey } from "./remote-countdown.mjs";
48
+ import { askLine, connectionsCommand, disconnectCommand, removePhones } from "./remote-connections.mjs";
37
49
  import { installService, removeService, serviceState, servicePlatform } from "./remote-service.mjs";
38
50
  import { qrMatrix, renderQr } from "./remote-qr.mjs";
39
51
  import { webSocketAvailable } from "./remote-transport.mjs";
@@ -42,8 +54,9 @@ import { allowCommand, parsePipelineConfig, PIPELINE_FILE } from "./remote-pipel
42
54
  import { pipelineState, projectReviewHash, readProjectFile } from "./remote-pipeline.mjs";
43
55
  import { openJournal } from "./remote-journal.mjs";
44
56
  import { loadPreviewGrants, savePreviewGrants } from "./remote-store.mjs";
45
- import { loadDeskMarks, loadPipelineReviews, loadRoots, remotePath, saveDeskMarks, savePipelineReviews, saveRoots } from "./remote-store.mjs";
46
- import { checkRoot, MAX_ROOTS, rootIdOf, rootLabel } from "./remote-projects.mjs";
57
+ import { loadDeskMarks, loadPipelineReviews, loadRoots, remotePath, saveDeskMarks, savePipelineReviews } from "./remote-store.mjs";
58
+ import { rootLabel } from "./remote-projects.mjs";
59
+ import { adminCommand, allowedModes, applySettingsChange, askMacFolderAccess, folderCheck, modesCommand } from "./remote-settings.mjs";
47
60
 
48
61
  const fingerprintOf = (keys) => P.deviceFingerprint(keys.public);
49
62
  const pretty = (code) => `${code.slice(0, 4)}-${code.slice(4)}`;
@@ -58,11 +71,12 @@ export async function askTyped(question) {
58
71
 
59
72
  function needPaired(io) {
60
73
  const keys = loadKeys(), identity = loadIdentity();
61
- if (!keys || !identity) io.fail("this computer is not paired for remote yet: run `npx worktrust remote enable`");
74
+ if (!keys || !identity) io.fail("this computer is not paired for remote yet: run `npx worktrust remote app` (or `remote web`)");
62
75
  return { keys, identity };
63
76
  }
64
77
 
65
- async function enable(io) {
78
+ /** `remote app` | `remote web`: the two roads to approve this computer; each does all of what `remote enable` did. */
79
+ async function approve(io, road) {
66
80
  if (!webSocketAvailable()) io.fail(`remote needs Node 22.4 or later for its connection (this is ${process.versions.node}); the Python package bundles one`);
67
81
  const settings = loadSettings();
68
82
  const gateway = io.flag("gateway") ?? process.env.WORKTRUST_REMOTE_GATEWAY ?? settings.gateway;
@@ -81,7 +95,18 @@ async function enable(io) {
81
95
  const keys = newKeys();
82
96
  const pub = P.publicKeysOf(P.importSecretKeys(keys));
83
97
  try {
84
- const paired = await pairComputer({ origin: io.origin, secret: P.importSecretKeys(keys), publicKeys: pub, host: hostname(), os: io.os, device: io.has("device"), issuerKeys: issuerKeys(gateway), say: io.say, openBrowser: io.openBrowser });
98
+ // The request's own clock under the QR or link (remote-countdown.mjs); after an expiry, Enter asks again with a new one.
99
+ let paired = null;
100
+ while (!paired) {
101
+ try {
102
+ paired = await pairComputer({ origin: io.origin, secret: P.importSecretKeys(keys), publicKeys: pub, host: hostname(), os: io.os, device: io.has("device"), road, showQr: (link) => io.say(renderQr(qrMatrix(link).modules, { color: Boolean(process.stdout.isTTY) && !process.env.NO_COLOR })), issuerKeys: issuerKeys(gateway), say: io.say, openBrowser: io.openBrowser, countdown: (w) => startCountdown(w) });
103
+ } catch (error) {
104
+ if (error instanceof PairingDenied) return;
105
+ if (!(error instanceof PairingExpired) || !process.stdin.isTTY) throw error;
106
+ io.say(` Press Enter for a new ${road === "app" ? "QR code" : "approval page"}, or q to quit.`);
107
+ if ((await waitKey()) !== "enter") return;
108
+ }
109
+ }
85
110
  saveKeys(keys);
86
111
  identity = { v: 1, device_id: paired.device_id, binding: paired.binding, sub: paired.sub, origin: io.origin, paired_at: Date.now() };
87
112
  saveIdentity(identity);
@@ -92,19 +117,20 @@ async function enable(io) {
92
117
  }
93
118
  } else io.say(` Already paired (${identity.device_id}); --repair pairs again with new keys.`);
94
119
  saveSettings({ ...settings, enabled: true, paused: null, gateway: gateway ?? null, agent_path: process.env.PATH ?? null });
95
- if (loadProjects().length === 0) io.say(" No folder is granted yet: npx worktrust remote projects add <folder>");
120
+ if (loadProjects().length === 0 && loadRoots().length === 0) io.say(" No folder is granted yet: npx worktrust remote roots add <folder> (or the menu: npx worktrust › Remote Agent › Roots)");
96
121
  if (!gateway) { io.say(" No gateway is set: the production gateway is not live yet. Nothing runs until one is (--gateway)."); return; }
97
- if (servicePlatform() === "foreground") { io.say(" Windows: there is no service; run `npx worktrust remote run` and keep that terminal open."); return; }
122
+ if (servicePlatform() === "foreground") { io.say(" ✓ This computer is connected to Remote Agent."); io.say(" Windows: there is no service; run `npx worktrust remote run` and keep that terminal open."); return; }
98
123
  const runtime = await io.prepare();
99
124
  const service = installService({ program: [runtime.node, ...runtime.nodeArgs, runtime.entry, "remote", "run"], path: process.env.PATH ?? "" });
100
125
  io.say(service.started ? ` ✓ The service runs (${service.kind}, while you are logged in; linger stays off).` : ` ! The service file was written (${service.file}) but did not start; run \`npx worktrust remote run\` to see why.`);
126
+ if (service.started) io.say(" ✓ This computer is connected to Remote Agent.");
101
127
  if (!io.has("no-pair")) await pair(io);
102
128
  }
103
129
 
104
130
  async function pair(io) {
105
131
  const { keys, identity } = needPaired(io);
106
132
  const settings = loadSettings();
107
- if (!settings.enabled || !settings.gateway) io.fail("remote is off or has no gateway: run `npx worktrust remote enable`");
133
+ if (!settings.enabled || !settings.gateway) io.fail("remote is off or has no gateway: run `npx worktrust remote app` (or `remote web`)");
108
134
  const started = Date.now();
109
135
  const invite = P.createPairingInvite({ gateway: settings.gateway, deviceId: identity.device_id, ed25519_pub: keys.public.ed25519_pub, x25519_pub: keys.public.x25519_pub, nowMs: started, random });
110
136
  const code = P.generatePairingCode(random);
@@ -157,14 +183,13 @@ async function phones(io, rest) {
157
183
  if (rest[0] === "remove" && (rest[1] === "--all" || io.has("all"))) { // EVERY DEVICE OFF, FROM THE SOURCE (owner, 2026-11-09): the daemon reads this list per message
158
184
  const all = [...list.confirmed, ...list.pending], at = Date.now(); if (all.length === 0) return io.say(" No phone or browser is connected to this computer.");
159
185
  if (process.stdin.isTTY && !(await askTyped(` Disconnect all ${all.length} phones and browsers from this computer now?`))) return io.say(" Nothing changed.");
160
- savePhones({ ...list, pending: [], confirmed: [], removed: [...list.removed.filter((p) => !all.some((x) => x.device_id === p.device_id)), ...all.map((p) => ({ device_id: p.device_id, fingerprint: p.fingerprint, how: "keyboard", removed_at: at }))].slice(-20) });
186
+ removePhones(all.map((p) => p.fingerprint), at);
161
187
  return io.say(` ✓ Disconnected ${all.length}: none of them can steer this computer any more. Live sessions they started keep running here; stop them with npx worktrust remote disable, or pause everything with npx worktrust remote pause.\n End their keys for your whole account too: app.worktrust.io › Settings › Remote Agent, or Remote Agent settings on your phone.`);
162
188
  }
163
189
  if (rest[0] === "remove") {
164
190
  const phone = find(rest[1]);
165
191
  if (!phone) io.fail("no phone by that fingerprint or id");
166
- savePhones({ ...list, pending: list.pending.filter((p) => p.fingerprint !== phone.fingerprint), confirmed: list.confirmed.filter((p) => p.fingerprint !== phone.fingerprint),
167
- removed: [...list.removed.filter((p) => p.device_id !== phone.device_id), { device_id: phone.device_id, fingerprint: phone.fingerprint, how: "keyboard", removed_at: Date.now() }].slice(-20) });
192
+ removePhones([phone.fingerprint]);
168
193
  io.say(` ✓ Removed ${phone.fingerprint}: it can no longer steer this computer. Revoke it in WorkTrust too.`);
169
194
  return;
170
195
  }
@@ -182,25 +207,18 @@ async function phones(io, rest) {
182
207
  }
183
208
  }
184
209
 
210
+ /** A change at this keyboard, through the one door (remote-settings.mjs); macOS is asked at once for a guarded folder. */
211
+ async function settingsChange(io, change) {
212
+ if (change.add !== undefined) needPaired(io);
213
+ const done = applySettingsChange(change, { kind: "keyboard" });
214
+ if (!done.ok) io.fail(done.reason);
215
+ io.say(` ✓ ${done.message}`);
216
+ if (done.paths && !io.has("no-folder-check")) await askMacFolderAccess(io, done.paths);
217
+ }
218
+
185
219
  function projects(io, rest) {
186
220
  const list = loadProjects();
187
- if (rest[0] === "add") {
188
- const { keys } = needPaired(io);
189
- const canonical = canonicalProject(rest[1]);
190
- if (!canonical.ok) io.fail(`not granted: ${canonical.reason}`);
191
- const project_id = projectIdOf(keys.projectSecret, canonical.path);
192
- if (!list.some((p) => p.project_id === project_id)) saveProjects([...list, { project_id, path: canonical.path, added_at: Date.now() }]);
193
- io.say(` ✓ Granted: ${canonical.path}`);
194
- return;
195
- }
196
- if (rest[0] === "remove") {
197
- const canonical = canonicalProject(rest[1] ?? "");
198
- const kept = list.filter((p) => p.project_id !== rest[1] && p.path !== rest[1] && !(canonical.ok && p.path === canonical.path));
199
- if (kept.length === list.length) io.fail("no granted folder by that path or id");
200
- saveProjects(kept);
201
- io.say(" ✓ Removed.");
202
- return;
203
- }
221
+ if (rest[0] === "add" || rest[0] === "remove") return settingsChange(io, { what: "projects", [rest[0]]: rest[1] ?? "" });
204
222
  io.say(` Granted folders (${list.length}):`);
205
223
  for (const p of list) io.say(` ${p.path} (${basename(p.path)})`);
206
224
  }
@@ -208,23 +226,8 @@ function projects(io, rest) {
208
226
  /** `remote roots …`: where a phone may create a new project folder, added here at the keyboard only. */
209
227
  function roots(io, rest) {
210
228
  const list = loadRoots();
211
- if (rest[0] === "add") {
212
- const { keys } = needPaired(io);
213
- const root = checkRoot(rest[1] ?? "");
214
- if (!root.ok) io.fail(`not added: ${root.reason}`);
215
- if (list.length >= MAX_ROOTS && !list.some((r) => r.path === root.path)) io.fail(`at most ${MAX_ROOTS} roots`);
216
- const root_id = rootIdOf(keys.projectSecret, root.path);
217
- saveRoots([...list.filter((r) => r.root_id !== root_id), { root_id, path: root.path, git_init: io.has("git-init"), added_at: Date.now() }]);
218
- io.say(` ✓ Root: ${root.path} (${rootLabel(root.path)}). A phone may create one new, empty folder in it per request${io.has("git-init") ? ", with git init" : ""}.`);
219
- return;
220
- }
221
- if (rest[0] === "remove") {
222
- const kept = list.filter((r) => r.root_id !== rest[1] && r.path !== rest[1] && r.path !== checkRoot(rest[1] ?? "").path);
223
- if (kept.length === list.length) io.fail("no root by that path or id");
224
- saveRoots(kept);
225
- io.say(" ✓ Removed. Projects made in it stay granted: npx worktrust remote projects remove <folder>.");
226
- return;
227
- }
229
+ if (rest[0] === "add") return settingsChange(io, { what: "roots", add: rest[1] ?? "", git_init: io.has("git-init") });
230
+ if (rest[0] === "remove") return settingsChange(io, { what: "roots", remove: rest[1] ?? "" });
228
231
  io.say(` Roots (${list.length}):`);
229
232
  for (const r of list) io.say(` ${r.path} (${rootLabel(r.path)}${r.git_init ? ", git init" : ""})`);
230
233
  }
@@ -281,7 +284,7 @@ function status(io) {
281
284
  const settings = loadSettings(), identity = loadIdentity(), keys = identity ? loadKeys() : null, phonesList = loadPhones(), service = serviceState();
282
285
  const agents = inventory({ env: { ...process.env, PATH: settings.agent_path ?? process.env.PATH } }).reports.filter((r) => r.installed);
283
286
  const summary = { enabled: settings.enabled, paused: settings.paused, paired: Boolean(identity), device_id: identity?.device_id ?? null, fingerprint: keys ? fingerprintOf(keys) : null,
284
- gateway: settings.gateway, service, node_websocket: webSocketAvailable(), phones: { confirmed: phonesList.confirmed.length, pending: phonesList.pending.length, browsers_added: phonesList.confirmed.filter((p) => p.how === "endorsed").length, allow_endorse: settings.allow_endorse === true }, projects: loadProjects().length,
287
+ gateway: settings.gateway, service, node_websocket: webSocketAvailable(), phones: { confirmed: phonesList.confirmed.length, pending: phonesList.pending.length, browsers_added: phonesList.confirmed.filter((p) => p.how === "endorsed").length, allow_endorse: settings.allow_endorse === true }, projects: loadProjects().length, modes_allowed: allowedModes(settings), admin: settings.admin !== false,
285
288
  agents: agents.map((a) => ({ adapter: a.adapter, version: a.version, adapter_ready: a.capabilities.start, switched_off: a.capabilities.start && (a.adapter === "codex" || a.adapter === "opencode") && settings[a.adapter] !== true, models: a.models === null ? "not listed" : a.models.length })), invite_open: Boolean(readJson("invite.json")?.used === false) };
286
289
  if (io.has("json")) { io.say(JSON.stringify(summary, null, 2)); return; }
287
290
  io.say(` Remote: ${settings.enabled ? (settings.paused ? `paused (${settings.paused === "desk" ? "here" : "from a phone"})` : "on") : "off"}`);
@@ -290,12 +293,13 @@ function status(io) {
290
293
  io.say(` Service: ${service.kind === "foreground" ? "none on this system: run `npx worktrust remote run`" : `${service.installed ? "installed" : "not installed"}, ${service.running ? "running" : "not running"}`}`);
291
294
  io.say(` Phones: ${summary.phones.confirmed} confirmed (${summary.phones.browsers_added} browsers added by a phone), ${summary.phones.pending} pending · Folders granted: ${summary.projects}`);
292
295
  io.say(` Phones may add a browser: ${summary.phones.allow_endorse ? "yes" : "no"}`);
296
+ io.say(` Agent modes a phone may start: ${allowedModes(settings).join(", ")} (npx worktrust remote modes)`);
293
297
  for (const a of summary.agents) io.say(` Agent: ${a.adapter} ${a.version ?? ""} · ${a.switched_off ? `installed, switched off: npx worktrust remote ${a.adapter} on` : a.adapter_ready ? "remote adapter ready" : "installed, no adapter yet"} · models: ${a.models}`);
294
298
  }
295
299
 
296
300
  export async function remoteCommand(args, io) {
297
301
  const [sub = "help", ...rest] = args;
298
- if (sub === "enable") return enable(io);
302
+ if (sub === "app" || sub === "web") return approve(io, sub);
299
303
  if (sub === "pair") return pair(io);
300
304
  if (sub === "status") return status(io);
301
305
  if (sub === "pause" || sub === "resume") { const s = loadSettings(); saveSettings({ ...s, paused: sub === "pause" ? "desk" : null }); io.say(sub === "pause" ? " Paused: every command from a phone is refused until `npx worktrust remote resume`." : " Resumed."); return; }
@@ -307,10 +311,15 @@ export async function remoteCommand(args, io) {
307
311
  return;
308
312
  }
309
313
  if (sub === "phones") return phones(io, rest);
314
+ if (sub === "connections") return connectionsCommand(io);
315
+ if (sub === "disconnect") return disconnectCommand(io, rest, askLine);
310
316
  if (sub === "projects") return projects(io, rest);
311
317
  if (sub === "run") return (await import("./remote-run.mjs")).runDaemon({ say: io.say });
312
318
  if (sub === "pipeline") return pipeline(io, rest);
313
319
  if (sub === "roots") return roots(io, rest);
320
+ if (sub === "modes") return modesCommand(io, rest);
321
+ if (sub === "admin") return adminCommand(io, rest);
322
+ if (sub === "folder-check") return folderCheck(); // internal: the one-shot launchd job of askMacFolderAccess
314
323
  if (sub === "preview") {
315
324
  const grants = loadPreviewGrants();
316
325
  if (rest[0] === "allow" || rest[0] === "deny") {
@@ -335,5 +344,6 @@ export async function remoteCommand(args, io) {
335
344
  if (sub === "releases") return releasesCommand(io, rest);
336
345
  if (sub === "terminal") return (await import("./remote-terminal-cli.mjs")).terminalCommand(io, rest, askTyped);
337
346
  if (sub === "attach") return (await import("./remote-terminal-cli.mjs")).attachCommand(io, rest);
338
- io.say(" npx worktrust remote enable | pair | status | pause | resume | disable [--forget] | phones [confirm|remove <id>|remove --all|allow-endorse on|off] | projects add|remove|list | run | pipeline review <folder>|status | roots add|remove|list | preview allow|deny|list | codex on|off | opencode on|off | terminal on|off|list|start | attach <id> | releases [released <n>]");
347
+ if (sub !== "help") { io.say(sub === "enable" ? " Unknown command: remote enable. Use `npx worktrust remote app` (approve with your phone) or `npx worktrust remote web` (approve in the browser)." : ` Unknown command: remote ${sub}. The remote commands are below.`); process.exitCode = 1; }
348
+ io.say(" npx worktrust remote app | web | pair | connections | disconnect <n|name|fingerprint>|--all | status | pause | resume | disable [--forget] | phones [confirm|remove <id>|remove --all|allow-endorse on|off] | projects add|remove|list | run | pipeline review <folder>|status | roots add|remove|list | modes allow|deny edit|auto|status | admin on|off | preview allow|deny|list | codex on|off | opencode on|off | terminal on|off|list|start | attach <id> | releases [released <n>]");
339
349
  }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * WHAT IS LINKED TO THIS COMPUTER, AND CLOSING IT (CLI 0.11.7, owner 2026-11-12). `remote connections` lists every phone and
3
+ * browser linked to this computer (name, kind, fingerprint, since, last seen) and this computer's own link; `remote
4
+ * disconnect <number | name | fingerprint>` closes one after TWO confirmations (y, then its short fingerprint or its name
5
+ * typed), and `remote disconnect --all` closes every one after `close all` typed exactly. Both are the same removal as
6
+ * `remote phones remove` (kept, and folded onto removePhones here): the phone leaves the confirmed and pending lists for
7
+ * `removed`, which the daemon reads per message, so it can no longer steer this computer. Its key for the whole account
8
+ * is ended in WorkTrust (Settings › Remote Agent), as before. No prompt without a terminal: the command refuses instead.
9
+ *
10
+ * The computer knows a phone by its keys only: the "name" is its kind and the start of its fingerprint ("Phone 9M8N"),
11
+ * never a model name it was not told.
12
+ */
13
+ import { createInterface } from "node:readline/promises";
14
+ import { loadIdentity, loadKeys, loadPhones, savePhones } from "./remote-store.mjs";
15
+ import * as P from "./remote-protocol.mjs";
16
+
17
+ const KEEP_REMOVED = 20;
18
+ const when = (ms) => (Number.isFinite(ms) ? new Date(ms).toISOString().slice(0, 16).replace("T", " ") : "never");
19
+ export const shortPrint = (fingerprint) => String(fingerprint ?? "").replace(/[^A-Za-z0-9]/g, "").slice(0, 4).toUpperCase();
20
+
21
+ /** A line typed at this keyboard (the typed confirmations below). */
22
+ export async function askLine(question) {
23
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
24
+ const answer = await prompt.question(`${question} `);
25
+ prompt.close();
26
+ return answer;
27
+ }
28
+
29
+ /** Every phone and browser, numbered from 1: confirmed first, then pending. */
30
+ export function connections(phones = loadPhones()) {
31
+ const row = (p, state) => {
32
+ const kind = p.how === "endorsed" ? "browser" : p.kind === "browser" ? "browser" : "phone";
33
+ return { device_id: p.device_id, fingerprint: p.fingerprint, kind, state, name: p.name ?? `${kind === "browser" ? "Browser" : "Phone"} ${shortPrint(p.fingerprint)}`, since: p.confirmed_at ?? p.seen_at ?? null, last_seen: p.seen_at ?? null };
34
+ };
35
+ return [...phones.confirmed.map((p) => row(p, "confirmed")), ...phones.pending.map((p) => row(p, "pending"))].map((c, i) => ({ n: i + 1, ...c }));
36
+ }
37
+
38
+ /** One connection by its number in the list, its name, its fingerprint (whole, or its first four) or its device id. */
39
+ export function findConnection(list, key) {
40
+ const k = String(key ?? "").trim();
41
+ if (!k) return null;
42
+ if (/^\d{1,3}$/.test(k)) return list.find((c) => c.n === Number(k)) ?? null;
43
+ const upper = k.toUpperCase();
44
+ return list.find((c) => c.device_id === k || c.fingerprint.toUpperCase() === upper || c.name.toLowerCase() === k.toLowerCase())
45
+ ?? (shortPrint(k).length === 4 ? list.filter((c) => shortPrint(c.fingerprint) === shortPrint(k)).at(0) ?? null : null);
46
+ }
47
+
48
+ /** Take phones off this computer, the one removal `remote phones remove` and `remote disconnect` share. */
49
+ export function removePhones(fingerprints, at = Date.now()) {
50
+ const phones = loadPhones(), gone = new Set(fingerprints);
51
+ const out = [...phones.confirmed, ...phones.pending].filter((p) => gone.has(p.fingerprint));
52
+ savePhones({ ...phones, pending: phones.pending.filter((p) => !gone.has(p.fingerprint)), confirmed: phones.confirmed.filter((p) => !gone.has(p.fingerprint)),
53
+ removed: [...phones.removed.filter((p) => !out.some((x) => x.device_id === p.device_id)), ...out.map((p) => ({ device_id: p.device_id, fingerprint: p.fingerprint, how: "keyboard", removed_at: at }))].slice(-KEEP_REMOVED) });
54
+ return out.length;
55
+ }
56
+
57
+ /** `remote connections`. */
58
+ export function connectionsCommand(io) {
59
+ const identity = loadIdentity(), keys = identity ? loadKeys() : null;
60
+ io.say(identity ? ` This computer: ${identity.device_id} · key ${P.deviceFingerprint(keys.public)} · linked ${when(identity.paired_at)}` : " This computer: not linked to Remote Agent (npx worktrust remote app)");
61
+ const list = connections();
62
+ io.say(` Linked to it (${list.length}):`);
63
+ for (const c of list) io.say(` ${String(c.n).padStart(2)} ${c.name.padEnd(16)} ${c.kind.padEnd(8)} ${c.fingerprint} since ${when(c.since)} · last seen ${when(c.last_seen)}${c.state === "pending" ? " (pending: npx worktrust remote phones confirm " + c.fingerprint + ")" : ""}`);
64
+ if (list.length) io.say(" Close one: npx worktrust remote disconnect <number|name|fingerprint> all: npx worktrust remote disconnect --all");
65
+ }
66
+
67
+ /**
68
+ * `remote disconnect <key> | --all`. `ask(question)` → the typed answer (a terminal's line); tests pass their own. Without a
69
+ * terminal it refuses: closing a link is confirmed by a person at this keyboard.
70
+ */
71
+ export async function disconnectCommand(io, rest, ask, tty = Boolean(process.stdin.isTTY)) {
72
+ const list = connections();
73
+ const all = rest[0] === "--all" || io.has("all");
74
+ if (!tty) return io.fail("closing a connection is confirmed at this keyboard: run it in a terminal");
75
+ if (list.length === 0) return io.say(" No phone or browser is linked to this computer.");
76
+ if (all) {
77
+ io.say(` This closes every connection to this computer (${list.length}):`);
78
+ for (const c of list) io.say(` ${c.name} (${c.kind}, ${c.fingerprint})`);
79
+ if ((await ask(" Type close all to confirm:")).trim() !== "close all") return io.say(" Cancelled. Nothing was closed.");
80
+ const n = removePhones(list.map((c) => c.fingerprint));
81
+ io.say(` ✓ Closed ${n}: none of them can steer this computer any more. End their keys for your whole account too: app.worktrust.io › Settings › Remote Agent.`);
82
+ return;
83
+ }
84
+ const c = findConnection(list, rest[0]);
85
+ if (!c) return io.fail("no connection by that number, name or fingerprint (npx worktrust remote connections lists them)");
86
+ if (!/^y(es)?$/i.test((await ask(` Disconnect ${c.name} (${c.fingerprint})? It can no longer steer this computer. [y/N]`)).trim())) return io.say(" Cancelled. Nothing was closed.");
87
+ const typed = (await ask(` To confirm, type ${shortPrint(c.fingerprint)} (the start of its fingerprint) or its name:`)).trim();
88
+ if (typed.toUpperCase() !== shortPrint(c.fingerprint) && typed.toLowerCase() !== c.name.toLowerCase()) return io.say(" That does not match. Cancelled. Nothing was closed.");
89
+ removePhones([c.fingerprint]);
90
+ io.say(` ✓ Disconnected ${c.name}: it can no longer steer this computer. End its key for your whole account too: app.worktrust.io › Settings › Remote Agent.`);
91
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * THE APPROVAL'S CLOCK IN THE TERMINAL (CLI 0.11.7, owner 2026-11-12, after testing `remote app` live). While `remote app`
3
+ * or `remote web` waits for the approval, a bar under the QR or link drains over the request's own window (the issuer's
4
+ * answer, never a fixed ten minutes), redrawn in place once a second: `[████████░░░░] 7:41 left`. Without a terminal the
5
+ * expiry time is printed once. The bar reads no key and never touches raw mode; waitKey (the "new QR code?" question after
6
+ * an expiry) does, and always gives it back.
7
+ */
8
+ import { emitKeypressEvents } from "node:readline";
9
+
10
+ export const BAR_WIDTH = 24;
11
+ const clock = (ms) => { const s = Math.max(0, Math.ceil(ms / 1000)); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; };
12
+
13
+ /** One line of the bar for `left` of `windowMs` milliseconds. Pure. */
14
+ export function barLine(left, windowMs, width = BAR_WIDTH) {
15
+ const share = windowMs > 0 ? Math.min(1, Math.max(0, left / windowMs)) : 0;
16
+ const full = Math.round(share * width);
17
+ return `[${"█".repeat(full)}${"░".repeat(width - full)}] ${clock(left)} left`;
18
+ }
19
+
20
+ /** Start the bar; → { stop(finalLine?) }. `out` is stdout, `tty` whether it is a terminal, `now` the clock. */
21
+ export function startCountdown({ expiresAt, windowMs, out = process.stdout, tty = Boolean(process.stdout.isTTY), now = Date.now }) {
22
+ if (!tty) {
23
+ out.write(` This request expires at ${new Date(expiresAt).toTimeString().slice(0, 5)} (in ${clock(expiresAt - now())}).\n`);
24
+ return { stop: (line) => { if (line) out.write(` ${line}\n`); } };
25
+ }
26
+ const draw = () => out.write(`\r\x1b[2K ${barLine(expiresAt - now(), windowMs)}`);
27
+ draw();
28
+ const timer = setInterval(draw, 1000);
29
+ timer.unref?.();
30
+ let stopped = false;
31
+ return {
32
+ stop(line) {
33
+ if (stopped) return;
34
+ stopped = true;
35
+ clearInterval(timer);
36
+ out.write(`\r\x1b[2K${line ? ` ${line}` : ""}\n`);
37
+ },
38
+ };
39
+ }
40
+
41
+ /** One key from a terminal: "enter", "q" or another; null without a terminal. Raw mode only for that key, always restored. */
42
+ export function waitKey(input = process.stdin) {
43
+ if (!input.isTTY) return Promise.resolve(null);
44
+ emitKeypressEvents(input);
45
+ return new Promise((resolve) => {
46
+ const done = (value) => { input.off("keypress", on); try { input.setRawMode(false); } catch { /* gone */ } input.pause(); resolve(value); };
47
+ const on = (str, k = {}) => done(k.ctrl && k.name === "c" ? "q" : k.name === "return" || k.name === "enter" ? "enter" : (k.name ?? str ?? "").toLowerCase());
48
+ try { input.setRawMode(true); } catch { resolve(null); return; }
49
+ input.resume();
50
+ input.on("keypress", on);
51
+ });
52
+ }