@belboy47/brc-agent 2.0.18 → 3.1.0

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.
Files changed (38) hide show
  1. package/README.md +26 -36
  2. package/dist/cli.js +110 -22
  3. package/dist/cli.js.map +1 -1
  4. package/dist/core/config-manager.d.ts +2 -0
  5. package/dist/core/config-manager.js +24 -5
  6. package/dist/core/config-manager.js.map +1 -1
  7. package/dist/core/tools/config.d.ts +2 -0
  8. package/dist/core/tools/config.js +3 -0
  9. package/dist/core/tools/config.js.map +1 -1
  10. package/dist/core/tools/pdf/markdown.js +2 -1
  11. package/dist/core/tools/pdf/markdown.js.map +1 -1
  12. package/dist/manager.d.ts +75 -0
  13. package/dist/manager.js +706 -0
  14. package/dist/manager.js.map +1 -0
  15. package/dist/runtime/detach.d.ts +15 -1
  16. package/dist/runtime/detach.js +86 -11
  17. package/dist/runtime/detach.js.map +1 -1
  18. package/dist/runtime/directories.d.ts +16 -0
  19. package/dist/runtime/directories.js +123 -0
  20. package/dist/runtime/directories.js.map +1 -0
  21. package/dist/runtime/lab-mode.d.ts +7 -3
  22. package/dist/runtime/lab-mode.js +55 -10
  23. package/dist/runtime/lab-mode.js.map +1 -1
  24. package/dist/runtime/manager-config.d.ts +36 -0
  25. package/dist/runtime/manager-config.js +174 -0
  26. package/dist/runtime/manager-config.js.map +1 -0
  27. package/dist/runtime/pdf-browser.d.ts +33 -0
  28. package/dist/runtime/pdf-browser.js +126 -0
  29. package/dist/runtime/pdf-browser.js.map +1 -0
  30. package/dist/runtime/permissions.d.ts +33 -0
  31. package/dist/runtime/permissions.js +144 -0
  32. package/dist/runtime/permissions.js.map +1 -0
  33. package/dist/runtime/updater.d.ts +28 -0
  34. package/dist/runtime/updater.js +111 -0
  35. package/dist/runtime/updater.js.map +1 -0
  36. package/dist/runtime/workspace.d.ts +6 -6
  37. package/dist/tools/jobs.d.ts +14 -14
  38. package/package.json +3 -5
