@dorokuma/magpie-gemini-web 0.0.0-stage → 0.15.2

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.
Files changed (50) hide show
  1. package/CHANGELOG.md +188 -0
  2. package/LICENSE +21 -0
  3. package/LICENSE-AISTUDIO +21 -0
  4. package/LICENSE-UPSTREAM +21 -0
  5. package/README.en.md +278 -0
  6. package/README.md +281 -2
  7. package/docs/backend-release.md +62 -0
  8. package/docs/logo.svg +16 -0
  9. package/docs/studio-release.md +312 -0
  10. package/index.mjs +285 -0
  11. package/lib/backend-release.json +31 -0
  12. package/lib/backend.mjs +731 -0
  13. package/lib/cite.mjs +166 -0
  14. package/lib/cleanup-detached.cjs +69 -0
  15. package/lib/cleanup.mjs +515 -0
  16. package/lib/native.mjs +734 -0
  17. package/lib/setup.mjs +261 -0
  18. package/lib/studio-connect-legacy.mjs +273 -0
  19. package/lib/studio-connect.mjs +269 -0
  20. package/lib/studio-native.mjs +2543 -0
  21. package/lib/studio-page.mjs +173 -0
  22. package/lib/studio-release.json +122 -0
  23. package/lib/studio-updates.mjs +320 -0
  24. package/lib/studio-upstream.mjs +135 -0
  25. package/lib/studio.mjs +1170 -0
  26. package/lib/usage.mjs +322 -0
  27. package/package.json +96 -4
  28. package/patches/studio-0.2.17-preserve-request-bodies.patch +190 -0
  29. package/patches/studio-0.2.19-managed-config.patch +121 -0
  30. package/patches/studio-0.3.4-magpie-signin.patch +676 -0
  31. package/patches/studio-0.3.5-signin-reauth.patch +25 -0
  32. package/patches/studio-0.3.7-magpie-signin.patch +676 -0
  33. package/patches/studio-0.3.7-managed-config.patch +121 -0
  34. package/patches/studio-0.3.7-signin-reauth.patch +25 -0
  35. package/scripts/backend-smoke.mjs +123 -0
  36. package/scripts/backend.mjs +57 -0
  37. package/scripts/studio-archive.go +92 -0
  38. package/scripts/studio-auto-update-smoke.mjs +116 -0
  39. package/scripts/studio-lifecycle-smoke.mjs +149 -0
  40. package/scripts/studio-managed-smoke.mjs +198 -0
  41. package/scripts/studio-official-smoke.mjs +12 -0
  42. package/scripts/studio-pins.mjs +52 -0
  43. package/scripts/studio-regzip.go +75 -0
  44. package/scripts/studio-release.mjs +287 -0
  45. package/scripts/studio-signin-candidate.json +102 -0
  46. package/scripts/studio-smoke.mjs +195 -0
  47. package/scripts/studio-update-smoke.mjs +82 -0
  48. package/scripts/studio-user-smoke.mjs +206 -0
  49. package/scripts/studio.mjs +468 -0
  50. package/scripts/sync-backend-pins.mjs +217 -0
