mslxdff 0.1.65 → 0.1.66

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.
Files changed (42) hide show
  1. package/bin/mslxdff.js +3 -3159
  2. package/package.json +1 -1
  3. package/src/cli/bootstrap.js +408 -0
  4. package/src/cli/commands/daemon.js +151 -0
  5. package/src/cli/commands/group.js +272 -0
  6. package/src/cli/commands/model.js +405 -0
  7. package/src/cli/commands/provider/add.js +106 -0
  8. package/src/cli/commands/provider/allowlist.js +99 -0
  9. package/src/cli/commands/provider/config.js +82 -0
  10. package/src/cli/commands/provider/index.js +193 -0
  11. package/src/cli/commands/provider/keys.js +135 -0
  12. package/src/cli/commands/provider/models.js +99 -0
  13. package/src/cli/commands/provider.js +1 -0
  14. package/src/cli/commands/sync.js +143 -0
  15. package/src/cli/commands/system.js +236 -0
  16. package/src/cli/commands/workbuddy.js +91 -0
  17. package/src/cli/format.js +119 -0
  18. package/src/cli/group-helpers.js +69 -0
  19. package/src/cli/help.js +66 -0
  20. package/src/cli/index.js +59 -0
  21. package/src/cli/interactive.js +84 -0
  22. package/src/cli/policy.js +119 -0
  23. package/src/cli/status.js +332 -0
  24. package/src/cli/util.js +24 -0
  25. package/src/providers/base.js +159 -0
  26. package/src/providers/generic.js +26 -166
  27. package/src/providers/openrouter.js +32 -162
  28. package/src/providers/workbuddy.js +7 -32
  29. package/src/routes/chat/gateway.js +301 -0
  30. package/src/routes/chat/index.js +1 -384
  31. package/src/state/facade.js +57 -0
  32. package/src/state/memory.js +180 -0
  33. package/src/state/persist.js +42 -0
  34. package/src/state/schemas/allowlist.js +87 -0
  35. package/src/state/schemas/group.js +31 -0
  36. package/src/state/schemas/model.js +53 -0
  37. package/src/state/schemas/peer.js +31 -0
  38. package/src/state/schemas/port.js +10 -0
  39. package/src/state/schemas/provider.js +254 -0
  40. package/src/state/schemas/token.js +43 -0
  41. package/src/state/store.js +202 -0
  42. package/src/state.js +1 -711
