@babylonjs-toolkit/agent 1.1.38 → 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.
- package/README.md +73 -4
- package/bin/bt-agent.js +23 -1
- package/lib/bridge/api.js +74 -0
- package/lib/bridge/args.js +172 -0
- package/lib/bridge/blender/discover.js +98 -0
- package/lib/bridge/blender/run.js +141 -0
- package/lib/bridge/cli.js +677 -0
- package/lib/bridge/config.js +193 -0
- package/lib/bridge/log.js +103 -0
- package/lib/bridge/loop.js +239 -0
- package/lib/bridge/pairing.js +101 -0
- package/lib/bridge/policy.js +396 -0
- package/lib/bridge/protocol.js +91 -0
- package/lib/bridge/service.js +395 -0
- package/lib/bridge/unity/automation.js +135 -0
- package/lib/bridge/unity/discover.js +606 -0
- package/lib/bridge/unity/guard.js +208 -0
- package/lib/bridge/unity/ops.js +1294 -0
- package/lib/bridge/unity/run.js +169 -0
- package/lib/bridge/unity/scaffold/bt-bootstrap.cs +39 -0
- package/lib/bridge/unity/scaffold/bt-newscene.cs +27 -0
- package/lib/doctor.js +33 -0
- package/package.json +1 -1
- package/skills/bt-execute/SKILL.md +4 -2
- package/skills/bt-plan/SKILL.md +4 -2
- package/skills/bt-spec/SKILL.md +5 -2
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
|
|
6
|
+
const { stateDir } = require('../paths');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The bridge settings (D42, D55): `~/.babylon-toolkit/bridge.json`, mode 0600.
|
|
10
|
+
*
|
|
11
|
+
* One file holds the credential for every App Builder this computer is paired with, plus the settings
|
|
12
|
+
* the start-at-login service runs with (written by `--install-service`). A file in the old single-server
|
|
13
|
+
* shape `{ server, deviceId, token }` is read as one entry in `servers`.
|
|
14
|
+
*
|
|
15
|
+
* @typedef {{ server: string, deviceId: string, token: string }} BridgeConfig one server's credential
|
|
16
|
+
* @typedef {{
|
|
17
|
+
* servers: BridgeConfig[],
|
|
18
|
+
* projects: string[],
|
|
19
|
+
* unity: string[],
|
|
20
|
+
* blender?: string,
|
|
21
|
+
* noScripts: boolean,
|
|
22
|
+
* currentProject?: string,
|
|
23
|
+
* }} BridgeSettings
|
|
24
|
+
* `currentProject` — the absolute root of the Unity project opened or created last, so a restarted service
|
|
25
|
+
* picks up where it left off instead of making the model reopen it (verifier, 2026-09-29).
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
function bridgeConfigPath() {
|
|
29
|
+
return path.join(stateDir('global'), 'bridge.json');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** @returns {BridgeSettings} */
|
|
33
|
+
function emptySettings() {
|
|
34
|
+
return { servers: [], projects: [], unity: [], noScripts: false };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** @param {any} c @returns {c is BridgeConfig} */
|
|
38
|
+
function isCredential(c) {
|
|
39
|
+
return Boolean(c) && typeof c.server === 'string' && typeof c.deviceId === 'string' && typeof c.token === 'string';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** @param {unknown} v @returns {string[]} */
|
|
43
|
+
function strings(v) {
|
|
44
|
+
return Array.isArray(v) ? v.filter((s) => typeof s === 'string' && s.length > 0) : [];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Normalises whatever is on disk into the current shape — including the old single-credential file.
|
|
49
|
+
* @param {any} raw
|
|
50
|
+
* @returns {BridgeSettings}
|
|
51
|
+
*/
|
|
52
|
+
function migrateSettings(raw) {
|
|
53
|
+
const out = emptySettings();
|
|
54
|
+
if (!raw || typeof raw !== 'object') return out;
|
|
55
|
+
if (Array.isArray(raw.servers)) {
|
|
56
|
+
for (const c of raw.servers) {
|
|
57
|
+
if (isCredential(c) && !out.servers.some((s) => s.server === c.server)) {
|
|
58
|
+
out.servers.push({ server: c.server, deviceId: c.deviceId, token: c.token });
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
} else if (isCredential(raw)) {
|
|
62
|
+
out.servers.push({ server: raw.server, deviceId: raw.deviceId, token: raw.token });
|
|
63
|
+
}
|
|
64
|
+
out.projects = strings(raw.projects);
|
|
65
|
+
out.unity = strings(raw.unity);
|
|
66
|
+
if (typeof raw.blender === 'string' && raw.blender) out.blender = raw.blender;
|
|
67
|
+
out.noScripts = raw.noScripts === true;
|
|
68
|
+
if (typeof raw.currentProject === 'string' && raw.currentProject) out.currentProject = raw.currentProject;
|
|
69
|
+
return out;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The stored settings; an absent or unreadable file is empty settings (nothing paired).
|
|
74
|
+
* @param {string} [file]
|
|
75
|
+
* @returns {BridgeSettings}
|
|
76
|
+
*/
|
|
77
|
+
function readSettings(file = bridgeConfigPath()) {
|
|
78
|
+
try {
|
|
79
|
+
return migrateSettings(JSON.parse(fs.readFileSync(file, 'utf8')));
|
|
80
|
+
} catch {
|
|
81
|
+
return emptySettings();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @param {BridgeSettings} settings
|
|
87
|
+
* @param {string} [file]
|
|
88
|
+
* @returns {string} the file written
|
|
89
|
+
*/
|
|
90
|
+
function writeSettings(settings, file = bridgeConfigPath()) {
|
|
91
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
92
|
+
/** @type {Record<string, unknown>} */
|
|
93
|
+
const out = {
|
|
94
|
+
servers: settings.servers.map((c) => ({ server: c.server, deviceId: c.deviceId, token: c.token })),
|
|
95
|
+
projects: settings.projects,
|
|
96
|
+
unity: settings.unity,
|
|
97
|
+
noScripts: settings.noScripts === true,
|
|
98
|
+
};
|
|
99
|
+
if (settings.blender) out.blender = settings.blender;
|
|
100
|
+
if (settings.currentProject) out.currentProject = settings.currentProject;
|
|
101
|
+
fs.writeFileSync(file, JSON.stringify(out, null, 2), { mode: 0o600 });
|
|
102
|
+
// `mode` only applies when the file is created; tighten an existing one too.
|
|
103
|
+
if (process.platform !== 'win32') fs.chmodSync(file, 0o600);
|
|
104
|
+
return file;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The stored credential for `server` — or, with no server, the first one. Null when not paired
|
|
109
|
+
* (a credential for one App Builder is "not paired" for every other one).
|
|
110
|
+
* @param {string} [server]
|
|
111
|
+
* @param {string} [file]
|
|
112
|
+
* @returns {BridgeConfig|null}
|
|
113
|
+
*/
|
|
114
|
+
function readBridgeConfig(server, file) {
|
|
115
|
+
const { servers } = readSettings(file);
|
|
116
|
+
const found = server === undefined ? servers[0] : servers.find((c) => c.server === server);
|
|
117
|
+
return found ? { ...found } : null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Adds or replaces one server's credential, keeping every other setting.
|
|
122
|
+
* @param {BridgeConfig} cfg
|
|
123
|
+
* @param {string} [file]
|
|
124
|
+
*/
|
|
125
|
+
function writeBridgeConfig(cfg, file) {
|
|
126
|
+
const settings = readSettings(file);
|
|
127
|
+
settings.servers = settings.servers.filter((c) => c.server !== cfg.server);
|
|
128
|
+
settings.servers.push({ server: cfg.server, deviceId: cfg.deviceId, token: cfg.token });
|
|
129
|
+
return writeSettings(settings, file);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Forgets one server's credential (or, with no server, the whole file).
|
|
134
|
+
* @param {string} [server]
|
|
135
|
+
* @param {string} [file]
|
|
136
|
+
*/
|
|
137
|
+
function deleteBridgeConfig(server, file = bridgeConfigPath()) {
|
|
138
|
+
if (server === undefined) {
|
|
139
|
+
fs.rmSync(file, { force: true });
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
if (!fs.existsSync(file)) return;
|
|
143
|
+
const settings = readSettings(file);
|
|
144
|
+
settings.servers = settings.servers.filter((c) => c.server !== server);
|
|
145
|
+
writeSettings(settings, file);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Remembers the current Unity project (the root), keeping every other setting. Never throws — losing this
|
|
150
|
+
* only costs a reopen, and it must never fail the job that changed the project.
|
|
151
|
+
* @param {string|undefined} root
|
|
152
|
+
* @param {string} [file]
|
|
153
|
+
*/
|
|
154
|
+
function saveCurrentProject(root, file = bridgeConfigPath()) {
|
|
155
|
+
try {
|
|
156
|
+
const settings = readSettings(file);
|
|
157
|
+
if ((settings.currentProject || undefined) === (root || undefined)) return;
|
|
158
|
+
if (root) settings.currentProject = root;
|
|
159
|
+
else delete settings.currentProject;
|
|
160
|
+
writeSettings(settings, file);
|
|
161
|
+
} catch {
|
|
162
|
+
/* best effort */
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* The stored current project to restore on start: only when it still exists as a Unity project DIRECTLY inside
|
|
168
|
+
* one of the configured projects folders (the only projects this helper serves, D54) — otherwise nothing.
|
|
169
|
+
* @param {string|undefined} stored
|
|
170
|
+
* @param {string[]} projectsDirs absolute
|
|
171
|
+
* @param {{ isProject: (root: string) => boolean, real?: (p: string) => string }} io
|
|
172
|
+
* @returns {string|undefined}
|
|
173
|
+
*/
|
|
174
|
+
function restorableCurrentProject(stored, projectsDirs, { isProject, real = (p) => p }) {
|
|
175
|
+
if (typeof stored !== 'string' || !stored || !path.isAbsolute(stored)) return undefined;
|
|
176
|
+
const root = real(stored);
|
|
177
|
+
const parent = path.dirname(root);
|
|
178
|
+
if (!projectsDirs.some((dir) => real(dir) === parent)) return undefined;
|
|
179
|
+
return isProject(root) ? root : undefined;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
module.exports = {
|
|
183
|
+
saveCurrentProject,
|
|
184
|
+
restorableCurrentProject,
|
|
185
|
+
bridgeConfigPath,
|
|
186
|
+
readSettings,
|
|
187
|
+
writeSettings,
|
|
188
|
+
migrateSettings,
|
|
189
|
+
emptySettings,
|
|
190
|
+
readBridgeConfig,
|
|
191
|
+
writeBridgeConfig,
|
|
192
|
+
deleteBridgeConfig,
|
|
193
|
+
};
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const nodeFs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Terminal output for `bt-agent bridge`. Colour only on a TTY, so piped/logged output stays plain.
|
|
8
|
+
*
|
|
9
|
+
* The start-at-login service (D55) has no terminal: `toFile()` sends every line to
|
|
10
|
+
* `~/.babylon-toolkit/bridge.log` instead, time-stamped, and rotates it at 5 MB to `bridge.log.1`.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
const LOG_MAX_BYTES = 5 * 1024 * 1024;
|
|
14
|
+
|
|
15
|
+
/** @type {{ file: string, maxBytes: number, fs: typeof nodeFs, now: () => Date }|null} */
|
|
16
|
+
let sink = null;
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Appends one line to a size-capped log: when the file has reached `maxBytes` it becomes `<file>.1`
|
|
20
|
+
* (replacing the previous one) and a new file is started. Never throws — a log must not stop the bridge.
|
|
21
|
+
* @param {{ file: string, line: string, maxBytes?: number, fs?: typeof nodeFs }} opts
|
|
22
|
+
*/
|
|
23
|
+
function appendLogLine({ file, line, maxBytes = LOG_MAX_BYTES, fs = nodeFs }) {
|
|
24
|
+
try {
|
|
25
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
26
|
+
let size = 0;
|
|
27
|
+
try {
|
|
28
|
+
size = fs.statSync(file).size;
|
|
29
|
+
} catch {
|
|
30
|
+
size = 0;
|
|
31
|
+
}
|
|
32
|
+
if (size >= maxBytes) {
|
|
33
|
+
fs.rmSync(`${file}.1`, { force: true });
|
|
34
|
+
fs.renameSync(file, `${file}.1`);
|
|
35
|
+
}
|
|
36
|
+
fs.appendFileSync(file, `${line}\n`, { mode: 0o600 });
|
|
37
|
+
} catch {
|
|
38
|
+
// nowhere left to report it
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Sends all bridge output to `file` from now on.
|
|
44
|
+
* @param {string} file
|
|
45
|
+
* @param {{ maxBytes?: number, fs?: typeof nodeFs, now?: () => Date }} [opts]
|
|
46
|
+
*/
|
|
47
|
+
function toFile(file, opts = {}) {
|
|
48
|
+
sink = { file, maxBytes: opts.maxBytes || LOG_MAX_BYTES, fs: opts.fs || nodeFs, now: opts.now || (() => new Date()) };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Back to the terminal (tests). */
|
|
52
|
+
function toConsole() {
|
|
53
|
+
sink = null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** @param {string} level @param {string} text */
|
|
57
|
+
function write(level, text) {
|
|
58
|
+
if (!sink) return false;
|
|
59
|
+
const stamp = sink.now().toISOString();
|
|
60
|
+
for (const line of String(text).split(/\r?\n/)) {
|
|
61
|
+
if (!line.trim()) continue;
|
|
62
|
+
appendLogLine({ file: sink.file, line: `${stamp} ${level} ${line}`, maxBytes: sink.maxBytes, fs: sink.fs });
|
|
63
|
+
}
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** @param {string} code @param {string} text */
|
|
68
|
+
function paint(code, text) {
|
|
69
|
+
return process.stdout.isTTY ? `\x1b[${code}m${text}\x1b[0m` : text;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** @param {string} msg */
|
|
73
|
+
function info(msg) {
|
|
74
|
+
if (write('info ', msg)) return;
|
|
75
|
+
console.log(msg);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* One line per operation the bridge runs: `▶ [<tier>] <label>`.
|
|
80
|
+
* @param {string} tier
|
|
81
|
+
* @param {string} label
|
|
82
|
+
*/
|
|
83
|
+
function op(tier, label) {
|
|
84
|
+
if (write('op ', `[${tier}] ${label}`)) return;
|
|
85
|
+
console.log(`${paint('36', '▶')} ${paint('2', `[${tier}]`)} ${label}`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** @param {string} msg */
|
|
89
|
+
function error(msg) {
|
|
90
|
+
if (write('error', msg)) return;
|
|
91
|
+
console.error(process.stderr.isTTY ? `\x1b[31m${msg}\x1b[0m` : msg);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** @param {string[]} lines */
|
|
95
|
+
function box(lines) {
|
|
96
|
+
if (write('info ', lines.join('\n'))) return;
|
|
97
|
+
const width = Math.max(...lines.map((l) => l.length));
|
|
98
|
+
const bar = '─'.repeat(width + 2);
|
|
99
|
+
const out = [`┌${bar}┐`, ...lines.map((l) => `│ ${l.padEnd(width)} │`), `└${bar}┘`];
|
|
100
|
+
console.log(paint('1', out.join('\n')));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
module.exports = { info, op, error, box, toFile, toConsole, appendLogLine, LOG_MAX_BYTES };
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { NotPairedError, UpdateRequiredError } = require('./api');
|
|
4
|
+
const { deleteBridgeConfig } = require('./config');
|
|
5
|
+
const { capText, isSafeJobId } = require('./protocol');
|
|
6
|
+
const log = require('./log');
|
|
7
|
+
|
|
8
|
+
/** Network back-off: 1 s, 2 s, 5 s, 10 s, then 30 s thereafter; reset on the first success. */
|
|
9
|
+
const BACKOFF_MS = [1000, 2000, 5000, 10000, 30000];
|
|
10
|
+
|
|
11
|
+
/** @param {string} server */
|
|
12
|
+
const notPairedText = (server) =>
|
|
13
|
+
`This computer is not paired with ${server} — copy the install command from the Unity Bridge dialog again.`;
|
|
14
|
+
const NOT_PAIRED = notPairedText('the App Builder');
|
|
15
|
+
const STOPPED = 'The Desktop Agent bridge was stopped (Ctrl-C).';
|
|
16
|
+
const STOPPED_BEFORE_START = 'The Desktop Agent bridge was stopped before this job started.';
|
|
17
|
+
|
|
18
|
+
/** @param {number} ms */
|
|
19
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @typedef {import('./protocol').BridgeDispatch} BridgeDispatch
|
|
23
|
+
* @typedef {import('./protocol').BridgeJobEvent} BridgeJobEvent
|
|
24
|
+
* @typedef {(event: BridgeJobEvent) => Promise<void>} Emit
|
|
25
|
+
* @typedef {{ api?: any, server?: string }} JobSource the App Builder a job came from
|
|
26
|
+
* @typedef {(dispatch: BridgeDispatch, emit: Emit, signal: AbortSignal, source?: JobSource) => Promise<void>} Execute
|
|
27
|
+
* @typedef {{ reason: 'stopped'|'not-paired'|'update-required', message?: string }} LoopExit
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* THE job queue (D54, D55). Every job works on the helper's CURRENT project and `unity_project open`
|
|
32
|
+
* changes which one that is, so jobs run ONE at a time, in arrival order — and with several App Builders
|
|
33
|
+
* (one poll loop each) they still share this one queue, so two builders can never drive Unity at once.
|
|
34
|
+
* Each job remembers its owner (the loop that received it) and reports through that loop's `emit`.
|
|
35
|
+
*
|
|
36
|
+
* @param {{ execute: Execute, logger?: typeof log }} opts
|
|
37
|
+
*/
|
|
38
|
+
function createJobQueue({ execute, logger = log }) {
|
|
39
|
+
/** @typedef {{ dispatch: BridgeDispatch, emit: Emit, owner: object, source?: JobSource }} Entry */
|
|
40
|
+
/** @type {Entry[]} */
|
|
41
|
+
const queue = [];
|
|
42
|
+
/** @type {(Entry & { controller: AbortController })|null} */
|
|
43
|
+
let current = null;
|
|
44
|
+
let closed = false;
|
|
45
|
+
/** @type {Set<Promise<void>>} */
|
|
46
|
+
const inflight = new Set();
|
|
47
|
+
|
|
48
|
+
const drain = () => {
|
|
49
|
+
if (current || closed) return;
|
|
50
|
+
const entry = queue.shift();
|
|
51
|
+
if (!entry) return;
|
|
52
|
+
const controller = new AbortController();
|
|
53
|
+
const running = { ...entry, controller };
|
|
54
|
+
current = running;
|
|
55
|
+
const task = (async () => {
|
|
56
|
+
try {
|
|
57
|
+
await execute(entry.dispatch, entry.emit, controller.signal, entry.source);
|
|
58
|
+
} catch (err) {
|
|
59
|
+
// An executor that throws must still settle the job, or the chat waits on it.
|
|
60
|
+
await entry.emit({
|
|
61
|
+
jobId: entry.dispatch.jobId,
|
|
62
|
+
type: 'final',
|
|
63
|
+
result: { ok: false, text: capText(`The Desktop Agent failed: ${err && err.message ? err.message : err}`) },
|
|
64
|
+
});
|
|
65
|
+
} finally {
|
|
66
|
+
if (current === running) current = null;
|
|
67
|
+
drain();
|
|
68
|
+
}
|
|
69
|
+
})();
|
|
70
|
+
inflight.add(task);
|
|
71
|
+
task.finally(() => inflight.delete(task));
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
/** @param {object} owner @param {BridgeDispatch} dispatch @param {Emit} emit @param {JobSource} [source] */
|
|
76
|
+
enqueue(owner, dispatch, emit, source) {
|
|
77
|
+
if (closed) return;
|
|
78
|
+
queue.push({ owner, dispatch, emit, source });
|
|
79
|
+
drain();
|
|
80
|
+
},
|
|
81
|
+
/** Cancels a job of `owner` (running or queued). @param {object} owner @param {string} jobId */
|
|
82
|
+
cancel(owner, jobId) {
|
|
83
|
+
if (current && current.owner === owner && current.dispatch.jobId === jobId) current.controller.abort();
|
|
84
|
+
const i = queue.findIndex((e) => e.owner === owner && e.dispatch.jobId === jobId);
|
|
85
|
+
if (i >= 0) queue.splice(i, 1);
|
|
86
|
+
},
|
|
87
|
+
/**
|
|
88
|
+
* Stops everything `owner` holds: its running job is aborted and settled with `text`, its queued jobs
|
|
89
|
+
* are refused — both only when `canReport` (a revoked device cannot report; its server settles them).
|
|
90
|
+
* @param {object} owner @param {{ text: string, canReport: boolean }} how
|
|
91
|
+
*/
|
|
92
|
+
async stopOwner(owner, { text, canReport }) {
|
|
93
|
+
const settles = [];
|
|
94
|
+
if (current && current.owner === owner) {
|
|
95
|
+
current.controller.abort();
|
|
96
|
+
if (canReport) settles.push(current.emit({ jobId: current.dispatch.jobId, type: 'final', result: { ok: false, text } }));
|
|
97
|
+
}
|
|
98
|
+
for (let i = queue.length - 1; i >= 0; i -= 1) {
|
|
99
|
+
const e = queue[i];
|
|
100
|
+
if (e.owner !== owner) continue;
|
|
101
|
+
queue.splice(i, 1);
|
|
102
|
+
if (canReport) settles.push(e.emit({ jobId: e.dispatch.jobId, type: 'refused', reason: STOPPED_BEFORE_START }));
|
|
103
|
+
}
|
|
104
|
+
await Promise.all(settles);
|
|
105
|
+
},
|
|
106
|
+
/** Nothing new starts after this. */
|
|
107
|
+
close() {
|
|
108
|
+
closed = true;
|
|
109
|
+
},
|
|
110
|
+
/** how many jobs are queued or running (tests) */
|
|
111
|
+
size() {
|
|
112
|
+
return queue.length + (current ? 1 : 0);
|
|
113
|
+
},
|
|
114
|
+
logger,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** @typedef {ReturnType<typeof createJobQueue>} JobQueue */
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The bridge's long-poll loop for ONE App Builder (D4). Each poll carries a fresh `hello`; jobs go into
|
|
122
|
+
* the shared queue (one is made when none is passed) and are never awaited by the poll.
|
|
123
|
+
*
|
|
124
|
+
* @param {{
|
|
125
|
+
* api: { server?: string, post: (path: string, body: unknown, signal?: AbortSignal) => Promise<{ status: number, body: any }> },
|
|
126
|
+
* hello: () => Promise<object>|object,
|
|
127
|
+
* execute?: Execute,
|
|
128
|
+
* queue?: JobQueue,
|
|
129
|
+
* onCancel?: (jobId: string) => void,
|
|
130
|
+
* onPolling?: () => void,
|
|
131
|
+
* signal: AbortSignal,
|
|
132
|
+
* sleep?: (ms: number) => Promise<void>,
|
|
133
|
+
* logger?: typeof log,
|
|
134
|
+
* clearConfig?: () => void,
|
|
135
|
+
* stoppedText?: string,
|
|
136
|
+
* }} opts
|
|
137
|
+
* @returns {Promise<LoopExit>}
|
|
138
|
+
*/
|
|
139
|
+
async function runLoop({
|
|
140
|
+
api,
|
|
141
|
+
hello,
|
|
142
|
+
execute,
|
|
143
|
+
queue,
|
|
144
|
+
onCancel,
|
|
145
|
+
onPolling,
|
|
146
|
+
signal,
|
|
147
|
+
sleep = defaultSleep,
|
|
148
|
+
logger = log,
|
|
149
|
+
clearConfig,
|
|
150
|
+
stoppedText = STOPPED,
|
|
151
|
+
}) {
|
|
152
|
+
const server = typeof api.server === 'string' ? api.server : 'the App Builder';
|
|
153
|
+
const jobs = queue || createJobQueue({ execute: /** @type {Execute} */ (execute), logger });
|
|
154
|
+
const owner = {};
|
|
155
|
+
/** @type {JobSource} */
|
|
156
|
+
const source = { api, server };
|
|
157
|
+
const forget = clearConfig || (() => deleteBridgeConfig(typeof api.server === 'string' ? api.server : undefined));
|
|
158
|
+
|
|
159
|
+
/** @type {Emit} */
|
|
160
|
+
const emit = async (event) => {
|
|
161
|
+
try {
|
|
162
|
+
const r = await api.post('/api/bridge/result', { events: [event] });
|
|
163
|
+
if (r.status !== 200) logger.error(`Could not report job ${event.jobId} (HTTP ${r.status}).`);
|
|
164
|
+
} catch (err) {
|
|
165
|
+
logger.error(`Could not report job ${event.jobId}: ${err.message}`);
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
let failures = 0;
|
|
170
|
+
let announced = false;
|
|
171
|
+
let warnedUnsafeId = false;
|
|
172
|
+
/** @type {LoopExit} */
|
|
173
|
+
let exit = { reason: 'stopped' };
|
|
174
|
+
|
|
175
|
+
while (!signal.aborted) {
|
|
176
|
+
try {
|
|
177
|
+
const h = await hello();
|
|
178
|
+
if (!announced) {
|
|
179
|
+
announced = true;
|
|
180
|
+
if (onPolling) onPolling();
|
|
181
|
+
}
|
|
182
|
+
const r = await api.post('/api/bridge/poll', { hello: h }, signal);
|
|
183
|
+
if (r.status !== 200) {
|
|
184
|
+
const message = r.body && r.body.message ? `: ${r.body.message}` : '';
|
|
185
|
+
throw new Error(`poll failed (HTTP ${r.status}${message})`);
|
|
186
|
+
}
|
|
187
|
+
failures = 0;
|
|
188
|
+
|
|
189
|
+
const body = r.body || {};
|
|
190
|
+
for (const c of Array.isArray(body.cancels) ? body.cancels : []) {
|
|
191
|
+
if (c && typeof c.jobId === 'string') {
|
|
192
|
+
jobs.cancel(owner, c.jobId);
|
|
193
|
+
if (onCancel) onCancel(c.jobId);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
for (const dispatch of Array.isArray(body.jobs) ? body.jobs : []) {
|
|
197
|
+
if (!dispatch || typeof dispatch.jobId !== 'string') continue;
|
|
198
|
+
if (!isSafeJobId(dispatch.jobId)) {
|
|
199
|
+
// The id names files on this computer; one that is not a plain token is never run, and is
|
|
200
|
+
// not echoed back either (D3). The server's pickup timeout cancels it.
|
|
201
|
+
if (!warnedUnsafeId) {
|
|
202
|
+
warnedUnsafeId = true;
|
|
203
|
+
logger.error('Ignored a job from the App Builder whose id is not a plain token.');
|
|
204
|
+
}
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
jobs.enqueue(owner, dispatch, emit, source);
|
|
208
|
+
}
|
|
209
|
+
} catch (err) {
|
|
210
|
+
if (err instanceof NotPairedError) {
|
|
211
|
+
try {
|
|
212
|
+
forget();
|
|
213
|
+
} catch {
|
|
214
|
+
// the credential is dead either way
|
|
215
|
+
}
|
|
216
|
+
exit = { reason: 'not-paired', message: notPairedText(server) };
|
|
217
|
+
break;
|
|
218
|
+
}
|
|
219
|
+
if (err instanceof UpdateRequiredError) {
|
|
220
|
+
exit = { reason: 'update-required', message: err.message };
|
|
221
|
+
break;
|
|
222
|
+
}
|
|
223
|
+
if (signal.aborted) break;
|
|
224
|
+
const wait = BACKOFF_MS[Math.min(failures, BACKOFF_MS.length - 1)];
|
|
225
|
+
failures += 1;
|
|
226
|
+
logger.error(`Lost ${server} (${err.message}); retrying in ${wait / 1000}s.`);
|
|
227
|
+
await sleep(wait);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// Stopping: settle everything this loop holds so nothing in the chat waits on it.
|
|
232
|
+
// A revoked device cannot report anything (every post is a 401); the server settles its jobs itself.
|
|
233
|
+
const text = exit.reason === 'stopped' ? stoppedText : exit.message || stoppedText;
|
|
234
|
+
await jobs.stopOwner(owner, { text, canReport: exit.reason !== 'not-paired' });
|
|
235
|
+
|
|
236
|
+
return exit;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
module.exports = { runLoop, createJobQueue, notPairedText, BACKOFF_MS, NOT_PAIRED, STOPPED, STOPPED_BEFORE_START };
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const os = require('os');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Install-code pairing (D55 — the ONLY pairing flow). The signed-in user mints a single-use code in the
|
|
7
|
+
* App Builder's Unity Bridge dialog; the command it shows carries the code (`--pair K7QM-2XWD`), and this
|
|
8
|
+
* helper claims it. Nothing is ever read from, or shown in, a terminal — which is what lets a
|
|
9
|
+
* start-at-login service pair at all.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** @param {string} server */
|
|
13
|
+
const notPairedText = (server) =>
|
|
14
|
+
`Not paired with ${server} — copy the install command from the Unity Bridge dialog in the App Builder.`;
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Claims one install code with one App Builder. The token is returned exactly once.
|
|
18
|
+
* @param {import('./api').BridgeApi} api an unauthenticated client for that server
|
|
19
|
+
* @param {string} code
|
|
20
|
+
* @param {{ deviceName?: string, os?: string, signal?: AbortSignal }} [opts]
|
|
21
|
+
* @returns {Promise<{ ok: true, deviceId: string, token: string } | { ok: false, message: string }>}
|
|
22
|
+
*/
|
|
23
|
+
async function claimPairing(api, code, opts = {}) {
|
|
24
|
+
const deviceName = (opts.deviceName || os.hostname() || 'computer').slice(0, 80);
|
|
25
|
+
const platform = opts.os || process.platform;
|
|
26
|
+
let r;
|
|
27
|
+
try {
|
|
28
|
+
r = await api.post('/api/bridge/pair', { action: 'claim', code, deviceName, os: platform }, opts.signal);
|
|
29
|
+
} catch (err) {
|
|
30
|
+
return { ok: false, message: `could not reach it (${err && err.message ? err.message : err})` };
|
|
31
|
+
}
|
|
32
|
+
const b = r.body || {};
|
|
33
|
+
if (r.status === 200 && typeof b.deviceId === 'string' && typeof b.token === 'string') {
|
|
34
|
+
return { ok: true, deviceId: b.deviceId, token: b.token };
|
|
35
|
+
}
|
|
36
|
+
const why = typeof b.message === 'string' && b.message ? b.message : `HTTP ${r.status}`;
|
|
37
|
+
return { ok: false, message: why };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Makes sure every requested server has a credential. A supplied `code` is ALWAYS claimed (D55): success
|
|
42
|
+
* replaces any stored credential; a rejection keeps the stored one (`kept: true`) and is reported. With no
|
|
43
|
+
* code, a stored credential is kept as is. One code pairs with the App Builder that minted it, so with
|
|
44
|
+
* several servers the user runs the command once per App Builder.
|
|
45
|
+
*
|
|
46
|
+
* @param {{
|
|
47
|
+
* servers: string[],
|
|
48
|
+
* code?: string,
|
|
49
|
+
* stored: (server: string) => import('./config').BridgeConfig|null,
|
|
50
|
+
* save: (cfg: import('./config').BridgeConfig) => void,
|
|
51
|
+
* makeApi: (server: string) => import('./api').BridgeApi,
|
|
52
|
+
* deviceName?: string,
|
|
53
|
+
* os?: string,
|
|
54
|
+
* signal?: AbortSignal,
|
|
55
|
+
* }} opts
|
|
56
|
+
* @returns {Promise<{
|
|
57
|
+
* ready: import('./config').BridgeConfig[],
|
|
58
|
+
* paired: string[],
|
|
59
|
+
* rejected: { server: string, message: string, kept?: true }[],
|
|
60
|
+
* unpaired: string[],
|
|
61
|
+
* }>}
|
|
62
|
+
* `ready` — every server that now has a credential; `paired` — the ones this call paired; `rejected` —
|
|
63
|
+
* the code was refused (or the server unreachable); `unpaired` — no credential and no code.
|
|
64
|
+
*/
|
|
65
|
+
async function ensurePaired({ servers, code, stored, save, makeApi, deviceName, os: platform, signal }) {
|
|
66
|
+
/** @type {import('./config').BridgeConfig[]} */
|
|
67
|
+
const ready = [];
|
|
68
|
+
/** @type {string[]} */
|
|
69
|
+
const paired = [];
|
|
70
|
+
/** @type {{ server: string, message: string, kept?: true }[]} */
|
|
71
|
+
const rejected = [];
|
|
72
|
+
/** @type {string[]} */
|
|
73
|
+
const unpaired = [];
|
|
74
|
+
for (const server of servers) {
|
|
75
|
+
const existing = stored(server);
|
|
76
|
+
if (!code) {
|
|
77
|
+
if (existing) ready.push(existing);
|
|
78
|
+
else unpaired.push(server);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
// A supplied code ALWAYS re-pairs (D55): after a revoke the stored token is dead, and the dialog's command must
|
|
82
|
+
// pair on its first run. The server replaces this computer's old pairing, so a re-claim never eats a device slot.
|
|
83
|
+
const claim = await claimPairing(makeApi(server), code, { deviceName, os: platform, signal });
|
|
84
|
+
if (!claim.ok) {
|
|
85
|
+
if (existing) {
|
|
86
|
+
ready.push(existing);
|
|
87
|
+
rejected.push({ server, message: claim.message, kept: true });
|
|
88
|
+
} else {
|
|
89
|
+
rejected.push({ server, message: claim.message });
|
|
90
|
+
}
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
const cfg = { server, deviceId: claim.deviceId, token: claim.token };
|
|
94
|
+
save(cfg);
|
|
95
|
+
ready.push(cfg);
|
|
96
|
+
paired.push(server);
|
|
97
|
+
}
|
|
98
|
+
return { ready, paired, rejected, unpaired };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
module.exports = { claimPairing, ensurePaired, notPairedText };
|