mslxdff 0.1.173 → 0.1.175

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 (122) hide show
  1. package/bin/mslxdff.js +3 -3
  2. package/package.json +1 -1
  3. package/src/auto.js +254 -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/auto-race.js +26 -1
  19. package/src/chat-pipeline/index.js +131 -131
  20. package/src/chat-pipeline/policy.js +84 -76
  21. package/src/chat-pipeline/serial-trial.js +35 -8
  22. package/src/chat-pipeline/terminal-verdict.js +109 -0
  23. package/src/claude-desktop/apply.js +42 -5
  24. package/src/claude-desktop/context1m.js +38 -0
  25. package/src/claude-desktop/slots.js +66 -0
  26. package/src/cli/commands/claude-desktop.js +27 -7
  27. package/src/cli/commands/group.js +249 -249
  28. package/src/cli/commands/model/picks.js +50 -50
  29. package/src/cli/commands/provider/bench-via.js +247 -247
  30. package/src/cli/commands/provider/bench.js +141 -141
  31. package/src/cli/commands/provider/index.js +136 -133
  32. package/src/cli/commands/provider/keys-guard.js +50 -0
  33. package/src/cli/commands/provider/keys.js +7 -0
  34. package/src/cli/commands/provider/models.js +145 -145
  35. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  36. package/src/cli/commands/provider/traework-checkin.js +144 -0
  37. package/src/cli/commands/provider/traework-login.js +7 -45
  38. package/src/cli/commands/sync.js +310 -310
  39. package/src/cli/help.js +4 -1
  40. package/src/cli/status.js +279 -279
  41. package/src/daemon.js +112 -112
  42. package/src/model-capabilities/enrich.js +86 -86
  43. package/src/model-capabilities/index.js +183 -183
  44. package/src/model-capabilities/parse.js +70 -70
  45. package/src/model-trace.js +2 -0
  46. package/src/models.js +225 -225
  47. package/src/opencode-identity.js +39 -19
  48. package/src/providers/cline/auth.js +228 -228
  49. package/src/providers/cline/chat.js +307 -307
  50. package/src/providers/cline.js +2 -2
  51. package/src/providers/codearts/chat.js +7 -1
  52. package/src/providers/codearts/const.js +6 -1
  53. package/src/providers/codearts/index.js +18 -11
  54. package/src/providers/globalqwenwork/cosy.js +123 -123
  55. package/src/providers/globalqwenwork/crypto.js +218 -218
  56. package/src/providers/globalqwenwork/http.js +20 -20
  57. package/src/providers/globalqwenwork/rsa.js +54 -54
  58. package/src/providers/globalqwenwork/sse.js +268 -268
  59. package/src/providers/globalqwenwork/stream.js +130 -130
  60. package/src/providers/globalqwenwork/upstream.js +122 -122
  61. package/src/providers/keyring.js +60 -60
  62. package/src/providers/qoder/chat.js +203 -203
  63. package/src/providers/qoder/index.js +249 -249
  64. package/src/providers/qoder/sse.js +145 -145
  65. package/src/providers/qwenwork/account-store.js +133 -133
  66. package/src/providers/qwenwork/constants.js +67 -67
  67. package/src/providers/qwenwork/cosy.js +120 -120
  68. package/src/providers/qwenwork/crypto.js +218 -218
  69. package/src/providers/qwenwork/http.js +20 -20
  70. package/src/providers/qwenwork/index.js +327 -327
  71. package/src/providers/qwenwork/payload.js +144 -144
  72. package/src/providers/qwenwork/rsa.js +54 -54
  73. package/src/providers/qwenwork/sse.js +268 -268
  74. package/src/providers/qwenwork/stream.js +130 -130
  75. package/src/providers/qwenwork/upstream.js +120 -120
  76. package/src/providers/qwenwork.js +1 -1
  77. package/src/providers/registry.js +79 -79
  78. package/src/providers/traework/account-store.js +87 -2
  79. package/src/providers/traework/checkin.js +51 -9
  80. package/src/providers/traework/constants.js +20 -0
  81. package/src/providers/traework/headers.js +42 -10
  82. package/src/providers/traework/index.js +14 -4
  83. package/src/providers/traework/market-identity.js +116 -0
  84. package/src/providers/workbuddy/chat.js +248 -248
  85. package/src/providers/workbuddy/reshape.js +152 -152
  86. package/src/providers/workbuddy.js +2 -2
  87. package/src/reasoning.js +32 -32
  88. package/src/routes/chat/gateway.js +46 -46
  89. package/src/routes/chat/relay-pipeline.js +294 -294
  90. package/src/routes/chat/via-route-handler.js +146 -146
  91. package/src/routes/hedge.js +255 -255
  92. package/src/routes/models-route.js +167 -167
  93. package/src/routes/peers.js +273 -273
  94. package/src/routes/stream.js +385 -385
  95. package/src/runtime/bootstrap.js +50 -50
  96. package/src/runtime/provider-gate.js +36 -36
  97. package/src/runtime/providers-setup.js +168 -165
  98. package/src/runtime/traework-checkin.js +26 -11
  99. package/src/server.js +69 -69
  100. package/src/state/schemas/allowlist.js +92 -92
  101. package/src/sync-opencode.js +280 -280
  102. package/src/transport/index.js +244 -244
  103. package/src/transport/pool.js +56 -56
  104. package/src/transport/retry.js +24 -24
  105. package/src/transport/sse.js +93 -93
  106. package/src/upstream-probe/display.js +52 -52
  107. package/src/upstream-probe/probe.js +49 -49
  108. package/src/upstream-probe/rotate.js +110 -110
  109. package/src/upstream-probe/start.js +45 -45
  110. package/src/upstream.js +291 -289
  111. package/src/warp-pool/config.js +71 -0
  112. package/src/warp-pool/health.js +65 -0
  113. package/src/warp-pool/index.js +252 -0
  114. package/src/warp-pool/keys.js +29 -0
  115. package/src/warp-pool/nodes.js +94 -0
  116. package/src/warp-pool/register.js +113 -0
  117. package/src/warp-pool/rotate.js +150 -0
  118. package/src/warp-pool/strategy.js +43 -0
  119. package/src/warp-pool/wireproxy.js +153 -0
  120. package/docs/cli_help_mini.md +0 -143
  121. package/src/providers/AGENTS.md +0 -49
  122. 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 };