@dorokuma/magpie-gemini-web 0.15.2 → 0.15.3

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 CHANGED
@@ -2,6 +2,13 @@
2
2
 
3
3
  本文件按版本倒序记录 `magpie-gemini-web`(0.15.0 起为 `@dorokuma/magpie-gemini-web`)的全部已发布与待发变更,依据本仓 `git log` 与 tag 事实编写。
4
4
 
5
+ ## 0.15.3
6
+
7
+ ### 修复
8
+ - 后端版本感知自愈:`ensureBackend` 收养在跑后端前比对后端自报版本(`GET /` 的 `version`)与盘上二进制期望版本(pin 版本、`argon-build.json` 记录的本地构建版本)。**插件升级现在真正换后端**:旧版只查健康就收养活进程,npm 更新后老后端只要不死就永远顶替新版运行。
9
+ - 陈旧后端正确回收:版本不匹配或盘上二进制不可信时,按「监听端口 + 进程映像归属本数据目录(exe/--config/--db 任一路径落在 dataDir 内)」精确识别并终止旧进程(Linux 走 `/proc`,macOS 走 `ps`,Windows 无此场景),再安装/拉起 pin 版本;同名端口但归属其它数据目录的进程、以及无法识别的占用一律不动。
10
+ - 修复两处静默假成功:旧逻辑在「二进制换了但旧进程仍占端口」时健康检查照样 200,新进程永远起不来而表面一切正常;「占端口者密钥不同(foreign 表象)」时直接报错而非回收,手工/老插件起的后端永久卡死。
11
+
5
12
  ## 0.15.2
6
13
 
7
14
  ### 文档
package/lib/native.mjs CHANGED
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import os from 'node:os';
4
4
  import crypto from 'node:crypto';
5
- import { spawn, execFile } from 'node:child_process';
5
+ import { spawn, execFile, execFileSync } from 'node:child_process';
6
6
  import { validateProxyURL } from './setup.mjs';
7
7
  import { verifyProcessIdentity, studioProcessPids, studioListenerPids } from './studio-native.mjs';
8
8
  import { hasProxyCredentials, normalizeCurlProxy, redactProxyCredentials } from './studio-upstream.mjs';
@@ -376,6 +376,133 @@ async function backendState(setup, fetchFn) {
376
376
  return res.ok ? 'up' : 'foreign';
377
377
  }
378
378
 
