@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.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Babylon Toolkit Desktop Agent (1.1.38)
1
+ # Babylon Toolkit Desktop Agent (1.1.44)
2
2
 
3
3
  The desktop agent owns the entire pipeline end to end — frontend and UI design, gameplay code, shaders, generated art and audio, 3D models in headless Blender, whole game levels and prefabs in a terminal-driven Unity Editor, the interactive glTF export, the web build, the dev server, and visual QA by screenshotting both Unity and the running browser.
4
4
 
@@ -31,6 +31,7 @@ up the skills, instructions and configuration.
31
31
  | `bt-agent uninstall` | Remove what it installed — and nothing else |
32
32
  | `bt-agent doctor` | Verify the install; prints `INSTALL OK` or lists what is missing |
33
33
  | `bt-agent targets` | Show every target and the paths it writes to |
34
+ | `bt-agent bridge` | Connect this computer to the App Builder so it can drive Unity and Blender |
34
35
 
35
36
  | Option | Effect |
36
37
  |--------|--------|
@@ -121,13 +122,81 @@ Skill folders are tracked in `~/.babylon-toolkit/install-manifest.json`, so `upd
121
122
  `uninstall` only ever touch folders this package installed — a skill you wrote yourself that
122
123
  happens to be named `bt-something` is safe.
123
124
 
125
+ ## Unity Bridge (App Builder)
126
+
127
+ `bt-agent bridge` connects this computer to the Babylon Toolkit App Builder, so the builder's
128
+ chat can open, create, edit and export Unity projects and drive Blender installed here.
129
+
130
+ Open the Unity Bridge dialog in the App Builder (the cube icon in the chat box), type your App
131
+ Builder projects folder (the one you picked for your projects in the App Builder), copy the one command
132
+ it then shows, and run it once in a terminal. The command points the helper at the Unity folder inside
133
+ your App Builder projects folder, where Unity projects live beside the `Apps` folder of apps (the
134
+ Unity Bridge dialog fills it in):
135
+
136
+ ```bash
137
+ npx @babylonjs-toolkit/agent bridge --install-service --pair K7QM-2XWD --projects "/Users/you/Projects/Unity"
138
+ ```
139
+
140
+ `--projects` is required with `--install-service` — the service runs at login, so the folder is never
141
+ guessed from where the command happened to run. A folder that does not exist is created. A later
142
+ reinstall without `--projects` keeps the folders stored by the first one.
143
+
144
+ The command carries a single-use install code (valid for 10 minutes) that pairs this computer with
145
+ your account — you never type a code anywhere. `--install-service` then copies the helper to
146
+ `~/.babylon-toolkit/service/` and starts it now and every time you log in (a launchd agent on
147
+ macOS, a systemd user unit on Linux, a Startup-folder script on Windows). It logs to
148
+ `~/.babylon-toolkit/bridge.log` (rotated at 5 MB). Run the command again to change the settings —
149
+ it re-installs and restarts the service. `bt-agent bridge --uninstall-service` stops it and stops
150
+ starting it at login; the pairing is kept until `bt-agent bridge logout`.
151
+
152
+ The App Builder can list the Unity projects in the projects folder, open one, or create a new one
153
+ there — the project it opened or created last is the one every other Unity and Blender job works on.
154
+ Run in the terminal (without `--install-service`) and without `--projects`, the bridge uses the folder
155
+ it runs in — or, started inside a Unity project, that project's parent, with that project open. Only folder and project NAMES are sent to the App Builder, never a path.
156
+
157
+ The helper talks to the production App Builder by default. `--server <url>` (or `BTK_BRIDGE_SERVER`)
158
+ points it at another one — the dialog adds it to the command for you when it is needed. `--server`
159
+ may be repeated to serve several App Builders at once (for example a local development server and
160
+ production): each is paired once, with its own install code, and they share one job queue and one
161
+ current project, so two builders never drive Unity at the same time.
162
+
163
+ | Option | Effect |
164
+ |--------|--------|
165
+ | `--pair <code>` | The install code from the Unity Bridge dialog |
166
+ | `--install-service` | Pair, then start the bridge now and at every login |
167
+ | `--uninstall-service` | Stop the service and remove it (the pairing is kept) |
168
+ | `--server <url>` | Another App Builder — `https://`, or `http://localhost` for development (repeatable) |
169
+ | `--projects <folder>` | A Unity projects folder (repeatable; created if missing) — with the App Builder, the Unity folder inside your App Builder projects folder (the Unity Bridge dialog fills it in). Required for `--install-service`; default only when running in the terminal: this folder, or its parent inside a Unity project |
170
+ | `--unity <path>` | Also serve this Unity project (repeatable); the first one starts as the current project |
171
+ | `--blender <path>` | The Blender executable to use |
172
+ | `--no-scripts` | Never run C# or Python scripts on this computer, whatever Allow scripts says |
173
+
174
+ Without `--install-service`, `bt-agent bridge [--pair <code>]` runs the bridge in the terminal until
175
+ Ctrl-C. With no stored pairing and no `--pair`, it says so and exits: copy the install command from
176
+ the Unity Bridge dialog. `bt-agent bridge status` shows the App Builders this computer is paired with
177
+ and whether the service is installed; `bt-agent bridge logout [--server <url>]` unpairs it (all App
178
+ Builders by default) and deletes the credentials. `bt-agent doctor` reports the service state too.
179
+ Credentials and service settings live in `~/.babylon-toolkit/bridge.json`, readable by you only.
180
+
181
+ Everything the App Builder asks for falls into one of three tiers, and this computer enforces
182
+ them itself:
183
+
184
+ | Tier | What it covers | When it runs |
185
+ |------|----------------|--------------|
186
+ | allowed | Listing, opening and creating projects in the projects folder; reading the project and ordinary edits | Straight away |
187
+ | scripts | Running C# or Python scripts | Only when **Allow scripts** is on for this computer in the App Builder's Unity Bridge dialog (on by default), and never with `--no-scripts` |
188
+ | consent | Deleting, moving, renaming, building, changing project settings | Only after you approve it in the chat |
189
+
190
+ The service is opt-in: `bt-agent install`, `bt-agent update` and the npm postinstall never start,
191
+ pair or schedule the bridge.
192
+
124
193
  ## Skills
