dsh-magpie-connect 0.5.0 → 0.6.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
@@ -35,6 +35,12 @@ dsh plugin --profile web add dsh-magpie-connect
35
35
  - **API 地址** — 网关地址,**要带版本号**。默认已填好 `http://127.0.0.1:3425/v1`,网关不在本机时改成实际地址。
36
36
  - **API Key** — 网关凭据,必填。
37
37
 
38
+ > Key 保存后**不会再回显**到页面;输入框留空表示沿用已保存的 Key,只有填入新值才会替换。
39
+ > 「测试连接」和「获取可用模型」同样复用已保存的 Key。设置文件里仍然是原来的 JSON 结构
40
+ > (`baseUrl` / `apiKey` / `enabledModels`),所以降级回旧版本也能直接读取。
41
+ > 插件自有状态目录在 POSIX 系统上为 `0700`、`settings.json` 为 `0600`;旧版本留下的宽权限
42
+ > 会在下次读取时自动收紧(只读文件系统或非 POSIX 平台会跳过,不影响设置读取)。
43
+
38
44
  点「保存」后,可以点「测试连接」确认通不通(会告诉你网关上有多少模型)。两项都齐了才会生效——
39
45
  地址有默认值,Key 没有,所以没填 Key 之前模型选择器是空的。
40
46
 
@@ -46,6 +52,17 @@ dsh plugin --profile web add dsh-magpie-connect
46
52
  点 **获取可用模型**,会弹出网关当前的模型列表:勾选你想要的,再点「应用选择」。
47
53
  弹窗里可以搜索、全选、取消全选。
48
54
 
55
+ 模型选择器、已选模型列表和弹窗统一显示 **`<组名>/<模型名>`**:模型名直接取 API 的
56
+ `display_name`;组名优先取 `magpie_label` 最后一个 ` · ` 右边的部分。若 `magpie_label`
57
+ 缺失或没有可解析的组名,则取 id 第一个 `/` 前的部分,并仅将首字母大写(例如
58
+ `workbuddy-ai/hy4free` → `Workbuddy-ai/Hy4`)。`auto/` 和 `group/` 是特例:组名始终从 id 前缀
59
+ 生成(`Auto`、`Group`),不使用 `magpie_label` 中的通用组名。
60
+ 原始路由 id 只在鼠标悬停时显示,请求、会话历史和白名单里始终是 id,所以改显示名
61
+ 不会影响已保存的选择或历史会话。搜索可以同时按显示名和 id 匹配,列表按显示名排序。
62
+
63
+ > 如果 API 没有返回 `display_name`,显示名回落到原始 id。旧版本留下的本地模型缓存
64
+ > 暂时以 id 显示,等下一次成功读取网关目录后自动换成新标签。
65
+
49
66
  模型列表是**白名单**,和 DSH 自带的「模型」设置语义一致:列表里有什么,选择器就提供
50
67
  什么。不想要的点该行末尾的「删除」,它就从列表和选择器里一起消失;想加回来,点
51
68
  「获取可用模型」,在弹窗里勾上它再「应用选择」。
@@ -178,6 +195,9 @@ http://127.0.0.1:3425/v1 ← 按 native_endpoints 选择 chat/completions 或 r
178
195
  (显式档位直通网关);`none` 关闭思考,`ultra` 直通网关,不在本地截断。
179
196
  - **图片** — 带图的请求经 harness 附件服务取字节后上行;文本模型收到图片会直接
180
197
  失败(harness 已按模型声明的输入类型做过门控)。
198
+ - **输出预算** — 模型目录保留网关声明的最大输出能力;每次请求的默认输出预算沿用
199
+ Magpie 的 DSH 策略,为上下文和压缩保留空间。例如 500,000 上下文、393,216 最大
200
+ 输出的模型默认预留 184,464 输出。显式设置的请求输出预算保持原值,读图能力不变。
181
201
  - **容错** — 启动即注册,目录在后台预热;静默挂起会被看门狗快速判为超时;
182
202
  上游截断如实上报,不做自动续写。
