@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.
- package/CHANGELOG.md +188 -0
- package/LICENSE +21 -0
- package/LICENSE-AISTUDIO +21 -0
- package/LICENSE-UPSTREAM +21 -0
- package/README.en.md +278 -0
- package/README.md +281 -2
- package/docs/backend-release.md +62 -0
- package/docs/logo.svg +16 -0
- package/docs/studio-release.md +312 -0
- package/index.mjs +285 -0
- package/lib/backend-release.json +31 -0
- package/lib/backend.mjs +731 -0
- package/lib/cite.mjs +166 -0
- package/lib/cleanup-detached.cjs +69 -0
- package/lib/cleanup.mjs +515 -0
- package/lib/native.mjs +734 -0
- package/lib/setup.mjs +261 -0
- package/lib/studio-connect-legacy.mjs +273 -0
- package/lib/studio-connect.mjs +269 -0
- package/lib/studio-native.mjs +2543 -0
- package/lib/studio-page.mjs +173 -0
- package/lib/studio-release.json +122 -0
- package/lib/studio-updates.mjs +320 -0
- package/lib/studio-upstream.mjs +135 -0
- package/lib/studio.mjs +1170 -0
- package/lib/usage.mjs +322 -0
- package/package.json +96 -4
- package/patches/studio-0.2.17-preserve-request-bodies.patch +190 -0
- package/patches/studio-0.2.19-managed-config.patch +121 -0
- package/patches/studio-0.3.4-magpie-signin.patch +676 -0
- package/patches/studio-0.3.5-signin-reauth.patch +25 -0
- package/patches/studio-0.3.7-magpie-signin.patch +676 -0
- package/patches/studio-0.3.7-managed-config.patch +121 -0
- package/patches/studio-0.3.7-signin-reauth.patch +25 -0
- package/scripts/backend-smoke.mjs +123 -0
- package/scripts/backend.mjs +57 -0
- package/scripts/studio-archive.go +92 -0
- package/scripts/studio-auto-update-smoke.mjs +116 -0
- package/scripts/studio-lifecycle-smoke.mjs +149 -0
- package/scripts/studio-managed-smoke.mjs +198 -0
- package/scripts/studio-official-smoke.mjs +12 -0
- package/scripts/studio-pins.mjs +52 -0
- package/scripts/studio-regzip.go +75 -0
- package/scripts/studio-release.mjs +287 -0
- package/scripts/studio-signin-candidate.json +102 -0
- package/scripts/studio-smoke.mjs +195 -0
- package/scripts/studio-update-smoke.mjs +82 -0
- package/scripts/studio-user-smoke.mjs +206 -0
- package/scripts/studio.mjs +468 -0
- package/scripts/sync-backend-pins.mjs +217 -0
package/lib/native.mjs
ADDED
|
@@ -0,0 +1,734 @@
|
|
|
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, execFile } from 'node:child_process';
|
|
6
|
+
import { validateProxyURL } from './setup.mjs';
|
|
7
|
+
import { verifyProcessIdentity, studioProcessPids, studioListenerPids } from './studio-native.mjs';
|
|
8
|
+
import { hasProxyCredentials, normalizeCurlProxy, redactProxyCredentials } from './studio-upstream.mjs';
|
|
9
|
+
import release from './backend-release.json' with { type: 'json' };
|
|
10
|
+
|
|
11
|
+
export const BACKEND_VERSION = `v${release.version}`;
|
|
12
|
+
const RELEASE_BASE = `https://github.com/${release.repository}/releases/download/${release.tag}/`;
|
|
13
|
+
export const PINNED_BINARIES = release.binaries;
|
|
14
|
+
|
|
15
|
+
const UPSTREAM_VERSION = 'v4.28.0';
|
|
16
|
+
const UPSTREAM_BASE = `https://github.com/zexadev/gemini-web2api-go/releases/download/${UPSTREAM_VERSION}/`;
|
|
17
|
+
// Retained for an explicit, checksum-verified rollback to the upstream release.
|
|
18
|
+
export const UPSTREAM_BINARIES = {
|
|
19
|
+
'darwin-arm64': { asset: 'gemini-web2api-go_v4.28.0_darwin_arm64', sha256: 'a6aaf315d4ea0ab4cc179e75b050c305b55e7347bc654eb5b5980dc82bedeffe' },
|
|
20
|
+
'darwin-x64': { asset: 'gemini-web2api-go_v4.28.0_darwin_amd64', sha256: '132207df8d9a87ad9c179f71dafc000e7d8f8721244a378e0989d063ecae5bdd' },
|
|
21
|
+
'linux-x64': { asset: 'gemini-web2api-go_v4.28.0_linux_amd64', sha256: 'e42cd70701a234c06eb81b4af4d925be4fe2b4c77bc6627e99b01750cdfea931' },
|
|
22
|
+
'linux-arm64': { asset: 'gemini-web2api-go_v4.28.0_linux_arm64', sha256: '404dd0e0e8ebc529f925b9db18541f1adfcb2edd5088827c86430c91b3065ea4' },
|
|
23
|
+
'win32-x64': { asset: 'gemini-web2api-go_v4.28.0_windows_amd64.exe', sha256: '4a990dbc106334c73ee2a4ae26b917073a2b82f069dc9da1b1073a608576d9a1' },
|
|
24
|
+
'win32-arm64': { asset: 'gemini-web2api-go_v4.28.0_windows_arm64.exe', sha256: 'ed421bb36a0bf2cd7d0c561ca035e251b01769d0db83ef78834f8578fa545279' }
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export function pinnedBinary(platform = process.platform, arch = process.arch, channel = 'optimized') {
|
|
28
|
+
if (channel !== 'optimized' && channel !== 'upstream') throw new Error(`Invalid backend channel: ${channel}`);
|
|
29
|
+
const pins = channel === 'upstream' ? UPSTREAM_BINARIES : PINNED_BINARIES;
|
|
30
|
+
const base = channel === 'upstream' ? UPSTREAM_BASE : RELEASE_BASE;
|
|
31
|
+
const version = channel === 'upstream' ? UPSTREAM_VERSION : BACKEND_VERSION;
|
|
32
|
+
const pin = pins[`${platform}-${arch}`];
|
|
33
|
+
if (!pin) {
|
|
34
|
+
throw new Error(`No gemini-web2api-go ${version} build for ${platform}/${arch}. See ${base.slice(0, -1).replace('/download/', '/tag/')}`);
|
|
35
|
+
}
|
|
36
|
+
return { url: base + pin.asset, sha256: pin.sha256 };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function backendChannel(dataDir = getDataDir()) {
|
|
40
|
+
try {
|
|
41
|
+
const { channel } = JSON.parse(fs.readFileSync(path.join(dataDir, 'backend-channel.json'), 'utf8'));
|
|
42
|
+
if (channel !== 'optimized' && channel !== 'upstream') throw new Error('Expected optimized or upstream');
|
|
43
|
+
return channel;
|
|
44
|
+
} catch (error) {
|
|
45
|
+
if (error.code === 'ENOENT') return 'optimized';
|
|
46
|
+
throw new Error(`Invalid backend-channel.json: ${error.message}`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function saveBackendChannel(dataDir, channel) {
|
|
51
|
+
const file = path.join(dataDir, 'backend-channel.json');
|
|
52
|
+
const temp = `${file}.${crypto.randomBytes(4).toString('hex')}.tmp`;
|
|
53
|
+
try {
|
|
54
|
+
fs.writeFileSync(temp, JSON.stringify({ channel }) + '\n', { mode: 0o600 });
|
|
55
|
+
fs.renameSync(temp, file);
|
|
56
|
+
} finally {
|
|
57
|
+
fs.rmSync(temp, { force: true });
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export function getDataDir(env = process.env) {
|
|
62
|
+
return env.GEMINI_WEB_DATA_DIR || path.join(os.homedir(), '.local', 'share', 'magpie-gemini-web');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function binaryPath(dataDir, platform = process.platform) {
|
|
66
|
+
return path.join(dataDir, 'bin', platform === 'win32' ? 'gemini-web2api-go.exe' : 'gemini-web2api-go');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function computeFileHash(filePath) {
|
|
70
|
+
const content = fs.readFileSync(filePath);
|
|
71
|
+
return crypto.createHash('sha256').update(content).digest('hex');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function installBackend(options = {}) {
|
|
75
|
+
const platform = options.platform || process.platform;
|
|
76
|
+
const arch = options.arch || process.arch;
|
|
77
|
+
const channel = options.channel ?? 'optimized';
|
|
78
|
+
const pin = options.expectedHash && options.url ? null : pinnedBinary(platform, arch, channel);
|
|
79
|
+
const expectedHash = options.expectedHash || pin.sha256;
|
|
80
|
+
const downloadUrl = options.url || pin.url;
|
|
81
|
+
const fetchFn = options.fetchFn || globalThis.fetch;
|
|
82
|
+
const proxy = validateProxyURL(options.proxy ?? process.env.GEMINI_WEB_PROXY ?? '');
|
|
83
|
+
|
|
84
|
+
const dataDir = options.dataDir || getDataDir();
|
|
85
|
+
fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
|
|
86
|
+
fs.chmodSync(dataDir, 0o700);
|
|
87
|
+
|
|
88
|
+
const binDir = path.join(dataDir, 'bin');
|
|
89
|
+
fs.mkdirSync(binDir, { recursive: true, mode: 0o700 });
|
|
90
|
+
fs.chmodSync(binDir, 0o700);
|
|
91
|
+
|
|
92
|
+
const binPath = binaryPath(dataDir, platform);
|
|
93
|
+
let binaryReady = false;
|
|
94
|
+
|
|
95
|
+
if (fs.existsSync(binPath)) {
|
|
96
|
+
const existingHash = computeFileHash(binPath);
|
|
97
|
+
if (existingHash === expectedHash) {
|
|
98
|
+
binaryReady = true;
|
|
99
|
+
console.log(`Backend binary verified: ${binPath}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (!binaryReady) {
|
|
104
|
+
console.log(`Downloading backend binary from ${downloadUrl}...`);
|
|
105
|
+
const tmpPath = path.join(binDir, `gemini-web2api-go.tmp.${Date.now()}.${crypto.randomBytes(4).toString('hex')}`);
|
|
106
|
+
try {
|
|
107
|
+
// A slow download goes on while data keeps coming; a minute without any gives it up.
|
|
108
|
+
if (proxy && (!options.fetchFn || options.fetchFn === globalThis.fetch)) {
|
|
109
|
+
if (/[\r\n]/.test(proxy)) throw new Error('Invalid GEMINI_WEB_PROXY');
|
|
110
|
+
// A proxy with credentials travels over stdin, never argv; inner blanks are encoded first.
|
|
111
|
+
const curlProxy = normalizeCurlProxy(proxy);
|
|
112
|
+
const proxySecret = hasProxyCredentials(curlProxy);
|
|
113
|
+
const curlArgs = [
|
|
114
|
+
'--fail', '--location', '--silent', '--show-error',
|
|
115
|
+
'--connect-timeout', '15', '--speed-limit', '1', '--speed-time', '60',
|
|
116
|
+
...(proxySecret ? ['--config', '-'] : ['--proxy', curlProxy]),
|
|
117
|
+
'-o', tmpPath, downloadUrl
|
|
118
|
+
];
|
|
119
|
+
await new Promise((resolve, reject) => {
|
|
120
|
+
const child = execFile('curl', curlArgs, (err, _stdout, stderr) => {
|
|
121
|
+
if (!err) return resolve();
|
|
122
|
+
const status = err.code ?? (err.signal ? `signal ${err.signal}` : err.status || 'failed');
|
|
123
|
+
const reason = redactProxyCredentials(String(stderr || '').trim().slice(0, 500));
|
|
124
|
+
reject(new Error(`Failed to download binary via curl (status: ${status})${reason ? `: ${reason}` : ''}`));
|
|
125
|
+
});
|
|
126
|
+
if (proxySecret) {
|
|
127
|
+
child.stdin?.on('error', () => {});
|
|
128
|
+
child.stdin?.end(`proxy = ${JSON.stringify(curlProxy)}\n`);
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
fs.chmodSync(tmpPath, 0o700);
|
|
132
|
+
} else {
|
|
133
|
+
const stall = new AbortController();
|
|
134
|
+
let timer;
|
|
135
|
+
const rearm = () => {
|
|
136
|
+
clearTimeout(timer);
|
|
137
|
+
timer = setTimeout(() => stall.abort(new Error('Failed to download binary: no data for 60 s')), 60000);
|
|
138
|
+
};
|
|
139
|
+
const chunks = [];
|
|
140
|
+
try {
|
|
141
|
+
rearm();
|
|
142
|
+
const res = await fetchFn(downloadUrl, {
|
|
143
|
+
...(proxy ? { proxy } : {}),
|
|
144
|
+
signal: stall.signal
|
|
145
|
+
});
|
|
146
|
+
if (!res.ok) {
|
|
147
|
+
throw new Error(`Failed to download binary: HTTP ${res.status}`);
|
|
148
|
+
}
|
|
149
|
+
for await (const chunk of res.body) {
|
|
150
|
+
chunks.push(chunk);
|
|
151
|
+
rearm();
|
|
152
|
+
}
|
|
153
|
+
} finally {
|
|
154
|
+
clearTimeout(timer);
|
|
155
|
+
}
|
|
156
|
+
fs.writeFileSync(tmpPath, Buffer.concat(chunks), { mode: 0o700 });
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const downloadedHash = computeFileHash(tmpPath);
|
|
160
|
+
if (downloadedHash !== expectedHash) {
|
|
161
|
+
throw new Error(`SHA256 checksum mismatch: expected ${expectedHash}, got ${downloadedHash}`);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
fs.renameSync(tmpPath, binPath);
|
|
165
|
+
fs.chmodSync(binPath, 0o700);
|
|
166
|
+
console.log(`Backend binary installed: ${binPath}`);
|
|
167
|
+
} finally {
|
|
168
|
+
if (fs.existsSync(tmpPath)) {
|
|
169
|
+
try { fs.unlinkSync(tmpPath); } catch {}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const files = ensureDataFiles(dataDir);
|
|
175
|
+
// A local custom build keeps the user's channel. Official installs record their
|
|
176
|
+
// selection only after verification and replacement succeeded.
|
|
177
|
+
if ((!options.expectedHash && !options.url) || options.channel !== undefined) saveBackendChannel(dataDir, channel);
|
|
178
|
+
onBackendAssetInstalled?.();
|
|
179
|
+
return { binPath, ...files };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ensureDataFiles creates config.json and secrets.json when missing; existing ones are kept.
|
|
183
|
+
function ensureDataFiles(dataDir) {
|
|
184
|
+
const configPath = path.join(dataDir, 'config.json');
|
|
185
|
+
if (!fs.existsSync(configPath)) {
|
|
186
|
+
const defaultConfig = {
|
|
187
|
+
host: "127.0.0.1",
|
|
188
|
+
port: 8083,
|
|
189
|
+
log_requests: false,
|
|
190
|
+
multi_turn: false,
|
|
191
|
+
temporary_chat: true,
|
|
192
|
+
// temporary_chat 不足以防幽灵会话(带附件/Mode-8 时服务端仍落「打不开」的
|
|
193
|
+
// 索引残片);auto_delete 让后端收尾统一 GzXR5e 删掉,双保险。
|
|
194
|
+
auto_delete_conversation: true
|
|
195
|
+
};
|
|
196
|
+
fs.writeFileSync(configPath, JSON.stringify(defaultConfig, null, 2) + '\n', { mode: 0o600 });
|
|
197
|
+
fs.chmodSync(configPath, 0o600);
|
|
198
|
+
console.log(`Created default config: ${configPath}`);
|
|
199
|
+
} else {
|
|
200
|
+
fs.chmodSync(configPath, 0o600);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const secretsPath = path.join(dataDir, 'secrets.json');
|
|
204
|
+
if (!fs.existsSync(secretsPath)) {
|
|
205
|
+
const defaultSecrets = {
|
|
206
|
+
apiKey: 'gw_' + crypto.randomBytes(32).toString('hex'),
|
|
207
|
+
adminToken: crypto.randomBytes(32).toString('hex')
|
|
208
|
+
};
|
|
209
|
+
fs.writeFileSync(secretsPath, JSON.stringify(defaultSecrets, null, 2) + '\n', { mode: 0o600 });
|
|
210
|
+
fs.chmodSync(secretsPath, 0o600);
|
|
211
|
+
console.log(`Created secrets: ${secretsPath}`);
|
|
212
|
+
} else {
|
|
213
|
+
fs.chmodSync(secretsPath, 0o600);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return { configPath, secretsPath };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export function startBackend(options = {}) {
|
|
220
|
+
const dataDir = options.dataDir || getDataDir();
|
|
221
|
+
const expectedHash = options.expectedHash || pinnedBinary(process.platform, process.arch, backendChannel(dataDir)).sha256;
|
|
222
|
+
const spawnFn = options.spawnFn || spawn;
|
|
223
|
+
const { binPath, args, env } = prepareLaunch(dataDir, [expectedHash]);
|
|
224
|
+
|
|
225
|
+
const child = spawnFn(binPath, args, {
|
|
226
|
+
env,
|
|
227
|
+
stdio: 'inherit'
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
const onSigInt = () => child.kill('SIGINT');
|
|
231
|
+
const onSigTerm = () => child.kill('SIGTERM');
|
|
232
|
+
process.on('SIGINT', onSigInt);
|
|
233
|
+
process.on('SIGTERM', onSigTerm);
|
|
234
|
+
|
|
235
|
+
const cleanupListeners = () => {
|
|
236
|
+
process.removeListener('SIGINT', onSigInt);
|
|
237
|
+
process.removeListener('SIGTERM', onSigTerm);
|
|
238
|
+
};
|
|
239
|
+
|
|
240
|
+
child.on('error', () => {
|
|
241
|
+
cleanupListeners();
|
|
242
|
+
console.error('Failed to start backend process');
|
|
243
|
+
process.exitCode = 1;
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
child.on('exit', (code, signal) => {
|
|
247
|
+
cleanupListeners();
|
|
248
|
+
if (typeof options.exitFn === 'function') {
|
|
249
|
+
options.exitFn(code, signal);
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
if (signal) {
|
|
253
|
+
process.kill(process.pid, signal);
|
|
254
|
+
} else {
|
|
255
|
+
process.exit(code ?? 0);
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
return child;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
// prepareLaunch checks the installed backend before it is run: a binary whose hash is one of
|
|
263
|
+
// trustedHashes, a loopback-only config and well-formed secrets. It returns what to spawn.
|
|
264
|
+
function prepareLaunch(dataDir, trustedHashes, platform = process.platform) {
|
|
265
|
+
const binPath = binaryPath(dataDir, platform);
|
|
266
|
+
const configPath = path.join(dataDir, 'config.json');
|
|
267
|
+
const secretsPath = path.join(dataDir, 'secrets.json');
|
|
268
|
+
|
|
269
|
+
if (!fs.existsSync(binPath)) {
|
|
270
|
+
throw new Error(`Binary not found at ${binPath}. Run 'npm run backend:install' first.`);
|
|
271
|
+
}
|
|
272
|
+
if (!fs.existsSync(configPath)) {
|
|
273
|
+
throw new Error(`Configuration not found at ${configPath}. Run 'npm run backend:install' first.`);
|
|
274
|
+
}
|
|
275
|
+
if (!fs.existsSync(secretsPath)) {
|
|
276
|
+
throw new Error(`Secrets not found at ${secretsPath}. Run 'npm run backend:install' first.`);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const actualHash = computeFileHash(binPath);
|
|
280
|
+
if (!trustedHashes.includes(actualHash)) {
|
|
281
|
+
throw new Error(`Binary integrity verification failed: expected ${trustedHashes.join(' or ')}, got ${actualHash}`);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
let config;
|
|
285
|
+
try {
|
|
286
|
+
config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
|
287
|
+
} catch {
|
|
288
|
+
throw new Error(`Failed to parse configuration file at ${configPath}`);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (config.host !== '127.0.0.1') {
|
|
292
|
+
throw new Error(`Security validation failed: host must be strictly 127.0.0.1, got ${config.host}`);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
if (!Number.isInteger(config.port) || config.port <= 0 || config.port > 65535) {
|
|
296
|
+
throw new Error(`Invalid port number in configuration: ${config.port}`);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
let secrets;
|
|
300
|
+
try {
|
|
301
|
+
secrets = JSON.parse(fs.readFileSync(secretsPath, 'utf8'));
|
|
302
|
+
} catch {
|
|
303
|
+
throw new Error(`Failed to parse secrets file at ${secretsPath}`);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
if (!secrets.apiKey || typeof secrets.apiKey !== 'string' || !secrets.adminToken || typeof secrets.adminToken !== 'string') {
|
|
307
|
+
throw new Error('Invalid secrets format in secrets.json');
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const dbPath = path.join(dataDir, 'gemini.db');
|
|
311
|
+
const args = ['--config', configPath, '--db', dbPath];
|
|
312
|
+
const env = {
|
|
313
|
+
...process.env,
|
|
314
|
+
API_KEY: secrets.apiKey,
|
|
315
|
+
ADMIN_TOKEN: secrets.adminToken
|
|
316
|
+
};
|
|
317
|
+
|
|
318
|
+
return { binPath, args, env, port: config.port, secrets };
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// trustedHashes accepts the selected release channel and any explicitly installed local build.
|
|
322
|
+
function trustedHashes(dataDir, platform, arch) {
|
|
323
|
+
const hashes = [];
|
|
324
|
+
try {
|
|
325
|
+
hashes.push(pinnedBinary(platform, arch, backendChannel(dataDir)).sha256);
|
|
326
|
+
} catch {}
|
|
327
|
+
try {
|
|
328
|
+
const argon = JSON.parse(fs.readFileSync(path.join(dataDir, 'argon-build.json'), 'utf8'));
|
|
329
|
+
if (/^[a-f0-9]{64}$/.test(argon.sha256)) hashes.push(argon.sha256);
|
|
330
|
+
} catch {}
|
|
331
|
+
return hashes;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function readLocalSetup(dataDir) {
|
|
335
|
+
try {
|
|
336
|
+
const config = JSON.parse(fs.readFileSync(path.join(dataDir, 'config.json'), 'utf8'));
|
|
337
|
+
const secrets = JSON.parse(fs.readFileSync(path.join(dataDir, 'secrets.json'), 'utf8'));
|
|
338
|
+
if (config.host !== '127.0.0.1' || !Number.isInteger(config.port) || typeof secrets.apiKey !== 'string' || typeof secrets.adminToken !== 'string') {
|
|
339
|
+
return null;
|
|
340
|
+
}
|
|
341
|
+
const origin = `http://127.0.0.1:${config.port}`;
|
|
342
|
+
return { origin, baseURL: `${origin}/v1`, apiKey: secrets.apiKey, adminToken: secrets.adminToken };
|
|
343
|
+
} catch {
|
|
344
|
+
return null;
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// localSetup returns the saved configuration and credentials in dataDir ({ origin, baseURL,
|
|
349
|
+
// apiKey, adminToken }), or null when none has been configured there, even if the binary was
|
|
350
|
+
// cleaned up.
|
|
351
|
+
export function localSetup(options = {}) {
|
|
352
|
+
const dataDir = options.dataDir || getDataDir();
|
|
353
|
+
return readLocalSetup(dataDir);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// localBackend returns the backend this plugin manages in dataDir ({ origin, baseURL, apiKey,
|
|
357
|
+
// adminToken }), or null when none has been set up there.
|
|
358
|
+
export function localBackend(options = {}) {
|
|
359
|
+
const dataDir = options.dataDir || getDataDir();
|
|
360
|
+
const platform = options.platform || process.platform;
|
|
361
|
+
if (!fs.existsSync(binaryPath(dataDir, platform))) return null;
|
|
362
|
+
return readLocalSetup(dataDir);
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// backendState says whether the backend at setup answers with this setup's API key.
|
|
366
|
+
async function backendState(setup, fetchFn) {
|
|
367
|
+
let res;
|
|
368
|
+
try {
|
|
369
|
+
res = await fetchFn(`${setup.baseURL}/models`, {
|
|
370
|
+
headers: { Authorization: `Bearer ${setup.apiKey}` },
|
|
371
|
+
signal: AbortSignal.timeout(2000)
|
|
372
|
+
});
|
|
373
|
+
} catch {
|
|
374
|
+
return 'down';
|
|
375
|
+
}
|
|
376
|
+
return res.ok ? 'up' : 'foreign';
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
380
|
+
|
|
381
|
+
// withLock serializes setup across plugin hosts (Magpie may run more than one) by a lock file.
|
|
382
|
+
async function withLock(dataDir, fn, timeoutMs) {
|
|
383
|
+
const lockPath = path.join(dataDir, '.setup.lock');
|
|
384
|
+
const deadline = Date.now() + timeoutMs;
|
|
385
|
+
for (;;) {
|
|
386
|
+
try {
|
|
387
|
+
fs.closeSync(fs.openSync(lockPath, 'wx', 0o600));
|
|
388
|
+
break;
|
|
389
|
+
} catch (err) {
|
|
390
|
+
if (err.code !== 'EEXIST') throw err;
|
|
391
|
+
try {
|
|
392
|
+
if (Date.now() - fs.statSync(lockPath).mtimeMs > timeoutMs) {
|
|
393
|
+
fs.rmSync(lockPath, { force: true });
|
|
394
|
+
continue;
|
|
395
|
+
}
|
|
396
|
+
} catch {}
|
|
397
|
+
if (Date.now() > deadline) throw new Error(`Timed out waiting for another Gemini Web setup (${lockPath})`);
|
|
398
|
+
await sleep(300);
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
// A download has no overall deadline, so the holder keeps the lock fresh while it works;
|
|
402
|
+
// only a lock left by a process that is gone goes stale.
|
|
403
|
+
const keepFresh = setInterval(() => {
|
|
404
|
+
try {
|
|
405
|
+
const now = new Date();
|
|
406
|
+
fs.utimesSync(lockPath, now, now);
|
|
407
|
+
} catch {}
|
|
408
|
+
}, Math.max(1000, Math.floor(timeoutMs / 4)));
|
|
409
|
+
keepFresh.unref?.();
|
|
410
|
+
try {
|
|
411
|
+
return await fn();
|
|
412
|
+
} finally {
|
|
413
|
+
clearInterval(keepFresh);
|
|
414
|
+
fs.rmSync(lockPath, { force: true });
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// ensureBackend makes sure the local backend is installed and running, and returns how to reach
|
|
419
|
+
// it. A backend already answering with this setup's key is left alone. Otherwise a missing or
|
|
420
|
+
// untrusted binary is (re)installed from the selected release channel, config and secrets are
|
|
421
|
+
// created when missing, and the backend is started in the background (logging to backend.log)
|
|
422
|
+
// so it outlives the caller.
|
|
423
|
+
export async function ensureBackend(options = {}) {
|
|
424
|
+
const dataDir = options.dataDir || getDataDir();
|
|
425
|
+
const platform = options.platform || process.platform;
|
|
426
|
+
const arch = options.arch || process.arch;
|
|
427
|
+
const fetchFn = options.fetchFn || globalThis.fetch;
|
|
428
|
+
const spawnFn = options.spawnFn || spawn;
|
|
429
|
+
const startTimeoutMs = options.startTimeoutMs ?? 20000;
|
|
430
|
+
|
|
431
|
+
let setup = readLocalSetup(dataDir);
|
|
432
|
+
if (setup && fs.existsSync(binaryPath(dataDir, platform)) && await backendState(setup, fetchFn) === 'up') {
|
|
433
|
+
return setup;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
|
|
437
|
+
return withLock(dataDir, async () => {
|
|
438
|
+
setup = readLocalSetup(dataDir);
|
|
439
|
+
if (setup && fs.existsSync(binaryPath(dataDir, platform)) && await backendState(setup, fetchFn) === 'up') {
|
|
440
|
+
return setup;
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
const trusted = trustedHashes(dataDir, platform, arch);
|
|
444
|
+
const binPath = binaryPath(dataDir, platform);
|
|
445
|
+
if (!fs.existsSync(binPath) || !trusted.includes(computeFileHash(binPath))) {
|
|
446
|
+
await installBackend({ dataDir, platform, arch, fetchFn, channel: backendChannel(dataDir), proxy: options.proxy });
|
|
447
|
+
} else {
|
|
448
|
+
ensureDataFiles(dataDir);
|
|
449
|
+
}
|
|
450
|
+
setup = readLocalSetup(dataDir);
|
|
451
|
+
if (!setup) throw new Error(`Invalid Gemini Web backend config in ${dataDir}`);
|
|
452
|
+
if (await backendState(setup, fetchFn) === 'foreign') {
|
|
453
|
+
throw new Error(`${setup.origin} is already used by another service; change "port" in ${path.join(dataDir, 'config.json')}`);
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
const launch = prepareLaunch(dataDir, trusted, platform);
|
|
457
|
+
const logPath = path.join(dataDir, 'backend.log');
|
|
458
|
+
const log = fs.openSync(logPath, 'a', 0o600);
|
|
459
|
+
let child;
|
|
460
|
+
try {
|
|
461
|
+
child = spawnFn(launch.binPath, launch.args, {
|
|
462
|
+
env: launch.env,
|
|
463
|
+
detached: true,
|
|
464
|
+
stdio: ['ignore', log, log],
|
|
465
|
+
windowsHide: true
|
|
466
|
+
});
|
|
467
|
+
child.on?.('error', () => {});
|
|
468
|
+
if (child.pid) fs.writeFileSync(path.join(dataDir, 'backend.pid'), `${child.pid}\n`, { mode: 0o600 });
|
|
469
|
+
child.unref?.();
|
|
470
|
+
} finally {
|
|
471
|
+
fs.closeSync(log);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
const deadline = Date.now() + startTimeoutMs;
|
|
475
|
+
while (Date.now() < deadline) {
|
|
476
|
+
if (await backendState(setup, fetchFn) === 'up') return setup;
|
|
477
|
+
await sleep(300);
|
|
478
|
+
}
|
|
479
|
+
try { child?.kill?.('SIGTERM'); } catch {}
|
|
480
|
+
if (child?.pid && typeof child?.kill !== 'function') {
|
|
481
|
+
try { process.kill(child.pid, 'SIGTERM'); } catch {}
|
|
482
|
+
}
|
|
483
|
+
fs.rmSync(path.join(dataDir, 'backend.pid'), { force: true });
|
|
484
|
+
throw new Error(`Gemini Web backend did not start within ${Math.round(startTimeoutMs / 1000)}s; see ${logPath}`);
|
|
485
|
+
}, 600000);
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
export async function statusBackend(options = {}) {
|
|
489
|
+
const dataDir = options.dataDir || getDataDir();
|
|
490
|
+
const configPath = path.join(dataDir, 'config.json');
|
|
491
|
+
const fetchFn = options.fetchFn || globalThis.fetch;
|
|
492
|
+
|
|
493
|
+
let host = '127.0.0.1';
|
|
494
|
+
let port = 8083;
|
|
495
|
+
|
|
496
|
+
if (fs.existsSync(configPath)) {
|
|
497
|
+
try {
|
|
498
|
+
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
|
499
|
+
if (config.host === '127.0.0.1') host = config.host;
|
|
500
|
+
if (Number.isInteger(config.port) && config.port > 0) port = config.port;
|
|
501
|
+
} catch {}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const statusUrl = `http://${host}:${port}/`;
|
|
505
|
+
let res;
|
|
506
|
+
try {
|
|
507
|
+
res = await fetchFn(statusUrl, {
|
|
508
|
+
signal: AbortSignal.timeout(2000)
|
|
509
|
+
});
|
|
510
|
+
} catch (err) {
|
|
511
|
+
throw new Error(`Failed to connect to backend at ${statusUrl}: ${err.message}`);
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
if (!res.ok) {
|
|
515
|
+
throw new Error(`Backend returned HTTP ${res.status}`);
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
let data;
|
|
519
|
+
try {
|
|
520
|
+
data = await res.json();
|
|
521
|
+
} catch {
|
|
522
|
+
throw new Error('Backend returned invalid JSON response');
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const version = data.version || 'unknown';
|
|
526
|
+
const models = Array.isArray(data.models) ? data.models.join(', ') : 'none';
|
|
527
|
+
|
|
528
|
+
console.log(`Backend status: ok`);
|
|
529
|
+
console.log(`Version: ${version}`);
|
|
530
|
+
console.log(`Available models: ${models}`);
|
|
531
|
+
|
|
532
|
+
return { status: 'ok', version, models: data.models };
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
let onBackendAssetInstalled = null;
|
|
536
|
+
|
|
537
|
+
export function setBackendAssetHook(fn) {
|
|
538
|
+
onBackendAssetInstalled = typeof fn === 'function' ? fn : null;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function processAlive(pid) {
|
|
542
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
543
|
+
try { process.kill(pid, 0); return true; } catch (err) { return err.code === 'EPERM'; }
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
function recordedBackendPid(dataDir) {
|
|
547
|
+
try { return Number(fs.readFileSync(path.join(dataDir, 'backend.pid'), 'utf8').trim()); } catch { return NaN; }
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
export function hasBackendAssets(dataDir = getDataDir(), platform = process.platform, options = {}) {
|
|
551
|
+
const verify = options.verifyIdentity || verifyProcessIdentity;
|
|
552
|
+
if (!fs.existsSync(dataDir)) return false;
|
|
553
|
+
for (const name of ['bin', 'backend-channel.json', 'argon-build.json']) {
|
|
554
|
+
if (fs.existsSync(path.join(dataDir, name))) return true;
|
|
555
|
+
}
|
|
556
|
+
const pidFile = path.join(dataDir, 'backend.pid');
|
|
557
|
+
if (fs.existsSync(pidFile)) {
|
|
558
|
+
const pid = recordedBackendPid(dataDir);
|
|
559
|
+
const bin = binaryPath(dataDir, platform);
|
|
560
|
+
if (processAlive(pid) && verify(pid, bin, platform) !== false) {
|
|
561
|
+
return true;
|
|
562
|
+
}
|
|
563
|
+
try { fs.rmSync(pidFile, { force: true }); } catch {}
|
|
564
|
+
}
|
|
565
|
+
return false;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function forceRemoveBackendPath(target, platform) {
|
|
569
|
+
if (!fs.existsSync(target)) return false;
|
|
570
|
+
try {
|
|
571
|
+
if (platform !== 'win32') {
|
|
572
|
+
const st = fs.lstatSync(target);
|
|
573
|
+
if (st.isDirectory()) {
|
|
574
|
+
try { fs.chmodSync(target, (st.mode & 0o777) | 0o700); } catch {}
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
fs.rmSync(target, { recursive: true, force: true });
|
|
578
|
+
return !fs.existsSync(target);
|
|
579
|
+
} catch {
|
|
580
|
+
return false;
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
export async function stopBackend(options = {}) {
|
|
585
|
+
const dataDir = options.dataDir || getDataDir();
|
|
586
|
+
const platform = options.platform || process.platform;
|
|
587
|
+
const fetchFn = options.fetchFn || globalThis.fetch;
|
|
588
|
+
const verify = options.verifyIdentity || verifyProcessIdentity;
|
|
589
|
+
const pidFile = path.join(dataDir, 'backend.pid');
|
|
590
|
+
const bin = binaryPath(dataDir, platform);
|
|
591
|
+
|
|
592
|
+
if (!fs.existsSync(dataDir)) return { stopped: true };
|
|
593
|
+
|
|
594
|
+
const setup = readLocalSetup(dataDir);
|
|
595
|
+
const state = setup ? await backendState(setup, fetchFn) : 'down';
|
|
596
|
+
if (state === 'foreign') {
|
|
597
|
+
throw new Error(`Cannot stop unknown or foreign process listening on ${setup.origin}`);
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
const candidates = [];
|
|
601
|
+
const tracked = recordedBackendPid(dataDir);
|
|
602
|
+
if (Number.isInteger(tracked) && tracked > 0) candidates.push(tracked);
|
|
603
|
+
if (fs.existsSync(bin)) {
|
|
604
|
+
try {
|
|
605
|
+
candidates.push(...studioProcessPids(bin, platform));
|
|
606
|
+
} catch {}
|
|
607
|
+
if (setup && state === 'up') {
|
|
608
|
+
const port = Number(new URL(setup.origin).port);
|
|
609
|
+
try {
|
|
610
|
+
candidates.push(...studioListenerPids(port, platform));
|
|
611
|
+
} catch {}
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
const live = [...new Set(candidates)].filter(p => processAlive(p));
|
|
616
|
+
const verified = [];
|
|
617
|
+
const unknown = [];
|
|
618
|
+
for (const p of live) {
|
|
619
|
+
const identity = verify(p, bin, platform);
|
|
620
|
+
if (identity === true) verified.push(p);
|
|
621
|
+
else if (identity === null) unknown.push(p);
|
|
622
|
+
}
|
|
623
|
+
if (!verified.length) {
|
|
624
|
+
// An uninspectable live process keeps its record rather than being abandoned or killed blind.
|
|
625
|
+
if (unknown.length) {
|
|
626
|
+
return { stopped: false, reported: `Cannot inspect gemini-web2api-go process ${unknown.join(', ')} safely; its PID record was kept` };
|
|
627
|
+
}
|
|
628
|
+
try { fs.rmSync(pidFile, { force: true }); } catch {}
|
|
629
|
+
if (state === 'up') {
|
|
630
|
+
return { stopped: false, reported: `Cannot identify a verified gemini-web2api-go process for ${setup.origin}` };
|
|
631
|
+
}
|
|
632
|
+
return { stopped: true };
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
for (const pid of verified) {
|
|
636
|
+
try { process.kill(pid, 'SIGTERM'); } catch {}
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
const deadline = Date.now() + 5000;
|
|
640
|
+
while (Date.now() < deadline) {
|
|
641
|
+
if (verified.every(p => !processAlive(p))) break;
|
|
642
|
+
await sleep(100);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
if (options.force && verified.some(p => processAlive(p))) {
|
|
646
|
+
for (const pid of verified) {
|
|
647
|
+
if (processAlive(pid) && verify(pid, bin, platform) === true) {
|
|
648
|
+
try { process.kill(pid, 'SIGKILL'); } catch {}
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
const killDeadline = Date.now() + 1000;
|
|
652
|
+
while (Date.now() < killDeadline) {
|
|
653
|
+
if (verified.every(p => !processAlive(p))) break;
|
|
654
|
+
await sleep(50);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
if (verified.some(p => processAlive(p))) {
|
|
659
|
+
return { stopped: false, reported: `Process ${verified.filter(p => processAlive(p)).join(', ')} did not exit after SIGTERM` };
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
if (unknown.some(p => processAlive(p))) {
|
|
663
|
+
return { stopped: false, reported: `Cannot inspect gemini-web2api-go process ${unknown.filter(p => processAlive(p)).join(', ')} safely; its PID record was kept` };
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
try { fs.rmSync(pidFile, { force: true }); } catch {}
|
|
667
|
+
|
|
668
|
+
if (setup && state === 'up') {
|
|
669
|
+
const closeDeadline = Date.now() + 2000;
|
|
670
|
+
while (Date.now() < closeDeadline) {
|
|
671
|
+
if (await backendState(setup, fetchFn) === 'down') break;
|
|
672
|
+
await sleep(100);
|
|
673
|
+
}
|
|
674
|
+
if (await backendState(setup, fetchFn) !== 'down') {
|
|
675
|
+
return { stopped: false, reported: `${setup.origin} is still responding after stop` };
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
return { stopped: true };
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
// cleanBackend stops any running managed gemini-web2api-go process in dataDir and deletes the
|
|
683
|
+
// downloaded binary and channel metadata while preserving config.json, secrets.json, gemini.db,
|
|
684
|
+
// and logs.
|
|
685
|
+
export async function cleanBackend(options = {}) {
|
|
686
|
+
const dataDir = options.dataDir || getDataDir();
|
|
687
|
+
const platform = options.platform || process.platform;
|
|
688
|
+
|
|
689
|
+
if (!fs.existsSync(dataDir)) {
|
|
690
|
+
return { stopped: true, cleaned: true, removed: [], dataDir };
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
return withLock(dataDir, async () => {
|
|
694
|
+
const stopRes = await stopBackend({ dataDir, platform, fetchFn: options.fetchFn, force: true, verifyIdentity: options.verifyIdentity }).catch(() => null);
|
|
695
|
+
|
|
696
|
+
// A PID whose identity cannot be disproven is not evidence the backend exited: keep its
|
|
697
|
+
// record and assets rather than deleting them under it, as assertStudioExited does.
|
|
698
|
+
const bin = binaryPath(dataDir, platform);
|
|
699
|
+
const tracked = recordedBackendPid(dataDir);
|
|
700
|
+
const pidFile = path.join(dataDir, 'backend.pid');
|
|
701
|
+
const verify = options.verifyIdentity || verifyProcessIdentity;
|
|
702
|
+
let lingering = [];
|
|
703
|
+
if (processAlive(tracked) && verify(tracked, bin, platform) !== false) {
|
|
704
|
+
lingering = [tracked];
|
|
705
|
+
} else {
|
|
706
|
+
try { fs.rmSync(pidFile, { force: true }); } catch {}
|
|
707
|
+
if (fs.existsSync(bin)) {
|
|
708
|
+
try {
|
|
709
|
+
lingering = studioProcessPids(bin, platform)
|
|
710
|
+
.filter(p => processAlive(p) && verify(p, bin, platform) !== false);
|
|
711
|
+
} catch {}
|
|
712
|
+
}
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
if (lingering.length > 0 || (stopRes && !stopRes.stopped)) {
|
|
716
|
+
return {
|
|
717
|
+
stopped: false,
|
|
718
|
+
cleaned: false,
|
|
719
|
+
removed: [],
|
|
720
|
+
dataDir,
|
|
721
|
+
reported: stopRes?.reported || `Gemini Web backend may still be running (PID ${lingering.join(', ')})`
|
|
722
|
+
};
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
const removed = [];
|
|
726
|
+
for (const name of ['bin', 'backend.pid', 'backend-channel.json', 'argon-build.json']) {
|
|
727
|
+
if (forceRemoveBackendPath(path.join(dataDir, name), platform)) {
|
|
728
|
+
removed.push(name);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
return { stopped: true, cleaned: true, removed, dataDir };
|
|
733
|
+
}, options.lockTimeoutMs ?? 600000);
|
|
734
|
+
}
|