mapsource-node 0.1.2 → 0.1.3

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/README.md CHANGED
@@ -36,3 +36,22 @@ them.
36
36
 
37
37
  Use `mapsource-node --help` for the CLI and [RELEASING.md](RELEASING.md) for
38
38
  publishing.
39
+ # Local intelligence services
40
+
41
+ Open **Services** in `mapsource-node` to inspect installed intelligence
42
+ workers and the selected worker's active dataset path. Use **E** to start and
43
+ enable the systemd unit at boot or to stop and disable it. Disable retains the
44
+ dataset. Use **M** to enter a directory on another mounted filesystem and
45
+ confirm the move. The directory must already exist and be writable by the
46
+ service user, with enough free space for the copy and filesystem reserve.
47
+
48
+ The move verifies the destination against the source checksum and restarts
49
+ an active worker. A failed readiness check restores the prior settings.
50
+ The original copy remains available for rollback. For a stopped unit, the
51
+ copy is verified and the next start uses the new path.
52
+
53
+ `mapsource-node retire --services ID[,ID]` previews reclaimable enrollment
54
+ data. Adding `--apply` requires an interactive review, a yes confirmation
55
+ and the exact retirement phrase before requesting deletion. The enrollment
56
+ authority also checks for a current preview and confirms there is a verified
57
+ surviving source copy.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mapsource-node",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "Mapsource node operations and enrollment",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
package/src/commands.mjs CHANGED
@@ -6,6 +6,7 @@ import { createInterface } from "node:readline/promises";
6
6
  import { parseArgs, promisify } from "node:util";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { measureHost, planServices, validateCatalog } from "./capability.mjs";
9
+ import { installedServices, moveServiceDataset, setServiceEnabled } from "./service-management.mjs";
9
10
  import { catalogDigest, enrollmentRequest, localIdentity, operatorRequest, readEnrollment, readInvitation, saveEnrollment, secretInput } from "./enrollment.mjs";
10
11
 
11
12
  const mirrorRoot = "/srv/mapsource-mirror";
