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,577 @@
1
+ import fs from 'node:fs';
2
+ import http from 'node:http';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import readline from 'node:readline';
6
+ import * as tar from 'tar';
7
+ import { WebSocketServer } from 'ws';
8
+ import { MIN_CLIENT_PROTOCOL, PROTOCOL, PROTOCOL_HEADER, VERSION, color, heartbeat, isSafeRelPath, isValidProjectId, negotiateProtocol, sha1File } from '../common.js';
9
+ import * as admin from './admin.js';
10
+ import * as awake from './awake.js';
11
+ import * as bonjour from './bonjour.js';
12
+ import * as build from './build.js';
13
+ import { publicResult, runChecks } from './checks.js';
14
+ import * as clients from './clients.js';
15
+ import { HttpError } from './clients.js';
16
+ import { spawnTool } from './exec.js';
17
+ import * as live from './live.js';
18
+ import { developerDir as findDeveloperDir, freeDiskGB, macosVersion, probe, wakeInfo, xcodeVersion } from './macinfo.js';
19
+ import * as pairing from './pairing.js';
20
+ import { pickRecipe } from './recipes/index.js';
21
+ import * as kit from './recipes/kit.js';
22
+ import * as record from './record.js';
23
+ import { agentHealth, isAgentHealth, writeStatus } from './runtime.js';
24
+ import * as screen from './screen.js';
25
+ import * as sim from './sim.js';
26
+ import { watchStalls } from './stalls.js';
27
+ import * as tunnel from './tunnel.js';
28
+ import { agentHome, loadAgentConfig, loadState, macName, macNameNow, projectPaths, saveState } from './state.js';
29
+
30
+ let busy = null; // one sync or build at a time; the Mac mini has enough to do
31
+ let runStep = null; // the run's current step, for the stall log
32
+
33
+ function sendJson(res, status, body) {
34
+ res.writeHead(status, { 'content-type': 'application/json' });
35
+ res.end(JSON.stringify(body));
36
+ }
37
+
38
+ async function readJson(req, limit = 64 * 1024 * 1024) {
39
+ const chunks = [];
40
+ let size = 0;
41
+ for await (const chunk of req) {
42
+ size += chunk.length;
43
+ if (size > limit) throw new HttpError(413, 'Request body too large');
44
+ chunks.push(chunk);
45
+ }
46
+ try {
47
+ return JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
48
+ } catch {
49
+ throw new HttpError(400, 'Invalid JSON body');
50
+ }
51
+ }
52
+
53
+ function requireProject(id) {
54
+ if (!isValidProjectId(id)) throw new HttpError(400, 'Invalid project id');
55
+ return projectPaths(id);
56
+ }
57
+
58
+ // Marks the Mac busy and keeps it awake until the returned release() is called
59
+ // (calling it again does nothing).
60
+ function claim(label) {
61
+ if (busy) throw new HttpError(409, `The Mac is busy (${busy}). Try again when it finishes.`);
62
+ busy = label;
63
+ writeStatus({ busy }, { now: true }); // not debounced: `clean` checks it before deleting builds
64
+ const unhold = awake.hold(label);
65
+ let released = false;
66
+ return () => {
67
+ if (released) return;
68
+ released = true;
69
+ busy = null;
70
+ writeStatus({ busy });
71
+ unhold();
72
+ };
73
+ }
74
+
75
+ // GET /info. `req` and `client` give the M3 fields that depend on the caller.
76
+ async function info(req, client, cfg) {
77
+ const developerDir = await findDeveloperDir();
78
+ const local = String(req.socket.localAddress || '').replace(/^::ffff:/, '');
79
+ let wake = null;
80
+ try { wake = (await wakeInfo(local)) || null; } catch { /* unknown interface */ }
81
+ return {
82
+ version: VERSION,
83
+ macos: await macosVersion(),
84
+ xcode: await xcodeVersion(),
85
+ developerDir,
86
+ deviceHub: developerDir ? fs.existsSync(path.join(developerDir, '..', 'Applications', 'DeviceHub.app')) : false,
87
+ cocoapods: (await probe('pod', ['--version']))?.split('\n').pop() || null,
88
+ idbCompanion: (await live.findCompanion()) || null,
89
+ hostApp: await live.hostAppRunning(),
90
+ live: live.liveStatus(),
91
+ pairedWith: clients.pairedClient()?.name || null,
92
+ node: process.version,
93
+ arch: process.arch,
94
+ memoryGB: Math.round(os.totalmem() / 1e9),
95
+ freeMemoryGB: Number((os.freemem() / 1e9).toFixed(1)),
96
+ freeDiskGB: await freeDiskGB(),
97
+ awake: awake.awakeStatus(),
98
+ agentId: cfg.agentId,
99
+ macName: macNameNow(),
100
+ pcs: clients.list().length,
101
+ wake,
102
+ tunnel: tunnel.portsFor(client.id),
103
+ bonjour: bonjour.status(),
104
+ };
105
+ }
106
+
107
+ // ---- sync ----------------------------------------------------------------
108
+
109
+ async function syncManifest(body) {
110
+ const { project, files } = body;
111
+ const p = requireProject(project);
112
+ if (!files || typeof files !== 'object') throw new HttpError(400, 'Missing files');
113
+ const release = claim('sync');
114
+ try {
115
+ fs.mkdirSync(p.src, { recursive: true });
116
+ const state = loadState(project);
117
+ const need = [];
118
+ for (const [rel, hash] of Object.entries(files)) {
119
+ if (!isSafeRelPath(rel)) throw new HttpError(400, `Unsafe path: ${rel}`);
120
+ const prev = state.manifest[rel];
121
+ if (!prev || prev.sha1 !== hash) {
122
+ need.push(rel);
123
+ continue;
124
+ }
125
+ // Re-send if something on the Mac (like prebuild) touched the file.
126
+ try {
127
+ const st = fs.statSync(path.join(p.src, rel));
128
+ if (st.mtimeMs !== prev.mtimeMs || st.size !== prev.size) need.push(rel);
129
+ } catch {
130
+ need.push(rel);
131
+ }
132
+ }
133
+ let deleted = 0;
134
+ for (const rel of Object.keys(state.manifest)) {
135
+ if (rel in files) continue;
136
+ fs.rmSync(path.join(p.src, rel), { force: true });
137
+ delete state.manifest[rel];
138
+ deleted++;
139
+ }
140
+ state.pending = need;
141
+ saveState(project, state);
142
+ return { need, deleted };
143
+ } finally {
144
+ release();
145
+ }
146
+ }
147
+
148
+ async function syncUpload(req, project) {
149
+ const p = requireProject(project);
150
+ const release = claim('sync');
151
+ try {
152
+ fs.mkdirSync(p.src, { recursive: true });
153
+ await new Promise((resolve, reject) => {
154
+ const extract = tar.x({ cwd: p.src, strict: true });
155
+ extract.on('error', reject);
156
+ extract.on('close', resolve);
157
+ req.on('error', reject);
158
+ req.pipe(extract);
159
+ });
160
+ const state = loadState(project);
161
+ for (const rel of state.pending || []) {
162
+ const abs = path.join(p.src, rel);
163
+ if (!fs.existsSync(abs)) continue;
164
+ const st = fs.statSync(abs);
165
+ state.manifest[rel] = { sha1: await sha1File(abs), mtimeMs: st.mtimeMs, size: st.size };
166
+ }
167
+ const count = (state.pending || []).length;
168
+ state.pending = [];
169
+ saveState(project, state);
170
+ return { ok: true, files: count };
171
+ } finally {
172
+ release();
173
+ }
174
+ }
175
+
176
+ // ---- run -----------------------------------------------------------------
177
+
178
+ async function runIos(req, res, body) {
179
+ const { project, device, rebuild = false, clean = false, cng = true, showUI = false, devServerUrl } = body;
180
+ const p = requireProject(project);
181
+ if (!fs.existsSync(p.src)) throw new HttpError(400, 'Project has not been synced yet');
182
+ let recipe;
183
+ try {
184
+ recipe = pickRecipe(p.src, body.recipe);
185
+ } catch (err) {
186
+ throw new HttpError(400, err.message);
187
+ }
188
+ const release = claim('build');
189
+ try {
190
+ await runClaimed(res, { project, device, rebuild, clean, cng, showUI, devServerUrl, p, recipe });
191
+ } finally {
192
+ release();
193
+ }
194
+ }
195
+
196
+ // The run itself, while claim('build') is held.
197
+ async function runClaimed(res, { project, device, rebuild, clean, cng, showUI, devServerUrl, p, recipe }) {
198
+ res.writeHead(200, { 'content-type': 'application/x-ndjson', 'cache-control': 'no-cache' });
199
+ const emit = (event) => {
200
+ if (!res.destroyed) res.write(`${JSON.stringify(event)}\n`);
201
+ };
202
+ fs.mkdirSync(p.logs, { recursive: true });
203
+ const logFile = path.join(p.logs, `run-${new Date().toISOString().replace(/[:.]/g, '-')}.log`);
204
+ const logStream = fs.createWriteStream(logFile);
205
+ const onLine = (line, stream) => {
206
+ logStream.write(`${line}\n`);
207
+ emit({ t: 'log', line, stream });
208
+ };
209
+ const step = (msg) => {
210
+ runStep = msg;
211
+ logStream.write(`\n=== ${msg} (${new Date().toISOString()})\n`);
212
+ emit({ t: 'step', msg });
213
+ };
214
+ const started = Date.now();
215
+ const state = loadState(project);
216
+
217
+ const ctx = {
218
+ src: p.src,
219
+ derived: p.derived,
220
+ state,
221
+ options: { cng, clean, devServerUrl },
222
+ sim,
223
+ tunnel: { listening: (port) => tunnel.listening(port) },
224
+ onLine,
225
+ step,
226
+ info: (msg) => emit({ t: 'info', msg }),
227
+ warn: (msg) => emit({ t: 'warn', msg }),
228
+ };
229
+
230
+ try {
231
+ step('Preparing simulator');
232
+ const dev = await sim.resolveDevice(device);
233
+ emit({ t: 'info', msg: `${dev.name} (${dev.runtime})` });
234
+ if (dev.state !== 'Booted') await sim.boot(dev.udid);
235
+ if (showUI) await sim.showUI();
236
+ ctx.info(`${recipe.name} project`);
237
+
238
+ if (recipe.deps) {
239
+ step('Checking JS dependencies');
240
+ const installed = await recipe.deps(ctx);
241
+ saveState(project, state);
242
+ emit({ t: 'info', msg: installed ? 'Dependencies installed' : 'Dependencies unchanged' });
243
+ }
244
+
245
+ step('Fingerprinting native code');
246
+ const fp = await recipe.fingerprint(ctx);
247
+ emit({ t: 'info', msg: `${fp.hash.slice(0, 12)} via ${fp.source}` });
248
+
249
+ let appPath = build.cachedApp(p.builds, fp.hash);
250
+ if (!appPath || rebuild || clean) {
251
+ step('Building native iOS app (the slow part, only when native code changes)');
252
+ const built = await recipe.build(ctx);
253
+ appPath = build.cacheApp(built, p.builds, fp.hash);
254
+ } else {
255
+ emit({ t: 'info', msg: 'Native code unchanged, reusing the cached build' });
256
+ }
257
+
258
+ step('Installing app');
259
+ const meta = await kit.readAppMeta(appPath);
260
+ await sim.terminate(dev.udid, meta.bundleId);
261
+ await sim.install(dev.udid, appPath);
262
+
263
+ step('Launching');
264
+ await recipe.launch(ctx, { udid: dev.udid, appPath, meta });
265
+
266
+ state.lastRun = { udid: dev.udid, bundleId: meta.bundleId, executable: meta.executable, at: Date.now() };
267
+ saveState(project, state);
268
+ emit({ t: 'done', ok: true, ms: Date.now() - started, logFile });
269
+ } catch (err) {
270
+ logStream.write(`\nFAILED: ${err.message}\n`);
271
+ emit({ t: 'done', ok: false, error: err.message, tail: err.tail || [], ms: Date.now() - started, logFile });
272
+ } finally {
273
+ runStep = null;
274
+ logStream.end();
275
+ res.end();
276
+ }
277
+ }
278
+
279
+ // ---- simulator actions ---------------------------------------------------
280
+
281
+ async function simAction(body) {
282
+ const { action, device, value, project } = body;
283
+ const dev = await sim.resolveDevice(device);
284
+ const lastBundle = isValidProjectId(project) ? loadState(project).lastRun?.bundleId : null;
285
+ switch (action) {
286
+ case 'boot': await sim.boot(dev.udid); break;
287
+ case 'shutdown': await sim.shutdown(dev.udid); break;
288
+ case 'erase': await sim.erase(dev.udid); break;
289
+ case 'show': await sim.showUI(); break;
290
+ case 'dark':
291
+ case 'light': await sim.appearance(dev.udid, action); break;
292
+ case 'rotate-left':
293
+ case 'rotate-right': return { ok: true, device: dev, rotation: await live.rotate(dev.udid, action.slice('rotate-'.length)) };
294
+ case 'url':
295
+ if (!value) throw new HttpError(400, 'Missing URL');
296
+ await sim.openUrl(dev.udid, value);
297
+ break;
298
+ case 'location':
299
+ if (value === 'clear') await sim.clearLocation(dev.udid);
300
+ else if (/^-?\d+(\.\d+)?,-?\d+(\.\d+)?$/.test(value || '')) await sim.setLocation(dev.udid, value);
301
+ else throw new HttpError(400, 'Location must be "lat,lon" or "clear"');
302
+ break;
303
+ case 'push': {
304
+ const bundleId = body.bundleId || lastBundle;
305
+ if (!bundleId) throw new HttpError(400, 'No bundle id. Run the app once first, or pass --bundle.');
306
+ await sim.push(dev.udid, bundleId, value || { aps: { alert: 'Hello from simcast' } });
307
+ break;
308
+ }
309
+ default: throw new HttpError(400, `Unknown action "${action}"`);
310
+ }
311
+ return { ok: true, device: dev };
312
+ }
313
+
314
+ // What `log stream` prints before the app's own lines: simctl spawn's
315
+ // "getpwuid_r did not find a match for uid 501" and the "Filtering the log
316
+ // data using ..." header.
317
+ export const logNoise = (line) => /^getpwuid_r did not find a match for uid \d+/.test(line) || /^Filtering the log data using /.test(line);
318
+
319
+ async function streamLogs(req, res, query) {
320
+ const project = query.get('project');
321
+ const state = isValidProjectId(project) ? loadState(project) : {};
322
+ const udid = query.get('device') ? (await sim.resolveDevice(query.get('device'))).udid : state.lastRun?.udid;
323
+ if (!udid) throw new HttpError(400, 'No device. Run the app once first, or pass --device.');
324
+ const args = ['simctl', 'spawn', udid, 'log', 'stream', '--style', 'compact'];
325
+ if (!query.get('all') && state.lastRun?.executable) args.push('--predicate', `process == "${state.lastRun.executable.replace(/"/g, '')}"`);
326
+ res.writeHead(200, { 'content-type': 'text/plain; charset=utf-8' });
327
+ const child = spawnTool('xcrun', args);
328
+ for (const stream of [child.stdout, child.stderr]) {
329
+ readline.createInterface({ input: stream }).on('line', (line) => {
330
+ if (!logNoise(line) && !res.destroyed) res.write(`${line}\n`);
331
+ });
332
+ }
333
+ child.on('error', () => res.end());
334
+ child.on('close', () => res.end());
335
+ req.on('close', () => child.kill());
336
+ }
337
+
338
+ // ---- live screen ---------------------------------------------------------
339
+
340
+ async function streamScreen(req, res, query) {
341
+ const dev = await sim.resolveDevice(query.get('device'));
342
+ if (dev.state !== 'Booted') await sim.boot(dev.udid);
343
+ const fps = Math.min(30, Math.max(1, Number(query.get('fps')) || 30));
344
+ const boundary = 'simcastframe';
345
+ res.writeHead(200, {
346
+ 'content-type': `multipart/x-mixed-replace; boundary=${boundary}`,
347
+ 'cache-control': 'no-cache, no-store',
348
+ connection: 'keep-alive',
349
+ 'x-device-udid': dev.udid,
350
+ });
351
+ req.socket.setNoDelay(true);
352
+ let waiting = false; // drop frames for slow viewers instead of lagging
353
+ let pending = null;
354
+ const write = (frame) => {
355
+ if (res.destroyed) return;
356
+ if (waiting) { pending = frame; return; }
357
+ res.write(`--${boundary}\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`);
358
+ const ok = res.write(frame);
359
+ res.write('\r\n');
360
+ if (!ok) {
361
+ waiting = true;
362
+ res.once('drain', () => {
363
+ waiting = false;
364
+ if (pending) { const f = pending; pending = null; write(f); }
365
+ });
366
+ }
367
+ };
368
+ console.log(`[${new Date().toISOString()}] viewer connected to ${dev.name} (${dev.udid})`);
369
+ const unsubscribe = await screen.subscribe(dev.udid, fps, write);
370
+ res.on('close', () => {
371
+ console.log(`[${new Date().toISOString()}] viewer left ${dev.name}`);
372
+ unsubscribe();
373
+ });
374
+ // Send headers right away so the window knows the Mac answered.
375
+ res.flushHeaders();
376
+ }
377
+
378
+ async function screenStatus(query) {
379
+ const dev = await sim.resolveDevice(query.get('device'));
380
+ let points = null;
381
+ try { points = screen.screenPoints(dev.udid); } catch { /* no frame yet */ }
382
+ return { device: dev, points, stream: screen.hubInfo(dev.udid) };
383
+ }
384
+
385
+ // ---- server --------------------------------------------------------------
386
+
387
+ // The protocol this request's client and the agent agree on (plan 2.1).
388
+ const protocolOf = (req) => negotiateProtocol(req.headers[PROTOCOL_HEADER]);
389
+
390
+ export function startAgent({ port } = {}) {
391
+ const cfg = loadAgentConfig();
392
+ clients.startServing();
393
+ macName(); // asked once at start, so /health soon has it
394
+ const listenPort = Number(port || process.env.SIMCAST_PORT || cfg.port);
395
+
396
+ const server = http.createServer(async (req, res) => {
397
+ const url = new URL(req.url, 'http://agent');
398
+ const route = `${req.method} ${url.pathname}`;
399
+ try {
400
+ // The order of checks: docs/protocol.md, "Order of checks".
401
+ // 1. /health: no checks.
402
+ if (route === 'GET /health') {
403
+ return sendJson(res, 200, {
404
+ ok: true, name: 'simcast-host', version: VERSION, protocol: protocolOf(req),
405
+ protocolMin: MIN_CLIENT_PROTOCOL, protocolMax: PROTOCOL, agentId: cfg.agentId, macName: macNameNow(),
406
+ pairing: pairing.status().open, platform: process.platform, features: ['doctor'],
407
+ });
408
+ }
409
+ // 2. The Mac-local admin API (loopback and the admin token).
410
+ if (url.pathname === '/admin' || url.pathname.startsWith('/admin/')) {
411
+ return await admin.handle(req, res, { url, adminToken: cfg.adminToken });
412
+ }
413
+ // 3. Pairing with a code: no bearer token, a valid client id.
414
+ if (route === 'POST /pair/code') {
415
+ const client = clients.clientOf(req);
416
+ if (!client) throw new HttpError(400, 'This PC runs an older simcast. Update simcast on this PC and run "simcast pair" again.');
417
+ const body = await readJson(req, 64 * 1024);
418
+ const paired = pairing.tryCode(client, body.code, body.force === true);
419
+ return sendJson(res, 200, {
420
+ ok: true, token: paired.token, agentId: cfg.agentId, macName: macNameNow(),
421
+ previous: paired.previous, active: true,
422
+ });
423
+ }
424
+ // 4-6. The bearer token and the client id.
425
+ const { client, via } = clients.authenticate(req);
426
+ // 7. The pairing routes.
427
+ if (route === 'POST /pair') {
428
+ const body = await readJson(req, 64 * 1024);
429
+ return sendJson(res, 200, { ok: true, ...clients.claim(client, { force: body.force === true }) });
430
+ }
431
+ if (route === 'DELETE /pair') {
432
+ clients.unpair(client.id, 'unpaired itself');
433
+ return sendJson(res, 200, { ok: true });
434
+ }
435
+ if (route === 'POST /token/rotate') {
436
+ const { token, issuedAt } = clients.rotate(client);
437
+ return sendJson(res, 200, { token, agentId: cfg.agentId, macName: macNameNow(), issuedAt });
438
+ }
439
+ // 8. Admission: the active PC, or a switch to this one.
440
+ clients.admit(client);
441
+ // 9. The route; the socket is remembered so it can be cut.
442
+ clients.track(req.socket, client.id, via);
443
+
444
+ switch (route) {
445
+ case 'GET /info': return sendJson(res, 200, await info(req, client, cfg));
446
+ case 'GET /doctor': return sendJson(res, 200, { checks: (await runChecks({ scope: 'doctor' })).map(publicResult) });
447
+ case 'GET /devices': return sendJson(res, 200, { devices: await sim.listDevices({ all: url.searchParams.has('all') }) });
448
+ case 'GET /probe': {
449
+ const target = url.searchParams.get('url') || '';
450
+ if (!/^https?:\/\//.test(target)) throw new HttpError(400, 'Only http(s) URLs can be probed');
451
+ return sendJson(res, 200, await kit.probe(target));
452
+ }
453
+ case 'POST /sync/manifest': return sendJson(res, 200, await syncManifest(await readJson(req)));
454
+ case 'POST /sync/upload': return sendJson(res, 200, await syncUpload(req, url.searchParams.get('project')));
455
+ case 'POST /run': return await runIos(req, res, await readJson(req));
456
+ case 'POST /sim': return sendJson(res, 200, await simAction(await readJson(req)));
457
+ case 'GET /screenshot': {
458
+ const dev = await sim.resolveDevice(url.searchParams.get('device'));
459
+ const png = await sim.screenshot(dev.udid);
460
+ res.writeHead(200, { 'content-type': 'image/png' });
461
+ return res.end(png);
462
+ }
463
+ case 'GET /pasteboard': {
464
+ const dev = await sim.resolveDevice(url.searchParams.get('device'));
465
+ return sendJson(res, 200, { text: await sim.pasteboard(dev.udid) });
466
+ }
467
+ case 'POST /pasteboard': {
468
+ const body = await readJson(req, 1024 * 1024);
469
+ if (typeof body.text !== 'string') throw new HttpError(400, 'Missing text');
470
+ const dev = await sim.resolveDevice(body.device);
471
+ await sim.setPasteboard(dev.udid, body.text);
472
+ return sendJson(res, 200, { ok: true });
473
+ }
474
+ case 'POST /record': {
475
+ const body = await readJson(req);
476
+ const dev = await sim.resolveDevice(body.device);
477
+ if (body.action === 'start') {
478
+ await record.startRecording(dev.udid);
479
+ return sendJson(res, 200, { ok: true });
480
+ }
481
+ if (body.action !== 'stop') throw new HttpError(400, 'action must be "start" or "stop"');
482
+ const mp4 = await record.stopRecording(dev.udid);
483
+ res.writeHead(200, { 'content-type': 'video/mp4' });
484
+ return res.end(mp4);
485
+ }
486
+ case 'GET /logs': return await streamLogs(req, res, url.searchParams);
487
+ case 'GET /stream': return await streamScreen(req, res, url.searchParams);
488
+ case 'GET /screen': return sendJson(res, 200, await screenStatus(url.searchParams));
489
+ case 'GET /tunnel/ports': return sendJson(res, 200, tunnel.portsFor(client.id));
490
+ case 'POST /input': {
491
+ const ev = await readJson(req, 64 * 1024);
492
+ try { screen.checkInput(ev); } catch (err) { throw new HttpError(400, err.message); }
493
+ const dev = await sim.resolveDevice(ev.device);
494
+ await screen.sendInput(dev.udid, ev);
495
+ return sendJson(res, 200, { ok: true });
496
+ }
497
+ default: return sendJson(res, 404, { error: `No route ${route}` });
498
+ }
499
+ } catch (err) {
500
+ if (res.headersSent) return res.end();
501
+ sendJson(res, err.status || 500, { error: err.message, ...(err.body || {}), tail: err.tail });
502
+ }
503
+ });
504
+
505
+ server.requestTimeout = 0; // builds can take a long time
506
+ for (const sig of ['SIGTERM', 'SIGINT', 'SIGHUP']) {
507
+ process.on(sig, () => {
508
+ clients.stopAll();
509
+ tunnel.stopAll();
510
+ bonjour.stop();
511
+ screen.stopAll();
512
+ live.stopAllCompanions();
513
+ process.exit(0);
514
+ });
515
+ }
516
+
517
+ // WebSockets: /session is the PC's control connection (heartbeats, so either side
518
+ // notices a lost connection within seconds); /live carries H.264 frames out and input in;
519
+ // /tunnel is the PC's tunnel control connection. /tunnel/data is a raw TCP
520
+ // stream (Upgrade: simcast-tcp) and never goes through the WebSocket server.
521
+ const wss = new WebSocketServer({ noServer: true, perMessageDeflate: false, maxPayload: 1024 * 1024 });
522
+ server.on('upgrade', (req, socket, head) => {
523
+ const url = new URL(req.url, 'http://agent');
524
+ const refuse = (status, msg) => {
525
+ socket.write(`HTTP/1.1 ${status}\r\nx-simcast-error: ${encodeURIComponent(msg)}\r\nConnection: close\r\n\r\n`);
526
+ socket.destroy();
527
+ };
528
+ if (!['/live', '/session', '/tunnel', '/tunnel/data'].includes(url.pathname)) return refuse('404 Not Found', `No route ${url.pathname}`);
529
+ // The same checks as for requests (steps 4-8), refused as bare responses.
530
+ let client;
531
+ let via;
532
+ try {
533
+ ({ client, via } = clients.authenticate(req));
534
+ clients.admit(client);
535
+ } catch (err) {
536
+ const status = err.status || 500;
537
+ return refuse(`${status} ${http.STATUS_CODES[status] || 'Error'}`, err.message);
538
+ }
539
+ clients.track(socket, client.id, via);
540
+ socket.setNoDelay(true);
541
+ if (url.pathname === '/tunnel/data') return tunnel.handleData(req, socket, head, client);
542
+ const protocol = protocolOf(req);
543
+ wss.handleUpgrade(req, socket, head, (ws) => {
544
+ if (url.pathname === '/session') return clients.addSession(ws, client, { protocol, via });
545
+ if (url.pathname === '/tunnel') return tunnel.attachControl(ws, client, { protocol });
546
+ heartbeat(ws); // a silent drop closes the viewer, which lifts a finger still held down
547
+ live.attachViewer(ws, { device: url.searchParams.get('device'), quality: url.searchParams.get('quality') })
548
+ .catch((err) => { try { ws.close(1011, err.message.slice(0, 120)); } catch { /* ignore */ } });
549
+ });
550
+ });
551
+ server.on('error', async (err) => {
552
+ if (err.code !== 'EADDRINUSE') {
553
+ console.error(color.red(`The agent could not listen on port ${listenPort}: ${err.message}`));
554
+ process.exit(1);
555
+ }
556
+ // Only one agent at a time: a second one (the LaunchAgent plus a manual
557
+ // `serve`, say) leaves quietly; anything else on the port is an error.
558
+ if (isAgentHealth(await agentHealth(listenPort, 2000))) {
559
+ console.log(`Another simcast-host is already running on port ${listenPort}.`);
560
+ console.log(' Use the running one, or stop it first: simcast-host uninstall. If another program uses the port, give the host another with --port.');
561
+ process.exit(0);
562
+ }
563
+ console.error(color.red(`Port ${listenPort} is used by another program. Stop it, or start the agent with --port.`));
564
+ process.exit(1);
565
+ });
566
+ server.listen(listenPort, '0.0.0.0', () => {
567
+ const boundPort = server.address().port; // differs from listenPort when 0 was asked for
568
+ console.log(color.bold(`simcast agent ${VERSION} listening on port ${boundPort}`));
569
+ console.log(`Data folder: ${agentHome}`);
570
+ if (process.platform !== 'darwin') console.log(color.yellow('Warning: not running on macOS, so builds and simulators will fail.'));
571
+ console.log(`\nPair a PC: run ${color.cyan('simcast-host pair')} on this Mac, then ${color.cyan('simcast pair')} on the PC.`);
572
+ macName().then((name) => bonjour.start({ port: boundPort, agentId: cfg.agentId, macName: name }));
573
+ });
574
+ const stopWatching = watchStalls({ during: () => (runStep ? `run step "${runStep}"` : '') });
575
+ server.on('close', stopWatching);
576
+ return server;
577
+ }