dsh-magpie-connect 0.4.4 → 0.5.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.md CHANGED
@@ -90,8 +90,12 @@ Key 无效、网关不通)不会清空本地目录,避免把选择器误清
90
90
  **从旧版本升级,我原来的删除记录还在吗?**
91
91
 
92
92
  在。首次启动会自动把旧的 `hiddenModels`(黑名单)换算成 `enabledModels`(白名单),
93
- 并写回 `~/.dsh-magpie-connect/settings.json`,只执行一次。若升级时网关不可达、
94
- 算不出旧列表,则退回「继承网关目录」,不会误删你能用的模型。
93
+ 只执行一次。若升级时网关不可达、算不出旧列表,则退回「继承网关目录」,不会误删你能用的模型。
94
+
95
+ > 配置文件位置:从 0.5.0 起写在 `$DSH_HOME/storages/magpie-connect/settings.json`
96
+ >(默认 `~/.dsh/storages/magpie-connect/settings.json`)。老版本的
97
+ > `~/.dsh-magpie-connect/settings.json` **不迁移、不删除**,只做只读兼容——升级后不改任何文件;
98
+ > 你第一次在设置页保存(或删除模型触发自动保存)时,新配置才会写入新位置,同时清掉旧文件。
95
99
 
96
100
  **为什么我删掉的模型又出现了?**
97
101
 
@@ -144,7 +148,7 @@ Key 无效、网关不通)不会清空本地目录,避免把选择器误清
144
148
  | `displayName` | `Magpie` | 模型选择器里的分组名。 |
145
149
  | `baseUrl` | `http://127.0.0.1:3425/v1` | 带版本号的 API 地址。 |
146
150
  | `apiKey` | `''`(未配置) | 网关凭据。必填,即使网关不校验——地址有默认值,Key 没有。 |
147
- | `dataDir` | `~/.dsh-magpie-connect` | 状态目录(状态快照、设置文件、模型缓存)。 |
151
+ | `dataDir` | `$DSH_HOME/storages/magpie-connect` | 状态目录(状态快照、设置文件、模型缓存)。默认 `~/.dsh/storages/magpie-connect`;显式指定后不会读写旧目录。 |
148
152
  | `refreshSeconds` | `300` | 模型目录刷新间隔(秒)。 |
149
153
  | `maxRetries` | `2` | 遇到 429/5xx 时的连接重试次数。 |
150
154
  | `timeoutMs` | `300000` | 单次请求的总超时(毫秒)。 |
@@ -177,7 +181,7 @@ http://127.0.0.1:3425/v1 ← 按 native_endpoints 选择 chat/completions 或 r
177
181
  - **容错** — 启动即注册,目录在后台预热;静默挂起会被看门狗快速判为超时;
178
182
  上游截断如实上报,不做自动续写。
179
183
 
180
- 运行状态快照写在 `~/.dsh-magpie-connect/adapter-status.json`,设置与缓存在同一目录。
184
+ 运行状态快照写在 `<dataDir>/adapter-status.json`(默认 `~/.dsh/storages/magpie-connect/adapter-status.json`),设置与缓存在同一目录。
181
185
 
182
186
  ## 开发
183
187
 
package/cordis.patch.yml CHANGED
@@ -8,12 +8,17 @@
8
8
  # (saved to <dataDir>/settings.json, applied without restart) and hides models
9
9
  # from the picker. Page values win per-field; the patch config below stays as
10
10
  # fallback (e.g. headless compositions without the settings page).
11
+ # <dataDir> defaults to $DSH_HOME/storages/magpie-connect
12
+ # (~/.dsh/storages/magpie-connect). The pre-0.5 dir ~/.dsh-magpie-connect is
13
+ # read once as a fallback and removed on the first save; it is never migrated
14
+ # eagerly, so an upgrade that changes nothing touches no file.
11
15
  #
12
16
  # - baseUrl: versioned API root (default http://127.0.0.1:3425/v1). Include the
13
17
  # version segment: the plugin appends only the resource (/models, /responses),
14
18
  # so a gateway on /v2 or /v3 is reached by changing this one string.
15
19
  # - apiKey: gateway credential (required, even if /models needs none).
16
- # - dataDir: plugin state dir (status snapshot, settings file, catalog cache).
20
+ # - dataDir: plugin state dir (status snapshot, settings file, catalog cache);
21
+ # defaults to $DSH_HOME/storages/magpie-connect.
17
22
  # - displayName: cosmetic label in the model picker (route id stays providerId).