@@ -0,0 +1,515 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import crypto from 'node:crypto';
5
+ import { spawn, execFileSync } from 'node:child_process';
6
+ import { fileURLToPath } from 'node:url';
7
+ import {
8
+ studioDataDir,
9
+ cleanStudio,
10
+ hasStudioAssets,
11
+ setStudioAssetHook
12
+ } from './studio-native.mjs';
13
+ import {
14
+ getDataDir,
15
+ cleanBackend,
16
+ hasBackendAssets,
17
+ setBackendAssetHook
18
+ } from './native.mjs';
19
+
20
+ export const PLUGIN_PACKAGE_NAME = '@dorokuma/magpie-gemini-web';
21
+ export const LEGACY_PLUGIN_PACKAGE_NAMES = ['magpie-gemini-web'];
22
+ const PLUGIN_PACKAGE_NAMES = [PLUGIN_PACKAGE_NAME, ...LEGACY_PLUGIN_PACKAGE_NAMES];
23
+ const PLUGIN_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
24
+ export const DETACHED_WORKER_PATH = fileURLToPath(new URL('./cleanup-detached.cjs', import.meta.url));
25
+ const PLUGIN_VERSION = JSON.parse(fs.readFileSync(path.join(PLUGIN_ROOT, 'package.json'), 'utf8')).version;
26
+
27
+ function normalizeComparePath(p, platform = process.platform) {
28
+ let resolved = path.resolve(p);
29
+ try {
30
+ if (fs.existsSync(resolved)) resolved = fs.realpathSync(resolved);
31
+ } catch {}
32
+ return platform === 'win32' ? resolved.toLowerCase() : resolved;
33
+ }
34
+
35
+ function isLocalPathSpec(spec) {
36
+ return (
37
+ spec.startsWith('/') ||
38
+ spec.startsWith('./') ||
39
+ spec.startsWith('../') ||
40
+ spec.startsWith('file:') ||
41
+ /^[a-zA-Z]:[\\/]/.test(spec)
42
+ );
43
+ }
44
+
45
+ function resolvePathSpec(magpieDir, spec) {
46
+ if (spec.startsWith('file:')) {
47
+ try {
48
+ return fileURLToPath(spec);
49
+ } catch {
50
+ return null;
51
+ }
52
+ }
53
+ return path.isAbsolute(spec) ? path.resolve(spec) : path.resolve(magpieDir, spec);
54
+ }
55
+
56
+ function matchesPluginSpec(magpieDir, rawSpec, pluginRoot = PLUGIN_ROOT) {
57
+ if (typeof rawSpec !== 'string') return false;
58
+ const spec = rawSpec.trim();
59
+ if (!spec) return false;
60
+
61
+ if (PLUGIN_PACKAGE_NAMES.some(name => spec === name || spec.startsWith(`${name}@`))) {
62
+ return true;
63
+ }
64
+
65
+ if (!isLocalPathSpec(spec)) {
66
+ return /(?:^|[/:])(?:@dorokuma\/)?magpie-gemini-web(?:\.git)?(?:[#@/?].*)?$/.test(spec);
67
+ }
68
+
69
+ const target = resolvePathSpec(magpieDir, spec);
70
+ if (!target || !fs.existsSync(target)) return false;
71
+
72
+ if (pluginRoot && normalizeComparePath(target) === normalizeComparePath(pluginRoot)) {
73
+ return true;
74
+ }
75
+
76
+ try {
77
+ const pkg = JSON.parse(fs.readFileSync(path.join(target, 'package.json'), 'utf8'));
78
+ return PLUGIN_PACKAGE_NAMES.includes(pkg?.name);
79
+ } catch {
80
+ return false;
81
+ }
82
+ }
83
+
84
+ // isPluginInMagpie checks whether magpie-gemini-web is still listed in Magpie's plugins.json
85
+ // (including when disabled with "off": true). Returns:
86
+ // - true when the plugin is present in plugins.json
87
+ // - false when plugins.json is valid and the plugin has been removed from it
88
+ // - null when plugins.json does not exist or cannot be parsed right now
89
+ export function isPluginInMagpie(magpieDir, options = {}) {
90
+ if (typeof magpieDir !== 'string' || !magpieDir.trim()) return null;
91
+ const pluginsPath = path.join(magpieDir, 'plugins.json');
92
+ let raw;
93
+ try {
94
+ raw = fs.readFileSync(pluginsPath, 'utf8');
95
+ } catch {
96
+ return null;
97
+ }
98
+
99
+ let parsed;
100
+ try {
101
+ parsed = JSON.parse(raw);
102
+ } catch {
103
+ return null;
104
+ }
105
+
106
+ if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.plugins)) {
107
+ return null;
108
+ }
109
+
110
+ const pluginRoot = options.pluginRoot ?? PLUGIN_ROOT;
111
+ for (const item of parsed.plugins) {
112
+ const spec = typeof item === 'string' ? item : item?.spec;
113
+ if (matchesPluginSpec(magpieDir, spec, pluginRoot)) {
114
+ return true;
115
+ }
116
+ }
117
+
118
+ return false;
119
+ }
120
+
121
+ export function hasDownloadedAssets(options = {}) {
122
+ const studioDir = options.studioDir || studioDataDir();
123
+ const webDir = options.webDir || getDataDir();
124
+ return hasStudioAssets(studioDir) || hasBackendAssets(webDir);
125
+ }
126
+
127
+ // cleanDownloadedAssets stops and deletes downloaded local binaries, archives, and Camoufox
128
+ // for both AI Studio and Gemini Web while preserving user accounts, databases, and configs.
129
+ export async function cleanDownloadedAssets(options = {}) {
130
+ const studioDir = options.studioDir || studioDataDir();
131
+ const webDir = options.webDir || getDataDir();
132
+ const platform = options.platform || process.platform;
133
+ const fetchFn = options.fetchFn || globalThis.fetch;
134
+
135
+ const [studio, web] = await Promise.all([
136
+ cleanStudio({ dataDir: studioDir, platform, fetchFn }).catch(err => ({
137
+ stopped: false,
138
+ cleaned: false,
139
+ removed: [],
140
+ dataDir: studioDir,
141
+ error: err.message
142
+ })),
143
+ cleanBackend({ dataDir: webDir, platform, fetchFn }).catch(err => ({
144
+ stopped: false,
145
+ cleaned: false,
146
+ removed: [],
147
+ dataDir: webDir,
148
+ error: err.message
149
+ }))
150
+ ]);
151
+
152
+ return { studio, web };
153
+ }
154
+
155
+ function watcherPidFilePath(magpieDir) {
156
+ const key = crypto.createHash('sha256').update(path.resolve(magpieDir)).digest('hex').slice(0, 16);
157
+ return path.join(os.tmpdir(), `magpie-gemini-web-cleanup-${key}.pid`);
158
+ }
159
+
160
+ function isProcessAlive(pid) {
161
+ if (!Number.isInteger(pid) || pid <= 0) return false;
162
+ try {
163
+ process.kill(pid, 0);
164
+ return true;
165
+ } catch (err) {
166
+ return err.code === 'EPERM';
167
+ }
168
+ }
169
+
170
+ // The pidfile graduated from a bare PID line to JSON { pid, pluginRoot, version } so a
171
+ // watcher from an older plugin build can be replaced instead of silently reused.
172
+ function readWatcherPidFile(pidFile) {
173
+ try {
174
+ const raw = fs.readFileSync(pidFile, 'utf8').trim();
175
+ if (!raw) return null;
176
+ if (raw.startsWith('{')) {
177
+ const parsed = JSON.parse(raw);
178
+ const pid = Number(parsed?.pid);
179
+ if (!Number.isInteger(pid) || pid <= 0) return null;
180
+ return {
181
+ pid,
182
+ legacy: false,
183
+ pluginRoot: typeof parsed?.pluginRoot === 'string' ? parsed.pluginRoot : null,
184
+ version: typeof parsed?.version === 'string' ? parsed.version : null
185
+ };
186
+ }
187
+ const pid = Number(raw);
188
+ if (!Number.isInteger(pid) || pid <= 0) return null;
189
+ return { pid, legacy: true, pluginRoot: null, version: null };
190
+ } catch {
191
+ return null;
192
+ }
193
+ }
194
+
195
+ function readLiveWatcherPid(pidFile) {
196
+ if (!pidFile) return null;
197
+ const record = readWatcherPidFile(pidFile);
198
+ if (record && isProcessAlive(record.pid)) return record.pid;
199
+ return null;
200
+ }
201
+
202
+ function writeWatcherPidFile(pidFile, pid, pluginRoot, version) {
203
+ try {
204
+ fs.writeFileSync(pidFile, `${JSON.stringify({ pid, pluginRoot, version })}\n`, { mode: 0o600 });
205
+ } catch {}
206
+ }
207
+
208
+ // A detached watcher can be identified either by the process.title it sets on startup
209
+ // ('magpie-gemini-web-cleanup'; on Linux uv_set_process_title rewrites /proc/<pid>/cmdline
210
+ // to just this title; macOS ps may truncate it to the 'magpie-gemini-web-cl' short-title
211
+ // prefix) or by the cleanup-detached.cjs script path in its argv/command line.
212
+ function isWatcherCommand(text) {
213
+ if (typeof text !== 'string') return false;
214
+ const trimmed = text.trim();
215
+ if (!trimmed) return false;
216
+ if (/^magpie-gemini-web-cl(?:eanup)?(?:\s|$)/.test(trimmed)) {
217
+ return true;
218
+ }
219
+ return trimmed.split(/\s+/).some(token => {
220
+ const base = token.replace(/^"|"$/g, '').split(/[\\/]/).pop();
221
+ return base === 'cleanup-detached.cjs';
222
+ });
223
+ }
224
+
225
+ const WATCHER_RUN_OPTIONS = { encoding: 'utf8', timeout: 5000, windowsHide: true };
226
+ const RUNNABLE_IMAGE_NAMES = new Set(['node', 'node.exe', 'bun', 'bun.exe']);
227
+
228
+ // true = the running process was launched from our detached worker script;
229
+ // false = another process reused the PID; null = inspection unavailable.
230
+ export function verifyWatcherIdentity(pid, platform = process.platform, run = execFileSync) {
231
+ if (!Number.isInteger(pid) || pid <= 0 || !isProcessAlive(pid)) return false;
232
+ if (platform === 'linux' && run === execFileSync) {
233
+ try {
234
+ const args = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').filter(Boolean);
235
+ if (args.length) return args.some(arg => isWatcherCommand(arg));
236
+ } catch {
237
+ // /proc read raced with process exit: fall through to ps for a second look.
238
+ }
239
+ }
240
+ try {
241
+ if (platform === 'win32') {
242
+ const out = run('powershell', ['-NoProfile', '-NonInteractive', '-Command',
243
+ '$ErrorActionPreference = "Stop"; [Console]::OutputEncoding = [Text.UTF8Encoding]::new(); ' +
244
+ '$p = Get-CimInstance Win32_Process -Filter "ProcessId = $env:TARGET_PID"; ' +
245
+ 'if ($p) { "$($p.Name)|$($p.CommandLine)" }'],
246
+ { ...WATCHER_RUN_OPTIONS, timeout: 20000, env: { ...process.env, TARGET_PID: String(pid) } }).trim();
247
+ if (!out) return isProcessAlive(pid) ? null : false;
248
+ const sep = out.indexOf('|');
249
+ const name = (sep === -1 ? '' : out.slice(0, sep)).trim();
250
+ const cmdLine = (sep === -1 ? out : out.slice(sep + 1)).trim();
251
+ if (isWatcherCommand(cmdLine)) return true;
252
+ if (cmdLine || (name && !RUNNABLE_IMAGE_NAMES.has(name.toLowerCase()))) return false;
253
+ return null;
254
+ }
255
+ const command = run('ps', ['-ww', '-p', String(pid), '-o', 'command='], WATCHER_RUN_OPTIONS).trim();
256
+ if (!command) return isProcessAlive(pid) ? null : false;
257
+ return isWatcherCommand(command);
258
+ } catch {
259
+ return isProcessAlive(pid) ? null : false;
260
+ }
261
+ }
262
+
263
+ async function terminateWatcher(pid, timeoutMs = 5000, verify) {
264
+ const isOurs = verify ?? verifyWatcherIdentity(pid);
265
+ if (isOurs !== true) {
266
+ // Never signal a PID whose identity cannot be proven ours.
267
+ return isOurs === null ? 'unknown' : 'foreign';
268
+ }
269
+ try { process.kill(pid, 'SIGTERM'); } catch {}
270
+ const deadline = Date.now() + timeoutMs;
271
+ while (Date.now() < deadline && isProcessAlive(pid)) {
272
+ await new Promise(resolve => setTimeout(resolve, 100));
273
+ }
274
+ if (!isProcessAlive(pid)) return 'stopped';
275
+ try { process.kill(pid, 'SIGKILL'); } catch {}
276
+ const killDeadline = Date.now() + 1000;
277
+ while (Date.now() < killDeadline && isProcessAlive(pid)) {
278
+ await new Promise(resolve => setTimeout(resolve, 50));
279
+ }
280
+ return isProcessAlive(pid) ? 'lingering' : 'stopped';
281
+ }
282
+
283
+ export function spawnDetachedCleanup(config, spawnFn = spawn) {
284
+ if (!fs.existsSync(DETACHED_WORKER_PATH)) return null;
285
+ const child = spawnFn(process.execPath, [DETACHED_WORKER_PATH], {
286
+ cwd: os.tmpdir(),
287
+ env: {
288
+ ...process.env,
289
+ MAGPIE_CLEANUP_CFG: JSON.stringify(config)
290
+ },
291
+ detached: true,
292
+ stdio: 'ignore',
293
+ windowsHide: true
294
+ });
295
+ child.on?.('error', () => {});
296
+ child.unref?.();
297
+ return child;
298
+ }
299
+
300
+ // Concurrent ensureDetachedWatcher calls for the same pidFile (e.g. GeminiWebPlugin and
301
+ // AIStudioPlugin registering back-to-back in one host) must share one in-flight take-over
302
+ // instead of both terminating the old watcher and spawning a duplicate daemon.
303
+ const inFlightWatchers = new Map();
304
+
305
+ export async function ensureDetachedWatcher(options = {}) {
306
+ const magpieDir = options.magpieDir;
307
+ if (typeof magpieDir !== 'string' || !magpieDir.trim()) return null;
308
+ const pluginRoot = options.pluginRoot ?? PLUGIN_ROOT;
309
+ const studioDir = options.studioDir || studioDataDir();
310
+ const webDir = options.webDir || getDataDir();
311
+ const pollMs = options.pollMs ?? 2000;
312
+ const spawnFn = options.spawnFn || spawn;
313
+
314
+ if (!hasStudioAssets(studioDir) && !hasBackendAssets(webDir)) {
315
+ return null;
316
+ }
317
+
318
+ const pidFile = options.pidFile || watcherPidFilePath(magpieDir);
319
+ const inflightKey = path.resolve(pidFile);
320
+ const inflight = inFlightWatchers.get(inflightKey);
321
+ if (inflight) return inflight;
322
+
323
+ const task = ensureDetachedWatcherOnce({
324
+ magpieDir, pluginRoot, studioDir, webDir, pollMs, spawnFn, pidFile, options
325
+ });
326
+ inFlightWatchers.set(inflightKey, task);
327
+ try {
328
+ return await task;
329
+ } finally {
330
+ if (inFlightWatchers.get(inflightKey) === task) {
331
+ inFlightWatchers.delete(inflightKey);
332
+ }
333
+ }
334
+ }
335
+
336
+ async function ensureDetachedWatcherOnce({
337
+ magpieDir, pluginRoot, studioDir, webDir, pollMs, spawnFn, pidFile, options
338
+ }) {
339
+ const record = readWatcherPidFile(pidFile);
340
+ if (record && isProcessAlive(record.pid)) {
341
+ // A watcher that still matches this plugin instance is reused; a bare-PID record
342
+ // (pre-JSON pidfile) or a different pluginRoot/version means a stale watcher from
343
+ // another plugin build that must hand over before a new one starts.
344
+ const current = !record.legacy &&
345
+ normalizeComparePath(record.pluginRoot ?? '') === normalizeComparePath(pluginRoot) &&
346
+ record.version === PLUGIN_VERSION;
347
+ if (current) {
348
+ return { pid: record.pid, pidFile, reused: true };
349
+ }
350
+ const outcome = await terminateWatcher(record.pid, options.terminateTimeoutMs ?? 5000,
351
+ options.verifyWatcherIdentity ? options.verifyWatcherIdentity(record.pid) : undefined);
352
+ if (outcome === 'foreign') {
353
+ // A PID that was provably never our watcher may have already been reused; only
354
+ // drop the stale record and continue, never signal it.
355
+ try { fs.rmSync(pidFile, { force: true }); } catch {}
356
+ } else if (outcome !== 'stopped') {
357
+ // 'unknown' or 'lingering': an uninspectable/stubborn process keeps the slot
358
+ // rather than being signaled blind or shadowed by a second watcher.
359
+ return { pid: record.pid, pidFile, reused: false, stale: outcome };
360
+ }
361
+ } else if (record && !isProcessAlive(record.pid)) {
362
+ try { fs.rmSync(pidFile, { force: true }); } catch {}
363
+ }
364
+
365
+ // Re-check after waiting for an old watcher to exit: the plugin may have been uninstalled
366
+ // or its assets removed in the meantime, in which case no short-lived watcher should start.
367
+ if (isPluginInMagpie(magpieDir, { pluginRoot }) === false ||
368
+ (!hasStudioAssets(studioDir) && !hasBackendAssets(webDir))) {
369
+ return null;
370
+ }
371
+
372
+ const child = spawnDetachedCleanup({
373
+ magpieDir: path.resolve(magpieDir),
374
+ pluginRoot,
375
+ studioDir,
376
+ webDir,
377
+ pidFile,
378
+ mode: 'watch',
379
+ pollMs
380
+ }, spawnFn);
381
+
382
+ if (child?.pid) {
383
+ writeWatcherPidFile(pidFile, child.pid, pluginRoot, PLUGIN_VERSION);
384
+ }
385
+
386
+ return { pid: child?.pid ?? null, pidFile, reused: false };
387
+ }
388
+
389
+ const activeRegistrations = new Map();
390
+
391
+ export function isPluginRemovedInActiveMagpie() {
392
+ for (const reg of activeRegistrations.values()) {
393
+ if (isPluginInMagpie(reg.magpieDir, { pluginRoot: reg.pluginRoot }) === false) {
394
+ return true;
395
+ }
396
+ }
397
+ return false;
398
+ }
399
+
400
+ // registerMagpieCleanup hooks Magpie's plugin lifecycle so removing magpie-gemini-web from
401
+ // Magpie's plugins.json automatically stops and deletes downloaded local binaries and Camoufox.
402
+ export function registerMagpieCleanup(input, options = {}) {
403
+ const magpieDir = typeof input?.directory === 'string' ? input.directory.trim() : '';
404
+ if (!magpieDir) return null;
405
+
406
+ const resolvedMagpieDir = path.resolve(magpieDir);
407
+ const pluginRoot = options.pluginRoot ?? PLUGIN_ROOT;
408
+ if (isPluginInMagpie(resolvedMagpieDir, { pluginRoot }) !== true) {
409
+ return null;
410
+ }
411
+
412
+ if (activeRegistrations.has(resolvedMagpieDir)) {
413
+ const existing = activeRegistrations.get(resolvedMagpieDir);
414
+ existing.ensureWatcher().catch(() => {});
415
+ return existing;
416
+ }
417
+
418
+ const studioDir = options.studioDir || studioDataDir();
419
+ const webDir = options.webDir || getDataDir();
420
+ const pollMs = options.pollMs ?? 2000;
421
+ const spawnFn = options.spawnFn || spawn;
422
+ const pidFile = options.pidFile || watcherPidFilePath(resolvedMagpieDir);
423
+
424
+ let cleaned = false;
425
+ let lastPid = null;
426
+ let watcher = null;
427
+
428
+ const ensureWatcher = async () => {
429
+ const state = isPluginInMagpie(resolvedMagpieDir, { pluginRoot });
430
+ if (state === true) {
431
+ cleaned = false;
432
+ }
433
+ if (cleaned || state === false) return null;
434
+ const res = await ensureDetachedWatcher({
435
+ magpieDir: resolvedMagpieDir,
436
+ pluginRoot,
437
+ studioDir,
438
+ webDir,
439
+ pollMs,
440
+ pidFile,
441
+ spawnFn
442
+ });
443
+ if (res?.pid) lastPid = res.pid;
444
+ return res;
445
+ };
446
+
447
+ const triggerIfRemoved = () => {
448
+ const state = isPluginInMagpie(resolvedMagpieDir, { pluginRoot });
449
+ if (state === true) {
450
+ if (cleaned) {
451
+ cleaned = false;
452
+ ensureWatcher().catch(() => {});
453
+ }
454
+ return false;
455
+ }
456
+ if (state !== false || cleaned) return false;
457
+ cleaned = true;
458
+ // Rely on the detached worker instead of running in-process cleanup so an in-flight request in
459
+ // the still-loaded host module cannot race with cleanup or leave cleaned permanently stuck.
460
+ if (!readLiveWatcherPid(pidFile) && (hasStudioAssets(studioDir) || hasBackendAssets(webDir))) {
461
+ const child = spawnDetachedCleanup({
462
+ magpieDir: resolvedMagpieDir,
463
+ pluginRoot,
464
+ studioDir,
465
+ webDir,
466
+ pidFile,
467
+ mode: 'immediate'
468
+ }, spawnFn);
469
+ if (child?.pid) {
470
+ lastPid = child.pid;
471
+ writeWatcherPidFile(pidFile, child.pid, pluginRoot, PLUGIN_VERSION);
472
+ }
473
+ }
474
+ return true;
475
+ };
476
+
477
+ try {
478
+ watcher = fs.watch(resolvedMagpieDir, (_eventType, filename) => {
479
+ if (!filename || filename === 'plugins.json') {
480
+ triggerIfRemoved();
481
+ }
482
+ });
483
+ watcher.on?.('error', () => {});
484
+ watcher.unref?.();
485
+ } catch {}
486
+
487
+ const notifyAssetInstalled = () => {
488
+ for (const reg of activeRegistrations.values()) {
489
+ reg.ensureWatcher().catch(() => {});
490
+ }
491
+ };
492
+ setStudioAssetHook(notifyAssetInstalled);
493
+ setBackendAssetHook(notifyAssetInstalled);
494
+ ensureWatcher().catch(() => {});
495
+
496
+ const handle = {
497
+ magpieDir: resolvedMagpieDir,
498
+ pluginRoot,
499
+ pidFile,
500
+ get pid() {
501
+ const live = readLiveWatcherPid(pidFile);
502
+ if (live) return live;
503
+ return isProcessAlive(lastPid) ? lastPid : undefined;
504
+ },
505
+ ensureWatcher,
506
+ triggerIfRemoved,
507
+ close() {
508
+ try { watcher?.close(); } catch {}
509
+ activeRegistrations.delete(resolvedMagpieDir);
510
+ }
511
+ };
512
+
513
+ activeRegistrations.set(resolvedMagpieDir, handle);
514
+ return handle;
515
+ }