simcast-host 0.0.0-stage → 0.9.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.
@@ -0,0 +1,283 @@
1
+ // `simcast-host setup` (check, then fix what it can) and `doctor` (check only).
2
+ // The checks themselves live in checks.js.
3
+ import readline from 'node:readline';
4
+ import { parseArgs } from 'node:util';
5
+ import { VERSION, color } from '../common.js';
6
+ import { CHECKS, checkById, newContext, publicResult, runCheck, runChecks, selectChecks, unknownIds } from './checks.js';
7
+ import { runInteractive } from './exec.js';
8
+ import { uid } from './paths.js';
9
+
10
+ const USAGE = 'Usage: simcast-host setup [--check] [--yes] [--download] [--only ids] [--skip ids] [--json]';
11
+ const DOCTOR_USAGE = 'Usage: simcast-host doctor [--json]';
12
+ const ROOT_REFUSAL = "Don't run setup with sudo; it asks when it needs to.";
13
+
14
+ const SYMBOL = {
15
+ ok: () => color.green('✓'),
16
+ warn: () => color.yellow('!'),
17
+ fail: () => color.red('✗'),
18
+ skipped: () => color.dim('-'),
19
+ };
20
+
21
+ const quote = (s) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${String(s).replace(/'/g, "'\\''")}'`);
22
+ const commandText = (cmd, sudo) => (cmd.text ?? `${sudo ? 'sudo ' : ''}${cmd.map(quote).join(' ')}`);
23
+
24
+ function usage(msg, text = USAGE) {
25
+ console.error(color.red(`✗ ${msg}`));
26
+ console.error(text);
27
+ return 64;
28
+ }
29
+
30
+ function parse(args, options, text) {
31
+ try {
32
+ return { values: parseArgs({ args, options, strict: true, allowPositionals: false }).values };
33
+ } catch (err) {
34
+ return { error: usage(err.message, text) };
35
+ }
36
+ }
37
+
38
+ const isInteractive = () => process.env.SIMCAST_ASSUME_TTY === '1' || Boolean(process.stdin.isTTY && process.stdout.isTTY);
39
+
40
+ // ---- output ---------------------------------------------------------------------
41
+
42
+ // hints: also show a fix's commands under the line (doctor, which runs none).
43
+ function printResult(r, width, { hints = false } = {}) {
44
+ const detail = r.status === 'ok' ? color.dim(r.detail) : r.detail;
45
+ const pad = ` ${' '.repeat(width)} `;
46
+ console.log(`${SYMBOL[r.status]()} ${r.title.padEnd(width)} ${detail}`);
47
+ if (r.manual) console.log(`${pad}${color.cyan(r.manual)}`);
48
+ else if (hints && r.status !== 'skipped' && r.fix?.commands) {
49
+ console.log(`${pad}${color.cyan(`Fix: ${r.fix.commands.map((c) => commandText(c, r.fix.sudo)).join(' && ')}`)}`);
50
+ }
51
+ }
52
+
53
+ function printResults(results, opts) {
54
+ const width = Math.max(...results.map((r) => r.title.length));
55
+ for (const r of results) printResult(r, width, opts);
56
+ }
57
+
58
+ function fixLine(r) {
59
+ const fix = checkById(r.id).fix;
60
+ const tags = [fix.sudo && 'admin password', fix.slow && 'slow'].filter(Boolean);
61
+ const head = `${fix.what}${tags.length ? color.yellow(` (${tags.join(', ')})`) : ''}`;
62
+ const cmds = r.fix.commands
63
+ ? r.fix.commands.map((c) => commandText(c, fix.sudo)).join(' && ')
64
+ : `worked out once ${r.detail.replace(/^Waiting for: /, '')} is done`;
65
+ return `${head}\n ${color.dim(cmds)}`;
66
+ }
67
+
68
+ function printJson(results) {
69
+ const ok = results.every((r) => r.status === 'ok');
70
+ console.log(JSON.stringify({ version: VERSION, ok, checks: results.map(publicResult) }, null, 2));
71
+ }
72
+
73
+ // ---- prompts --------------------------------------------------------------------
74
+
75
+ // Answers come from stdin one line each, so tests can pipe them in. EOF answers ''.
76
+ function prompter() {
77
+ const lines = [];
78
+ const waiting = [];
79
+ let ended = false;
80
+ const rl = readline.createInterface({ input: process.stdin, terminal: false });
81
+ rl.on('line', (line) => (waiting.length ? waiting.shift()(line) : lines.push(line)));
82
+ rl.on('close', () => {
83
+ ended = true;
84
+ while (waiting.length) waiting.shift()('');
85
+ });
86
+ return {
87
+ async ask(question, defaultYes) {
88
+ process.stdout.write(`${question} ${defaultYes ? '[Y/n]' : '[y/N]'} `);
89
+ const answer = lines.length ? lines.shift() : ended ? '' : await new Promise((resolve) => waiting.push(resolve));
90
+ if (!process.stdin.isTTY) process.stdout.write(`${answer}\n`);
91
+ const a = answer.trim().toLowerCase();
92
+ return a ? a === 'y' || a === 'yes' : defaultYes;
93
+ },
94
+ close() {
95
+ rl.close();
96
+ process.stdin.pause();
97
+ },
98
+ };
99
+ }
100
+
101
+ // ---- setup ----------------------------------------------------------------------
102
+
103
+ export async function setupCmd(args = []) {
104
+ const { values: opts, error } = parse(args, {
105
+ check: { type: 'boolean' },
106
+ yes: { type: 'boolean', short: 'y' },
107
+ download: { type: 'boolean' },
108
+ only: { type: 'string', multiple: true },
109
+ skip: { type: 'string', multiple: true },
110
+ json: { type: 'boolean' },
111
+ });
112
+ if (error) return error;
113
+ if (opts.json && !opts.check) return usage('--json only works with --check (setup asks questions and runs commands otherwise).');
114
+ const unknown = unknownIds(opts.only, opts.skip);
115
+ if (unknown.length) return usage(`Unknown check: ${unknown.join(', ')}. Checks: ${CHECKS.map((c) => c.id).join(', ')}`);
116
+ if (uid() === 0) {
117
+ console.error(color.red(`✗ ${ROOT_REFUSAL}`));
118
+ return 1;
119
+ }
120
+
121
+ const tty = isInteractive();
122
+ const checkOnly = opts.check || (!tty && !opts.yes);
123
+ const ctx = newContext();
124
+ const results = await runChecks({ scope: 'setup', only: opts.only, skip: opts.skip, ctx });
125
+ const pending = (list) => list.filter((r) => r.status !== 'ok');
126
+
127
+ if (opts.json) {
128
+ printJson(results);
129
+ return pending(results).length ? 2 : 0;
130
+ }
131
+ console.log(color.bold(`simcast-host setup ${VERSION}\n`));
132
+ printResults(results);
133
+
134
+ const fixable = results.filter((r) => r.status !== 'ok' && r.fix);
135
+ if (!pending(results).length) {
136
+ console.log(color.green('\nAll set.'));
137
+ return 0;
138
+ }
139
+ if (!fixable.length) {
140
+ console.log(color.yellow('\nNothing here can be fixed automatically; see the notes above.'));
141
+ return 2;
142
+ }
143
+
144
+ console.log(`\nSetup can fix ${fixable.length === 1 ? 'this' : 'these'}:`);
145
+ fixable.forEach((r, i) => console.log(` ${String(i + 1).padStart(2)}. ${fixLine(r)}`));
146
+ if (checkOnly) {
147
+ if (!opts.check) console.log(color.dim('\n(No terminal to ask in, so nothing was changed.)'));
148
+ console.log(`\nRun ${color.cyan('simcast-host setup')} to apply them${fixable.some((r) => checkById(r.id).fix.slow) ? `, or ${color.cyan('simcast-host setup --yes --download')} to apply them all without asking` : ''}.`);
149
+ return 2;
150
+ }
151
+
152
+ // Which fixes to run: one question for the ordinary ones, one each for the
153
+ // slow (download) and confirm-flagged ones. --yes answers all but the slow
154
+ // ones, which need --download (or a yes in a terminal).
155
+ const approved = new Set();
156
+ let ordinaryApproved = false;
157
+ const fixOf = (r) => checkById(r.id).fix;
158
+ const ordinary = fixable.filter((r) => !fixOf(r).slow && !fixOf(r).confirm);
159
+ const special = fixable.filter((r) => !ordinary.includes(r));
160
+ const prompts = tty && (!opts.yes || special.some((r) => fixOf(r).slow && !opts.download)) ? prompter() : null;
161
+ try {
162
+ console.log('');
163
+ if (ordinary.length) {
164
+ const except = special.length ? ` (${special.map((r) => fixOf(r).what.toLowerCase()).join('; ')}: asked next)` : '';
165
+ if (opts.yes || await prompts.ask(`Apply ${special.length ? 'the other fixes' : 'these fixes'}${except}?`, true)) {
166
+ for (const r of ordinary) approved.add(r.id);
167
+ ordinaryApproved = true;
168
+ }
169
+ }
170
+ for (const r of special) {
171
+ const fix = fixOf(r);
172
+ const yes = fix.slow
173
+ ? opts.download || (prompts ? await prompts.ask(`${fix.what}? It can take a while.`, false) : false)
174
+ : opts.yes || await prompts.ask(`${fix.what}?`, true);
175
+ if (yes) approved.add(r.id);
176
+ }
177
+ } finally {
178
+ prompts?.close();
179
+ }
180
+
181
+ if (!approved.size) {
182
+ console.log(color.yellow('Nothing changed.'));
183
+ return 2;
184
+ }
185
+
186
+ // One password prompt up front; the sudo fixes after it reuse it.
187
+ let sudoOk = true;
188
+ if (fixable.some((r) => approved.has(r.id) && fixOf(r).sudo)) {
189
+ console.log(color.dim('Some fixes need your admin password.'));
190
+ sudoOk = (await runInteractive('sudo', ['-v'])) === 0;
191
+ if (!sudoOk) console.log(color.red('✗ sudo did not accept the password; the fixes that need it were not run.'));
192
+ }
193
+
194
+ // Run the approved fixes in check order. Once a fix has run, the checks after
195
+ // it are run again first: it may have unblocked or already fixed them.
196
+ let failed = !sudoOk;
197
+ let changed = false;
198
+ const width = Math.max(...results.map((r) => r.title.length));
199
+ const final = [];
200
+ for (const check of selectChecks({ scope: 'setup', only: opts.only, skip: opts.skip })) {
201
+ const before = ctx.results[check.id];
202
+ let r = changed ? await runCheck(check, ctx) : before;
203
+ const fix = check.fix;
204
+ // An earlier fix can break a check that passed (removing the old LaunchAgent
205
+ // stops the agent that answered), so its fix goes with the ordinary ones.
206
+ if (before.status === 'ok' && r.status !== 'ok' && ordinaryApproved && fix && !fix.slow && !fix.confirm) {
207
+ approved.add(check.id);
208
+ }
209
+ if (r.status === 'ok' || r.status === 'skipped' || !approved.has(check.id) || !r.fix?.commands || (fix.sudo && !sudoOk)) {
210
+ final.push(r);
211
+ continue;
212
+ }
213
+ console.log(color.bold(`\n→ ${fix.what}`));
214
+ let code = 0;
215
+ for (const cmd of r.fix.commands) {
216
+ console.log(color.dim(` $ ${commandText(cmd, fix.sudo)}`));
217
+ if (cmd.run) code = await cmd.run();
218
+ else code = fix.sudo ? await runInteractive('sudo', cmd) : await runInteractive(cmd[0], cmd.slice(1));
219
+ if (code !== 0) break;
220
+ }
221
+ changed = true;
222
+ r = await runCheck(check, ctx);
223
+ // A wall-clock deadline: each re-check can itself take a while (a /health timeout).
224
+ const deadline = Date.now() + (fix.settleMs || 0);
225
+ if (code === 0 && r.status !== 'ok' && Date.now() < deadline) console.log(color.dim(' waiting for the agent to answer…'));
226
+ while (code === 0 && r.status !== 'ok' && Date.now() < deadline) {
227
+ await new Promise((resolve) => setTimeout(resolve, Math.min(500, Math.max(0, deadline - Date.now()))));
228
+ r = await runCheck(check, ctx);
229
+ }
230
+ if (code !== 0 || r.status !== 'ok') {
231
+ failed = true;
232
+ if (code !== 0) r.detail = `${r.detail} (the fix exited with code ${code})`;
233
+ }
234
+ printResult(r, width);
235
+ final.push(r);
236
+ }
237
+
238
+ const left = pending(final);
239
+ console.log('');
240
+ if (failed) {
241
+ console.log(color.red('✗ Some fixes did not work; see above.'));
242
+ printResults(left);
243
+ return 1;
244
+ }
245
+ if (left.length) {
246
+ console.log(color.yellow('Still to do:'));
247
+ printResults(left);
248
+ if (left.some((r) => r.id === 'ios-runtime') && !approved.has('ios-runtime')) {
249
+ console.log(`\nTo download the iOS runtime: ${color.cyan('simcast-host setup --yes --download')}`);
250
+ }
251
+ return 2;
252
+ }
253
+ console.log(color.green('✓ All set.'));
254
+ return 0;
255
+ }
256
+
257
+ // ---- doctor ---------------------------------------------------------------------
258
+
259
+ export async function doctorCmd(args = []) {
260
+ const { values: opts, error } = parse(args, { json: { type: 'boolean' } }, DOCTOR_USAGE);
261
+ if (error) return error;
262
+ const results = await runChecks({ scope: 'doctor' });
263
+ const code = results.some((r) => r.status === 'fail') ? 1 : 0;
264
+ if (opts.json) {
265
+ printJson(results);
266
+ return code;
267
+ }
268
+ console.log(color.bold(`simcast-host doctor ${VERSION}\n`));
269
+ printResults(results, { hints: true });
270
+ const fails = results.filter((r) => r.status === 'fail').length;
271
+ const warns = results.filter((r) => r.status === 'warn').length;
272
+ console.log('');
273
+ if (fails) {
274
+ const fixable = results.some((r) => r.status !== 'ok' && r.fix && checkById(r.id).in.includes('setup'));
275
+ console.log(color.red(`✗ ${fails} problem${fails === 1 ? '' : 's'}${warns ? ` and ${warns} warning${warns === 1 ? '' : 's'}` : ''}.${fixable ? ' Run simcast-host setup to fix what it can.' : ''}`));
276
+ } else if (warns) {
277
+ console.log(color.yellow(`! Working, with ${warns} warning${warns === 1 ? '' : 's'}.`));
278
+ } else {
279
+ console.log(color.green('✓ Everything looks good.'));
280
+ }
281
+ return code;
282
+ }
283
+
@@ -0,0 +1,124 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { agentEnv, run, runOk } from './exec.js';
6
+
7
+ function runtimeLabel(id) {
8
+ const m = /SimRuntime\.([A-Za-z]+)-(\d+)-(\d+)(?:-(\d+))?$/.exec(id);
9
+ return m ? `${m[1]} ${m[2]}.${m[3]}${m[4] ? `.${m[4]}` : ''}` : id;
10
+ }
11
+
12
+ function runtimeRank(id) {
13
+ const m = /-(\d+)-(\d+)(?:-(\d+))?$/.exec(id);
14
+ return m ? Number(m[1]) * 10000 + Number(m[2]) * 100 + Number(m[3] || 0) : 0;
15
+ }
16
+
17
+ export async function listDevices({ all = false } = {}) {
18
+ const { stdout } = await runOk('xcrun', ['simctl', 'list', 'devices', 'available', '-j'], { capture: true });
19
+ const data = JSON.parse(stdout.toString());
20
+ const devices = [];
21
+ for (const [runtime, list] of Object.entries(data.devices || {})) {
22
+ if (!all && !/SimRuntime\.iOS-/.test(runtime)) continue;
23
+ for (const d of list) {
24
+ if (d.isAvailable === false) continue;
25
+ devices.push({ udid: d.udid, name: d.name, state: d.state, runtime: runtimeLabel(runtime), rank: runtimeRank(runtime) });
26
+ }
27
+ }
28
+ devices.sort((a, b) => b.rank - a.rank || a.name.localeCompare(b.name));
29
+ return devices;
30
+ }
31
+
32
+ // Accepts a UDID, an exact name, or part of a name. Defaults to a booted
33
+ // device, then the newest iPhone.
34
+ export async function resolveDevice(query) {
35
+ const devices = await listDevices();
36
+ if (!devices.length) {
37
+ throw new Error('No iOS simulators are available. Add an iOS runtime in Xcode > Settings > Components.');
38
+ }
39
+ if (query) {
40
+ const q = query.toLowerCase();
41
+ const hit = devices.find((d) => d.udid.toLowerCase() === q)
42
+ || devices.find((d) => d.name.toLowerCase() === q)
43
+ || devices.find((d) => d.name.toLowerCase().includes(q));
44
+ if (!hit) throw new Error(`No simulator matches "${query}". Run "simcast devices" to list them.`);
45
+ return hit;
46
+ }
47
+ return devices.find((d) => d.state === 'Booted') || devices.find((d) => /^iPhone/.test(d.name)) || devices[0];
48
+ }
49
+
50
+ export async function boot(udid) {
51
+ const res = await run('xcrun', ['simctl', 'boot', udid]);
52
+ if (res.code !== 0 && !res.tail.join('\n').includes('Booted')) {
53
+ const err = new Error(`Could not boot simulator ${udid}`);
54
+ err.tail = res.tail;
55
+ throw err;
56
+ }
57
+ await runOk('xcrun', ['simctl', 'bootstatus', udid, '-b']);
58
+ }
59
+
60
+ // Xcode 27 replaced Simulator.app with Device Hub (com.apple.dt.Devices).
61
+ export async function showUI() {
62
+ for (const args of [['-b', 'com.apple.dt.Devices'], ['-a', 'Simulator']]) {
63
+ const res = await run('open', args);
64
+ if (res.code === 0) return true;
65
+ }
66
+ return false;
67
+ }
68
+
69
+ export const shutdown = (udid) => run('xcrun', ['simctl', 'shutdown', udid]);
70
+ export async function erase(udid) {
71
+ await shutdown(udid);
72
+ await runOk('xcrun', ['simctl', 'erase', udid]);
73
+ }
74
+ export const install = (udid, appPath) => runOk('xcrun', ['simctl', 'install', udid, appPath]);
75
+ export const terminate = (udid, bundleId) => run('xcrun', ['simctl', 'terminate', udid, bundleId]);
76
+ export const launch = (udid, bundleId) => runOk('xcrun', ['simctl', 'launch', udid, bundleId]);
77
+ export const openUrl = (udid, url) => runOk('xcrun', ['simctl', 'openurl', udid, url]);
78
+ // iOS asks "Open in <app>?" the first time a scheme is opened on a device, and
79
+ // waits for a tap. Its answers live in this preference (key "<opener>--><scheme>",
80
+ // value the app's bundle id); writing it first means it never asks.
81
+ export const approveScheme = (udid, scheme, bundleId) => run('xcrun', [
82
+ 'simctl', 'spawn', udid, 'defaults', 'write', 'com.apple.launchservices.schemeapproval',
83
+ `com.apple.CoreSimulator.CoreSimulatorBridge-->${scheme}`, '-string', bundleId,
84
+ ]);
85
+ export const appearance = (udid, mode) => runOk('xcrun', ['simctl', 'ui', udid, 'appearance', mode]);
86
+ export const setLocation = (udid, latLon) => runOk('xcrun', ['simctl', 'location', udid, 'set', latLon]);
87
+ export const clearLocation = (udid) => runOk('xcrun', ['simctl', 'location', udid, 'clear']);
88
+
89
+ export async function push(udid, bundleId, payload) {
90
+ const file = path.join(os.tmpdir(), `simcast-push-${Date.now()}.json`);
91
+ fs.writeFileSync(file, JSON.stringify(payload));
92
+ try {
93
+ await runOk('xcrun', ['simctl', 'push', udid, bundleId, file]);
94
+ } finally {
95
+ fs.rmSync(file, { force: true });
96
+ }
97
+ }
98
+
99
+ // The simulator's pasteboard, as text.
100
+ export async function pasteboard(udid) {
101
+ const { stdout } = await runOk('xcrun', ['simctl', 'pbpaste', udid], { capture: true });
102
+ return stdout.toString('utf8');
103
+ }
104
+
105
+ export function setPasteboard(udid, text) {
106
+ return new Promise((resolve, reject) => {
107
+ const child = spawn('xcrun', ['simctl', 'pbcopy', udid], { env: agentEnv(), stdio: ['pipe', 'ignore', 'pipe'] });
108
+ let err = '';
109
+ child.stderr.on('data', (d) => { err += d; });
110
+ child.on('error', reject);
111
+ child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`simctl pbcopy failed: ${err.trim() || `code ${code}`}`))));
112
+ child.stdin.end(text, 'utf8');
113
+ });
114
+ }
115
+
116
+ export async function screenshot(udid) {
117
+ const file = path.join(os.tmpdir(), `simcast-shot-${Date.now()}.png`);
118
+ try {
119
+ await runOk('xcrun', ['simctl', 'io', udid, 'screenshot', '--type=png', file]);
120
+ return fs.readFileSync(file);
121
+ } finally {
122
+ fs.rmSync(file, { force: true });
123
+ }
124
+ }
@@ -0,0 +1,32 @@
1
+ // Logs when the agent's event loop was blocked: a timer that should fire every
2
+ // `intervalMs` notices how late it is. While blocked, the agent answers no
3
+ // heartbeats, so a PC gives up on it ("Lost the connection to the Mac"); this
4
+ // line in the log says for how long, and what the agent was doing.
5
+ // The CPU time tells the two causes apart: code blocking the loop keeps the CPU
6
+ // busy for about the whole gap, while a Mac that stalled (or never scheduled the
7
+ // agent) leaves it near zero.
8
+ const defaultLog = (msg) => console.log(`[${new Date().toISOString()}] stall: ${msg}`);
9
+
10
+ const cpuMs = () => {
11
+ const { user, system } = process.cpuUsage();
12
+ return (user + system) / 1000;
13
+ };
14
+
15
+ // Returns stop(). `during()` names the work in progress ('' for none).
16
+ export function watchStalls({ intervalMs = 1000, thresholdMs = 2000, log = defaultLog, during = () => '' } = {}) {
17
+ let last = Date.now();
18
+ let lastCpu = cpuMs();
19
+ const timer = setInterval(() => {
20
+ const now = Date.now();
21
+ const cpu = cpuMs();
22
+ const late = now - last - intervalMs;
23
+ const used = cpu - lastCpu;
24
+ last = now;
25
+ lastCpu = cpu;
26
+ if (late < thresholdMs) return;
27
+ const what = during();
28
+ log(`the agent was blocked for ${(late / 1000).toFixed(1)} s${what ? ` (${what})` : ''}; it used ${(used / 1000).toFixed(1)} s of CPU meanwhile`);
29
+ }, intervalMs);
30
+ timer.unref();
31
+ return () => clearInterval(timer);
32
+ }
@@ -0,0 +1,121 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { DEFAULT_PORT } from '../common.js';
6
+
7
+ export const agentHome = process.env.SIMCAST_HOME || path.join(os.homedir(), '.simcast');
8
+ export const agentConfigFile = path.join(agentHome, 'agent.json');
9
+
10
+ // base64url can start with "-", which a command line reads as an option, so
11
+ // draw again until it doesn't.
12
+ export function newToken() {
13
+ let token;
14
+ do token = crypto.randomBytes(24).toString('base64url');
15
+ while (token.startsWith('-'));
16
+ return token;
17
+ }
18
+
19
+ // agent.json. Keys:
20
+ // - port
21
+ // - agentId: the Mac's identity, 16 random bytes in base64url (created at first start)
22
+ // - adminToken: for the Mac-local /admin API, 24 random bytes (created at first start)
23
+ // - bonjour: advertise with dns-sd (default true)
24
+ // - extraPath (see readAgentConfigSafe)
25
+ export function loadAgentConfig() {
26
+ const file = agentConfigFile;
27
+ fs.mkdirSync(agentHome, { recursive: true });
28
+ let cfg = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : null;
29
+ let changed = false;
30
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) {
31
+ cfg = { port: DEFAULT_PORT };
32
+ changed = true;
33
+ }
34
+ if (typeof cfg.agentId !== 'string' || !cfg.agentId) {
35
+ cfg.agentId = crypto.randomBytes(16).toString('base64url');
36
+ changed = true;
37
+ }
38
+ if (typeof cfg.adminToken !== 'string' || !cfg.adminToken) {
39
+ cfg.adminToken = newToken();
40
+ changed = true;
41
+ }
42
+ if (cfg.bonjour === undefined) {
43
+ cfg.bonjour = true;
44
+ changed = true;
45
+ }
46
+ if (changed) saveAgentConfig(cfg);
47
+ return cfg;
48
+ }
49
+
50
+ // Writes agent.json (0600) through a temp file, so a reader never sees half of it.
51
+ export function saveAgentConfig(cfg) {
52
+ fs.mkdirSync(agentHome, { recursive: true });
53
+ const tmp = `${agentConfigFile}.${process.pid}.tmp`;
54
+ fs.writeFileSync(tmp, JSON.stringify(cfg, null, 2), { mode: 0o600 });
55
+ try { fs.chmodSync(tmp, 0o600); } catch { /* not on Windows */ }
56
+ fs.renameSync(tmp, agentConfigFile);
57
+ }
58
+
59
+ // The Mac's name for pairing, /health and Bonjour: macinfo.computerName()
60
+ // (`scutil --get ComputerName`), else os.hostname() without ".local". Asked
61
+ // once per process (a promise).
62
+ const hostName = () => os.hostname().replace(/\.local$/i, '') || 'Mac';
63
+ let macNameAsked = null;
64
+ let macNameKnown = null;
65
+ export function macName() {
66
+ macNameAsked ??= (async () => {
67
+ let name = null;
68
+ try {
69
+ // macinfo.js imports exec.js, which imports this module: load it when first needed.
70
+ const { computerName } = await import('./macinfo.js');
71
+ name = await computerName();
72
+ } catch { /* no scutil */ }
73
+ macNameKnown = String(name || '').replace(/[\r\n]/g, ' ').trim().slice(0, 63) || hostName();
74
+ return macNameKnown;
75
+ })();
76
+ return macNameAsked;
77
+ }
78
+
79
+ // macName() without waiting: the answer once known, else the hostname.
80
+ export const macNameNow = () => macNameKnown || hostName();
81
+
82
+ // For readers that must not create agent.json or a token as a side effect
83
+ // (agentEnv, CLI checks). Missing or unreadable means {}. Optional keys:
84
+ // extraPath, a PATH-style string or an array of folders put first on the agent's PATH.
85
+ export function readAgentConfigSafe() {
86
+ try {
87
+ const cfg = JSON.parse(fs.readFileSync(agentConfigFile, 'utf8'));
88
+ return cfg && typeof cfg === 'object' ? cfg : {};
89
+ } catch {
90
+ return {};
91
+ }
92
+ }
93
+
94
+ export function projectPaths(id) {
95
+ const base = path.join(agentHome, 'projects', id);
96
+ return {
97
+ base,
98
+ src: path.join(base, 'src'),
99
+ derived: path.join(base, 'DerivedData'),
100
+ builds: path.join(base, 'builds'),
101
+ logs: path.join(base, 'logs'),
102
+ state: path.join(base, 'state.json'),
103
+ };
104
+ }
105
+
106
+ export function loadState(id) {
107
+ const p = projectPaths(id);
108
+ try {
109
+ return JSON.parse(fs.readFileSync(p.state, 'utf8'));
110
+ } catch {
111
+ return { manifest: {}, pending: [], lockHash: null, lastRun: null };
112
+ }
113
+ }
114
+
115
+ export function saveState(id, state) {
116
+ const p = projectPaths(id);
117
+ fs.mkdirSync(p.base, { recursive: true });
118
+ const tmp = `${p.state}.tmp`;
119
+ fs.writeFileSync(tmp, JSON.stringify(state));
120
+ fs.renameSync(tmp, p.state);
121
+ }