18
23
  # - providerId: RENAME the route id itself (existing sessions pointing at the
19
24
  # old id will orphan — prefer displayName for a cosmetic rename).
package/dsh.plugin.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-magpie-connect",
3
3
  "description": "Magpie gateway models for the DeepSeek Harness web GUI",
4
- "version": "0.4.4",
4
+ "version": "0.5.0",
5
5
  "entry": {
6
6
  "name": "dsh-magpie-connect",
7
7
  "inject": [
package/lib/client.js CHANGED
@@ -592,7 +592,7 @@ function shouldRetryPending(snapshot2, attempts, limit = PENDING_RETRY_LIMIT) {
592
592
 
593
593
  // src/client/page.tsx
594
594
  var import_jsx_runtime3 = require("react/jsx-runtime");
595
- var PLUGIN_VERSION = "0.4.4";
595
+ var PLUGIN_VERSION = "0.5.0";
596
596
  var REPO_URL = "https://github.com/bitxeno/dsh-magpie-connect";
597
597
  var css2 = {
598
598
  section: { display: "flex", flexDirection: "column", gap: 16, maxWidth: 780, paddingBottom: 32 },
package/lib/index.js CHANGED
@@ -3,6 +3,7 @@ import { join as join4 } from "node:path";
3
3
  import { writeFile as writeFile3 } from "node:fs/promises";
4
4
 
5
5
  // src/adapter/catalog.ts
6
+ import { randomBytes } from "node:crypto";
6
7
  import { readFile, rename, rm, writeFile, mkdir } from "node:fs/promises";
7
8
  import { dirname, join } from "node:path";
8
9
  var KNOWN_EFFORTS = ["minimal", "low", "medium", "high", "xhigh", "max"];
@@ -156,7 +157,7 @@ var ModelCatalog = class {
156
157
  let attempts = 0;
157
158
  while (this.#entries.size === 0 && attempts < 4 && !this.#stopped) {
158
159
  attempts += 1;
159
- await new Promise((resolve) => setTimeout(resolve, this.#startupRetryMs));
160
+ await new Promise((resolve2) => setTimeout(resolve2, this.#startupRetryMs));
160
161
  if (this.#stopped) return;
161
162
  await this.refreshOnce();
162
163
  }
@@ -479,11 +480,15 @@ async function fetchMagpieModels(baseUrl, fetchImpl, options = {}) {
479
480
  }
480
481
  async function saveModelsCache(path, entries, now) {
481
482
  const cache = { updatedAt: now, entries: [...entries.values()] };
482
- const tmp = `${path}.${process.pid}.tmp`;
483
+ const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
483
484
  await mkdir(dirname(path), { recursive: true });
484
- await writeFile(tmp, JSON.stringify(cache), "utf8");
485
- await rm(path, { force: true });
486
- await rename(tmp, path);
485
+ try {
486
+ await writeFile(tmp, JSON.stringify(cache), { encoding: "utf8", mode: 384, flag: "wx" });
487
+ await rename(tmp, path);
488
+ } finally {
489
+ await rm(tmp, { force: true }).catch(() => {
490
+ });
491
+ }
487
492
  }
488
493
  async function loadModelsCache(path) {
489
494
  const raw = JSON.parse(await readFile(path, "utf8"));
@@ -496,6 +501,22 @@ function defaultCachePath(dataDir) {
496
501
  return join(dataDir, "magpie-models.json");
497
502
  }
498
503
 
504
+ // src/homeDir.ts
505
+ import { homedir } from "node:os";
506
+ import { join as join2, resolve } from "node:path";
507
+ function resolveDshHome(configured, env = process.env) {
508
+ if (typeof configured === "string" && configured.trim() !== "") return resolve(configured);
509
+ const fromEnv = env.DSH_HOME;
510
+ if (typeof fromEnv === "string" && fromEnv.trim() !== "") return resolve(fromEnv);
511
+ return join2(homedir(), ".dsh");
512
+ }
513
+ function dshHomePath(...segments) {
514
+ return join2(resolveDshHome(), ...segments);
515
+ }
516
+ function legacyDataDir() {
517
+ return join2(homedir(), ".dsh-magpie-connect");
518
+ }
519
+
499
520
  // src/adapter/magpie-adapter.ts
500
521
  import { createProvider } from "@earendil-works/pi-ai";
501
522
  import * as openaiCompletions from "@earendil-works/pi-ai/api/openai-completions";
@@ -915,8 +936,8 @@ function userContentToBlocks(blocks, requestImages) {
915
936
  var TIMED_OUT = Symbol("watchdog-timed-out");
916
937
  function raceTimeout(promise, ms) {
917
938
  let timer;
918
- const timeout = new Promise((resolve) => {
919
- timer = setTimeout(() => resolve(TIMED_OUT), ms);
939
+ const timeout = new Promise((resolve2) => {
940
+ timer = setTimeout(() => resolve2(TIMED_OUT), ms);
920
941
  const t = timer;
921
942
  t.unref?.();
922
943
  });
@@ -1240,8 +1261,6 @@ var MagpieAdapter = class {
1240
1261
  };
1241
1262
 
1242
1263
  // src/config.ts
1243
- import { homedir } from "node:os";
1244
- import { join as join2 } from "node:path";
1245
1264
  var defaults = {
1246
1265
  providerId: "dsh-magpie-connect",
1247
1266
  displayName: "Magpie",
@@ -1262,11 +1281,12 @@ function resolveConfig(config = {}) {
1262
1281
  displayName: config.displayName ?? (config.providerId ?? defaults.displayName),
1263
1282
  baseUrl: config.baseUrl ?? defaults.baseUrl,
1264
1283
  apiKey: config.apiKey ?? defaults.apiKey,
1265
- dataDir: config.dataDir ?? join2(homedir(), ".dsh-magpie-connect")
1284
+ dataDir: config.dataDir ?? dshHomePath("storages", "magpie-connect")
1266
1285
  };
1267
1286
  }
1268
1287
 
1269
1288
  // src/settings.ts
1289
+ import { randomBytes as randomBytes2 } from "node:crypto";
1270
1290
  import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2, rename as rename2, rm as rm2 } from "node:fs/promises";
1271
1291
  import { dirname as dirname2, join as join3 } from "node:path";
1272
1292
  var SETTINGS_FILE = "settings.json";
@@ -1344,28 +1364,103 @@ function isConfigured(endpoint) {
1344
1364
  }
1345
1365
  var SettingsStore = class {
1346
1366
  #path;
1367
+ /**
1368
+ * Pre-0.5 settings file (`~/.dsh-magpie-connect/settings.json`), or
1369
+ * `undefined` when no read-through-and-migrate is wanted (an explicit
1370
+ * `dataDir` means the user owns the path — never fall back, never delete).
1371
+ *
1372
+ * Read-only until the first successful write: settings are only moved to the
1373
+ * new location when the user saves something, so an upgrade that changes no
1374
+ * setting touches no file at all.
1375
+ */
1376
+ #legacyPath;
1377
+ /** True while the live state came from {@link #legacyPath}, not {@link #path}. */
1378
+ #legacySource = false;
1379
+ /**
1380
+ * Set when the settings file exists but could not be read/parsed at startup.
1381
+ * Blocks a partial save (e.g. the model-list autosave that posts only
1382
+ * `enabledModels`) from writing the empty in-memory state over a file whose
1383
+ * credentials we simply failed to load — that is how a key silently vanished.
1384
+ */
1385
+ #loadFailed = false;
1347
1386
  #settings = {};
1387
+ /** Serializes writes: one persist in flight, so two generations cannot interleave. */
1388
+ #writeChain = Promise.resolve();
1348
1389
  #listeners = /* @__PURE__ */ new Set();
1349
1390
  constructor(options = {}) {
1350
1391
  this.#path = options.path;
1392
+ this.#legacyPath = options.legacyPath;
1351
1393
  }
1352
1394
  /**
1353
- * Read and normalize the persisted document (missing/corrupt reads as empty,
1354
- * never throws). Does not touch memory or disk.
1395
+ * Read one settings file, distinguishing "absent" from "unreadable".
1355
1396
  *
1356
- * Separate from {@link load} because the legacy conversion needs the gateway
1357
- * directory, and that can only be read once the persisted endpoint is known:
1358
- * the process starts with the patch/default endpoint, not the user's.
1397
+ * Returns the raw parsed document (`raw`) untouched so the legacy
1398
+ * `hiddenModels` conversion can still see that field; validation happens in
1399
+ * {@link read}. `exists: true` with `raw: undefined` means the file is there
1400
+ * but could not be read or parsed — callers must not mistake that for "no
1401
+ * configuration", or a later save would persist the blank state over a
1402
+ * perfectly good file.
1403
+ * @param path - file to read; `undefined` yields `{ exists: false }`.
1359
1404
  */
1360
- async read() {
1361
- if (!this.#path) return {};
1405
+ async #readFile(path) {
1406
+ if (!path) return { exists: false };
1407
+ let text;
1362
1408
  try {
1363
- const raw = JSON.parse(await readFile2(this.#path, "utf8"));
1364
- return normalizePageSettings(raw);
1365
- } catch {
1366
- return {};
1409
+ text = await readFile2(path, "utf8");
1410
+ } catch (error) {
1411
+ if (error.code === "ENOENT") return { exists: false };
1412
+ return { exists: true, error };
1413
+ }
1414
+ try {
1415
+ return { exists: true, raw: JSON.parse(text) };
1416
+ } catch (error) {
1417
+ return { exists: true, error };
1367
1418
  }
1368
1419
  }
1420
+ /**
1421
+ * Locate the document to use: new location first, then the pre-0.5 file.
1422
+ *
1423
+ * A file that exists but is unreadable is returned as-is (`exists: true`,
1424
+ * `raw: undefined`) so callers can flag it instead of mistaking it for
1425
+ * "no configuration". A present-but-corrupt NEW file is authoritative and
1426
+ * does not fall back to the legacy one — that could resurrect stale
1427
+ * credentials over a deliberately replaced file.
1428
+ */
1429
+ async #resolveRaw() {
1430
+ const fromNew = await this.#readFile(this.#path);
1431
+ if (fromNew.raw !== void 0) return fromNew;
1432
+ if (fromNew.exists) return fromNew;
1433
+ const fromOld = await this.#readFile(this.#legacyPath);
1434
+ if (fromOld.raw !== void 0) {
1435
+ this.#legacySource = true;
1436
+ return fromOld;
1437
+ }
1438
+ return fromOld;
1439
+ }
1440
+ /**
1441
+ * Read and normalize the persisted document without touching memory or disk.
1442
+ *
1443
+ * New location first; when it is absent, fall back **read-only** to the
1444
+ * pre-0.5 file so an upgrade shows the user's saved endpoint immediately.
1445
+ *
1446
+ * A file that is *present but unreadable* is NOT treated as "no
1447
+ * configuration": it sets {@link #loadFailed} (blocking a later partial save
1448
+ * from overwriting it with the blank state) and still returns `{}` so callers
1449
+ * have something to render.
1450
+ */
1451
+ async read() {
1452
+ const resolved = await this.#resolveRaw();
1453
+ if (resolved.raw !== void 0) {
1454
+ try {
1455
+ return normalizePageSettings(resolved.raw);
1456
+ } catch {
1457
+ this.#loadFailed = true;
1458
+ return {};
1459
+ }
1460
+ }
1461
+ if (resolved.exists) this.#loadFailed = true;
1462
+ return {};
1463
+ }
1369
1464
  /**
1370
1465
  * Load persisted settings, running the one-time `hiddenModels` ->
1371
1466
  * `enabledModels` conversion.
@@ -1379,14 +1474,13 @@ var SettingsStore = class {
1379
1474
  */
1380
1475
  async load(known) {
1381
1476
  if (!this.#path) return this.get();
1382
- let raw;
1383
- try {
1384
- raw = JSON.parse(await readFile2(this.#path, "utf8"));
1385
- } catch {
1477
+ const resolved = await this.#resolveRaw();
1478
+ if (resolved.raw === void 0) {
1479
+ if (resolved.exists) this.#loadFailed = true;
1386
1480
  this.#settings = {};
1387
1481
  return this.get();
1388
1482
  }
1389
- const { settings, migrated } = migrateLegacySettings(raw, known);
1483
+ const { settings, migrated } = migrateLegacySettings(resolved.raw, known);
1390
1484
  this.#settings = settings;
1391
1485
  if (migrated) await this.persist().catch(() => {
1392
1486
  });
@@ -1416,8 +1510,14 @@ var SettingsStore = class {
1416
1510
  /** Merge a partial payload, persist, and notify listeners. */
1417
1511
  async save(partial) {
1418
1512
  const normalized = normalizePageSettings(partial);
1513
+ if (this.#loadFailed && normalized.baseUrl === void 0 && normalized.apiKey === void 0) {
1514
+ throw new Error(
1515
+ "dsh-magpie-connect: settings file was unreadable; refusing to overwrite it with a partial save \u2014 reload the settings page or restore settings.json"
1516
+ );
1517
+ }
1419
1518
  this.#settings = { ...this.#settings, ...normalized };
1420
1519
  await this.persist();
1520
+ if (normalized.baseUrl !== void 0 && normalized.apiKey !== void 0) this.#loadFailed = false;
1421
1521
  this.#emit();
1422
1522
  return this.get();
1423
1523
  }
@@ -1434,11 +1534,39 @@ var SettingsStore = class {
1434
1534
  }
1435
1535
  async persist() {
1436
1536
  if (!this.#path) return;
1437
- const tmp = `${this.#path}.${process.pid}.tmp`;
1438
- await mkdir2(dirname2(this.#path), { recursive: true });
1439
- await writeFile2(tmp, JSON.stringify(this.#settings, null, 2), "utf8");
1440
- await rm2(this.#path, { force: true });
1441
- await rename2(tmp, this.#path);
1537
+ this.#writeChain = this.#writeChain.then(
1538
+ () => this.#writeNow(),
1539
+ () => this.#writeNow()
1540
+ );
1541
+ await this.#writeChain;
1542
+ }
1543
+ /**
1544
+ * Write the current state to {@link #path} atomically, then clean up the
1545
+ * pre-0.5 file if this generation had read from it.
1546
+ *
1547
+ * The temp file is a random-suffixed sibling opened with `wx` and renamed
1548
+ * over the target — no `rm` beforehand (that opened a window where the file
1549
+ * did not exist and a concurrent read saw an empty document), and a random
1550
+ * suffix so two generations in one process cannot share a temp name.
1551
+ */
1552
+ async #writeNow() {
1553
+ const target = this.#path;
1554
+ if (!target) return;
1555
+ await mkdir2(dirname2(target), { recursive: true });
1556
+ const tmp = `${target}.${process.pid}.${randomBytes2(6).toString("hex")}.tmp`;
1557
+ try {
1558
+ await writeFile2(tmp, JSON.stringify(this.#settings, null, 2), { encoding: "utf8", mode: 384, flag: "wx" });
1559
+ await rename2(tmp, target);
1560
+ } finally {
1561
+ await rm2(tmp, { force: true }).catch(() => {
1562
+ });
1563
+ }
1564
+ if (this.#legacySource && this.#legacyPath) {
1565
+ await rm2(this.#legacyPath, { force: true }).then(() => {
1566
+ this.#legacySource = false;
1567
+ }).catch(() => {
1568
+ });
1569
+ }
1442
1570
  }
1443
1571
  #emit() {
1444
1572
  for (const listener of [...this.#listeners]) {
@@ -1539,7 +1667,7 @@ async function handleSettingsPost(request) {
1539
1667
  if (normalized.baseUrl !== void 0 || normalized.apiKey !== void 0) {
1540
1668
  await Promise.race([
1541
1669
  backend.catalog.refreshOnce(),
1542
- new Promise((resolve) => setTimeout(resolve, SAVE_REFRESH_WAIT_MS))
1670
+ new Promise((resolve2) => setTimeout(resolve2, SAVE_REFRESH_WAIT_MS))
1543
1671
  ]);
1544
1672
  }
1545
1673
  const endpoint = resolveEffectiveEndpoint(backend.patchEndpoint, saved);
@@ -1704,7 +1832,10 @@ function apply(ctx, config = {}) {
1704
1832
  ).catch(() => {
1705
1833
  });
1706
1834
  };
1707
- const store = new SettingsStore({ path: defaultSettingsPath(dataDir) });
1835
+ const store = new SettingsStore({
1836
+ path: defaultSettingsPath(dataDir),
1837
+ legacyPath: config.dataDir === void 0 ? join4(legacyDataDir(), "settings.json") : void 0
1838
+ });
1708
1839
  const patchEndpoint = { baseUrl: cfg.baseUrl, apiKey: cfg.apiKey };
1709
1840
  const effective = () => resolveEffectiveEndpoint(patchEndpoint, store.get());
1710
1841
  const announceTopology = () => {