arena-bridge 0.8.1 → 0.8.12

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/src/cli.mjs CHANGED
@@ -10,11 +10,15 @@ import { runDevice } from './device.mjs';
10
10
  import { buildPrompt } from './prompt.mjs';
11
11
  import { listApprovals, decide } from './approvals.mjs';
12
12
  import { tailAudit, auditDir, listArtifacts, pruneArtifacts } from './audit.mjs';
13
+ import { pruneInbox } from './telegram.mjs';
14
+ import { pruneApprovals } from './approvals.mjs';
13
15
  import { startTunnel, isPortOpen } from './tunnel.mjs';
14
- import { spawn, execSync } from 'node:child_process';
16
+ import { spawn, execSync, spawnSync } from 'node:child_process';
15
17
  import { parseDuration, trustState, saveTrust, clearTrust } from './trust.mjs';
16
18
  import { findPeekaboo } from './mac.mjs';
19
+ import { tailLog, logPathForCli } from './log.mjs';
17
20
  import { findChrome, listProfiles, resolveProfile, sanitizeProfile } from './browser.mjs';
21
+ import { COMPLETION_BASH, COMPLETION_ZSH, COMPLETION_FISH } from './completion.mjs';
18
22
  import { packageInfo, latestVersion, compareVersions, selfUpdate } from './selfupdate.mjs';
19
23
  import { serviceStatus, serviceInstall, serviceUninstall } from './service.mjs';
20
24
  import {
@@ -49,6 +53,14 @@ export function parseArgs(argv) {
49
53
  } else {
50
54
  set(key, true);
51
55
  }
56
+ } else if (a.startsWith('-') && a.length === 2 && /^[a-zA-Z]$/.test(a[1])) {
57
+ // B8 fix: handle single-dash flags like -n 50, -h
58
+ const key = a.slice(1);
59
+ if (argv[i + 1] && !argv[i + 1].startsWith('-')) {
60
+ set(key, argv[++i]);
61
+ } else {
62
+ set(key, true);
63
+ }
52
64
  } else {
53
65
  out._.push(a);
54
66
  }
@@ -72,29 +84,37 @@ Commands:
72
84
  connect Connect this machine to a hub as a device
73
85
  prompt Print the ready-to-paste agent instructions
74
86
  tools Print the tool catalog as JSON
75
- approvals List pending approval requests
87
+ approvals [--json] List approval requests (or: approvals prune [--days 14])
76
88
  approve <id> Approve a pending request (--deny to refuse)
77
89
  rotate Generate a new agent token (--device for the device token)
78
- trust Open a trust window so the agent needs no approvals
90
+ trust Open a trust window (use --history to see past windows)
79
91
  --for 2h how long (30m, 2h, 1d)
80
92
  --tools a,b only these tools (default: all)
81
93
  --paths p1,p2 only these paths (bash is not covered)
82
- --off | --status
83
- audit [-n N] Show the audit log
94
+ --off | --status | --extend --for 1h
95
+ audit [-n N] [--tool NAME] [--since DUR] [--from DATE] [--to DATE] [--json] Show the audit log
96
+ cleanup [--days N] Remove old artifacts + approvals (default 14 days)
97
+ events [--json] Stream live events (approvals/audit) via SSE /v1/events
98
+ logs [-n N] [--json] Show bridge.log (structured logs)
99
+ config Manage configuration (get/set/edit)
100
+ get <key> | set <key> <value> | edit | list
84
101
  telegram Talk to the user in Telegram
85
102
  setup --token <bot token> --chat-id <id>
86
103
  test send a test message
87
104
  status show the bot, the chats, the unread count
88
105
  inbox [-n N] show the messages the user sent
89
106
  poll listen for messages in the foreground
90
- doctor Check the installation and configuration
107
+ doctor [--fix] Check the installation and configuration (--fix repairs perms/dirs)
108
+ status [--json] One-line runtime status (config, url, trust, approvals, service)
91
109
  url Print the public URL the agent should use
110
+ open Open the public URL in the browser
92
111
  version Show the installed version and the latest one on npm
93
112
  update Update this package from npm (--check to only look)
94
113
  service Run the bridge as a macOS background service
95
- install | uninstall | status
96
- browser The agent's own browser profiles
97
- list | login <name> | close <name> (open = deprecated alias of login)
114
+ install | uninstall | status | logs [-n N]
115
+ restart Restart the service if installed, else show how (alias)
116
+ browser [--json] The agent's own browser profiles (list --json for automation)
117
+ list | login <name> | close <name> | clean [--days 30] (open = deprecated alias of login)
98
118
 
99
119
  Common options:
100
120
  --mode direct|hub mode for "init"
@@ -111,7 +131,12 @@ Common options:
111
131
  --no-approval disable the human approval gate (dangerous)
112
132
  --no-shell disable shell execution entirely
