simcast-host 0.0.0-stage → 0.9.1

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.
@@ -0,0 +1,617 @@
1
+ // simcast-host: the Mac side of simcast, as a command (installed with npm).
2
+ // main(argv) returns the exit code; bin/simcast-host.js sets it.
3
+ import fs from 'node:fs';
4
+ import http from 'node:http';
5
+ import os from 'node:os';
6
+ import readline from 'node:readline';
7
+ import { parseArgs } from 'node:util';
8
+ import { DEFAULT_PORT, VERSION, color } from '../common.js';
9
+ import { AGENT_LABEL, LOG_FILE, isMac } from './paths.js';
10
+ import { agentHealth, agentPort, clearStatus, isAgentHealth, pidAlive, readStatus, watchForUpgrade, writeStatus } from './runtime.js';
11
+ import { loadAgentConfig, readAgentConfigSafe } from './state.js';
12
+
13
+ // Exit codes (sysexits where one fits).
14
+ const USAGE = 64;
15
+ const UNAVAILABLE = 70;
16
+
17
+ const HELP = `simcast-host ${VERSION}: the Mac side of simcast (use this Mac's iOS Simulator from a Windows, Linux or Mac computer)
18
+
19
+ Usage: simcast-host <command> [options]
20
+
21
+ Getting started:
22
+ setup [--check] [--yes] Check this Mac and fix what's missing (Xcode, simulators, CocoaPods)
23
+ [--download] With --yes, also download the iOS Simulator runtime (about 8 GB)
24
+ pair [--seconds N] Show a pairing code to type into simcast pair on your computer
25
+ status Is the agent running? Version, port, active PC
26
+ doctor Check everything, change nothing
27
+
28
+ Running the agent:
29
+ serve [--port N] Run the agent in this terminal (the LaunchAgent runs it for you)
30
+ install [--port N] Run the agent at login, as a LaunchAgent (setup does this)
31
+ uninstall Remove that LaunchAgent
32
+ logs [-f] [-n N] Show the agent's log (-f keeps following it)
33
+
34
+ Housekeeping:
35
+ clean [--yes] [--dry-run] Free disk space: old builds, idle DerivedData, dead simulators
36
+
37
+ Paired PCs:
38
+ pcs List the paired PCs (the Mac works with one at a time)
39
+ unpair <name|id> | --all Unpair a PC: it has to pair again to use this Mac
40
+
41
+ Options:
42
+ --json Machine-readable output (pair, pcs, unpair, status, setup, doctor, clean)
43
+ --help Show this help
44
+ --version Print the version
45
+
46
+ setup starts the agent at login as a LaunchAgent (com.simcast.host).
47
+ Log: ${LOG_FILE}
48
+ `;
49
+
50
+ export async function main(argv = []) {
51
+ if (argv.includes('--version') || argv[0] === 'version' || argv[0] === '-v') {
52
+ console.log(VERSION);
53
+ return 0;
54
+ }
55
+ // Commands with their own usage text get --help passed through.
56
+ const ownHelp = ['clean'].includes(argv[0]);
57
+ if (argv.length === 0 || argv[0] === 'help' || (!ownHelp && (argv.includes('--help') || argv.includes('-h')))) {
58
+ process.stdout.write(HELP);
59
+ return 0;
60
+ }
61
+ const [cmd, ...args] = argv;
62
+ const handler = COMMANDS[cmd];
63
+ if (!handler) {
64
+ console.error(`Unknown command "${cmd}". Run simcast-host --help to see the commands.`);
65
+ return USAGE;
66
+ }
67
+ if (!isMac()) {
68
+ console.error(`simcast-host ${cmd} runs on the Mac. On your computer, use the simcast command.`);
69
+ return 1;
70
+ }
71
+ try {
72
+ return await handler(args);
73
+ } catch (err) {
74
+ if (err.code?.startsWith?.('ERR_PARSE_ARGS')) {
75
+ console.error(`${err.message}\nRun simcast-host --help for usage.`);
76
+ return USAGE;
77
+ }
78
+ throw err;
79
+ }
80
+ }
81
+
82
+ const COMMANDS = {
83
+ serve: serveCmd,
84
+ pair: pairCmd,
85
+ pcs: pcsCmd,
86
+ unpair: unpairCmd,
87
+ status: statusCmd,
88
+ logs: logsCmd,
89
+ setup: (args) => external('./setup.js', 'setupCmd', 'setup', args, ['./checks.js']),
90
+ doctor: (args) => external('./checks.js', 'doctorCmd', 'doctor', args, ['./setup.js']),
91
+ clean: (args) => external('./clean.js', 'cleanCmd', 'clean', args),
92
+ install: (args) => external('./service.js', 'installCmd', 'install', args),
93
+ uninstall: (args) => external('./service.js', 'uninstallCmd', 'uninstall', args),
94
+ };
95
+
96
+ // Command modules load when used, so a missing or broken one only affects its command.
97
+ // setupCmd and doctorCmd may live in setup.js or checks.js; the first module that
98
+ // exports the function wins. A module that exists but fails to load is a real error.
99
+ async function external(spec, name, cmd, args, fallbacks = []) {
100
+ for (const s of [spec, ...fallbacks]) {
101
+ const url = new URL(s, import.meta.url);
102
+ if (!fs.existsSync(url)) continue;
103
+ const mod = await import(url.href);
104
+ if (typeof mod[name] === 'function') return (await mod[name](args)) ?? 0;
105
+ }
106
+ console.error(`${cmd} isn't available in this build.`);
107
+ return UNAVAILABLE;
108
+ }
109
+
110
+ // ---- shared ----------------------------------------------------------------
111
+
112
+ const addresses = () => Object.values(os.networkInterfaces()).flat()
113
+ .filter((a) => a && a.family === 'IPv4' && !a.internal).map((a) => a.address);
114
+
115
+ async function pairedPC() {
116
+ const { pairedClient } = await import('./clients.js');
117
+ return pairedClient() || null;
118
+ }
119
+
120
+ // /health's body when a simcast agent answers on this Mac's port, else null.
121
+ async function runningAgent(port) {
122
+ const h = await agentHealth(port);
123
+ return isAgentHealth(h) ? h : null;
124
+ }
125
+
126
+
127
+ function managerOf(env = process.env) {
128
+ if (env.XPC_SERVICE_NAME === AGENT_LABEL) return 'launchd';
129
+ return 'foreground';
130
+ }
131
+
132
+ function printJson(value) {
133
+ console.log(JSON.stringify(value, null, 2));
134
+ }
135
+
136
+ // ---- serve -----------------------------------------------------------------
137
+
138
+ const ROTATE_BYTES = 10 * 1024 * 1024;
139
+ const ROTATE_CHECK_MS = 60 * 60 * 1000;
140
+
141
+ // launchd appends to the log forever. Copy it aside and truncate in place: launchd
142
+ // keeps the file open, so renaming it would leave the agent writing to the old one.
143
+ function rotateLog() {
144
+ try {
145
+ if (fs.statSync(LOG_FILE).size <= ROTATE_BYTES) return;
146
+ fs.copyFileSync(LOG_FILE, `${LOG_FILE}.1`);
147
+ fs.truncateSync(LOG_FILE, 0);
148
+ } catch { /* no log yet */ }
149
+ }
150
+
151
+ async function serveCmd(args) {
152
+ const { values } = parseArgs({ args, options: { port: { type: 'string' }, json: { type: 'boolean' } } });
153
+ if (values.port !== undefined && !/^\d+$/.test(values.port)) {
154
+ console.error(`--port must be a number, not "${values.port}".`);
155
+ return USAGE;
156
+ }
157
+
158
+ // One agent at a time: a second one (a terminal while the LaunchAgent runs it, say) steps aside.
159
+ const prev = readStatus();
160
+ if (prev && prev.pid !== process.pid && pidAlive(prev.pid) && prev.port && await runningAgent(prev.port)) {
161
+ const how = { launchd: 'by the LaunchAgent', foreground: 'in a terminal' }[prev.manager] || 'elsewhere';
162
+ console.log(`Another simcast-host is already running ${how} (pid ${prev.pid}, port ${prev.port}).`);
163
+ console.log(' Use the running one, or stop it first: simcast-host uninstall.');
164
+ return 0;
165
+ }
166
+
167
+ if (process.env.XPC_SERVICE_NAME) {
168
+ rotateLog();
169
+ setInterval(rotateLog, ROTATE_CHECK_MS).unref(); // the agent runs for weeks
170
+ }
171
+ const cfg = loadAgentConfig();
172
+ const port = Number(values.port ?? (process.env.SIMCAST_PORT || cfg.port));
173
+ const ownStatus = (boundPort) => ({
174
+ pid: process.pid,
175
+ port: boundPort,
176
+ version: VERSION,
177
+ manager: managerOf(),
178
+ startedAt: new Date().toISOString(),
179
+ logFile: LOG_FILE,
180
+ });
181
+
182
+ // Only remove the status file if it is still ours (a newer agent may have replaced it).
183
+ process.on('exit', () => {
184
+ if (readStatus()?.pid === process.pid) clearStatus();
185
+ });
186
+
187
+ const { startAgent } = await import('./server.js');
188
+ const server = await startAgent({ port: values.port });
189
+
190
+ // startAgent has its own SIGINT/SIGTERM cleanup that exits; this one runs
191
+ // after it, and covers a server without one. The exit hook clears the status.
192
+ for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => process.exit(0));
193
+
194
+ if (!server || typeof server.on !== 'function') {
195
+ writeStatus(ownStatus(port), { replace: true, now: true });
196
+ return new Promise(() => {});
197
+ }
198
+ // The status file is only ours once we own the port: a second serve that loses
199
+ // the port (EADDRINUSE) must leave the running agent's file alone. Replacing it
200
+ // atomically, rather than deleting first, never leaves a gap for readers.
201
+ const listening = () => {
202
+ writeStatus(ownStatus(server.address()?.port || port), { replace: true, now: true });
203
+ };
204
+ if (server.listening) listening();
205
+ else server.once('listening', listening);
206
+ // Restart into a newer install, never during a sync or build or while a screen is
207
+ // watched. Only as the LaunchAgent: its KeepAlive starts the new version, while
208
+ // a terminal's serve would stay down.
209
+ const { liveStatus } = await import('./live.js');
210
+ const { fallbackViewers } = await import('./screen.js');
211
+ if (process.env.XPC_SERVICE_NAME === AGENT_LABEL) watchForUpgrade({
212
+ isBusy: () => Boolean(readStatus()?.busy) || liveStatus().some((l) => l.viewers > 0) || fallbackViewers() > 0,
213
+ exit: (code) => process.exit(code),
214
+ intervalMs: Number(process.env.SIMCAST_UPGRADE_CHECK_MS) || undefined,
215
+ });
216
+ // Runs until a signal; resolves only if the server closes on its own.
217
+ return new Promise((resolve) => server.once('close', () => resolve(0)));
218
+ }
219
+
220
+ // ---- talking to the running agent ---------------------------------------------
221
+
222
+ // A call to the running agent's Mac-local admin API (agent.json adminToken):
223
+ // { status, body }, or null when nothing answered.
224
+ function adminCall(port, method, pathname, json) {
225
+ const { adminToken } = readAgentConfigSafe();
226
+ if (!adminToken) return Promise.resolve(null);
227
+ return new Promise((resolve) => {
228
+ const req = http.request({
229
+ host: '127.0.0.1', port, method, path: pathname, timeout: 5000,
230
+ headers: { authorization: `Bearer ${adminToken}`, ...(json !== undefined ? { 'content-type': 'application/json' } : {}) },
231
+ }, (res) => {
232
+ const chunks = [];
233
+ res.on('data', (c) => chunks.push(c));
234
+ res.on('end', () => {
235
+ let body = {};
236
+ try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { /* not JSON */ }
237
+ resolve({ status: res.statusCode, body });
238
+ });
239
+ res.on('error', () => resolve(null));
240
+ });
241
+ req.on('timeout', () => req.destroy());
242
+ req.on('error', () => resolve(null));
243
+ req.end(json !== undefined ? JSON.stringify(json) : undefined);
244
+ });
245
+ }
246
+
247
+ // The paired PCs: from the running agent (with `connected` and the tunnel), or
248
+ // from clients.json when no agent runs. { pcs, live }.
249
+ async function pcsNow(port) {
250
+ const health = await runningAgent(port);
251
+ if (health) {
252
+ const r = await adminCall(port, 'GET', '/admin/pcs');
253
+ if (r?.status === 200 && Array.isArray(r.body.pcs)) return { pcs: r.body.pcs, live: true, health };
254
+ }
255
+ const { readDb, publicRecord } = await import('./clients.js');
256
+ const { db } = readDb();
257
+ const pcs = db.pcs.map((pc) => publicRecord(pc, { active: pc.id === db.active, connected: false, tunnel: null }));
258
+ return { pcs, live: false, health };
259
+ }
260
+
261
+ // Removes PCs from clients.json directly (no agent running; it loads the file at start).
262
+ async function unpairOffline(ids) {
263
+ const { readDb, writeDb } = await import('./clients.js');
264
+ const { db } = readDb();
265
+ db.pcs = db.pcs.filter((pc) => !ids.includes(pc.id));
266
+ if (ids.includes(db.active)) db.active = null;
267
+ writeDb(db);
268
+ }
269
+
270
+ const tokenKind = (pc) => (pc.ownToken ? 'own token' : 'no token');
271
+
272
+ const prettyCode = (code) => `${code.slice(0, 3)} ${code.slice(3)}`;
273
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
274
+
275
+ function waitForEnter() {
276
+ return new Promise((resolve) => {
277
+ const rl = readline.createInterface({ input: process.stdin });
278
+ rl.once('line', () => { rl.close(); resolve(true); });
279
+ rl.once('close', () => resolve(false));
280
+ });
281
+ }
282
+
283
+ // Opens a pairing window on the running agent and shows its code. --json
284
+ // prints it and leaves the window open (for scripts); otherwise this waits
285
+ // until a PC pairs, the code expires (Enter for a new one on a terminal; without
286
+ // one it just exits), three wrong codes close it, or Ctrl+C (which closes the
287
+ // window).
288
+ async function pairCmd(args) {
289
+ const { values } = parseArgs({ args, options: { json: { type: 'boolean' }, seconds: { type: 'string' } } });
290
+ let seconds;
291
+ if (values.seconds !== undefined) {
292
+ seconds = Number(values.seconds);
293
+ if (!/^\d+$/.test(values.seconds) || seconds < 10 || seconds > 600) {
294
+ console.error(`--seconds must be a whole number from 10 to 600, not "${values.seconds}".`);
295
+ return USAGE;
296
+ }
297
+ }
298
+ const port = agentPort();
299
+ const health = await runningAgent(port);
300
+ if (!health) {
301
+ if (values.json) printJson({ running: false, port, error: 'The agent is not running.' });
302
+ else {
303
+ console.error(color.yellow(`The agent isn't running (nothing answered on port ${port}).`));
304
+ console.error(`Start it with: ${color.cyan('simcast-host setup')}`);
305
+ console.error(`or, in this terminal: ${color.cyan('simcast-host serve')}`);
306
+ }
307
+ return 2;
308
+ }
309
+ const openWindow = async () => {
310
+ const r = await adminCall(port, 'POST', '/admin/pairing', seconds === undefined ? {} : { seconds });
311
+ if (r?.status !== 200) throw new Error(r?.body?.error || 'The agent didn\'t answer the admin API.');
312
+ return r.body;
313
+ };
314
+ let win;
315
+ try {
316
+ win = await openWindow();
317
+ } catch (err) {
318
+ if (values.json) printJson({ running: true, port, error: err.message });
319
+ else console.error(color.red(`Could not open pairing: ${err.message}`));
320
+ return 1;
321
+ }
322
+ const info = { running: true, code: win.code, expiresAt: win.expiresAt, attemptsLeft: win.attemptsLeft, port, addresses: addresses(), agentId: health.agentId, macName: health.macName };
323
+ if (values.json) {
324
+ printJson(info);
325
+ return 0;
326
+ }
327
+
328
+ const show = (w) => {
329
+ const mins = Math.max(1, Math.round((Date.parse(w.expiresAt) - Date.now()) / 60000));
330
+ console.log(`\nPairing code: ${color.bold(prettyCode(w.code))}`);
331
+ console.log(`On your computer, run ${color.cyan('simcast pair')} and type this code.`);
332
+ console.log(color.dim(` It works once, for ${mins} minute${mins === 1 ? '' : 's'}. Pick ${health.macName || 'this Mac'} if the PC lists several Macs.`));
333
+ console.log(color.dim(` Or, if the PC doesn't find this Mac: simcast pair ${info.addresses[0] || '<mac-ip>'}${port !== DEFAULT_PORT ? ` --port ${port}` : ''}`));
334
+ };
335
+ show(win);
336
+ console.log(color.dim(process.stdin.isTTY
337
+ ? ' Waiting for the PC. Ctrl+C to stop.'
338
+ : ' Waiting for the PC until the code expires.'));
339
+ const stop = () => {
340
+ adminCall(port, 'DELETE', '/admin/pairing').finally(() => {
341
+ console.log('\nPairing cancelled.');
342
+ process.exit(130);
343
+ });
344
+ };
345
+ process.once('SIGINT', stop);
346
+ try {
347
+ for (;;) {
348
+ await sleep(500);
349
+ const r = await adminCall(port, 'GET', '/admin/pairing');
350
+ if (r?.status !== 200) {
351
+ console.error(color.red('✗ The agent stopped answering.'));
352
+ return 1;
353
+ }
354
+ const st = r.body;
355
+ if (st.open) continue;
356
+ if (st.closedBecause === 'paired') {
357
+ console.log(color.green(`✓ Paired with ${st.pairedPC?.name || 'the PC'}.`));
358
+ return 0;
359
+ }
360
+ if (st.closedBecause === 'locked') {
361
+ console.error(color.red('✗ Three wrong codes, so pairing closed. Run simcast-host pair for a new code.'));
362
+ return 1;
363
+ }
364
+ if (st.closedBecause === 'expired' && process.stdin.isTTY) {
365
+ console.log(color.yellow('The code expired.') + ' Press Enter for a new code, or Ctrl+C to stop.');
366
+ if (!await waitForEnter()) return 1;
367
+ win = await openWindow();
368
+ show(win);
369
+ continue;
370
+ }
371
+ if (st.closedBecause === 'expired') {
372
+ console.error(color.yellow('The code expired. Run simcast-host pair for a new one.'));
373
+ return 1;
374
+ }
375
+ console.error('Pairing was cancelled.');
376
+ return 1;
377
+ }
378
+ } finally {
379
+ process.removeListener('SIGINT', stop);
380
+ }
381
+ }
382
+
383
+ // ---- pcs / unpair ----------------------------------------------------------
384
+
385
+ async function pcsCmd(args) {
386
+ const { values } = parseArgs({ args, options: { json: { type: 'boolean' } } });
387
+ const { pcs, live } = await pcsNow(agentPort());
388
+ if (values.json) {
389
+ printJson({ pcs, live });
390
+ return 0;
391
+ }
392
+ if (!pcs.length) {
393
+ console.log(`No PC is paired yet. Run ${color.cyan('simcast-host pair')} on this Mac, then ${color.cyan('simcast pair')} on the PC.`);
394
+ return 0;
395
+ }
396
+ console.log(`Paired PCs (${pcs.length}):`);
397
+ const width = Math.max(...pcs.map((pc) => pc.name.length));
398
+ for (const pc of pcs) {
399
+ const state = live ? (pc.connected ? 'connected' : 'idle') : 'agent not running';
400
+ const seen = pc.lastSeenAt ? `last seen ${pc.lastSeenAt.slice(0, 16).replace('T', ' ')}` : 'never seen';
401
+ console.log(` ${pc.active ? '*' : ' '} ${pc.name.padEnd(width)} ${tokenKind(pc).padEnd(12)} ${state.padEnd(9)} ${seen} id ${pc.id.slice(0, 8)}`);
402
+ }
403
+ console.log(color.dim(' * the active PC: the Mac works with one PC at a time, and switches when the active one is idle.'));
404
+ return 0;
405
+ }
406
+
407
+ async function unpairCmd(args) {
408
+ const { values, positionals } = parseArgs({ args, allowPositionals: true, options: { all: { type: 'boolean' }, json: { type: 'boolean' } } });
409
+ const query = positionals.join(' ').trim();
410
+ if (!values.all === !query) {
411
+ console.error('Usage: simcast-host unpair <name|id-prefix>, or simcast-host unpair --all');
412
+ return USAGE;
413
+ }
414
+ const port = agentPort();
415
+ const { pcs, live } = await pcsNow(port);
416
+ let matches = pcs;
417
+ if (!values.all) {
418
+ matches = pcs.filter((pc) => pc.name.toLowerCase() === query.toLowerCase());
419
+ if (!matches.length) matches = pcs.filter((pc) => pc.id.startsWith(query));
420
+ if (!matches.length) {
421
+ console.error(`No paired PC matches "${query}". simcast-host pcs lists them.`);
422
+ return 1;
423
+ }
424
+ if (matches.length > 1) {
425
+ console.error(`"${query}" matches ${matches.length} PCs: ${matches.map((pc) => `${pc.name} (id ${pc.id.slice(0, 8)})`).join(', ')}. Use more of the id.`);
426
+ return 1;
427
+ }
428
+ }
429
+ if (live) {
430
+ for (const pc of matches) {
431
+ const r = await adminCall(port, 'DELETE', `/admin/pcs/${encodeURIComponent(pc.id)}`);
432
+ if (r?.status !== 200 && r?.status !== 404) {
433
+ console.error(color.red(`Could not unpair ${pc.name}: ${r?.body?.error || 'the agent didn\'t answer'}`));
434
+ return 1;
435
+ }
436
+ }
437
+ } else {
438
+ await unpairOffline(matches.map((pc) => pc.id));
439
+ }
440
+ if (values.json) {
441
+ printJson({ unpaired: matches.map((pc) => ({ id: pc.id, name: pc.name })), live });
442
+ return 0;
443
+ }
444
+ if (!matches.length) console.log('No PC is paired, so there was nothing to unpair.');
445
+ for (const pc of matches) console.log(`Unpaired ${pc.name}. It has to pair again (simcast pair) to use this Mac.`);
446
+ return 0;
447
+ }
448
+
449
+ // ---- status ----------------------------------------------------------------
450
+
451
+ function formatUptime(seconds) {
452
+ if (seconds == null) return null;
453
+ const d = Math.floor(seconds / 86400);
454
+ const h = Math.floor((seconds % 86400) / 3600);
455
+ const m = Math.floor((seconds % 3600) / 60);
456
+ if (d) return `${d}d ${h}h`;
457
+ if (h) return `${h}h ${m}m`;
458
+ return m ? `${m}m` : `${seconds % 60}s`;
459
+ }
460
+
461
+ function describeTunnel(t) {
462
+ if (!t) return 'unknown';
463
+ if (!t.connected) return 'not connected';
464
+ const ports = (t.ports || []).map((p) => (p.listening ? String(p.port) : `${p.port} (${p.error || 'not listening'})`));
465
+ return ports.length ? `up, ports ${ports.join(', ')}` : 'up, no ports';
466
+ }
467
+
468
+ function describeBonjour(b) {
469
+ if (!b || typeof b !== 'object') return 'unknown';
470
+ return b.name ? `${b.state} as "${b.name}"` : String(b.state);
471
+ }
472
+
473
+ async function statusCmd(args) {
474
+ const { values } = parseArgs({ args, options: { json: { type: 'boolean' } } });
475
+ const raw = readStatus();
476
+ const alive = raw && pidAlive(raw.pid) ? raw : null; // a crashed agent leaves its file behind
477
+ const port = agentPort(raw);
478
+ const { pcs, live, health } = await pcsNow(port);
479
+ const running = isAgentHealth(health);
480
+ const startedAt = alive?.startedAt || null;
481
+ const uptimeSeconds = running && startedAt ? Math.max(0, Math.round((Date.now() - Date.parse(startedAt)) / 1000)) : null;
482
+ // W7's live fields (connected, busy, awake) are passed through as written.
483
+ const s = running ? alive || {} : {};
484
+ const active = pcs.find((pc) => pc.active) || null;
485
+ const out = {
486
+ running,
487
+ version: { running: health?.version || null, installed: VERSION },
488
+ port,
489
+ pid: running ? alive?.pid ?? null : null,
490
+ startedAt: running ? startedAt : null,
491
+ uptimeSeconds,
492
+ manager: running ? alive?.manager || 'unknown' : 'none',
493
+ logFile: alive?.logFile || LOG_FILE,
494
+ pairedPC: active,
495
+ pcs: pcs.length,
496
+ connected: s.connected ?? null,
497
+ busy: s.busy ?? null,
498
+ awake: s.awake ?? null,
499
+ bonjour: s.bonjour ?? null,
500
+ tunnel: live && active ? active.tunnel ?? null : null,
501
+ health: running,
502
+ };
503
+ if (values.json) {
504
+ printJson(out);
505
+ return running ? 0 : 3;
506
+ }
507
+
508
+ if (!running) {
509
+ console.log(color.yellow(`The agent is not running (nothing answered on port ${port}).`));
510
+ console.log(`Start it with: ${color.cyan('simcast-host setup')}, or ${color.cyan('simcast-host serve')}`);
511
+ } else {
512
+ console.log(color.green(`The agent is running on port ${port}.`));
513
+ }
514
+ const rows = [
515
+ ['Version', running && out.version.running !== VERSION ? `${out.version.running} running, ${VERSION} installed (restart the agent to update)` : VERSION],
516
+ running && ['Pid', out.pid ?? 'unknown'],
517
+ running && ['Uptime', formatUptime(uptimeSeconds) ?? 'unknown'],
518
+ running && ['Started by', out.manager],
519
+ ['Log', out.logFile],
520
+ ['Active PC', active ? `${active.name}${live && active.connected ? ' (connected)' : ''}` : 'none (run simcast-host pair)'],
521
+ ['Paired PCs', `${pcs.length} (simcast-host pcs)`],
522
+ running && out.connected != null && ['Connected now', describe(out.connected)],
523
+ running && out.busy != null && ['Busy', describe(out.busy, 'no')],
524
+ running && out.awake != null && ['Keep-awake', describeAwake(out.awake)],
525
+ running && ['Bonjour', describeBonjour(out.bonjour)],
526
+ running && live && active && ['Tunnel', describeTunnel(out.tunnel)],
527
+ ].filter(Boolean);
528
+ for (const [k, v] of rows) console.log(` ${`${k}:`.padEnd(15)}${v}`);
529
+ return running ? 0 : 3;
530
+ }
531
+
532
+ function describe(v, none = 'no') {
533
+ if (v === true) return 'yes';
534
+ if (v === false || v === null || v === '') return none;
535
+ if (typeof v === 'object') return v.name || v.label || v.reason || JSON.stringify(v);
536
+ return String(v);
537
+ }
538
+
539
+ function describeAwake(a) {
540
+ if (typeof a !== 'object' || a === null) return describe(a);
541
+ if (!a.held) return 'off';
542
+ const reasons = Array.isArray(a.reasons) && a.reasons.length ? ` (${a.reasons.join(', ')})` : '';
543
+ return `on${reasons}`;
544
+ }
545
+
546
+ // ---- logs ------------------------------------------------------------------
547
+
548
+ async function logsCmd(args) {
549
+ const { values } = parseArgs({
550
+ args,
551
+ options: { follow: { type: 'boolean', short: 'f' }, lines: { type: 'string', short: 'n' }, json: { type: 'boolean' } },
552
+ });
553
+ const n = values.lines === undefined ? 50 : Number(values.lines);
554
+ if (!Number.isInteger(n) || n < 0) {
555
+ console.error(`-n must be a whole number, not "${values.lines}".`);
556
+ return USAGE;
557
+ }
558
+ let offset = 0;
559
+ if (fs.existsSync(LOG_FILE)) {
560
+ const fd = fs.openSync(LOG_FILE, 'r');
561
+ try {
562
+ offset = fs.fstatSync(fd).size;
563
+ process.stdout.write(tailLines(fd, offset, n));
564
+ } finally {
565
+ fs.closeSync(fd);
566
+ }
567
+ } else if (!values.follow) {
568
+ console.error(`No log yet at ${LOG_FILE}. The agent writes it when its LaunchAgent runs it (simcast-host setup).`);
569
+ return 1;
570
+ }
571
+ if (!values.follow) return 0;
572
+
573
+ // Poll the size rather than fs.watch: it survives the file being created,
574
+ // truncated or rotated. Only the new bytes are read.
575
+ return new Promise(() => {
576
+ setInterval(() => {
577
+ let size;
578
+ try {
579
+ size = fs.statSync(LOG_FILE).size;
580
+ } catch {
581
+ return; // not there yet
582
+ }
583
+ if (size < offset) offset = 0; // truncated (rotated): start over
584
+ if (size === offset) return;
585
+ const fd = fs.openSync(LOG_FILE, 'r');
586
+ try {
587
+ while (offset < size) {
588
+ const buf = Buffer.alloc(Math.min(size - offset, LOG_CHUNK));
589
+ const read = fs.readSync(fd, buf, 0, buf.length, offset);
590
+ if (!read) break;
591
+ offset += read;
592
+ process.stdout.write(buf.subarray(0, read));
593
+ }
594
+ } finally {
595
+ fs.closeSync(fd);
596
+ }
597
+ }, 500);
598
+ });
599
+ }
600
+
601
+ const LOG_CHUNK = 64 * 1024;
602
+
603
+ // The last n lines of an open file of `size` bytes, read back from the end in
604
+ // growing chunks, so a big log isn't read whole.
605
+ function tailLines(fd, size, n) {
606
+ if (n === 0 || size === 0) return '';
607
+ for (let chunk = LOG_CHUNK; ; chunk *= 4) {
608
+ const start = Math.max(0, size - chunk);
609
+ const buf = Buffer.alloc(size - start);
610
+ fs.readSync(fd, buf, 0, buf.length, start);
611
+ const lines = buf.toString('utf8').split('\n');
612
+ if (lines.at(-1) === '') lines.pop();
613
+ // Unless the chunk starts the file, its first line may be cut off: it only
614
+ // counts once there are more than n lines.
615
+ if (start === 0 || lines.length > n) return lines.length ? `${lines.slice(-n).join('\n')}\n` : '';
616
+ }
617
+ }