@@ -0,0 +1,332 @@
1
+ import { readFileSync, existsSync, statSync } from "node:fs";
2
+ import { join, dirname } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { readPid, readPidVersion, isPidAlive, pidFile } from "../daemon.js";
5
+ import { defaultStateFile, getPort, loadGroupsJoined, loadModelErrors, loadModelStats, loadModelPicks } from "../state.js";
6
+ import { resolvePort } from "../server.js";
7
+ import { loadProviderKeys, loadProviderAuths, loadProviderConfigs, loadProviderAllowedModels, loadProviderShareKeys, loadProviderBaseUrl } from "../state.js";
8
+ import { loadToken } from "../state.js";
9
+ import { logDir } from "../logs.js";
10
+ import { createGroupsService } from "../groups.js";
11
+ import { createPeersService } from "../peers.js";
12
+ import { refreshGroupMembers } from "../groups.js";
13
+ import { fmtShanghaiYMDHM } from "../time.js";
14
+ import { fmtStatus, fmtUptime, fmtTs } from "./format.js";
15
+ import { compareSemver } from "./policy.js";
16
+
17
+ export async function printStatus(VERSION) {
18
+ const daemon = readPid();
19
+ const alive = daemon ? isPidAlive(daemon) : false;
20
+ const port = getPort() || resolvePort();
21
+ const persisted = getPort();
22
+ const portSrc = persisted != null ? "persisted" : (process.env.MSLXDFF_PORT ? "env MSLXDFF_PORT" : "default 8989");
23
+ const stateFile = defaultStateFile();
24
+ const dir = logDir();
25
+ let upStr = "";
26
+ if (daemon && alive) {
27
+ try {
28
+ const st = statSync(pidFile());
29
+ const ms = Date.now() - st.mtimeMs;
30
+ upStr = `, up ${fmtUptime(ms)}`;
31
+ } catch {}
32
+ }
33
+ const verNote = daemon && alive ? (() => { const v = readPidVersion(); if (!v) return ""; if (v === VERSION) return "version ok"; const cmp = compareSemver(VERSION, v); if (cmp > 0) return `version ${v} → ${VERSION} (upgrade pending)`; if (cmp < 0) return `version ${v} (newer than local ${VERSION}, keeping)`; return "version ok"; })() : "";
34
+ console.log(`mslxdff v${VERSION}`);
35
+ console.log(`daemon: ${daemon ? (alive ? `running (pid ${daemon}${upStr})` : `stale pid ${daemon} (not alive)`) : "not running"}${verNote ? ` [${verNote}]` : ""}`);
36
+ let healthLine = "";
37
+ try {
38
+ const t0 = Date.now();
39
+ const r = await fetch(`http://127.0.0.1:${port}/health`, { signal: AbortSignal.timeout(1200) });
40
+ const ms = Date.now() - t0;
41
+ healthLine = r.ok ? `health ok ${ms}ms` : `health HTTP ${r.status} ${ms}ms`;
42
+ } catch (e) {
43
+ healthLine = daemon && alive ? `health fail (${String(e?.message || e).slice(0, 60)})` : "health — (daemon not running)";
44
+ }
45
+ console.log(`endpoint: http://localhost:${port}/v1 · ${healthLine}`);
46
+ console.log(`config: port ${port} (${portSrc}) · state ${stateFile} · log ${dir}`);
47
+ try {
48
+ const host = process.env.MSLXDFF_HOST || process.env.MSLXDFF_BIND_HOST || "0.0.0.0";
49
+ if (host !== "0.0.0.0") console.log(`bind: ${host}`);
50
+ } catch {}
51
+
52
+ try {
53
+ const configs = loadProviderConfigs();
54
+ const upstreamBase = process.env.UPSTREAM_BASE_URL || "https://opencode.ai";
55
+ const providerRows = [];
56
+ const opAllowed = loadProviderAllowedModels("opencode");
57
+ providerRows.push({ id: "opencode", enabled: true, baseUrl: upstreamBase, keys: [], allowed: opAllowed, share: false, note: "built-in, no key, cannot share" });
58
+ const genericIds = new Set(Object.keys(configs).filter((id) => id !== "opencode"));
59
+ try {
60
+ const raw = JSON.parse(readFileSync(stateFile, "utf8"));
61
+ const pk = raw.providerKeys || {};
62
+ for (const id of Object.keys(pk)) if (id !== "opencode") genericIds.add(id);
63
+ const cfgRaw = raw.providerConfigs || {};
64
+ for (const id of Object.keys(cfgRaw)) if (id !== "opencode") genericIds.add(id);
65
+ } catch {}
66
+ for (const k of Object.keys(process.env)) {
67
+ const m = k.match(/^MSLXDFF_(.+)_KEY$/);
68
+ if (m) {
69
+ const id = m[1].toLowerCase().replace(/__/g, "-");
70
+ if (id !== "opencode") genericIds.add(id);
71
+ }
72
+ }
73
+ for (const gid of [...genericIds].sort()) {
74
+ const cfg = configs[gid];
75
+ const keys = loadProviderKeys(gid);
76
+ const baseUrl = loadProviderBaseUrl(gid) || cfg?.baseUrl || (gid === "openrouter" ? "https://openrouter.ai/api/v1" : gid === "workbuddy" ? "https://copilot.tencent.com" : "");
77
+ const share = loadProviderShareKeys(gid);
78
+ const allowed = loadProviderAllowedModels(gid);
79
+ let enabled = Boolean(baseUrl && keys.length) || (gid === "openrouter" && keys.length > 0);
80
+ const auths = gid === "workbuddy" ? (loadProviderAuths(gid) || []) : [];
81
+ let note = "";
82
+ const isWorkbuddyStub = gid === "workbuddy" && (keys.includes("k-new") || baseUrl.includes("127.0.0.1") || (keys.length === 1 && keys[0].length < 20));
83
+ if (isWorkbuddyStub) {
84
+ enabled = false;
85
+ note = "测试桩 (key=k-new, baseUrl=127.0.0.1) — 请重跑 node workbuddy-token-auto.js 写入真实 JWT";
86
+ } else if (!enabled) {
87
+ if (!baseUrl && !keys.length) note = "no baseUrl, no keys";
88
+ else if (!baseUrl) note = "missing baseUrl";
89
+ else if (!keys.length) note = "no keys";
90
+ } else if (gid === "workbuddy" && auths.length && auths.length !== keys.length) {
91
+ note = `${auths.length} auth(s) / ${keys.length} key(s) — 数量不一致请重跑 workbuddy-token-auto.js`;
92
+ }
93
+ providerRows.push({ id: gid, enabled, baseUrl: baseUrl || "(none)", keys, allowed, share, note, authCount: auths.length });
94
+ }
95
+ const enabledCount = providerRows.filter((r) => r.enabled).length;
96
+ console.log(`\nupstream providers (${providerRows.length}, ${enabledCount} enabled) — mslxdff -providers list 查看详情`);
97
+ for (const p of providerRows) {
98
+ const dot = p.enabled ? "●" : "○";
99
+ const state = p.enabled ? "enabled " : "disabled";
100
+ let keysInfo;
101
+ if (p.id === "opencode") keysInfo = "无需 key (内置)";
102
+ else keysInfo = p.keys.length ? `${p.keys.length} key${p.keys.length > 1 ? "s" : ""} ${p.keys.map((k) => `${k.slice(0, 3)}…${k.slice(-3)}`).join(", ")}` : "0 keys";
103
+ const authInfo = p.authCount ? ` ${p.authCount} acc` : "";
104
+ const allowInfo = p.allowed.length ? `allow=${p.allowed.length}(${p.allowed.slice(0, 2).join(",")}${p.allowed.length > 2 ? "…" : ""})` : "allow=all";
105
+ const shareInfo = p.id === "opencode" ? "cannot share" : `share=${p.share ? "ON" : "off"}`;
106
+ const note = p.note ? ` (${p.note})` : "";
107
+ console.log(` ${dot} ${p.id.padEnd(12)} ${state} ${keysInfo}${authInfo} ${allowInfo.padEnd(18)} baseUrl=${p.baseUrl} ${shareInfo}${note}`);
108
+ }
109
+ if (enabledCount === 1 && providerRows.length === 1) {
110
+ console.log(` (仅 opencode 内置免费通道;按需加:mslxdff -provider add bai https://api.b.ai/v1 <key> 或 node workbuddy-token-auto.js)`);
111
+ }
112
+ } catch (e) {
113
+ console.log(`\nupstream providers: (unavailable — ${String(e?.message || e).slice(0, 80)})`);
114
+ }
115
+
116
+ try {
117
+ const statuses = loadModelErrors();
118
+ const stats = loadModelStats();
119
+ const picks = loadModelPicks();
120
+ const { getPreferredModel: gpm } = await import("../auto.js");
121
+ const preferred = gpm();
122
+ const modelsFile = join(dir, "models.json");
123
+ let freeIds = [];
124
+ let cachedAt = null;
125
+ let cacheErr = null;
126
+ if (existsSync(modelsFile)) {
127
+ try {
128
+ const cached = JSON.parse(readFileSync(modelsFile, "utf8"));
129
+ freeIds = (cached.data || []).map((m) => m.id).filter(Boolean);
130
+ cachedAt = cached.cachedAt || null;
131
+ } catch (err) { cacheErr = String(err?.message || err).slice(0, 60); }
132
+ }
133
+ const ageStr = cachedAt ? (() => { const ms = Date.now() - cachedAt; const h = Math.floor(ms / 3600000); const m = Math.floor((ms % 3600000) / 60000); return h ? `${h}h${m}m ago` : `${m}m ago`; })() : "";
134
+ const cacheLine = freeIds.length ? `${freeIds.length} free${cachedAt ? ` (cached ${fmtShanghaiYMDHM(cachedAt)} · ${ageStr})` : ""}` : (cacheErr ? `cache unreadable (${cacheErr})` : "not cached yet (daemon 拉取后出现)");
135
+ const prefStat = preferred ? (stats[preferred] || stats[`opencode/${preferred}`] || null) : null;
136
+ const prefErr = preferred ? statuses[preferred] : null;
137
+ const prefStatus = prefErr ? (typeof prefErr === "number" ? "error" : (prefErr?.status || "error")) : (prefStat ? "normal" : "");
138
+ const prefLine = preferred ? `${preferred}${prefStatus ? ` [${prefStatus}]` : ""}` : "(none)";
139
+ const picksLine = picks.length ? `${picks.length} (*${picks.slice(0, 4).join(", *")}${picks.length > 4 ? ` …+${picks.length - 4}` : ""})` : "(空=全量 auto)";
140
+ console.log(`\nmodels: ${cacheLine} — mslxdff -model status 查看详情`);
141
+ const prefTtfbDisp = prefStat ? (() => { const v = prefStat.avgTtfbMs ?? prefStat.emaTtfbMs; return v != null && v >= 10 ? `首字 ${v}ms` : (v != null && v < 10 ? "首字 — (测试数据)" : ""); })() : "";
142
+ const prefTotDisp = prefStat?.avgTotalMs && prefStat.avgTotalMs >= 10 ? `总 ${prefStat.avgTotalMs}ms` : "";
143
+ const prefTpsDisp = prefStat?.avgTps && prefStat.avgTps >= 1 ? `${prefStat.avgTps} tok/s` : "";
144
+ const prefExtra = prefStat ? ` ${[prefTtfbDisp, prefTotDisp, prefTpsDisp].filter(Boolean).join(" ")} ${prefStat.count || 0}次` : "";
145
+ console.log(` preferred: ${prefLine}${prefExtra}`);
146
+ console.log(` picks: ${picksLine} ${picks.length ? "auto 仅在勾选内" : "auto 用全量免费池"}`);
147
+ if (freeIds.length) {
148
+ const ids = freeIds;
149
+ console.log(` free list:`);
150
+ for (const id of ids) {
151
+ const st = fmtStatus(id, statuses);
152
+ const full = id.includes("/") ? id : `opencode/${id}`;
153
+ const ms = stats[full] || stats[id];
154
+ let extra = "";
155
+ if (ms) {
156
+ const v = ms.avgTtfbMs ?? ms.emaTtfbMs;
157
+ const vStr = v != null ? (v >= 10 ? `avg首字 ${v}ms` : (v < 10 ? "avg首字 —" : "")) : "";
158
+ const tpsStr = ms.avgTps && ms.avgTps >= 1 ? ` ${ms.avgTps} tok/s` : "";
159
+ const cntStr = ms.count ? ` ${ms.count}次` : "";
160
+ extra = ` ${vStr}${tpsStr}${cntStr}`;
161
+ }
162
+ console.log(` ${id}${st ? ` [${st}]` : ""}${extra}`);
163
+ }
164
+ }
165
+ const allStatIds = Object.keys(stats);
166
+ if (allStatIds.length) {
167
+ const sorted = allStatIds.map((full) => ({ full, s: stats[full] })).filter((x) => x.s && x.s.count).sort((a, b) => (b.s.count - a.s.count) || ((b.s.avgTps || 0) - (a.s.avgTps || 0))).slice(0, 7);
168
+ if (sorted.length) {
169
+ console.log(` 模型体检 Top${sorted.length}(样本>0, 按次数):`);
170
+ console.log(` ${"模型".padEnd(28)} ${"首字".padEnd(7)} ${"总耗时".padEnd(7)} ${"速度".padEnd(10)} ${"啰嗦".padEnd(7)} ${"样本".padEnd(5)} 状态`);
171
+ for (const { full, s } of sorted) {
172
+ const ttfb = s.avgTtfbMs ?? s.emaTtfbMs;
173
+ const total = s.avgTotalMs ?? s.emaTotalMs;
174
+ const tps = s.avgTps ?? s.emaTps;
175
+ const verbose = s.avgCompTok != null ? `${s.avgCompTok}tok` : "—";
176
+ const st = statuses[full] || statuses[full.split("/").slice(1).join("/")] || null;
177
+ const statusStr = st ? (typeof st === "number" ? "error" : (st.status || "normal")) : "normal";
178
+ const p95 = s.p95Ttfb && s.p95Ttfb >= 10 ? ` p95:${s.p95Ttfb}ms` : "";
179
+ const ttfbStr = ttfb != null ? (ttfb >= 10 ? ttfb + "ms" : "—") : "—";
180
+ const totalStr = total != null ? (total >= 10 ? total + "ms" : "—") : "—";
181
+ const tpsStr = tps != null && tps >= 1 ? tps + " tok/s" : "—";
182
+ console.log(` ${full.padEnd(28)} ${ttfbStr.padEnd(7)} ${totalStr.padEnd(7)} ${tpsStr.padEnd(10)} ${verbose.padEnd(7)} ${String(s.count).padEnd(5)} ${statusStr}${p95}`);
183
+ }
184
+ }
185
+ } else if (!freeIds.length) {
186
+ console.log(` (暂无模型样本 — 发一次 mslxdff -chat 后出现,100次后均值更稳)`);
187
+ }
188
+ } catch (e) {
189
+ console.log(`\nmodels: (unavailable — ${String(e?.message || e).slice(0, 80)})`);
190
+ }
191
+
192
+ try {
193
+ const { getAutostartStatus } = await import("../autostart.js");
194
+ const a = await getAutostartStatus();
195
+ const detail = a.detail || (a.enabled ? "已启用" : "未启用");
196
+ const label = detail.startsWith("已启用") || detail.startsWith("未启用") ? detail : `${a.enabled ? "已启用" : "未启用"} · ${detail}`;
197
+ console.log(`\nautostart: ${label} — mslxdff -autostart status`);
198
+ if (a.taskToRun) console.log(` task: ${a.taskToRun.slice(0, 120)}`);
199
+ if (a.unit) console.log(` unit: ${a.unit}`);
200
+ } catch {}
201
+ try {
202
+ const { resolvePluginDirs, loadPlugins } = await import("../plugins.js");
203
+ const pkgRoot2 = dirname(fileURLToPath(import.meta.url)) + "/../..";
204
+ const dirs = resolvePluginDirs({ pkgRoot: pkgRoot2 });
205
+ const { plugins, errors } = await loadPlugins({ dirs });
206
+ if (plugins.length || errors.length) {
207
+ console.log(`plugins: ${plugins.length} loaded${errors.length ? `, ${errors.length} error(s)` : ""} — mslxdff -plugins`);
208
+ for (const p of plugins) console.log(` ${p.name}${p.version ? `@${p.version}` : ""} [${Object.keys(p.hooks || {}).join(", ") || "no hooks"}]`);
209
+ for (const e of errors) console.log(` ! ${e.file} — ${e.error}`);
210
+ } else {
211
+ console.log(`plugins: (none) — 放 *.mjs 到 ${dirs[dirs.length - 1] || "~/.config/mslxdff/plugins"} 启用`);
212
+ }
213
+ } catch {}
214
+
215
+ const groups = createGroupsService({});
216
+ const joined = loadGroupsJoined();
217
+ if (joined.length) {
218
+ console.log(`\njoined groups (${joined.length}):`);
219
+ const { token } = await loadToken();
220
+ for (const g of joined) {
221
+ const isLeader = !g.leaderUrl;
222
+ console.log(` ${g.name} ${isLeader ? "(this node is the leader)" : `leader ${g.leaderUrl}`}`);
223
+ let members = null;
224
+ if (isLeader) {
225
+ members = groups.list()[g.name]?.members ?? {};
226
+ } else {
227
+ const fetchImpl = (url, opts) => fetch(url, { ...opts, signal: AbortSignal.timeout(1500) });
228
+ try {
229
+ members = await refreshGroupMembers(g.name, {
230
+ leaderUrl: g.leaderUrl,
231
+ memberName: g.memberName,
232
+ url: g.myUrl,
233
+ token,
234
+ fetchImpl,
235
+ });
236
+ } catch {
237
+ members = null;
238
+ }
239
+ }
240
+ if (members === null) {
241
+ console.log(" members: (unavailable — leader unreachable)");
242
+ } else {
243
+ const ids = Object.keys(members);
244
+ if (!ids.length) {
245
+ console.log(" members: (none yet)");
246
+ } else {
247
+ console.log(` members (${ids.length}):`);
248
+ for (const id of ids) {
249
+ const m = members[id];
250
+ const tags = [];
251
+ if (id === "leader" && isLeader) tags.push("leader");
252
+ if (m?.url && m.url === g.myUrl) tags.push("this node");
253
+ if (m?.kind === "broadband") tags.push("broadband");
254
+ if (m?.kind === "broadband" && m?.publicIp) tags.push(`ip=${m.publicIp}`);
255
+ if (m?.kind === "broadband" && m?.lastSeen) {
256
+ const ago = Math.round((Date.now() - m.lastSeen) / 1000);
257
+ tags.push(ago < 90 ? `via leader ${ago}s ago` : "stale");
258
+ }
259
+ const tag = tags.length ? ` [${tags.join(", ")}]` : "";
260
+ console.log(` ${m?.url || id}${tag}`);
261
+ }
262
+ }
263
+ }
264
+ }
265
+ } else {
266
+ console.log("\njoined groups: (none — use -creategroup or -addtogroup)");
267
+ }
268
+
269
+ const peers = createPeersService({});
270
+ const allPeers = peers.all();
271
+ if (allPeers.length) {
272
+ console.log(`\nfailover targets (${allPeers.length}):`);
273
+ for (const p of allPeers) {
274
+ const tags = [];
275
+ if (peers.isCooling(p.url)) tags.push("cooling");
276
+ if (peers.isHot(p.url)) tags.push("hot");
277
+ const s = peers.stat(p.url);
278
+ if (s?.latencyMs != null) tags.push(`${s.latencyMs}ms`);
279
+ if (s?.fails) tags.push(`${s.fails} fail(s)`);
280
+ const tag = tags.length ? ` [${tags.join(", ")}]` : "";
281
+ console.log(` ${p.name || p.url} ${p.url}${tag}`);
282
+ }
283
+ } else {
284
+ console.log(`\nfailover: (none — 加组后自动出现,mslxdff -group list)`);
285
+ }
286
+
287
+ const groupNames = Object.keys(groups.list());
288
+ if (groupNames.length) {
289
+ console.log(`\ngroups on this node (${groupNames.length}):`);
290
+ for (const n of groupNames) console.log(` ${n}`);
291
+ }
292
+
293
+ const { recentCalls, lastError } = await import("../logs.js");
294
+ console.log("\nrecent calls: (gateway 持久化,最近5条,含首字/tok/s)");
295
+ const calls = recentCalls(5);
296
+ if (calls.length) {
297
+ let sumDur = 0, sumTps = 0, tpsN = 0;
298
+ for (const c of calls) {
299
+ if (Number.isFinite(c.durationMs)) sumDur += c.durationMs;
300
+ else if (Number.isFinite(c.totalMs)) sumDur += c.totalMs;
301
+ if (Number.isFinite(c.tps)) { sumTps += c.tps; tpsN++; } else if (Number.isFinite(c.charsPerSec)) { sumTps += c.charsPerSec; tpsN++; }
302
+ }
303
+ const avgDur = calls.length ? Math.round(sumDur / calls.length) : null;
304
+ const avgTps = tpsN ? Math.round(sumTps / tpsN) : null;
305
+ console.log(` avg ${avgDur ? avgDur + "ms" : "—"}${avgTps ? ` · ${avgTps} tok/s` : ""} — mslxdff -log 20 查看详情`);
306
+ for (const c of calls) {
307
+ const dur = c.totalMs ?? c.durationMs;
308
+ const ttfb = c.ttfbMs != null ? ` 首字${c.ttfbMs}ms` : "";
309
+ const tps = c.tps != null ? ` ${c.tps}tok/s` : (c.charsPerSec ? ` ${c.charsPerSec}ch/s` : "");
310
+ const tok = c.usage?.completion_tokens != null ? ` tok${c.usage.completion_tokens}` : (c.chars ? ` ch${c.chars}` : "");
311
+ const tm = fmtTs(c.ts);
312
+ console.log(` ${tm} ${(c.model || "-").padEnd(28)} ${String(c.status || "-").padEnd(4)} ${dur ? dur + "ms" : ""}${ttfb}${tps}${tok}${c.auto ? " auto" : ""}`);
313
+ }
314
+ } else {
315
+ console.log(" (none yet — 发一次请求后出现,mslxdff -chat hi)");
316
+ }
317
+
318
+ console.log("\nlast error:");
319
+ const err = lastError();
320
+ if (err) {
321
+ console.log(` ${fmtTs(err.ts)} ${err.model || "-"} ${err.status} ${err.message || ""}`);
322
+ if (err.stack) console.log(` ${String(err.stack).slice(0, 200)}`);
323
+ } else {
324
+ console.log(" (none — 暂无错误,挺好)");
325
+ }
326
+
327
+ const daemon2 = readPid();
328
+ const alive2 = daemon2 ? isPidAlive(daemon2) : false;
329
+ if (daemon2 && alive2) console.log(`\nauth token: use \`mslxdff -showtoken\` · health: http://127.0.0.1:${port}/health`);
330
+ else console.log(`\nnot running — start with: mslxdff -d · 查看日志 mslxdff -log 20`);
331
+ console.log(`hints: mslxdff -providers list · mslxdff -model status · mslxdff -group list · mslxdff -autostart status`);
332
+ }
@@ -0,0 +1,24 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { execFile } from "node:child_process";
3
+
4
+ export function errMsg(err) { return String(err?.message || err); }
5
+
6
+ export function readModelsCache(cacheFile) {
7
+ try {
8
+ return JSON.parse(readFileSync(cacheFile, "utf8"));
9
+ } catch {
10
+ return null;
11
+ }
12
+ }
13
+
14
+ export function npmCmd() {
15
+ return process.platform === "win32" ? "npm.cmd" : "npm";
16
+ }
17
+
18
+ export function run(cmd, args, opts = {}) {
19
+ const isWin = process.platform === "win32";
20
+ return new Promise((resolve) => {
21
+ const execOpts = isWin ? { shell: true, windowsHide: true } : {};
22
+ execFile(cmd, args, { timeout: 120_000, ...execOpts, ...opts }, (err, stdout, stderr) => resolve({ err, stdout, stderr }));
23
+ });
24
+ }
@@ -0,0 +1,159 @@
1
+ import { createKeyRing } from "./keyring.js";
2
+ import { joinModelId } from "./model-id.js";
3
+
4
+ let UndiciAgent = null;
5
+ let UndiciFetch = null;
6
+ try {
7
+ const mod = await import("undici");
8
+ UndiciAgent = mod.Agent;
9
+ UndiciFetch = mod.fetch;
10
+ } catch {}
11
+
12
+ export function envInt(name, fallback) {
13
+ const v = Number(process.env[name]);
14
+ return Number.isInteger(v) && v > 0 ? v : fallback;
15
+ }
16
+
17
+ export function joinUrl(base, path) {
18
+ const b = String(base || "").trim().replace(/\/+$/, "");
19
+ const p = String(path || "").trim();
20
+ if (!p) return b;
21
+ const pp = p.startsWith("/") ? p : `/${p}`;
22
+ return `${b}${pp}`;
23
+ }
24
+
25
+ export function sleep(ms) {
26
+ return new Promise((r) => setTimeout(r, ms));
27
+ }
28
+
29
+ export function getUndici() {
30
+ return { UndiciAgent, UndiciFetch };
31
+ }
32
+
33
+ export function createAgent({ keepAliveTimeout = 30_000, keepAliveMaxTimeout = 60_000, connections = 20 } = {}) {
34
+ if (!UndiciAgent) return { agent: null, dispatcher: null };
35
+ try {
36
+ const agent = new UndiciAgent({ keepAliveTimeout, keepAliveMaxTimeout, connections, pipelining: 1 });
37
+ return { agent, dispatcher: agent };
38
+ } catch {
39
+ return { agent: null, dispatcher: null };
40
+ }
41
+ }
42
+
43
+ export function collectApiKeysGeneric(id, apiKeys, apiKey, loadKeys) {
44
+ const list = [
45
+ ...(Array.isArray(apiKeys) ? apiKeys : [apiKeys].filter(Boolean)),
46
+ apiKey,
47
+ ...(apiKeys === undefined && apiKey === undefined ? loadKeys(id) : []),
48
+ ].filter((k) => typeof k === "string" && k.trim().length);
49
+ return [...new Set(list.map((k) => k.trim()))];
50
+ }
51
+
52
+ export function createChatRunner({ id, ring, cooldownMs, retry, fetchImpl, dispatcher, buildHeaders, getUrl, connectTimeoutMs = 30_000 }) {
53
+ async function attemptOnce(url, body, key, activeRing) {
54
+ const controller = new AbortController();
55
+ const timer = setTimeout(() => controller.abort(new Error(`${id} timed out after ${connectTimeoutMs}ms`)), connectTimeoutMs);
56
+ try {
57
+ const opts = { method: "POST", headers: buildHeaders(body, key), body: JSON.stringify(body), signal: controller.signal };
58
+ if (dispatcher) opts.dispatcher = dispatcher;
59
+ const res = await fetchImpl(url, opts);
60
+ if (res.status === 401 && !activeRing.size) return { __needKey: true };
61
+ return res;
62
+ } catch (err) {
63
+ return err;
64
+ } finally {
65
+ clearTimeout(timer);
66
+ }
67
+ }
68
+
69
+ async function runChat(body, activeRing, sourceKey) {
70
+ const url = getUrl();
71
+ const t0 = performance.now();
72
+ const attempts = [];
73
+ let waitMs = 0;
74
+ const key = activeRing.next();
75
+ if (!key && activeRing.size > 0) {
76
+ const err = new Error(`${id}: all API keys are in cooldown (last error < ${cooldownMs}ms ago) — provider temporarily unavailable`);
77
+ err._t = { attempts: [], waitMs: 0, totalMs: Math.round(performance.now() - t0), cooldownMs };
78
+ throw err;
79
+ }
80
+ for (let attempt = 0; ; attempt++) {
81
+ const t = performance.now();
82
+ const result = await attemptOnce(url, body, key, activeRing);
83
+ const type = result instanceof Error ? "network" : `http${result?.status}`;
84
+ attempts.push({ attempt, type, ms: Math.round(performance.now() - t) });
85
+ if (result?.__needKey) {
86
+ const err = new Error(`${id}: missing ${sourceKey} (chat requires a real key)`);
87
+ err._t = { attempts, waitMs, totalMs: Math.round(performance.now() - t0) };
88
+ throw err;
89
+ }
90
+ if (result instanceof Error) {
91
+ const entry = retry?.network;
92
+ if (entry && attempt < entry.attempts) { await sleep(entry.delayMs); waitMs += entry.delayMs; continue; }
93
+ activeRing.onError(key);
94
+ result._t = { attempts, waitMs, totalMs: Math.round(performance.now() - t0) };
95
+ throw result;
96
+ }
97
+ const entry = retry?.[result.status];
98
+ if (entry && attempt < entry.attempts) { await sleep(entry.delayMs); waitMs += entry.delayMs; continue; }
99
+ if (result.status === 401 || result.status === 403 || result.status === 429 || result.status >= 500) activeRing.onError(key);
100
+ result._t = { attempts, waitMs, totalMs: Math.round(performance.now() - t0) };
101
+ return result;
102
+ }
103
+ }
104
+
105
+ return { attemptOnce, runChat };
106
+ }
107
+
108
+ export function createListModelsRunner({ id, ring, dispatcher, fetchImpl, getUrl, mapModel }) {
109
+ const CACHE_TTL_MS = 10 * 60 * 1000;
110
+ let cache = null;
111
+ let fetchedAt = 0;
112
+ async function listModels() {
113
+ const now = Date.now();
114
+ if (cache && now - fetchedAt < CACHE_TTL_MS) return cache;
115
+ const url = getUrl();
116
+ const controller = new AbortController();
117
+ const timer = setTimeout(() => controller.abort(new Error(`${id} models timed out`)), 15_000);
118
+ try {
119
+ const headers = { Accept: "application/json" };
120
+ const key = ring.next();
121
+ if (key) headers["Authorization"] = `Bearer ${key}`;
122
+ const opts = { headers, signal: controller.signal };
123
+ if (dispatcher) opts.dispatcher = dispatcher;
124
+ const res = await fetchImpl(url, opts);
125
+ if (!res.ok) return [];
126
+ const json = await res.json().catch(() => ({}));
127
+ const raw = Array.isArray(json.data) ? json.data : Array.isArray(json) ? json : [];
128
+ const mapped = mapModel ? mapModel(raw) : raw;
129
+ cache = mapped.filter((m) => m && typeof m.id === "string").map((m) => ({ ...m, id: joinModelId(id, m.id) }));
130
+ fetchedAt = now;
131
+ return cache;
132
+ } catch {
133
+ return [];
134
+ } finally {
135
+ clearTimeout(timer);
136
+ }
137
+ }
138
+ return { listModels, _cache: () => cache };
139
+ }
140
+
141
+ export function createPreheatRunner({ dispatcher, fetchImpl, getUrl, id, ring, loadKeys }) {
142
+ async function preheat() {
143
+ const url = getUrl();
144
+ const t0 = performance.now();
145
+ try {
146
+ const headers = { Accept: "application/json" };
147
+ const key = (loadKeys ? loadKeys(id)[0] : ring.next()) || ring.next();
148
+ if (key) headers["Authorization"] = `Bearer ${key}`;
149
+ const opts = { headers };
150
+ if (dispatcher) opts.dispatcher = dispatcher;
151
+ const res = await fetchImpl(url, opts);
152
+ try { if (res.body) await res.text().catch(() => {}); } catch {}
153
+ return { ok: res.ok, status: res.status, ms: Math.round(performance.now() - t0) };
154
+ } catch (err) {
155
+ return { ok: false, error: String(err?.message || err), ms: Math.round(performance.now() - t0) };
156
+ }
157
+ }
158
+ return { preheat };
159
+ }