magpie-gemini-web 0.9.0 → 0.10.0
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.en.md +7 -2
- package/README.md +7 -2
- package/docs/studio-release.md +19 -7
- package/index.mjs +17 -10
- package/lib/backend-release.json +14 -14
- package/lib/cleanup-detached.cjs +61 -0
- package/lib/cleanup.mjs +357 -0
- package/lib/native.mjs +165 -0
- package/lib/studio-native.mjs +276 -8
- package/lib/studio-release.json +19 -19
- package/lib/studio.mjs +18 -13
- package/lib/usage.mjs +23 -13
- package/package.json +4 -1
- package/patches/argon.patch +56 -19
- package/patches/studio-0.2.19-managed-config.patch +13 -10
- package/scripts/backend.mjs +15 -2
- package/scripts/studio-managed-smoke.mjs +3 -1
- package/scripts/studio.mjs +17 -5
package/lib/cleanup.mjs
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
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 } 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 = 'magpie-gemini-web';
|
|
21
|
+
const PLUGIN_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
22
|
+
export const DETACHED_WORKER_PATH = fileURLToPath(new URL('./cleanup-detached.cjs', import.meta.url));
|
|
23
|
+
|
|
24
|
+
function normalizeComparePath(p, platform = process.platform) {
|
|
25
|
+
let resolved = path.resolve(p);
|
|
26
|
+
try {
|
|
27
|
+
if (fs.existsSync(resolved)) resolved = fs.realpathSync(resolved);
|
|
28
|
+
} catch {}
|
|
29
|
+
return platform === 'win32' ? resolved.toLowerCase() : resolved;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function isLocalPathSpec(spec) {
|
|
33
|
+
return (
|
|
34
|
+
spec.startsWith('/') ||
|
|
35
|
+
spec.startsWith('./') ||
|
|
36
|
+
spec.startsWith('../') ||
|
|
37
|
+
spec.startsWith('file:') ||
|
|
38
|
+
/^[a-zA-Z]:[\\/]/.test(spec)
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function resolvePathSpec(magpieDir, spec) {
|
|
43
|
+
if (spec.startsWith('file:')) {
|
|
44
|
+
try {
|
|
45
|
+
return fileURLToPath(spec);
|
|
46
|
+
} catch {
|
|
47
|
+
return null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return path.isAbsolute(spec) ? path.resolve(spec) : path.resolve(magpieDir, spec);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function matchesPluginSpec(magpieDir, rawSpec, pluginRoot = PLUGIN_ROOT) {
|
|
54
|
+
if (typeof rawSpec !== 'string') return false;
|
|
55
|
+
const spec = rawSpec.trim();
|
|
56
|
+
if (!spec) return false;
|
|
57
|
+
|
|
58
|
+
if (spec === PLUGIN_PACKAGE_NAME || spec.startsWith(`${PLUGIN_PACKAGE_NAME}@`)) {
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
if (!isLocalPathSpec(spec)) {
|
|
63
|
+
return /(?:^|[/:])magpie-gemini-web(?:\.git)?(?:[#@/?].*)?$/.test(spec);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const target = resolvePathSpec(magpieDir, spec);
|
|
67
|
+
if (!target || !fs.existsSync(target)) return false;
|
|
68
|
+
|
|
69
|
+
if (pluginRoot && normalizeComparePath(target) === normalizeComparePath(pluginRoot)) {
|
|
70
|
+
return true;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
try {
|
|
74
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(target, 'package.json'), 'utf8'));
|
|
75
|
+
return pkg?.name === PLUGIN_PACKAGE_NAME;
|
|
76
|
+
} catch {
|
|
77
|
+
return false;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// isPluginInMagpie checks whether magpie-gemini-web is still listed in Magpie's plugins.json
|
|
82
|
+
// (including when disabled with "off": true). Returns:
|
|
83
|
+
// - true when the plugin is present in plugins.json
|
|
84
|
+
// - false when plugins.json is valid and the plugin has been removed from it
|
|
85
|
+
// - null when plugins.json does not exist or cannot be parsed right now
|
|
86
|
+
export function isPluginInMagpie(magpieDir, options = {}) {
|
|
87
|
+
if (typeof magpieDir !== 'string' || !magpieDir.trim()) return null;
|
|
88
|
+
const pluginsPath = path.join(magpieDir, 'plugins.json');
|
|
89
|
+
let raw;
|
|
90
|
+
try {
|
|
91
|
+
raw = fs.readFileSync(pluginsPath, 'utf8');
|
|
92
|
+
} catch {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
let parsed;
|
|
97
|
+
try {
|
|
98
|
+
parsed = JSON.parse(raw);
|
|
99
|
+
} catch {
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.plugins)) {
|
|
104
|
+
return null;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const pluginRoot = options.pluginRoot ?? PLUGIN_ROOT;
|
|
108
|
+
for (const item of parsed.plugins) {
|
|
109
|
+
const spec = typeof item === 'string' ? item : item?.spec;
|
|
110
|
+
if (matchesPluginSpec(magpieDir, spec, pluginRoot)) {
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return false;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function hasDownloadedAssets(options = {}) {
|
|
119
|
+
const studioDir = options.studioDir || studioDataDir();
|
|
120
|
+
const webDir = options.webDir || getDataDir();
|
|
121
|
+
return hasStudioAssets(studioDir) || hasBackendAssets(webDir);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// cleanDownloadedAssets stops and deletes downloaded local binaries, archives, and Camoufox
|
|
125
|
+
// for both AI Studio and Gemini Web while preserving user accounts, databases, and configs.
|
|
126
|
+
export async function cleanDownloadedAssets(options = {}) {
|
|
127
|
+
const studioDir = options.studioDir || studioDataDir();
|
|
128
|
+
const webDir = options.webDir || getDataDir();
|
|
129
|
+
const platform = options.platform || process.platform;
|
|
130
|
+
const fetchFn = options.fetchFn || globalThis.fetch;
|
|
131
|
+
|
|
132
|
+
const [studio, web] = await Promise.all([
|
|
133
|
+
cleanStudio({ dataDir: studioDir, platform, fetchFn }).catch(err => ({
|
|
134
|
+
stopped: false,
|
|
135
|
+
cleaned: false,
|
|
136
|
+
removed: [],
|
|
137
|
+
dataDir: studioDir,
|
|
138
|
+
error: err.message
|
|
139
|
+
})),
|
|
140
|
+
cleanBackend({ dataDir: webDir, platform, fetchFn }).catch(err => ({
|
|
141
|
+
stopped: false,
|
|
142
|
+
cleaned: false,
|
|
143
|
+
removed: [],
|
|
144
|
+
dataDir: webDir,
|
|
145
|
+
error: err.message
|
|
146
|
+
}))
|
|
147
|
+
]);
|
|
148
|
+
|
|
149
|
+
return { studio, web };
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function watcherPidFilePath(magpieDir) {
|
|
153
|
+
const key = crypto.createHash('sha256').update(path.resolve(magpieDir)).digest('hex').slice(0, 16);
|
|
154
|
+
return path.join(os.tmpdir(), `magpie-gemini-web-cleanup-${key}.pid`);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function isProcessAlive(pid) {
|
|
158
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
159
|
+
try {
|
|
160
|
+
process.kill(pid, 0);
|
|
161
|
+
return true;
|
|
162
|
+
} catch (err) {
|
|
163
|
+
return err.code === 'EPERM';
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function readLiveWatcherPid(pidFile) {
|
|
168
|
+
if (!pidFile) return null;
|
|
169
|
+
try {
|
|
170
|
+
const pid = Number(fs.readFileSync(pidFile, 'utf8').trim());
|
|
171
|
+
if (isProcessAlive(pid)) return pid;
|
|
172
|
+
} catch {}
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export function spawnDetachedCleanup(config, spawnFn = spawn) {
|
|
177
|
+
if (!fs.existsSync(DETACHED_WORKER_PATH)) return null;
|
|
178
|
+
const child = spawnFn(process.execPath, [DETACHED_WORKER_PATH], {
|
|
179
|
+
cwd: os.tmpdir(),
|
|
180
|
+
env: {
|
|
181
|
+
...process.env,
|
|
182
|
+
MAGPIE_CLEANUP_CFG: JSON.stringify(config)
|
|
183
|
+
},
|
|
184
|
+
detached: true,
|
|
185
|
+
stdio: 'ignore',
|
|
186
|
+
windowsHide: true
|
|
187
|
+
});
|
|
188
|
+
child.on?.('error', () => {});
|
|
189
|
+
child.unref?.();
|
|
190
|
+
return child;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export function ensureDetachedWatcher(options = {}) {
|
|
194
|
+
const magpieDir = options.magpieDir;
|
|
195
|
+
if (typeof magpieDir !== 'string' || !magpieDir.trim()) return null;
|
|
196
|
+
const pluginRoot = options.pluginRoot ?? PLUGIN_ROOT;
|
|
197
|
+
const studioDir = options.studioDir || studioDataDir();
|
|
198
|
+
const webDir = options.webDir || getDataDir();
|
|
199
|
+
const pollMs = options.pollMs ?? 2000;
|
|
200
|
+
const spawnFn = options.spawnFn || spawn;
|
|
201
|
+
|
|
202
|
+
if (!hasStudioAssets(studioDir) && !hasBackendAssets(webDir)) {
|
|
203
|
+
return null;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const pidFile = options.pidFile || watcherPidFilePath(magpieDir);
|
|
207
|
+
const existingPid = readLiveWatcherPid(pidFile);
|
|
208
|
+
if (existingPid) {
|
|
209
|
+
return { pid: existingPid, pidFile, reused: true };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const child = spawnDetachedCleanup({
|
|
213
|
+
magpieDir: path.resolve(magpieDir),
|
|
214
|
+
pluginRoot,
|
|
215
|
+
studioDir,
|
|
216
|
+
webDir,
|
|
217
|
+
pidFile,
|
|
218
|
+
mode: 'watch',
|
|
219
|
+
pollMs
|
|
220
|
+
}, spawnFn);
|
|
221
|
+
|
|
222
|
+
if (child?.pid) {
|
|
223
|
+
try {
|
|
224
|
+
fs.writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 });
|
|
225
|
+
} catch {}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
return { pid: child?.pid ?? null, pidFile, reused: false };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const activeRegistrations = new Map();
|
|
232
|
+
|
|
233
|
+
export function isPluginRemovedInActiveMagpie() {
|
|
234
|
+
for (const reg of activeRegistrations.values()) {
|
|
235
|
+
if (isPluginInMagpie(reg.magpieDir, { pluginRoot: reg.pluginRoot }) === false) {
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
return false;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// registerMagpieCleanup hooks Magpie's plugin lifecycle so removing magpie-gemini-web from
|
|
243
|
+
// Magpie's plugins.json automatically stops and deletes downloaded local binaries and Camoufox.
|
|
244
|
+
export function registerMagpieCleanup(input, options = {}) {
|
|
245
|
+
const magpieDir = typeof input?.directory === 'string' ? input.directory.trim() : '';
|
|
246
|
+
if (!magpieDir) return null;
|
|
247
|
+
|
|
248
|
+
const resolvedMagpieDir = path.resolve(magpieDir);
|
|
249
|
+
const pluginRoot = options.pluginRoot ?? PLUGIN_ROOT;
|
|
250
|
+
if (isPluginInMagpie(resolvedMagpieDir, { pluginRoot }) !== true) {
|
|
251
|
+
return null;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
if (activeRegistrations.has(resolvedMagpieDir)) {
|
|
255
|
+
const existing = activeRegistrations.get(resolvedMagpieDir);
|
|
256
|
+
existing.ensureWatcher();
|
|
257
|
+
return existing;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const studioDir = options.studioDir || studioDataDir();
|
|
261
|
+
const webDir = options.webDir || getDataDir();
|
|
262
|
+
const pollMs = options.pollMs ?? 2000;
|
|
263
|
+
const spawnFn = options.spawnFn || spawn;
|
|
264
|
+
const pidFile = options.pidFile || watcherPidFilePath(resolvedMagpieDir);
|
|
265
|
+
|
|
266
|
+
let cleaned = false;
|
|
267
|
+
let lastPid = null;
|
|
268
|
+
let watcher = null;
|
|
269
|
+
|
|
270
|
+
const ensureWatcher = () => {
|
|
271
|
+
const state = isPluginInMagpie(resolvedMagpieDir, { pluginRoot });
|
|
272
|
+
if (state === true) {
|
|
273
|
+
cleaned = false;
|
|
274
|
+
}
|
|
275
|
+
if (cleaned || state === false) return null;
|
|
276
|
+
const res = ensureDetachedWatcher({
|
|
277
|
+
magpieDir: resolvedMagpieDir,
|
|
278
|
+
pluginRoot,
|
|
279
|
+
studioDir,
|
|
280
|
+
webDir,
|
|
281
|
+
pollMs,
|
|
282
|
+
pidFile,
|
|
283
|
+
spawnFn
|
|
284
|
+
});
|
|
285
|
+
if (res?.pid) lastPid = res.pid;
|
|
286
|
+
return res;
|
|
287
|
+
};
|
|
288
|
+
|
|
289
|
+
const triggerIfRemoved = () => {
|
|
290
|
+
const state = isPluginInMagpie(resolvedMagpieDir, { pluginRoot });
|
|
291
|
+
if (state === true) {
|
|
292
|
+
if (cleaned) {
|
|
293
|
+
cleaned = false;
|
|
294
|
+
ensureWatcher();
|
|
295
|
+
}
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
if (state !== false || cleaned) return false;
|
|
299
|
+
cleaned = true;
|
|
300
|
+
// Rely on the detached worker instead of running in-process cleanup so an in-flight request in
|
|
301
|
+
// the still-loaded host module cannot race with cleanup or leave cleaned permanently stuck.
|
|
302
|
+
if (!readLiveWatcherPid(pidFile) && (hasStudioAssets(studioDir) || hasBackendAssets(webDir))) {
|
|
303
|
+
const child = spawnDetachedCleanup({
|
|
304
|
+
magpieDir: resolvedMagpieDir,
|
|
305
|
+
pluginRoot,
|
|
306
|
+
studioDir,
|
|
307
|
+
webDir,
|
|
308
|
+
pidFile,
|
|
309
|
+
mode: 'immediate'
|
|
310
|
+
}, spawnFn);
|
|
311
|
+
if (child?.pid) {
|
|
312
|
+
lastPid = child.pid;
|
|
313
|
+
try { fs.writeFileSync(pidFile, `${child.pid}\n`, { mode: 0o600 }); } catch {}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return true;
|
|
317
|
+
};
|
|
318
|
+
|
|
319
|
+
try {
|
|
320
|
+
watcher = fs.watch(resolvedMagpieDir, (_eventType, filename) => {
|
|
321
|
+
if (!filename || filename === 'plugins.json') {
|
|
322
|
+
triggerIfRemoved();
|
|
323
|
+
}
|
|
324
|
+
});
|
|
325
|
+
watcher.on?.('error', () => {});
|
|
326
|
+
watcher.unref?.();
|
|
327
|
+
} catch {}
|
|
328
|
+
|
|
329
|
+
const notifyAssetInstalled = () => {
|
|
330
|
+
for (const reg of activeRegistrations.values()) {
|
|
331
|
+
reg.ensureWatcher();
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
setStudioAssetHook(notifyAssetInstalled);
|
|
335
|
+
setBackendAssetHook(notifyAssetInstalled);
|
|
336
|
+
ensureWatcher();
|
|
337
|
+
|
|
338
|
+
const handle = {
|
|
339
|
+
magpieDir: resolvedMagpieDir,
|
|
340
|
+
pluginRoot,
|
|
341
|
+
pidFile,
|
|
342
|
+
get pid() {
|
|
343
|
+
const live = readLiveWatcherPid(pidFile);
|
|
344
|
+
if (live) return live;
|
|
345
|
+
return isProcessAlive(lastPid) ? lastPid : undefined;
|
|
346
|
+
},
|
|
347
|
+
ensureWatcher,
|
|
348
|
+
triggerIfRemoved,
|
|
349
|
+
close() {
|
|
350
|
+
try { watcher?.close(); } catch {}
|
|
351
|
+
activeRegistrations.delete(resolvedMagpieDir);
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
activeRegistrations.set(resolvedMagpieDir, handle);
|
|
356
|
+
return handle;
|
|
357
|
+
}
|
package/lib/native.mjs
CHANGED
|
@@ -4,6 +4,7 @@ import os from 'node:os';
|
|
|
4
4
|
import crypto from 'node:crypto';
|
|
5
5
|
import { spawn, execFile } from 'node:child_process';
|
|
6
6
|
import { validateProxyURL } from './setup.mjs';
|
|
7
|
+
import { verifyProcessIdentity, studioProcessPids, studioListenerPids } from './studio-native.mjs';
|
|
7
8
|
import release from './backend-release.json' with { type: 'json' };
|
|
8
9
|
|
|
9
10
|
export const BACKEND_VERSION = `v${release.version}`;
|
|
@@ -165,6 +166,7 @@ export async function installBackend(options = {}) {
|
|
|
165
166
|
// A local custom build keeps the user's channel. Official installs record their
|
|
166
167
|
// selection only after verification and replacement succeeded.
|
|
167
168
|
if ((!options.expectedHash && !options.url) || options.channel !== undefined) saveBackendChannel(dataDir, channel);
|
|
169
|
+
onBackendAssetInstalled?.();
|
|
168
170
|
return { binPath, ...files };
|
|
169
171
|
}
|
|
170
172
|
|
|
@@ -331,6 +333,14 @@ function readLocalSetup(dataDir) {
|
|
|
331
333
|
}
|
|
332
334
|
}
|
|
333
335
|
|
|
336
|
+
// localSetup returns the saved configuration and credentials in dataDir ({ origin, baseURL,
|
|
337
|
+
// apiKey, adminToken }), or null when none has been configured there, even if the binary was
|
|
338
|
+
// cleaned up.
|
|
339
|
+
export function localSetup(options = {}) {
|
|
340
|
+
const dataDir = options.dataDir || getDataDir();
|
|
341
|
+
return readLocalSetup(dataDir);
|
|
342
|
+
}
|
|
343
|
+
|
|
334
344
|
// localBackend returns the backend this plugin manages in dataDir ({ origin, baseURL, apiKey,
|
|
335
345
|
// adminToken }), or null when none has been set up there.
|
|
336
346
|
export function localBackend(options = {}) {
|
|
@@ -509,3 +519,158 @@ export async function statusBackend(options = {}) {
|
|
|
509
519
|
|
|
510
520
|
return { status: 'ok', version, models: data.models };
|
|
511
521
|
}
|
|
522
|
+
|
|
523
|
+
let onBackendAssetInstalled = null;
|
|
524
|
+
|
|
525
|
+
export function setBackendAssetHook(fn) {
|
|
526
|
+
onBackendAssetInstalled = typeof fn === 'function' ? fn : null;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function processAlive(pid) {
|
|
530
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
531
|
+
try { process.kill(pid, 0); return true; } catch (err) { return err.code === 'EPERM'; }
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
function recordedBackendPid(dataDir) {
|
|
535
|
+
try { return Number(fs.readFileSync(path.join(dataDir, 'backend.pid'), 'utf8').trim()); } catch { return NaN; }
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
export function hasBackendAssets(dataDir = getDataDir(), platform = process.platform) {
|
|
539
|
+
if (!fs.existsSync(dataDir)) return false;
|
|
540
|
+
for (const name of ['bin', 'backend-channel.json', 'argon-build.json']) {
|
|
541
|
+
if (fs.existsSync(path.join(dataDir, name))) return true;
|
|
542
|
+
}
|
|
543
|
+
const pidFile = path.join(dataDir, 'backend.pid');
|
|
544
|
+
if (fs.existsSync(pidFile)) {
|
|
545
|
+
const pid = recordedBackendPid(dataDir);
|
|
546
|
+
const bin = binaryPath(dataDir, platform);
|
|
547
|
+
if (processAlive(pid) && verifyProcessIdentity(pid, bin, platform)) {
|
|
548
|
+
return true;
|
|
549
|
+
}
|
|
550
|
+
try { fs.rmSync(pidFile, { force: true }); } catch {}
|
|
551
|
+
}
|
|
552
|
+
return false;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function forceRemoveBackendPath(target, platform) {
|
|
556
|
+
if (!fs.existsSync(target)) return false;
|
|
557
|
+
try {
|
|
558
|
+
if (platform !== 'win32') {
|
|
559
|
+
const st = fs.lstatSync(target);
|
|
560
|
+
if (st.isDirectory()) {
|
|
561
|
+
try { fs.chmodSync(target, (st.mode & 0o777) | 0o700); } catch {}
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
fs.rmSync(target, { recursive: true, force: true });
|
|
565
|
+
return !fs.existsSync(target);
|
|
566
|
+
} catch {
|
|
567
|
+
return false;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
export async function stopBackend(options = {}) {
|
|
572
|
+
const dataDir = options.dataDir || getDataDir();
|
|
573
|
+
const platform = options.platform || process.platform;
|
|
574
|
+
const fetchFn = options.fetchFn || globalThis.fetch;
|
|
575
|
+
const pidFile = path.join(dataDir, 'backend.pid');
|
|
576
|
+
const bin = binaryPath(dataDir, platform);
|
|
577
|
+
|
|
578
|
+
if (!fs.existsSync(dataDir)) return { stopped: true };
|
|
579
|
+
|
|
580
|
+
const setup = readLocalSetup(dataDir);
|
|
581
|
+
const state = setup ? await backendState(setup, fetchFn) : 'down';
|
|
582
|
+
if (state === 'foreign') {
|
|
583
|
+
throw new Error(`Cannot stop unknown or foreign process listening on ${setup.origin}`);
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
const candidates = [];
|
|
587
|
+
const tracked = recordedBackendPid(dataDir);
|
|
588
|
+
if (Number.isInteger(tracked) && tracked > 0) candidates.push(tracked);
|
|
589
|
+
if (fs.existsSync(bin)) {
|
|
590
|
+
try {
|
|
591
|
+
candidates.push(...studioProcessPids(bin, platform));
|
|
592
|
+
} catch {}
|
|
593
|
+
if (setup && state === 'up') {
|
|
594
|
+
const port = Number(new URL(setup.origin).port);
|
|
595
|
+
try {
|
|
596
|
+
candidates.push(...studioListenerPids(port, platform));
|
|
597
|
+
} catch {}
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
const verified = [...new Set(candidates)].filter(p => processAlive(p) && verifyProcessIdentity(p, bin, platform));
|
|
602
|
+
if (!verified.length) {
|
|
603
|
+
try { fs.rmSync(pidFile, { force: true }); } catch {}
|
|
604
|
+
if (state === 'up') {
|
|
605
|
+
return { stopped: false, reported: `Cannot identify a verified gemini-web2api-go process for ${setup.origin}` };
|
|
606
|
+
}
|
|
607
|
+
return { stopped: true };
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
for (const pid of verified) {
|
|
611
|
+
try { process.kill(pid, 'SIGTERM'); } catch {}
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
const deadline = Date.now() + 5000;
|
|
615
|
+
while (Date.now() < deadline) {
|
|
616
|
+
if (verified.every(p => !processAlive(p))) break;
|
|
617
|
+
await sleep(100);
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
if (options.force && verified.some(p => processAlive(p))) {
|
|
621
|
+
for (const pid of verified) {
|
|
622
|
+
if (processAlive(pid) && verifyProcessIdentity(pid, bin, platform)) {
|
|
623
|
+
try { process.kill(pid, 'SIGKILL'); } catch {}
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
const killDeadline = Date.now() + 1000;
|
|
627
|
+
while (Date.now() < killDeadline) {
|
|
628
|
+
if (verified.every(p => !processAlive(p))) break;
|
|
629
|
+
await sleep(50);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
if (verified.some(p => processAlive(p))) {
|
|
634
|
+
return { stopped: false, reported: `Process ${verified.filter(p => processAlive(p)).join(', ')} did not exit after SIGTERM` };
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
try { fs.rmSync(pidFile, { force: true }); } catch {}
|
|
638
|
+
|
|
639
|
+
if (setup && state === 'up') {
|
|
640
|
+
const closeDeadline = Date.now() + 2000;
|
|
641
|
+
while (Date.now() < closeDeadline) {
|
|
642
|
+
if (await backendState(setup, fetchFn) === 'down') break;
|
|
643
|
+
await sleep(100);
|
|
644
|
+
}
|
|
645
|
+
if (await backendState(setup, fetchFn) !== 'down') {
|
|
646
|
+
return { stopped: false, reported: `${setup.origin} is still responding after stop` };
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
return { stopped: true };
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// cleanBackend stops any running managed gemini-web2api-go process in dataDir and deletes the
|
|
654
|
+
// downloaded binary and channel metadata while preserving config.json, secrets.json, gemini.db,
|
|
655
|
+
// and logs.
|
|
656
|
+
export async function cleanBackend(options = {}) {
|
|
657
|
+
const dataDir = options.dataDir || getDataDir();
|
|
658
|
+
const platform = options.platform || process.platform;
|
|
659
|
+
|
|
660
|
+
if (!fs.existsSync(dataDir)) {
|
|
661
|
+
return { stopped: true, cleaned: true, removed: [], dataDir };
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
return withLock(dataDir, async () => {
|
|
665
|
+
await stopBackend({ dataDir, platform, fetchFn: options.fetchFn, force: true }).catch(() => {});
|
|
666
|
+
|
|
667
|
+
const removed = [];
|
|
668
|
+
for (const name of ['bin', 'backend.pid', 'backend-channel.json', 'argon-build.json']) {
|
|
669
|
+
if (forceRemoveBackendPath(path.join(dataDir, name), platform)) {
|
|
670
|
+
removed.push(name);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
return { stopped: true, cleaned: true, removed, dataDir };
|
|
675
|
+
}, options.lockTimeoutMs ?? 600000);
|
|
676
|
+
}
|