mslxdff 0.1.88 → 0.1.90

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 (46) hide show
  1. package/package.json +1 -1
  2. package/src/bench/cline-bench.js +21 -33
  3. package/src/bench/probe.js +4 -11
  4. package/src/bench/runner.js +8 -23
  5. package/src/bench/via-probe.js +12 -30
  6. package/src/bench/workbuddy-bench.js +15 -31
  7. package/src/chat/engine.js +160 -0
  8. package/src/chat/repl.js +32 -299
  9. package/src/chat/terminal.js +95 -0
  10. package/src/chat/tool-handlers.js +67 -0
  11. package/src/chat/upstream.js +1 -4
  12. package/src/chat-pipeline/auto-race.js +124 -0
  13. package/src/chat-pipeline/engine.js +17 -0
  14. package/src/chat-pipeline/index.js +86 -0
  15. package/src/chat-pipeline/planner.js +31 -0
  16. package/src/chat-pipeline/policy.js +73 -0
  17. package/src/chat-pipeline/serial-trial.js +144 -0
  18. package/src/cli/commands/model/list-providers.js +75 -0
  19. package/src/cli/commands/model/list-render.js +79 -0
  20. package/src/cli/commands/model/list.js +208 -0
  21. package/src/cli/commands/model/picks.js +45 -0
  22. package/src/cli/commands/model/stats.js +43 -0
  23. package/src/cli/commands/model/status.js +47 -0
  24. package/src/cli/commands/model.js +17 -371
  25. package/src/cli/help.js +2 -1
  26. package/src/providers/cline/chat.js +26 -53
  27. package/src/providers/workbuddy/chat.js +109 -221
  28. package/src/routes/chat/gateway.js +23 -286
  29. package/src/routes/chat/relay-pipeline.js +26 -0
  30. package/src/routes/groups-relay.js +85 -1
  31. package/src/routes/index.js +7 -1
  32. package/src/routes/relay-queue.js +53 -0
  33. package/src/runtime/bootstrap.js +14 -387
  34. package/src/runtime/broadband-stream.js +76 -0
  35. package/src/runtime/broadband.js +97 -0
  36. package/src/runtime/group-sync.js +28 -0
  37. package/src/runtime/providers-setup.js +147 -0
  38. package/src/runtime/server-lifecycle.js +156 -0
  39. package/src/state/facade.js +1 -0
  40. package/src/state/schemas/model.js +41 -0
  41. package/src/transport/index.js +248 -0
  42. package/src/transport/pool.js +60 -0
  43. package/src/transport/retry.js +24 -0
  44. package/src/transport/sse.js +93 -0
  45. package/src/upstream-responses.js +64 -0
  46. package/src/upstream.js +106 -334
