@babylonjs-toolkit/agent 1.1.38 → 1.1.44

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,606 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Finds the Unity CLI and the Unity projects this computer serves (T24 step 3, D51).
5
+ *
6
+ * Everything here is read-only: it reads a handful of text files and runs `unity --version`.
7
+ */
8
+
9
+ const crypto = require('crypto');
10
+ const fs = require('fs');
11
+ const os = require('os');
12
+ const path = require('path');
13
+ const { execFileSync } = require('child_process');
14
+ const { compareVersions } = require('./guard');
15
+ const { BRIDGE_TOOLKIT_MIN_VERSION } = require('../protocol');
16
+
17
+ const TOOLKIT_PACKAGE = 'com.babylontoolkit.editor';
18
+ const PIPELINE_PACKAGE = 'com.unity.pipeline';
19
+
20
+ /**
21
+ * @typedef {{ key: string, name: string, root: string, productGuid?: string, unityVersion?: string, toolkitVersion?: string, pipelineVersion?: string }} DiscoveredProject
22
+ * @typedef {(file: string, args: string[]) => string|undefined} Exec stdout, or undefined on any failure
23
+ */
24
+
25
+ /** @type {Exec} */
26
+ function defaultExec(file, args) {
27
+ try {
28
+ return execFileSync(file, args, {
29
+ encoding: 'utf8',
30
+ timeout: 15_000,
31
+ stdio: ['ignore', 'pipe', 'ignore'],
32
+ windowsHide: true,
33
+ });
34
+ } catch {
35
+ return undefined;
36
+ }
37
+ }
38
+
39
+ /** @param {string} p */
40
+ function isFile(p) {
41
+ try {
42
+ return fs.statSync(p).isFile();
43
+ } catch {
44
+ return false;
45
+ }
46
+ }
47
+
48
+ /** @param {string} p */
49
+ function isDir(p) {
50
+ try {
51
+ return fs.statSync(p).isDirectory();
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
56
+
57
+ /** @param {string} p @returns {string|undefined} */
58
+ function readText(p) {
59
+ try {
60
+ return fs.readFileSync(p, 'utf8');
61
+ } catch {
62
+ return undefined;
63
+ }
64
+ }
65
+
66
+ /** @param {string} p @returns {any} */
67
+ function readJson(p) {
68
+ const text = readText(p);
69
+ if (text === undefined) return undefined;
70
+ try {
71
+ return JSON.parse(text);
72
+ } catch {
73
+ return undefined;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * @param {{ env: Record<string, string|undefined>, platform: string, exec: Exec }} opts
79
+ * @returns {{ path: string, version: string } | undefined}
80
+ */
81
+ function findUnityCli({ env, platform, exec }) {
82
+ /** @type {string|undefined} */
83
+ let cliPath;
84
+ if (platform === 'win32') {
85
+ const local = env.LOCALAPPDATA;
86
+ const candidate = local ? path.win32.join(local, 'unity', 'bin', 'unity.exe') : undefined;
87
+ if (candidate && isFile(candidate)) cliPath = candidate;
88
+ } else {
89
+ const home = env.HOME || os.homedir();
90
+ const candidate = path.join(home, '.unity', 'bin', 'unity');
91
+ if (isFile(candidate)) cliPath = candidate;
92
+ }
93
+ if (!cliPath) {
94
+ const found = exec(platform === 'win32' ? 'where' : 'which', ['unity']);
95
+ const first = found && found.split(/\r?\n/).map((l) => l.trim()).find(Boolean);
96
+ if (first) cliPath = first;
97
+ }
98
+ if (!cliPath) return undefined;
99
+ const version = (exec(cliPath, ['--version']) || '').trim().split(/\r?\n/)[0].trim();
100
+ return { path: cliPath, version: version || 'unknown' };
101
+ }
102
+
103
+ /**
104
+ * A package's version from the lock file, then the manifest; a `file:` (local/embedded) reference is
105
+ * read from that package's own package.json, and an embedded package with no entry at all is read
106
+ * from `Packages/<name>/package.json`. A git package (D56 installs the Babylon Toolkit packages from git
107
+ * URLs) records the URL, not a version, in both files — its version is read from the copy UPM unpacked
108
+ * under `Library/PackageCache/<name>@<hash>/package.json`.
109
+ * @param {string} root
110
+ * @param {string} name
111
+ * @returns {string|undefined}
112
+ */
113
+ function packageVersion(root, name) {
114
+ const packagesDir = path.join(root, 'Packages');
115
+ /** @param {unknown} value @returns {string|undefined} */
116
+ const fromValue = (value) => {
117
+ if (typeof value !== 'string') return undefined;
118
+ if (/^\d/.test(value)) return value;
119
+ if (value.startsWith('file:')) {
120
+ const pkg = readJson(path.join(path.resolve(packagesDir, value.slice(5)), 'package.json'));
121
+ if (pkg && typeof pkg.version === 'string' && /^\d/.test(pkg.version)) return pkg.version;
122
+ }
123
+ return undefined;
124
+ };
125
+
126
+ const lock = readJson(path.join(packagesDir, 'packages-lock.json'));
127
+ const locked = lock && lock.dependencies && lock.dependencies[name];
128
+ const fromLock = fromValue(locked && locked.version);
129
+ if (fromLock) return fromLock;
130
+
131
+ const manifest = readJson(path.join(packagesDir, 'manifest.json'));
132
+ const fromManifest = fromValue(manifest && manifest.dependencies && manifest.dependencies[name]);
133
+ if (fromManifest) return fromManifest;
134
+
135
+ const embedded = readJson(path.join(packagesDir, name, 'package.json'));
136
+ if (embedded && typeof embedded.version === 'string' && /^\d/.test(embedded.version)) return embedded.version;
137
+
138
+ const isGit = (/** @type {unknown} */ v) => typeof v === 'string' && /(^git\+|^git@|\.git(#.*)?$)/.test(v);
139
+ if (isGit(locked && locked.version) || isGit(manifest && manifest.dependencies && manifest.dependencies[name])) {
140
+ let entries = [];
141
+ try {
142
+ entries = fs.readdirSync(path.join(root, 'Library', 'PackageCache')).filter((e) => e.startsWith(`${name}@`)).sort();
143
+ } catch {
144
+ entries = [];
145
+ }
146
+ for (const e of entries) {
147
+ const cached = readJson(path.join(root, 'Library', 'PackageCache', e, 'package.json'));
148
+ if (cached && typeof cached.version === 'string' && /^\d/.test(cached.version)) return cached.version;
149
+ }
150
+ }
151
+ return undefined;
152
+ }
153
+
154
+ /**
155
+ * @param {string} root an existing Unity project directory
156
+ * @returns {DiscoveredProject}
157
+ */
158
+ function describeProject(root) {
159
+ const real = fs.realpathSync(root);
160
+ /** @type {DiscoveredProject} */
161
+ const project = {
162
+ key: crypto.createHash('sha256').update(real).digest('hex').slice(0, 12),
163
+ name: path.basename(real),
164
+ root: real,
165
+ };
166
+
167
+ const versionText = readText(path.join(real, 'ProjectSettings', 'ProjectVersion.txt')) || '';
168
+ const editor = /^m_EditorVersion:\s*(\S+)\s*$/m.exec(versionText);
169
+ if (editor) project.unityVersion = editor[1];
170
+
171
+ const settings = readText(path.join(real, 'ProjectSettings', 'ProjectSettings.asset')) || '';
172
+ const guid = /^\s*productGUID:\s*([0-9a-fA-F]{32})\s*$/m.exec(settings);
173
+ if (guid) project.productGuid = guid[1].toLowerCase();
174
+
175
+ const toolkit = packageVersion(real, TOOLKIT_PACKAGE);
176
+ if (toolkit) project.toolkitVersion = toolkit;
177
+ const pipeline = packageVersion(real, PIPELINE_PACKAGE);
178
+ if (pipeline) project.pipelineVersion = pipeline;
179
+
180
+ return project;
181
+ }
182
+
183
+ /** @param {string} dir */
184
+ function isUnityProject(dir) {
185
+ return isDir(path.join(dir, 'Assets')) && isFile(path.join(dir, 'ProjectSettings', 'ProjectVersion.txt'));
186
+ }
187
+
188
+ /** Hello's project list is bounded; a folder with more Unity projects than this lists the first by name. */
189
+ const MAX_LISTED_PROJECTS = 100;
190
+ const REDISCOVER_EVERY_MS = 30_000;
191
+
192
+ /** @param {string} p @returns {string} */
193
+ function realOrResolved(p) {
194
+ const abs = path.resolve(p);
195
+ try {
196
+ return fs.realpathSync(abs);
197
+ } catch {
198
+ return abs;
199
+ }
200
+ }
201
+
202
+ /**
203
+ * The Unity projects DIRECTLY inside `folder` (one level, D54), sorted by name. Hidden folders are skipped.
204
+ * @param {string} folder
205
+ * @returns {DiscoveredProject[]}
206
+ */
207
+ function listProjectsIn(folder) {
208
+ let names;
209
+ try {
210
+ names = fs.readdirSync(folder);
211
+ } catch {
212
+ return [];
213
+ }
214
+ /** @type {DiscoveredProject[]} */
215
+ const out = [];
216
+ for (const name of names.sort((a, b) => a.localeCompare(b))) {
217
+ if (name.startsWith('.')) continue;
218
+ const dir = path.join(folder, name);
219
+ if (!isUnityProject(dir)) continue;
220
+ out.push(describeProject(dir));
221
+ if (out.length >= MAX_LISTED_PROJECTS) break;
222
+ }
223
+ return out;
224
+ }
225
+
226
+ /**
227
+ * Where the Unity projects live (D54): `--projects <folder>` when given; otherwise the current directory,
228
+ * unless it is itself a Unity project — then its parent is the folder and it is the current project.
229
+ * @param {{ projectsDir?: string, cwd: string }} opts
230
+ * @returns {{ folder: string, currentRoot?: string }}
231
+ */
232
+ function resolveProjectsFolder({ projectsDir, cwd }) {
233
+ if (projectsDir) return { folder: realOrResolved(path.resolve(cwd, projectsDir)) };
234
+ const here = realOrResolved(cwd);
235
+ if (isUnityProject(here)) return { folder: path.dirname(here), currentRoot: here };
236
+ return { folder: here };
237
+ }
238
+
239
+ /**
240
+ * @param {{
241
+ * unityPaths?: string[],
242
+ * projectsDir?: string|string[],
243
+ * cwd?: string,
244
+ * env?: Record<string, string|undefined>,
245
+ * platform?: string,
246
+ * exec?: Exec,
247
+ * }} opts
248
+ * `projectsDir` may name several folders (D55 — `--projects` is repeatable); the first is where
249
+ * `unity_project create` makes new projects, and projects are listed across all of them.
250
+ * @returns {{
251
+ * cli?: { path: string, version: string },
252
+ * projectsDir: string,
253
+ * projectsDirs: string[],
254
+ * missingDirs: string[],
255
+ * projectsDirMissing: boolean,
256
+ * projects: DiscoveredProject[],
257
+ * folderProjectCount: number,
258
+ * extraRoots: string[],
259
+ * currentRoot?: string,
260
+ * notProjects: string[],
261
+ * }}
262
+ */
263
+ function discoverUnity({
264
+ unityPaths,
265
+ projectsDir,
266
+ cwd = process.cwd(),
267
+ env = process.env,
268
+ platform = process.platform,
269
+ exec = defaultExec,
270
+ } = {}) {
271
+ const requested = (Array.isArray(projectsDir) ? projectsDir : projectsDir ? [projectsDir] : []).filter(Boolean);
272
+ /** @type {string[]} */
273
+ const folders = [];
274
+ /** @type {string|undefined} */
275
+ let currentRoot;
276
+ if (requested.length) {
277
+ for (const dir of requested) {
278
+ const folder = resolveProjectsFolder({ projectsDir: dir, cwd }).folder;
279
+ if (!folders.includes(folder)) folders.push(folder);
280
+ }
281
+ } else {
282
+ const here = resolveProjectsFolder({ cwd });
283
+ folders.push(here.folder);
284
+ currentRoot = here.currentRoot;
285
+ }
286
+
287
+ /** @type {string[]} */
288
+ const extraRoots = [];
289
+ /** @type {string[]} */
290
+ const notProjects = [];
291
+ for (const p of Array.isArray(unityPaths) ? unityPaths : []) {
292
+ const dir = path.resolve(cwd, p);
293
+ if (!isUnityProject(dir)) {
294
+ notProjects.push(dir);
295
+ continue;
296
+ }
297
+ const real = realOrResolved(dir);
298
+ if (!extraRoots.includes(real)) extraRoots.push(real);
299
+ }
300
+ // The first --unity project is current (D54); it wins over the folder the helper was started in.
301
+ if (extraRoots.length) currentRoot = extraRoots[0];
302
+
303
+ const listed = folders.flatMap((f) => listProjectsIn(f));
304
+ const projects = mergeProjects(listed, extraRoots);
305
+ const cli = findUnityCli({ env, platform, exec });
306
+ const missingDirs = folders.filter((f) => !isDir(f));
307
+ /** @type {ReturnType<typeof discoverUnity>} */
308
+ const out = {
309
+ projectsDir: folders[0],
310
+ projectsDirs: folders,
311
+ missingDirs,
312
+ projectsDirMissing: missingDirs.length > 0,
313
+ projects,
314
+ // how many of `projects` are IN the projects folder; the rest came from --unity paths
315
+ folderProjectCount: listed.length,
316
+ extraRoots,
317
+ notProjects,
318
+ };
319
+ if (currentRoot) out.currentRoot = currentRoot;
320
+ if (cli) out.cli = cli;
321
+ return out;
322
+ }
323
+
324
+ /**
325
+ * @param {DiscoveredProject[]} listed
326
+ * @param {string[]} extraRoots
327
+ * @returns {DiscoveredProject[]}
328
+ */
329
+ function mergeProjects(listed, extraRoots) {
330
+ const projects = [...listed];
331
+ for (const root of extraRoots) {
332
+ if (!isUnityProject(root)) continue;
333
+ const project = describeProject(root);
334
+ if (!projects.some((p) => p.key === project.key)) projects.push(project);
335
+ }
336
+ return projects;
337
+ }
338
+
339
+ /**
340
+ * The helper's in-memory view of the projects folder and the CURRENT project (D54). The current project
341
+ * is set by `unity.project open|create` (or at start-up from the folder / the first --unity path); every
342
+ * other Unity and Blender job runs against it. The workspace writes nothing itself; `onCurrentChange` lets the
343
+ * caller persist the current project (bridge.json) so a restarted service keeps it.
344
+ *
345
+ * With several projects folders (D55) projects are listed across all of them; a name found in more
346
+ * than one is ambiguous and must be given as `<folder>/<name>` (see `resolve`).
347
+ *
348
+ * @param {{
349
+ * projectsDir: string,
350
+ * projectsDirs?: string[],
351
+ * extraRoots?: string[],
352
+ * currentRoot?: string,
353
+ * projects?: DiscoveredProject[],
354
+ * onCurrentChange?: (root: string) => void,
355
+ * now?: () => number,
356
+ * everyMs?: number,
357
+ * platform?: string,
358
+ * }} opts
359
+ */
360
+ function createWorkspace({
361
+ projectsDir,
362
+ projectsDirs,
363
+ extraRoots = [],
364
+ currentRoot,
365
+ projects,
366
+ onCurrentChange,
367
+ now = Date.now,
368
+ everyMs = REDISCOVER_EVERY_MS,
369
+ platform = process.platform,
370
+ }) {
371
+ /** @type {string[]} */
372
+ const folders = [];
373
+ for (const f of projectsDirs && projectsDirs.length ? projectsDirs : [projectsDir]) {
374
+ const real = realOrResolved(f);
375
+ if (!folders.includes(real)) folders.push(real);
376
+ }
377
+ const folder = folders[0];
378
+ /** @type {DiscoveredProject[]} */
379
+ let cache = projects ? [...projects] : [];
380
+ let at = projects ? now() : -Infinity;
381
+ /** @type {string|undefined} */
382
+ let current = currentRoot ? realOrResolved(currentRoot) : undefined;
383
+ const caseless = platform === 'darwin' || platform === 'win32';
384
+
385
+ const refresh = () => {
386
+ cache = mergeProjects(folders.flatMap((f) => listProjectsIn(f)), extraRoots);
387
+ at = now();
388
+ return cache;
389
+ };
390
+
391
+ const list = () => (now() - at >= everyMs ? refresh() : cache);
392
+
393
+ /** @param {string} s */
394
+ const plain = (s) => typeof s === 'string' && s.length > 0 && !s.startsWith('.') && !s.includes('/') && !s.includes('\\') && !s.includes('..');
395
+
396
+ /**
397
+ * Candidates for a name among `known`: exact matches, else (macOS/Windows) case-insensitive ones.
398
+ * @param {DiscoveredProject[]} known @param {string} name
399
+ */
400
+ const matching = (known, name) => {
401
+ const exact = known.filter((p) => p.name === name);
402
+ if (exact.length || !caseless) return exact;
403
+ const lower = name.toLowerCase();
404
+ return known.filter((p) => p.name.toLowerCase() === lower);
405
+ };
406
+
407
+ /**
408
+ * The project a name means — one of the DISCOVERED projects only (directly inside a projects folder,
409
+ * or a --unity path), never a path. `<folder>/<name>` picks the projects folder by its name when the
410
+ * same project name exists in more than one.
411
+ * @param {string} name
412
+ * @returns {{ root: string } | { ambiguous: string[] } | null}
413
+ */
414
+ const resolve = (name) => {
415
+ if (typeof name !== 'string' || !name) return null;
416
+ const known = refresh();
417
+ const slash = name.indexOf('/');
418
+ if (slash > 0) {
419
+ const folderName = name.slice(0, slash);
420
+ const projectName = name.slice(slash + 1);
421
+ if (!plain(folderName) || !plain(projectName)) return null;
422
+ const sameFolder = (/** @type {string} */ f) =>
423
+ path.basename(f) === folderName || (caseless && path.basename(f).toLowerCase() === folderName.toLowerCase());
424
+ const inFolder = known.filter((p) => folders.some((f) => sameFolder(f) && path.dirname(p.root) === f));
425
+ const found = matching(inFolder, projectName);
426
+ return found.length ? { root: found[0].root } : null;
427
+ }
428
+ if (!plain(name)) return null;
429
+ const found = matching(known, name);
430
+ if (!found.length) return null;
431
+ if (found.length === 1) return { root: found[0].root };
432
+ return { ambiguous: [...new Set(found.map((p) => path.basename(path.dirname(p.root))))] };
433
+ };
434
+
435
+ return {
436
+ /** the FIRST projects folder's absolute path — where new projects are created (never sent to the App Builder) */
437
+ projectsDir: folder,
438
+ /** every projects folder, absolute */
439
+ projectsDirs: folders,
440
+ /** the projects folders' names — the only part of them hello carries */
441
+ projectsDirName: folders.map((f) => path.basename(f)).join(', '),
442
+ refresh,
443
+ /** the known projects, re-discovered at most every 30 s */
444
+ projects: list,
445
+ /** @returns {DiscoveredProject|undefined} */
446
+ current() {
447
+ if (!current) return undefined;
448
+ const found = list().find((p) => p.root === current);
449
+ if (found) return found;
450
+ if (!isUnityProject(current)) return undefined;
451
+ return describeProject(current);
452
+ },
453
+ /** @param {string} root */
454
+ setCurrent(root) {
455
+ const next = realOrResolved(root);
456
+ const changed = next !== current;
457
+ current = next;
458
+ refresh();
459
+ // persisted by the caller (bridge.json) so a restarted service keeps the current project
460
+ if (changed && onCurrentChange) onCurrentChange(next);
461
+ },
462
+ resolve,
463
+ /**
464
+ * The project directory a name means (see `resolve`); undefined when unknown OR ambiguous.
465
+ * @param {string} name
466
+ * @returns {string|undefined}
467
+ */
468
+ rootFor(name) {
469
+ const r = resolve(name);
470
+ return r && 'root' in r ? r.root : undefined;
471
+ },
472
+ };
473
+ }
474
+
475
+ /** @typedef {ReturnType<typeof createWorkspace>} Workspace */
476
+
477
+ /**
478
+ * `bt_devserver_status` prints `key : value` lines (with `--result-only`, as one JSON string).
479
+ * @param {string} stdout
480
+ * @returns {Record<string, string>}
481
+ */
482
+ function parseKeyValues(stdout) {
483
+ let text = String(stdout || '').trim();
484
+ try {
485
+ const parsed = JSON.parse(text);
486
+ if (typeof parsed === 'string') text = parsed;
487
+ else if (parsed && typeof parsed === 'object') {
488
+ const r = parsed.data && parsed.data.result !== undefined ? parsed.data.result : parsed.result;
489
+ if (typeof r === 'string') text = r;
490
+ }
491
+ } catch {
492
+ // plain text already
493
+ }
494
+ /** @type {Record<string, string>} */
495
+ const out = {};
496
+ for (const line of text.split(/\r?\n/)) {
497
+ const i = line.indexOf(':');
498
+ if (i <= 0) continue;
499
+ out[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim();
500
+ }
501
+ return out;
502
+ }
503
+
504
+ /**
505
+ * The exported `.gltf`/`.glb` scene names (at most 20) of a dev server root.
506
+ * @param {string[]} roots candidate `<root>` directories, first readable wins
507
+ * @returns {string[]}
508
+ */
509
+ function listScenes(roots) {
510
+ for (const root of roots) {
511
+ let names;
512
+ try {
513
+ names = fs.readdirSync(path.join(root, 'scenes'));
514
+ } catch {
515
+ continue;
516
+ }
517
+ return names.filter((n) => /\.(gltf|glb)$/i.test(n)).sort().slice(0, 20);
518
+ }
519
+ return [];
520
+ }
521
+
522
+ /** An answer that says the Editor has no such command (the Toolkit is missing, too old, or not compiled in). */
523
+ const UNKNOWN_COMMAND = /no command named|unknown command/i;
524
+
525
+ /**
526
+ * How long an unknown-command answer is remembered (verifier, 2026-09-29): long enough that a project without
527
+ * the Toolkit command is not asked on every hello, short enough that a project whose Toolkit was just added
528
+ * (package_add — the Editor still compiling when first asked) recovers without restarting the helper.
529
+ */
530
+ const UNKNOWN_COMMAND_MEMORY_MS = 5 * 60_000;
531
+
532
+ /**
533
+ * Hello's `devServer` for a project (T24 step 7). Any error → `{ running: false }`.
534
+ *
535
+ * `bt_devserver_status` is a Babylon Toolkit command, and asking an Editor that does not have it prints
536
+ * "No command named 'bt_devserver_status'" into the user's Unity console on every hello. So it is asked
537
+ * only when the project's Toolkit is at least BRIDGE_TOOLKIT_MIN_VERSION (the version that has it); an
538
+ * unknown-command answer is remembered in `memo` for that project + Toolkit version and not asked again
539
+ * until the version changes or UNKNOWN_COMMAND_MEMORY_MS passes; and a project whose create scaffold is still running (`busy`) is never
540
+ * asked. Every skipped case is `{ running: false }` with no Unity call.
541
+ * @param {{
542
+ * cli?: { path: string },
543
+ * project: { root: string, toolkitVersion?: string },
544
+ * runProcess: import('./run').RunProcess,
545
+ * memo?: Map<string, number>,
546
+ * busy?: (root: string) => boolean,
547
+ * now?: () => number,
548
+ * }} opts
549
+ * @returns {Promise<import('../protocol').BridgeDevServerInfo>}
550
+ */
551
+ async function probeDevServer({ cli, project, runProcess, memo, busy, now = Date.now }) {
552
+ if (!cli || !project) return { running: false };
553
+ if (busy && busy(project.root)) return { running: false };
554
+ const toolkit = project.toolkitVersion;
555
+ if (!toolkit || compareVersions(toolkit, BRIDGE_TOOLKIT_MIN_VERSION) < 0) return { running: false };
556
+ const key = `${project.root}\0${toolkit}`;
557
+ if (memo && memo.has(key)) {
558
+ if (now() - /** @type {number} */ (memo.get(key)) < UNKNOWN_COMMAND_MEMORY_MS) return { running: false };
559
+ memo.delete(key);
560
+ }
561
+ try {
562
+ const res = await runProcess(
563
+ cli.path,
564
+ ['command', 'bt_devserver_status', '--project-path', project.root, '--result-only'],
565
+ { cwd: project.root, timeoutMs: 5_000 }
566
+ );
567
+ if (UNKNOWN_COMMAND.test(`${res.stdout || ''}\n${res.stderr || ''}`)) {
568
+ if (memo) {
569
+ // one entry per project: a newer Toolkit version replaces the old one
570
+ for (const k of [...memo.keys()]) if (k.startsWith(`${project.root}\0`)) memo.delete(k);
571
+ memo.set(key, now());
572
+ }
573
+ return { running: false };
574
+ }
575
+ if (res.timedOut || res.code !== 0) return { running: false };
576
+ const kv = parseKeyValues(res.stdout);
577
+ const started = /^(true|yes|1)$/i.test(kv.started || '');
578
+ const port = parseInt(kv.port || '', 10);
579
+ if (!started || !Number.isInteger(port) || port <= 0) return { running: false };
580
+ /** @type {import('../protocol').BridgeDevServerInfo} */
581
+ const info = { running: true, origin: `http://localhost:${port}` };
582
+ if (kv.project) info.project = kv.project;
583
+ if (kv.listen === 'loopback' || kv.listen === 'all') info.listen = kv.listen;
584
+ const roots = [kv.root, path.join(project.root, 'Export'), path.join(project.root, 'export')].filter(Boolean);
585
+ info.scenes = listScenes(/** @type {string[]} */ (roots));
586
+ return info;
587
+ } catch {
588
+ return { running: false };
589
+ }
590
+ }
591
+
592
+ module.exports = {
593
+ discoverUnity,
594
+ createWorkspace,
595
+ listProjectsIn,
596
+ resolveProjectsFolder,
597
+ MAX_LISTED_PROJECTS,
598
+ REDISCOVER_EVERY_MS,
599
+ describeProject,
600
+ packageVersion,
601
+ isUnityProject,
602
+ findUnityCli,
603
+ probeDevServer,
604
+ UNKNOWN_COMMAND_MEMORY_MS,
605
+ parseKeyValues,
606
+ };