183
203
 
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.5.0",
4
+ "version": "0.6.0",
5
5
  "entry": {
6
6
  "name": "dsh-magpie-connect",
7
7
  "inject": [
package/lib/client.js CHANGED
@@ -44,7 +44,8 @@ var EN = {
44
44
  baseUrlPlaceholder: "http://127.0.0.1:3425/v1",
45
45
  apiKey: "API key",
46
46
  apiKeyPlaceholder: "required",
47
- requiredNote: "API URL and API key are both required. Include the version segment (e.g. /v1) \u2014 the URL is used exactly as written.",
47
+ apiKeySavedPlaceholder: "Saved \u2014 leave blank to keep the existing key",
48
+ requiredNote: "API URL and API key are both required. Once a key is saved, leave the field blank to keep it. Include the version segment (e.g. /v1) \u2014 the URL is used exactly as written.",
48
49
  test: "Test connection",
49
50
  testing: "Testing\u2026",
50
51
  save: "Save",
@@ -97,7 +98,8 @@ var ZH = {
97
98
  baseUrlPlaceholder: "http://127.0.0.1:3425/v1",
98
99
  apiKey: "API Key",
99
100
  apiKeyPlaceholder: "\u5FC5\u586B",
100
- requiredNote: "API \u5730\u5740\u4E0E Key \u5747\u4E3A\u5FC5\u586B\u3002\u5730\u5740\u9700\u5305\u542B\u7248\u672C\u6BB5\uFF08\u5982 /v1\uFF09\uFF0C\u63D2\u4EF6\u6309\u4F60\u586B\u5199\u7684\u539F\u6837\u4F7F\u7528\u3002",
101
+ apiKeySavedPlaceholder: "\u5DF2\u4FDD\u5B58\uFF1B\u7559\u7A7A\u4FDD\u7559\u73B0\u6709 Key",
102
+ requiredNote: "API \u5730\u5740\u4E0E Key \u5747\u4E3A\u5FC5\u586B\u3002Key \u4FDD\u5B58\u540E\u7559\u7A7A\u5373\u53EF\u6CBF\u7528\uFF1B\u5730\u5740\u9700\u5305\u542B\u7248\u672C\u6BB5\uFF08\u5982 /v1\uFF09\uFF0C\u63D2\u4EF6\u6309\u4F60\u586B\u5199\u7684\u539F\u6837\u4F7F\u7528\u3002",
101
103
  test: "\u6D4B\u8BD5\u8FDE\u63A5",
102
104
  testing: "\u6D4B\u8BD5\u4E2D\u2026",
103
105
  save: "\u4FDD\u5B58",
@@ -312,7 +314,9 @@ var css = {
312
314
  item: { display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", borderRadius: 8, background: "transparent" },
313
315
  removeButton: { border: "1px solid var(--dsw-alias-border-l2)", background: "transparent", color: "var(--dsw-alias-label-secondary)", cursor: "pointer", padding: "3px 10px", borderRadius: 6, fontSize: 12, lineHeight: "18px", flex: "none" },
314
316
  itemMain: { display: "flex", flexDirection: "column", gap: 2, minWidth: 0, flex: 1 },
315
- itemId: { fontSize: 13, lineHeight: "20px", fontWeight: 500, color: "var(--dsw-alias-label-primary)", overflowWrap: "anywhere", fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace" },
317
+ // The visible label is `<group>/<name>`; the raw route id is only a hover
318
+ // title, so the list reads cleanly while the allowlist key stays inspectable.
319
+ itemId: { fontSize: 13, lineHeight: "20px", fontWeight: 500, color: "var(--dsw-alias-label-primary)", overflowWrap: "anywhere" },
316
320
  chips: { display: "flex", gap: 6, flexWrap: "wrap" },
317
321
  chip: { fontSize: 11, lineHeight: "18px", padding: "0 7px", borderRadius: 999, border: "1px solid var(--dsw-alias-border-l2)", color: "var(--dsw-alias-label-secondary)", whiteSpace: "nowrap" },
318
322
  // A row the live gateway does not list is informational, not a capability the
@@ -327,7 +331,7 @@ var css = {
327
331
  candidateLabel: { display: "flex", alignItems: "center", gap: 10, padding: "8px 10px", cursor: "pointer" },
328
332
  candidateCheckbox: { width: 15, height: 15, accentColor: "var(--dsw-alias-brand-primary)", flex: "none", cursor: "pointer" },
329
333
  candidateText: { display: "flex", flexDirection: "column", gap: 2, minWidth: 0, flex: 1 },
330
- candidateId: { fontSize: 13, lineHeight: "20px", fontWeight: 500, color: "var(--dsw-alias-label-primary)", overflowWrap: "anywhere", fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace" },
334
+ candidateId: { fontSize: 13, lineHeight: "20px", fontWeight: 500, color: "var(--dsw-alias-label-primary)", overflowWrap: "anywhere" },
331
335
  candidateEmpty: { margin: "24px 0", textAlign: "center", fontSize: 13, lineHeight: "20px", color: "var(--dsw-alias-label-secondary)" }
332
336
  };
333
337
  function formatWindow(value) {
@@ -462,7 +466,7 @@ function ModelListEditor(props) {
462
466
  const source = sourceChip(row);
463
467
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { style: css.item, children: [
464
468
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { style: css.itemMain, children: [
465
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: css.itemId, children: row.id }),
469
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: css.itemId, title: row.id, children: row.displayName }),
466
470
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { style: css.chips, children: [
467
471
  chipsFor(row).map((chip) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: css.chip, children: chip.label }, chip.key)),
468
472
  source === void 0 ? null : /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: { ...css.chip, ...css.chipStale }, children: source.label }, source.key)
@@ -524,7 +528,7 @@ function ModelListEditor(props) {
524
528
  }
525
529
  ),
526
530
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("span", { style: css.candidateText, children: [
527
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: css.candidateId, title: candidate.id, children: candidate.id }),
531
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: css.candidateId, title: candidate.id, children: candidate.displayName }),
528
532
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: css.chips, children: chipsFor(candidate).map((chip) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("span", { style: css.chip, children: chip.label }, chip.key)) })
529
533
  ] })
530
534
  ] }) }, candidate.id)) })
