mslxdff 0.1.231 → 0.1.233

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 (117) hide show
  1. package/bin/mslxdff.js +3 -3
  2. package/package.json +1 -1
  3. package/src/auto.js +264 -254
  4. package/src/bench/cline-bench.js +42 -42
  5. package/src/bench/probe.js +70 -70
  6. package/src/bench/report.js +162 -162
  7. package/src/bench/runner.js +77 -77
  8. package/src/bench/via-probe.js +124 -124
  9. package/src/bench/via-routes.js +87 -87
  10. package/src/bench/workbuddy-bench.js +54 -54
  11. package/src/chat/engine.js +160 -160
  12. package/src/chat/gateway.js +163 -163
  13. package/src/chat/orchestrator.js +234 -234
  14. package/src/chat/prompt.js +70 -70
  15. package/src/chat/repl.js +88 -88
  16. package/src/chat/terminal.js +135 -135
  17. package/src/chat/tools.js +306 -306
  18. package/src/chat-pipeline/index.js +155 -145
  19. package/src/chat-pipeline/policy.js +84 -84
  20. package/src/cli/commands/group.js +266 -266
  21. package/src/cli/commands/model/picks.js +50 -50
  22. package/src/cli/commands/provider/bench-via.js +247 -247
  23. package/src/cli/commands/provider/bench.js +141 -141
  24. package/src/cli/commands/provider/index.js +139 -139
  25. package/src/cli/commands/provider/models.js +149 -149
  26. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  27. package/src/cli/commands/provider/raccoon-quota.js +156 -156
  28. package/src/cli/commands/sync.js +310 -310
  29. package/src/cli/status.js +279 -279
  30. package/src/daemon.js +246 -246
  31. package/src/model-capabilities/enrich.js +86 -86
  32. package/src/model-capabilities/index.js +183 -183
  33. package/src/model-capabilities/parse.js +70 -70
  34. package/src/model-trace.js +10 -2
  35. package/src/models.js +292 -225
  36. package/src/peers.js +345 -345
  37. package/src/providers/agentrouter.js +238 -238
  38. package/src/providers/base.js +164 -164
  39. package/src/providers/cline/auth.js +228 -228
  40. package/src/providers/cline/chat.js +307 -307
  41. package/src/providers/cline.js +2 -2
  42. package/src/providers/codearts/chat.js +207 -207
  43. package/src/providers/dispatcher.js +147 -147
  44. package/src/providers/globalqwenwork/cosy.js +123 -123
  45. package/src/providers/globalqwenwork/crypto.js +218 -218
  46. package/src/providers/globalqwenwork/http.js +20 -20
  47. package/src/providers/globalqwenwork/rsa.js +54 -54
  48. package/src/providers/globalqwenwork/sse.js +268 -268
  49. package/src/providers/globalqwenwork/stream.js +130 -130
  50. package/src/providers/globalqwenwork/upstream.js +122 -122
  51. package/src/providers/keyring.js +60 -60
  52. package/src/providers/qoder/account-store.js +18 -0
  53. package/src/providers/qoder/chat.js +292 -203
  54. package/src/providers/qoder/checkin.js +25 -12
  55. package/src/providers/qoder/index.js +311 -249
  56. package/src/providers/qoder/models.js +64 -2
  57. package/src/providers/qoder/oauth.js +42 -1
  58. package/src/providers/qoder/payload.js +116 -80
  59. package/src/providers/qoder/request.js +7 -2
  60. package/src/providers/qoder/session.js +26 -10
  61. package/src/providers/qoder/sse.js +233 -145
  62. package/src/providers/qoder/sticky.js +5 -2
  63. package/src/providers/qoder/wire-messages.js +242 -0
  64. package/src/providers/qwenwork/account-store.js +133 -133
  65. package/src/providers/qwenwork/constants.js +67 -67
  66. package/src/providers/qwenwork/cosy.js +120 -120
  67. package/src/providers/qwenwork/crypto.js +218 -218
  68. package/src/providers/qwenwork/http.js +20 -20
  69. package/src/providers/qwenwork/index.js +337 -337
  70. package/src/providers/qwenwork/payload.js +144 -144
  71. package/src/providers/qwenwork/rsa.js +54 -54
  72. package/src/providers/qwenwork/sse.js +268 -268
  73. package/src/providers/qwenwork/stream.js +130 -130
  74. package/src/providers/qwenwork/upstream.js +120 -120
  75. package/src/providers/qwenwork.js +1 -1
  76. package/src/providers/raccoon/chat.js +1 -1
  77. package/src/providers/raccoon/const.js +219 -202
  78. package/src/providers/raccoon/credits.js +285 -285
  79. package/src/providers/raccoon/index.js +15 -2
  80. package/src/providers/raccoon/models.js +68 -17
  81. package/src/providers/registry.js +89 -89
  82. package/src/providers/workbuddy/auth.js +16 -0
  83. package/src/providers/workbuddy/chat.js +298 -264
  84. package/src/providers/workbuddy/client-headers.js +148 -0
  85. package/src/providers/workbuddy/desktop-info.js +17 -1
  86. package/src/providers/workbuddy/models.js +8 -20
  87. package/src/providers/workbuddy/reshape.js +152 -152
  88. package/src/providers/workbuddy.js +2 -2
  89. package/src/reasoning.js +32 -32
  90. package/src/routes/chat/broadband-handler.js +80 -80
  91. package/src/routes/chat/gateway.js +46 -46
  92. package/src/routes/chat/relay-pipeline.js +282 -282
  93. package/src/routes/chat/via-route-handler.js +156 -156
  94. package/src/routes/hedge.js +260 -260
  95. package/src/routes/models-route.js +167 -167
  96. package/src/routes/peers.js +373 -373
  97. package/src/routes/stream.js +364 -347
  98. package/src/runtime/bootstrap.js +75 -75
  99. package/src/runtime/keep-warm.js +135 -135
  100. package/src/runtime/provider-gate.js +75 -75
  101. package/src/runtime/providers-setup.js +187 -187
  102. package/src/runtime/raccoon-checkin.js +175 -175
  103. package/src/server.js +85 -85
  104. package/src/state/schemas/allowlist.js +92 -92
  105. package/src/sync-opencode.js +280 -280
  106. package/src/transport/index.js +244 -244
  107. package/src/transport/pool.js +56 -56
  108. package/src/transport/retry.js +24 -24
  109. package/src/transport/sse.js +93 -93
  110. package/src/upstream-probe/display.js +52 -52
  111. package/src/upstream-probe/probe.js +49 -49
  112. package/src/upstream-probe/rotate.js +110 -110
  113. package/src/upstream-probe/start.js +45 -45
  114. package/src/upstream.js +355 -355
  115. package/docs/cli_help_mini.md +0 -148
  116. package/src/providers/AGENTS.md +0 -49
  117. package/src/routes/AGENTS.md +0 -37