125
194
 
126
195
  | Skill | Command | What it does |
127
196
  |-------|---------|--------------|
128
- | [`bt-spec`](skills/bt-spec/SKILL.md) | `/bt-spec` | Turn a short idea into a feature spec file on a new git branch. Add `--grill-me` to be interviewed first, `--parity` to allow numeric parity bars in the acceptance criteria. |
129
- | [`bt-plan`](skills/bt-plan/SKILL.md) | `/bt-plan` | Produce a detailed, task-checklist technical plan from a spec. Add `--heavy` for a decision-complete plan that keeps a long, fresh-context-per-task run cohesive, and `--parity` for numeric parity gates instead of the default functional proof. |
130
- | [`bt-execute`](skills/bt-execute/SKILL.md) | `/bt-execute` | Implement one task, a range (`T3-T7`, `T12-`, `NEXT:3`) or all remaining tasks from a plan/spec; with no task id it runs the next unchecked task. Add `--auto-pilot` for an unattended overnight run that never stops for human input, and `--strict` for an adversarial verifier on every task. |
197
+ | [`bt-spec`](skills/bt-spec/SKILL.md) | `/bt-spec` | Turn a short idea into a feature spec file on a new git branch. Add `--grill-me` to be interviewed first, `--parity` to allow numeric parity bars in the acceptance criteria. Runs in `TIME MATTERS` mode by default; `--no-time-limit` turns it off. |
198
+ | [`bt-plan`](skills/bt-plan/SKILL.md) | `/bt-plan` | Produce a detailed, task-checklist technical plan from a spec. Add `--heavy` for a decision-complete plan that keeps a long, fresh-context-per-task run cohesive, and `--parity` for numeric parity gates instead of the default functional proof. Runs in `TIME MATTERS` mode by default; `--no-time-limit` turns it off. |
199
+ | [`bt-execute`](skills/bt-execute/SKILL.md) | `/bt-execute` | Implement one task, a range (`T3-T7`, `T12-`, `NEXT:3`) or all remaining tasks from a plan/spec; with no task id it runs the next unchecked task. Add `--auto-pilot` for an unattended overnight run that never stops for human input, and `--strict` for an adversarial verifier on every task. Runs in `TIME MATTERS` mode by default; `--no-time-limit` turns it off. |
131
200
  | [`bt-convert`](skills/bt-convert/SKILL.md) | `/bt-convert` | Convert source code to Babylon Toolkit TypeScript. |