@@ -592,7 +596,7 @@ function shouldRetryPending(snapshot2, attempts, limit = PENDING_RETRY_LIMIT) {
592
596
 
593
597
  // src/client/page.tsx
594
598
  var import_jsx_runtime3 = require("react/jsx-runtime");
595
- var PLUGIN_VERSION = "0.5.0";
599
+ var PLUGIN_VERSION = "0.6.0";
596
600
  var REPO_URL = "https://github.com/bitxeno/dsh-magpie-connect";
597
601
  var css2 = {
598
602
  section: { display: "flex", flexDirection: "column", gap: 16, maxWidth: 780, paddingBottom: 32 },
@@ -667,6 +671,7 @@ function MagpieSettings() {
667
671
  useLocaleRevision();
668
672
  const [baseUrl, setBaseUrl] = (0, import_react3.useState)("");
669
673
  const [apiKey, setApiKey] = (0, import_react3.useState)("");
674
+ const [hasApiKey, setHasApiKey] = (0, import_react3.useState)(false);
670
675
  const [enabled, setEnabled] = (0, import_react3.useState)(void 0);
671
676
  const [models, setModels] = (0, import_react3.useState)([]);
672
677
  const [busy, setBusy] = (0, import_react3.useState)("idle");
@@ -710,10 +715,8 @@ function MagpieSettings() {
710
715
  const settings = settingsValue;
711
716
  const listed = modelsValue.models ?? [];
712
717
  const snapshot2 = modelsValue.snapshot;
713
- if (!credentialsDirty.current) {
714
- setBaseUrl(settings.baseUrl ?? "");
715
- setApiKey(settings.apiKey ?? "");
716
- }
718
+ if (!credentialsDirty.current) setBaseUrl(settings.baseUrl ?? "");
719
+ setHasApiKey(settings.hasApiKey === true);
717
720
  setEnabled(settings.enabledModels);
718
721
  setModels(listed);
719
722
  setLoaded(true);
@@ -734,7 +737,7 @@ function MagpieSettings() {
734
737
  };
735
738
  }, []);
736
739
  const fetchCandidates = async () => {
737
- const result = await request("/api/magpie-discover", "POST", { baseUrl, apiKey });
740
+ const result = await request("/api/magpie-discover", "POST", { baseUrl, ...apiKey.trim() === "" ? {} : { apiKey } });
738
741
  return result.models ?? [];
739
742
  };
740
743
  const refreshModels = async () => {
@@ -755,11 +758,12 @@ function MagpieSettings() {
755
758
  try {
756
759
  const saved = await request("/api/magpie-settings", "POST", {
757
760
  baseUrl,
758
- apiKey,
761
+ ...apiKey.trim() === "" ? {} : { apiKey },
759
762
  ...enabled === void 0 ? {} : { enabledModels: enabled }
760
763
  });
761
764
  setBaseUrl(saved.baseUrl);
762
- setApiKey(saved.apiKey);
765
+ setHasApiKey(saved.hasApiKey);
766
+ setApiKey("");
763
767
  setEnabled(saved.enabledModels);
764
768
  await refreshModels();
765
769
  setNotice(text("saved"));
@@ -774,7 +778,7 @@ function MagpieSettings() {
774
778
  setError(void 0);
775
779
  setNotice(void 0);
776
780
  try {
777
- const result = await request("/api/magpie-test", "POST", { baseUrl, apiKey });
781
+ const result = await request("/api/magpie-test", "POST", { baseUrl, ...apiKey.trim() === "" ? {} : { apiKey } });
778
782
  setNotice(text("testOk", { count: result.count }));
779
783
  } catch (cause) {
780
784
  setError(cause instanceof Error ? cause.message : String(cause));
@@ -783,7 +787,7 @@ function MagpieSettings() {
783
787
  }
784
788
  };
785
789
  const working = busy !== "idle";
786
- const incomplete = baseUrl.trim() === "" || apiKey.trim() === "";
790
+ const incomplete = baseUrl.trim() === "" || !hasApiKey && apiKey.trim() === "";
787
791
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("section", { style: css2.section, children: [
788
792
  /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("header", { style: css2.header, children: [
789
793
  /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: css2.brand, children: [
@@ -821,7 +825,7 @@ function MagpieSettings() {
821
825
  ] }),
822
826
  /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)("div", { style: css2.field, children: [
823
827
  /* @__PURE__ */ (0, import_jsx_runtime3.jsx)("span", { style: css2.label, children: text("apiKey") }),
824
- /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_dsh_client_ui_primitives2.Input, { type: "password", value: apiKey, placeholder: text("apiKeyPlaceholder"), disabled: working, onChange: (event) => {
828
+ /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_dsh_client_ui_primitives2.Input, { type: "password", value: apiKey, placeholder: text(hasApiKey ? "apiKeySavedPlaceholder" : "apiKeyPlaceholder"), disabled: working, onChange: (event) => {
825
829
  credentialsDirty.current = true;
826
830
  setApiKey(event.currentTarget.value);
827
831
  } })
package/lib/index.js CHANGED
@@ -54,13 +54,34 @@ function requiresResponsesApiEntry(nativeEndpoints) {
54
54
  function modelApiForEntry(nativeEndpoints) {
55
55
  return requiresResponsesApiEntry(nativeEndpoints) ? "openai-responses" : "openai-completions";
56
56
  }
57
+ var LABEL_GROUP_SEPARATOR = "\xB7";
58
+ function capitalizeGroup(group) {
59
+ return group.length === 0 ? "" : group[0].toLocaleUpperCase() + group.slice(1);
60
+ }
61
+ function groupFromId(id) {
62
+ const prefix = id.split("/", 1)[0]?.trim() ?? "";
63
+ return capitalizeGroup(prefix);
64
+ }
65
+ function displayNameFor(raw) {
66
+ const id = typeof raw.id === "string" ? raw.id : "";
67
+ const name2 = typeof raw.display_name === "string" ? raw.display_name.trim() : "";
68
+ if (name2 === "") return id;
69
+ const label = typeof raw.magpie_label === "string" ? raw.magpie_label.trim() : "";
70
+ const at = label.lastIndexOf(LABEL_GROUP_SEPARATOR);
71
+ const parsedGroup = at >= 0 ? label.slice(at + 1).trim() : "";
72
+ const idGroup = groupFromId(id);
73
+ const routingPrefix = id.startsWith("auto/") || id.startsWith("group/");
74
+ const group = routingPrefix ? idGroup : parsedGroup || idGroup;
75
+ if (group === "") return id;
76
+ return `${group}/${name2}`;
77
+ }
57
78
  function decodeModel(raw) {
58
79
  if (!raw || typeof raw !== "object") return void 0;
59
80
  const record = raw;
60
81
  const id = record.id;
61
82
  if (typeof id !== "string" || id.length === 0) return void 0;
62
83
  const num = (value) => typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : void 0;
63
- const displayName = typeof record.display_name === "string" && record.display_name || typeof record.magpie_label === "string" && record.magpie_label || id;
84
+ const displayName = displayNameFor(record);
64
85
  const contextWindow = num(record.context_window) ?? num(record.context_length) ?? num(record.max_input_tokens);
65
86
  const maxTokens = num(record.max_output_tokens);
66
87
  const modalities = record.modalities;
@@ -83,7 +104,7 @@ function decodeMagpieModels(data) {
83
104
  }
84
105
  return result;
85
106
  }
86
- var staticMagpieModels = [
107
+ var staticMagpieModelSeeds = [
87
108
  { id: "group/auto-gpt-4-1", displayName: "GPT-4.1", contextWindow: 1047576, maxTokens: 32768, image: true, nativeEndpoints: [], reasoning: false },
88
109
  { id: "group/auto-gpt-6-luna", displayName: "GPT-6-Luna", contextWindow: 272e3, maxTokens: 128e3, image: true, nativeEndpoints: [], reasoning: true, efforts: ["low", "medium", "high", "xhigh", "max"] },
89
110
  { id: "vercel/xiaomi/mimo-v2.6-flash", displayName: "xiaomi/mimo-v2.6-flash", contextWindow: 1048576, maxTokens: 131072, image: true, nativeEndpoints: ["/v1/chat/completions"], reasoning: true },
@@ -107,6 +128,10 @@ var staticMagpieModels = [
107
128
  { id: "workbuddy-ai/hy4-preview-f", displayName: "hy4-preview-f", contextWindow: 1e6, maxTokens: 64e3, image: true, nativeEndpoints: ["/v1/chat/completions"], reasoning: true, efforts: ["high"] },
108
129
  { id: "workbuddy-ai/deepseek-v4.1-flash", displayName: "deepseek-v4.1-flash", contextWindow: 1e6, maxTokens: 128e3, image: true, nativeEndpoints: ["/v1/chat/completions"], reasoning: true, efforts: ["low", "high", "max"] }
109
130
  ];
131
+ var staticMagpieModels = staticMagpieModelSeeds.map((entry) => ({
132
+ ...entry,
133
+ displayName: displayNameFor({ id: entry.id, display_name: entry.displayName })
134
+ }));
110
135
  var FETCH_TIMEOUT_MS = 3e4;
111
136
  var ModelCatalog = class {
112
137
  #entries = /* @__PURE__ */ new Map();
@@ -478,8 +503,9 @@ async function fetchMagpieModels(baseUrl, fetchImpl, options = {}) {
478
503
  if (models.size === 0) throw new Error("models endpoint returned an empty list");
479
504
  return models;
480
505
  }
506
+ var MODELS_CACHE_VERSION = 3;
481
507
  async function saveModelsCache(path, entries, now) {
482
- const cache = { updatedAt: now, entries: [...entries.values()] };
508
+ const cache = { version: MODELS_CACHE_VERSION, updatedAt: now, entries: [...entries.values()] };
483
509
  const tmp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
484
510
  await mkdir(dirname(path), { recursive: true });
485
511
  try {
@@ -495,7 +521,11 @@ async function loadModelsCache(path) {
495
521
  if (Date.now() - raw.updatedAt > 7 * 24 * 60 * 60 * 1e3) {
496
522
  throw new Error("gateway cache too old");
497
523
  }
498
- return new Map(raw.entries.map((entry) => [entry.id, entry]));
524
+ const legacy = raw.version !== MODELS_CACHE_VERSION;
525
+ return new Map(raw.entries.map((entry) => {
526
+ const relabeled = legacy ? { ...entry, displayName: entry.id } : entry;
527
+ return [entry.id, relabeled];
528
+ }));
499
529
  }
500
530
  function defaultCachePath(dataDir) {
501
531
  return join(dataDir, "magpie-models.json");
@@ -1004,6 +1034,10 @@ var PROVIDER_ID = "dsh-magpie-connect";
1004
1034
  var DEFAULT_DISPLAY_NAME = "Magpie";
1005
1035
  var DEFAULT_CONTEXT_WINDOW = 262144;
1006
1036
  var DEFAULT_MAX_TOKENS = 32768;
1037
+ function requestDefaultMaxTokens(contextWindow, outputLimit) {
1038
+ const room = Math.max(1, Math.floor(contextWindow / 4), Math.floor(contextWindow / 2) - 65536);
1039
+ return Math.min(outputLimit, room);
1040
+ }
1007
1041
  var DEFAULT_API_KEY = "not-needed";
1008
1042
  var DEFAULT_MAX_RETRIES = 2;
1009
1043
  var DEFAULT_TIMEOUT_MS = 3e5;
@@ -1146,6 +1180,16 @@ var MagpieAdapter = class {
1146
1180
  imageRequestPricing(_provider, _model) {
1147
1181
  return void 0;
1148
1182
  }
1183
+ /**
1184
+ * Picker label: the catalog's `<group>/<display_name>` label
1185
+ * (e.g. "Codex/GPT-6-Luna"); the group comes from `magpie_label` or falls
1186
+ * back to the capitalized first id segment. The id itself stays the route id
1187
+ * (`codex/gpt-6-luna`) for requests and session history.
1188
+ */
1189
+ #labelFor(id) {
1190
+ const label = this.#catalog.getEntry?.(id)?.displayName;
1191
+ return typeof label === "string" && label.trim() !== "" ? label : id;
1192
+ }
1149
1193
  /** Advisory catalog for the DSH model picker (deduped; dsh-llm rejects duplicates). */
1150
1194
  listModels(provider) {
1151
1195
  const seen = /* @__PURE__ */ new Set();
@@ -1154,20 +1198,21 @@ var MagpieAdapter = class {
1154
1198
  if (seen.has(id)) continue;
1155
1199
  seen.add(id);
1156
1200
  const image = this.#catalog.supportsImage?.(id) ?? false;
1157
- models.push({ provider, id, name: id, inputModalities: image ? ["text", "image"] : ["text"] });
1201
+ models.push({ provider, id, name: this.#labelFor(id), inputModalities: image ? ["text", "image"] : ["text"] });
1158
1202
  }
1159
1203
  return models;
1160
1204
  }
1161
1205
  resolveModel(provider, model) {
1162
1206
  const image = this.#catalog.supportsImage?.(model) ?? this.#catalog.requiresResponsesApi?.(model) ?? false;
1163
1207
  const ladder = this.#catalog.reasoningFor?.(model);
1208
+ const contextWindow = this.#catalog.contextWindowFor?.(model) ?? DEFAULT_CONTEXT_WINDOW;
1164
1209
  return {
1165
1210
  provider,
1166
1211
  id: model,
1167
- name: model,
1212
+ name: this.#labelFor(model),
1168
1213
  inputModalities: image ? ["text", "image"] : ["text"],
1169
- context: { contextWindow: this.#catalog.contextWindowFor?.(model) ?? DEFAULT_CONTEXT_WINDOW },
1170
- defaultMaxTokens: this.#catalog.maxTokensFor?.(model) ?? DEFAULT_MAX_TOKENS,
1214
+ context: { contextWindow },
1215
+ defaultMaxTokens: requestDefaultMaxTokens(contextWindow, this.#catalog.maxTokensFor?.(model) ?? DEFAULT_MAX_TOKENS),
1171
1216
  ...ladder !== void 0 ? { reasoning: ladder } : {}
1172
1217
  };
1173
1218
  }
@@ -1245,7 +1290,7 @@ var MagpieAdapter = class {
1245
1290
  maxRetries: this.#maxRetries,
1246
1291
  timeoutMs: this.#timeoutMs,
1247
1292
  temperature: options.temperature,
1248
- maxTokens: options.maxTokens ?? model.maxTokens,
1293
+ maxTokens: options.maxTokens ?? requestDefaultMaxTokens(model.contextWindow, model.maxTokens),
1249
1294
  ...reasoningEffort !== void 0 ? { reasoningEffort } : {}
1250
1295
  });
1251
1296
  }
@@ -1287,7 +1332,7 @@ function resolveConfig(config = {}) {
1287
1332
 
1288
1333
  // src/settings.ts
1289
1334
  import { randomBytes as randomBytes2 } from "node:crypto";
1290
- import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2, rename as rename2, rm as rm2 } from "node:fs/promises";
1335
+ import { chmod, readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2, rename as rename2, rm as rm2 } from "node:fs/promises";
1291
1336
  import { dirname as dirname2, join as join3 } from "node:path";
1292
1337
  var SETTINGS_FILE = "settings.json";
1293
1338
  function defaultSettingsPath(dataDir) {
@@ -1387,9 +1432,29 @@ var SettingsStore = class {
1387
1432
  /** Serializes writes: one persist in flight, so two generations cannot interleave. */
1388
1433
  #writeChain = Promise.resolve();
1389
1434
  #listeners = /* @__PURE__ */ new Set();
1435
+ /**
1436
+ * Whether the state directory is the plugin's own (`$DSH_HOME/storages/…`),
1437
+ * in which case its permissions are tightened to `0700`. An explicit
1438
+ * `dataDir` belongs to the user, so it is never chmod-ed behind their back.
1439
+ * The settings file itself is repaired to `0600` either way: it holds a
1440
+ * credential.
1441
+ */
1442
+ #privateDir;
1390
1443
  constructor(options = {}) {
1391
1444
  this.#path = options.path;
1392
1445
  this.#legacyPath = options.legacyPath;
1446
+ this.#privateDir = options.privateDir ?? false;
1447
+ }
1448
+ /**
1449
+ * Tighten permissions on a file this store owns, best-effort.
1450
+ *
1451
+ * Never throws: the file may live on a read-only mount, a non-POSIX
1452
+ * filesystem, or a platform where `chmod` is a no-op. A permission repair
1453
+ * must never make otherwise-readable settings unreadable.
1454
+ */
1455
+ async #chmodQuietly(path, mode) {
1456
+ await chmod(path, mode).catch(() => {
1457
+ });
1393
1458
  }
1394
1459
  /**
1395
1460
  * Read one settings file, distinguishing "absent" from "unreadable".
@@ -1411,6 +1476,8 @@ var SettingsStore = class {
1411
1476
  if (error.code === "ENOENT") return { exists: false };
1412
1477
  return { exists: true, error };
1413
1478
  }
1479
+ await this.#chmodQuietly(path, 384);
1480
+ if (this.#privateDir) await this.#chmodQuietly(dirname2(path), 448);
1414
1481
  try {
1415
1482
  return { exists: true, raw: JSON.parse(text) };
1416
1483
  } catch (error) {
@@ -1552,7 +1619,9 @@ var SettingsStore = class {
1552
1619
  async #writeNow() {
1553
1620
  const target = this.#path;
1554
1621
  if (!target) return;
1555
- await mkdir2(dirname2(target), { recursive: true });
1622
+ const dir = dirname2(target);
1623
+ await mkdir2(dir, { recursive: true, ...this.#privateDir ? { mode: 448 } : {} });
1624
+ if (this.#privateDir) await this.#chmodQuietly(dir, 448);
1556
1625
  const tmp = `${target}.${process.pid}.${randomBytes2(6).toString("hex")}.tmp`;
1557
1626
  try {
1558
1627
  await writeFile2(tmp, JSON.stringify(this.#settings, null, 2), { encoding: "utf8", mode: 384, flag: "wx" });
@@ -1591,6 +1660,9 @@ function responsesOnlyFor(nativeEndpoints) {
1591
1660
  const hasCompletions = nativeEndpoints.some((endpoint) => endpoint.includes("/chat/completions"));
1592
1661
  return !hasCompletions && nativeEndpoints.some((endpoint) => endpoint.includes("/responses"));
1593
1662
  }
1663
+ function compareModelRows(left, right) {
1664
+ return left.displayName.localeCompare(right.displayName, "zh") || left.id.localeCompare(right.id);
1665
+ }
1594
1666
  function toRow(id, entry) {
1595
1667
  return {
1596
1668
  id,
@@ -1630,29 +1702,40 @@ function buildModelRows(backend) {
1630
1702
  const { store, catalog } = backend;
1631
1703
  const allowlist = store.get().enabledModels;
1632
1704
  const allowed = allowlist === void 0 ? void 0 : new Set(allowlist);
1633
- return catalog.directory().sort().map((id) => ({
1705
+ return catalog.directory().map((id) => ({
1634
1706
  ...toRow(id, catalog.getEntry(id)),
1635
1707
  enabled: allowed === void 0 || allowed.has(id),
1636
1708
  source: catalog.sourceFor(id)
1637
- }));
1709
+ })).sort(compareModelRows);
1638
1710
  }
1639
1711
  function backendOrThrow() {
1640
1712
  if (!currentBackend) throw new Error("dsh-magpie-connect: settings backend not ready");
1641
1713
  return currentBackend;
1642
1714
  }
1715
+ function settingsView(backend) {
1716
+ const page = backend.store.get();
1717
+ const endpoint = resolveEffectiveEndpoint(backend.patchEndpoint, page);
1718
+ return {
1719
+ baseUrl: endpoint.baseUrl,
1720
+ hasApiKey: endpoint.apiKey !== "",
1721
+ enabledModels: page.enabledModels,
1722
+ inheritedModels: page.enabledModels === void 0
1723
+ };
1724
+ }
1725
+ function stripBlankApiKey(backend, body) {
1726
+ if (!body || typeof body !== "object") return body;
1727
+ const record = body;
1728
+ if (typeof record.apiKey !== "string" || record.apiKey.trim() !== "") return body;
1729
+ if (resolveEffectiveEndpoint(backend.patchEndpoint, backend.store.get()).apiKey === "") {
1730
+ throw new Error("dsh-magpie-connect: apiKey is required and must not be empty");
1731
+ }
1732
+ const rest = { ...record };
1733
+ delete rest.apiKey;
1734
+ return rest;
1735
+ }
1643
1736
  async function handleSettingsGet() {
1644
1737
  try {
1645
- const backend = backendOrThrow();
1646
- const page = backend.store.get();
1647
- const endpoint = resolveEffectiveEndpoint(backend.patchEndpoint, page);
1648
- return routeOk({
1649
- baseUrl: endpoint.baseUrl,
1650
- apiKey: endpoint.apiKey,
1651
- enabledModels: page.enabledModels,
1652
- inheritedModels: page.enabledModels === void 0,
1653
- fromPage: page,
1654
- fromPatch: backend.patchEndpoint
1655
- });
1738
+ return routeOk(settingsView(backendOrThrow()));
1656
1739
  } catch (error) {
1657
1740
  return routeFail(error);
1658
1741
  }
@@ -1661,8 +1744,8 @@ async function handleSettingsPost(request) {
1661
1744
  try {
1662
1745
  const backend = backendOrThrow();
1663
1746
  const body = await readRouteBody(request);
1664
- const normalized = normalizePageSettings(body);
1665
- const saved = await backend.store.save(normalized);
1747
+ const normalized = normalizePageSettings(stripBlankApiKey(backend, body));
1748
+ await backend.store.save(normalized);
1666
1749
  backend.applyPageSettings();
1667
1750
  if (normalized.baseUrl !== void 0 || normalized.apiKey !== void 0) {
1668
1751
  await Promise.race([
@@ -1670,13 +1753,7 @@ async function handleSettingsPost(request) {
1670
1753
  new Promise((resolve2) => setTimeout(resolve2, SAVE_REFRESH_WAIT_MS))
1671
1754
  ]);
1672
1755
  }
1673
- const endpoint = resolveEffectiveEndpoint(backend.patchEndpoint, saved);
1674
- return routeOk({
1675
- baseUrl: endpoint.baseUrl,
1676
- apiKey: endpoint.apiKey,
1677
- enabledModels: saved.enabledModels,
1678
- inheritedModels: saved.enabledModels === void 0
1679
- });
1756
+ return routeOk(settingsView(backend));
1680
1757
  } catch (error) {
1681
1758
  return routeFail(error);
1682
1759
  }
@@ -1692,8 +1769,8 @@ async function handleModelsGet() {
1692
1769
  function probeTarget(backend, body) {
1693
1770
  const effective = backend.effective();
1694
1771
  const origin = normalizeBaseUrl(body.baseUrl ?? effective.baseUrl);
1695
- const rawKey = typeof body.apiKey === "string" ? body.apiKey : effective.apiKey;
1696
- const key = rawKey.trim();
1772
+ const typed = typeof body.apiKey === "string" ? body.apiKey.trim() : "";
1773
+ const key = typed === "" ? effective.apiKey.trim() : typed;
1697
1774
  if (key === "") throw new Error("dsh-magpie-connect: apiKey is required \u2014 fill it in before asking the gateway");
1698
1775
  return { origin, key };
1699
1776
  }
@@ -1720,7 +1797,7 @@ async function handleDiscoverPost(request) {
1720
1797
  const { origin, key } = probeTarget(backend, body);
1721
1798
  const models = await fetchMagpieModels(origin, fetch, { headers: { authorization: `Bearer ${key}` } });
1722
1799
  backend.catalog.adoptDirectory(models);
1723
- const candidates = [...models.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([id, entry]) => toRow(id, entry));
1800
+ const candidates = [...models.entries()].map(([id, entry]) => toRow(id, entry)).sort(compareModelRows);
1724
1801
  return routeOk({ count: candidates.length, models: candidates });
1725
1802
  } catch (error) {
1726
1803
  return hintGatewayFailure(error);
@@ -1834,7 +1911,10 @@ function apply(ctx, config = {}) {
1834
1911
  };
1835
1912
  const store = new SettingsStore({
1836
1913
  path: defaultSettingsPath(dataDir),
1837
- legacyPath: config.dataDir === void 0 ? join4(legacyDataDir(), "settings.json") : void 0
1914
+ legacyPath: config.dataDir === void 0 ? join4(legacyDataDir(), "settings.json") : void 0,
1915
+ // Only the plugin-owned default directory is chmod-ed; an explicit
1916
+ // `dataDir` belongs to the user and is left as they set it.
1917
+ privateDir: config.dataDir === void 0
1838
1918
  });
1839
1919
  const patchEndpoint = { baseUrl: cfg.baseUrl, apiKey: cfg.apiKey };
1840
1920
  const effective = () => resolveEffectiveEndpoint(patchEndpoint, store.get());