379
+
380
+ // backendVersion asks the backend at setup for its self-reported version (the same string
381
+ // --version prints). Returns null when the backend is down, foreign, or too old to answer.
382
+ async function backendVersion(setup, fetchFn) {
383
+ try {
384
+ const res = await fetchFn(`${setup.origin}/`, { signal: AbortSignal.timeout(3000) });
385
+ if (!res.ok) return null;
386
+ const data = await res.json();
387
+ return typeof data.version === "string" && data.version ? data.version : null;
388
+ } catch {
389
+ return null;
390
+ }
391
+ }
392
+
393
+ // normalizeVersion strips a leading "v" so "v5.0.0" and "5.0.0" compare equal.
394
+ function normalizeVersion(v) { return typeof v === "string" ? v.replace(/^v/, "") : null; }
395
+
396
+ // expectedBackendVersion returns the version string the running backend should report for the
397
+ // binary on disk: a trusted argon-build.json local build keeps its recorded version, the
398
+ // pinned release keeps its tag version, and anything else falls back to the pin so an
399
+ // untrusted binary is still steered back to the release.
400
+ function expectedBackendVersion(dataDir, platform, arch) {
401
+ const channel = backendChannel(dataDir);
402
+ let fallback = release.version;
403
+ try {
404
+ const binHash = fs.existsSync(binaryPath(dataDir, platform))
405
+ ? computeFileHash(binaryPath(dataDir, platform)) : null;
406
+ if (binHash) {
407
+ try {
408
+ const argon = JSON.parse(fs.readFileSync(path.join(dataDir, "argon-build.json"), "utf8"));
409
+ if (argon.sha256 === binHash && typeof argon.version === "string") return argon.version;
410
+ } catch {}
411
+ try {
412
+ const pin = pinnedBinary(platform, arch, channel);
413
+ if (pin.sha256 === binHash) return release.version;
414
+ } catch {}
415
+ }
416
+ } catch {}
417
+ return fallback;
418
+ }
419
+
420
+ // inDataDirBackendProc
421
+ // using /proc on Linux so a stale binary renamed elsewhere is still recognised.
422
+ // backendOwnedByDataDir reports whether pid is OUR backend: it must both run a
423
+ // gemini-web2api-go image and tie itself to this dataDir — launched from bin/ inside it, or
424
+ // carrying --config/--db inside it. Both halves keep a same-port stranger (another install,
425
+ // or a test fixture pointing its config at a live port) from being killed by mistake.
426
+ function backendOwnedByDataDir(pid, dataDir, platform) {
427
+ const root = path.resolve(dataDir);
428
+ const owned = candidate => {
429
+ if (!candidate) return false;
430
+ const cleaned = candidate.replace(/ \(deleted\)$/, "");
431
+ if (!path.basename(cleaned).startsWith("gemini-web2api-go")) return false;
432
+ const resolved = path.resolve(cleaned);
433
+ const rel = path.relative(root, resolved);
434
+ return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
435
+ };
436
+ const argsInDataDir = cmdline => {
437
+ if (!cmdline) return false;
438
+ return cmdline.split("\0").concat(cmdline.split(/\s+/)).some(a => {
439
+ const v = a.replace(/^--(?:config|db)=/, "");
440
+ if (!v) return false;
441
+ const resolved = path.resolve(v);
442
+ const rel = path.relative(root, resolved);
443
+ return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
444
+ });
445
+ };
446
+ if (platform === "linux") {
447
+ let exe = "", cmdline = "";
448
+ try { exe = fs.readlinkSync(`/proc/${pid}/exe`); } catch {}
449
+ try { cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, "utf8"); } catch {}
450
+ const arg0 = cmdline.split("\0")[0] || "";
451
+ // The executable image must live under dataDir (bin/, backups kept beside it), AND the
452
+ // process must own this dataDir either by its launch path or by --config/--db inside it.
453
+ return (owned(exe) || owned(arg0)) && (owned(arg0) || argsInDataDir(cmdline));
454
+ }
455
+ if (platform === "darwin") {
456
+ try {
457
+ const cmdline = execFileSync("ps", ["-p", String(pid), "-ww", "-o", "command="], { encoding: "utf8", timeout: 5000 }).trim();
458
+ const arg0 = cmdline.split(/\s+/)[0] || "";
459
+ return owned(arg0) && argsInDataDir(cmdline);
460
+ } catch { return false; }
461
+ }
462
+ // win32 cannot have a stale backend: Windows locks the running image, so the binary can
463
+ // never be replaced underneath a live process — verifyProcessIdentity covers it.
464
+ return false;
465
+ }
466
+
467
+ // staleBackendPids lists live processes listening on setup.origin that are NOT the binary on
468
+ // disk but still look like a gemini-web2api-go image — the leftovers that keep an outdated
469
+ // backend answering health checks after the binary was swapped.
470
+ function staleBackendPids(setup, dataDir, platform, verify) {
471
+ const bin = binaryPath(dataDir, platform);
472
+ const port = Number(new URL(setup.origin).port);
473
+ let listeners = [];
474
+ try { listeners = studioListenerPids(port, platform); } catch {}
475
+ const tracked = recordedBackendPid(dataDir);
476
+ const candidates = [...new Set([...listeners, ...(Number.isInteger(tracked) && tracked > 0 ? [tracked] : [])])];
477
+ // No verify exemption: reaching this point means the answerer is stale (version mismatch)
478
+ // or the backend is being rebuilt — a same-path stale process must go down too.
479
+ return candidates.filter(pid => processAlive(pid) && backendOwnedByDataDir(pid, dataDir, platform));
480
+ }
481
+
482
+ // stopStaleBackend kills backend processes that hold the port but are not the managed binary,
483
+ // so the release build can actually take over the port instead of being adopted-and-masked.
484
+ async function stopStaleBackend(setup, dataDir, platform, verify, fetchFn) {
485
+ const stale = staleBackendPids(setup, dataDir, platform, verify);
486
+ if (!stale.length) return 0;
487
+ for (const pid of stale) { try { process.kill(pid, "SIGTERM"); } catch {} }
488
+ const deadline = Date.now() + 5000;
489
+ while (Date.now() < deadline) {
490
+ if (stale.every(p => !processAlive(p))) break;
491
+ await sleep(100);
492
+ }
493
+ for (const pid of stale) {
494
+ if (processAlive(pid) && backendOwnedByDataDir(pid, dataDir, platform)) {
495
+ try { process.kill(pid, "SIGKILL"); } catch {}
496
+ }
497
+ }
498
+ const closeDeadline = Date.now() + 2000;
499
+ while (Date.now() < closeDeadline) {
500
+ if (await backendState(setup, fetchFn) !== "up") break;
501
+ await sleep(100);
502
+ }
503
+ return stale.length;
504
+ }
505
+
379
506
  const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
380
507
 
381
508
  // withLock serializes setup across plugin hosts (Magpie may run more than one) by a lock file.