132
201
  | [`bt-copycat`](skills/bt-copycat/SKILL.md) | `/bt-copycat` | Re-create the specified website adapted to specified genre. |
133
202
  | [`bt-landing`](skills/bt-landing/SKILL.md) | `/bt-landing` | Re-design the landing page, splash screen, preloader and custom overlays. |
@@ -198,9 +267,13 @@ implementer writes the tests and the independent verifier judges them.
198
267
  ```
199
268
 
200
269
  Auto-pilot is for running a 50-task plan overnight. There is no one to ask, so `bt-execute`
201
- makes every call itself — from the plan's Decisions, then the Babylon Toolkit Agent Reference
202
- (Unity → interactive glTF → BabylonJS script components), then the codebase, then senior-developer
203
- default — and logs each one. Nothing is relaxed on quality: every task still has passing tests
270
+ owns the whole pipeline — code, UI, shaders, generated art and audio, Blender, Unity, export,
271
+ build, dev server and visual QA — and makes every call itself: it first looks the answer up in the
272
+ brief, plan, spec and `SPEC.md`, then the Babylon Toolkit Agent Reference (Unity → interactive glTF
273
+ → BabylonJS script components), then the codebase, then senior-developer default — and logs each
274
+ one. It never asks a question and never ends its
275
+ turn until the requested range, or every task, is done; it stops early only for a missing plan, a
276
+ bad range, a stop point named in the brief, or you telling it to stop. Nothing is relaxed on quality: every task still has passing tests
204
277
  and goes through an independent verifier, and a box only flips on a genuine PASS.
205
278
  What changes is that a failure never halts the run: a failing task gets a bounded fix loop (3
206
279
  attempts, 5 under `--strict`), is then marked `⏭️ DEFERRED (auto-pilot): <reason>` in the plan, and the run moves
package/bin/bt-agent.js CHANGED
@@ -24,6 +24,7 @@ Commands
24
24
  uninstall Remove what this tool installed, and nothing else
25
25
  doctor Verify the install; prints INSTALL OK or INSTALL FAILED
26
26
  targets List the available targets and their paths
27
+ bridge Connect this computer to the App Builder (Unity/Blender); see bt-agent bridge --help
27
28
 
28
29
  Options
29
30
  --project Install into the current directory instead of $HOME
@@ -44,6 +45,7 @@ Examples
44
45
  bt-agent install --project
45
46
  bt-agent doctor
46
47
  bt-agent update
48
+ bt-agent bridge --install-service --pair <code from the Unity Bridge dialog>
47
49
  `;
48
50
 