@@ -0,0 +1,147 @@
1
+ import { join, dirname } from "node:path";
2
+ import { fileURLToPath } from "node:url";
3
+ import { defaultStateFile, loadToken } from "../state.js";
4
+ import { createUpstreamClient } from "../upstream.js";
5
+ import { createModelsService } from "../models.js";
6
+ import { createAutoSelector } from "../auto.js";
7
+ import { createPeersService } from "../peers.js";
8
+ import { createGroupsService, createBansService } from "../groups.js";
9
+ import { logDir, appendEvent } from "../logs.js";
10
+ import { loadPlugins, runHook, resolvePluginDirs } from "../plugins.js";
11
+ import { createOpenCodeProvider } from "../providers/opencode.js";
12
+ import { loadProviderKeys, loadProviderAuths, loadProviderConfigs } from "../state.js";
13
+ import { refreshIntervalMs, modelCooldownMs, slowCooldownMs, peerCooldownMs, peerHeatMs, banWindowMs, banThreshold } from "../cli/policy.js";
14
+ import { errMsg } from "../cli/util.js";
15
+
16
+ /**
17
+ * 世界组装 — 插件加载 → providers → models/auto/peers/groups/bans。
18
+ * 无参(读 env/state 自身),返回 ctx 由门面接力 server-lifecycle。
19
+ */
20
+ export async function setupProviders() {
21
+ const { token, created } = await loadToken();
22
+ const pkgRoot2 = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
23
+ const pluginDirs = resolvePluginDirs({ pkgRoot: pkgRoot2 });
24
+ const { plugins: loadedPlugins, errors: pluginErrors } = await loadPlugins({ dirs: pluginDirs });
25
+ for (const e of pluginErrors) {
26
+ console.log(`plugin load failed: ${e.file} — ${e.error}`);
27
+ appendEvent({ ts: Date.now(), type: "plugin-load-error", file: e.file, error: e.error });
28
+ }
29
+ if (loadedPlugins.length) {
30
+ console.log(`plugins loaded (${loadedPlugins.length}): ${loadedPlugins.map((p) => `${p.name}${p.version ? `@${p.version}` : ""}`).join(", ")}`);
31
+ appendEvent({ ts: Date.now(), type: "plugins-loaded", plugins: loadedPlugins.map((p) => ({ name: p.name, version: p.version })) });
32
+ }
33
+ const upstreamHooks = loadedPlugins.length
34
+ ? (name, ctx) => runHook(loadedPlugins, name, ctx)
35
+ : null;
36
+ const providerPlugin = loadedPlugins.find((p) => typeof p.createUpstream === "function");
37
+ let upstream;
38
+ const baseUrl = process.env.UPSTREAM_BASE_URL || "https://opencode.ai";
39
+ let providers = [];
40
+ if (providerPlugin) {
41
+ if (!upstream) {
42
+ try {
43
+ upstream = await providerPlugin.createUpstream({ baseUrl, authToken: process.env.UPSTREAM_AUTH_TOKEN || "public", env: process.env });
44
+ console.log(`upstream provider replaced by plugin: ${providerPlugin.name}`);
45
+ appendEvent({ ts: Date.now(), type: "plugin-upstream-active", plugin: providerPlugin.name });
46
+ } catch (err) {
47
+ console.log(`plugin upstream (${providerPlugin.name}) failed: ${errMsg(err)} — falling back to default`);
48
+ appendEvent({ ts: Date.now(), type: "plugin-upstream-error", plugin: providerPlugin.name, error: errMsg(err) });
49
+ }
50
+ }
51
+ if (!upstream) upstream = createUpstreamClient({ hooks: upstreamHooks });
52
+ } else {
53
+ const opencodeClient = createUpstreamClient({ hooks: upstreamHooks });
54
+ const opencodeModels = createModelsService({
55
+ baseUrl,
56
+ headers: opencodeClient.headers,
57
+ refreshMs: refreshIntervalMs(),
58
+ cacheFile: join(logDir(), "models.json"),
59
+ });
60
+ providers.push(createOpenCodeProvider({ upstream: opencodeClient, modelsService: opencodeModels }));
61
+ const orKeys = loadProviderKeys("openrouter");
62
+ if (orKeys.length) {
63
+ const { createOpenRouterProvider } = await import("../providers/openrouter.js");
64
+ providers.push(createOpenRouterProvider({ apiKeys: orKeys }));
65
+ console.log(`provider enabled: openrouter (${orKeys.length} key${orKeys.length > 1 ? "s" : ""})`);
66
+ appendEvent({ ts: Date.now(), type: "provider-enabled", provider: "openrouter", keys: orKeys.length });
67
+ }
68
+ const genericConfigs = loadProviderConfigs();
69
+ for (const [gid, cfg] of Object.entries(genericConfigs)) {
70
+ if (gid === "opencode" || gid === "openrouter") continue;
71
+ const base = String(cfg?.baseUrl || "").trim();
72
+ const keys = Array.isArray(cfg?.keys) ? cfg.keys.filter((k) => typeof k === "string" && k.trim()) : [];
73
+ const auths = Array.isArray(cfg?.auths) ? cfg.auths : [];
74
+ // 可扩展:优先走注册表定制 provider(如 workbuddy、cline),新增供应商仅需在 registry.js 注册
75
+ const { getCustomProviderFactory } = await import("../providers/registry.js");
76
+ const customFactory = await getCustomProviderFactory(gid, base);
77
+ if (customFactory) {
78
+ if (gid === "workbuddy" && !keys.length) continue;
79
+ if (gid !== "workbuddy" && (!base || !keys.length)) continue;
80
+ try {
81
+ const provider = gid === "workbuddy"
82
+ ? await customFactory({ baseUrl: base || "https://copilot.tencent.com", apiKeys: keys, auths })
83
+ : await customFactory({ id: gid, baseUrl: base, apiKeys: keys });
84
+ providers.push(provider);
85
+ console.log(`provider enabled: ${gid} (${keys.length} key${keys.length > 1 ? "s" : ""}) baseUrl=${base || provider.baseUrl} [custom]`);
86
+ appendEvent({ ts: Date.now(), type: "provider-enabled", provider: gid, keys: keys.length, baseUrl: base || provider.baseUrl });
87
+ } catch (err) {
88
+ console.log(`provider ${gid} failed: ${err?.message || err}`);
89
+ appendEvent({ ts: Date.now(), type: "provider-error", provider: gid, error: String(err?.message || err) });
90
+ }
91
+ continue;
92
+ }
93
+ if (!base || !keys.length) continue;
94
+ try {
95
+ const { createGenericProvider } = await import("../providers/generic.js");
96
+ providers.push(createGenericProvider({ id: gid, baseUrl: base, apiKeys: keys }));
97
+ console.log(`provider enabled: ${gid} (${keys.length} key${keys.length > 1 ? "s" : ""}) baseUrl=${base}`);
98
+ appendEvent({ ts: Date.now(), type: "provider-enabled", provider: gid, keys: keys.length, baseUrl: base });
99
+ } catch (err) {
100
+ console.log(`provider ${gid} failed: ${err?.message || err}`);
101
+ appendEvent({ ts: Date.now(), type: "provider-error", provider: gid, error: String(err?.message || err) });
102
+ }
103
+ }
104
+ if (!genericConfigs["workbuddy"]) {
105
+ const wbKeys = loadProviderKeys("workbuddy");
106
+ if (wbKeys.length) {
107
+ try {
108
+ const { createWorkbuddyProvider } = await import("../providers/workbuddy.js");
109
+ const wbAuths = loadProviderAuths("workbuddy");
110
+ providers.push(createWorkbuddyProvider({ apiKeys: wbKeys, auths: wbAuths }));
111
+ console.log(`provider enabled: workbuddy (${wbKeys.length} key${wbKeys.length > 1 ? "s" : ""}) baseUrl=https://copilot.tencent.com (env)`);
112
+ appendEvent({ ts: Date.now(), type: "provider-enabled", provider: "workbuddy", keys: wbKeys.length, baseUrl: "https://copilot.tencent.com" });
113
+ } catch (err) {
114
+ console.log(`provider workbuddy failed: ${err?.message || err}`);
115
+ }
116
+ }
117
+ }
118
+ const { createProviderDispatcher } = await import("../providers/dispatcher.js");
119
+ upstream = createProviderDispatcher(providers);
120
+ appendEvent({ ts: Date.now(), type: "providers", providers: providers.map((p) => p.id) });
121
+ }
122
+ const opencodeProvider = providers.find((p) => p.id === "opencode");
123
+ const models = createModelsService({
124
+ providers: providers.length > 1 ? providers : undefined,
125
+ baseUrl,
126
+ headers: upstream.headers || opencodeProvider?.upstream?.headers,
127
+ refreshMs: refreshIntervalMs(),
128
+ cacheFile: join(logDir(), "models.json"),
129
+ });
130
+ const auto = createAutoSelector({
131
+ cooldownMs: modelCooldownMs(),
132
+ slowCooldownMs: slowCooldownMs(),
133
+ file: defaultStateFile(),
134
+ loadCandidates: async () => {
135
+ try {
136
+ return (await models.get()).data.map((m) => m.id);
137
+ } catch {
138
+ return null;
139
+ }
140
+ },
141
+ });
142
+ const peers = createPeersService({ cooldownMs: peerCooldownMs(), heatMs: peerHeatMs() });
143
+ const groups = createGroupsService({});
144
+ const bans = createBansService({ windowMs: banWindowMs(), threshold: banThreshold() });
145
+
146
+ return { token, created, loadedPlugins, upstreamHooks, providerPlugin, upstream, providers, baseUrl, opencodeProvider, models, auto, peers, groups, bans };
147
+ }
@@ -0,0 +1,156 @@
1
+ import { startServer, resolvePort } from "../server.js";
2
+ import { createRouter } from "../routes.js";
3
+ import { createEventBus } from "../events.js";
4
+ import { runHook } from "../plugins.js";
5
+ import { effectiveHost, maxHopsValue } from "../cli/policy.js";
6
+ import { fmtEvent } from "../cli/format.js";
7
+ import { writePid } from "../daemon.js";
8
+
9
+ /**
10
+ * 服务生命周期 — router 装配 → server 创建/ready-EADDRINUSE 自愈 →
11
+ * plugin 事件 → preheat → pid/监听日志 → autostart。返回 { srv, bus, router }。
12
+ */
13
+ export async function startServerLifecycle({ VERSION, token, created, upstream, models, auto, peers, groups, bans, loadedPlugins, baseUrl, logs }) {
14
+ const bus = createEventBus();
15
+
16
+ try {
17
+ const { loadModelAliases } = await import("../providers/model-id.js");
18
+ loadModelAliases();
19
+ } catch {}
20
+
21
+ const router = createRouter({ token, upstream, models, auto, logs, peers, maxHops: maxHopsValue(), groups, bans, bus, plugins: loadedPlugins });
22
+ const listenHost = effectiveHost();
23
+ const isDebug = process.env.MSLXDFF_DEBUG === "1";
24
+ const srv = startServer({
25
+ router,
26
+ signals: !isDebug,
27
+ host: listenHost,
28
+ onBeforeClose: loadedPlugins.length
29
+ ? () => runHook(loadedPlugins, "server:stop", { version: VERSION }).then(() => {})
30
+ : undefined,
31
+ });
32
+
33
+ if (isDebug) {
34
+ bus.subscribe((e) => {
35
+ try {
36
+ console.log(fmtEvent(e));
37
+ } catch {}
38
+ });
39
+ const { startDaemon: sd } = await import("../daemon.js");
40
+ const restore2 = () => {
41
+ console.log("\n[debug] restoring background daemon...");
42
+ try {
43
+ const restoredPid = sd([]);
44
+ console.log(`[debug] daemon restored (pid ${restoredPid})`);
45
+ } catch (err) {
46
+ console.error(`[debug] could not restore daemon: ${err.message}`);
47
+ }
48
+ setTimeout(() => process.exit(0), 300);
49
+ };
50
+ process.on("SIGINT", restore2);
51
+ process.on("SIGTERM", restore2);
52
+ }
53
+
54
+ // Robust ready: if EADDRINUSE (bare daemon still holds port), kill holders and retry once
55
+ try {
56
+ await srv.ready();
57
+ } catch (err) {
58
+ const msg = String(err?.message || err);
59
+ const code = err?.code || "";
60
+ if (code === "EADDRINUSE" || msg.includes("EADDRINUSE")) {
61
+ console.log(`port ${resolvePort()} in use — freeing stale holder and retrying...`);
62
+ try {
63
+ const { execFile } = await import("node:child_process");
64
+ const execAsync2 = (f, a) => new Promise((res) => execFile(f, a, { windowsHide: true, timeout: 4000 }, (e, so, se) => res({ e, so: String(so||""), se: String(se||"") })));
65
+ const port = resolvePort();
66
+ // kill via ss parse (same as autostart)
67
+ const ss1 = await execAsync2("ss", ["-lptn", `sport = :${port}`]);
68
+ const out = ss1.so || "";
69
+ const pids = new Set();
70
+ let m;
71
+ const re = /pid=(\d+)/g;
72
+ while ((m = re.exec(out))) pids.add(Number(m[1]));
73
+ if (!pids.size) {
74
+ const ss2 = await execAsync2("ss", ["-lptn"]);
75
+ for (const line of (ss2.so||"").split("\n")) {
76
+ if (!line.includes(`:${port}`)) continue;
77
+ let m2; const re2 = /pid=(\d+)/g;
78
+ while ((m2 = re2.exec(line))) pids.add(Number(m2[1]));
79
+ }
80
+ }
81
+ for (const p of pids) { if (p !== process.pid) try { process.kill(p, "SIGTERM"); } catch {} }
82
+ if (pids.size) await new Promise((r2) => setTimeout(r2, 600));
83
+ for (const p of pids) try { const { isPidAlive } = await import("../daemon.js"); if (isPidAlive(p)) process.kill(p, "SIGKILL"); } catch {}
84
+ try { await execAsync2("fuser", ["-k", `${port}/tcp`]); } catch {}
85
+ for (let i=0;i<10;i++) {
86
+ const chk = await execAsync2("ss", ["-ltn"]);
87
+ if (!chk.so.includes(`:${port}`)) break;
88
+ await new Promise((r2)=>setTimeout(r2,200));
89
+ }
90
+ } catch {}
91
+ await srv.ready();
92
+ } else throw err;
93
+ }
94
+
95
+ if (loadedPlugins.length) {
96
+ runHook(loadedPlugins, "server:start", { port: srv.server.address()?.port, host: listenHost, version: VERSION }).catch(() => {});
97
+ const eventPlugins = loadedPlugins.filter((p) => typeof p.onEvent === "function");
98
+ if (eventPlugins.length) {
99
+ bus.subscribe((e) => {
100
+ for (const p of eventPlugins) {
101
+ try { p.onEvent(e); } catch {}
102
+ }
103
+ });
104
+ }
105
+ }
106
+
107
+ setTimeout(() => {
108
+ upstream.preheat().then((r) => {
109
+ const entry = { ts: Date.now(), type: "upstream-preheat", ...r, baseUrl };
110
+ try { bus.emit(entry); } catch {}
111
+ try { logs.appendEvent(entry); } catch {}
112
+ if (r.skipped) console.log(`[preheat] skipped (MSLXDFF_PREHEAT disabled)`);
113
+ else if (r.ok) console.log(`[preheat] opencode models ok ${r.status} ${r.ms}ms`);
114
+ else console.log(`[preheat] opencode models failed ${r.error || r.status || ""} ${r.ms || 0}ms`);
115
+ }).catch(() => {});
116
+ }, 100).unref?.();
117
+
118
+ models.startAutoRefresh();
119
+ if (process.env.MSLXDFF_DAEMON) {
120
+ writePid(process.pid, VERSION);
121
+ }
122
+ const addr = srv.server.address();
123
+ const host = addr.address === "0.0.0.0" || addr.address === "::" ? "localhost" : addr.address;
124
+ console.log(`mslxdff v${VERSION} listening on http://${host}:${addr.port}`);
125
+ if (created) {
126
+ console.log(`auth token: ${token}`);
127
+ }
128
+ console.log(`endpoint: http://${host}:${addr.port}/v1`);
129
+ try {
130
+ const { hedgeDelayMs } = await import("../routes/hedge.js");
131
+ const hd = hedgeDelayMs();
132
+ console.log(`hedge: ${hd ? `${hd}ms` : "off"} (MSLXDFF_HEDGE_DELAY_MS)`);
133
+ } catch {}
134
+
135
+ // best-effort: ensure autostart on Linux (so daemon survives reboot/SSH disconnect without manual cmd)
136
+ if (process.platform === "linux" && !process.env.MSLXDFF_NO_AUTOSTART) {
137
+ setTimeout(async () => {
138
+ try {
139
+ const { getAutostartStatus, enableAutostart } = await import("../autostart.js");
140
+ const st = await getAutostartStatus();
141
+ if (!st.enabled) {
142
+ const r = await enableAutostart();
143
+ if (r.ok) {
144
+ console.log(`autostart auto-enabled: ${r.method}${r.linger ? ` linger=${r.linger}` : ""}`);
145
+ try { bus?.emit({ ts: Date.now(), type: "autostart-auto-enabled", method: r.method }); } catch {}
146
+ try { logs.appendEvent({ ts: Date.now(), type: "autostart-auto-enabled", method: r.method }); } catch {}
147
+ } else {
148
+ console.log(`autostart auto-enable failed: ${r.error || "unknown"} (run mslxdff -enable-autostart manually)`);
149
+ }
150
+ }
151
+ } catch {}
152
+ }, 2500).unref?.();
153
+ }
154
+
155
+ return { srv, bus, router };
156
+ }
@@ -48,6 +48,7 @@ export {
48
48
  saveModelLatencies,
49
49
  loadModelStats,
50
50
  saveModelStats,
51
+ recordModelStats,
51
52
  loadPreferredModel,
52
53
  loadModelPicks,
53
54
  saveModelPicks,
@@ -30,6 +30,47 @@ export function saveModelStats(stats, { file = defaultStateFile() } = {}) {
30
30
  return stats;
31
31
  }
32
32
 
33
+ const STATS_ALPHA = 0.3;
34
+ function ema(prev, next) {
35
+ if (!Number.isFinite(prev) || prev <= 0) return Math.round(next);
36
+ if (!Number.isFinite(next) || next <= 0) return Math.round(prev);
37
+ return Math.round(prev * (1 - STATS_ALPHA) + next * STATS_ALPHA);
38
+ }
39
+
40
+ export function recordModelStats(id, { ttfbMs, totalMs, tps, completionTokens, file = defaultStateFile() } = {}) {
41
+ if (!id || typeof id !== "string") return null;
42
+ const stats = loadModelStats({ file });
43
+ const cur = stats[id] || { count: 0 };
44
+ const next = { ...cur };
45
+ next.count = (cur.count || 0) + 1;
46
+ next.lastAt = Date.now();
47
+ if (Number.isFinite(ttfbMs) && ttfbMs >= 0) {
48
+ next.avgTtfbMs = cur.avgTtfbMs != null ? ema(cur.avgTtfbMs, ttfbMs) : Math.round(ttfbMs);
49
+ next.emaTtfbMs = next.avgTtfbMs;
50
+ // 简易 p95:取 max 的 EMA
51
+ if (cur.p95Ttfb == null) next.p95Ttfb = Math.round(ttfbMs);
52
+ else next.p95Ttfb = Math.max(cur.p95Ttfb, Math.round(ttfbMs * 0.7 + cur.p95Ttfb * 0.3));
53
+ }
54
+ if (Number.isFinite(totalMs) && totalMs >= 0) {
55
+ next.avgTotalMs = cur.avgTotalMs != null ? ema(cur.avgTotalMs, totalMs) : Math.round(totalMs);
56
+ next.emaTotalMs = next.avgTotalMs;
57
+ next.lastTotalMs = Math.round(totalMs);
58
+ }
59
+ if (Number.isFinite(tps) && tps > 0) {
60
+ next.avgTps = cur.avgTps != null ? Number((cur.avgTps * (1 - STATS_ALPHA) + tps * STATS_ALPHA).toFixed(1)) : Number(tps.toFixed(1));
61
+ next.emaTps = next.avgTps;
62
+ }
63
+ if (Number.isFinite(completionTokens) && completionTokens > 0) {
64
+ const prevAvg = cur.avgCompTok;
65
+ next.avgCompTok = prevAvg != null ? Math.round(prevAvg * (1 - STATS_ALPHA) + completionTokens * STATS_ALPHA) : Math.round(completionTokens);
66
+ }
67
+ // 兼容旧字段:lastAt 供排序
68
+ stats[id] = next;
69
+ // 监控需实时可见,用同步落盘而非 500ms debounce
70
+ try { writeStateImmediate(file, { modelStats: stats }); } catch { saveModelStats(stats, { file }); }
71
+ return next;
72
+ }
73
+
33
74
  export function loadPreferredModel({ file = defaultStateFile() } = {}) {
34
75
  const v = readState(file).preferredModel;
35
76
  return typeof v === "string" && v.trim() ? v.trim() : null;
@@ -0,0 +1,248 @@
1
+ import { performance } from "node:perf_hooks";
2
+ import { resolveRetry, sleep, backoffDelay } from "./retry.js";
3
+ import { createSseParser } from "./sse.js";
4
+ import { createPool } from "./pool.js";
5
+
6
+ let UndiciFetch = null;
7
+ try {
8
+ const mod = await import("undici");
9
+ UndiciFetch = mod.fetch;
10
+ } catch {}
11
+
12
+ const DEFAULT_RETRY = {
13
+ network: { attempts: 2, delayMs: 300 },
14
+ 429: { attempts: 1, delayMs: 100 },
15
+ 502: { attempts: 1, delayMs: 100 },
16
+ 503: { attempts: 1, delayMs: 100 },
17
+ 504: { attempts: 1, delayMs: 100 },
18
+ };
19
+
20
+ export function createTransport({
21
+ baseUrl,
22
+ headers: baseHeaders = {},
23
+ keepAlive = true,
24
+ fetchImpl,
25
+ dispatcher: extDispatcher,
26
+ timeoutMs: defaultTimeoutMs = 30_000,
27
+ retry: defaultRetry = DEFAULT_RETRY,
28
+ hooks,
29
+ } = {}) {
30
+ if (!fetchImpl) fetchImpl = UndiciFetch || globalThis.fetch;
31
+ const pool = keepAlive && !extDispatcher ? createPool({ keepAlive }) : null;
32
+ const getDispatcher = () => extDispatcher || pool?.dispatcher || null;
33
+
34
+ let closed = false;
35
+
36
+ function resolveUrl(url) {
37
+ if (!url) return baseUrl || "";
38
+ if (/^https?:\/\//i.test(url)) return url;
39
+ if (!baseUrl) return url;
40
+ return `${String(baseUrl).replace(/\/+$/, "")}/${String(url).replace(/^\/+/, "")}`;
41
+ }
42
+
43
+ async function applyHooks(name, ctx) {
44
+ if (!hooks) return null;
45
+ try { return await hooks(name, ctx); } catch { return null; }
46
+ }
47
+
48
+ async function request({
49
+ url,
50
+ method = "POST",
51
+ headers = {},
52
+ body,
53
+ stream,
54
+ timeoutMs,
55
+ retry,
56
+ dispatcher,
57
+ } = {}) {
58
+ const finalUrl = resolveUrl(url);
59
+ const retryCfg = retry ?? defaultRetry;
60
+ const timeout = Number(timeoutMs ?? defaultTimeoutMs) || 30_000;
61
+ const disp = dispatcher ?? getDispatcher();
62
+ const t0 = performance.now();
63
+ const attempts = [];
64
+ let waitMs = 0;
65
+
66
+ // 合并 headers
67
+ const finalHeaders = { ...baseHeaders, ...headers };
68
+ if (body != null && !finalHeaders["Content-Type"] && !finalHeaders["content-type"]) {
69
+ finalHeaders["Content-Type"] = "application/json";
70
+ }
71
+ if (stream && !finalHeaders["Accept"] && !finalHeaders["accept"]) {
72
+ finalHeaders["Accept"] = "text/event-stream";
73
+ }
74
+
75
+ const bodyStr = body != null && typeof body !== "string" ? JSON.stringify(body) : body;
76
+
77
+ for (let attempt = 0; ; attempt++) {
78
+ const tAttempt = performance.now();
79
+ let res;
80
+ let err = null;
81
+ const controller = new AbortController();
82
+ const timer = setTimeout(() => controller.abort(new Error(`upstream timed out after ${timeout}ms`)), timeout);
83
+ try {
84
+ let reqUrl = finalUrl;
85
+ let reqHeaders = { ...finalHeaders };
86
+ // hooks
87
+ const hh = await applyHooks("upstream:headers", { url: reqUrl, body, headers: reqHeaders });
88
+ if (hh?.changed && hh.value?.headers) reqHeaders = hh.value.headers;
89
+ const br = await applyHooks("upstream:before-request", { url: reqUrl, method, body, headers: reqHeaders });
90
+ if (br?.changed && br.value) {
91
+ if (typeof br.value.url === "string" && br.value.url) reqUrl = br.value.url;
92
+ if (br.value.headers && typeof br.value.headers === "object") reqHeaders = br.value.headers;
93
+ }
94
+ const opts = { method, headers: reqHeaders, body: bodyStr, signal: controller.signal };
95
+ if (disp) opts.dispatcher = disp;
96
+ res = await fetchImpl(reqUrl, opts);
97
+ } catch (e) {
98
+ err = e;
99
+ } finally {
100
+ clearTimeout(timer);
101
+ }
102
+ const ms = Math.round(performance.now() - tAttempt);
103
+
104
+ if (err) {
105
+ attempts.push({ type: "network", ms });
106
+ const { shouldRetry, delayMs } = resolveRetry("network", attempt, retryCfg);
107
+ if (shouldRetry) {
108
+ await sleep(delayMs);
109
+ waitMs += delayMs;
110
+ continue;
111
+ }
112
+ err._t = { attempts, waitMs, totalMs: Math.round(performance.now() - t0) };
113
+ throw err;
114
+ }
115
+
116
+ // http
117
+ attempts.push({ type: `http${res.status}`, ms });
118
+ const { shouldRetry, delayMs } = resolveRetry(res.status, attempt, retryCfg);
119
+ if (shouldRetry) {
120
+ // 消耗 body 以释放连接
121
+ try { if (res.body) await res.text().catch(() => {}); } catch {}
122
+ await sleep(delayMs);
123
+ waitMs += delayMs;
124
+ continue;
125
+ }
126
+
127
+ const ttfbMs = Math.round(performance.now() - t0);
128
+ const isStreamRequested = stream === true;
129
+ const contentType = res.headers.get("content-type") || "";
130
+ // 若请求为 stream 但上游返回的是 JSON(测试桩常见),则回退为非流式处理,避免 SSE 空聚合
131
+ const isStream = isStreamRequested && contentType.includes("text/event-stream");
132
+ if (!isStream) {
133
+ // 非流式:预读 body 以得 totalMs 与缓存(兼容 stream:true 但返回 JSON 的桩)
134
+ let cachedText = "";
135
+ let readMs = ttfbMs;
136
+ try {
137
+ cachedText = await res.text();
138
+ readMs = Math.round(performance.now() - t0);
139
+ } catch {
140
+ cachedText = "";
141
+ readMs = ttfbMs;
142
+ }
143
+ const totalMs = readMs;
144
+ const headers = res.headers;
145
+ return {
146
+ status: res.status,
147
+ headers,
148
+ ok: res.ok,
149
+ ttfbMs,
150
+ totalMs,
151
+ _t: { attempts, waitMs, totalMs },
152
+ async json() { try { return JSON.parse(cachedText); } catch { return cachedText; } },
153
+ async text() { return cachedText; },
154
+ stream() { throw new Error("not-streaming: call with stream:true"); },
155
+ get body() { return null; },
156
+ };
157
+ } else {
158
+ // 流式:保留原始 res 用于 stream()
159
+ const headers = res.headers;
160
+ let firstTtfb = ttfbMs; // 更新为首事件到达时刻(测得即所得)
161
+ let firstDone = false;
162
+ let lastRead = ttfbMs;
163
+ const markFirst = () => {
164
+ if (!firstDone) { firstTtfb = Math.round(performance.now() - t0); firstDone = true; }
165
+ };
166
+ let _t = { attempts, waitMs, totalMs: ttfbMs };
167
+ return {
168
+ status: res.status,
169
+ headers,
170
+ ok: res.ok,
171
+ get ttfbMs() { return firstDone ? firstTtfb : ttfbMs; },
172
+ get totalMs() { return lastRead; },
173
+ get _t() { return _t; },
174
+ set _t(v) { _t = v; },
175
+ async json() {
176
+ let acc = "";
177
+ for await (const chunk of this.stream()) acc += chunk;
178
+ try { return JSON.parse(acc); } catch { return acc; }
179
+ },
180
+ async text() {
181
+ let acc = "";
182
+ for await (const chunk of this.stream()) acc += chunk;
183
+ return acc;
184
+ },
185
+ get body() { return res.body; },
186
+ async *stream() {
187
+ const parser = createSseParser();
188
+ if (res.body && typeof res.body.getReader === "function") {
189
+ const reader = res.body.getReader();
190
+ const decoder = new TextDecoder();
191
+ while (true) {
192
+ const { done, value } = await reader.read();
193
+ if (done) break;
194
+ lastRead = Math.round(performance.now() - t0);
195
+ try { _t.totalMs = lastRead; } catch {}
196
+ const text = decoder.decode(value, { stream: true });
197
+ const evs = parser.push(text);
198
+ for (const e of evs) {
199
+ if (e === "[DONE]") return;
200
+ if (e === "") continue;
201
+ markFirst();
202
+ yield e;
203
+ }
204
+ }
205
+ } else if (typeof res.text === "function") {
206
+ const txt = await res.text();
207
+ const evs = parser.push(txt);
208
+ for (const e of evs) {
209
+ if (e === "[DONE]") return;
210
+ if (e === "") continue;
211
+ markFirst();
212
+ yield e;
213
+ }
214
+ }
215
+ },
216
+ };
217
+ }
218
+ }
219
+ }
220
+
221
+ async function preheat(url) {
222
+ const target = url || (baseUrl ? `${String(baseUrl).replace(/\/+$/, "")}/zen/v1/models` : null);
223
+ if (!target) return { ok: false, skipped: true };
224
+ const t0 = performance.now();
225
+ try {
226
+ const res = await request({ url: target, method: "GET", stream: false, timeoutMs: 3000 });
227
+ try { if (res.text) await res.text().catch(() => {}); } catch {}
228
+ return { ok: res.ok, status: res.status, ms: Math.round(performance.now() - t0) };
229
+ } catch (e) {
230
+ return { ok: false, error: String(e?.message || e), ms: Math.round(performance.now() - t0) };
231
+ }
232
+ }
233
+
234
+ async function close() {
235
+ if (closed) return;
236
+ closed = true;
237
+ if (pool) await pool.close();
238
+ }
239
+
240
+ return {
241
+ request,
242
+ preheat,
243
+ close,
244
+ get dispatcher() { return getDispatcher(); },
245
+ get agent() { return pool?.agent || null; },
246
+ [Symbol.asyncDispose]: close,
247
+ };
248
+ }
@@ -0,0 +1,60 @@
1
+ let UndiciAgent = null;
2
+ try {
3
+ const mod = await import("undici");
4
+ UndiciAgent = mod.Agent;
5
+ } catch {
6
+ UndiciAgent = null;
7
+ }
8
+
9
+ function envInt(name, fallback) {
10
+ const v = Number(process.env[name]);
11
+ return Number.isInteger(v) && v > 0 ? v : fallback;
12
+ }
13
+
14
+ export function createPool({
15
+ keepAlive = true,
16
+ keepAliveTimeout,
17
+ keepAliveMaxTimeout,
18
+ connections,
19
+ } = {}) {
20
+ const keepAliveTimeoutMs = keepAliveTimeout ?? envInt("MSLXDFF_UPSTREAM_KEEPALIVE_TIMEOUT", 30_000);
21
+ const keepAliveMaxTimeoutMs = keepAliveMaxTimeout ?? envInt("MSLXDFF_UPSTREAM_KEEPALIVE_MAX_TIMEOUT", 60_000);
22
+ const keepAliveConnections = connections ?? envInt("MSLXDFF_UPSTREAM_KEEPALIVE_CONNECTIONS", 20);
23
+
24
+ let agent = null;
25
+ let dispatcher = null;
26
+ let closed = false;
27
+
28
+ if (keepAlive && UndiciAgent) {
29
+ try {
30
+ agent = new UndiciAgent({
31
+ keepAliveTimeout: keepAliveTimeoutMs,
32
+ keepAliveMaxTimeout: keepAliveMaxTimeoutMs,
33
+ connections: keepAliveConnections,
34
+ pipelining: 1,
35
+ });
36
+ dispatcher = agent;
37
+ } catch {
38
+ agent = null;
39
+ dispatcher = null;
40
+ }
41
+ }
42
+
43
+ async function close() {
44
+ if (closed) return;
45
+ closed = true;
46
+ if (agent && typeof agent.close === "function") {
47
+ try { await agent.close(); } catch {}
48
+ } else if (dispatcher && typeof dispatcher.close === "function" && dispatcher !== agent) {
49
+ try { await dispatcher.close(); } catch {}
50
+ }
51
+ }
52
+
53
+ return {
54
+ get dispatcher() { return dispatcher; },
55
+ get agent() { return agent; },
56
+ get closed() { return closed; },
57
+ close,
58
+ [Symbol.asyncDispose]: close,
59
+ };
60
+ }