@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,1294 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Runs one Unity Bridge job on this computer (T24 step 6).
5
+ *
6
+ * Order: the helper's own guard (tiers, paths, toolkit floor, unsaved work — D3/D39) → `started` →
7
+ * one `log.op` line → the operation → `final`. A refusal is reported as `refused` BEFORE anything runs,
8
+ * which the App Builder records as refused (nothing ran).
9
+ *
10
+ * Every Unity CLI call carries `--format json --non-interactive` and never `--yes` (D41), runs without a
11
+ * shell, and has a hard timeout (120 s ordinary, 1800 s long).
12
+ */
13
+
14
+ const fs = require('fs');
15
+ const path = require('path');
16
+
17
+ const defaultLog = require('../log');
18
+ const { capText, BRIDGE_MAX_IMAGE_BASE64, isSafeJobId } = require('../protocol');
19
+ const { PATH_PARAMS, isLongOperation } = require('../policy');
20
+ const { helperTier, resolveProjectPath, pruneEmptyScratchDirs, dirtyScenes, unsavedWorkReason } = require('./guard');
21
+ const { runProcess: defaultRunProcess, launchDetached: defaultLaunchDetached } = require('./run');
22
+ const { ensureAutomation: defaultEnsureAutomation } = require('./automation');
23
+ const { packageVersion, isUnityProject } = require('./discover');
24
+
25
+ const ORDINARY_TIMEOUT_MS = 120_000;
26
+ const LONG_TIMEOUT_MS = 1_800_000;
27
+ const PROGRESS_EVERY_MS = 500;
28
+ const EDITOR_POLL_MS = 5_000;
29
+ const EDITOR_OPEN_WAIT_MS = 180_000;
30
+ const CANCELLED = 'Cancel requested — Unity may still finish the operation.';
31
+ const NO_CLI =
32
+ 'The Unity command-line tool (unity) was not found on this computer. Install it, then run bt-agent bridge again.';
33
+ const NO_PROJECT = 'No Unity project is open. Use unity_project to open or create one.';
34
+ const PIPELINE_PACKAGE = 'com.unity.pipeline';
35
+
36
+ // ── D56: `unity_project create` = the Agent Reference's Babylon Toolkit scaffold (unity-exporter-cli.md §4, §4B.4) ──
37
+ const GIT_MISSING = 'git is not on PATH — Unity needs it to install packages from git URLs. Install git and try again.';
38
+ /** The two Babylon Toolkit packages, in install order (the Khronos glTF package first — the toolkit builds on it). */
39
+ const TOOLKIT_PACKAGES = [
40
+ { name: 'org.khronos.unitygltf', url: 'https://github.com/babylontoolkit/unitygltf.git' },
41
+ { name: 'com.babylontoolkit.editor', url: 'https://github.com/babylontoolkit/professionaledition.git' },
42
+ ];
43
+ const SCAFFOLD_STEPS = 10;
44
+ const SCAFFOLD_POLL_MS = 5_000;
45
+ /** Each package add, and the exporter compile, is bounded at 15 min (§4.1); the whole create at 30 min (D56). */
46
+ const PACKAGE_WAIT_MS = 15 * 60_000;
47
+ const CREATE_BUDGET_MS = 30 * 60_000;
48
+ /** A brand-new project's first open imports every asset before the Editor reports ready. */
49
+ const CREATE_OPEN_WAIT_MS = 10 * 60_000;
50
+ const NPM_TIMEOUT_MS = 10 * 60_000;
51
+ /**
52
+ * The helper's own fixed C# — copied verbatim from AgentReference `references/scripts/` (see each file's
53
+ * header). They run whatever the Allow scripts switch says and even when the user started the helper with
54
+ * --no-scripts (D58): both gate scripts the MODEL supplies (unity_script), and these are part of the helper,
55
+ * not something a job can change.
56
+ */
57
+ const SCAFFOLD_DIR = path.join(__dirname, 'scaffold');
58
+ const BOOTSTRAP_CS = path.join(SCAFFOLD_DIR, 'bt-bootstrap.cs');
59
+ const NEWSCENE_CS = path.join(SCAFFOLD_DIR, 'bt-newscene.cs');
60
+ const STARTER_SCENE = 'Assets/Scenes/Level01.unity';
61
+ /** §4.1: the real success condition — the exporter type compiled into the Editor's domain. */
62
+ const EXPORTER_COMPILED_CS =
63
+ 'foreach (var a in System.AppDomain.CurrentDomain.GetAssemblies()) if (a.GetType("CanvasTools.CanvasToolsExporter") != null) return "READY"; return "no";';
64
+ /** §4.2: both toolkit packages registered. */
65
+ const PACKAGES_REGISTERED_CS =
66
+ 'var r = ""; foreach (var n in new[]{"org.khronos.unitygltf","com.babylontoolkit.editor"}) r += n + "=" + (UnityEditor.PackageManager.PackageInfo.FindForAssetPath("Packages/" + n + "/package.json") != null) + "; "; return r;';
67
+ /** §4.2: the one that matters — did the exporter compile in? */
68
+ const EXPORTER_ASSEMBLY_CS = 'return typeof(CanvasTools.CanvasToolsExporter).Assembly.FullName;';
69
+ /** bt-new-unity-project.sh's VERIFY line (pro / tsc / exportRoot / scene). */
70
+ const SCAFFOLD_VERIFY_CS =
71
+ 'string r = UnityTools.GetRootPath(); return "pro=" + ToolkitManager.IsPro() + " tsc=" + System.IO.File.Exists(System.IO.Path.Combine(r, CanvasTools.CVPanel.TscLocalPath)) + " exportRoot=" + CanvasToolsInfo.DefaultProjectFolder + " scene=" + UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene().path;';
72
+
73
+ /**
74
+ * @typedef {import('../protocol').BridgeDispatch} BridgeDispatch
75
+ * @typedef {import('../protocol').BridgeJobEvent} BridgeJobEvent
76
+ * @typedef {import('../protocol').BridgeResultPayload} BridgeResultPayload
77
+ * @typedef {import('./run').RunProcess} RunProcess
78
+ * @typedef {import('./run').RunResult} RunResult
79
+ * @typedef {{ key: string, name: string, root: string, productGuid?: string, toolkitVersion?: string }} LocalProject
80
+ * @typedef {{
81
+ * project: LocalProject,
82
+ * cli?: { path: string, version: string },
83
+ * emit: (event: BridgeJobEvent) => Promise<void>,
84
+ * signal?: AbortSignal,
85
+ * noScripts?: boolean,
86
+ * runProcess?: RunProcess,
87
+ * launch?: import('./run').LaunchDetached,
88
+ * api?: { post: (path: string, body: unknown, signal?: AbortSignal) => Promise<{ status: number, body: any }> },
89
+ * ensureAutomation?: typeof defaultEnsureAutomation,
90
+ * log?: { info: (m: string) => void, op: (tier: string, label: string) => void, error?: (m: string) => void },
91
+ * now?: () => number,
92
+ * sleep?: (ms: number, signal?: AbortSignal) => Promise<void>,
93
+ * }} UnityDeps
94
+ */
95
+
96
+ /** Does this Node hand JSON.parse revivers the source text (Node 21+)? */
97
+ const REVIVER_HAS_SOURCE = (() => {
98
+ let seen = false;
99
+ JSON.parse('1', (_k, v, ctx) => ((seen = Boolean(ctx && ctx.source === '1')), v));
100
+ return seen;
101
+ })();
102
+
103
+ /**
104
+ * JSON.parse that keeps 64-bit integers exact: Unity instance ids (e.g. 568105584918862612) are beyond
105
+ * Number's safe range, and a rounded id handed back to the model names a different object — or none.
106
+ * They come back as strings, which is how the CLI passes them anyway.
107
+ * @param {string} text
108
+ * @returns {any}
109
+ */
110
+ function parseJsonExact(text) {
111
+ if (REVIVER_HAS_SOURCE) {
112
+ return JSON.parse(text, (_k, v, ctx) =>
113
+ typeof v === 'number' && !Number.isSafeInteger(v) && ctx && /^-?\d+$/.test(ctx.source) ? ctx.source : v
114
+ );
115
+ }
116
+ return JSON.parse(text.replace(/([:\[,]\s*)(-?\d{16,})(?=\s*[,\]}])/g, '$1"$2"'));
117
+ }
118
+
119
+ /** @param {string} stdout @returns {any} */
120
+ function parseEnvelope(stdout) {
121
+ try {
122
+ const v = parseJsonExact(stdout);
123
+ return v && typeof v === 'object' ? v : undefined;
124
+ } catch {
125
+ return undefined;
126
+ }
127
+ }
128
+
129
+ /** @param {unknown} value a command result → text for the model (a string result is shown as is) */
130
+ function resultText(value) {
131
+ return typeof value === 'string' ? value : JSON.stringify(value, null, 2);
132
+ }
133
+
134
+ /** @param {any} env @returns {string} */
135
+ function firstError(env) {
136
+ const first = env && Array.isArray(env.errors) ? env.errors[0] : undefined;
137
+ if (first && typeof first.message === 'string') return first.message;
138
+ if (typeof first === 'string') return first;
139
+ return 'Unity reported a failure.';
140
+ }
141
+
142
+ /** @param {RunResult} res */
143
+ function rawText(res) {
144
+ return [res.stdout, res.stderr].filter((s) => s && s.trim()).join('\n').trim();
145
+ }
146
+
147
+ /** @param {number} ms @param {AbortSignal} [signal] */
148
+ function defaultSleep(ms, signal) {
149
+ return new Promise((resolve) => {
150
+ if (signal && signal.aborted) return resolve();
151
+ const timer = setTimeout(done, ms);
152
+ function done() {
153
+ clearTimeout(timer);
154
+ if (signal) signal.removeEventListener('abort', done);
155
+ resolve();
156
+ }
157
+ if (signal) signal.addEventListener('abort', done, { once: true });
158
+ });
159
+ }
160
+
161
+ /** @param {string} a @param {string} b */
162
+ function samePath(a, b) {
163
+ const norm = (/** @type {string} */ p) => {
164
+ let r = path.resolve(p);
165
+ try {
166
+ r = fs.realpathSync(r);
167
+ } catch {
168
+ // keep the resolved path
169
+ }
170
+ return process.platform === 'darwin' || process.platform === 'win32' ? r.toLowerCase() : r;
171
+ };
172
+ return norm(a) === norm(b);
173
+ }
174
+
175
+ /** @param {unknown} value @returns {string} */
176
+ function paramValue(value) {
177
+ return value !== null && typeof value === 'object' ? JSON.stringify(value) : String(value);
178
+ }
179
+
180
+ /** @param {string} p */
181
+ function removeQuietly(p) {
182
+ try {
183
+ fs.rmSync(p, { force: true });
184
+ } catch {
185
+ // scratch clean-up is best effort
186
+ }
187
+ }
188
+
189
+ /**
190
+ * The npm to run `npm install` with (D56 step 8): the npm that ships next to this Node when it is there —
191
+ * run as `<node> <npm-cli.js>`, so no shell and no `.cmd` shim is needed on Windows — else `npm` on PATH.
192
+ * @param {{ execPath?: string, platform?: NodeJS.Platform, exists?: (p: string) => boolean }} [opts]
193
+ * @returns {{ file: string, args: string[] }}
194
+ */
195
+ function resolveNpm({ execPath = process.execPath, platform = process.platform, exists = fs.existsSync } = {}) {
196
+ const dir = path.dirname(execPath);
197
+ const candidates =
198
+ platform === 'win32'
199
+ ? [path.join(dir, 'node_modules', 'npm', 'bin', 'npm-cli.js')]
200
+ : [path.join(dir, '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js'), path.join(dir, 'node_modules', 'npm', 'bin', 'npm-cli.js')];
201
+ const cli = candidates.find((c) => exists(c));
202
+ return cli ? { file: execPath, args: [path.resolve(cli), 'install'] } : { file: 'npm', args: ['install'] };
203
+ }
204
+
205
+ /**
206
+ * Is the package in this project at all — in the manifest, the lock file, or embedded? (A git package has
207
+ * no version in either file, so `packageVersion` alone cannot answer this.)
208
+ * @param {string} root @param {string} name
209
+ */
210
+ function hasPackage(root, name) {
211
+ const read = (/** @type {string} */ f) => {
212
+ try {
213
+ return JSON.parse(fs.readFileSync(f, 'utf8'));
214
+ } catch {
215
+ return undefined;
216
+ }
217
+ };
218
+ const manifest = read(path.join(root, 'Packages', 'manifest.json'));
219
+ if (manifest && manifest.dependencies && name in manifest.dependencies) return true;
220
+ const lock = read(path.join(root, 'Packages', 'packages-lock.json'));
221
+ if (lock && lock.dependencies && name in lock.dependencies) return true;
222
+ return fs.existsSync(path.join(root, 'Packages', name, 'package.json'));
223
+ }
224
+
225
+ /**
226
+ * An `eval` / `eval_file` envelope → the value the C# returned, or its error (a C# exception is outer
227
+ * `success:false`; a compile error can be `data.result.success:false`). Mirrors bt-new-unity-project.sh's `J`.
228
+ * @param {any} env
229
+ * @returns {{ ok: true, value: string } | { ok: false, error: string }}
230
+ */
231
+ function evalOutcome(env) {
232
+ if (!env) return { ok: false, error: 'unreachable' };
233
+ if (env.success !== true) return { ok: false, error: firstError(env) };
234
+ const inner = env.data && env.data.result;
235
+ if (inner && typeof inner === 'object' && inner.success === false) {
236
+ return { ok: false, error: typeof inner.error === 'string' && inner.error ? inner.error : 'Unity reported a failure.' };
237
+ }
238
+ const value = inner && typeof inner === 'object' && 'result' in inner ? inner.result : inner;
239
+ return { ok: true, value: value === undefined || value === null ? '' : typeof value === 'string' ? value : JSON.stringify(value) };
240
+ }
241
+
242
+ /**
243
+ * A `package_status` envelope → its status word (`idle` | `in_progress` | `completed` | `failed`), or
244
+ * undefined when the Editor could not be reached (a domain reload — "not yet", never a failure).
245
+ * @param {any} env
246
+ * @returns {{ status: string, text: string } | undefined}
247
+ */
248
+ function packageStatusOf(env) {
249
+ if (!env || env.success !== true) return undefined;
250
+ let v = env.data && env.data.result !== undefined ? env.data.result : env.data;
251
+ if (typeof v === 'string') {
252
+ try {
253
+ v = JSON.parse(v);
254
+ } catch {
255
+ // a plain word
256
+ }
257
+ }
258
+ const text = typeof v === 'string' ? v : JSON.stringify(v);
259
+ const status = v && typeof v === 'object' && typeof v.status === 'string' ? v.status : text;
260
+ return { status, text };
261
+ }
262
+
263
+ /** @param {number} ms */
264
+ function seconds(ms) {
265
+ return ms < 1000 ? '<1s' : ms < 60_000 ? `${Math.round(ms / 1000)}s` : `${Math.floor(ms / 60_000)}m${String(Math.round((ms % 60_000) / 1000)).padStart(2, '0')}s`;
266
+ }
267
+
268
+ /**
269
+ * @param {BridgeDispatch} dispatch
270
+ * @returns {string} the one-line description printed in the helper's terminal
271
+ */
272
+ function labelOf(dispatch) {
273
+ const op = /** @type {any} */ (dispatch.op);
274
+ switch (op.kind) {
275
+ case 'unity.command':
276
+ return `unity command ${op.name}`;
277
+ case 'unity.cli':
278
+ return `unity ${(op.args || []).join(' ')}`;
279
+ case 'unity.list':
280
+ return `unity command --query ${op.query || '(all)'}`;
281
+ case 'unity.script':
282
+ return `unity run_script ${op.entry}`;
283
+ case 'unity.capture':
284
+ return `unity screenshot ${op.view || 'game'} ${op.width}x${op.height}`;
285
+ case 'unity.editor':
286
+ return `unity editor ${op.action}`;
287
+ case 'unity.project':
288
+ return `unity project ${op.action}${op.name ? ` "${op.name}"` : ''}`;
289
+ default:
290
+ return op.kind;
291
+ }
292
+ }
293
+
294
+
295
+ /**
296
+ * Whether the Editor for `dir` ANSWERS commands yet (verifier, 2026-09-29): `unity status` lists an Editor as
297
+ * ready while the Pipeline still refuses commands with "Server Busy" (HTTP 503) as it settles after a launch,
298
+ * which cost the model a reopen. Ready = `editor_status` succeeds and reports neither compiling nor a domain
299
+ * reload; a busy answer, a failure or unreadable output is not ready.
300
+ * @param {import('./run').RunProcess} runProcess @param {string} cliPath @param {string} dir @param {AbortSignal} [signal]
301
+ * @returns {Promise<boolean>}
302
+ */
303
+ async function editorAnswers(runProcess, cliPath, dir, signal) {
304
+ let res;
305
+ try {
306
+ res = await runProcess(
307
+ cliPath,
308
+ ['command', 'editor_status', '--project-path', dir, '--timeout', '10', '--format', 'json', '--non-interactive'],
309
+ { cwd: dir, timeoutMs: 15_000, signal }
310
+ );
311
+ } catch {
312
+ return false;
313
+ }
314
+ if (res.timedOut || res.aborted) return false;
315
+ const env = parseEnvelope(res.stdout);
316
+ if (!env || env.success !== true) return false; // "Server Busy" (503, retryable) lands here
317
+ const r = env.data && env.data.result !== undefined ? env.data.result : env.data;
318
+ if (!r || typeof r !== 'object') return true;
319
+ return r.status !== 'compiling' && r.status !== 'reloading' && r.status !== 'busy' && r.compiling !== true && r.domainReloadInProgress !== true;
320
+ }
321
+
322
+ /** At or below this many matches `unity_list_commands` shows each command's parameters (T24-2). */
323
+ const LIST_FULL_DETAIL_MAX = 5;
324
+
325
+ /** @param {unknown} v */
326
+ const oneLine = (v) => String(v === undefined || v === null ? '' : v).replace(/\s+/g, ' ').trim();
327
+
328
+ /**
329
+ * One listed command: `name — description`, then (full detail only) one line per parameter —
330
+ * ` --name <type> (required|optional[, default x]) — description`.
331
+ * @param {any} c @returns {string}
332
+ */
333
+ function describeListedCommand(c) {
334
+ const head = `${c.name} — ${oneLine(c.description)}`;
335
+ if (!Array.isArray(c.parameters)) return head;
336
+ if (!c.parameters.length) return `${head}\n (no parameters)`;
337
+ const params = c.parameters.map((/** @type {any} */ p) => {
338
+ const req = p.required === true ? 'required' : 'optional';
339
+ const def = p.required !== true && p.defaultValue !== undefined && p.defaultValue !== null ? `, default ${oneLine(JSON.stringify(p.defaultValue))}` : '';
340
+ const desc = oneLine(p.description);
341
+ return ` --${p.name} <${oneLine(p.type) || 'value'}> (${req}${def})${desc ? ` — ${desc}` : ''}`;
342
+ });
343
+ return [head, ...params].join('\n');
344
+ }
345
+
346
+ /** Unity CLI subcommands whose project is a trailing POSITIONAL argument (`unity <cmd> --help`: `[project]`, defaults to cwd). */
347
+ const CLI_POSITIONAL_PROJECT = new Set(['test', 'projects info', 'projects verify', 'projects clean', 'projects upgrade', 'projects size', 'projects require']);
348
+ /** Unity CLI subcommands that take `--project-path <path>` (`unity recompile --help`, `unity list --help`). */
349
+ const CLI_PROJECT_PATH_OPTION = new Set(['recompile', 'list']);
350
+
351
+ /**
352
+ * How a `unity.cli` op names the project — per subcommand, the way its --help says (T24-1): a positional for
353
+ * `test` / `projects info|verify|clean|upgrade|size|require`, `--project-path` for `recompile` / `list`, and nothing
354
+ * otherwise (`logs` reads the Hub log and rejects the option). A positional the model already gave is kept.
355
+ * @param {string[]} args @param {string} root @returns {string[]}
356
+ */
357
+ function cliProjectArgs(args, root) {
358
+ const one = args[0];
359
+ const two = args.length > 1 ? `${args[0]} ${args[1]}` : '';
360
+ if (CLI_PROJECT_PATH_OPTION.has(one)) return args.includes('--project-path') ? [] : ['--project-path', root];
361
+ const head = CLI_POSITIONAL_PROJECT.has(two) ? 2 : CLI_POSITIONAL_PROJECT.has(one) ? 1 : 0;
362
+ if (!head) return [];
363
+ // A bare token right after `--flag` is read as that flag's value; any other bare token is the model's own positional.
364
+ const tail = args.slice(head);
365
+ const hasPositional = tail.some((a, i) => !a.startsWith('-') && !(i > 0 && /^--[^=]+$/.test(tail[i - 1])));
366
+ return hasPositional ? [] : [root];
367
+ }
368
+
369
+ /**
370
+ * @param {BridgeDispatch} dispatch
371
+ * @param {UnityDeps} deps
372
+ * @returns {Promise<void>}
373
+ */
374
+ async function executeUnity(dispatch, deps) {
375
+ const {
376
+ project,
377
+ cli,
378
+ emit,
379
+ signal,
380
+ noScripts = false,
381
+ runProcess = defaultRunProcess,
382
+ launch = defaultLaunchDetached,
383
+ api,
384
+ ensureAutomation = defaultEnsureAutomation,
385
+ log = defaultLog,
386
+ now = Date.now,
387
+ sleep = defaultSleep,
388
+ } = deps;
389
+ const jobId = dispatch.jobId;
390
+ // The id names files under .bridge/ — never run one that is not a plain token (D3).
391
+ if (!isSafeJobId(jobId)) return;
392
+ const op = /** @type {any} */ (dispatch.op);
393
+ const P = project.root;
394
+ const suffix = ['--project-path', P, '--format', 'json', '--non-interactive'];
395
+
396
+ /** @param {string} reason */
397
+ const refuse = (reason) => emit({ jobId, type: 'refused', reason });
398
+
399
+ // 1. guard
400
+ const tier = helperTier(dispatch, project, { noScripts });
401
+ if (!tier.ok) return refuse(tier.reason);
402
+ if (!cli) return refuse(NO_CLI);
403
+
404
+ /** a quiet Unity call (no progress lines) — used by the guards and the grant */
405
+ const runUnityQuiet = (/** @type {string[]} */ args, timeoutMs = ORDINARY_TIMEOUT_MS) =>
406
+ runProcess(cli.path, args, { cwd: P, timeoutMs, signal });
407
+
408
+ const needsSavedWork =
409
+ (op.kind === 'unity.command' && op.name === 'bt_export_level') || (op.kind === 'unity.editor' && op.action === 'close');
410
+ if (needsSavedWork) {
411
+ const unsaved = unsavedWorkReason(await dirtyScenes((args) => runUnityQuiet(args), P));
412
+ if (unsaved) return refuse(unsaved);
413
+ }
414
+
415
+ // path params resolve under the project (validateOperation already refused the unsafe ones)
416
+ /** @type {Record<string, unknown>} */
417
+ let params = {};
418
+ if (op.kind === 'unity.command') {
419
+ params = { ...(op.params || {}) };
420
+ for (const key of Object.keys(params)) {
421
+ if (PATH_PARAMS.has(key) && typeof params[key] === 'string') {
422
+ const abs = resolveProjectPath(P, params[key]);
423
+ if (!abs) return refuse(`The "${key}" path "${params[key]}" is outside the Unity project.`);
424
+ params[key] = abs;
425
+ }
426
+ }
427
+ }
428
+
429
+ // 2. started, 3. log
430
+ await emit({ jobId, type: 'started' });
431
+ log.op(tier.tier, labelOf(dispatch));
432
+
433
+ let lastProgress = 0;
434
+ /** @param {string} line */
435
+ const onLine = (line) => {
436
+ const t = now();
437
+ if (t - lastProgress < PROGRESS_EVERY_MS) return;
438
+ lastProgress = t;
439
+ emit({ jobId, type: 'progress', line: capText(line, 500) }).catch(() => {});
440
+ };
441
+
442
+ const long = isLongOperation(op);
443
+ const hardTimeoutMs = long || op.kind === 'unity.script' ? LONG_TIMEOUT_MS : ORDINARY_TIMEOUT_MS;
444
+ /** @param {string[]} args @param {number} [timeoutMs] */
445
+ const runUnity = (args, timeoutMs = hardTimeoutMs) => runProcess(cli.path, args, { cwd: P, timeoutMs, signal, onLine });
446
+
447
+ /** @param {BridgeResultPayload} result */
448
+ const finalize = (result) =>
449
+ emit({
450
+ jobId,
451
+ type: 'final',
452
+ result: signal && signal.aborted ? { ok: false, text: CANCELLED } : { ...result, text: capText(result.text) },
453
+ });
454
+
455
+ /** @param {RunResult} res @returns {BridgeResultPayload|null} */
456
+ const interrupted = (res) => {
457
+ if (res.aborted || (signal && signal.aborted)) return { ok: false, text: CANCELLED };
458
+ if (res.timedOut) {
459
+ return { ok: false, text: `Timed out after ${Math.round(hardTimeoutMs / 1000)} s — Unity may still finish the operation.` };
460
+ }
461
+ return null;
462
+ };
463
+
464
+ /**
465
+ * `unity command <name> <suffix> --timeout <s> -- --<k> <v>…` → the envelope's result (params after `--` are command parameters, never CLI options).
466
+ * @param {string} name @param {Record<string, unknown>} p
467
+ * @returns {Promise<BridgeResultPayload>}
468
+ */
469
+ const runCommand = async (name, p) => {
470
+ // The CLI's own options come first; everything after `--` is a parameter OF THE COMMAND, so a
471
+ // param can never become `--yes`, `--project-path`, `--format` or `--timeout` for the CLI itself
472
+ // (D41). Real commands declare `timeout` (eval, run_tests…) and `format` (get_serialized_fields),
473
+ // and this is how they still reach them.
474
+ const args = ['command', name, ...suffix, '--timeout', String(long ? 1800 : 110), '--'];
475
+ for (const [k, v] of Object.entries(p)) {
476
+ if (v === undefined) continue;
477
+ args.push(`--${k}`, paramValue(v));
478
+ }
479
+ const res = await runUnity(args);
480
+ const stop = interrupted(res);
481
+ if (stop) return stop;
482
+ const env = parseEnvelope(res.stdout);
483
+ if (!env) return { ok: res.code === 0, text: rawText(res) || `unity exited with code ${res.code}`, exitCode: res.code ?? undefined };
484
+ const ok = env.success === true;
485
+ const data = env.data || {};
486
+ const text = ok ? resultText(data.result !== undefined ? data.result : data) : firstError(env);
487
+ return { ok, text, exitCode: res.code ?? undefined };
488
+ };
489
+
490
+ /** @returns {Promise<BridgeResultPayload>} */
491
+ const run = async () => {
492
+ switch (op.kind) {
493
+ case 'unity.list': {
494
+ const res = await runUnity([
495
+ 'command',
496
+ '--query',
497
+ typeof op.query === 'string' ? op.query : '',
498
+ '--detail',
499
+ 'compact',
500
+ '--limit',
501
+ '200',
502
+ ...suffix,
503
+ ]);
504
+ const stop = interrupted(res);
505
+ if (stop) return stop;
506
+ const env = parseEnvelope(res.stdout);
507
+ if (!env) return { ok: res.code === 0, text: rawText(res), exitCode: res.code ?? undefined };
508
+ if (env.success !== true) return { ok: false, text: firstError(env), exitCode: res.code ?? undefined };
509
+ let commands = env.data && Array.isArray(env.data.commands) ? env.data.commands : [];
510
+ // A narrow query (≤ LIST_FULL_DETAIL_MAX matches) also fetches each command's parameters (T24-2), so the
511
+ // model can call a typed command instead of falling back to a C# script. A failed full fetch keeps the compact list.
512
+ if (commands.length > 0 && commands.length <= LIST_FULL_DETAIL_MAX) {
513
+ const full = await runUnity([
514
+ 'command',
515
+ '--query',
516
+ typeof op.query === 'string' ? op.query : '',
517
+ '--detail',
518
+ 'full',
519
+ '--limit',
520
+ String(LIST_FULL_DETAIL_MAX),
521
+ ...suffix,
522
+ ]);
523
+ const stopFull = interrupted(full);
524
+ if (stopFull) return stopFull;
525
+ const fullEnv = parseEnvelope(full.stdout);
526
+ if (fullEnv && fullEnv.success === true && fullEnv.data && Array.isArray(fullEnv.data.commands) && fullEnv.data.commands.length) {
527
+ commands = fullEnv.data.commands;
528
+ }
529
+ }
530
+ const lines = commands.map((/** @type {any} */ c) => describeListedCommand(c));
531
+ const text = lines.length
532
+ ? `${lines.length} command(s):\n${lines.join('\n')}`
533
+ : 'No Unity commands matched that query.';
534
+ return { ok: true, text, exitCode: res.code ?? undefined };
535
+ }
536
+
537
+ case 'unity.command': {
538
+ const name = /** @type {string} */ (op.name);
539
+ if (name === 'screenshot' && (params.output === undefined || params.output === '')) {
540
+ const out = path.join(P, '.bridge', 'out');
541
+ fs.mkdirSync(out, { recursive: true });
542
+ params.output = path.join(out, `${jobId}.png`);
543
+ }
544
+ if (name.startsWith('bt_') && api) {
545
+ // Never changes the job's outcome; the grant never reaches a log, a progress line or a result.
546
+ await ensureAutomation(project, {
547
+ api,
548
+ runUnity: (args) => runUnityQuiet(args),
549
+ now,
550
+ log,
551
+ });
552
+ }
553
+ return runCommand(name, params);
554
+ }
555
+
556
+ case 'devserver.start': {
557
+ /** @type {Record<string, unknown>} */
558
+ const p = {};
559
+ if (op.port !== undefined) p.port = op.port;
560
+ else if (op.auto === true) p.auto = true;
561
+ return runCommand('bt_devserver_start', p);
562
+ }
563
+
564
+ case 'devserver.status':
565
+ return runCommand('bt_devserver_status', {});
566
+
567
+ case 'unity.cli': {
568
+ const args = /** @type {string[]} */ (op.args);
569
+ // cwd is the project root too (runUnity), so a subcommand that defaults to the current directory is right either way.
570
+ const res = await runUnity([...args, ...cliProjectArgs(args, P), '--format', 'json', '--non-interactive']);
571
+ const stop = interrupted(res);
572
+ if (stop) return stop;
573
+ const env = parseEnvelope(res.stdout);
574
+ if (env) {
575
+ const ok = res.code === 0 && env.success !== false;
576
+ return { ok, text: ok ? JSON.stringify(env.data !== undefined ? env.data : env, null, 2) : firstError(env), exitCode: res.code ?? undefined };
577
+ }
578
+ return { ok: res.code === 0, text: rawText(res) || `unity exited with code ${res.code}`, exitCode: res.code ?? undefined };
579
+ }
580
+
581
+ case 'unity.script': {
582
+ const dir = path.join(P, '.bridge', 'scripts');
583
+ fs.mkdirSync(dir, { recursive: true });
584
+ const rel = `.bridge/scripts/${jobId}.cs`;
585
+ const file = path.join(dir, `${jobId}.cs`);
586
+ fs.writeFileSync(file, /** @type {string} */ (op.source));
587
+ try {
588
+ const res = await runUnity([
589
+ 'command',
590
+ 'run_script',
591
+ ...suffix,
592
+ '--timeout',
593
+ '1800',
594
+ '--',
595
+ '--file',
596
+ rel,
597
+ '--entry',
598
+ /** @type {string} */ (op.entry),
599
+ ]);
600
+ const stop = interrupted(res);
601
+ if (stop) return stop;
602
+ const env = parseEnvelope(res.stdout);
603
+ if (!env) return { ok: false, text: rawText(res) || `unity exited with code ${res.code}`, exitCode: res.code ?? undefined };
604
+ const result = env.data ? env.data.result : undefined;
605
+ const ok = env.success === true && !(result && typeof result === 'object' && result.success === false);
606
+ const text = env.success === true ? resultText(result !== undefined ? result : env.data) : firstError(env);
607
+ return { ok, text, exitCode: res.code ?? undefined };
608
+ } finally {
609
+ removeQuietly(file);
610
+ pruneEmptyScratchDirs(P);
611
+ }
612
+ }
613
+
614
+ case 'unity.capture': {
615
+ const dir = path.join(P, '.bridge', 'out');
616
+ fs.mkdirSync(dir, { recursive: true });
617
+ const file = path.join(dir, `${jobId}.png`);
618
+ const view = op.view === 'scene' ? 'scene' : 'game';
619
+ /** @param {number} w @param {number} h @returns {Promise<BridgeResultPayload|{ base64: string }>} */
620
+ const shoot = async (w, h) => {
621
+ removeQuietly(file);
622
+ const res = await runUnity([
623
+ 'command',
624
+ 'screenshot',
625
+ ...suffix,
626
+ '--',
627
+ '--view',
628
+ view,
629
+ '--output',
630
+ file,
631
+ '--width',
632
+ String(w),
633
+ '--height',
634
+ String(h),
635
+ ]);
636
+ const stop = interrupted(res);
637
+ if (stop) return stop;
638
+ const env = parseEnvelope(res.stdout);
639
+ if (env && env.success !== true) return { ok: false, text: firstError(env), exitCode: res.code ?? undefined };
640
+ let bytes;
641
+ try {
642
+ bytes = fs.readFileSync(file);
643
+ } catch {
644
+ return { ok: false, text: rawText(res) || 'Unity did not write the capture.', exitCode: res.code ?? undefined };
645
+ }
646
+ return { base64: bytes.toString('base64') };
647
+ };
648
+ try {
649
+ let w = op.width;
650
+ let h = op.height;
651
+ let shot = await shoot(w, h);
652
+ if ('base64' in shot && shot.base64.length > BRIDGE_MAX_IMAGE_BASE64) {
653
+ w = Math.max(64, Math.floor(w / 2));
654
+ h = Math.max(64, Math.floor(h / 2));
655
+ shot = await shoot(w, h);
656
+ if ('base64' in shot && shot.base64.length > BRIDGE_MAX_IMAGE_BASE64) {
657
+ return { ok: false, text: 'capture too large' };
658
+ }
659
+ }
660
+ if (!('base64' in shot)) return shot;
661
+ return {
662
+ ok: true,
663
+ text: `Captured the ${view} view at ${w}x${h}.`,
664
+ image: { base64: shot.base64, mimeType: 'image/png' },
665
+ };
666
+ } finally {
667
+ removeQuietly(file);
668
+ pruneEmptyScratchDirs(P);
669
+ }
670
+ }
671
+
672
+ case 'unity.editor': {
673
+ const status = async () => {
674
+ const res = await runUnity(['status', '--format', 'json', '--non-interactive'], ORDINARY_TIMEOUT_MS);
675
+ const env = parseEnvelope(res.stdout);
676
+ const instances = env && env.data && Array.isArray(env.data.instances) ? env.data.instances : [];
677
+ return {
678
+ res,
679
+ env,
680
+ mine: instances.filter((/** @type {any} */ i) => i && typeof i.project === 'string' && samePath(i.project, P)),
681
+ };
682
+ };
683
+
684
+ if (op.action === 'status') {
685
+ const { res, env, mine } = await status();
686
+ const stop = interrupted(res);
687
+ if (stop) return stop;
688
+ if (!env) return { ok: false, text: rawText(res) || 'Could not read the Unity status.', exitCode: res.code ?? undefined };
689
+ const text = mine.length
690
+ ? JSON.stringify({ running: true, instances: mine }, null, 2)
691
+ : `Unity is not running with the project "${project.name}".`;
692
+ return { ok: env.success !== false, text };
693
+ }
694
+
695
+ if (op.action === 'open') {
696
+ // Detached: the Editor must survive the helper stopping (Ctrl-C) — see launchDetached.
697
+ const res = await launch(cli.path, ['open', P, '--non-interactive'], { cwd: P, signal });
698
+ if (res.aborted || (signal && signal.aborted)) return { ok: false, text: CANCELLED };
699
+ if (res.code !== 0) {
700
+ return { ok: false, text: rawText(res) || `unity open exited with code ${res.code}`, exitCode: res.code ?? undefined };
701
+ }
702
+ const deadline = now() + EDITOR_OPEN_WAIT_MS;
703
+ while (now() < deadline) {
704
+ if (signal && signal.aborted) return { ok: false, text: CANCELLED };
705
+ const s = await status();
706
+ if (s.mine.some((/** @type {any} */ i) => !i.state || i.state === 'ready') && (await editorAnswers(runProcess, cli.path, P, signal))) {
707
+ return { ok: true, text: `Unity is open with the project "${project.name}".` };
708
+ }
709
+ await sleep(EDITOR_POLL_MS, signal);
710
+ }
711
+ return { ok: false, text: `Unity did not report the project "${project.name}" as open within 180 s.` };
712
+ }
713
+
714
+ if (op.action === 'close') {
715
+ const res = await runUnity(['close', P, '--timeout', '60', '--format', 'json', '--non-interactive'], ORDINARY_TIMEOUT_MS);
716
+ const stop = interrupted(res);
717
+ if (stop) return stop;
718
+ const env = parseEnvelope(res.stdout);
719
+ if (!env) return { ok: res.code === 0, text: rawText(res) || 'Unity closed.', exitCode: res.code ?? undefined };
720
+ return { ok: env.success === true, text: env.success === true ? `Unity closed the project "${project.name}".` : firstError(env) };
721
+ }
722
+
723
+ return { ok: false, text: `Unknown Unity editor action "${op.action}".` };
724
+ }
725
+
726
+ default:
727
+ return { ok: false, text: `This Desktop Agent does not know the operation "${op.kind}".` };
728
+ }
729
+ };
730
+
731
+ let result;
732
+ try {
733
+ result = await run();
734
+ } catch (err) {
735
+ result = { ok: false, text: `The Desktop Agent failed: ${err && err.message ? err.message : err}` };
736
+ }
737
+ await finalize(result);
738
+ }
739
+
740
+ /**
741
+ * `unity.project list|open|create` (D54). Runs against the helper's projects folder, never a path the
742
+ * App Builder sent: a name resolves to a folder DIRECTLY inside it (or one of the --unity paths), and
743
+ * open/create make that project the CURRENT one every other job runs against.
744
+ *
745
+ * Opening a project that does not have the Unity Pipeline package adds it first (a manifest edit, no
746
+ * Editor needed) — the Unity CLI reaches an Editor only through that package, so without it no other
747
+ * Unity job could run. Opening does NOT add the Babylon Toolkit packages; its result says when they are
748
+ * missing, and the model adds them with `unity_command package_add` per the Agent Reference.
749
+ *
750
+ * Creating a project runs the Agent Reference's whole Babylon Toolkit scaffold (D56, unity-exporter-cli.md
751
+ * §4 + §4B.4): git check (a refusal when missing) → projects new → pipeline install → launch → unitygltf →
752
+ * professionaledition → exporter compiled → bootstrap → npm install → starter scene → verify. A failed step
753
+ * stops the job and names the step; the project is left in place, never deleted, and becomes current only
754
+ * when every step succeeded.
755
+ *
756
+ * @param {BridgeDispatch} dispatch
757
+ * @param {{
758
+ * workspace: import('./discover').Workspace,
759
+ * cli?: { path: string, version: string },
760
+ * emit: (event: BridgeJobEvent) => Promise<void>,
761
+ * signal?: AbortSignal,
762
+ * runProcess?: RunProcess,
763
+ * launch?: import('./run').LaunchDetached,
764
+ * log?: { op: (tier: string, label: string) => void },
765
+ * now?: () => number,
766
+ * sleep?: (ms: number, signal?: AbortSignal) => Promise<void>,
767
+ * openWaitMs?: number,
768
+ * createOpenWaitMs?: number,
769
+ * npm?: { file: string, args: string[] },
770
+ * onScaffold?: (active: boolean, root: string) => void,
771
+ * }} deps
772
+ * @returns {Promise<void>}
773
+ */
774
+ async function executeUnityProject(dispatch, deps) {
775
+ const {
776
+ workspace,
777
+ cli,
778
+ emit,
779
+ signal,
780
+ runProcess = defaultRunProcess,
781
+ launch = defaultLaunchDetached,
782
+ log = defaultLog,
783
+ now = Date.now,
784
+ sleep = defaultSleep,
785
+ openWaitMs = EDITOR_OPEN_WAIT_MS,
786
+ createOpenWaitMs = CREATE_OPEN_WAIT_MS,
787
+ npm = resolveNpm(),
788
+ onScaffold,
789
+ } = deps;
790
+ const jobId = dispatch.jobId;
791
+ if (!isSafeJobId(jobId)) return;
792
+ const op = /** @type {any} */ (dispatch.op);
793
+ /** @param {string} reason */
794
+ const refuse = (reason) => emit({ jobId, type: 'refused', reason });
795
+
796
+ if (!op || op.kind !== 'unity.project') return refuse('This runner only runs unity_project jobs.');
797
+ const tier = helperTier(dispatch, {}, { noScripts: false });
798
+ if (!tier.ok) return refuse(tier.reason);
799
+ const folderName = workspace.projectsDirName;
800
+
801
+ /** @param {{ name: string, root: string, unityVersion?: string, toolkitVersion?: string }} p */
802
+ const describe = (p) => {
803
+ const bits = [];
804
+ if (p.unityVersion) bits.push(`Unity ${p.unityVersion}`);
805
+ bits.push(p.toolkitVersion ? `Babylon Toolkit ${p.toolkitVersion}` : 'no Babylon Toolkit package');
806
+ return bits.join(', ');
807
+ };
808
+
809
+ if (op.action === 'list') {
810
+ await emit({ jobId, type: 'started' });
811
+ log.op(tier.tier, labelOf(dispatch));
812
+ const projects = workspace.refresh();
813
+ const current = workspace.current();
814
+ const lines = projects.map(
815
+ (p) => `- ${p.name} — ${describe(p)}${current && current.root === p.root ? ' (current)' : ''}`
816
+ );
817
+ const head = lines.length
818
+ ? `Projects folder "${folderName}" — ${lines.length} Unity project(s):\n${lines.join('\n')}`
819
+ : `The projects folder "${folderName}" has no Unity projects yet — create one with unity_project action "create".`;
820
+ const tail = current
821
+ ? `\nCurrent project: "${current.name}".`
822
+ : '\nNo project is open yet — open or create one with unity_project.';
823
+ return emit({ jobId, type: 'final', result: { ok: true, text: capText(head + tail) } });
824
+ }
825
+
826
+ if (!cli) return refuse(NO_CLI);
827
+ const name = /** @type {string} */ (op.name);
828
+
829
+ /** @type {string} */
830
+ let root;
831
+ /** the project's own name (on macOS/Windows "real" may name the folder "Real") */
832
+ let label = name;
833
+ if (op.action === 'open') {
834
+ const hit = typeof workspace.resolve === 'function' ? workspace.resolve(name) : (() => {
835
+ const r = workspace.rootFor(name);
836
+ return r ? { root: r } : null;
837
+ })();
838
+ if (hit && 'ambiguous' in hit) {
839
+ const bare = name.includes('/') ? name.slice(name.indexOf('/') + 1) : name;
840
+ return refuse(
841
+ `There is a Unity project named "${bare}" in more than one projects folder (${hit.ambiguous.map((f) => `"${f}"`).join(', ')}). Call unity_project again with the folder in the name, e.g. "${hit.ambiguous[0]}/${bare}".`
842
+ );
843
+ }
844
+ const found = hit ? hit.root : undefined;
845
+ if (!found) {
846
+ return refuse(
847
+ `There is no Unity project named "${name}" in the projects folder "${folderName}". Call unity_project with action "list" to see them, or "create" to make one.`
848
+ );
849
+ }
850
+ root = found;
851
+ label = path.basename(found);
852
+ } else {
853
+ const folder = workspace.projectsDir;
854
+ let isFolder = false;
855
+ try {
856
+ isFolder = fs.statSync(folder).isDirectory();
857
+ } catch {
858
+ isFolder = false;
859
+ }
860
+ if (!isFolder) return refuse(`The projects folder "${folderName}" does not exist on this computer.`);
861
+ root = path.join(folder, name);
862
+ if (fs.existsSync(root)) {
863
+ return refuse(
864
+ `A folder named "${name}" already exists in the projects folder "${folderName}" — open it, or create the project under another name.`
865
+ );
866
+ }
867
+ }
868
+
869
+ if (op.action === 'create') {
870
+ // D56: git first — Unity's Package Manager clones the two toolkit packages. Missing git is a refusal:
871
+ // nothing has run and nothing was created.
872
+ const git = await runProcess('git', ['--version'], { cwd: workspace.projectsDir, timeoutMs: 15_000, signal });
873
+ if (signal && signal.aborted) return emit({ jobId, type: 'final', result: { ok: false, text: CANCELLED } });
874
+ if (git.code !== 0 || git.timedOut) return refuse(GIT_MISSING);
875
+ }
876
+
877
+ await emit({ jobId, type: 'started' });
878
+ log.op(tier.tier, labelOf(dispatch));
879
+
880
+ let lastProgress = 0;
881
+ /** @param {string} line */
882
+ const onLine = (line) => {
883
+ const t = now();
884
+ if (t - lastProgress < PROGRESS_EVERY_MS) return;
885
+ lastProgress = t;
886
+ emit({ jobId, type: 'progress', line: capText(line, 500) }).catch(() => {});
887
+ };
888
+ /** @param {string[]} args @param {string} cwd @param {number} timeoutMs */
889
+ const runUnity = (args, cwd, timeoutMs) => runProcess(cli.path, args, { cwd, timeoutMs, signal, onLine });
890
+
891
+ /** @param {BridgeResultPayload} result */
892
+ const finalize = (result) =>
893
+ emit({
894
+ jobId,
895
+ type: 'final',
896
+ result: signal && signal.aborted ? { ok: false, text: CANCELLED } : { ...result, text: capText(result.text) },
897
+ });
898
+
899
+ /** @param {RunResult} res @param {number} timeoutMs @returns {BridgeResultPayload|null} */
900
+ const interrupted = (res, timeoutMs) => {
901
+ if (res.aborted || (signal && signal.aborted)) return { ok: false, text: CANCELLED };
902
+ if (res.timedOut) return { ok: false, text: `Timed out after ${Math.round(timeoutMs / 1000)} s — Unity may still finish the operation.` };
903
+ return null;
904
+ };
905
+
906
+ /** the Editor instances `unity status` reports for `dir` */
907
+ const instancesFor = async (/** @type {string} */ dir) => {
908
+ const res = await runUnity(['status', '--format', 'json', '--non-interactive'], dir, ORDINARY_TIMEOUT_MS);
909
+ const env = parseEnvelope(res.stdout);
910
+ const instances = env && env.data && Array.isArray(env.data.instances) ? env.data.instances : [];
911
+ return instances.filter((/** @type {any} */ i) => i && typeof i.project === 'string' && samePath(i.project, dir));
912
+ };
913
+ const isReady = (/** @type {any[]} */ mine) => mine.some((i) => !i.state || i.state === 'ready');
914
+
915
+ let addedPipeline = false;
916
+ /** The disclosure a result carries when this job edited the project's manifest. */
917
+ const pipelineNote = (/** @type {string} */ label) =>
918
+ `Added the Unity Pipeline package (com.unity.pipeline) to "${label}"'s Packages/manifest.json so the Unity command-line tool can reach the Editor.`;
919
+
920
+ /**
921
+ * Pipeline package → `unity open` → poll `unity status` until the Editor is ready. An `open` makes the
922
+ * project current as soon as the Editor is launched; the create scaffold passes makeCurrent=false and
923
+ * makes it current only when every step succeeded (D56).
924
+ * @param {string} dir @param {string} label @param {number} [waitMs] @param {boolean} [makeCurrent]
925
+ * Sets `addedPipeline` when it added the Pipeline package — the final result then discloses it.
926
+ * @returns {Promise<BridgeResultPayload & { opened?: boolean }>}
927
+ */
928
+ const openAndWait = async (dir, label, waitMs = openWaitMs, makeCurrent = true) => {
929
+ if (!packageVersion(dir, PIPELINE_PACKAGE)) {
930
+ const res = await runUnity(
931
+ ['pipeline', 'install', '--project-path', dir, '--format', 'json', '--non-interactive'],
932
+ dir,
933
+ ORDINARY_TIMEOUT_MS
934
+ );
935
+ const stop = interrupted(res, ORDINARY_TIMEOUT_MS);
936
+ if (stop) return stop;
937
+ const env = parseEnvelope(res.stdout);
938
+ if (!env || env.success !== true) {
939
+ const why = env ? firstError(env) : rawText(res) || `unity exited with code ${res.code}`;
940
+ return { ok: false, text: `Could not add the Unity Pipeline package to "${label}" (the Unity command-line tool needs it to reach the Editor): ${why}` };
941
+ }
942
+ addedPipeline = true;
943
+ }
944
+
945
+ // Ready = listed as ready by `unity status` AND answering commands (editor_status, no "Server Busy").
946
+ const readyNow = async () => isReady(await instancesFor(dir)) && (await editorAnswers(runProcess, cli.path, dir, signal));
947
+
948
+ if (isReady(await instancesFor(dir))) {
949
+ // Already open: no launch — but it only counts once it answers (it may still be settling).
950
+ if (makeCurrent) workspace.setCurrent(dir);
951
+ if (await editorAnswers(runProcess, cli.path, dir, signal)) {
952
+ return { ok: true, text: `Unity is open with the project "${label}".`, opened: true };
953
+ }
954
+ } else {
955
+ // Detached: the Editor must survive the helper stopping (Ctrl-C) — see launchDetached. Every other
956
+ // Unity call stays in the helper's process group so a cancel can stop it.
957
+ const res = await launch(cli.path, ['open', dir, '--non-interactive'], { cwd: dir, signal });
958
+ if (res.aborted || (signal && signal.aborted)) return { ok: false, text: CANCELLED };
959
+ if (res.code !== 0) {
960
+ return { ok: false, text: rawText(res) || `unity open exited with code ${res.code}`, exitCode: res.code ?? undefined };
961
+ }
962
+ if (makeCurrent) workspace.setCurrent(dir);
963
+ }
964
+
965
+ const deadline = now() + waitMs;
966
+ while (now() < deadline) {
967
+ if (signal && signal.aborted) return { ok: false, text: CANCELLED };
968
+ if (await readyNow()) {
969
+ return { ok: true, text: `Unity is open with the project "${label}".`, opened: true };
970
+ }
971
+ await sleep(EDITOR_POLL_MS, signal);
972
+ }
973
+ return {
974
+ ok: false,
975
+ text: makeCurrent
976
+ ? `Unity did not report the project "${label}" as ready within ${Math.round(waitMs / 1000)} s — it may still be importing assets. It is the current project; check with unity_editor status before the next Unity command.`
977
+ : `Unity did not report the project "${label}" as ready within ${Math.round(waitMs / 1000)} s — it may still be importing assets.`,
978
+ };
979
+ };
980
+
981
+ /** Why the Toolkit cannot export yet, or '' when both of its packages are in the project. */
982
+ const missingToolkitLine = (/** @type {string} */ dir) => {
983
+ const missing = TOOLKIT_PACKAGES.filter((p) => !hasPackage(dir, p.name)).map((p) => p.name);
984
+ return missing.length
985
+ ? ` It does not have the Babylon Toolkit packages yet (missing: ${missing.join(', ')}) — add them with unity_command package_add (see the Agent Reference) before exporting.`
986
+ : '';
987
+ };
988
+
989
+ /**
990
+ * D56 — the Agent Reference's "Create a Babylon Toolkit Unity Project" scaffold (unity-exporter-cli.md §4,
991
+ * §4B.4, bt-new-unity-project.sh). Every step emits "n/10 …"; the first failure stops the job naming the
992
+ * step, and the project stays where it is. §4B step 6 (copy a licence) is skipped on purpose: bridge
993
+ * exports run under the automation grant (D47–D51), so no licence file is needed here. The two `.cs`
994
+ * snippets are eval_file bodies (top-level statements), run exactly as the reference script runs them.
995
+ * git was checked before the job started. The whole create is bounded at 30 min: every step's own
996
+ * timeout is capped by what is left of that budget. The project becomes current only when every step
997
+ * succeeded.
998
+ * @returns {Promise<BridgeResultPayload>}
999
+ */
1000
+ const scaffold = async () => {
1001
+ const started = now();
1002
+ const budgetEnd = started + CREATE_BUDGET_MS;
1003
+ /** @type {string[]} */
1004
+ const timings = [];
1005
+ let step = 0;
1006
+ let stepAt = started;
1007
+ /** @returns {boolean} false when the 30 min budget is spent before this step could start */
1008
+ const begin = (/** @type {number} */ n, /** @type {string} */ what) => {
1009
+ if (step) timings.push(`${step}/${SCAFFOLD_STEPS} ${seconds(now() - stepAt)}`);
1010
+ step = n;
1011
+ stepAt = now();
1012
+ lastProgress = now();
1013
+ emit({ jobId, type: 'progress', line: capText(`${n}/${SCAFFOLD_STEPS} ${what}`, 500) }).catch(() => {});
1014
+ return now() < budgetEnd;
1015
+ };
1016
+ const overBudget = () => `the create ran past its ${seconds(CREATE_BUDGET_MS)} budget.`;
1017
+ /** @param {string} text */
1018
+ const fail = (text) => ({
1019
+ ok: false,
1020
+ text:
1021
+ `Step ${step}/${SCAFFOLD_STEPS} (${STEP_NAMES[step]}) failed: ${text}` +
1022
+ (fs.existsSync(root)
1023
+ ? ` The project "${name}" was left in the projects folder "${folderName}" — nothing was deleted; open it with unity_project to continue.`
1024
+ : ' Nothing was created.'),
1025
+ });
1026
+ /** a step's own timeout, capped by what is left of the create's budget (never below 1 s) */
1027
+ const cap = (/** @type {number} */ ms) => Math.max(1_000, Math.min(ms, budgetEnd - now()));
1028
+ const quiet = (/** @type {string[]} */ args, timeoutMs = ORDINARY_TIMEOUT_MS) =>
1029
+ runProcess(cli.path, args, { cwd: root, timeoutMs: cap(timeoutMs), signal });
1030
+ const sfx = ['--project-path', root, '--format', 'json', '--non-interactive'];
1031
+ /** `unity command eval|eval_file <code|file>` — the form bt-new-unity-project.sh's `evs` / `ev` use. */
1032
+ const evalRun = async (/** @type {'eval'|'eval_file'} */ kind, /** @type {string} */ what) => {
1033
+ const res = await quiet(['command', kind, what, ...sfx]);
1034
+ if (res.aborted || (signal && signal.aborted)) return { ok: /** @type {false} */ (false), error: CANCELLED, cancelled: true };
1035
+ return evalOutcome(parseEnvelope(res.stdout));
1036
+ };
1037
+ const deadlineFor = (/** @type {number} */ ms) => Math.min(now() + ms, budgetEnd);
1038
+ const cancelled = () => Boolean(signal && signal.aborted);
1039
+ /** @param {{ ok: boolean, text: string }} r */
1040
+ const stopWith = (r) => (r.text === CANCELLED ? r : fail(r.text));
1041
+
1042
+ /**
1043
+ * Poll `probe` every 5 s until it says done / failed, or the deadline. A probe that cannot reach the
1044
+ * Editor (a domain reload takes the Pipeline server down 15–25 s) is "not yet", never a failure.
1045
+ * @param {() => Promise<{ done?: boolean, fail?: string, value?: string }>} probe
1046
+ * @param {number} waitMs @param {string} what
1047
+ * @returns {Promise<{ ok: true, value?: string } | { ok: false, text: string }>}
1048
+ */
1049
+ const pollUntil = async (probe, waitMs, what) => {
1050
+ const deadline = deadlineFor(waitMs);
1051
+ for (;;) {
1052
+ if (cancelled()) return { ok: false, text: CANCELLED };
1053
+ const r = await probe();
1054
+ if (r.done) return { ok: true, value: r.value };
1055
+ if (r.fail) return { ok: false, text: r.fail };
1056
+ if (now() >= deadline) {
1057
+ return { ok: false, text: deadline === budgetEnd ? `${what} — ${overBudget()}` : `${what} timed out after ${seconds(waitMs)}.` };
1058
+ }
1059
+ await sleep(SCAFFOLD_POLL_MS, signal);
1060
+ }
1061
+ };
1062
+
1063
+ /** undefined = not asked yet; the Pipeline's typed package_add is absent on older Pipeline versions (§4.1). */
1064
+ /** @type {boolean|undefined} */
1065
+ let hasPackageAdd;
1066
+ /**
1067
+ * §4.1: add one toolkit package by git URL, then poll until it resolved. One at a time — a second
1068
+ * package operation while one runs returns busy, so busy / unreachable are retried until the deadline.
1069
+ * @param {{ name: string, url: string }} pkg
1070
+ * @returns {Promise<{ ok: true } | { ok: false, text: string }>}
1071
+ */
1072
+ const addToolkitPackage = async (pkg) => {
1073
+ const deadline = deadlineFor(PACKAGE_WAIT_MS);
1074
+ let lastError = '';
1075
+ /** @type {string|undefined} */
1076
+ let accepted;
1077
+ while (hasPackageAdd !== false) {
1078
+ if (cancelled()) return { ok: false, text: CANCELLED };
1079
+ const res = await quiet(['command', 'package_add', ...sfx, '--timeout', '110', '--', '--identifier', pkg.url, '--confirm', 'true']);
1080
+ const env = parseEnvelope(res.stdout);
1081
+ const st = packageStatusOf(env);
1082
+ if (st && !/busy/i.test(st.text)) {
1083
+ accepted = st.status;
1084
+ hasPackageAdd = true;
1085
+ break;
1086
+ }
1087
+ lastError = st ? st.text : env ? firstError(env) : rawText(res) || `unity exited with code ${res.code}`;
1088
+ if (hasPackageAdd === undefined) {
1089
+ const q = parseEnvelope((await quiet(['command', '--query', 'package_add', '--detail', 'compact', ...sfx])).stdout);
1090
+ if (q && q.success === true) {
1091
+ const cmds = q.data && Array.isArray(q.data.commands) ? q.data.commands : [];
1092
+ hasPackageAdd = cmds.some((/** @type {any} */ c) => c && c.name === 'package_add');
1093
+ if (!hasPackageAdd) break;
1094
+ }
1095
+ }
1096
+ if (now() >= deadline) return { ok: false, text: `Unity did not accept the package add: ${lastError}` };
1097
+ await sleep(SCAFFOLD_POLL_MS, signal);
1098
+ }
1099
+
1100
+ if (hasPackageAdd === false) {
1101
+ // §4.1 fallback: Unity's own Package Manager through eval, polled with separate calls (never loop
1102
+ // inside one eval — Client.Add only progresses on the Editor's update loop).
1103
+ const queued = await pollUntil(async () => {
1104
+ const r = await evalRun('eval', `UnityEditor.PackageManager.Client.Add("${pkg.url}"); return "queued";`);
1105
+ return r.ok ? { done: true } : {};
1106
+ }, PACKAGE_WAIT_MS, `Queuing ${pkg.name}`);
1107
+ if (!queued.ok) return queued;
1108
+ return pollUntil(async () => {
1109
+ const r = await evalRun('eval', `return UnityEditor.PackageManager.PackageInfo.FindForAssetPath("Packages/${pkg.name}/package.json") != null ? "READY" : "no";`);
1110
+ return r.ok && r.value.includes('READY') ? { done: true } : {};
1111
+ }, PACKAGE_WAIT_MS, `${pkg.name} resolve`);
1112
+ }
1113
+
1114
+ if (accepted && /completed/i.test(accepted)) return { ok: true };
1115
+ if (accepted && /failed/i.test(accepted)) return { ok: false, text: 'the Package Manager reported failed.' };
1116
+ let seen = Boolean(accepted && /in_progress|running|baking/i.test(accepted));
1117
+ return pollUntil(async () => {
1118
+ const st = packageStatusOf(parseEnvelope((await quiet(['command', 'package_status', ...sfx])).stdout));
1119
+ if (!st) return {};
1120
+ if (/failed/i.test(st.status)) return { fail: `the Package Manager reported failed: ${capText(st.text, 400)}` };
1121
+ if (/completed/i.test(st.status)) return { done: true };
1122
+ if (/in_progress|running|baking/i.test(st.status)) seen = true;
1123
+ else if (/idle/i.test(st.status) && seen) return { fail: 'the package operation stopped without completing.' };
1124
+ return {};
1125
+ }, PACKAGE_WAIT_MS, `${pkg.name} install`);
1126
+ };
1127
+
1128
+ // 1. projects new — wait for it to EXIT (ProjectVersion.txt is written last, §3)
1129
+ begin(1, `creating the Unity project "${name}"`);
1130
+ const newTimeout = cap(LONG_TIMEOUT_MS);
1131
+ const created = await runUnity(
1132
+ ['projects', 'new', name, '--path', workspace.projectsDir, '--format', 'json', '--non-interactive'],
1133
+ workspace.projectsDir,
1134
+ newTimeout
1135
+ );
1136
+ const stop1 = interrupted(created, newTimeout);
1137
+ if (stop1) return stop1.text === CANCELLED ? stop1 : fail(stop1.text);
1138
+ const env1 = parseEnvelope(created.stdout);
1139
+ if (!env1 || env1.success !== true || !isUnityProject(root)) {
1140
+ return fail(env1 && env1.success !== true ? firstError(env1) : rawText(created) || `unity projects new exited with code ${created.code}`);
1141
+ }
1142
+ const unityVersion = env1.data && typeof env1.data.version === 'string' ? env1.data.version : undefined;
1143
+
1144
+ // 2. com.unity.pipeline (1/3) — no Editor needed
1145
+ if (!begin(2, `${PIPELINE_PACKAGE} (1/3)`)) return fail(overBudget());
1146
+ const pipeTimeout = cap(ORDINARY_TIMEOUT_MS);
1147
+ const pipe = await runUnity(['pipeline', 'install', '--project-path', root, '--format', 'json', '--non-interactive'], root, pipeTimeout);
1148
+ const stop2 = interrupted(pipe, pipeTimeout);
1149
+ if (stop2) return stopWith(stop2);
1150
+ const env2 = parseEnvelope(pipe.stdout);
1151
+ if (!env2 || env2.success !== true || !packageVersion(root, PIPELINE_PACKAGE)) {
1152
+ return fail(env2 && env2.success !== true ? firstError(env2) : rawText(pipe) || 'the manifest has no com.unity.pipeline entry.');
1153
+ }
1154
+ if (!(env2.data && env2.data.alreadyInstalled === true)) addedPipeline = true;
1155
+
1156
+ // 3. launch the Editor (detached — it outlives the helper) and wait until it reports ready
1157
+ if (!begin(3, 'launching the Unity Editor')) return fail(overBudget());
1158
+ const opened = await openAndWait(root, name, Math.min(createOpenWaitMs, budgetEnd - now()), false);
1159
+ if (!opened.ok) return stopWith(opened);
1160
+
1161
+ // 4 + 5. the two toolkit packages, one at a time, Khronos glTF first (§4.1)
1162
+ for (const [i, pkg] of TOOLKIT_PACKAGES.entries()) {
1163
+ if (!begin(4 + i, `${pkg.name} (${2 + i}/3)`)) return fail(overBudget());
1164
+ const added = await addToolkitPackage(pkg);
1165
+ if (!added.ok) return stopWith(added);
1166
+ }
1167
+
1168
+ // 6. the real success condition: the exporter compiled into the domain (§4.1)
1169
+ if (!begin(6, 'waiting for the Babylon Toolkit exporter to compile')) return fail(overBudget());
1170
+ const compiled = await pollUntil(async () => {
1171
+ const r = await evalRun('eval', EXPORTER_COMPILED_CS);
1172
+ return r.ok && r.value.includes('READY') ? { done: true } : {};
1173
+ }, PACKAGE_WAIT_MS, 'The exporter compile');
1174
+ if (!compiled.ok) return stopWith(compiled);
1175
+
1176
+ // 7. bootstrap — replicates CVPanel.OnEnable (writes package.json, §5.1 / §4B.4)
1177
+ if (!begin(7, 'bootstrap (Scene Exporter settings + package.json)')) return fail(overBudget());
1178
+ const boot = await evalRun('eval_file', BOOTSTRAP_CS);
1179
+ if (!boot.ok && 'cancelled' in boot) return { ok: false, text: CANCELLED };
1180
+ const packageJson = path.join(root, 'package.json');
1181
+ // eval gives up after ~5 s on the main thread while the work may still finish (§7.3) — package.json is the proof.
1182
+ if (!boot.ok && !(/timed out/i.test(boot.error) && fs.existsSync(packageJson))) return fail(boot.error);
1183
+ const bootText = boot.ok ? boot.value : "the bootstrap outlived eval's 5 s wait but wrote package.json";
1184
+
1185
+ // 8. npm install in the project root — AFTER package.json, BEFORE any TypeScript build (§5.2). A failure is
1186
+ // reported, not fatal (the reference script does the same): only builds that compile scripts need it.
1187
+ if (!begin(8, 'npm install (TypeScript)')) return fail(overBudget());
1188
+ let npmText = 'npm install skipped — the project has no package.json';
1189
+ if (fs.existsSync(packageJson)) {
1190
+ const res = await runProcess(npm.file, npm.args, { cwd: root, timeoutMs: cap(NPM_TIMEOUT_MS), signal });
1191
+ if (cancelled()) return { ok: false, text: CANCELLED };
1192
+ npmText =
1193
+ res.code === 0 && !res.timedOut
1194
+ ? 'npm install: TypeScript installed'
1195
+ : `npm install FAILED (${res.timedOut ? 'timed out' : capText(rawText(res) || `exit code ${res.code}`, 300)})`;
1196
+ }
1197
+
1198
+ // 9. starter scene + LightingSettings (§8.1)
1199
+ if (!begin(9, `starter scene ${STARTER_SCENE} + LightingSettings`)) return fail(overBudget());
1200
+ const scene = await evalRun('eval_file', NEWSCENE_CS);
1201
+ if (!scene.ok && 'cancelled' in scene) return { ok: false, text: CANCELLED };
1202
+ const sceneOnDisk = () => fs.existsSync(path.join(root, ...STARTER_SCENE.split('/')));
1203
+ if (!scene.ok && !(/timed out/i.test(scene.error) && sceneOnDisk())) return fail(scene.error);
1204
+
1205
+ // 10. verify (§4.2 + the reference script's VERIFY line + the files on disk)
1206
+ if (!begin(10, 'verify')) return fail(overBudget());
1207
+ const list = parseEnvelope((await quiet(['pipeline', 'list', '--format', 'json', '--non-interactive'])).stdout);
1208
+ const inst = list && list.data && Array.isArray(list.data.instances) ? list.data.instances : [];
1209
+ const reachable = inst.some(
1210
+ (/** @type {any} */ i) => i && typeof i.projectPath === 'string' && samePath(i.projectPath, root) && i.pipelineServer && i.pipelineServer.isReachable === true
1211
+ );
1212
+ const pkgs = await evalRun('eval', PACKAGES_REGISTERED_CS);
1213
+ const asm = await evalRun('eval', EXPORTER_ASSEMBLY_CS);
1214
+ const info = await evalRun('eval', SCAFFOLD_VERIFY_CS);
1215
+ if (cancelled()) return { ok: false, text: CANCELLED };
1216
+ const tsc = fs.existsSync(path.join(root, 'node_modules', 'typescript', 'bin', 'tsc'));
1217
+ const sceneFile = sceneOnDisk();
1218
+ const pkgsOk = pkgs.ok && TOOLKIT_PACKAGES.every((p) => pkgs.value.includes(`${p.name}=True`));
1219
+ const verify = [
1220
+ `pipeline=${reachable ? 'reachable' : 'NOT reachable'}`,
1221
+ `packages: ${pkgs.ok ? pkgs.value.trim() : `ERR ${pkgs.error}`}`,
1222
+ `exporter=${asm.ok ? asm.value : `ERR ${asm.error}`}`,
1223
+ info.ok ? info.value : `ERR ${info.error}`,
1224
+ `package.json=${fs.existsSync(packageJson)} node_modules/typescript=${tsc} ${STARTER_SCENE}=${sceneFile}`,
1225
+ ].join(' | ');
1226
+ timings.push(`10/${SCAFFOLD_STEPS} ${seconds(now() - stepAt)}`);
1227
+ if (!(reachable && pkgsOk && asm.ok && sceneFile)) return fail(`VERIFY ${verify}`);
1228
+
1229
+ workspace.setCurrent(root);
1230
+ const version = unityVersion ? ` with Unity ${unityVersion}` : '';
1231
+ return {
1232
+ ok: true,
1233
+ text:
1234
+ `Created the Unity project "${name}"${version} in the projects folder "${folderName}"; it is now the current project and Unity is open with it. ` +
1235
+ `Installed com.unity.pipeline, org.khronos.unitygltf and com.babylontoolkit.editor (the exporter compiled in); bootstrap: ${bootText}; ${npmText}; starter scene ${STARTER_SCENE} with LightingSettings. ` +
1236
+ `VERIFY ${verify}. Took ${seconds(now() - started)} (${timings.join(', ')}). Ready to export with bt_export_level.`,
1237
+ };
1238
+ };
1239
+
1240
+ /** @type {BridgeResultPayload} */
1241
+ let result;
1242
+ try {
1243
+ if (op.action === 'open') {
1244
+ const { opened, ...payload } = await openAndWait(root, label);
1245
+ const current = opened ? workspace.current() : undefined;
1246
+ result = current
1247
+ ? { ok: true, text: `${payload.text} It is now the current project (${describe(current)}).${missingToolkitLine(root)}` }
1248
+ : payload;
1249
+ } else {
1250
+ // The dev-server probe never asks a project that is mid-scaffold (its Editor is importing and
1251
+ // reloading, and the Toolkit command is not compiled in yet).
1252
+ if (onScaffold) onScaffold(true, root);
1253
+ try {
1254
+ result = await scaffold();
1255
+ } finally {
1256
+ if (onScaffold) onScaffold(false, root);
1257
+ }
1258
+ }
1259
+ } catch (err) {
1260
+ result = { ok: false, text: `The Desktop Agent failed: ${err && err.message ? err.message : err}` };
1261
+ }
1262
+ // Never edit a user's manifest silently: say so whatever else happened (covers open and create).
1263
+ if (addedPipeline) result = { ...result, text: `${pipelineNote(label)} ${result.text}` };
1264
+ await finalize(result);
1265
+ }
1266
+
1267
+ /** The scaffold's step names, as the failure text names them (index = step number). */
1268
+ const STEP_NAMES = [
1269
+ '',
1270
+ 'unity projects new',
1271
+ 'com.unity.pipeline',
1272
+ 'launch the Unity Editor',
1273
+ 'org.khronos.unitygltf',
1274
+ 'com.babylontoolkit.editor',
1275
+ 'Babylon Toolkit exporter compile',
1276
+ 'bootstrap',
1277
+ 'npm install',
1278
+ 'starter scene',
1279
+ 'verify',
1280
+ ];
1281
+
1282
+ module.exports = {
1283
+ editorAnswers,
1284
+ executeUnityProject,
1285
+ resolveNpm,
1286
+ hasPackage,
1287
+ GIT_MISSING,
1288
+ TOOLKIT_PACKAGES,
1289
+ BOOTSTRAP_CS,
1290
+ NEWSCENE_CS,
1291
+ EXPORTER_COMPILED_CS,
1292
+ NO_PROJECT,
1293
+ EDITOR_OPEN_WAIT_MS,
1294
+ executeUnity, labelOf, parseEnvelope, parseJsonExact, CANCELLED, NO_CLI, ORDINARY_TIMEOUT_MS, LONG_TIMEOUT_MS };