49
51
  function parseArgs(argv) {
@@ -248,6 +250,13 @@ function printTargets(mode) {
248
250
  }
249
251
 
250
252
  function main() {
253
+ if (process.argv[2] === 'bridge') {
254
+ require('../lib/bridge/cli')
255
+ .runBridgeCli(process.argv.slice(3))
256
+ .then((code) => process.exit(code), (error) => { console.error(error.message); process.exit(1); });
257
+ return;
258
+ }
259
+
251
260
  let opts;
252
261
  try {
253
262
  opts = parseArgs(process.argv.slice(2));
@@ -366,7 +375,20 @@ function main() {
366
375
  case 'doctor': {
367
376
  const result = doctor(common);
368
377
  if (opts.json) console.log(JSON.stringify(result, null, 2));
369
- else printDoctor(result);
378
+ else {
379
+ printDoctor(result);
380
+ console.log(
381
+ result.bridge.paired
382
+ ? ` bridge paired with ${result.bridge.servers.join(', ')}`
383
+ : ' bridge not paired (copy the install command from the Unity Bridge dialog in the App Builder)'
384
+ );
385
+ console.log(
386
+ ` bridge service: ${result.bridge.service}${result.bridge.serviceRunning === true ? ' (running)' : result.bridge.serviceRunning === false ? ' (not running)' : ''}`
387
+ );
388
+ console.log(
389
+ ` bridge unity CLI ${result.bridge.unityCli ? 'found' : 'not found'}; ${result.bridge.blender ? 'Blender ' + result.bridge.blender : 'Blender not found'}`
390
+ );
391
+ }
370
392
  process.exit(result.ok ? 0 : 1);
371
393
  break;
372
394
  }
@@ -0,0 +1,74 @@
1
+ 'use strict';
2
+
3
+ /** The server refused this helper's protocol version (HTTP 426). */
4
+ class UpdateRequiredError extends Error {
5
+ /** @param {string} message */
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = 'UpdateRequiredError';
9
+ }
10
+ }
11
+
12
+ /** The device token is unknown or revoked (HTTP 401). */
13
+ class NotPairedError extends Error {
14
+ /** @param {string} [message] */
15
+ constructor(message = 'This device is not paired.') {
16
+ super(message);
17
+ this.name = 'NotPairedError';
18
+ }
19
+ }
20
+
21
+ /**
22
+ * Minimal JSON client for the App Builder's bridge routes. The token travels only in the
23
+ * `authorization` header, never in a URL (D8).
24
+ */
25
+ class BridgeApi {
26
+ /**
27
+ * @param {string} server origin, no trailing slash
28
+ * @param {string} [token]
29
+ */
30
+ constructor(server, token) {
31
+ this.server = server;
32
+ this.token = token;
33
+ }
34
+
35
+ /**
36
+ * @param {string} path
37
+ * @param {unknown} body
38
+ * @param {AbortSignal} [signal]
39
+ * @returns {Promise<{ status: number, body: any }>}
40
+ */
41
+ async post(path, body, signal) {
42
+ /** @type {Record<string, string>} */
43
+ const headers = { 'content-type': 'application/json', accept: 'application/json' };
44
+ if (this.token) headers.authorization = `Bearer ${this.token}`;
45
+
46
+ const res = await fetch(`${this.server}${path}`, {
47
+ method: 'POST',
48
+ headers,
49
+ body: JSON.stringify(body ?? {}),
50
+ signal,
51
+ });
52
+
53
+ let parsed = null;
54
+ try {
55
+ parsed = await res.json();
56
+ } catch {
57
+ parsed = null;
58
+ }
59
+
60
+ if (res.status === 426) {
61
+ throw new UpdateRequiredError(
62
+ (parsed && typeof parsed.message === 'string' && parsed.message) ||
63
+ 'This Desktop Agent is too old for the App Builder.'
64
+ );
65
+ }
66
+ if (res.status === 401) {
67
+ throw new NotPairedError((parsed && typeof parsed.message === 'string' && parsed.message) || undefined);
68
+ }
69
+
70
+ return { status: res.status, body: parsed };
71
+ }
72
+ }
73
+
74
+ module.exports = { BridgeApi, UpdateRequiredError, NotPairedError };
@@ -0,0 +1,172 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Argument parser for `bt-agent bridge` (D46 — it runs before, and instead of, the installer's parser).
5
+ *
6
+ * @typedef {'run'|'install-service'|'uninstall-service'|'service'|'logout'|'status'|'help'} BridgeCommand
7
+ * @typedef {{
8
+ * command: BridgeCommand,
9
+ * servers: string[],
10
+ * serverExplicit: boolean,
11
+ * server?: string,
12
+ * pair?: string,
13
+ * projects: string[],
14
+ * unity: string[],
15
+ * blender?: string,
16
+ * noScripts: boolean,
17
+ * errors: string[],
18
+ * }} BridgeArgs
19
+ *
20
+ * `servers` is every App Builder this run talks to: the `--server` flags (repeatable), else
21
+ * `BTK_BRIDGE_SERVER`, else the production App Builder (D55 — end users never type a URL).
22
+ * `serverExplicit` says whether the user named them; `status` and `logout` without one mean "all".
23
+ * `server` is `servers[0]`, kept for callers that only ever talk to one.
24
+ */
25
+
26
+ /**
27
+ * The production App Builder (D55, owner 2026-09-29: "why do I have to specify the server url?").
28
+ * This is the Desktop Agent package, not the app — the app's no-hardcoded-URL rule does not govern it.
29
+ */
30
+ const DEFAULT_SERVER = 'https://app.babylontoolkit.com';
31
+
32
+ /** An install code as the Unity Bridge dialog shows it: `XXXX-XXXX` (case and the dash are forgiven). */
33
+ const PAIR_CODE = /^[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}$/;
34
+
35
+ const MODE_FLAGS = /** @type {const} */ ({
36
+ '--install-service': 'install-service',
37
+ '--uninstall-service': 'uninstall-service',
38
+ '--service': 'service',
39
+ });
40
+
41
+ /**
42
+ * `https://…` anywhere, or plain http to this machine only. Anything else would send the device
43
+ * token in clear text.
44
+ * @param {string} server
45
+ * @returns {boolean}
46
+ */
47
+ function isAcceptableServer(server) {
48
+ let url;
49
+ try {
50
+ url = new URL(server);
51
+ } catch {
52
+ return false;
53
+ }
54
+ if (url.protocol === 'https:') return Boolean(url.hostname);
55
+ if (url.protocol !== 'http:') return false;
56
+ return url.hostname === 'localhost' || url.hostname === '127.0.0.1';
57
+ }
58
+
59
+ /**
60
+ * @param {string[]} argv arguments after `bridge`
61
+ * @param {Record<string, string|undefined>} [env]
62
+ * @returns {BridgeArgs}
63
+ */
64
+ function parseBridgeArgs(argv, env = process.env) {
65
+ /** @type {BridgeArgs} */
66
+ const out = { command: 'run', servers: [], serverExplicit: false, projects: [], unity: [], noScripts: false, errors: [] };
67
+ /** @type {string[]} */
68
+ const flagServers = [];
69
+ let help = false;
70
+ /** @type {string|undefined} */
71
+ let positional;
72
+ /** @type {BridgeCommand|undefined} */
73
+ let mode;
74
+
75
+ /** @param {string} flag @param {number} i */
76
+ const valueOf = (flag, i) => {
77
+ const value = argv[i];
78
+ if (value === undefined || value.startsWith('-')) {
79
+ out.errors.push(`${flag} needs a value`);
80
+ return undefined;
81
+ }
82
+ return value;
83
+ };
84
+
85
+ for (let i = 0; i < argv.length; i += 1) {
86
+ const arg = argv[i];
87
+ switch (arg) {
88
+ case '-h':
89
+ case '--help':
90
+ help = true;
91
+ break;
92
+ case '--server': {
93
+ const v = valueOf(arg, i + 1);
94
+ if (v !== undefined) {
95
+ i += 1;
96
+ flagServers.push(v);
97
+ }
98
+ break;
99
+ }
100
+ case '--pair': {
101
+ const v = valueOf(arg, i + 1);
102
+ if (v !== undefined) {
103
+ i += 1;
104
+ if (PAIR_CODE.test(v.trim())) out.pair = v.trim().toUpperCase();
105
+ else out.errors.push(`--pair needs the install code from the Unity Bridge dialog (like K7QM-2XWD), not "${v}"`);
106
+ }
107
+ break;
108
+ }
109
+ case '--projects': {
110
+ const v = valueOf(arg, i + 1);
111
+ if (v !== undefined) {
112
+ i += 1;
113
+ out.projects.push(v);
114
+ }
115
+ break;
116
+ }
117
+ case '--unity': {
118
+ const v = valueOf(arg, i + 1);
119
+ if (v !== undefined) {
120
+ i += 1;
121
+ out.unity.push(v);
122
+ }
123
+ break;
124
+ }
125
+ case '--blender': {
126
+ const v = valueOf(arg, i + 1);
127
+ if (v !== undefined) {
128
+ i += 1;
129
+ out.blender = v;
130
+ }
131
+ break;
132
+ }
133
+ case '--no-scripts':
134
+ out.noScripts = true;
135
+ break;
136
+ case '--install-service':
137
+ case '--uninstall-service':
138
+ case '--service': {
139
+ const m = MODE_FLAGS[arg];
140
+ if (mode && mode !== m) out.errors.push(`${arg} cannot be combined with --${mode}`);
141
+ else mode = m;
142
+ break;
143
+ }
144
+ case 'logout':
145
+ case 'status':
146
+ if (positional) out.errors.push(`Unknown option: ${arg}`);
147
+ else positional = arg;
148
+ break;
149
+ default:
150
+ out.errors.push(`Unknown option: ${arg}`);
151
+ }
152
+ }
153
+
154
+ if (positional && mode) out.errors.push(`${positional} cannot be combined with --${mode}`);
155
+ out.command = help ? 'help' : mode || /** @type {'logout'|'status'|undefined} */ (positional) || 'run';
156
+
157
+ /** @type {string[]} */
158
+ let raw = flagServers;
159
+ if (!raw.length && env.BTK_BRIDGE_SERVER) raw = [env.BTK_BRIDGE_SERVER];
160
+ out.serverExplicit = raw.length > 0;
161
+ if (!raw.length) raw = [DEFAULT_SERVER];
162
+ for (const r of raw) {
163
+ const server = r.replace(/\/+$/, '');
164
+ if (!isAcceptableServer(server)) out.errors.push(`refusing a non-HTTPS server: ${r}`);
165
+ else if (!out.servers.includes(server)) out.servers.push(server);
166
+ }
167
+ out.server = out.servers[0];
168
+
169
+ return out;
170
+ }
171
+
172
+ module.exports = { parseBridgeArgs, isAcceptableServer, DEFAULT_SERVER, PAIR_CODE };
@@ -0,0 +1,98 @@
1
+ 'use strict';
2
+
3
+ /** Finds Blender on this computer (T25 step 1, D40). Read-only: it runs `blender --version` only. */
4
+
5
+ const fs = require('fs');
6
+ const path = require('path');
7
+ const { execFileSync } = require('child_process');
8
+
9
+ /** @typedef {(file: string, args: string[]) => string|undefined} Exec */
10
+
11
+ /** @type {Exec} */
12
+ function defaultExec(file, args) {
13
+ try {
14
+ return execFileSync(file, args, {
15
+ encoding: 'utf8',
16
+ timeout: 20_000,
17
+ stdio: ['ignore', 'pipe', 'ignore'],
18
+ windowsHide: true,
19
+ });
20
+ } catch {
21
+ return undefined;
22
+ }
23
+ }
24
+
25
+ /** @param {string} p */
26
+ function isFile(p) {
27
+ try {
28
+ return fs.statSync(p).isFile();
29
+ } catch {
30
+ return false;
31
+ }
32
+ }
33
+
34
+ /** @param {string} name e.g. "Blender 4.2" @returns {number[]} */
35
+ function versionOf(name) {
36
+ const m = /(\d+(?:\.\d+)*)/.exec(name);
37
+ return m ? m[1].split('.').map((n) => parseInt(n, 10) || 0) : [0];
38
+ }
39
+
40
+ /** @param {number[]} a @param {number[]} b */
41
+ function compare(a, b) {
42
+ for (let i = 0; i < Math.max(a.length, b.length); i += 1) {
43
+ const d = (a[i] || 0) - (b[i] || 0);
44
+ if (d !== 0) return d;
45
+ }
46
+ return 0;
47
+ }
48
+
49
+ /**
50
+ * The highest-version `<Program Files>\Blender Foundation\Blender *\blender.exe`.
51
+ * @param {Record<string, string|undefined>} env
52
+ * @returns {string|undefined}
53
+ */
54
+ function windowsInstall(env) {
55
+ const base = path.win32.join(env.ProgramFiles || 'C:\\Program Files', 'Blender Foundation');
56
+ let dirs;
57
+ try {
58
+ dirs = fs.readdirSync(base).filter((d) => /^Blender\b/i.test(d));
59
+ } catch {
60
+ return undefined;
61
+ }
62
+ dirs.sort((a, b) => compare(versionOf(b), versionOf(a)));
63
+ for (const d of dirs) {
64
+ const exe = path.win32.join(base, d, 'blender.exe');
65
+ if (isFile(exe)) return exe;
66
+ }
67
+ return undefined;
68
+ }
69
+
70
+ /**
71
+ * @param {{ explicit?: string, platform?: string, env?: Record<string, string|undefined>, exec?: Exec }} [opts]
72
+ * @returns {{ path: string, version: string } | undefined}
73
+ */
74
+ function discoverBlender({ explicit, platform = process.platform, env = process.env, exec = defaultExec } = {}) {
75
+ /** @type {string[]} */
76
+ const candidates = [];
77
+ if (explicit) candidates.push(path.resolve(explicit));
78
+ if (platform === 'darwin') candidates.push('/Applications/Blender.app/Contents/MacOS/Blender');
79
+ if (platform === 'win32') {
80
+ const found = windowsInstall(env);
81
+ if (found) candidates.push(found);
82
+ }
83
+ const which = exec(platform === 'win32' ? 'where' : 'which', ['blender']);
84
+ const onPath = which && which.split(/\r?\n/).map((l) => l.trim()).find(Boolean);
85
+ if (onPath) candidates.push(onPath);
86
+
87
+ for (const candidate of candidates) {
88
+ if (!isFile(candidate)) continue;
89
+ const out = exec(candidate, ['--version']);
90
+ const line = out && out.split(/\r?\n/).map((l) => l.trim()).find(Boolean);
91
+ // The first --version line is "Blender 5.1.2"; report the number, or the UI and the model note read "Blender Blender 5.1.2".
92
+ const version = line && (line.replace(/^Blender\s+/i, '') || line);
93
+ if (version) return { path: candidate, version };
94
+ }
95
+ return undefined;
96
+ }
97
+
98
+ module.exports = { discoverBlender };
@@ -0,0 +1,141 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Runs one Blender script job (T25 step 2, D40):
5
+ * "$BLENDER" --background --factory-startup --python-exit-code 1 --python <script> -- <jobDir>/io.json
6
+ *
7
+ * Every input and output is resolved under the Unity project; existing outputs inside `Assets/` are
8
+ * copied to `<file>~` first; every declared output must be written by THIS run, or the job fails
9
+ * naming the missing files.
10
+ */
11
+
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+
15
+ const defaultLog = require('../log');
16
+ const { capText, isSafeJobId } = require('../protocol');
17
+ const { helperTier, resolveProjectPath, pruneEmptyScratchDirs } = require('../unity/guard');
18
+ const { runProcess: defaultRunProcess } = require('../unity/run');
19
+
20
+ const PREAMBLE =
21
+ "import json, sys\n_io = json.load(open(sys.argv[sys.argv.index('--') + 1]))\nBRIDGE_INPUTS = _io['inputs']\nBRIDGE_OUTPUTS = _io['outputs']\n";
22
+ const NO_BLENDER = 'Blender was not found on this computer. Run bt-agent bridge with --blender <path>.';
23
+ const CANCELLED = 'Cancel requested — the Blender run was stopped.';
24
+ const PROGRESS_EVERY_MS = 500;
25
+
26
+ /**
27
+ * @param {import('../protocol').BridgeDispatch} dispatch
28
+ * @param {{
29
+ * project: { key: string, name: string, root: string, toolkitVersion?: string },
30
+ * blender?: { path: string, version: string },
31
+ * emit: (event: import('../protocol').BridgeJobEvent) => Promise<void>,
32
+ * signal?: AbortSignal,
33
+ * noScripts?: boolean,
34
+ * runProcess?: import('../unity/run').RunProcess,
35
+ * log?: { op: (tier: string, label: string) => void },
36
+ * now?: () => number,
37
+ * }} deps
38
+ * @returns {Promise<void>}
39
+ */
40
+ async function executeBlender(dispatch, deps) {
41
+ const { project, blender, emit, signal, noScripts = false, runProcess = defaultRunProcess, log = defaultLog, now = Date.now } = deps;
42
+ const jobId = dispatch.jobId;
43
+ // The id names the job folder that is removed afterwards — never run one that is not a plain token (D3).
44
+ if (!isSafeJobId(jobId)) return;
45
+ const op = /** @type {any} */ (dispatch.op);
46
+ const P = project.root;
47
+ /** @param {string} reason */
48
+ const refuse = (reason) => emit({ jobId, type: 'refused', reason });
49
+
50
+ // 1. guard: tiers, then every input and output under the project
51
+ const tier = helperTier(dispatch, project, { noScripts });
52
+ if (!tier.ok) return refuse(tier.reason);
53
+ if (op.kind !== 'blender.script') return refuse(`This runner only runs Blender scripts, not "${op.kind}".`);
54
+ /** @type {string[]} */
55
+ const inputs = [];
56
+ /** @type {string[]} */
57
+ const outputs = [];
58
+ for (const [list, into] of /** @type {[string[], string[]][]} */ ([
59
+ [op.inputs, inputs],
60
+ [op.outputs, outputs],
61
+ ])) {
62
+ for (const rel of list) {
63
+ const abs = resolveProjectPath(P, rel);
64
+ if (!abs) return refuse(`The path "${rel}" is outside the Unity project.`);
65
+ into.push(abs);
66
+ }
67
+ }
68
+ if (!blender) return refuse(NO_BLENDER);
69
+
70
+ // 2–4. job dir, io.json, script.py, backups
71
+ const jobDir = path.join(P, '.bridge', 'blender', jobId);
72
+ fs.mkdirSync(jobDir, { recursive: true });
73
+ const ioPath = path.join(jobDir, 'io.json');
74
+ const scriptPath = path.join(jobDir, 'script.py');
75
+ fs.writeFileSync(ioPath, JSON.stringify({ inputs, outputs }));
76
+ fs.writeFileSync(scriptPath, PREAMBLE + '\n' + op.source);
77
+ const assets = path.join(P, 'Assets') + path.sep;
78
+ // Decide every backup BEFORE writing any: a model that also declares `Knight.fbx~` would otherwise get the
79
+ // fresh backup of Knight.fbx backed up again as `Knight.fbx~~`. A `~` file is itself a backup — never re-backed-up.
80
+ const toBackUp = outputs.filter((out) => out.startsWith(assets) && !out.endsWith('~') && fs.existsSync(out));
81
+ for (const out of toBackUp) fs.copyFileSync(out, `${out}~`);
82
+ for (const out of outputs) fs.mkdirSync(path.dirname(out), { recursive: true });
83
+
84
+ // 5. started
85
+ await emit({ jobId, type: 'started' });
86
+ log.op(tier.tier, `blender ${path.basename(blender.path)} (${outputs.length} output(s))`);
87
+
88
+ let lastProgress = 0;
89
+ /** @param {string} line */
90
+ const onLine = (line) => {
91
+ const t = now();
92
+ if (t - lastProgress < PROGRESS_EVERY_MS) return;
93
+ lastProgress = t;
94
+ emit({ jobId, type: 'progress', line: capText(line, 500) }).catch(() => {});
95
+ };
96
+
97
+ // 6. run
98
+ const startMs = now();
99
+ let result;
100
+ try {
101
+ const res = await runProcess(
102
+ blender.path,
103
+ ['--background', '--factory-startup', '--python-exit-code', '1', '--python', scriptPath, '--', ioPath],
104
+ { cwd: P, timeoutMs: op.timeoutSeconds * 1000, signal, onLine }
105
+ );
106
+ const text = [res.stdout, res.stderr].filter(Boolean).join('\n');
107
+ if (res.aborted || (signal && signal.aborted)) {
108
+ result = { ok: false, text: CANCELLED };
109
+ } else if (res.timedOut) {
110
+ result = { ok: false, text: capText(`Blender timed out after ${op.timeoutSeconds} s.\n${text}`) };
111
+ } else {
112
+ // 7. every declared output must be written by this run
113
+ const missing = outputs.filter((out) => {
114
+ try {
115
+ return fs.statSync(out).mtimeMs < startMs;
116
+ } catch {
117
+ return true;
118
+ }
119
+ });
120
+ if (missing.length) {
121
+ const names = missing.map((m) => path.relative(P, m).split(path.sep).join('/'));
122
+ result = { ok: false, text: capText(`Blender finished but did not write: ${names.join(', ')}\n${text}`), exitCode: res.code ?? undefined };
123
+ } else {
124
+ // 8.
125
+ result = { ok: res.code === 0, text: capText(text || `Blender exited with code ${res.code}`), exitCode: res.code ?? undefined };
126
+ }
127
+ }
128
+ } catch (err) {
129
+ result = { ok: false, text: `The Desktop Agent failed: ${err && err.message ? err.message : err}` };
130
+ } finally {
131
+ try {
132
+ fs.rmSync(jobDir, { recursive: true, force: true });
133
+ } catch {
134
+ // scratch clean-up is best effort
135
+ }
136
+ pruneEmptyScratchDirs(P);
137
+ }
138
+ await emit({ jobId, type: 'final', result });
139
+ }
140
+
141
+ module.exports = { executeBlender, PREAMBLE, NO_BLENDER };