@@ -426,23 +553,68 @@ export async function ensureBackend(options = {}) {
426
553
  const arch = options.arch || process.arch;
427
554
  const fetchFn = options.fetchFn || globalThis.fetch;
428
555
  const spawnFn = options.spawnFn || spawn;
556
+ const verify = options.verifyIdentity || verifyProcessIdentity;
429
557
  const startTimeoutMs = options.startTimeoutMs ?? 20000;
430
558
 
559
+ // Adoption is version-aware. A healthy backend is only reused when it reports the version
560
+ // the binary on disk should run; a stale one — including the case where it answers with a
561
+ // different API key and so looks "foreign" — is killed first so the release build can
562
+ // actually take the port. Without this, a plugin upgrade never reaches the backend: the
563
+ // old process keeps answering health checks and the swap silently never happens.
431
564
  let setup = readLocalSetup(dataDir);
432
- if (setup && fs.existsSync(binaryPath(dataDir, platform)) && await backendState(setup, fetchFn) === 'up') {
433
- return setup;
434
- }
565
+ const expectedVersion = expectedBackendVersion(dataDir, platform, arch);
566
+ const matchesExpected = async () => {
567
+ const running = normalizeVersion(await backendVersion(setup, fetchFn));
568
+ const expected = normalizeVersion(expectedVersion);
569
+ if (!running) return 'unknown'; // too old to report — adopt, cannot self-heal
570
+ return running === expected ? 'match' : 'stale';
571
+ };
435
572
 
436
573
  fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
437
574
  return withLock(dataDir, async () => {
438
575
  setup = readLocalSetup(dataDir);
439
- if (setup && fs.existsSync(binaryPath(dataDir, platform)) && await backendState(setup, fetchFn) === 'up') {
440
- return setup;
441
- }
442
-
443
576
  const trusted = trustedHashes(dataDir, platform, arch);
444
577
  const binPath = binaryPath(dataDir, platform);
445
- if (!fs.existsSync(binPath) || !trusted.includes(computeFileHash(binPath))) {
578
+ const binTrusted = fs.existsSync(binPath) && trusted.includes(computeFileHash(binPath));
579
+
580
+ if (setup) {
581
+ const state = await backendState(setup, fetchFn);
582
+ if (state === 'up') {
583
+ const verdict = binTrusted ? await matchesExpected() : 'stale';
584
+ if (verdict === 'match' || verdict === 'unknown') return setup;
585
+ // Version mismatch or untrusted binary: kill whatever holds the port before the
586
+ // pinned build is installed and respawned. Nothing killed = the listener is not
587
+ // ours to swap, so keep adopting rather than break a working install.
588
+ const killed = await stopStaleBackend(setup, dataDir, platform, verify, fetchFn);
589
+ if (!killed) return setup;
590
+ if (await backendState(setup, fetchFn) === 'up') {
591
+ // Port still claimed by something we could not identify; never stack a second
592
+ // backend behind it.
593
+ return setup;
594
+ }
595
+ } else if (state === 'foreign' && fs.existsSync(binPath)) {
596
+ // "foreign" here is often still OUR backend — launched by hand or by an older plugin
597
+ // with a different secrets file — holding the port while a pinned build waits. Only
598
+ // images owned by this dataDir are killed; anything else keeps its name. When no
599
+ // binary exists yet we skip the probe entirely: the port cannot be ours anyway, and
600
+ // probing now would consume the caller's network before the download runs.
601
+ const killed = await stopStaleBackend(setup, dataDir, platform, verify, fetchFn);
602
+ if (!killed) {
603
+ throw new Error(`${setup.origin} is already used by another service; change "port" in ${path.join(dataDir, 'config.json')}`);
604
+ }
605
+ const after = await backendState(setup, fetchFn);
606
+ if (after === 'foreign') {
607
+ throw new Error(`${setup.origin} is already used by another service; change "port" in ${path.join(dataDir, 'config.json')}`);
608
+ }
609
+ if (after === 'up') {
610
+ const verdict = binTrusted ? await matchesExpected() : 'stale';
611
+ if (verdict === 'match' || verdict === 'unknown') return setup;
612
+ await stopStaleBackend(setup, dataDir, platform, verify, fetchFn);
613
+ }
614
+ }
615
+ }
616
+
617
+ if (!binTrusted) {
446
618
  await installBackend({ dataDir, platform, arch, fetchFn, channel: backendChannel(dataDir), proxy: options.proxy });
447
619
  } else {
448
620
  ensureDataFiles(dataDir);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dorokuma/magpie-gemini-web",
3
- "version": "0.15.2",
3
+ "version": "0.15.3",
4
4
  "description": "Google AI Studio and Gemini Web provider for Magpie (Gemini 4 Carbon / Hydrogen / Argon, Nano Banana image generation, Deep Research), backed by AIStudio2API and gemini-web2api-go",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",