113
133
 
114
- Config file: ${CONFIG_DIR}/config.json`);
134
+ Config file: ${CONFIG_DIR}/config.json
135
+
136
+ Shell completion:
137
+ arena-bridge completion bash|zsh|fish print shell completion script
138
+ # then: arena-bridge completion bash >> ~/.bashrc or eval "$(arena-bridge completion bash)"
139
+ `);
115
140
  }
116
141
 
117
142
  function cmdInit(args) {
@@ -340,8 +365,18 @@ function cmdTools() {
340
365
  console.log(JSON.stringify(engine.mcpTools(), null, 2));
341
366
  }
342
367
 
343
- function cmdApprovals() {
368
+ function cmdApprovals(args) {
369
+ const act = String(args._[1] || '').toLowerCase();
370
+ if (act === 'prune' || act === 'clean') {
371
+ const days = Number(args.flags.days || args._[2] || 14);
372
+ const d = Number.isFinite(days) && days>0 ? days : 14;
373
+ const res = pruneApprovals(d);
374
+ console.log(`pruned ${res.removed} approval(s) older than ${d} days`);
375
+ return;
376
+ }
377
+ const isJson = !!(args?.flags?.json);
344
378
  const list = listApprovals();
379
+ if (isJson) { console.log(JSON.stringify(list, null, 2)); return; }
345
380
  if (!list.length) {
346
381
  console.log('no approval requests');
347
382
  return;
@@ -373,6 +408,24 @@ function cmdApprove(args) {
373
408
 
374
409
  function cmdTrust(args) {
375
410
  const state = trustState();
411
+ if (args.flags.extend || args.flags.extend) {
412
+ const cur = trustState();
413
+ if (!cur.active) { console.error('no active trust window to extend — use arena-bridge trust --for 2h'); process.exit(1); }
414
+ const ms = parseDuration(args.flags.for || args.flags.extend || '1h');
415
+ const saved = saveTrust({ ...cur, until: cur.until + ms, enabled: true, createdAt: cur.createdAt || Date.now() });
416
+ console.log(`✓ trust window extended: until ${new Date(saved.until).toLocaleString()} (+${Math.round(ms/60000)} min)`);
417
+ return;
418
+ }
419
+ if (args.flags.history) {
420
+ try {
421
+ const hist = path.join(CONFIG_DIR, 'trust.history.json');
422
+ if (!fs.existsSync(hist)) { console.log('no trust history yet'); return; }
423
+ const data = JSON.parse(fs.readFileSync(hist,'utf8'));
424
+ if (args.flags.json) console.log(JSON.stringify(data, null, 2));
425
+ else { for (const h of data.slice(-20)) console.log(`${new Date(h.until).toLocaleString()} ${h.tools.length? h.tools.join(','):'all'} ${h.paths.length? h.paths.join(','):''} ${h.by||''}`); }
426
+ } catch (e) { console.error(e.message); }
427
+ return;
428
+ }
376
429
  if (args.flags.off) {
377
430
  clearTrust();
378
431
  console.log('✓ trust window cleared — every side-effecting action needs approval again');
@@ -445,8 +498,54 @@ function cmdAudit(args) {
445
498
  console.log(rec ? JSON.stringify(rec, null, 2) : `no entry with id ${what}`);
446
499
  return;
447
500
  }
448
- const n = Number(args.flags.n || 30);
449
- for (const rec of tailAudit(n)) {
501
+ // B8 fix: handle -n, --n, and positional number
502
+ let n = 30;
503
+ if (args.flags.n != null) n = Number(args.flags.n);
504
+ else if (args.flags.N != null) n = Number(args.flags.N);
505
+ else if (args._[1] && /^\d+$/.test(String(args._[1]))) n = Number(args._[1]);
506
+ if (!Number.isFinite(n) || n <= 0) n = 30;
507
+ n = Math.min(n, 200);
508
+ let entries = tailAudit(Math.min(n*5, 500));
509
+ if (args.flags.since) {
510
+ try {
511
+ const ms = parseDuration(String(args.flags.since));
512
+ const cutoff = Date.now() - ms;
513
+ entries = entries.filter(e => {
514
+ const ts = e.ts ? new Date(e.ts).getTime() : (e.createdAt||0);
515
+ return ts >= cutoff;
516
+ });
517
+ } catch {}
518
+ }
519
+ if (args.flags.from) {
520
+ try {
521
+ const from = new Date(String(args.flags.from)).getTime();
522
+ if (Number.isFinite(from)) entries = entries.filter(e => {
523
+ const ts = e.ts ? new Date(e.ts).getTime() : (e.createdAt||0);
524
+ return ts >= from;
525
+ });
526
+ } catch {}
527
+ }
528
+ if (args.flags.to) {
529
+ try {
530
+ const to = new Date(String(args.flags.to)).getTime();
531
+ if (Number.isFinite(to)) entries = entries.filter(e => {
532
+ const ts = e.ts ? new Date(e.ts).getTime() : (e.createdAt||0);
533
+ return ts <= to;
534
+ });
535
+ } catch {}
536
+ }
537
+ if (args.flags.tool) {
538
+ const want = String(args.flags.tool).toLowerCase();
539
+ entries = entries.filter(e => String(e.tool||'').toLowerCase() === want);
540
+ entries = entries.slice(-n);
541
+ } else {
542
+ entries = entries.slice(-n);
543
+ }
544
+ if (args.flags.json) {
545
+ console.log(JSON.stringify(entries, null, 2));
546
+ return;
547
+ }
548
+ for (const rec of entries) {
450
549
  const arts = (rec.artifacts || []).map((a) => a.name).join(' ');
451
550
  console.log(
452
551
  `${rec.ts} ${String(rec.tool).padEnd(18)} ${String(rec.status).padEnd(14)} ${String(rec.duration_ms ?? '').padStart(6)}ms${arts ? ' ' + arts : ''}${
@@ -465,6 +564,53 @@ async function cmdSetup(args) {
465
564
  await cmdTunnel(args);
466
565
  }
467
566
 
567
+ function cmdOpen() {
568
+ const cfg = loadConfig();
569
+ const url = cfg.publicUrl;
570
+ if (!url) {
571
+ console.error('no public URL yet — run "arena-bridge tunnel" or "arena-bridge service install"');
572
+ process.exit(1);
573
+ }
574
+ console.log(`opening ${url} ...`);
575
+ try {
576
+ // execSync already imported
577
+ const cmd = process.platform === 'darwin' ? `open "${url}"` : process.platform === 'win32' ? `start "" "${url}"` : `xdg-open "${url}"`;
578
+ execSync(cmd);
579
+ } catch (e) {
580
+ console.log(url);
581
+ }
582
+ }
583
+
584
+ function cmdStatus(args) {
585
+ const isJson = !!(args.flags.json || args.flags['output-json']);
586
+ const cfg = loadConfig();
587
+ const checks = [];
588
+ const hasConfig = fs.existsSync(path.join(CONFIG_DIR, 'config.json'));
589
+ checks.push({ name: 'config', ok: hasConfig, detail: hasConfig ? CONFIG_DIR : 'missing — run arena-bridge init' });
590
+ checks.push({ name: 'token', ok: !!cfg.token, detail: cfg.token ? 'present' : 'MISSING' });
591
+ checks.push({ name: 'publicUrl', ok: !!cfg.publicUrl, detail: cfg.publicUrl || 'not set — run arena-bridge tunnel' });
592
+ try {
593
+ const st = trustState();
594
+ checks.push({ name: 'trust window', ok: !!st.active, detail: st.active ? `active until ${new Date(st.until).toLocaleString()}` : 'none (approvals required)' });
595
+ } catch {}
596
+ try {
597
+ const pending = listApprovals().filter(a => a.status==='pending').length;
598
+ checks.push({ name: 'pending approvals', ok: true, detail: `${pending} pending` });
599
+ } catch {}
600
+ checks.push({ name: 'API port', ok: true, detail: `${cfg.host||'127.0.0.1'}:${Number(cfg.port||8787)} (expected)` });
601
+ try {
602
+ const svc = serviceStatus();
603
+ checks.push({ name: 'service', ok: svc.installed, detail: svc.installed ? (svc.running ? 'installed, running' : 'installed, not running') : 'not installed' });
604
+ } catch {}
605
+ if (isJson) {
606
+ console.log(JSON.stringify({ ok: checks.every(c=>c.ok && c.name!=='pending approvals' && c.name!=='API port'), checks, version: cfg._state?.version || undefined, publicUrl: cfg.publicUrl || null }, null, 2));
607
+ } else {
608
+ for (const c of checks) console.log(`${c.ok ? '✓' : (c.name==='trust window' || c.name==='publicUrl' ? '○' : '✗')} ${c.name.padEnd(18)} ${c.detail}`);
609
+ console.log(`\nPublic URL: ${cfg.publicUrl || '(not set)'}`);
610
+ if (!cfg.publicUrl) console.log('Run: arena-bridge tunnel or arena-bridge service install');
611
+ }
612
+ }
613
+
468
614
  function cmdUrl() {
469
615
  const cfg = loadConfig();
470
616
  if (!cfg.publicUrl) {
@@ -506,6 +652,27 @@ async function cmdUpdate(args) {
506
652
  console.log('restart the bridge to use the new version: arena-bridge tunnel');
507
653
  }
508
654
 
655
+ function cmdRestart(args) {
656
+ const cfg = loadConfig();
657
+ try {
658
+ const st = serviceStatus();
659
+ if (st.installed) {
660
+ console.log('restarting service...');
661
+ try {
662
+ const label = 'ai.arena.bridge';
663
+ let res = spawnSync('launchctl', ['kickstart', '-k', `gui/${process.uid}/${label}`], { encoding: 'utf8' });
664
+ if (res.status !== 0) res = spawnSync('launchctl', ['kickstart', '-k', label], { encoding: 'utf8' });
665
+ if (res.status === 0) { console.log('✓ service kickstarted'); return; }
666
+ console.log(`kickstart failed: ${res.stderr || res.stdout || res.error || 'unknown'}`);
667
+ } catch (e) { console.log(`kickstart error: ${e.message}`); }
668
+ console.log('fallback: arena-bridge service uninstall && arena-bridge service install');
669
+ return;
670
+ }
671
+ } catch {}
672
+ console.log('no service installed — restart your API manually:');
673
+ console.log(` arena-bridge start --port ${cfg.port||8787}`);
674
+ }
675
+
509
676
  function cmdService(args) {
510
677
  const what = args._[1] || 'status';
511
678
  if (what === 'install') {
@@ -527,6 +694,20 @@ function cmdService(args) {
527
694
  console.log(`\u2713 service removed: ${res.removed}`);
528
695
  return;
529
696
  }
697
+ if (what === 'logs') {
698
+ const logs = ["service-reload.err.log", "service-reload.out.log", "bridge.log"].map(f => path.join(CONFIG_DIR, 'logs', f));
699
+ let n = Number(args.flags.n || 50); if (!Number.isFinite(n) || n<=0) n=50; n=Math.min(n,200);
700
+ for (const f of logs) {
701
+ try {
702
+ const fs2=fs;
703
+ if (!fs2.existsSync(f)) continue;
704
+ console.log(`\n=== ${f} (last ${n} lines) ===`);
705
+ const lines=fs2.readFileSync(f,'utf8').trim().split('\n').slice(-n);
706
+ for (const l of lines) console.log(l.slice(0,1000));
707
+ } catch {}
708
+ }
709
+ return;
710
+ }
530
711
  const st = serviceStatus();
531
712
  console.log(`service: ${st.installed ? 'installed' : 'not installed'} (${st.running ? 'running' : 'not running'})`);
532
713
  console.log(` plist: ${st.plist}`);
@@ -540,6 +721,7 @@ function cmdBrowser(args) {
540
721
  const what = args._[1] || 'list';
541
722
  if (what === 'list') {
542
723
  const profiles = listProfiles();
724
+ if (args.flags.json) { console.log(JSON.stringify(profiles, null, 2)); return; }
543
725
  if (!profiles.length) {
544
726
  console.log('no agent browser profiles yet — create one: arena-bridge browser login <name>');
545
727
  return;
@@ -589,6 +771,21 @@ function cmdBrowser(args) {
589
771
  console.log(` the agent opens the same profile with: chrome_launch {"profile":"${sanitizeProfile(name)}"}`);
590
772
  return;
591
773
  }
774
+ if (what === 'clean' || what === 'prune') {
775
+ const days = Number(args.flags.days || args._[2] || 30);
776
+ const d = Number.isFinite(days) && days>0 ? days : 30;
777
+ const profiles = listProfiles();
778
+ let removed=0;
779
+ for (const prof of profiles) {
780
+ const ageDays = (Date.now() - prof.mtime) / 86400000;
781
+ if (ageDays > d) {
782
+ try { fs.rmSync(prof.path, { recursive: true, force: true }); removed++; console.log(`removed ${prof.name} (${Math.round(ageDays)} days old)`); } catch {}
783
+ }
784
+ }
785
+ if (!removed) console.log(`no profiles older than ${d} days`);
786
+ else console.log(`cleaned ${removed} profile(s)`);
787
+ return;
788
+ }
592
789
  if (what === 'close') {
593
790
  const name = args._[2];
594
791
  if (!name) {
@@ -617,7 +814,7 @@ function cmdBrowser(args) {
617
814
  console.log(`✓ closed ${killed} Chrome window(s) for "${sanitizeProfile(name)}"`);
618
815
  return;
619
816
  }
620
- console.error(`unknown browser action: ${what}\nuse: list | login <name> | close <name>`);
817
+ console.error(`unknown browser action: ${what}\nuse: list | login <name> | close <name> | clean`);
621
818
  process.exitCode = 1;
622
819
  }
623
820
 
@@ -636,6 +833,106 @@ function cmdRotate(args) {
636
833
  );
637
834
  }
638
835
 
836
+ function cmdConfig(args) {
837
+ const sub = args._[1] || 'list';
838
+ const cfg = loadConfig();
839
+ if (sub === 'list' || sub === 'show') {
840
+ const out = { ...cfg };
841
+ delete out.configPath;
842
+ if (args.flags.json) {
843
+ console.log(JSON.stringify(out, null, 2));
844
+ } else {
845
+ for (const [k, v] of Object.entries(out)) {
846
+ if (k === '_state') continue;
847
+ console.log(`${k}: ${typeof v === 'object' ? JSON.stringify(v) : v}`);
848
+ }
849
+ }
850
+ return;
851
+ }
852
+ if (sub === 'get') {
853
+ const key = args._[2];
854
+ if (!key) { console.error('usage: arena-bridge config get <key>'); process.exit(1); }
855
+ const val = key.split('.').reduce((o, k) => o?.[k], cfg);
856
+ if (val === undefined) { console.error(`no such key: ${key}`); process.exit(1); }
857
+ if (args.flags.json) console.log(JSON.stringify({ key, value: val }, null, 2));
858
+ else console.log(typeof val === 'object' ? JSON.stringify(val, null, 2) : String(val));
859
+ return;
860
+ }
861
+ if (sub === 'set') {
862
+ const key = args._[2];
863
+ const value = args._[3];
864
+ if (!key || value === undefined) { console.error('usage: arena-bridge config set <key> <value>'); process.exit(1); }
865
+ // validate key against known config keys
866
+ const allowed = Object.keys(DEFAULTS);
867
+ const topKey = key.split('.')[0];
868
+ if (!allowed.includes(topKey) && !['exposeDeviceInHealth','telegram'].includes(topKey)) {
869
+ console.error(`unknown config key: ${topKey} (allowed: ${allowed.join(', ')})`);
870
+ process.exit(1);
871
+ }
872
+ let parsed = value;
873
+ try { parsed = JSON.parse(value); } catch { /* keep as string */ }
874
+ if (key.includes('.')) {
875
+ const parts = key.split('.');
876
+ let cur = cfg;
877
+ for (let i = 0; i < parts.length - 1; i++) {
878
+ if (!cur[parts[i]] || typeof cur[parts[i]] !== 'object') cur[parts[i]] = {};
879
+ cur = cur[parts[i]];
880
+ }
881
+ cur[parts[parts.length - 1]] = parsed;
882
+ } else {
883
+ cfg[key] = parsed;
884
+ }
885
+ saveConfig(cfg);
886
+ console.log(`✓ config ${key} = ${JSON.stringify(parsed)}`);
887
+ return;
888
+ }
889
+ if (sub === 'diff') {
890
+ const isJson = !!(args.flags.json);
891
+ const defs = DEFAULTS;
892
+ const diffs = {};
893
+ for (const k of Object.keys(cfg)) {
894
+ if (k === 'configPath' || k === '_state') continue;
895
+ const cur = cfg[k];
896
+ const def = defs[k];
897
+ if (JSON.stringify(cur) !== JSON.stringify(def)) diffs[k] = { current: cur, default: def };
898
+ }
899
+ if (isJson) console.log(JSON.stringify(diffs, null, 2));
900
+ else {
901
+ if (!Object.keys(diffs).length) console.log('✓ config matches defaults');
902
+ else {
903
+ console.log('config diff (current vs default):');
904
+ for (const [k,v] of Object.entries(diffs)) {
905
+ console.log(` ${k}:`);
906
+ console.log(` current: ${JSON.stringify(v.current)}`);
907
+ console.log(` default: ${JSON.stringify(v.default)}`);
908
+ }
909
+ }
910
+ }
911
+ return;
912
+ }
913
+ if (sub === 'validate') {
914
+ const isJson = !!(args.flags.json);
915
+ const errs = [];
916
+ if (!cfg.roots || !cfg.roots.length) errs.push('roots is empty — run arena-bridge init --root ~/projects');
917
+ else for (const r of cfg.roots) { try { if (!fs.existsSync(r)) errs.push(`root not found: ${r}`); } catch {} }
918
+ if (!cfg.token) errs.push('token missing — run arena-bridge init');
919
+ if (!cfg.deviceToken) errs.push('deviceToken missing');
920
+ if (!Number.isFinite(Number(cfg.port)) || Number(cfg.port) < 1 || Number(cfg.port) > 65535) errs.push(`port invalid: ${cfg.port}`);
921
+ if (isJson) console.log(JSON.stringify({ ok: errs.length===0, errors: errs }, null, 2));
922
+ else { if (!errs.length) console.log('✓ config valid'); else { console.log('✗ config issues:'); for (const e of errs) console.log(` - ${e}`); process.exitCode=1; } }
923
+ return;
924
+ }
925
+ if (sub === 'edit') {
926
+ const editor = process.env.EDITOR || process.env.VISUAL || 'nano';
927
+ // spawnSync already imported
928
+ const res = spawnSync(editor, [cfg.configPath || path.join(CONFIG_DIR, 'config.json')], { stdio: 'inherit' });
929
+ if (res.error) console.error(`cannot open editor: ${res.error.message}`);
930
+ return;
931
+ }
932
+ console.error(`unknown config action: ${sub}\nuse: get <key> | set <key> <value> | edit | list | validate | diff`);
933
+ process.exit(1);
934
+ }
935
+
639
936
  async function cmdTelegram(args) {
640
937
  const cfg = loadConfig();
641
938
  const sub = args._[1] || 'status';
@@ -715,33 +1012,150 @@ async function cmdTelegram(args) {
715
1012
  }
716
1013
  }
717
1014
 
718
- function cmdDoctor() {
1015
+ function cmdCompletion(args) {
1016
+ const shell = String(args._[1] || 'bash').toLowerCase();
1017
+ if (shell === 'bash') console.log(COMPLETION_BASH);
1018
+ else if (shell === 'zsh') console.log(COMPLETION_ZSH);
1019
+ else if (shell === 'fish') console.log(COMPLETION_FISH);
1020
+ else {
1021
+ console.error(`unknown shell: ${shell} (use bash|zsh|fish)`);
1022
+ process.exit(1);
1023
+ }
1024
+ }
1025
+
1026
+ function cmdCleanup(args) {
1027
+ const days = Number(args.flags.days || args._[1] || 14);
1028
+ const d = Number.isFinite(days) && days > 0 ? days : 14;
1029
+ const a1 = pruneArtifacts(d);
1030
+ const a2 = pruneApprovals(d);
1031
+ let a3 = { removed: 0 };
1032
+ try { a3 = pruneInbox(d); } catch {}
1033
+ console.log(`cleanup: removed ${a1.removed} artifact folder(s) (${a1.freed_bytes||0} bytes), ${a2.removed} old approval(s), ${a3.removed||0} telegram file(s) older than ${d} days`);
1034
+ }
1035
+
1036
+ async function cmdEvents(args) {
1037
+ const cfg = loadConfig();
1038
+ const isJson = !!(args.flags.json);
1039
+ const url = `http://${cfg.host||'127.0.0.1'}:${cfg.port||8787}/v1/events`;
1040
+ const token = cfg.token || cfg.localToken;
1041
+ console.log(`# streaming ${url} (Ctrl-C to stop)`);
1042
+ try {
1043
+ const res = await fetch(url, { headers: token ? { Authorization: `Bearer ${token}` } : {} });
1044
+ if (!res.ok) { console.error(`events: ${res.status} ${res.statusText}`); return; }
1045
+ const reader = res.body.getReader();
1046
+ const decoder = new TextDecoder();
1047
+ let buf='';
1048
+ while (true) {
1049
+ const { done, value } = await reader.read();
1050
+ if (done) break;
1051
+ buf += decoder.decode(value, { stream:true });
1052
+ let idx;
1053
+ while ((idx = buf.indexOf('\n\n')) !== -1) {
1054
+ const chunk = buf.slice(0, idx);
1055
+ buf = buf.slice(idx+2);
1056
+ if (!chunk.trim() || chunk.startsWith(':')) continue;
1057
+ // parse event: and data:
1058
+ let event='message', data='';
1059
+ for (const line of chunk.split('\n')) {
1060
+ if (line.startsWith('event:')) event=line.slice(6).trim();
1061
+ if (line.startsWith('data:')) data+=line.slice(5).trim();
1062
+ }
1063
+ if (isJson) console.log(JSON.stringify({ event, data: (()=>{ try{return JSON.parse(data)}catch{return data}})() }));
1064
+ else console.log(`[${event}] ${data}`);
1065
+ }
1066
+ }
1067
+ } catch (e) { console.error(`events error: ${e.message}`); }
1068
+ }
1069
+
1070
+ function cmdLogs(args) {
1071
+ const isJson = !!(args.flags.json || args.flags['output-json']);
1072
+ let n = 30;
1073
+ if (args.flags.n != null) n = Number(args.flags.n);
1074
+ else if (args._[1] && /^\d+$/.test(String(args._[1]))) n = Number(args._[1]);
1075
+ if (!Number.isFinite(n) || n <= 0) n = 30;
1076
+ n = Math.min(n, 500);
1077
+ const entries = tailLog(n);
1078
+ if (!entries.length) {
1079
+ console.log(`no log entries yet (${logPathForCli()})`);
1080
+ return;
1081
+ }
1082
+ if (isJson) {
1083
+ console.log(JSON.stringify(entries, null, 2));
1084
+ } else {
1085
+ for (const e of entries) {
1086
+ if (e.raw) console.log(e.raw);
1087
+ else console.log(`${e.ts} ${String(e.level||'').padEnd(5)} ${e.msg||''} ${e.tool? '['+e.tool+']':''} ${e.error||''}`.trim());
1088
+ }
1089
+ console.log(`\n-- ${entries.length} entries from ${logPathForCli()} --`);
1090
+ }
1091
+ }
1092
+
1093
+ function cmdDoctor(args) {
1094
+ const isJson = !!(args?.flags?.json || args?.flags?.['output-json']);
1095
+ const doFix = !!(args?.flags?.fix || args?.flags?.['fix']);
1096
+ if (doFix) {
1097
+ try {
1098
+ ensureDirs();
1099
+ console.log(`✓ ensured ${CONFIG_DIR} exists with 0700`);
1100
+ try { fs.chmodSync(CONFIG_DIR, 0o700); } catch {}
1101
+ } catch (e) { console.error(`fix failed: ${e.message}`); }
1102
+ }
719
1103
  const cfg = loadConfig();
720
1104
  const checks = [];
721
- checks.push(['config file', fs.existsSync(path.join(CONFIG_DIR, 'config.json')), CONFIG_DIR]);
722
- checks.push(['agent token', !!cfg.token, cfg.token ? 'present' : 'MISSING — run init']);
723
- checks.push(['device token', !!cfg.deviceToken, cfg.deviceToken ? 'present' : 'MISSING — run init']);
724
- checks.push(['mode', !!cfg.mode, cfg.mode]);
725
- checks.push(['roots', (cfg.roots || []).length > 0, (cfg.roots || []).join(', ')]);
726
- checks.push(['approval gate', cfg.requireApproval !== false, cfg.requireApproval ? 'on' : 'OFF (dangerous)']);
727
- checks.push(['shell', cfg.allowShell !== false, cfg.allowShell ? 'on' : 'off']);
728
- checks.push(['protected paths', (cfg.protected || []).length > 0, `${(cfg.protected || []).length} entries`]);
1105
+ checks.push({ name: 'config file', code: 'config_file', passed: fs.existsSync(path.join(CONFIG_DIR, 'config.json')), detail: CONFIG_DIR, hint: 'run arena-bridge init --root <path>' });
1106
+ checks.push({ name: 'agent token', code: 'agent_token', passed: !!cfg.token, detail: cfg.token ? 'present' : 'MISSING', hint: 'run arena-bridge init' });
1107
+ checks.push({ name: 'device token', code: 'device_token', passed: !!cfg.deviceToken, detail: cfg.deviceToken ? 'present' : 'MISSING', hint: 'run arena-bridge init' });
1108
+ checks.push({ name: 'mode', code: 'mode', passed: !!cfg.mode, detail: cfg.mode, hint: '' });
1109
+ checks.push({ name: 'roots', code: 'roots', passed: (cfg.roots || []).length > 0, detail: (cfg.roots || []).join(', '), hint: 'arena-bridge init --root ~/Documents' });
1110
+ checks.push({ name: 'approval gate', code: 'approval_gate', passed: cfg.requireApproval !== false, detail: cfg.requireApproval ? 'on' : 'OFF (dangerous)', hint: 'set requireApproval=true in config' });
1111
+ checks.push({ name: 'shell', code: 'shell', passed: cfg.allowShell !== false, detail: cfg.allowShell ? 'on' : 'off', hint: '' });
1112
+ checks.push({ name: 'protected paths', code: 'protected', passed: (cfg.protected || []).length > 0, detail: `${(cfg.protected || []).length} entries`, hint: '' });
1113
+ // config validate as doctor checks
1114
+ try {
1115
+ if (!cfg.roots || !cfg.roots.length) checks.push({ name: 'config roots', code: 'config_roots', passed: false, detail: 'empty', hint: 'run arena-bridge init --root ~/projects' });
1116
+ else for (const r of cfg.roots) if (!fs.existsSync(r)) checks.push({ name: `root ${r}`, code: 'config_root_missing', passed: false, detail: 'not found', hint: `mkdir -p ${r}` });
1117
+ if (!cfg.token) checks.push({ name: 'config token', code: 'config_token', passed: false, detail: 'missing', hint: 'run arena-bridge init' });
1118
+ if (!Number.isFinite(Number(cfg.port)) || Number(cfg.port) < 1 || Number(cfg.port) > 65535) checks.push({ name: 'config port', code: 'config_port', passed: false, detail: `invalid: ${cfg.port}`, hint: 'arena-bridge config set port 8787' });
1119
+ } catch {}
1120
+ // service health as doctor check (non-fatal)
1121
+ try { const svc = serviceStatus(); checks.push({ name: 'service health', code: 'service_health', passed: svc.installed ? svc.running : true, detail: svc.installed ? (svc.running ? 'running' : 'not running') : 'not installed', hint: svc.installed && !svc.running ? 'arena-bridge service install' : '' }); } catch {}
1122
+
1123
+ // audit log + bridge.log size checks (R6)
1124
+ try {
1125
+ const alPath = path.join(CONFIG_DIR, 'audit.log');
1126
+ if (fs.existsSync(alPath)) {
1127
+ const sz = fs.statSync(alPath).size;
1128
+ if (sz > 10*1024*1024) checks.push({ name: 'audit log size', code: 'audit_log_size', passed: false, detail: `${(sz/1024/1024).toFixed(1)} MB — run arena-bridge cleanup`, hint: 'arena-bridge cleanup --days 14' });
1129
+ else checks.push({ name: 'audit log size', code: 'audit_log_size', passed: true, detail: `${(sz/1024).toFixed(0)} KB`, hint: '' });
1130
+ }
1131
+ } catch {}
1132
+ try {
1133
+ const blPath = path.join(CONFIG_DIR, 'logs', 'bridge.log');
1134
+ if (fs.existsSync(blPath)) {
1135
+ const sz = fs.statSync(blPath).size;
1136
+ if (sz > 5*1024*1024) checks.push({ name: 'bridge.log size', code: 'bridge_log_size', passed: false, detail: `${(sz/1024/1024).toFixed(1)} MB — consider arena-bridge logs prune`, hint: 'arena-bridge cleanup' });
1137
+ }
1138
+ } catch {}
729
1139
  const peek = findPeekaboo(cfg);
730
- checks.push(['peekaboo (desktop control)', !!peek, peek || 'not installed - screen and mouse control are off']);
1140
+ checks.push({ name: 'peekaboo (desktop control)', code: 'peekaboo', passed: !!peek, detail: peek || 'not installed - screen and mouse control are off', hint: 'brew install peekaboo or set peekabooPath' });
731
1141
  const chrome = [
732
1142
  '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
733
1143
  '/Applications/Chromium.app/Contents/MacOS/Chromium',
734
1144
  ].find((c) => fs.existsSync(c));
735
- checks.push(['chrome', !!chrome, chrome || 'not found in /Applications']);
736
- let ok = true;
737
- for (const [name, passed, detail] of checks) {
738
- if (!passed) ok = false;
739
- console.log(`${passed ? '✓' : '✗'} ${name.padEnd(18)} ${detail}`);
1145
+ checks.push({ name: 'chrome', code: 'chrome', passed: !!chrome, detail: chrome || 'not found in /Applications', hint: 'install Chrome to use browser tools' });
1146
+ const ok = checks.every(c => c.passed);
1147
+ if (isJson) {
1148
+ console.log(JSON.stringify({ ok, version: VERSION, publicUrl: cfg.publicUrl || null, node: process.version, checks }, null, 2));
1149
+ } else {
1150
+ for (const c of checks) {
1151
+ console.log(`${c.passed ? '✓' : '✗'} ${c.name.padEnd(18)} ${c.detail}`);
1152
+ }
1153
+ console.log(
1154
+ `\nNode ${process.version} • public URL: ${cfg.publicUrl || '(not set — run with --public-url or set config.publicUrl)'}`,
1155
+ );
740
1156
  }
741
- console.log(
742
- `\nNode ${process.version} • public URL: ${cfg.publicUrl || '(not set — run with --public-url or set config.publicUrl)'}`,
743
- );
744
1157
  if (!ok) process.exitCode = 1;
1158
+ return { ok, checks };
745
1159
  }
746
1160
 
747
1161
  export async function main(argv = process.argv.slice(2)) {
@@ -770,6 +1184,14 @@ export async function main(argv = process.argv.slice(2)) {
770
1184
  return cmdApprove(args);
771
1185
  case 'audit':
772
1186
  return cmdAudit(args);
1187
+ case 'events':
1188
+ return cmdEvents(args);
1189
+ case 'logs':
1190
+ return cmdLogs(args);
1191
+ case 'cleanup':
1192
+ return cmdCleanup(args);
1193
+ case 'config':
1194
+ return cmdConfig(args);
773
1195
  case 'telegram':
774
1196
  return cmdTelegram(args);
775
1197
  case 'rotate':
@@ -778,16 +1200,24 @@ export async function main(argv = process.argv.slice(2)) {
778
1200
  return cmdTrust(args);
779
1201
  case 'doctor':
780
1202
  return cmdDoctor(args);
1203
+ case 'status':
1204
+ return cmdStatus(args);
781
1205
  case 'url':
782
1206
  return cmdUrl();
1207
+ case 'open':
1208
+ return cmdOpen();
783
1209
  case 'version':
784
1210
  return cmdVersion();
785
1211
  case 'update':
786
1212
  return cmdUpdate(args);
787
1213
  case 'service':
788
1214
  return cmdService(args);
1215
+ case 'restart':
1216
+ return cmdRestart(args);
789
1217
  case 'browser':
790
1218
  return cmdBrowser(args);
1219
+ case 'completion':
1220
+ return cmdCompletion(args);
791
1221
  case undefined:
792
1222
  case 'help':
793
1223
  case '--help':