package/src/chat/repl.js CHANGED
@@ -1,88 +1,88 @@
1
- import { buildSystemPrompt, getModelsForPrompt } from "./prompt.js";
2
- import { getToolDefs, execCommand, readFileTool, curlTool } from "./tools.js";
3
- import { chatWithFallback, summarizeHistory } from "./upstream.js";
4
- import { loadHistory, saveHistory, histPath } from "./store.js";
5
- import { CHAT_PREFERRED } from "./config.js";
6
- import { createEngine } from "./engine.js";
7
- import { printBanner, printFooter, handleSlash, createReadline, createSpinner, estimateChars } from "./terminal.js";
8
- import { assertChatNode } from "../readline-compat.js";
9
-
10
- function trace(line) {
11
- if (process.env.MSLXDFF_CHAT_TRACE === "0") return;
12
- console.log(`\x1b[90m· ${line}\x1b[0m`);
13
- }
14
-
15
- export async function startRepl({ singleShot } = {}) {
16
- if (!assertChatNode()) process.exit(1);
17
- const models = getModelsForPrompt();
18
- const system = buildSystemPrompt({ modelsOverride: models });
19
- let messages = [{ role: "system", content: system }];
20
- const hist = loadHistory();
21
- if (hist.length) {
22
- for (const h of hist) messages.push(h);
23
- console.log(`\x1b[90m[恢复] 已载入 ${hist.length} 条历史\x1b[0m`);
24
- }
25
- const engine = createEngine({
26
- chatWithFallback,
27
- summarizeHistory,
28
- getToolDefs,
29
- execCommand,
30
- readFileTool,
31
- curlTool,
32
- onTrace: trace,
33
- });
34
- let pinnedModel = null; // /model 锁定的模型:严格单模型,不通即报错(null=默认链)
35
-
36
- function applyPrompt() {
37
- const label = pinnedModel || CHAT_PREFERRED.split("-")[0];
38
- rl.setPrompt(`\x1b[36m${label}>\x1b[0m `);
39
- }
40
-
41
- if (singleShot) {
42
- const text = String(singleShot).trim();
43
- if (!text) return;
44
- const spinner = createSpinner("已发送给 AI,等待回复中");
45
- spinner.start();
46
- let r;
47
- try { r = await engine.runTurn(text, messages); } finally { spinner.stop(`\x1b[90m✓ AI 已回复\x1b[0m`); }
48
- console.log(r.text);
49
- if (r.model) printFooter(r);
50
- saveHistory(messages.slice(1));
51
- return;
52
- }
53
-
54
- await printBanner();
55
- const rl = createReadline(`\x1b[36m${CHAT_PREFERRED.split("-")[0]}>\x1b[0m `);
56
- applyPrompt();
57
- rl.prompt();
58
- for await (const line of rl) {
59
- const raw = String(line || "").trim();
60
- if (!raw) { rl.prompt(); continue; }
61
- const slash = handleSlash(raw, { messages, system, pinnedModel });
62
- if (slash.handled) {
63
- if (slash.exit) { console.log("再见"); saveHistory(messages.slice(1)); rl.close(); return; }
64
- if (slash.messages) messages = slash.messages;
65
- if ("pinnedModel" in slash) { pinnedModel = slash.pinnedModel; applyPrompt(); }
66
- rl.prompt();
67
- continue;
68
- }
69
- try {
70
- const spinner = createSpinner(pinnedModel ? `已发送给 ${pinnedModel},等待回复中` : "已发送给 AI,等待回复中");
71
- spinner.start();
72
- let r;
73
- try { r = await engine.runTurn(raw, messages, pinnedModel); }
74
- finally { spinner.stop(`\x1b[90m✓ AI 已回复\x1b[0m`); }
75
- if (r.text && !r.text.startsWith("OK") && !r.text.startsWith("FAIL")) console.log(r.text);
76
- if (r.model || r.latency) printFooter(r);
77
- } catch (e) {
78
- console.log(`\x1b[31m[错误] ${String(e.message || e).slice(0, 800)}\x1b[0m`);
79
- messages.push({ role: "assistant", content: `error: ${String(e.message || e)}` });
80
- }
81
- saveHistory(messages.slice(1));
82
- if (messages.length > 2) {
83
- const maybe = await engine.maybeCompress(messages);
84
- if (maybe.length !== messages.length) { messages = maybe; saveHistory(messages.slice(1)); }
85
- }
86
- rl.prompt();
87
- }
88
- }
1
+ import { buildSystemPrompt, getModelsForPrompt } from "./prompt.js";
2
+ import { getToolDefs, execCommand, readFileTool, curlTool } from "./tools.js";
3
+ import { chatWithFallback, summarizeHistory } from "./upstream.js";
4
+ import { loadHistory, saveHistory, histPath } from "./store.js";
5
+ import { CHAT_PREFERRED } from "./config.js";
6
+ import { createEngine } from "./engine.js";
7
+ import { printBanner, printFooter, handleSlash, createReadline, createSpinner, estimateChars } from "./terminal.js";
8
+ import { assertChatNode } from "../readline-compat.js";
9
+
10
+ function trace(line) {
11
+ if (process.env.MSLXDFF_CHAT_TRACE === "0") return;
12
+ console.log(`\x1b[90m· ${line}\x1b[0m`);
13
+ }
14
+
15
+ export async function startRepl({ singleShot } = {}) {
16
+ if (!assertChatNode()) process.exit(1);
17
+ const models = getModelsForPrompt();
18
+ const system = buildSystemPrompt({ modelsOverride: models });
19
+ let messages = [{ role: "system", content: system }];
20
+ const hist = loadHistory();
21
+ if (hist.length) {
22
+ for (const h of hist) messages.push(h);
23
+ console.log(`\x1b[90m[恢复] 已载入 ${hist.length} 条历史\x1b[0m`);
24
+ }
25
+ const engine = createEngine({
26
+ chatWithFallback,
27
+ summarizeHistory,
28
+ getToolDefs,
29
+ execCommand,
30
+ readFileTool,
31
+ curlTool,
32
+ onTrace: trace,
33
+ });
34
+ let pinnedModel = null; // /model 锁定的模型:严格单模型,不通即报错(null=默认链)
35
+
36
+ function applyPrompt() {
37
+ const label = pinnedModel || CHAT_PREFERRED.split("-")[0];
38
+ rl.setPrompt(`\x1b[36m${label}>\x1b[0m `);
39
+ }
40
+
41
+ if (singleShot) {
42
+ const text = String(singleShot).trim();
43
+ if (!text) return;
44
+ const spinner = createSpinner("已发送给 AI,等待回复中");
45
+ spinner.start();
46
+ let r;
47
+ try { r = await engine.runTurn(text, messages); } finally { spinner.stop(`\x1b[90m✓ AI 已回复\x1b[0m`); }
48
+ console.log(r.text);
49
+ if (r.model) printFooter(r);
50
+ saveHistory(messages.slice(1));
51
+ return;
52
+ }
53
+
54
+ await printBanner();
55
+ const rl = createReadline(`\x1b[36m${CHAT_PREFERRED.split("-")[0]}>\x1b[0m `);
56
+ applyPrompt();
57
+ rl.prompt();
58
+ for await (const line of rl) {
59
+ const raw = String(line || "").trim();
60
+ if (!raw) { rl.prompt(); continue; }
61
+ const slash = handleSlash(raw, { messages, system, pinnedModel });
62
+ if (slash.handled) {
63
+ if (slash.exit) { console.log("再见"); saveHistory(messages.slice(1)); rl.close(); return; }
64
+ if (slash.messages) messages = slash.messages;
65
+ if ("pinnedModel" in slash) { pinnedModel = slash.pinnedModel; applyPrompt(); }
66
+ rl.prompt();
67
+ continue;
68
+ }
69
+ try {
70
+ const spinner = createSpinner(pinnedModel ? `已发送给 ${pinnedModel},等待回复中` : "已发送给 AI,等待回复中");
71
+ spinner.start();
72
+ let r;
73
+ try { r = await engine.runTurn(raw, messages, pinnedModel); }
74
+ finally { spinner.stop(`\x1b[90m✓ AI 已回复\x1b[0m`); }
75
+ if (r.text && !r.text.startsWith("OK") && !r.text.startsWith("FAIL")) console.log(r.text);
76
+ if (r.model || r.latency) printFooter(r);
77
+ } catch (e) {
78
+ console.log(`\x1b[31m[错误] ${String(e.message || e).slice(0, 800)}\x1b[0m`);
79
+ messages.push({ role: "assistant", content: `error: ${String(e.message || e)}` });
80
+ }
81
+ saveHistory(messages.slice(1));
82
+ if (messages.length > 2) {
83
+ const maybe = await engine.maybeCompress(messages);
84
+ if (maybe.length !== messages.length) { messages = maybe; saveHistory(messages.slice(1)); }
85
+ }
86
+ rl.prompt();
87
+ }
88
+ }
@@ -1,135 +1,135 @@
1
- import { createInterface } from "../readline-compat.js";
2
- import { stdin, stdout } from "node:process";
3
- import { formatBannerLines, formatStatsDetail, collectStats, probeGateway } from "./stats.js";
4
- import { createSpinner } from "./spinner.js";
5
- import { normalizeFullId } from "../providers/model-id.js";
6
- import { isFreeModel } from "../models.js";
7
- import { getModelsForPrompt } from "./prompt.js";
8
- import { loadHistory, saveHistory, clearHistory, histPath, estimateChars } from "./store.js";
9
-
10
- // -chat 只用 opencode 上游的免费模型:裸 id(无供应商前缀)+ free 池
11
- const FALLBACK_FREE_POOL = ["big-pickle", "mimo-v2.5-free", "ling-3.0-flash-fin-free", "deepseek-v4-flash-free", "nemotron-3.5-lightning-free", "nemotron-3-ultra-free", "muse-spark-1.3-contributor-free", "muse-spark-1.2-contributor-free"];
12
-
13
- function freePoolNow() {
14
- try {
15
- const ids = getModelsForPrompt().filter((id) => typeof id === "string" && !id.includes("/") && isFreeModel(id));
16
- if (ids.length) return ids;
17
- } catch {}
18
- return FALLBACK_FREE_POOL;
19
- }
20
-
21
- export const SLASH_HELP = `自然语言直接说,斜杠快捷:
22
- /help 本帮助
23
- /model 查看/锁定模型(仅限 opencode free 池;锁定后严格只用该模型,不通即报错)
24
- /model mimo-v2.5-free 锁定 · /model auto 解除锁定(回默认 mimo→pickle→auto 链)
25
- /stats 详细统计(网关 -d 的请求/延迟/模型)
26
- /history 查看对话历史
27
- /clear 清空历史
28
- /exit 退出
29
- 示例:设置 hy3 为默认模型 / 查看组列表 / 看最近20条日志 / 读一下 src/logs.js`;
30
-
31
- export async function printBanner() {
32
- let probe = null;
33
- try {
34
- const s = collectStats();
35
- probe = await probeGateway(s.port, 800);
36
- } catch {}
37
- const { lines } = formatBannerLines(probe);
38
- for (const l of lines) console.log(l);
39
- if (probe && !probe.alive) console.log(`\x1b[31m本地服务没有启动无法使用auto模式,请mslxdff -d 启动\x1b[0m`);
40
- console.log(`\x1b[90m输入自然语言即可执行;/help 帮助,/stats 看网关统计,/exit 退出\x1b[0m`);
41
- console.log(`\x1b[90m历史:${histPath()} · 仅拦截 -uninstall · 数据来自网关 -d,非本会话计数\x1b[0m`);
42
- }
43
-
44
- export function printFooter({ model, provider, latency, usage, totalMs, fallback, fallbackGateway, viaGateway }) {
45
- const dim = "\x1b[90m";
46
- const rst = "\x1b[0m";
47
- let gw = null;
48
- try { gw = collectStats(); } catch {}
49
- const prov = provider && provider !== "opencode" ? `${provider}/` : "";
50
- const baseLabel = model ? `${prov}${model}` : "—";
51
- const via = provider && !baseLabel.startsWith(`${provider}/`) ? `: ${provider}` : "";
52
- const modelLabel = model ? (fallbackGateway || viaGateway ? `${baseLabel} (gateway auto${via})` : baseLabel) : "—";
53
- const latLabel = latency ? `${latency}ms` : "—";
54
- const totalLabel = totalMs ? ` · 总耗时 ${totalMs}ms` : "";
55
- const tokLabel = usage ? ` · tokens ${usage.prompt_tokens ?? "?"}→${usage.completion_tokens ?? "?"}` : "";
56
- const fbLabel = fallbackGateway || viaGateway ? " · gateway-fallback" : fallback ? " · fallback" : "";
57
- let gwLabel = "";
58
- let extra = "";
59
- if (gw) {
60
- const full = (() => { try { return normalizeFullId(model); } catch { return model; } })();
61
- const stat = gw.modelStats?.[full] || gw.modelStats?.[model] || null;
62
- const cnt = stat?.count ?? gw.latencies?.[model]?.count;
63
- const avgTtfb = stat?.avgTtfbMs ?? stat?.emaTtfbMs;
64
- const avgTps = stat?.avgTps ?? stat?.emaTps;
65
- const per = cnt ? ` · 网关该模型 ${cnt}次` : "";
66
- const ttfbLabel = avgTtfb ? ` 平均首字 ${avgTtfb}ms` : (gw.latencies?.[model]?.emaMs ? ` EMA ${gw.latencies[model].emaMs}ms` : "");
67
- const tpsLabel = avgTps ? ` · ${avgTps} tok/s` : "";
68
- const verbose = stat?.avgCompTok ? ` · 啰嗦 ${stat.avgCompTok}tok/次` : "";
69
- gwLabel = ` · 网关 总${gw.total} 成功${gw.success} 失败${gw.fail}${per}${ttfbLabel}${tpsLabel}${verbose}`;
70
- if (usage?.completion_tokens && latency) {
71
- const tpsNow = Math.round(usage.completion_tokens / (latency / 1000));
72
- if (Number.isFinite(tpsNow) && tpsNow > 0) extra = ` · 本次首字 ~${latency}ms · ${tpsNow} tok/s`;
73
- }
74
- }
75
- console.log(`${dim}─ ${modelLabel} ${latLabel}${totalLabel}${tokLabel}${fbLabel}${gwLabel}${extra}${rst}`);
76
- }
77
-
78
- export function handleSlash(line, ctx) {
79
- const raw = String(line || "").trim();
80
- const low = raw.toLowerCase();
81
- if (["/help", "help", "/h", "?"].includes(low)) {
82
- console.log(SLASH_HELP);
83
- return { handled: true };
84
- }
85
- if (low.startsWith("/model")) {
86
- const arg = raw.slice(6).trim();
87
- if (!arg) {
88
- if (ctx.pinnedModel) console.log(`\x1b[36m当前锁定模型:${ctx.pinnedModel}(严格单模型,不通即报错)\x1b[0m`);
89
- else console.log(`\x1b[90m未锁定模型 · 默认链:mimo-v2.5-free → big-pickle → 网关 auto\x1b[0m`);
90
- return { handled: true };
91
- }
92
- if (arg === "auto" || arg === "clear" || arg === "off" || arg === "解锁" || arg === "解除") {
93
- console.log(`\x1b[90m已解除模型锁定 · 回默认链:mimo-v2.5-free → big-pickle → 网关 auto\x1b[0m`);
94
- return { handled: true, pinnedModel: null };
95
- }
96
- const id = arg;
97
- if (id.includes("/")) {
98
- console.log(`\x1b[31m[拒绝] ${id} 带供应商前缀 — -chat 只支持 opencode 上游模型(裸 id,直连 opencode.ai 免费池)\x1b[0m`);
99
- console.log(`\x1b[90m其他供应商(deepseek/ workbuddy/ cline/ 等)请走网关:mslxdff -model set <id> 或 curl 本机 /v1/chat/completions\x1b[0m`);
100
- return { handled: true };
101
- }
102
- if (!isFreeModel(id) || !freePoolNow().includes(id)) {
103
- console.log(`\x1b[31m[拒绝] ${id} 不在 opencode free 池 — -chat 只能用 opencode 免费模型\x1b[0m`);
104
- console.log(`\x1b[90m当前 free 池:${freePoolNow().join(", ")}\x1b[0m`);
105
- return { handled: true };
106
- }
107
- console.log(`\x1b[36m[已锁定] ${id} · 严格只用该模型,不通即报错(不自动换模型)· 解除:/model auto\x1b[0m`);
108
- return { handled: true, pinnedModel: id };
109
- }
110
- if (["/stats", "/status", "stats", "status"].includes(low)) {
111
- console.log(formatStatsDetail());
112
- return { handled: true };
113
- }
114
- if (["/clear", "clear"].includes(low)) {
115
- clearHistory();
116
- ctx.messages = [{ role: "system", content: ctx.system }];
117
- console.log("\x1b[90m[已清空历史]\x1b[0m");
118
- return { handled: true, messages: ctx.messages };
119
- }
120
- if (["/history"].includes(low)) {
121
- console.log(`\x1b[90m历史 ${ctx.messages.length - 1} 条,约 ${estimateChars(ctx.messages)} 字符 · ${histPath()}\x1b[0m`);
122
- for (const m of ctx.messages.slice(1).slice(-10)) console.log(`- ${m.role}: ${(m.content || "").slice(0, 120)}`);
123
- return { handled: true };
124
- }
125
- if (["/exit", "/quit", "exit", "quit", "退出"].includes(low)) {
126
- return { handled: true, exit: true };
127
- }
128
- return { handled: false };
129
- }
130
-
131
- export function createReadline(promptStr) {
132
- return createInterface({ input: stdin, output: stdout, prompt: promptStr });
133
- }
134
-
135
- export { createSpinner, loadHistory, saveHistory, histPath, estimateChars };
1
+ import { createInterface } from "../readline-compat.js";
2
+ import { stdin, stdout } from "node:process";
3
+ import { formatBannerLines, formatStatsDetail, collectStats, probeGateway } from "./stats.js";
4
+ import { createSpinner } from "./spinner.js";
5
+ import { normalizeFullId } from "../providers/model-id.js";
6
+ import { isFreeModel } from "../models.js";
7
+ import { getModelsForPrompt } from "./prompt.js";
8
+ import { loadHistory, saveHistory, clearHistory, histPath, estimateChars } from "./store.js";
9
+
10
+ // -chat 只用 opencode 上游的免费模型:裸 id(无供应商前缀)+ free 池
11
+ const FALLBACK_FREE_POOL = ["big-pickle", "mimo-v2.5-free", "ling-3.0-flash-fin-free", "deepseek-v4-flash-free", "nemotron-3.5-lightning-free", "nemotron-3-ultra-free", "muse-spark-1.3-contributor-free", "muse-spark-1.2-contributor-free"];
12
+
13
+ function freePoolNow() {
14
+ try {
15
+ const ids = getModelsForPrompt().filter((id) => typeof id === "string" && !id.includes("/") && isFreeModel(id));
16
+ if (ids.length) return ids;
17
+ } catch {}
18
+ return FALLBACK_FREE_POOL;
19
+ }
20
+
21
+ export const SLASH_HELP = `自然语言直接说,斜杠快捷:
22
+ /help 本帮助
23
+ /model 查看/锁定模型(仅限 opencode free 池;锁定后严格只用该模型,不通即报错)
24
+ /model mimo-v2.5-free 锁定 · /model auto 解除锁定(回默认 mimo→pickle→auto 链)
25
+ /stats 详细统计(网关 -d 的请求/延迟/模型)
26
+ /history 查看对话历史
27
+ /clear 清空历史
28
+ /exit 退出
29
+ 示例:设置 hy3 为默认模型 / 查看组列表 / 看最近20条日志 / 读一下 src/logs.js`;
30
+
31
+ export async function printBanner() {
32
+ let probe = null;
33
+ try {
34
+ const s = collectStats();
35
+ probe = await probeGateway(s.port, 800);
36
+ } catch {}
37
+ const { lines } = formatBannerLines(probe);
38
+ for (const l of lines) console.log(l);
39
+ if (probe && !probe.alive) console.log(`\x1b[31m本地服务没有启动无法使用auto模式,请mslxdff -d 启动\x1b[0m`);
40
+ console.log(`\x1b[90m输入自然语言即可执行;/help 帮助,/stats 看网关统计,/exit 退出\x1b[0m`);
41
+ console.log(`\x1b[90m历史:${histPath()} · 仅拦截 -uninstall · 数据来自网关 -d,非本会话计数\x1b[0m`);
42
+ }
43
+
44
+ export function printFooter({ model, provider, latency, usage, totalMs, fallback, fallbackGateway, viaGateway }) {
45
+ const dim = "\x1b[90m";
46
+ const rst = "\x1b[0m";
47
+ let gw = null;
48
+ try { gw = collectStats(); } catch {}
49
+ const prov = provider && provider !== "opencode" ? `${provider}/` : "";
50
+ const baseLabel = model ? `${prov}${model}` : "—";
51
+ const via = provider && !baseLabel.startsWith(`${provider}/`) ? `: ${provider}` : "";
52
+ const modelLabel = model ? (fallbackGateway || viaGateway ? `${baseLabel} (gateway auto${via})` : baseLabel) : "—";
53
+ const latLabel = latency ? `${latency}ms` : "—";
54
+ const totalLabel = totalMs ? ` · 总耗时 ${totalMs}ms` : "";
55
+ const tokLabel = usage ? ` · tokens ${usage.prompt_tokens ?? "?"}→${usage.completion_tokens ?? "?"}` : "";
56
+ const fbLabel = fallbackGateway || viaGateway ? " · gateway-fallback" : fallback ? " · fallback" : "";
57
+ let gwLabel = "";
58
+ let extra = "";
59
+ if (gw) {
60
+ const full = (() => { try { return normalizeFullId(model); } catch { return model; } })();
61
+ const stat = gw.modelStats?.[full] || gw.modelStats?.[model] || null;
62
+ const cnt = stat?.count ?? gw.latencies?.[model]?.count;
63
+ const avgTtfb = stat?.avgTtfbMs ?? stat?.emaTtfbMs;
64
+ const avgTps = stat?.avgTps ?? stat?.emaTps;
65
+ const per = cnt ? ` · 网关该模型 ${cnt}次` : "";
66
+ const ttfbLabel = avgTtfb ? ` 平均首字 ${avgTtfb}ms` : (gw.latencies?.[model]?.emaMs ? ` EMA ${gw.latencies[model].emaMs}ms` : "");
67
+ const tpsLabel = avgTps ? ` · ${avgTps} tok/s` : "";
68
+ const verbose = stat?.avgCompTok ? ` · 啰嗦 ${stat.avgCompTok}tok/次` : "";
69
+ gwLabel = ` · 网关 总${gw.total} 成功${gw.success} 失败${gw.fail}${per}${ttfbLabel}${tpsLabel}${verbose}`;
70
+ if (usage?.completion_tokens && latency) {
71
+ const tpsNow = Math.round(usage.completion_tokens / (latency / 1000));
72
+ if (Number.isFinite(tpsNow) && tpsNow > 0) extra = ` · 本次首字 ~${latency}ms · ${tpsNow} tok/s`;
73
+ }
74
+ }
75
+ console.log(`${dim}─ ${modelLabel} ${latLabel}${totalLabel}${tokLabel}${fbLabel}${gwLabel}${extra}${rst}`);
76
+ }
77
+
78
+ export function handleSlash(line, ctx) {
79
+ const raw = String(line || "").trim();
80
+ const low = raw.toLowerCase();
81
+ if (["/help", "help", "/h", "?"].includes(low)) {
82
+ console.log(SLASH_HELP);
83
+ return { handled: true };
84
+ }
85
+ if (low.startsWith("/model")) {
86
+ const arg = raw.slice(6).trim();
87
+ if (!arg) {
88
+ if (ctx.pinnedModel) console.log(`\x1b[36m当前锁定模型:${ctx.pinnedModel}(严格单模型,不通即报错)\x1b[0m`);
89
+ else console.log(`\x1b[90m未锁定模型 · 默认链:mimo-v2.5-free → big-pickle → 网关 auto\x1b[0m`);
90
+ return { handled: true };
91
+ }
92
+ if (arg === "auto" || arg === "clear" || arg === "off" || arg === "解锁" || arg === "解除") {
93
+ console.log(`\x1b[90m已解除模型锁定 · 回默认链:mimo-v2.5-free → big-pickle → 网关 auto\x1b[0m`);
94
+ return { handled: true, pinnedModel: null };
95
+ }
96
+ const id = arg;
97
+ if (id.includes("/")) {
98
+ console.log(`\x1b[31m[拒绝] ${id} 带供应商前缀 — -chat 只支持 opencode 上游模型(裸 id,直连 opencode.ai 免费池)\x1b[0m`);
99
+ console.log(`\x1b[90m其他供应商(deepseek/ workbuddy/ cline/ 等)请走网关:mslxdff -model set <id> 或 curl 本机 /v1/chat/completions\x1b[0m`);
100
+ return { handled: true };
101
+ }
102
+ if (!isFreeModel(id) || !freePoolNow().includes(id)) {
103
+ console.log(`\x1b[31m[拒绝] ${id} 不在 opencode free 池 — -chat 只能用 opencode 免费模型\x1b[0m`);
104
+ console.log(`\x1b[90m当前 free 池:${freePoolNow().join(", ")}\x1b[0m`);
105
+ return { handled: true };
106
+ }
107
+ console.log(`\x1b[36m[已锁定] ${id} · 严格只用该模型,不通即报错(不自动换模型)· 解除:/model auto\x1b[0m`);
108
+ return { handled: true, pinnedModel: id };
109
+ }
110
+ if (["/stats", "/status", "stats", "status"].includes(low)) {
111
+ console.log(formatStatsDetail());
112
+ return { handled: true };
113
+ }
114
+ if (["/clear", "clear"].includes(low)) {
115
+ clearHistory();
116
+ ctx.messages = [{ role: "system", content: ctx.system }];
117
+ console.log("\x1b[90m[已清空历史]\x1b[0m");
118
+ return { handled: true, messages: ctx.messages };
119
+ }
120
+ if (["/history"].includes(low)) {
121
+ console.log(`\x1b[90m历史 ${ctx.messages.length - 1} 条,约 ${estimateChars(ctx.messages)} 字符 · ${histPath()}\x1b[0m`);
122
+ for (const m of ctx.messages.slice(1).slice(-10)) console.log(`- ${m.role}: ${(m.content || "").slice(0, 120)}`);
123
+ return { handled: true };
124
+ }
125
+ if (["/exit", "/quit", "exit", "quit", "退出"].includes(low)) {
126
+ return { handled: true, exit: true };
127
+ }
128
+ return { handled: false };
129
+ }
130
+
131
+ export function createReadline(promptStr) {
132
+ return createInterface({ input: stdin, output: stdout, prompt: promptStr });
133
+ }
134
+
135
+ export { createSpinner, loadHistory, saveHistory, histPath, estimateChars };