@babylonjs-toolkit/agent 1.1.38 → 1.1.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,395 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * The start-at-login service (D55). `bt-agent bridge --install-service` copies this zero-dependency
5
+ * package to `~/.babylon-toolkit/service/` (so the service never points into an ephemeral npx cache) and
6
+ * registers `node <service>/bin/bt-agent.js bridge --service` to start when the user logs in:
7
+ *
8
+ * macOS a launchd agent ~/Library/LaunchAgents/com.babylontoolkit.bridge.plist
9
+ * Linux a systemd user unit ~/.config/systemd/user/babylon-toolkit-bridge.service
10
+ * Windows a Startup-folder script %APPDATA%\Microsoft\Windows\Start Menu\Programs\Startup\babylon-toolkit-bridge.vbs
11
+ *
12
+ * Opt-in only: install/update/postinstall never call this. Every side effect goes through injected
13
+ * `fs`/`exec`/`spawn`/`kill`, so the tests never register a real service.
14
+ */
15
+
16
+ const nodeFs = require('fs');
17
+ const path = require('path');
18
+ const { spawnSync, spawn: nodeSpawn } = require('child_process');
19
+
20
+ const { PACKAGE_ROOT } = require('../paths');
21
+
22
+ const LAUNCHD_LABEL = 'com.babylontoolkit.bridge';
23
+ const SYSTEMD_UNIT = 'babylon-toolkit-bridge.service';
24
+ const STARTUP_SCRIPT = 'babylon-toolkit-bridge.vbs';
25
+ /** What the service copy carries — the package minus the skills payload the bridge never reads. */
26
+ const PACKAGE_PARTS = ['package.json', 'bin', 'lib'];
27
+ const BOOTSTRAP_ATTEMPTS = 5;
28
+
29
+ /**
30
+ * @typedef {{ code: number|null, stdout: string, stderr: string }} ExecResult
31
+ * @typedef {(file: string, args: string[]) => ExecResult} ServiceExec
32
+ * @typedef {(file: string, args: string[], opts: object) => { unref: () => void }} ServiceSpawn
33
+ * @typedef {{
34
+ * platform: string,
35
+ * home: string,
36
+ * uid?: number,
37
+ * execPath: string,
38
+ * env: Record<string, string|undefined>,
39
+ * fs?: typeof nodeFs,
40
+ * exec?: ServiceExec,
41
+ * spawn?: ServiceSpawn,
42
+ * kill?: (pid: number, signal?: string|number) => void,
43
+ * sleep?: (ms: number) => Promise<void>,
44
+ * packageRoot?: string,
45
+ * }} ServiceDeps
46
+ */
47
+
48
+ /** @type {ServiceExec} */
49
+ function defaultExec(file, args) {
50
+ const r = spawnSync(file, args, { encoding: 'utf8', timeout: 30_000, windowsHide: true });
51
+ return { code: r.error ? null : r.status, stdout: r.stdout || '', stderr: r.stderr || (r.error ? r.error.message : '') };
52
+ }
53
+
54
+ /** @type {ServiceSpawn} */
55
+ function defaultSpawn(file, args, opts) {
56
+ return nodeSpawn(file, args, opts);
57
+ }
58
+
59
+ /** @param {number} ms */
60
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
61
+
62
+ /** @param {{ home: string }} d */
63
+ function stateDirOf({ home }) {
64
+ return path.join(home, '.babylon-toolkit');
65
+ }
66
+
67
+ /**
68
+ * Every path the service uses, for one platform.
69
+ * @param {{ platform: string, home: string, env: Record<string, string|undefined> }} d
70
+ */
71
+ function servicePaths(d) {
72
+ const state = stateDirOf(d);
73
+ /** @type {string|undefined} */
74
+ let registration;
75
+ if (d.platform === 'darwin') registration = path.join(d.home, 'Library', 'LaunchAgents', `${LAUNCHD_LABEL}.plist`);
76
+ else if (d.platform === 'win32') {
77
+ const appData = d.env.APPDATA || path.join(d.home, 'AppData', 'Roaming');
78
+ registration = path.join(appData, 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', STARTUP_SCRIPT);
79
+ } else if (d.platform === 'linux') {
80
+ const config = d.env.XDG_CONFIG_HOME || path.join(d.home, '.config');
81
+ registration = path.join(config, 'systemd', 'user', SYSTEMD_UNIT);
82
+ }
83
+ return {
84
+ stateDir: state,
85
+ serviceDir: path.join(state, 'service'),
86
+ logFile: path.join(state, 'bridge.log'),
87
+ pidFile: path.join(state, 'bridge.pid'),
88
+ registration,
89
+ };
90
+ }
91
+
92
+ /**
93
+ * The service's command line: this Node, the COPIED package's entry point, `bridge --service`.
94
+ * @param {{ execPath: string, serviceDir: string }} d
95
+ */
96
+ function serviceArgv({ execPath, serviceDir }) {
97
+ return [execPath, path.join(serviceDir, 'bin', 'bt-agent.js'), 'bridge', '--service'];
98
+ }
99
+
100
+ /** @param {string} s */
101
+ function xml(s) {
102
+ return String(s)
103
+ .replace(/&/g, '&amp;')
104
+ .replace(/</g, '&lt;')
105
+ .replace(/>/g, '&gt;')
106
+ .replace(/"/g, '&quot;')
107
+ .replace(/'/g, '&apos;');
108
+ }
109
+
110
+ /**
111
+ * The launchd agent (macOS).
112
+ * @param {{ argv: string[], path: string, home: string, logFile: string }} d
113
+ */
114
+ function launchdPlist({ argv, path: pathEnv, home, logFile }) {
115
+ return [
116
+ '<?xml version="1.0" encoding="UTF-8"?>',
117
+ '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
118
+ '<plist version="1.0">',
119
+ '<dict>',
120
+ ' <key>Label</key>',
121
+ ` <string>${LAUNCHD_LABEL}</string>`,
122
+ ' <key>ProgramArguments</key>',
123
+ ' <array>',
124
+ ...argv.map((a) => ` <string>${xml(a)}</string>`),
125
+ ' </array>',
126
+ ' <key>RunAtLoad</key>',
127
+ ' <true/>',
128
+ ' <key>KeepAlive</key>',
129
+ ' <dict>',
130
+ ' <key>SuccessfulExit</key>',
131
+ ' <false/>',
132
+ ' </dict>',
133
+ ' <key>ThrottleInterval</key>',
134
+ ' <integer>30</integer>',
135
+ ' <key>EnvironmentVariables</key>',
136
+ ' <dict>',
137
+ ' <key>PATH</key>',
138
+ ` <string>${xml(pathEnv)}</string>`,
139
+ ' <key>HOME</key>',
140
+ ` <string>${xml(home)}</string>`,
141
+ ' </dict>',
142
+ ' <key>StandardOutPath</key>',
143
+ ` <string>${xml(logFile)}</string>`,
144
+ ' <key>StandardErrorPath</key>',
145
+ ` <string>${xml(logFile)}</string>`,
146
+ '</dict>',
147
+ '</plist>',
148
+ '',
149
+ ].join('\n');
150
+ }
151
+
152
+ /**
153
+ * One systemd word: double-quoted, with `\` and `"` escaped, `%` (specifiers) and `$` (variables) doubled.
154
+ * @param {string} s
155
+ */
156
+ function systemdQuote(s) {
157
+ return `"${String(s).replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/%/g, '%%').replace(/\$/g, '$$$$')}"`;
158
+ }
159
+
160
+ /**
161
+ * The systemd user unit (Linux).
162
+ * @param {{ argv: string[], path: string, home: string }} d
163
+ */
164
+ function systemdUnit({ argv, path: pathEnv, home }) {
165
+ return [
166
+ '[Unit]',
167
+ 'Description=Babylon Toolkit Unity Bridge',
168
+ 'After=network-online.target',
169
+ '',
170
+ '[Service]',
171
+ `ExecStart=${argv.map(systemdQuote).join(' ')}`,
172
+ 'Restart=on-failure',
173
+ 'RestartSec=30',
174
+ `Environment=${systemdQuote(`PATH=${pathEnv}`)}`,
175
+ `Environment=${systemdQuote(`HOME=${home}`)}`,
176
+ '',
177
+ '[Install]',
178
+ 'WantedBy=default.target',
179
+ '',
180
+ ].join('\n');
181
+ }
182
+
183
+ /**
184
+ * The Startup-folder script (Windows): runs the command line hidden (window style 0), not waiting.
185
+ * @param {{ argv: string[] }} d
186
+ */
187
+ function startupScript({ argv }) {
188
+ const commandLine = argv.map((a) => `"${a}"`).join(' ');
189
+ return [
190
+ "' Babylon Toolkit Unity Bridge - starts the Desktop Agent helper when you log in.",
191
+ "' Remove it with: bt-agent bridge --uninstall-service",
192
+ 'Set shell = CreateObject("WScript.Shell")',
193
+ `shell.Run "${commandLine.replace(/"/g, '""')}", 0, False`,
194
+ '',
195
+ ].join('\r\n');
196
+ }
197
+
198
+ /**
199
+ * Copies the package to `to` atomically: into a temp dir beside it, then renamed into place (the old
200
+ * copy is moved aside first and deleted last), so a failed copy never leaves a half-written service.
201
+ * @param {{ fs: typeof nodeFs, from: string, to: string }} d
202
+ */
203
+ function copyPackage({ fs, from, to }) {
204
+ const tmp = `${to}.tmp-${process.pid}`;
205
+ const old = `${to}.old-${process.pid}`;
206
+ fs.rmSync(tmp, { recursive: true, force: true });
207
+ fs.mkdirSync(tmp, { recursive: true });
208
+ try {
209
+ for (const part of PACKAGE_PARTS) {
210
+ fs.cpSync(path.join(from, part), path.join(tmp, part), { recursive: true });
211
+ }
212
+ } catch (err) {
213
+ fs.rmSync(tmp, { recursive: true, force: true });
214
+ throw err;
215
+ }
216
+ fs.rmSync(old, { recursive: true, force: true });
217
+ const had = fs.existsSync(to);
218
+ if (had) fs.renameSync(to, old);
219
+ fs.renameSync(tmp, to);
220
+ if (had) fs.rmSync(old, { recursive: true, force: true });
221
+ }
222
+
223
+ /** @param {ServiceDeps} d */
224
+ function resolved(d) {
225
+ return {
226
+ fs: d.fs || nodeFs,
227
+ exec: d.exec || defaultExec,
228
+ spawn: d.spawn || defaultSpawn,
229
+ kill: d.kill || ((pid, sig) => process.kill(pid, sig)),
230
+ sleep: d.sleep || defaultSleep,
231
+ packageRoot: d.packageRoot || PACKAGE_ROOT,
232
+ uid: typeof d.uid === 'number' ? d.uid : typeof process.getuid === 'function' ? process.getuid() : 0,
233
+ };
234
+ }
235
+
236
+ /**
237
+ * Stops the helper a Windows Startup script started (the pid it recorded). No-op elsewhere / when none.
238
+ * @param {typeof nodeFs} fs @param {string} pidFile @param {(pid: number, signal?: string|number) => void} kill
239
+ */
240
+ function stopRecordedPid(fs, pidFile, kill) {
241
+ let pid;
242
+ try {
243
+ pid = parseInt(fs.readFileSync(pidFile, 'utf8'), 10);
244
+ } catch {
245
+ return;
246
+ }
247
+ if (Number.isInteger(pid) && pid > 0 && pid !== process.pid) {
248
+ try {
249
+ kill(pid);
250
+ } catch {
251
+ // already gone
252
+ }
253
+ }
254
+ fs.rmSync(pidFile, { force: true });
255
+ }
256
+
257
+ /**
258
+ * Copies the package, writes the registration and starts the service now. Re-running it updates the
259
+ * copy and restarts the service (idempotent).
260
+ * @param {ServiceDeps} deps
261
+ * @returns {Promise<{ registration: string, serviceDir: string, logFile: string, argv: string[] }>}
262
+ */
263
+ async function installService(deps) {
264
+ const { fs, exec, spawn, kill, sleep, packageRoot, uid } = resolved(deps);
265
+ const paths = servicePaths(deps);
266
+ if (!paths.registration) throw new Error(`Starting the Unity Bridge at login is not supported on ${deps.platform}.`);
267
+ const registration = paths.registration;
268
+
269
+ fs.mkdirSync(paths.stateDir, { recursive: true });
270
+ copyPackage({ fs, from: packageRoot, to: paths.serviceDir });
271
+ const argv = serviceArgv({ execPath: deps.execPath, serviceDir: paths.serviceDir });
272
+ const pathEnv = deps.env.PATH || '';
273
+ fs.mkdirSync(path.dirname(registration), { recursive: true });
274
+
275
+ if (deps.platform === 'darwin') {
276
+ fs.writeFileSync(registration, launchdPlist({ argv, path: pathEnv, home: deps.home, logFile: paths.logFile }), { mode: 0o644 });
277
+ exec('launchctl', ['bootout', `gui/${uid}/${LAUNCHD_LABEL}`]); // not loaded yet is fine
278
+ // `bootout` returns before launchd has finished tearing the old instance down; bootstrap can
279
+ // briefly fail with an I/O error, so it is retried.
280
+ let last = { code: 0, stdout: '', stderr: '' };
281
+ for (let attempt = 1; attempt <= BOOTSTRAP_ATTEMPTS; attempt += 1) {
282
+ last = exec('launchctl', ['bootstrap', `gui/${uid}`, registration]);
283
+ if (last.code === 0) break;
284
+ if (attempt < BOOTSTRAP_ATTEMPTS) await sleep(1000);
285
+ }
286
+ if (last.code !== 0) {
287
+ throw new Error(`launchctl bootstrap failed (exit ${last.code}): ${(last.stderr || last.stdout).trim()}`);
288
+ }
289
+ } else if (deps.platform === 'linux') {
290
+ const existed = fs.existsSync(registration);
291
+ fs.writeFileSync(registration, systemdUnit({ argv, path: pathEnv, home: deps.home }), { mode: 0o644 });
292
+ for (const args of [
293
+ ['--user', 'daemon-reload'],
294
+ ['--user', 'enable', '--now', SYSTEMD_UNIT],
295
+ ...(existed ? [['--user', 'restart', SYSTEMD_UNIT]] : []),
296
+ ]) {
297
+ const r = exec('systemctl', args);
298
+ if (r.code !== 0) throw new Error(`systemctl ${args.join(' ')} failed (exit ${r.code}): ${(r.stderr || r.stdout).trim()}`);
299
+ }
300
+ } else {
301
+ stopRecordedPid(fs, paths.pidFile, kill);
302
+ fs.writeFileSync(registration, startupScript({ argv }));
303
+ const child = spawn(argv[0], argv.slice(1), { detached: true, stdio: 'ignore', windowsHide: true, cwd: deps.home });
304
+ child.unref();
305
+ }
306
+
307
+ return { registration, serviceDir: paths.serviceDir, logFile: paths.logFile, argv };
308
+ }
309
+
310
+ /**
311
+ * Stops and unregisters the service and deletes its copy of the package. The credential is kept
312
+ * (`bt-agent bridge logout` removes it).
313
+ * @param {ServiceDeps} deps
314
+ * @returns {{ removed: string[] }}
315
+ */
316
+ function uninstallService(deps) {
317
+ const { fs, exec, kill, uid } = resolved(deps);
318
+ const paths = servicePaths(deps);
319
+ /** @type {string[]} */
320
+ const removed = [];
321
+ const reg = paths.registration;
322
+
323
+ if (deps.platform === 'darwin') {
324
+ exec('launchctl', ['bootout', `gui/${uid}/${LAUNCHD_LABEL}`]);
325
+ } else if (deps.platform === 'linux') {
326
+ if (reg && fs.existsSync(reg)) exec('systemctl', ['--user', 'disable', '--now', SYSTEMD_UNIT]);
327
+ } else if (deps.platform === 'win32') {
328
+ stopRecordedPid(fs, paths.pidFile, kill);
329
+ }
330
+ if (reg && fs.existsSync(reg)) {
331
+ fs.rmSync(reg, { force: true });
332
+ removed.push(reg);
333
+ }
334
+ if (deps.platform === 'linux' && removed.length) exec('systemctl', ['--user', 'daemon-reload']);
335
+ if (fs.existsSync(paths.serviceDir)) {
336
+ fs.rmSync(paths.serviceDir, { recursive: true, force: true });
337
+ removed.push(paths.serviceDir);
338
+ }
339
+ fs.rmSync(paths.pidFile, { force: true });
340
+ return { removed };
341
+ }
342
+
343
+ /**
344
+ * Is the service installed, and (where it is cheap to ask) running?
345
+ * @param {ServiceDeps} deps
346
+ * @returns {{ installed: boolean, running: boolean|null, registration?: string }}
347
+ */
348
+ function serviceStatus(deps) {
349
+ const { fs, exec, kill, uid } = resolved(deps);
350
+ const paths = servicePaths(deps);
351
+ const reg = paths.registration;
352
+ const installed = Boolean(reg && fs.existsSync(reg));
353
+ if (!installed) return { installed, running: null, registration: reg };
354
+ /** @type {boolean|null} */
355
+ let running = null;
356
+ try {
357
+ if (deps.platform === 'darwin') {
358
+ const r = exec('launchctl', ['print', `gui/${uid}/${LAUNCHD_LABEL}`]);
359
+ running = r.code === 0 && /\bstate\s*=\s*running\b/.test(r.stdout);
360
+ } else if (deps.platform === 'linux') {
361
+ const r = exec('systemctl', ['--user', 'is-active', SYSTEMD_UNIT]);
362
+ running = r.stdout.trim() === 'active';
363
+ } else {
364
+ const pid = parseInt(fs.readFileSync(paths.pidFile, 'utf8'), 10);
365
+ kill(pid, 0);
366
+ running = true;
367
+ }
368
+ } catch {
369
+ running = deps.platform === 'win32' ? false : null;
370
+ }
371
+ return { installed, running, registration: reg };
372
+ }
373
+
374
+ /** The deps for this process. @returns {ServiceDeps} */
375
+ function hostDeps() {
376
+ const os = require('os');
377
+ return { platform: process.platform, home: os.homedir(), execPath: process.execPath, env: process.env };
378
+ }
379
+
380
+ module.exports = {
381
+ LAUNCHD_LABEL,
382
+ SYSTEMD_UNIT,
383
+ STARTUP_SCRIPT,
384
+ PACKAGE_PARTS,
385
+ servicePaths,
386
+ serviceArgv,
387
+ launchdPlist,
388
+ systemdUnit,
389
+ startupScript,
390
+ copyPackage,
391
+ installService,
392
+ uninstallService,
393
+ serviceStatus,
394
+ hostDeps,
395
+ };
@@ -0,0 +1,135 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Unity automation grants (D51). Before every `bt_*` Unity command the helper makes sure it holds a
5
+ * grant for that project with more than 2 h left (fetching `POST /api/bridge/grant` otherwise), then
6
+ * hands it to the Editor with `unity command bt_automation --grant <grant>` — every time, since grants
7
+ * live in Editor memory only and an Editor restart forgets them.
8
+ *
9
+ * The grant is kept in THIS process's memory only. It is never written to disk, never logged, never
10
+ * put in a progress line or a job result. A refused or unavailable grant never fails the job: the
11
+ * export then runs under the user's own Babylon Toolkit licence.
12
+ */
13
+
14
+ const REFRESH_BEFORE_MS = 2 * 60 * 60 * 1000;
15
+
16
+ /** The reason in an "automation unavailable" log line is cut to this many characters. */
17
+ const MAX_LOGGED_REASON = 200;
18
+
19
+ /**
20
+ * @typedef {{ post: (path: string, body: unknown, signal?: AbortSignal) => Promise<{ status: number, body: any }> }} GrantApi
21
+ * @typedef {(args: string[]) => Promise<import('./run').RunResult>} RunUnity
22
+ * @typedef {{ info: (msg: string) => void }} InfoLog
23
+ */
24
+
25
+ /** @param {unknown} value @returns {number} epoch ms, or NaN */
26
+ function toEpochMs(value) {
27
+ if (typeof value === 'number') return value;
28
+ if (typeof value === 'string') return Date.parse(value);
29
+ return NaN;
30
+ }
31
+
32
+ /** @param {string} text @param {string|undefined} grant */
33
+ function scrub(text, grant) {
34
+ const s = String(text || '');
35
+ return grant ? s.split(grant).join('[grant]') : s;
36
+ }
37
+
38
+ /** A fresh, independent grant store (tests use their own; the helper uses the module one). */
39
+ function createAutomation() {
40
+ /** @type {Map<string, { grant: string, expiresAtMs: number }>} */
41
+ const held = new Map();
42
+ /** @type {Set<string>} */
43
+ const warned = new Set();
44
+
45
+ /**
46
+ * @param {{ productGuid?: string, root?: string }} project
47
+ * @param {{ api: GrantApi, runUnity: RunUnity, now?: () => number, log: InfoLog }} deps
48
+ * @returns {Promise<'on'|'off'>}
49
+ */
50
+ async function ensureAutomation(project, { api, runUnity, now = Date.now, log }) {
51
+ const guid = project && project.productGuid;
52
+ if (!guid) return 'off';
53
+
54
+ /**
55
+ * Logged once per DISTINCT message for a key — a later, different failure is still reported — and the
56
+ * message is capped (the Pipeline's "no such command" error lists every available command).
57
+ * @param {string} key @param {string} message
58
+ */
59
+ const once = (key, message) => {
60
+ const flat = String(message).replace(/\s+/g, ' ').trim();
61
+ const shown = flat.length > MAX_LOGGED_REASON ? flat.slice(0, MAX_LOGGED_REASON - 1) + '…' : flat;
62
+ const seen = `${key}\0${shown}`;
63
+ if (warned.has(seen)) return;
64
+ warned.add(seen);
65
+ log.info(`Unity automation unavailable: ${shown} — exports use your own Babylon Toolkit licence.`);
66
+ };
67
+
68
+ let entry = held.get(guid);
69
+ if (!entry || entry.expiresAtMs - now() < REFRESH_BEFORE_MS) {
70
+ held.delete(guid);
71
+ entry = undefined;
72
+ try {
73
+ const r = await api.post('/api/bridge/grant', { productGuid: guid });
74
+ const grant = r && r.body && typeof r.body.grant === 'string' ? r.body.grant : '';
75
+ const expiresAtMs = toEpochMs(r && r.body && r.body.expiresAt);
76
+ if (r.status === 200 && grant && Number.isFinite(expiresAtMs)) {
77
+ entry = { grant, expiresAtMs };
78
+ held.set(guid, entry);
79
+ } else {
80
+ const message =
81
+ (r && r.body && typeof r.body.message === 'string' && r.body.message) ||
82
+ `the App Builder answered HTTP ${r ? r.status : '?'}`;
83
+ once(`grant:${guid}`, scrub(message, grant));
84
+ return 'off';
85
+ }
86
+ } catch (err) {
87
+ once(`grant:${guid}`, err && err.message ? err.message : String(err));
88
+ return 'off';
89
+ }
90
+ }
91
+
92
+ const grant = entry.grant;
93
+ try {
94
+ const res = await runUnity([
95
+ 'command',
96
+ 'bt_automation',
97
+ '--grant',
98
+ grant,
99
+ '--project-path',
100
+ /** @type {string} */ (project.root),
101
+ '--format',
102
+ 'json',
103
+ '--non-interactive',
104
+ ]);
105
+ let ok = res.code === 0 && !res.timedOut;
106
+ let detail = '';
107
+ try {
108
+ const env = JSON.parse(res.stdout);
109
+ ok = env && env.success === true;
110
+ const first = env && Array.isArray(env.errors) && env.errors[0];
111
+ detail = (first && first.message) || '';
112
+ } catch {
113
+ detail = (res.stderr || res.stdout || '').trim().split(/\r?\n/).pop() || '';
114
+ }
115
+ if (ok) return 'on';
116
+ once(`run:${guid}`, scrub(detail || 'the Unity Editor refused the grant', grant));
117
+ return 'off';
118
+ } catch (err) {
119
+ once(`run:${guid}`, scrub(err && err.message ? err.message : String(err), grant));
120
+ return 'off';
121
+ }
122
+ }
123
+
124
+ return { ensureAutomation, reset: () => (held.clear(), warned.clear()) };
125
+ }
126
+
127
+ const shared = createAutomation();
128
+
129
+ module.exports = {
130
+ ensureAutomation: shared.ensureAutomation,
131
+ resetAutomation: shared.reset,
132
+ createAutomation,
133
+ REFRESH_BEFORE_MS,
134
+ MAX_LOGGED_REASON,
135
+ };