@babylonjs-toolkit/agent 1.1.36 → 1.1.42

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,677 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const os = require('os');
5
+ const path = require('path');
6
+
7
+ const { parseBridgeArgs, DEFAULT_SERVER } = require('./args');
8
+ const {
9
+ readSettings,
10
+ writeSettings,
11
+ deleteBridgeConfig,
12
+ bridgeConfigPath,
13
+ saveCurrentProject,
14
+ restorableCurrentProject,
15
+ } = require('./config');
16
+ const { BridgeApi, UpdateRequiredError, NotPairedError } = require('./api');
17
+ const { ensurePaired, notPairedText } = require('./pairing');
18
+ const { runLoop, createJobQueue, STOPPED } = require('./loop');
19
+ const { BRIDGE_PROTOCOL_VERSION, isSafeJobId } = require('./protocol');
20
+ const log = require('./log');
21
+ const { discoverUnity, probeDevServer, createWorkspace, resolveProjectsFolder, isUnityProject } = require('./unity/discover');
22
+ const { executeUnity, executeUnityProject, NO_PROJECT } = require('./unity/ops');
23
+ const { runProcess: defaultRunProcess } = require('./unity/run');
24
+ const { discoverBlender } = require('./blender/discover');
25
+ const { executeBlender } = require('./blender/run');
26
+ const service = require('./service');
27
+ const { prettyPath } = require('../paths');
28
+ const { version } = require('../../package.json');
29
+
30
+ const USAGE = `
31
+ bt-agent bridge — connect this computer to the App Builder (Unity/Blender)
32
+
33
+ Usage
34
+ bt-agent bridge --install-service --pair <code> --projects <folder>
35
+ Pair, then start the bridge now and whenever you log in
36
+ bt-agent bridge --uninstall-service Stop the bridge and stop starting it at login
37
+ bt-agent bridge [--pair <code>] [options] Run the bridge in this terminal until Ctrl-C
38
+ bt-agent bridge status Show the App Builders this computer is paired with
39
+ bt-agent bridge logout Unpair this computer and delete its credentials
40
+
41
+ The Unity Bridge dialog in the App Builder shows the whole command, install code included — copy it
42
+ from there. An install code is single-use and expires after 10 minutes.
43
+
44
+ Options
45
+ --pair <code> The install code from the Unity Bridge dialog (like K7QM-2XWD)
46
+ --server <url> The App Builder's address (default: ${DEFAULT_SERVER}). Repeat it to serve
47
+ several App Builders (each pairs with its own code). Also read from BTK_BRIDGE_SERVER.
48
+ status/logout: only this App Builder (default: all).
49
+ --projects <folder> A Unity projects folder (repeatable): the Unity folder inside your App Builder projects
50
+ folder (the Unity Bridge dialog fills it in). The App Builder opens and creates projects
51
+ in it; a folder that does not exist is created. REQUIRED for --install-service (a
52
+ reinstall without it keeps the stored folders). Default, only when running in this
53
+ terminal: this folder, or its parent when this folder is itself a Unity project.
54
+ --unity <path> Also serve this Unity project (repeatable); the first one starts as the current project
55
+ --blender <path> The Blender executable to use (default: discovered)
56
+ --no-scripts Never run C# or Python scripts on this computer, whatever Allow scripts says
57
+ -h, --help Show this help
58
+
59
+ What the App Builder may ask this computer to do
60
+ allowed List, open or create projects in the projects folder, read the project and make ordinary
61
+ edits — runs straight away
62
+ scripts Run C# or Python scripts — only when you turn on Allow scripts for this computer in the
63
+ App Builder's Unity Bridge dialog (on by default), and never with --no-scripts
64
+ consent Delete, move, rename, build or change project settings — asks you in the chat first
65
+
66
+ --install-service copies this helper to ~/.babylon-toolkit/service/ and starts it at login (macOS launchd,
67
+ Linux systemd user unit, Windows Startup folder), logging to ~/.babylon-toolkit/bridge.log. Run it again
68
+ to change the settings; it restarts the service. Installing or updating the Desktop Agent never starts
69
+ the bridge. Credentials and settings are stored in ${prettyPath(bridgeConfigPath())} (readable by you only).
70
+ `;
71
+
72
+ const DEV_SERVER_EVERY_MS = 30_000;
73
+
74
+ /**
75
+ * Routes one dispatch to its runner (D54). `unity.project` works on the projects folder; every other
76
+ * Unity, dev-server and Blender job runs against the CURRENT project and is refused when there is none.
77
+ * @param {{
78
+ * workspace: import('./unity/discover').Workspace,
79
+ * cli?: { path: string, version: string },
80
+ * blender?: { path: string, version: string },
81
+ * noScripts: boolean,
82
+ * api?: import('./api').BridgeApi,
83
+ * runProcess?: import('./unity/run').RunProcess,
84
+ * launch?: import('./unity/run').LaunchDetached,
85
+ * log?: { info: (m: string) => void, op: (tier: string, label: string) => void, error?: (m: string) => void },
86
+ * sleep?: (ms: number, signal?: AbortSignal) => Promise<void>,
87
+ * now?: () => number,
88
+ * onScaffold?: (active: boolean, root: string) => void,
89
+ * }} ctx
90
+ * @returns {import('./loop').Execute}
91
+ */
92
+ function makeExecuteDispatch(ctx) {
93
+ return async (dispatch, emit, signal, source) => {
94
+ // Defence in depth behind loop.js: a job id names files under .bridge/, so an unsafe one never runs.
95
+ if (!dispatch || !isSafeJobId(dispatch.jobId)) return;
96
+ const kind = dispatch.op && dispatch.op.kind;
97
+ const extras = {};
98
+ if (ctx.log) extras.log = ctx.log;
99
+ if (ctx.sleep) extras.sleep = ctx.sleep;
100
+ if (ctx.now) extras.now = ctx.now;
101
+ if (ctx.launch) extras.launch = ctx.launch;
102
+ if (kind === 'unity.project') {
103
+ if (ctx.onScaffold) extras.onScaffold = ctx.onScaffold;
104
+ await executeUnityProject(dispatch, { workspace: ctx.workspace, cli: ctx.cli, emit, signal, runProcess: ctx.runProcess, ...extras });
105
+ return;
106
+ }
107
+ const isUnity = typeof kind === 'string' && (kind.startsWith('unity.') || kind.startsWith('devserver.'));
108
+ if (kind !== 'blender.script' && !isUnity) {
109
+ await emit({ jobId: dispatch.jobId, type: 'refused', reason: 'This Desktop Agent cannot run that yet.' });
110
+ return;
111
+ }
112
+ const project = ctx.workspace.current();
113
+ if (!project) {
114
+ await emit({ jobId: dispatch.jobId, type: 'refused', reason: NO_PROJECT });
115
+ return;
116
+ }
117
+ const common = { project, emit, signal, noScripts: ctx.noScripts, runProcess: ctx.runProcess, ...extras };
118
+ if (kind === 'blender.script') {
119
+ await executeBlender(dispatch, { ...common, blender: ctx.blender });
120
+ return;
121
+ }
122
+ // the App Builder the job came from (D55: one helper may serve several)
123
+ const api = (source && source.api) || ctx.api;
124
+ await executeUnity(dispatch, { ...common, cli: ctx.cli, api });
125
+ };
126
+ }
127
+
128
+ /**
129
+ * Hello's `devServer` for the CURRENT Unity project, refreshed at most every 30 s (and at once when the
130
+ * current project changes). The probe's own rules (Toolkit ≥ 9.25.1, an unknown-command answer remembered
131
+ * per project + Toolkit version for 5 minutes, never while `busy` — a create scaffold running) live in
132
+ * probeDevServer; the memory lives here.
133
+ * @param {{ cli?: { path: string }, current: () => { root: string, toolkitVersion?: string }|undefined, runProcess?: import('./unity/run').RunProcess, now?: () => number, busy?: (root: string) => boolean }} opts
134
+ * @returns {() => Promise<import('./protocol').BridgeDevServerInfo|undefined>}
135
+ */
136
+ function makeDevServerProbe({ cli, current, runProcess = defaultRunProcess, now = Date.now, busy }) {
137
+ /** project root + Toolkit version → when its Editor answered "No command named 'bt_devserver_status'" (kept 5 min) */
138
+ const memo = new Map();
139
+ /** @type {import('./protocol').BridgeDevServerInfo|undefined} */
140
+ let cached;
141
+ /** @type {string|undefined} */
142
+ let cachedRoot;
143
+ let at = -Infinity;
144
+ return async () => {
145
+ const project = current();
146
+ if (!cli || !project) return undefined;
147
+ if (cached && cachedRoot === project.root && now() - at < DEV_SERVER_EVERY_MS) return cached;
148
+ at = now();
149
+ cachedRoot = project.root;
150
+ cached = await probeDevServer({ cli, project, runProcess, memo, busy, now });
151
+ return cached;
152
+ };
153
+ }
154
+
155
+ /**
156
+ * The hello this computer sends with every poll (D54). Only NAMES leave this computer: the projects
157
+ * folder is sent as its basename, and each project without its local `root`.
158
+ * @param {{
159
+ * workspace: import('./unity/discover').Workspace,
160
+ * cli?: { path: string, version: string },
161
+ * blender?: { path: string, version: string },
162
+ * noScripts: boolean,
163
+ * devServer: () => Promise<import('./protocol').BridgeDevServerInfo|undefined>,
164
+ * helperVersion?: string,
165
+ * os?: 'darwin'|'win32'|'linux',
166
+ * }} opts
167
+ * @returns {() => Promise<import('./protocol').BridgeHello>}
168
+ */
169
+ function makeHello({ workspace, cli, blender, noScripts, devServer, helperVersion = version, os: helloOsValue = helloOs() }) {
170
+ return async () => {
171
+ const current = workspace.current();
172
+ /** @type {import('./protocol').BridgeHello} */
173
+ const h = {
174
+ protocol: BRIDGE_PROTOCOL_VERSION,
175
+ helperVersion,
176
+ os: helloOsValue,
177
+ projectsDir: workspace.projectsDirName,
178
+ unityProjects: workspace.projects().map((p) => {
179
+ const { root, ...wire } = p; // the local path never leaves this computer
180
+ return wire;
181
+ }),
182
+ scriptsDisabledLocally: noScripts,
183
+ };
184
+ if (current) h.currentProject = current.name;
185
+ if (cli) h.unityCli = cli;
186
+ if (blender) h.blender = blender;
187
+ const ds = await devServer();
188
+ if (ds) h.devServer = ds;
189
+ return h;
190
+ };
191
+ }
192
+
193
+ /**
194
+ * The start-up line naming the projects folder(s): `<n> in <folder>[, <folder>…]`, plus `, +<m> from
195
+ * --unity` when --unity added projects from outside them — so an empty folder never reads as holding a project.
196
+ * @param {{ projectsDir: string, projectsDirs?: string[], projects: unknown[], folderProjectCount: number }} unity
197
+ * @returns {string}
198
+ */
199
+ function projectsFolderLine({ projectsDir, projectsDirs, projects, folderProjectCount }) {
200
+ const extra = projects.length - folderProjectCount;
201
+ const where = projectsDirs && projectsDirs.length ? projectsDirs.join(', ') : projectsDir;
202
+ return `Unity projects: ${folderProjectCount} in ${where}${extra > 0 ? `, +${extra} from --unity` : ''}.`;
203
+ }
204
+
205
+ /** @returns {'darwin'|'win32'|'linux'} */
206
+ function helloOs() {
207
+ return process.platform === 'darwin' || process.platform === 'win32' ? process.platform : 'linux';
208
+ }
209
+
210
+ /** @param {number} ms @param {AbortSignal} signal */
211
+ function abortableSleep(ms, signal) {
212
+ return new Promise((resolve) => {
213
+ if (signal.aborted) return resolve();
214
+ const timer = setTimeout(done, ms);
215
+ function done() {
216
+ clearTimeout(timer);
217
+ signal.removeEventListener('abort', done);
218
+ resolve();
219
+ }
220
+ signal.addEventListener('abort', done);
221
+ });
222
+ }
223
+
224
+ /**
225
+ * Everything a bridge command touches outside this module, so tests can replace it.
226
+ * @typedef {{
227
+ * env?: Record<string, string|undefined>,
228
+ * cwd?: string,
229
+ * settingsFile?: string,
230
+ * deviceName?: string,
231
+ * makeApi?: (server: string, token?: string) => any,
232
+ * logger?: { info: (m: string) => void, op: (t: string, l: string) => void, error: (m: string) => void },
233
+ * serviceDeps?: import('./service').ServiceDeps,
234
+ * discover?: typeof discoverUnity,
235
+ * findBlender?: typeof discoverBlender,
236
+ * signal?: AbortSignal,
237
+ * sleep?: (ms: number) => Promise<void>,
238
+ * logFile?: string,
239
+ * pidFile?: string,
240
+ * }} CliDeps
241
+ */
242
+
243
+ /** @param {CliDeps} deps */
244
+ function withDefaults(deps) {
245
+ return {
246
+ env: deps.env || process.env,
247
+ cwd: deps.cwd || process.cwd(),
248
+ settingsFile: deps.settingsFile || bridgeConfigPath(),
249
+ deviceName: deps.deviceName || os.hostname() || 'computer',
250
+ makeApi: deps.makeApi || ((/** @type {string} */ server, /** @type {string|undefined} */ token) => new BridgeApi(server, token)),
251
+ logger: deps.logger || log,
252
+ serviceDeps: deps.serviceDeps || service.hostDeps(),
253
+ discover: deps.discover || discoverUnity,
254
+ findBlender: deps.findBlender || discoverBlender,
255
+ };
256
+ }
257
+
258
+ /**
259
+ * Pairs every requested server (a supplied code always re-pairs — D55), stores the new credentials,
260
+ * and reports the ones that could not be paired. Returns the credentials of the requested servers.
261
+ * @param {import('./args').BridgeArgs} args
262
+ * @param {ReturnType<typeof withDefaults>} d
263
+ */
264
+ async function pairRequested(args, d) {
265
+ const settings = readSettings(d.settingsFile);
266
+ const result = await ensurePaired({
267
+ servers: args.servers,
268
+ code: args.pair,
269
+ stored: (server) => settings.servers.find((c) => c.server === server) || null,
270
+ save: (cfg) => {
271
+ const now = readSettings(d.settingsFile);
272
+ now.servers = now.servers.filter((c) => c.server !== cfg.server).concat([cfg]);
273
+ writeSettings(now, d.settingsFile);
274
+ },
275
+ makeApi: (server) => d.makeApi(server),
276
+ deviceName: d.deviceName,
277
+ os: helloOs(),
278
+ });
279
+ for (const server of result.paired) d.logger.info(`Paired with ${server}.`);
280
+ for (const r of result.rejected) {
281
+ d.logger.error(`Could not pair with ${r.server}: ${r.message}${r.kept ? ' — keeping this computer\'s existing pairing.' : ''}`);
282
+ }
283
+ for (const server of result.unpaired) d.logger.error(notPairedText(server));
284
+ return result;
285
+ }
286
+
287
+ /**
288
+ * Runs one poll loop per paired App Builder, all sharing ONE job queue and ONE workspace (D55), until
289
+ * every loop has ended. Returns each loop's exit.
290
+ * @param {{
291
+ * creds: import('./config').BridgeConfig[],
292
+ * projects: string[],
293
+ * unity: string[],
294
+ * blender?: string,
295
+ * noScripts: boolean,
296
+ * signal: AbortSignal,
297
+ * sleep: (ms: number) => Promise<void>,
298
+ * foreground: boolean,
299
+ * }} opts
300
+ * @param {ReturnType<typeof withDefaults>} d
301
+ * @returns {Promise<{ server: string, exit: import('./loop').LoopExit }[]>}
302
+ */
303
+ async function serve(opts, d) {
304
+ const logger = d.logger;
305
+ const unity = d.discover({ unityPaths: opts.unity, projectsDir: opts.projects, cwd: d.cwd });
306
+ for (const dir of unity.notProjects) logger.error(`Not a Unity project (no Assets/ and ProjectSettings/ProjectVersion.txt): ${dir}`);
307
+ for (const dir of unity.missingDirs || (unity.projectsDirMissing ? [unity.projectsDir] : [])) {
308
+ logger.error(`The projects folder does not exist: ${dir}`);
309
+ }
310
+ // A current project started inside wins; otherwise the one remembered from the last run, when it still exists
311
+ // inside a configured projects folder (a restarted service must not make the model reopen it).
312
+ const remembered = unity.currentRoot
313
+ ? undefined
314
+ : restorableCurrentProject(readSettings(d.settingsFile).currentProject, unity.projectsDirs || [unity.projectsDir], {
315
+ isProject: isUnityProject,
316
+ real: (p) => {
317
+ try {
318
+ return fs.realpathSync(p);
319
+ } catch {
320
+ return path.resolve(p);
321
+ }
322
+ },
323
+ });
324
+ const workspace = createWorkspace({
325
+ projectsDir: unity.projectsDir,
326
+ projectsDirs: unity.projectsDirs,
327
+ extraRoots: unity.extraRoots,
328
+ currentRoot: unity.currentRoot || remembered,
329
+ projects: unity.projects,
330
+ onCurrentChange: (root) => saveCurrentProject(root, d.settingsFile),
331
+ });
332
+ logger.info(projectsFolderLine(unity));
333
+ const startCurrent = workspace.current();
334
+ if (startCurrent) logger.info(`Current Unity project: ${startCurrent.name}.`);
335
+ else logger.info('No current Unity project — the App Builder opens or creates one in the projects folder.');
336
+ if (!unity.cli) logger.info('The Unity command-line tool (unity) was not found; Unity jobs will be refused until it is installed.');
337
+ const blender = d.findBlender({ explicit: opts.blender });
338
+ /** Unity projects whose create scaffold is running — the dev-server probe leaves them alone (D56). */
339
+ const scaffolding = new Set();
340
+ const onScaffold = (/** @type {boolean} */ active, /** @type {string} */ root) => void (active ? scaffolding.add(root) : scaffolding.delete(root));
341
+ const real = (/** @type {string} */ p) => {
342
+ try {
343
+ return fs.realpathSync(p);
344
+ } catch {
345
+ return p;
346
+ }
347
+ };
348
+ // The scaffold names the folder before it exists; the workspace names projects by their real path.
349
+ const busy = (/** @type {string} */ root) => [...scaffolding].some((r) => r === root || real(r) === real(root));
350
+ const devServer = makeDevServerProbe({ cli: unity.cli, current: () => workspace.current(), busy });
351
+ const hello = makeHello({ workspace, cli: unity.cli, blender, noScripts: opts.noScripts, devServer });
352
+ const queue = createJobQueue({
353
+ execute: makeExecuteDispatch({ workspace, cli: unity.cli, blender, noScripts: opts.noScripts, log: logger, onScaffold }),
354
+ logger,
355
+ });
356
+
357
+ const stoppedText = opts.foreground ? STOPPED : 'The Unity Bridge service was stopped.';
358
+ const loops = opts.creds.map(async (cred) => {
359
+ const api = d.makeApi(cred.server, cred.token);
360
+ if (typeof api.server !== 'string') api.server = cred.server;
361
+ const exit = await runLoop({
362
+ api,
363
+ hello,
364
+ queue,
365
+ signal: opts.signal,
366
+ sleep: opts.sleep,
367
+ logger,
368
+ stoppedText,
369
+ clearConfig: () => deleteBridgeConfig(cred.server, d.settingsFile),
370
+ onPolling: () =>
371
+ logger.info(`Unity Bridge connected to ${cred.server} as ${d.deviceName}.${opts.foreground ? ' Press Ctrl-C to stop.' : ''}`),
372
+ });
373
+ if (exit.reason !== 'stopped') {
374
+ logger.error(exit.message || `The Unity Bridge stopped serving ${cred.server}.`);
375
+ if (exit.reason === 'update-required') logger.error('Update the Desktop Agent: copy the install command from the Unity Bridge dialog again.');
376
+ }
377
+ return { server: cred.server, exit };
378
+ });
379
+ const exits = await Promise.all(loops);
380
+ queue.close();
381
+ return exits;
382
+ }
383
+
384
+ /** D59: an install with no projects folder anywhere is refused before anything is paired or installed. */
385
+ const PROJECTS_FOLDER_REQUIRED =
386
+ 'Choose your Unity projects folder: add --projects <folder> (the Unity Bridge dialog puts it in the command).';
387
+
388
+ /**
389
+ * The projects folders to store for the service (D59 — REQUIRED, never guessed from where the command runs):
390
+ * `--projects` resolved absolute (a missing folder is created, a file is refused), else the folders already
391
+ * stored by an earlier install (a reinstall keeps them), else a refusal. `--unity` replaces the stored extra
392
+ * projects; a plain reinstall (neither flag) keeps them too.
393
+ * @param {import('./args').BridgeArgs} args
394
+ * @param {string} cwd
395
+ * @param {{ projects: string[], unity: string[] }} stored
396
+ * @returns {{ ok: true, projects: string[], unity: string[], created: string[] } | { ok: false, message: string }}
397
+ */
398
+ function resolveServiceFolders(args, cwd, stored) {
399
+ const unity = args.unity.map((u) => path.resolve(cwd, u));
400
+ if (!args.projects.length) {
401
+ if (!stored.projects.length) return { ok: false, message: PROJECTS_FOLDER_REQUIRED };
402
+ return { ok: true, projects: stored.projects.slice(), unity: args.unity.length ? unity : stored.unity.slice(), created: [] };
403
+ }
404
+
405
+ /** @type {string[]} */
406
+ const projects = [];
407
+ /** @type {string[]} */
408
+ const created = [];
409
+ for (const p of args.projects) {
410
+ const abs = path.resolve(cwd, p);
411
+ let stat;
412
+ try {
413
+ stat = fs.statSync(abs);
414
+ } catch {
415
+ stat = undefined;
416
+ }
417
+ if (stat && !stat.isDirectory()) {
418
+ return { ok: false, message: `The Unity projects folder is a file, not a folder: ${abs}` };
419
+ }
420
+ if (!stat) {
421
+ try {
422
+ fs.mkdirSync(abs, { recursive: true });
423
+ } catch (err) {
424
+ return { ok: false, message: `Could not create the Unity projects folder ${abs}: ${err instanceof Error ? err.message : String(err)}` };
425
+ }
426
+ created.push(abs);
427
+ }
428
+ const folder = resolveProjectsFolder({ projectsDir: abs, cwd }).folder;
429
+ if (!projects.includes(folder)) projects.push(folder);
430
+ }
431
+ return { ok: true, projects, unity, created };
432
+ }
433
+
434
+ /** @param {import('./args').BridgeArgs} args @param {ReturnType<typeof withDefaults>} d */
435
+ async function installServiceCommand(args, d) {
436
+ // D59: settle the projects folder BEFORE the install code is claimed — a refusal must not spend it.
437
+ const folders = resolveServiceFolders(args, d.cwd, readSettings(d.settingsFile));
438
+ if (!folders.ok) {
439
+ d.logger.error(folders.message);
440
+ return 1;
441
+ }
442
+ for (const dir of folders.created) d.logger.info(`Created ${prettyPath(dir)}.`);
443
+
444
+ const paired = await pairRequested(args, d);
445
+ if (!paired.ready.length) {
446
+ d.logger.error('Nothing was installed: this computer is not paired with any App Builder yet.');
447
+ return 1;
448
+ }
449
+
450
+ const settings = readSettings(d.settingsFile);
451
+ settings.projects = folders.projects;
452
+ settings.unity = folders.unity;
453
+ if (args.blender) settings.blender = path.resolve(d.cwd, args.blender);
454
+ else delete settings.blender;
455
+ settings.noScripts = args.noScripts;
456
+ writeSettings(settings, d.settingsFile);
457
+
458
+ const installed = await service.installService(d.serviceDeps);
459
+ d.logger.info(`Installed the Unity Bridge service: ${prettyPath(installed.registration)}`);
460
+ d.logger.info(`Helper copied to ${prettyPath(installed.serviceDir)}`);
461
+ d.logger.info(`App Builder${settings.servers.length === 1 ? '' : 's'}: ${settings.servers.map((c) => c.server).join(', ')}`);
462
+ d.logger.info(`Unity projects folder${settings.projects.length === 1 ? '' : 's'}: ${settings.projects.map(prettyPath).join(', ')}`);
463
+ if (settings.noScripts) d.logger.info('Scripts are disabled on this computer (--no-scripts).');
464
+ d.logger.info(`Log: ${prettyPath(installed.logFile)}`);
465
+ d.logger.info('Unity Bridge will start automatically when you log in. Remove it with: bt-agent bridge --uninstall-service');
466
+ return 0;
467
+ }
468
+
469
+ /** @param {ReturnType<typeof withDefaults>} d */
470
+ function uninstallServiceCommand(d) {
471
+ const { removed } = service.uninstallService(d.serviceDeps);
472
+ if (!removed.length) d.logger.info('The Unity Bridge service is not installed.');
473
+ else {
474
+ for (const p of removed) d.logger.info(`Removed ${prettyPath(p)}`);
475
+ d.logger.info('The Unity Bridge service is stopped and will not start at login. This computer stays paired (bt-agent bridge logout unpairs it).');
476
+ }
477
+ return 0;
478
+ }
479
+
480
+ /**
481
+ * `bridge --service`: what the start-at-login service runs. Reads everything from the stored settings,
482
+ * logs to the (size-capped) log file, and exits 0 once no App Builder is left to serve — so launchd /
483
+ * systemd never restart a service that has nothing to do.
484
+ * @param {ReturnType<typeof withDefaults>} d
485
+ * @param {CliDeps} raw
486
+ */
487
+ async function serviceModeCommand(d, raw) {
488
+ const paths = service.servicePaths(d.serviceDeps);
489
+ const logFile = raw.logFile || paths.logFile;
490
+ if (!raw.logger) log.toFile(logFile);
491
+ const pidFile = raw.pidFile || paths.pidFile;
492
+ try {
493
+ fs.mkdirSync(path.dirname(pidFile), { recursive: true });
494
+ fs.writeFileSync(pidFile, String(process.pid));
495
+ } catch {
496
+ // only Windows uses it, to stop the helper it started
497
+ }
498
+ try {
499
+ const settings = readSettings(d.settingsFile);
500
+ d.logger.info(`Unity Bridge service ${version} starting.`);
501
+ if (!settings.servers.length) {
502
+ d.logger.error('This computer is not paired with any App Builder — copy the install command from the Unity Bridge dialog again.');
503
+ return 0;
504
+ }
505
+ return await withSignals(raw, async (signal, sleep) => {
506
+ await serve(
507
+ {
508
+ creds: settings.servers,
509
+ projects: settings.projects,
510
+ unity: settings.unity,
511
+ blender: settings.blender,
512
+ noScripts: settings.noScripts,
513
+ signal,
514
+ sleep,
515
+ foreground: false,
516
+ },
517
+ d
518
+ );
519
+ d.logger.info(signal.aborted ? 'Unity Bridge service stopped.' : 'No App Builder is left to serve; the Unity Bridge service is exiting.');
520
+ return 0;
521
+ });
522
+ } finally {
523
+ try {
524
+ if (fs.readFileSync(pidFile, 'utf8') === String(process.pid)) fs.rmSync(pidFile, { force: true });
525
+ } catch {
526
+ // gone already
527
+ }
528
+ }
529
+ }
530
+
531
+ /**
532
+ * Runs `fn` with an abort signal wired to Ctrl-C / SIGTERM (or the injected one).
533
+ * @template T
534
+ * @param {CliDeps} raw
535
+ * @param {(signal: AbortSignal, sleep: (ms: number) => Promise<void>) => Promise<T>} fn
536
+ */
537
+ async function withSignals(raw, fn) {
538
+ const controller = new AbortController();
539
+ const stop = () => controller.abort();
540
+ if (raw.signal) {
541
+ if (raw.signal.aborted) controller.abort();
542
+ else raw.signal.addEventListener('abort', stop);
543
+ }
544
+ process.once('SIGINT', stop);
545
+ process.once('SIGTERM', stop);
546
+ const sleep = raw.sleep || ((/** @type {number} */ ms) => abortableSleep(ms, controller.signal));
547
+ try {
548
+ return await fn(controller.signal, sleep);
549
+ } finally {
550
+ process.removeListener('SIGINT', stop);
551
+ process.removeListener('SIGTERM', stop);
552
+ if (raw.signal) raw.signal.removeEventListener('abort', stop);
553
+ }
554
+ }
555
+
556
+ /** @param {import('./args').BridgeArgs} args @param {ReturnType<typeof withDefaults>} d @param {CliDeps} raw */
557
+ async function runForegroundCommand(args, d, raw) {
558
+ const paired = await pairRequested(args, d);
559
+ if (!paired.ready.length) return 1;
560
+ return withSignals(raw, async (signal, sleep) => {
561
+ const exits = await serve(
562
+ {
563
+ creds: paired.ready,
564
+ projects: args.projects,
565
+ unity: args.unity,
566
+ blender: args.blender,
567
+ noScripts: args.noScripts,
568
+ signal,
569
+ sleep,
570
+ foreground: true,
571
+ },
572
+ d
573
+ );
574
+ if (exits.every((e) => e.exit.reason === 'stopped')) {
575
+ d.logger.info('\nUnity Bridge stopped.');
576
+ return 0;
577
+ }
578
+ return 1;
579
+ });
580
+ }
581
+
582
+ /** @param {import('./args').BridgeArgs} args @param {ReturnType<typeof withDefaults>} d */
583
+ function statusCommand(args, d) {
584
+ const { servers } = readSettings(d.settingsFile);
585
+ const shown = args.serverExplicit ? servers.filter((c) => args.servers.includes(c.server)) : servers;
586
+ if (!shown.length) d.logger.info(args.serverExplicit ? `Not paired with ${args.servers.join(', ')}.` : 'Not paired.');
587
+ for (const c of shown) d.logger.info(`Paired with ${c.server} as device ${c.deviceId}.`);
588
+ const st = service.serviceStatus(d.serviceDeps);
589
+ d.logger.info(
590
+ `Service: ${st.installed ? `installed${st.running === true ? ', running' : st.running === false ? ', not running' : ''}` : 'not installed'}.`
591
+ );
592
+ return 0;
593
+ }
594
+
595
+ /** @param {import('./args').BridgeArgs} args @param {ReturnType<typeof withDefaults>} d */
596
+ async function logoutCommand(args, d) {
597
+ const { servers } = readSettings(d.settingsFile);
598
+ const targets = args.serverExplicit ? servers.filter((c) => args.servers.includes(c.server)) : servers;
599
+ if (!targets.length) {
600
+ d.logger.info(args.serverExplicit ? `Not paired with ${args.servers.join(', ')}.` : 'Not paired.');
601
+ return 0;
602
+ }
603
+ for (const c of targets) {
604
+ try {
605
+ await d.makeApi(c.server, c.token).post('/api/bridge/result', { action: 'logout' });
606
+ } catch {
607
+ // The credential is deleted either way; the server revokes an unreachable device on its own terms.
608
+ }
609
+ deleteBridgeConfig(c.server, d.settingsFile);
610
+ d.logger.info(`Logged out of ${c.server}.`);
611
+ }
612
+ // Nothing left to serve: the settings go too (the next --install-service writes them again).
613
+ if (!readSettings(d.settingsFile).servers.length) deleteBridgeConfig(undefined, d.settingsFile);
614
+ return 0;
615
+ }
616
+
617
+ /**
618
+ * @param {string[]} argv arguments after `bridge`
619
+ * @param {CliDeps} [raw] injected for tests
620
+ * @returns {Promise<number>} exit code
621
+ */
622
+ async function runBridgeCli(argv, raw = {}) {
623
+ const d = withDefaults(raw);
624
+ const args = parseBridgeArgs(argv, d.env);
625
+
626
+ if (args.command === 'help') {
627
+ d.logger.info(USAGE);
628
+ return 0;
629
+ }
630
+ if (args.errors.length) {
631
+ for (const e of args.errors) d.logger.error(e);
632
+ d.logger.error('\nRun `bt-agent bridge --help` for usage.');
633
+ return 2;
634
+ }
635
+
636
+ try {
637
+ switch (args.command) {
638
+ case 'status':
639
+ return statusCommand(args, d);
640
+ case 'logout':
641
+ return await logoutCommand(args, d);
642
+ case 'install-service':
643
+ return await installServiceCommand(args, d);
644
+ case 'uninstall-service':
645
+ return uninstallServiceCommand(d);
646
+ case 'service':
647
+ return await serviceModeCommand(d, raw);
648
+ default:
649
+ return await runForegroundCommand(args, d, raw);
650
+ }
651
+ } catch (err) {
652
+ if (err instanceof UpdateRequiredError) {
653
+ d.logger.error(err.message);
654
+ d.logger.error('Update the Desktop Agent: copy the install command from the Unity Bridge dialog again.');
655
+ return 1;
656
+ }
657
+ if (err instanceof NotPairedError) {
658
+ d.logger.error('The App Builder refused this computer. Copy the install command from the Unity Bridge dialog again.');
659
+ return 1;
660
+ }
661
+ d.logger.error(err && err.message ? err.message : String(err));
662
+ return 1;
663
+ }
664
+ }
665
+
666
+ module.exports = {
667
+ runBridgeCli,
668
+ USAGE,
669
+ serve,
670
+ pairRequested,
671
+ resolveServiceFolders,
672
+ makeExecuteDispatch,
673
+ makeDevServerProbe,
674
+ makeHello,
675
+ projectsFolderLine,
676
+ NO_PROJECT,
677
+ };