@@ -30,6 +31,10 @@ const usage = `Mapsource Node
30
31
  mapsource-node Open the terminal dashboard
31
32
  mapsource-node --json Read current fleet telemetry
32
33
  mapsource-node services List profiles offered by the local authority
34
+ mapsource-node local-services List installed intelligence units and dataset locations
35
+ mapsource-node service enable ID Enable and start one local unit
36
+ mapsource-node service disable ID Disable and stop one local unit
37
+ mapsource-node service move ID DIRECTORY Copy, verify and switch an installed dataset
33
38
  mapsource-node invite --node NAME [--services ID[,ID]] [--out FILE]
34
39
  mapsource-node revoke --node NAME Revoke an unused sync key
35
40
  mapsource-node setup [--key-file FILE | --key-stdin] [--services ID[,ID]] [--apply]
@@ -197,6 +202,13 @@ export async function main(command, args) {
197
202
  if (command === "setup") { await setup(args); return; }
198
203
  if (command === "resume" && !args.length) { show(await resume()); return; }
199
204
  if (command === "services" && !args.length) { show((await operatorRequest("catalog", {})).catalog.services); return; }
205
+ if (command === "local-services" && !args.length) { show(await installedServices()); return; }
206
+ if (command === "service") {
207
+ const [action, id, directory] = args;
208
+ if (["enable", "disable"].includes(action) && id && args.length === 2) { await setServiceEnabled(id, action === "enable"); return; }
209
+ if (action === "move" && id && directory && args.length === 3) { show(await moveServiceDataset(id, directory)); return; }
210
+ throw new Error("Use service enable ID, service disable ID or service move ID DIRECTORY.");
211
+ }
200
212
  if (command === "invite" || command === "revoke") {
201
213
  const options = flags(args, command === "invite" ? { node: { type: "string" }, out: { type: "string" }, ...servicesOption } : { node: { type: "string" } });
202
214
  if (!options.node) throw new Error("Pass --node NAME.");
@@ -223,8 +235,22 @@ export async function main(command, args) {
223
235
  const options = flags(args, command === "status" ? {} : { ...servicesOption, apply: { type: "boolean" } });
224
236
  const saved = await readEnrollment();
225
237
  if (saved.pendingClaim) throw new Error("Waiting for sync key confirmation. Run mapsource-node setup.");
226
- show(await enrollmentRequest(saved.endpoint, command, { node: saved.node, preview: !options.apply,
227
- ...(options.services && { services: ids(options.services) }) }, { identity: await localIdentity() }));
238
+ const services = options.services ? [...new Set(ids(options.services))].sort() : undefined;
239
+ const identity = await localIdentity();
240
+ const invoke = (preview, approval = {}) => enrollmentRequest(saved.endpoint, command, { node: saved.node, preview,
241
+ ...(services && { services }), ...approval }, { identity });
242
+ if (command === "retire" && options.apply) {
243
+ if (!services?.length || !process.stdin.isTTY) throw new Error("Retirement requires an interactive terminal and explicit service IDs.");
244
+ const { confirmation, expiresAt, ...plan } = await invoke(true);
245
+ show(plan);
246
+ if ((await input("Remove these services and their exclusive dataset copies? [y/N] ")).toLowerCase() !== "y") return;
247
+ const phrase = "RETIRE " + services.join(",");
248
+ if (await input("Type " + phrase + " to confirm: ") !== phrase) return;
249
+ if (expiresAt && expiresAt <= Date.now()) throw new Error("The reviewed retirement plan expired. Review it again.");
250
+ show(await invoke(false, { confirmation, confirm: phrase }));
251
+ return;
252
+ }
253
+ show(await invoke(!options.apply));
228
254
  return;
229
255
  }
230
256
  throw new Error("Unknown command. Run mapsource-node --help.");
package/src/index.ts CHANGED
@@ -12,9 +12,11 @@ const [arg, ...remaining] = process.argv.slice(2);
12
12
  function bindKeys(renderer: CliRenderer, ui: ReturnType<typeof nodeInterface>, refresh: () => void) {
13
13
  renderer.keyInput.on("paste", event => {
14
14
  if (ui.tab() === 3) { event.preventDefault(); ui.enrollment.paste(new TextDecoder().decode(event.bytes)); }
15
+ if (ui.tab() === 2) { event.preventDefault(); ui.management.paste(new TextDecoder().decode(event.bytes)); }
15
16
  });
16
17
  renderer.keyInput.on("keypress", key => {
17
18
  if (ui.tab() === 3 && ui.enrollment.keypress(key)) { key.preventDefault(); return; }
19
+ if (ui.tab() === 2 && ui.management.keypress(key)) { key.preventDefault(); return; }
18
20
  if (key.name === "q" || key.name === "escape") renderer.destroy();
19
21
  else if (key.name === "r") { if (ui.tab() === 3) void ui.enrollment.refresh(); else refresh(); }
20
22
  else if (key.name === "left") ui.navigate(ui.tab() - 1);
@@ -71,6 +73,8 @@ else if (arg === "--self-test" && !remaining.length) {
71
73
  } finally { renderer.destroy(); }
72
74
  const { testEnrollmentScreen } = await import("./enrollment-screen-test.ts");
73
75
  await testEnrollmentScreen(bindKeys, createTestRenderer);
76
+ const { testServiceScreen } = await import("./service-screen-test.ts");
77
+ await testServiceScreen();
74
78
  console.log("mapsource-node self-test " + version);
75
79
  } else if (arg !== undefined || !process.stdin.isTTY || !process.stdout.isTTY) {
76
80
  process.stderr.write(arg === undefined ? "A terminal is required. SSH with -t or use mapsource-node --json.\n" : usage);
package/src/interface.ts CHANGED
@@ -3,6 +3,7 @@ import type { CliRenderer, RenderContext } from "@opentui/core";
3
3
  import { mapsourcePalette as palette } from "./palette.ts";
4
4
  import type { Telemetry } from "./telemetry.ts";
5
5
  import { enrollmentScreen, type enrollmentActions } from "./enrollment-screen.ts";
6
+ import { serviceScreen, type serviceActions } from "./service-screen.ts";
6
7
 
7
8
  const tabs = ["Overview", "Fleet", "Services", "Enrollment"] as const;
8
9
  const compactTabs = ["Node", "Fleet", "Svc", "Enroll"] as const;
@@ -27,11 +28,12 @@ const stateColor = (state: string) => {
27
28
  return value.includes("unavailable") ? red : amber;
28
29
  };
29
30
 
30
- export function nodeInterface(renderer: CliRenderer, version: string, actions?: typeof enrollmentActions) {
31
+ export function nodeInterface(renderer: CliRenderer, version: string, actions?: typeof enrollmentActions, manager?: typeof serviceActions) {
31
32
  let selected = 0, snapshot: Telemetry | null = null;
32
33
  let closed = false;
33
34
  renderer.once("destroy", () => { closed = true; });
34
35
  const enrollment = enrollmentScreen(() => { if (selected === 3 && !closed) paint(); }, value => renderer.copyToClipboardOSC52(value), actions);
36
+ const management = serviceScreen(() => { if (selected === 2 && !closed) paint(); }, manager);
35
37
  const history = new Map<string, { latency: (number | null)[]; queued: (number | null)[] }>();
36
38
  // OpenTUI's renderer getter types omit undefined on optional context fields.
37
39
  const context = renderer as unknown as RenderContext;
@@ -161,10 +163,17 @@ export function nodeInterface(renderer: CliRenderer, version: string, actions?:
161
163
  section.add(entry);
162
164
  }
163
165
  viewport.add(section);
166
+ } else if (selected === 2) {
167
+ const section = panel("MANAGE LOCAL SERVICES");
168
+ for (const line of management.view()) {
169
+ section.add(new TextRenderable(context, { content: line.text, fg: line.action ? good : palette.paper,
170
+ wrapMode: "char", flexShrink: 0, ...(line.action && { onMouseUp: line.action }) }));
171
+ }
172
+ viewport.add(section);
173
+ if (snapshot) services(snapshot);
164
174
  } else if (!snapshot) viewport.add(text("Reading node, fleet, and public status…", muted));
165
175
  else if (selected === 0) overview(snapshot);
166
176
  else if (selected === 1) fleet(snapshot);
167
- else services(snapshot);
168
177
  viewport.scrollTop = oldOffset;
169
178
  }
170
179
 
@@ -176,6 +185,7 @@ export function nodeInterface(renderer: CliRenderer, version: string, actions?:
176
185
  viewport.scrollTop = 0;
177
186
  paint();
178
187
  if (selected === 3) void enrollment.refresh();
188
+ if (selected === 2) void management.refresh();
179
189
  }
180
190
 
181
191
  return {
@@ -193,6 +203,7 @@ export function nodeInterface(renderer: CliRenderer, version: string, actions?:
193
203
  },
194
204
  navigate,
195
205
  enrollment,
206
+ management,
196
207
  tab: () => selected,
197
208
  scroll(lines: number) { viewport.scrollBy(lines); },
198
209
  };
@@ -0,0 +1,172 @@
1
+ import { execFile } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { constants, createReadStream } from "node:fs";
4
+ import { copyFile, link, lstat, mkdtemp, open, readFile, readdir, realpath, rm, statfs, writeFile } from "node:fs/promises";
5
+ import { tmpdir, userInfo } from "node:os";
6
+ import path from "node:path";
7
+ import { setTimeout as pause } from "node:timers/promises";
8
+ import { parseEnv, promisify } from "node:util";
9
+
10
+ const run = promisify(execFile);
11
+ const configRoot = "/etc/mapsource-intelligence";
12
+ const systemdRoot = "/etc/systemd/system";
13
+ const safeRole = /^[a-z][a-z0-9-]{0,47}$/;
14
+ const safePath = /^\/[A-Za-z0-9_./-]+$/;
15
+ const protectedRoots = ["/srv/geo", "/media/roko/sdb1/noclip-maps/openfreemap", "/media/roko/sdb1/noclip-maps/tileserver"];
16
+ const within = (file, root) => file === root || file.startsWith(root + "/");
17
+ const unitName = role => `mapsource-intelligence@${role}.service`;
18
+ const serviceControl = (action, unit) => run("/usr/bin/sudo", ["-n", "/usr/bin/systemctl", ...action, unit], { timeout: 40_000 });
19
+
20
+ async function readService(role) {
21
+ if (!safeRole.test(role)) throw Error("Use a managed Mapsource service ID.");
22
+ const unit = unitName(role);
23
+ const configFile = path.join(configRoot, role + ".env");
24
+ const [config, result] = await Promise.all([
25
+ readFile(configFile, "utf8"),
26
+ run("/usr/bin/systemctl", ["show", unit, "--property=LoadState,ActiveState,UnitFileState,User"], { timeout: 6000 }),
27
+ ]);
28
+ const env = parseEnv(config), status = parseEnv(result.stdout);
29
+ const { MAPSOURCE_INTELLIGENCE_ROLE: name, MAPSOURCE_INTELLIGENCE_DATABASE: database, MAPSOURCE_INTELLIGENCE_BUNDLE: bundle,
30
+ MAPSOURCE_INTELLIGENCE_SOCKET: socket } = env;
31
+ if (name !== role || status.LoadState !== "loaded" || !safePath.test(database ?? "") || !safePath.test(bundle ?? "")
32
+ || socket !== `/run/mapsource-intelligence-${role}/read.sock`) throw Error("The local unit does not expose managed dataset settings.");
33
+ return { role, unit, configFile, config, env, database, bundle, socket, user: status.User,
34
+ active: status.ActiveState === "active", enabled: status.UnitFileState === "enabled", state: status.ActiveState };
35
+ }
36
+
37
+ export async function installedServices() {
38
+ const files = await readdir(configRoot).catch(error => {
39
+ if (error.code === "ENOENT") return [];
40
+ throw error;
41
+ });
42
+ const roles = files.filter(file => file.endsWith(".env") && safeRole.test(file.slice(0, -4))).map(file => file.slice(0, -4)).sort();
43
+ return Promise.all(roles.map(async role => {
44
+ try {
45
+ const { role: id, database, active, enabled, state } = await readService(role);
46
+ return { id, database, active, enabled, state };
47
+ } catch {
48
+ return { id: role, database: null, active: false, enabled: false, state: "unverified" };
49
+ }
50
+ }));
51
+ }
52
+
53
+ async function ready(socket) {
54
+ for (let attempt = 0; attempt < 12; attempt++) {
55
+ try {
56
+ const result = await run("/usr/bin/curl", ["--fail", "--silent", "--max-time", "2", "--unix-socket", socket, "http://localhost/ready"],
57
+ { timeout: 2500, maxBuffer: 200_000 });
58
+ const value = JSON.parse(result.stdout);
59
+ if (value.ready && typeof value.dataset?.release === "string") return value.dataset.release;
60
+ } catch { /* A restarting unit may need a moment to open its socket. */ }
61
+ await pause(450);
62
+ }
63
+ throw Error("The worker did not verify its dataset through the readiness socket.");
64
+ }
65
+
66
+ export async function setServiceEnabled(role, enabled) {
67
+ const service = await readService(role);
68
+ await serviceControl([enabled ? "enable" : "disable", "--now"], service.unit);
69
+ try {
70
+ if (enabled) await ready(service.socket);
71
+ const status = await readService(role);
72
+ if (status.enabled !== enabled || status.active !== enabled) throw Error("systemd did not reach the requested service state.");
73
+ } catch (error) {
74
+ if (enabled && !service.enabled) await serviceControl(["disable", ...(service.active ? [] : ["--now"])], service.unit);
75
+ throw error;
76
+ }
77
+ }
78
+
79
+ async function writableDataDirectory(value) {
80
+ if (!safePath.test(value) || path.resolve(value) !== value || value === "/" || value.startsWith("/etc/")
81
+ || protectedRoots.some(root => within(value, root))) throw Error("Use an existing absolute directory on the destination data volume.");
82
+ if (await realpath(value) !== value) throw Error("Choose the real directory path without symbolic links.");
83
+ const info = await lstat(value);
84
+ if (!info.isDirectory() || info.uid !== process.getuid() || info.mode & 0o022) {
85
+ throw Error("The destination must belong to the service user and be private to that user for writes.");
86
+ }
87
+ const { stdout } = await run("/usr/bin/findmnt", ["--json", "--target", value, "--output", "TARGET,FSROOT,OPTIONS"], { timeout: 5000 });
88
+ const mount = JSON.parse(stdout).filesystems?.[0];
89
+ if (!mount || mount.fsroot !== "/" || mount.options.split(",").includes("ro")) {
90
+ throw Error("Use a writable data volume with a direct filesystem mount.");
91
+ }
92
+ return value;
93
+ }
94
+
95
+ async function hash(file) {
96
+ const digest = createHash("sha256");
97
+ for await (const chunk of createReadStream(file)) digest.update(chunk);
98
+ return digest.digest("hex");
99
+ }
100
+
101
+ /** Copy an immutable release, then switch only this systemd unit. */
102
+ export async function moveServiceDataset(role, directory) {
103
+ const service = await readService(role);
104
+ if (service.user !== userInfo().username || service.user === "root") throw Error("Run Mapsource Node as the local service user.");
105
+ const target = await writableDataDirectory(directory);
106
+ const source = String(await realpath(service.database));
107
+ const sourceInfo = await lstat(source);
108
+ if (protectedRoots.some(root => within(source, root)) || !sourceInfo.isFile() || sourceInfo.uid !== process.getuid()
109
+ || sourceInfo.mode & 0o222 || !/^[a-z0-9-]+\.sqlite$/.test(path.basename(source))) {
110
+ throw Error("The active path must be an operator-owned, immutable Mapsource dataset.");
111
+ }
112
+ const nextDatabase = path.join(target, path.basename(source));
113
+ if (nextDatabase === source) throw Error("The dataset is already in this directory.");
114
+ const [disk, existing] = await Promise.all([statfs(target), lstat(nextDatabase).catch(error => {
115
+ if (error.code !== "ENOENT") throw error;
116
+ return null;
117
+ })]);
118
+ const free = disk.bsize * disk.bavail;
119
+ if (!existing && (disk.ffree < 8 || free - sourceInfo.size < disk.bsize * disk.blocks * 0.25)) {
120
+ throw Error("The dataset copy would exceed the destination's available storage.");
121
+ }
122
+ const priorRelease = service.active ? await ready(service.socket) : null;
123
+ const identityFile = path.join(systemdRoot, unitName(role) + ".d", "identity.conf");
124
+ const identity = await readFile(identityFile, "utf8");
125
+ const mounts = /^RequiresMountsFor=\/[^\r\n]+$/m;
126
+ if (!mounts.test(identity)) throw Error("The installed unit does not declare a dataset mount.");
127
+ const scratch = await mkdtemp(path.join(target, "mapsource-move-"));
128
+ try {
129
+ const digest = await hash(source);
130
+ if (!existing) {
131
+ const staged = path.join(scratch, "dataset.sqlite");
132
+ await copyFile(source, staged, constants.COPYFILE_EXCL | constants.COPYFILE_FICLONE);
133
+ if (await hash(staged) !== digest) throw Error("The copy failed checksum verification.");
134
+ const file = await open(staged, "r");
135
+ try { await file.sync(); } finally { await file.close(); }
136
+ await link(staged, nextDatabase);
137
+ const parent = await open(target, "r");
138
+ try { await parent.sync(); } finally { await parent.close(); }
139
+ } else if (!existing.isFile() || existing.uid !== process.getuid() || existing.mode & 0o222 || await hash(nextDatabase) !== digest) {
140
+ throw Error("The destination already contains a different dataset.");
141
+ }
142
+ if ((await readService(role)).config !== service.config) throw Error("The service changed while the dataset was being copied.");
143
+ const local = await mkdtemp(path.join(tmpdir(), "mapsource-service-config-"));
144
+ async function install(name, targetFile, contents) {
145
+ const file = path.join(local, name);
146
+ const pending = targetFile + ".mapsource-" + randomUUID();
147
+ await writeFile(file, contents, { mode: 0o600 });
148
+ await run("/usr/bin/sudo", ["-n", "/usr/bin/install", "-m", "0644", "--", file, pending], { timeout: 6000 });
149
+ await run("/usr/bin/sudo", ["-n", "/usr/bin/mv", "-T", "--", pending, targetFile], { timeout: 6000 });
150
+ }
151
+ async function configure(config, dropin) {
152
+ await install("identity.conf", identityFile, dropin);
153
+ await install("service.env", service.configFile, config);
154
+ await run("/usr/bin/sudo", ["-n", "/usr/bin/systemctl", "daemon-reload"], { timeout: 12_000 });
155
+ if (service.active) {
156
+ await serviceControl(["restart"], service.unit);
157
+ if (await ready(service.socket) !== priorRelease) throw Error("The restarted service loaded a different release.");
158
+ }
159
+ }
160
+ try {
161
+ const config = service.config.replace(/^MAPSOURCE_INTELLIGENCE_DATABASE=.*$/m, `MAPSOURCE_INTELLIGENCE_DATABASE=${nextDatabase}`);
162
+ const dropin = identity.replace(mounts, `RequiresMountsFor=${target} ${path.dirname(service.bundle)}`);
163
+ if (config === service.config || parseEnv(config).MAPSOURCE_INTELLIGENCE_DATABASE !== nextDatabase) throw Error("The dataset setting could not be updated.");
164
+ try { await configure(config, dropin); }
165
+ catch (cause) {
166
+ await configure(service.config, identity).catch(error => { throw new AggregateError([cause, error], "The move failed and automatic rollback needs attention."); });
167
+ throw Error("The move failed and the previous configuration was restored.", { cause });
168
+ }
169
+ } finally { await rm(local, { recursive: true, force: true }); }
170
+ return { role, database: nextDatabase, previous: source, sha256: digest, active: service.active };
171
+ } finally { await rm(scratch, { recursive: true, force: true }); }
172
+ }
@@ -0,0 +1,41 @@
1
+ import assert from "node:assert/strict";
2
+ import type { KeyEvent } from "@opentui/core";
3
+ import { serviceScreen } from "./service-screen.ts";
4
+
5
+ export async function testServiceScreen() {
6
+ const calls: unknown[] = [];
7
+ let database = "/srv/data/storm.sqlite", enabled = true;
8
+ const screen = serviceScreen(() => {}, {
9
+ list: async () => [{ id: "historical-weather", database, enabled, active: enabled, state: enabled ? "active" : "inactive" }],
10
+ enable: async (id, requested) => { calls.push({ id, requested }); enabled = requested; },
11
+ move: async (role, directory) => {
12
+ const previous = database;
13
+ database = directory + "/storm.sqlite";
14
+ calls.push({ role, directory });
15
+ return { role, database, previous, sha256: "a".repeat(64), active: enabled };
16
+ },
17
+ });
18
+ const press = (name: string) => screen.keypress({ name, sequence: name } as KeyEvent);
19
+ const rendered = () => screen.view().map(line => line.text).join("\n");
20
+ const tick = () => new Promise(resolve => setTimeout(resolve, 1));
21
+ await screen.refresh();
22
+ assert.match(rendered(), /Running · Enabled at boot/);
23
+ assert.match(rendered(), /\/srv\/data\/storm.sqlite/);
24
+ assert.equal(press("e"), true);
25
+ await tick();
26
+ assert.match(rendered(), /Stopped · Boot disabled/);
27
+ assert.deepEqual(calls, [{ id: "historical-weather", requested: false }]);
28
+ assert.equal(press("m"), true);
29
+ screen.paste("/mnt/backup");
30
+ press("return");
31
+ assert.match(rendered(), /Confirm destination · \/mnt\/backup/);
32
+ press("escape");
33
+ assert.equal(calls.length, 1);
34
+ press("m");
35
+ screen.paste("/mnt/backup");
36
+ press("return");
37
+ press("return");
38
+ await tick();
39
+ assert.match(rendered(), /Dataset · \/mnt\/backup\/storm.sqlite/);
40
+ assert.deepEqual(calls[1], { role: "historical-weather", directory: "/mnt/backup" });
41
+ }
@@ -0,0 +1,101 @@
1
+ import type { KeyEvent } from "@opentui/core";
2
+ import { installedServices, moveServiceDataset, setServiceEnabled } from "./service-management.mjs";
3
+
4
+ type Service = Awaited<ReturnType<typeof installedServices>>[number];
5
+ export const serviceActions = { list: installedServices, enable: setServiceEnabled, move: moveServiceDataset };
6
+
7
+ export function serviceScreen(draw: () => void, api = serviceActions) {
8
+ let services: Service[] = [], cursor = 0, busy = false;
9
+ let notice = "", directory: string | null = null, confirming = false;
10
+ const selected = () => services[cursor];
11
+ const safe = (message: string) => message.replace(/[\p{Cc}\p{Cf}]/gu, "");
12
+
13
+ async function act(action: () => Promise<string | void>) {
14
+ if (busy) return;
15
+ busy = true; notice = ""; draw();
16
+ try {
17
+ const message = await action();
18
+ services = await api.list();
19
+ cursor = Math.min(cursor, Math.max(0, services.length - 1));
20
+ notice = message ?? "";
21
+ } catch (error) { notice = safe(error instanceof Error ? error.message : "The request failed."); }
22
+ finally { busy = false; draw(); }
23
+ }
24
+
25
+ function toggle() {
26
+ const service = selected();
27
+ if (!service?.database) return;
28
+ const enable = !(service.enabled || service.active);
29
+ void act(async () => {
30
+ await api.enable(service.id, enable);
31
+ return enable ? "Worker started and enabled at boot." : "Worker stopped. Dataset retained.";
32
+ });
33
+ }
34
+
35
+ function edit() {
36
+ if (!selected()?.database || busy) return;
37
+ directory = ""; notice = ""; draw();
38
+ }
39
+
40
+ function submit() {
41
+ const service = selected();
42
+ if (!service || !directory || busy) return;
43
+ if (!confirming) { confirming = true; draw(); return; }
44
+ const destination = directory;
45
+ directory = null; confirming = false;
46
+ void act(async () => {
47
+ await api.move(service.id, destination);
48
+ return "Dataset verified and switched. The prior copy is available for rollback.";
49
+ });
50
+ }
51
+
52
+ function paste(value: string) {
53
+ if (directory === null || busy || confirming) return;
54
+ directory = (directory + value.trim().replace(/[^A-Za-z0-9_./-]/g, "")).slice(0, 512);
55
+ draw();
56
+ }
57
+
58
+ function keypress(key: KeyEvent) {
59
+ if (busy) return key.name !== "q";
60
+ if (directory !== null) {
61
+ if (key.name === "escape") { directory = null; confirming = false; draw(); }
62
+ else if (key.name === "return") submit();
63
+ else if (key.name === "backspace" && !confirming) { directory = directory.slice(0, -1); draw(); }
64
+ else if (!key.ctrl && !key.meta && /^[A-Za-z0-9_./-]$/.test(key.sequence)) paste(key.sequence);
65
+ return true;
66
+ }
67
+ if (key.name === "r") { void act(async () => {}); return true; }
68
+ if (key.name === "m" && selected()?.database) { edit(); return true; }
69
+ if (key.name === "e" && selected()?.database) { toggle(); return true; }
70
+ if (key.name === "up" || key.name === "down") {
71
+ if (services.length === 0) return false;
72
+ cursor = Math.max(0, Math.min(services.length - 1, cursor + (key.name === "up" ? -1 : 1)));
73
+ draw(); return true;
74
+ }
75
+ return false;
76
+ }
77
+
78
+ function view() {
79
+ const lines: { text: string; action?: () => void }[] = [];
80
+ if (!services.length && !busy) lines.push({ text: "No local intelligence workers found. Install services under Enrollment." });
81
+ for (const [index, service] of services.entries()) {
82
+ const state = service.active ? "Running" : service.state === "unverified" ? "Unverified" : "Stopped";
83
+ lines.push({ text: `${index === cursor ? "›" : " "} ${service.id} · ${state} · ${service.enabled ? "Enabled at boot" : "Boot disabled"}`,
84
+ action: () => { if (!busy && directory === null) { cursor = index; draw(); } } });
85
+ }
86
+ const service = selected();
87
+ if (service?.database) lines.push({ text: "Dataset · " + service.database });
88
+ if (directory !== null) {
89
+ lines.push({ text: (confirming ? "Confirm destination · " : "Destination directory · ") + directory });
90
+ if (confirming) lines.push({ text: "This copies the release and switches its systemd configuration. A running worker restarts." });
91
+ lines.push({ text: `[Enter] ${confirming ? "Move dataset" : "Review move"} · [Esc] Cancel`, action: submit });
92
+ } else if (service?.database) {
93
+ lines.push({ text: service.enabled || service.active ? "[E] Disable worker" : "[E] Enable worker", action: toggle });
94
+ lines.push({ text: "[M] Move dataset", action: edit });
95
+ }
96
+ if (busy || notice) lines.push({ text: busy ? "Checking local service or copying dataset…" : notice });
97
+ return lines;
98
+ }
99
+
100
+ return { view, keypress, paste, refresh: () => act(async () => {}) };
101
+ }