@@ -0,0 +1,706 @@
1
+ /**
2
+ * Interactive terminal manager for Better Remote Commander (`brc`).
3
+ *
4
+ * Cross-platform (Linux, Windows, macOS) unified manager backed by the same
5
+ * configuration, permission, directory, detached-process, extension, and
6
+ * update modules as the manual CLI.
7
+ */
8
+ import os from 'node:os';
9
+ import { spawnSync } from 'node:child_process';
10
+ import { createTerminalPrompts } from './terminal-setup.js';
11
+ import { normalizeRelayUrl } from './transport/relay-url.js';
12
+ import { loadCredentials, clearCredentials } from './transport/pairing.js';
13
+ import { detectRelayStateFromLog, formatUptime, getDetachPaths, getDetachedStatus, readDetachedLogs, stopDetachedAgent, } from './runtime/detach.js';
14
+ import { loadLocalConfig, updateLocalConfig, validateDeviceName, } from './runtime/manager-config.js';
15
+ import { CAPABILITY_GROUPS, getCapabilityGroup, resolveEffectivePermissions, } from './runtime/permissions.js';
16
+ import { isWindowsAdmin } from './runtime/lab-mode.js';
17
+ import { describeEffectiveFilesystemScope, validateDirectoryPath, } from './runtime/directories.js';
18
+ import { disablePdfBrowser, enablePdfBrowser, getPdfBrowserStatus, } from './runtime/pdf-browser.js';
19
+ import { checkForUpdates, installLatestUpdate, } from './runtime/updater.js';
20
+ /** Build the CLI arguments that `Start Agent` passes to `cli.js` from saved preferences. */
21
+ export function buildManagerLaunchArgs(prefs, savedCreds, platform = process.platform) {
22
+ const args = [];
23
+ const relay = prefs.relayUrl ?? savedCreds?.relayUrl;
24
+ const name = prefs.deviceName ?? savedCreds?.name ?? os.hostname();
25
+ if (relay)
26
+ args.push('--relay', relay);
27
+ if (name)
28
+ args.push('--name', name);
29
+ if (prefs.permissionProfile === 'lab-networking')
30
+ args.push('--lab-mode');
31
+ if (!prefs.openBrowser)
32
+ args.push('--no-browser');
33
+ if (!prefs.enablePlugins)
34
+ args.push('--no-plugins');
35
+ if ((platform === 'linux' || platform === 'win32' || platform === 'darwin') && prefs.detachByDefault) {
36
+ args.push('--detach');
37
+ }
38
+ return args;
39
+ }
40
+ export function renderFeaturesSummary(opts) {
41
+ const { config, running, record, pdfStatus } = opts;
42
+ const p = config.preferences;
43
+ const savedLab = p.permissionProfile === 'lab-networking';
44
+ const liveLab = running ? record?.mode === 'lab' : undefined;
45
+ const fmt = (savedOn, liveOn) => {
46
+ const s = savedOn ? 'ENABLED ' : 'DISABLED';
47
+ if (!running || liveOn === undefined)
48
+ return s;
49
+ return savedOn === liveOn ? `${s} (live: ${liveOn ? 'ON' : 'OFF'})` : `${s} (live: ${liveOn ? 'ON' : 'OFF'} — restart required)`;
50
+ };
51
+ const pdfLabel = pdfStatus.enabled
52
+ ? (pdfStatus.installed ? 'ENABLED (installed)' : 'ENABLED (not installed)')
53
+ : (pdfStatus.installed ? 'DISABLED (cached on disk)' : 'DISABLED (not installed)');
54
+ const caps = p.authorizedCapabilities.length ? p.authorizedCapabilities.join(', ') : 'none';
55
+ const dirs = config.allowedDirectories.length ? `${config.allowedDirectories.length} configured` : 'default (OS permissions)';
56
+ return [
57
+ '',
58
+ '--- Features & Modes (CLI Flags, Permissions & Extensions) ---',
59
+ ` 1) Detached execution [--detach] : ${fmt(p.detachByDefault, running ? true : undefined)}`,
60
+ ` 2) Laboratory mode [--lab-mode] : ${fmt(savedLab, liveLab)}`,
61
+ ` 3) Open browser pairing [--no-browser off/on] : ${p.openBrowser ? 'ENABLED ' : 'DISABLED (--no-browser)'}`,
62
+ ` 4) Default plugins [--no-plugins off/on] : ${p.enablePlugins ? 'ENABLED ' : 'DISABLED (--no-plugins)'}`,
63
+ ` 5) PDF browser ext [--enable-pdf-browser] : ${pdfLabel}`,
64
+ ` 6) Scoped capabilities (profile: ${p.permissionProfile}) : ${caps}`,
65
+ ` 7) Permitted dirs [--allow-dir] : ${dirs}`,
66
+ ` 8) Restore all feature & permission defaults`,
67
+ ` 0) Back to main menu`,
68
+ '',
69
+ ].join('\n');
70
+ }
71
+ export function renderManagerDashboard(opts) {
72
+ const { version, platform, config, creds, running, record, relayState } = opts;
73
+ const prefs = config.preferences;
74
+ const relay = record?.relayUrl ?? prefs.relayUrl ?? creds?.relayUrl ?? '(not configured)';
75
+ const device = record?.name ?? prefs.deviceName ?? creds?.name ?? os.hostname();
76
+ const savedProfile = prefs.permissionProfile === 'custom' && prefs.authorizedCapabilities.length
77
+ ? `custom (${prefs.authorizedCapabilities.join(', ')})`
78
+ : prefs.permissionProfile;
79
+ const activeProfile = running
80
+ ? (record?.profile ?? (record?.mode === 'lab' ? 'lab-networking' : 'standard'))
81
+ : savedProfile;
82
+ const detachSupported = platform === 'linux' || platform === 'win32' || platform === 'darwin';
83
+ const execMode = running
84
+ ? 'detached'
85
+ : (detachSupported && prefs.detachByDefault ? 'detached (default)' : 'foreground');
86
+ const stateLine = running && record
87
+ ? `RUNNING (PID ${record.pid}, uptime ${formatUptime(record.startedAt)})`
88
+ : 'STOPPED';
89
+ const relayConn = running ? relayState : 'n/a (stopped)';
90
+ const width = 78;
91
+ const rule = '-'.repeat(width - 2);
92
+ const row = (text) => '| ' + text.slice(0, width - 4).padEnd(width - 4, ' ') + ' |';
93
+ const lines = [
94
+ '',
95
+ '+' + rule + '+',
96
+ row(` BRC v${version} (${platform}) | Better Remote Commander Interactive Manager`),
97
+ '+' + rule + '+',
98
+ row(` Agent State : ${stateLine}`),
99
+ row(` Relay Status : ${relayConn}`),
100
+ row(` Device Name : ${device}`),
101
+ row(` Relay Address : ${relay}`),
102
+ row(` Active Profile : ${activeProfile}`),
103
+ ...(running && activeProfile !== savedProfile
104
+ ? [row(` Saved Profile : ${savedProfile} (restart to apply)`)]
105
+ : []),
106
+ row(` Execution Mode : ${execMode}`),
107
+ '+' + rule + '+',
108
+ '',
109
+ ' 1) Start agent 7) Features & Modes (flags & toggles)',
110
+ ' 2) Stop agent 8) Manage permissions & capabilities',
111
+ ' 3) Restart agent 9) View agent logs',
112
+ ' 4) Display detailed agent status 10) Check for and install BRC updates',
113
+ ' 5) Configure relay & device name 11) Stop agent and exit manager',
114
+ ' 6) Manage permitted directories 12) Exit manager (leave agent running)',
115
+ '',
116
+ ];
117
+ return lines.join('\n');
118
+ }
119
+ export async function runManager(deps) {
120
+ const platform = deps.platform ?? process.platform;
121
+ const uid = deps.uid ?? process.getuid?.();
122
+ const paths = getDetachPaths(deps.brcHome);
123
+ const ownedPrompts = !deps.io;
124
+ const io = deps.io ?? createTerminalPrompts(process.stdin, process.stdout);
125
+ const loadCreds = deps.loadCreds ?? loadCredentials;
126
+ const clearCreds = deps.clearCreds ?? clearCredentials;
127
+ const getStatus = deps.getStatus ?? (() => getDetachedStatus(paths));
128
+ const stopAgent = deps.stopAgent ?? (() => stopDetachedAgent(paths));
129
+ const readLogs = deps.readLogs ?? ((n) => readDetachedLogs(n, paths));
130
+ const doCheckUpdates = deps.checkUpdates ?? ((v) => checkForUpdates(v, { platform }));
131
+ const doInstallUpdate = deps.installUpdate ?? ((v, t) => installLatestUpdate(v, t, { platform }));
132
+ const getPdf = deps.getPdfStatus ?? (() => getPdfBrowserStatus(deps.brcHome));
133
+ const doEnablePdf = deps.enablePdf ?? (() => enablePdfBrowser(deps.brcHome, { platform }));
134
+ const doDisablePdf = deps.disablePdf ?? ((rm) => disablePdfBrowser(deps.brcHome, { removeFiles: rm, platform }));
135
+ const launchAgent = deps.launchAgent ?? (async (args) => {
136
+ const res = spawnSync(process.execPath, [deps.cliPath, ...args], {
137
+ stdio: 'inherit',
138
+ env: { ...process.env, ...(deps.brcHome ? { BRC_HOME: deps.brcHome } : {}) },
139
+ });
140
+ const code = res.status ?? (res.error ? 1 : 0);
141
+ return { ok: code === 0, code, message: res.error?.message };
142
+ });
143
+ const confirm = async (prompt) => {
144
+ const ans = await io.ask(prompt);
145
+ return ans !== null && /^(?:y|yes)$/i.test(ans.trim());
146
+ };
147
+ const offerControlledRestart = async (reason) => {
148
+ const st = getStatus();
149
+ if (!st.running)
150
+ return;
151
+ io.write(`\nNote: ${reason}`);
152
+ if (await confirm('Restart the running agent now to apply changes? [y/N]: ')) {
153
+ await handleRestart();
154
+ }
155
+ else {
156
+ io.write('Changes saved. Restart the agent later (option 3) to apply them.');
157
+ }
158
+ };
159
+ const handleStart = async () => {
160
+ const cfg = loadLocalConfig(deps.brcHome, platform);
161
+ const creds = loadCreds();
162
+ const st = getStatus();
163
+ if (st.running && st.record) {
164
+ io.write(`Agent is already running (PID ${st.record.pid}). Use option 3 to restart or option 2 to stop.`);
165
+ return false;
166
+ }
167
+ const relay = cfg.preferences.relayUrl ?? creds?.relayUrl;
168
+ if (!relay) {
169
+ io.write('No relay address configured yet. Use option 5 to configure a relay address first.');
170
+ return false;
171
+ }
172
+ if (cfg.preferences.permissionProfile === 'lab-networking') {
173
+ if (platform === 'linux' && uid !== 0) {
174
+ io.write('Error: lab-networking profile on Linux requires root (run `sudo brc`).');
175
+ return false;
176
+ }
177
+ if (platform === 'win32' && !(deps.isAdmin ?? isWindowsAdmin())) {
178
+ io.write('Error: lab-networking profile on Windows requires an elevated Administrator terminal.');
179
+ return false;
180
+ }
181
+ }
182
+ const args = buildManagerLaunchArgs(cfg.preferences, creds, platform);
183
+ if (args.includes('--detach')) {
184
+ io.write('Starting agent (will complete any required enrollment, then detach)...');
185
+ }
186
+ else {
187
+ io.write('Starting agent in foreground mode (press Ctrl+C to stop and return to manager)...');
188
+ }
189
+ const res = await launchAgent(args);
190
+ if (!res.ok) {
191
+ io.write(`Start failed (exit code ${res.code})${res.message ? `: ${res.message}` : ''}.`);
192
+ return false;
193
+ }
194
+ return true;
195
+ };
196
+ const handleStop = async () => {
197
+ const res = await stopAgent();
198
+ io.write(res.message);
199
+ };
200
+ const handleRestart = async () => {
201
+ const st = getStatus();
202
+ if (st.running) {
203
+ const stopRes = await stopAgent();
204
+ io.write(stopRes.message);
205
+ if (!stopRes.stopped && !stopRes.staleCleaned) {
206
+ io.write('Aborting restart because the existing instance could not be stopped.');
207
+ return;
208
+ }
209
+ }
210
+ await handleStart();
211
+ };
212
+ const handleConfigureRelay = async () => {
213
+ const cfg = loadLocalConfig(deps.brcHome, platform);
214
+ const creds = loadCreds();
215
+ const currentRelay = cfg.preferences.relayUrl ?? creds?.relayUrl ?? '';
216
+ const currentName = cfg.preferences.deviceName ?? creds?.name ?? os.hostname();
217
+ io.write(`\nCurrent relay: ${currentRelay || '(not set)'}`);
218
+ io.write(`Current device name: ${currentName}`);
219
+ const rawRelay = await io.ask(`Relay URL [${currentRelay || 'https://relay.example.com'}] (or "forget" to clear pairing): `);
220
+ if (rawRelay === null)
221
+ return;
222
+ const trimmedRelay = rawRelay.trim();
223
+ if (trimmedRelay.toLowerCase() === 'forget') {
224
+ clearCreds();
225
+ updateLocalConfig(({ preferences }) => {
226
+ delete preferences.relayUrl;
227
+ }, deps.brcHome, platform);
228
+ io.write('Cleared saved relay URL and local pairing credentials.');
229
+ return;
230
+ }
231
+ let nextRelay = currentRelay;
232
+ if (trimmedRelay) {
233
+ try {
234
+ nextRelay = normalizeRelayUrl(trimmedRelay, true);
235
+ }
236
+ catch (err) {
237
+ io.write(`Invalid relay URL: ${err instanceof Error ? err.message : String(err)}`);
238
+ return;
239
+ }
240
+ }
241
+ const rawName = await io.ask(`Device name [${currentName}]: `);
242
+ if (rawName === null)
243
+ return;
244
+ let nextName = currentName;
245
+ if (rawName.trim()) {
246
+ const v = validateDeviceName(rawName);
247
+ if (!v.valid || !v.value) {
248
+ io.write(`Invalid device name: ${v.error}`);
249
+ return;
250
+ }
251
+ nextName = v.value;
252
+ }
253
+ updateLocalConfig(({ preferences }) => {
254
+ if (nextRelay)
255
+ preferences.relayUrl = nextRelay;
256
+ preferences.deviceName = nextName;
257
+ }, deps.brcHome, platform);
258
+ io.write(`Saved relay "${nextRelay || '(unset)'}" and device name "${nextName}".`);
259
+ await offerControlledRestart('Relay/device settings changed.');
260
+ };
261
+ const handleDirectoriesMenu = async () => {
262
+ for (;;) {
263
+ const cfg = loadLocalConfig(deps.brcHome, platform);
264
+ const st = getStatus();
265
+ const labActive = st.running ? st.record?.mode === 'lab' : cfg.preferences.permissionProfile === 'lab-networking';
266
+ io.write('\n--- Permitted Directory Manager ---');
267
+ if (cfg.allowedDirectories.length === 0) {
268
+ io.write('Saved allowedDirectories: (none — default)');
269
+ }
270
+ else {
271
+ cfg.allowedDirectories.forEach((d, idx) => io.write(` ${idx + 1}) ${d}`));
272
+ }
273
+ for (const line of describeEffectiveFilesystemScope({
274
+ savedAllowedDirectories: cfg.allowedDirectories,
275
+ labSessionActive: labActive,
276
+ platform,
277
+ })) {
278
+ io.write(` ${line}`);
279
+ }
280
+ io.write('\n 1) Add directory');
281
+ io.write(' 2) Remove directory');
282
+ io.write(' 3) Restore default directory settings');
283
+ io.write(' 0) Back');
284
+ const choice = await io.ask('Directories> ');
285
+ if (choice === null || choice.trim() === '0' || choice.trim().toLowerCase() === 'b')
286
+ return;
287
+ const c = choice.trim();
288
+ if (c === '1') {
289
+ const input = await io.ask('Directory path to permit: ');
290
+ if (!input || !input.trim())
291
+ continue;
292
+ const v = validateDirectoryPath(input);
293
+ if (!v.valid || !v.normalizedPath) {
294
+ io.write(`Validation failed: ${v.error}`);
295
+ continue;
296
+ }
297
+ if (v.isSymlink && v.realPath) {
298
+ io.write(`Note: "${v.normalizedPath}" is a symlink resolving to "${v.realPath}". Storing normalized real path.`);
299
+ }
300
+ const target = v.realPath ?? v.normalizedPath;
301
+ updateLocalConfig(({ allowedDirectories }) => {
302
+ allowedDirectories.push(target);
303
+ }, deps.brcHome, platform);
304
+ io.write(`Added permitted directory: ${target}`);
305
+ await offerControlledRestart('Directory policy updated.');
306
+ }
307
+ else if (c === '2') {
308
+ if (cfg.allowedDirectories.length === 0) {
309
+ io.write('No saved directories to remove.');
310
+ continue;
311
+ }
312
+ const raw = await io.ask('Enter number or path to remove: ');
313
+ if (!raw || !raw.trim())
314
+ continue;
315
+ const idx = Number.parseInt(raw.trim(), 10);
316
+ let removed;
317
+ updateLocalConfig(({ allowedDirectories }) => {
318
+ if (Number.isInteger(idx) && idx >= 1 && idx <= allowedDirectories.length) {
319
+ removed = allowedDirectories.splice(idx - 1, 1)[0];
320
+ }
321
+ else {
322
+ const pos = allowedDirectories.findIndex((d) => d.toLowerCase() === raw.trim().toLowerCase());
323
+ if (pos >= 0)
324
+ removed = allowedDirectories.splice(pos, 1)[0];
325
+ }
326
+ }, deps.brcHome, platform);
327
+ if (removed) {
328
+ io.write(`Removed permitted directory: ${removed}`);
329
+ await offerControlledRestart('Directory policy updated.');
330
+ }
331
+ else {
332
+ io.write('Directory not found in saved list.');
333
+ }
334
+ }
335
+ else if (c === '3') {
336
+ if (await confirm('Restore default directory settings (clear saved allowedDirectories)? [y/N]: ')) {
337
+ updateLocalConfig(({ allowedDirectories }) => {
338
+ allowedDirectories.length = 0;
339
+ }, deps.brcHome, platform);
340
+ io.write('Restored default directory settings.');
341
+ await offerControlledRestart('Directory policy restored to defaults.');
342
+ }
343
+ }
344
+ else {
345
+ io.write('Choose 1, 2, 3, or 0.');
346
+ }
347
+ }
348
+ };
349
+ const handlePermissionsMenu = async () => {
350
+ for (;;) {
351
+ const cfg = loadLocalConfig(deps.brcHome, platform);
352
+ const st = getStatus();
353
+ const prefs = cfg.preferences;
354
+ const effective = resolveEffectivePermissions({
355
+ profile: prefs.permissionProfile,
356
+ authorizedCapabilities: prefs.authorizedCapabilities,
357
+ savedAllowedDirectories: cfg.allowedDirectories,
358
+ labSessionActive: prefs.permissionProfile === 'lab-networking',
359
+ });
360
+ io.write('\n--- Local Permission & Capability Management ---');
361
+ io.write(`Saved profile: ${prefs.permissionProfile}`);
362
+ io.write(`Authorized caps: ${effective.authorizedCapabilities.length ? effective.authorizedCapabilities.join(', ') : '(none — default blocklist active)'}`);
363
+ if (st.running && st.record) {
364
+ io.write(`Running agent: PID ${st.record.pid}, effective profile: ${st.record.profile ?? st.record.mode}`);
365
+ }
366
+ io.write('Note: Remote MCP callers cannot modify profiles, capabilities, or blockedCommands.');
367
+ io.write('\n 1) Select standard profile (default protections)');
368
+ io.write(' 2) Select laboratory networking profile (Linux root / Windows Admin)');
369
+ io.write(' 3) Authorize a scoped capability group');
370
+ io.write(' 4) Revoke an authorized capability group');
371
+ io.write(' 5) Inspect all capability groups (permitted vs restricted)');
372
+ io.write(' 6) Restore default permission settings');
373
+ io.write(' 0) Back');
374
+ const choice = await io.ask('Permissions> ');
375
+ if (choice === null || choice.trim() === '0' || choice.trim().toLowerCase() === 'b')
376
+ return;
377
+ const c = choice.trim();
378
+ if (c === '1') {
379
+ updateLocalConfig(({ preferences }) => {
380
+ preferences.permissionProfile = 'standard';
381
+ preferences.authorizedCapabilities = [];
382
+ }, deps.brcHome, platform);
383
+ io.write('Selected standard permission profile.');
384
+ await offerControlledRestart('Permission profile changed to standard.');
385
+ }
386
+ else if (c === '2') {
387
+ if (await confirm('Authorize laboratory networking profile (temporary host scope + firewall/networking tools)? [y/N]: ')) {
388
+ updateLocalConfig(({ preferences }) => {
389
+ preferences.permissionProfile = 'lab-networking';
390
+ if (!preferences.authorizedCapabilities.includes('networking-firewall')) {
391
+ preferences.authorizedCapabilities.push('networking-firewall');
392
+ }
393
+ }, deps.brcHome, platform);
394
+ io.write('Selected laboratory networking profile.');
395
+ await offerControlledRestart('Permission profile changed to lab-networking.');
396
+ }
397
+ }
398
+ else if (c === '3') {
399
+ io.write('\nAvailable scoped capability groups:');
400
+ CAPABILITY_GROUPS.forEach((g, idx) => {
401
+ const active = effective.authorizedCapabilities.includes(g.id) ? ' [AUTHORIZED]' : ' [restricted]';
402
+ io.write(` ${idx + 1}) ${g.id} (${g.riskLevel} risk)${active} - ${g.label}`);
403
+ });
404
+ const pick = await io.ask('Enter number or capability id to authorize: ');
405
+ if (!pick || !pick.trim())
406
+ continue;
407
+ const idx = Number.parseInt(pick.trim(), 10);
408
+ const group = Number.isInteger(idx) && idx >= 1 && idx <= CAPABILITY_GROUPS.length
409
+ ? CAPABILITY_GROUPS[idx - 1]
410
+ : getCapabilityGroup(pick.trim().toLowerCase());
411
+ if (!group) {
412
+ io.write('Unknown capability group.');
413
+ continue;
414
+ }
415
+ io.write(`\nCapability: ${group.label} (${group.id})`);
416
+ io.write(`Risk level: ${group.riskLevel.toUpperCase()}`);
417
+ io.write(`Details: ${group.description}`);
418
+ if (await confirm(`Explicitly authorize "${group.id}" locally on this host? [y/N]: `)) {
419
+ updateLocalConfig(({ preferences }) => {
420
+ if (preferences.permissionProfile === 'standard') {
421
+ preferences.permissionProfile = 'custom';
422
+ }
423
+ if (!preferences.authorizedCapabilities.includes(group.id)) {
424
+ preferences.authorizedCapabilities.push(group.id);
425
+ }
426
+ }, deps.brcHome, platform);
427
+ io.write(`Authorized capability group: ${group.id}`);
428
+ await offerControlledRestart(`Capability "${group.id}" authorized locally.`);
429
+ }
430
+ }
431
+ else if (c === '4') {
432
+ if (!prefs.authorizedCapabilities.length) {
433
+ io.write('No extra capabilities are currently authorized.');
434
+ continue;
435
+ }
436
+ prefs.authorizedCapabilities.forEach((id, idx) => io.write(` ${idx + 1}) ${id}`));
437
+ const pick = await io.ask('Enter number or capability id to revoke: ');
438
+ if (!pick || !pick.trim())
439
+ continue;
440
+ const idx = Number.parseInt(pick.trim(), 10);
441
+ const targetId = Number.isInteger(idx) && idx >= 1 && idx <= prefs.authorizedCapabilities.length
442
+ ? prefs.authorizedCapabilities[idx - 1]
443
+ : pick.trim().toLowerCase();
444
+ if (!prefs.authorizedCapabilities.includes(targetId)) {
445
+ io.write('Capability not found in authorized list.');
446
+ continue;
447
+ }
448
+ updateLocalConfig(({ preferences }) => {
449
+ preferences.authorizedCapabilities = preferences.authorizedCapabilities.filter((x) => x !== targetId);
450
+ if (targetId === 'networking-firewall' && preferences.permissionProfile === 'lab-networking') {
451
+ preferences.permissionProfile = preferences.authorizedCapabilities.length ? 'custom' : 'standard';
452
+ }
453
+ else if (!preferences.authorizedCapabilities.length && preferences.permissionProfile === 'custom') {
454
+ preferences.permissionProfile = 'standard';
455
+ }
456
+ }, deps.brcHome, platform);
457
+ io.write(`Revoked capability group: ${targetId}`);
458
+ await offerControlledRestart(`Capability "${targetId}" revoked.`);
459
+ }
460
+ else if (c === '5') {
461
+ io.write('\nCapability inventory:');
462
+ for (const g of CAPABILITY_GROUPS) {
463
+ const status = effective.authorizedCapabilities.includes(g.id) ? 'PERMITTED' : 'RESTRICTED';
464
+ io.write(` [${status}] ${g.id} (${g.riskLevel}): ${g.label}`);
465
+ io.write(` Commands: ${g.commands.slice(0, 12).join(', ')}${g.commands.length > 12 ? ', ...' : ''}`);
466
+ }
467
+ }
468
+ else if (c === '6') {
469
+ if (await confirm('Restore default permission settings (standard profile, revoke all extra capabilities)? [y/N]: ')) {
470
+ updateLocalConfig(({ preferences }) => {
471
+ preferences.permissionProfile = 'standard';
472
+ preferences.authorizedCapabilities = [];
473
+ }, deps.brcHome, platform);
474
+ io.write('Restored default permission settings.');
475
+ await offerControlledRestart('Permission settings restored to defaults.');
476
+ }
477
+ }
478
+ else {
479
+ io.write('Choose 1-6 or 0.');
480
+ }
481
+ }
482
+ };
483
+ const handleFeaturesMenu = async () => {
484
+ for (;;) {
485
+ const cfg = loadLocalConfig(deps.brcHome, platform);
486
+ const st = getStatus();
487
+ const pdf = getPdf();
488
+ io.write(renderFeaturesSummary({
489
+ config: cfg,
490
+ running: st.running,
491
+ record: st.record,
492
+ pdfStatus: pdf,
493
+ }));
494
+ const choice = await io.ask('Features [1-8, 0=back]> ');
495
+ if (choice === null || choice.trim() === '0' || choice.trim().toLowerCase() === 'b')
496
+ return;
497
+ const c = choice.trim();
498
+ if (c === '1') {
499
+ const next = !cfg.preferences.detachByDefault;
500
+ updateLocalConfig(({ preferences }) => {
501
+ preferences.detachByDefault = next;
502
+ }, deps.brcHome, platform);
503
+ io.write(`Detached execution (--detach) set to ${next ? 'ENABLED' : 'DISABLED'}.`);
504
+ }
505
+ else if (c === '2') {
506
+ const currentlyLab = cfg.preferences.permissionProfile === 'lab-networking';
507
+ if (currentlyLab) {
508
+ updateLocalConfig(({ preferences }) => {
509
+ preferences.permissionProfile = 'standard';
510
+ preferences.authorizedCapabilities = preferences.authorizedCapabilities.filter((x) => x !== 'networking-firewall');
511
+ }, deps.brcHome, platform);
512
+ io.write('Laboratory mode (--lab-mode) DISABLED (switched to standard profile).');
513
+ await offerControlledRestart('Laboratory mode disabled.');
514
+ }
515
+ else {
516
+ if (await confirm('Enable laboratory mode (--lab-mode: temporary host scope + firewall/networking tools; requires Linux root or Windows Admin)? [y/N]: ')) {
517
+ updateLocalConfig(({ preferences }) => {
518
+ preferences.permissionProfile = 'lab-networking';
519
+ if (!preferences.authorizedCapabilities.includes('networking-firewall')) {
520
+ preferences.authorizedCapabilities.push('networking-firewall');
521
+ }
522
+ }, deps.brcHome, platform);
523
+ io.write('Laboratory mode (--lab-mode) ENABLED.');
524
+ await offerControlledRestart('Laboratory mode enabled.');
525
+ }
526
+ }
527
+ }
528
+ else if (c === '3') {
529
+ const next = !cfg.preferences.openBrowser;
530
+ updateLocalConfig(({ preferences }) => {
531
+ preferences.openBrowser = next;
532
+ }, deps.brcHome, platform);
533
+ io.write(`Open browser on pairing set to ${next ? 'ENABLED' : 'DISABLED (--no-browser)'}.`);
534
+ }
535
+ else if (c === '4') {
536
+ const next = !cfg.preferences.enablePlugins;
537
+ updateLocalConfig(({ preferences }) => {
538
+ preferences.enablePlugins = next;
539
+ }, deps.brcHome, platform);
540
+ io.write(`Default plugins set to ${next ? 'ENABLED' : 'DISABLED (--no-plugins)'}.`);
541
+ await offerControlledRestart('Plugin preference updated.');
542
+ }
543
+ else if (c === '5') {
544
+ if (pdf.enabled) {
545
+ const remove = await confirm('Disable PDF browser extension. Also remove cached files from disk? [y/N]: ');
546
+ const res = doDisablePdf(remove);
547
+ io.write(res.message);
548
+ }
549
+ else {
550
+ if (await confirm('Install and enable the optional PDF browser extension (md-to-pdf / Chromium)? [y/N]: ')) {
551
+ io.write('Installing PDF browser extension...');
552
+ const res = await doEnablePdf();
553
+ io.write(res.message);
554
+ }
555
+ }
556
+ }
557
+ else if (c === '6') {
558
+ await handlePermissionsMenu();
559
+ }
560
+ else if (c === '7') {
561
+ await handleDirectoriesMenu();
562
+ }
563
+ else if (c === '8') {
564
+ if (await confirm('Restore all feature & permission defaults (standard profile, detached ON, plugins OFF, PDF browser OFF)? [y/N]: ')) {
565
+ updateLocalConfig(({ preferences }) => {
566
+ preferences.permissionProfile = 'standard';
567
+ preferences.authorizedCapabilities = [];
568
+ preferences.detachByDefault = platform === 'linux' || platform === 'win32' || platform === 'darwin';
569
+ preferences.openBrowser = platform !== 'linux';
570
+ preferences.enablePlugins = false;
571
+ preferences.pdfBrowserEnabled = false;
572
+ }, deps.brcHome, platform);
573
+ io.write('Restored all feature and permission defaults.');
574
+ await offerControlledRestart('Feature defaults restored.');
575
+ }
576
+ }
577
+ else {
578
+ io.write('Choose 1-8 or 0.');
579
+ }
580
+ }
581
+ };
582
+ const handleUpdates = async () => {
583
+ io.write('\nChecking npm registry for @belboy47/brc-agent updates...');
584
+ const check = await doCheckUpdates(deps.version);
585
+ if (!check.ok) {
586
+ io.write(`Update check failed: ${check.error}`);
587
+ io.write('Manual update command: npm update -g @belboy47/brc-agent');
588
+ return;
589
+ }
590
+ io.write(`Installed version: ${check.installedVersion}`);
591
+ io.write(`Latest version: ${check.latestVersion}`);
592
+ if (!check.updateAvailable) {
593
+ io.write('You are already running the latest version.');
594
+ return;
595
+ }
596
+ const st = getStatus();
597
+ if (st.running && st.record) {
598
+ io.write(`Note: A detached agent (PID ${st.record.pid}) is currently running and will be stopped before updating.`);
599
+ io.write('The agent will NOT be restarted automatically after the update.');
600
+ }
601
+ if (!(await confirm(`Install @belboy47/brc-agent@${check.latestVersion} now? [y/N]: `))) {
602
+ io.write('Update cancelled.');
603
+ return;
604
+ }
605
+ if (st.running) {
606
+ const stopRes = await stopAgent();
607
+ io.write(stopRes.message);
608
+ if (!stopRes.stopped && !stopRes.staleCleaned) {
609
+ io.write('Update aborted because the running agent could not be stopped cleanly.');
610
+ return;
611
+ }
612
+ }
613
+ io.write(`Installing @belboy47/brc-agent@${check.latestVersion}...`);
614
+ const res = await doInstallUpdate(check.installedVersion, check.latestVersion);
615
+ if (!res.ok) {
616
+ io.write(`Update failed: ${res.error}`);
617
+ io.write(`Recovery command: ${res.recoveryCommand}`);
618
+ return;
619
+ }
620
+ io.write(`Updated to @belboy47/brc-agent@${check.latestVersion}.`);
621
+ io.write('Exit and relaunch `brc` to use the new version, then start the agent manually when ready.');
622
+ };
623
+ try {
624
+ for (;;) {
625
+ const config = loadLocalConfig(deps.brcHome, platform);
626
+ if (config.recoveredFromInvalid) {
627
+ io.write(`Warning: ${config.recoveredFromInvalid}`);
628
+ }
629
+ const creds = loadCreds();
630
+ const status = getStatus();
631
+ const relayState = status.running ? detectRelayStateFromLog(paths) : 'n/a';
632
+ io.write(renderManagerDashboard({
633
+ version: deps.version,
634
+ platform,
635
+ config,
636
+ creds,
637
+ running: status.running,
638
+ record: status.record,
639
+ relayState,
640
+ }));
641
+ const raw = await io.ask('Select an option [1-12]: ');
642
+ if (raw === null)
643
+ return 0;
644
+ const choice = raw.trim();
645
+ if (choice === '1') {
646
+ await handleStart();
647
+ }
648
+ else if (choice === '2') {
649
+ await handleStop();
650
+ }
651
+ else if (choice === '3') {
652
+ await handleRestart();
653
+ }
654
+ else if (choice === '4') {
655
+ const st = getStatus();
656
+ io.write('\n' + st.message);
657
+ }
658
+ else if (choice === '5') {
659
+ await handleConfigureRelay();
660
+ }
661
+ else if (choice === '6') {
662
+ await handleDirectoriesMenu();
663
+ }
664
+ else if (choice === '7') {
665
+ await handleFeaturesMenu();
666
+ }
667
+ else if (choice === '8') {
668
+ await handlePermissionsMenu();
669
+ }
670
+ else if (choice === '9') {
671
+ const logs = readLogs(50);
672
+ io.write(`\n--- Agent Logs (${logs.logFile}) ---\n${logs.text}`);
673
+ }
674
+ else if (choice === '10') {
675
+ await handleUpdates();
676
+ }
677
+ else if (choice === '11') {
678
+ const st = getStatus();
679
+ if (st.running) {
680
+ const stopRes = await stopAgent();
681
+ io.write(stopRes.message);
682
+ }
683
+ io.write('Exiting BRC manager.');
684
+ return 0;
685
+ }
686
+ else if (choice === '12' || choice.toLowerCase() === 'q' || choice.toLowerCase() === 'exit') {
687
+ const st = getStatus();
688
+ if (st.running && st.record) {
689
+ io.write(`Exiting BRC manager. Detached agent (PID ${st.record.pid}) remains running.`);
690
+ }
691
+ else {
692
+ io.write('Exiting BRC manager.');
693
+ }
694
+ return 0;
695
+ }
696
+ else {
697
+ io.write('Invalid selection. Choose a number from 1 to 12.');
698
+ }
699
+ }
700
+ }
701
+ finally {
702
+ if (ownedPrompts)
703
+ io.close();
704
+ }
705
+ }
706
+ //# sourceMappingURL=manager.js.map