mslxdff 0.1.107 → 0.1.109

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mslxdff",
3
- "version": "0.1.107",
3
+ "version": "0.1.109",
4
4
  "description": "测试项目,请勿使用。",
5
5
  "type": "module",
6
6
  "bin": {
@@ -4,6 +4,7 @@ import { planRoute } from "./planner.js";
4
4
  import { createEngine } from "./engine.js";
5
5
  import { runHook } from "../plugins.js";
6
6
  import { isFreeModel } from "../models.js";
7
+ import { shouldUseGroupForModel } from "../state/schemas/use-group.js";
7
8
  import { clientIp, summarizePrompt } from "../routes/helpers.js";
8
9
 
9
10
  /**
@@ -85,7 +86,7 @@ export function createChatPipeline({ upstream, auto, logs, peers, groups, bus, t
85
86
 
86
87
  const plan = planRoute(policy, {
87
88
  candidates: order,
88
- viaRoute: Boolean(!useAuto && requested.includes("/") && canForwardPeers) ? { via: true } : null,
89
+ viaRoute: Boolean(!useAuto && requested.includes("/") && canForwardPeers && shouldUseGroupForModel(requested)) ? { via: true } : null,
89
90
  });
90
91
  await engine.run(plan, {
91
92
  reqId, startedAt, req, res, body: req?.body, policy,
@@ -35,7 +35,7 @@ export async function runSerialTrial(ctx, deps = {}) {
35
35
  const workbuddyUid = ctx.workbuddyUid ?? ctx.policy?.workbuddyUid ?? null;
36
36
 
37
37
  let viaRouteLastErr = null;
38
- if (!useAuto && requested && requested.includes("/") && canForwardPeers && !lockModel && peers) {
38
+ if (!useAuto && requested && requested.includes("/") && canForwardPeers && !lockModel && peers && shouldUseGroupForModel(requested)) {
39
39
  try {
40
40
  const vr = await viaRoute({ model: requested, body, peers, handlerCtx, evt, logCall, logError, mark, perf0, stages, startedAt, plugins, res, requested, useAuto, lockModel, auto });
41
41
  if (vr.handled) return { done: true };
@@ -131,7 +131,7 @@ export async function runSerialTrial(ctx, deps = {}) {
131
131
  }
132
132
  if (canForwardPeers) {
133
133
  if (!shouldUseGroupForModel(model)) {
134
- evt("group-skip", { reqId, model, reason: "useGroup=off for opencode (peer)" });
134
+ evt("group-skip", { reqId, model, reason: "useGroup=off (peer)" });
135
135
  } else {
136
136
  const pr = await peerRelay({ model, body, lastErr, requested, useAuto, lockModel, auto, peers, handlerCtx, evt, logCall, mark, perf0, stages, startedAt, plugins, res });
137
137
  if (pr.handled) return { done: true };
@@ -139,7 +139,7 @@ export async function runSerialTrial(ctx, deps = {}) {
139
139
  }
140
140
  if (groups) {
141
141
  if (!shouldUseGroupForModel(model)) {
142
- evt("group-skip", { reqId, model, reason: "useGroup=off for opencode (broadband)" });
142
+ evt("group-skip", { reqId, model, reason: "useGroup=off (broadband)" });
143
143
  } else {
144
144
  const br = await broadbandRelay({ model, body, hops, lastErr, requested, useAuto, lockModel, auto, groups, token, bus, logs, handlerCtx, evt, mark, perf0, stages, res, startedAt, plugins });
145
145
  if (br.handled) return { done: true };
@@ -33,7 +33,7 @@ export async function handleUseGroup(args) {
33
33
  console.log(` stored: ${stored ? "on" : "off"} (state.json useGroup)`);
34
34
  if (envVal !== null) console.log(` env MSLXDFF_USE_GROUP=${envVal ? "on" : "off"} (overrides stored)`);
35
35
  console.log(` default: on`);
36
- console.log(` usage: mslxdff -use-group on|off (opencode 供应商本机失败时是否走组员网络,默认 on)`);
36
+ console.log(` usage: mslxdff -use-group on|off (本机失败时是否走组员网络,默认 on)`);
37
37
  console.log(` env: MSLXDFF_USE_GROUP=0|1 (优先级高于 state)`);
38
38
  process.exit(0);
39
39
  }
@@ -50,7 +50,7 @@ export async function handleUseGroup(args) {
50
50
 
51
51
  saveUseGroup(parsed);
52
52
  console.log(`use-group set to ${parsed ? "on" : "off"} (stored in state.json)`);
53
- console.log(` opencode 供应商:本机失败时 ${parsed ? "允许" : "不再"} 通过组员网络请求上游`);
54
- if (!parsed) console.log(` 提示:opencode 请求将仅在本机重试,不再走 peer/broadband 组员中继`);
53
+ console.log(` ${parsed ? "允许" : "不再允许"}走组员网络(via-route/hedge/peer/broadband,全部供应商)`);
54
+ if (!parsed) console.log(` 提示:所有请求将仅在本机重试,不再走组员中继`);
55
55
  process.exit(0);
56
56
  }
package/src/cli/help.js CHANGED
@@ -43,7 +43,7 @@ Usage:
43
43
  mslxdff -autostart status 查看自启状态
44
44
  mslxdff -chat ["prompt"] chat REPL(mimo-v2.5-free 优先/big-pickle 兜底,自然语言转命令,模糊匹配由模型完成,历史持久化,超长自动压缩,仅拦 -uninstall,daemon 重启不影响)
45
45
  mslxdff -resetban [ip] clear join-failure bans (all, or one ip)
46
- mslxdff -use-group [on|off] opencode 供应商本机失败时是否走组员网络(默认 on;off 则仅本机,MSLXDFF_USE_GROUP 环境变量可覆盖)
46
+ mslxdff -use-group [on|off] 本机失败时是否走组员网络(默认 on;off 则所有供应商仅本机,MSLXDFF_USE_GROUP 环境变量可覆盖)
47
47
  mslxdff -help show this help
48
48
 
49
49
  Environment:
@@ -63,7 +63,7 @@ Environment:
63
63
  MSLXDFF_BAN_THRESHOLD failed joins before an ip is banned (default 5)
64
64
  MSLXDFF_BAN_WINDOW_MS ban duration after too many failures (default 48h)
65
65
  MSLXDFF_HEDGE_DELAY_MS hedge peer race when local stream first chunk slow (default 1000, 0/off to disable)
66
- MSLXDFF_USE_GROUP opencode 组员中继开关(默认 on;0/off/false 关闭后 opencode 仅本机,不走 peer/broadband)
66
+ MSLXDFF_USE_GROUP 组员中继总开关(默认 on;0/off/false 关闭后所有供应商仅本机,不走 via-route/hedge/peer/broadband)
67
67
  MSLXDFF_AUTO_UPDATE auto-update: hourly by default, 0/off/false to disable, 1/true or ms
68
68
  MSLXDFF_AUTO_UPDATE_MS same as above, explicit ms (overrides AUTO_UPDATE)
69
69
  `);
@@ -19,6 +19,22 @@ export function parseCooldown(body, status) {
19
19
  return 60 * 1000;
20
20
  }
21
21
 
22
+ /**
23
+ * 真死 vs 假死:对标官方 getValidClineCredentials 契约——只有 invalid_grant
24
+ *(refresh token 被拒)才判死,需重新授权;网络抖动/5xx/超时是瞬时失败,
25
+ * 手里 token 仍有效时继续用,且绝不清掉已存凭证。
26
+ */
27
+ export function isInvalidGrant(bodyText, status) {
28
+ const t = String(bodyText || "").toLowerCase();
29
+ if (/invalid_grant|invalid_token/.test(t)) return true;
30
+ // 路由拼错/版本提示类 401("...latest version...re-authenticate your Cline account")
31
+ // 只是打错了地址,不是 token 死,绝不能判死,否则好号会被永久冷冻。
32
+ if (/latest version|re-authenticate/.test(t)) return false;
33
+ if ((status === 400 || status === 403) && /invalid|expired|revoked/.test(t)) return true;
34
+ if (status === 401 && /invalid_grant|invalid token|token[^.]{0,30}(expired|revoked|invalid)/.test(t)) return true;
35
+ return false;
36
+ }
37
+
22
38
  /**
23
39
  * 一次性 refresh:bench/诊断用,不落盘、不建池。
24
40
  * 返回 accessToken 或 null。
@@ -90,6 +106,7 @@ export function createAuthPool({
90
106
  for (let k = 0; k < list.length; k++) {
91
107
  const acc = list[accountIndex % list.length];
92
108
  accountIndex = (accountIndex + 1) % list.length;
109
+ if (acc.dead) continue;
93
110
  if (!acc.cooldownUntil || acc.cooldownUntil <= clock()) {
94
111
  currentAccount = acc;
95
112
  return acc;
@@ -100,9 +117,13 @@ export function createAuthPool({
100
117
 
101
118
  async function refreshOne(account) {
102
119
  const now = clock();
120
+ if (account.dead) throw new Error("invalid_grant");
103
121
  if (account.cooldownUntil > now) throw new Error("account_cooldown");
104
122
  if (account.accessToken && now < account.expiry) return account.accessToken;
105
- const url = joinUrl(resolvedBase, "/api/v1/auth/refresh");
123
+ // base 可能已含 /api/v1(state 里 clinebot baseUrl 就是 …/api/v1),直接拼会 double 成
124
+ // …/api/v1/api/v1/auth/refresh → 上游回 401 Unauthorized(版本/重认证提示),绝不能当 token 死。
125
+ const baseNoV1 = resolvedBase.replace(/\/api\/v1\/?$/, "");
126
+ const url = joinUrl(baseNoV1, "/api/v1/auth/refresh");
106
127
  const opts = {
107
128
  method: "POST",
108
129
  headers: { "Content-Type": "application/json" },
@@ -111,7 +132,12 @@ export function createAuthPool({
111
132
  if (dispatcher) opts.dispatcher = dispatcher;
112
133
  let res;
113
134
  try { res = await fetchImpl(url, opts); } catch { account.cooldownUntil = now + 60 * 1000; throw new Error("refresh_failed"); }
114
- if (!res.ok) { account.cooldownUntil = now + 60 * 1000; throw new Error("refresh_failed"); }
135
+ if (!res.ok) {
136
+ let t = "";
137
+ try { t = await res.text(); } catch {}
138
+ if (isInvalidGrant(t, res.status)) { account.dead = true; throw new Error("invalid_grant"); }
139
+ account.cooldownUntil = now + 60 * 1000; throw new Error("refresh_failed");
140
+ }
115
141
  let data;
116
142
  try { data = await res.json(); } catch { account.cooldownUntil = now + 60 * 1000; throw new Error("refresh_no_token"); }
117
143
  const accessToken = data?.data?.accessToken || data?.accessToken || data?.access_token;
@@ -138,11 +164,12 @@ export function createAuthPool({
138
164
  if (pool.length === 0) throw new Error("缺少 CLINE_REFRESH_TOKEN(请用 cline_oauth.py 获取)");
139
165
  for (let attempt = 0; attempt < pool.length; attempt++) {
140
166
  const acc = pool[attempt % pool.length];
167
+ if (acc.dead) continue;
141
168
  if (acc.cooldownUntil && acc.cooldownUntil > clock()) continue;
142
169
  currentAccount = acc;
143
170
  try { return await refreshOne(acc); } catch (e) { if (e.message === "account_cooldown") continue; continue; }
144
171
  }
145
- const acc = pool[0];
172
+ const acc = pool.find((a) => !a.dead) || null;
146
173
  if (!acc) throw new Error("无可用 Cline 账号");
147
174
  currentAccount = acc;
148
175
  acc.cooldownUntil = 0;
@@ -155,9 +155,14 @@ export function createChatService({
155
155
  const sessionId = genSessionId();
156
156
  const isStream = body?.stream === true;
157
157
  const upstreamModel = stripProviderPrefix(model);
158
+ // token 口径双写:对标官方 withMaxCompletionTokensForReasoningModels——
159
+ // cline 上游默认 reasoning_effort high,推理模型认 max_completion_tokens,
160
+ // 只发 max_tokens 会被部分通道拒;双写兼容最稳。
161
+ const tokLimit = body?.max_tokens || body?.max_completion_tokens || 4096;
158
162
  const upstreamBody = {
159
163
  model: upstreamModel,
160
- max_tokens: body?.max_tokens || body?.max_completion_tokens || 4096,
164
+ max_tokens: tokLimit,
165
+ max_completion_tokens: tokLimit,
161
166
  session_id: sessionId,
162
167
  reasoning_effort: body?.reasoning_effort || body?.reasoningEffort || "high",
163
168
  messages: body?.messages || [],
@@ -16,10 +16,34 @@ export function createModelsService({ id, baseUrl, modelsPath, fetchImpl, dispat
16
16
  let cache = null;
17
17
  let fetchedAt = 0;
18
18
 
19
+ // 离线兜底:对标官方 FALLBACK(free 数组实证含 z-ai/glm-5.3-flash)。
20
+ // 上游挂了/401 时也不返回空数组,保证 -provider clinebot models 与 picks 仍有免费可用。
21
+ const FALLBACK_FREE = [
22
+ { id: "deepseek/deepseek-v4-flash", name: "deepseek-v4-flash" },
23
+ { id: "z-ai/glm-5.3-flash", name: "glm-5.3-flash" },
24
+ { id: "poolside/laguna-s-2.1:free", name: "laguna-s-2.1:free" },
25
+ ];
26
+
27
+ function fallbackList() {
28
+ const out = FALLBACK_FREE.map((m) => ({ ...m, id: joinModelId(id, m.id) }));
29
+ cache = out; fetchedAt = Date.now();
30
+ return out;
31
+ }
32
+
33
+ // 端点归一化:官方取 {bareHost}/api/v1/ai/cline/recommended-models。
34
+ // baseUrl 可能是裸 host(https://api.cline.bot)也可能是带 /api/v1 的,
35
+ // 统一收敛到 …/api/v1/ai/cline/recommended-models;用户自定义 path 原样尊重。
36
+ function resolveModelsUrl() {
37
+ const custom = modelsPath && modelsPath !== "/models" && modelsPath !== "/ai/cline/recommended-models";
38
+ if (custom) return joinUrl(resolvedBase, resolvedPath);
39
+ const bare = resolvedBase.replace(/\/api\/v1\/?$/, "");
40
+ return joinUrl(bare, "/api/v1/ai/cline/recommended-models");
41
+ }
42
+
19
43
  async function listModels() {
20
44
  const now = Date.now();
21
45
  if (cache && now - fetchedAt < CACHE_TTL) return cache;
22
- const url = joinUrl(resolvedBase, resolvedPath);
46
+ const url = resolveModelsUrl();
23
47
  const controller = new AbortController();
24
48
  const timer = setTimeout(() => controller.abort(new Error(`${id} models timed out`)), 15_000);
25
49
  try {
@@ -29,20 +53,22 @@ export function createModelsService({ id, baseUrl, modelsPath, fetchImpl, dispat
29
53
  const opts = { headers, signal: controller.signal };
30
54
  if (dispatcher) opts.dispatcher = dispatcher;
31
55
  const res = await fetchImpl(url, opts);
32
- if (!res.ok) return [];
56
+ if (!res.ok) return fallbackList();
33
57
  const json = await res.json().catch(() => ({}));
34
58
  if (isClineBotHost(resolvedBase) && Array.isArray(json.free)) {
35
59
  const out = json.free.filter((m) => m && typeof m.id === "string").map((m) => ({ ...m, id: joinModelId(id, m.id) }));
60
+ if (!out.length) return fallbackList();
36
61
  cache = out; fetchedAt = now; return out;
37
62
  }
38
63
  const raw = Array.isArray(json.data) ? json.data : Array.isArray(json.models) ? json.models : Array.isArray(json) ? json : [];
39
64
  const out = raw.filter((m) => m && typeof m.id === "string").map((m) => ({ ...m, id: joinModelId(id, m.id) }));
65
+ if (!out.length) return fallbackList();
40
66
  cache = out; fetchedAt = now; return out;
41
- } catch { return []; } finally { clearTimeout(timer); }
67
+ } catch { return fallbackList(); } finally { clearTimeout(timer); }
42
68
  }
43
69
 
44
70
  async function preheat() {
45
- const url = joinUrl(resolvedBase, resolvedPath);
71
+ const url = resolveModelsUrl();
46
72
  const t0 = performance.now();
47
73
  try {
48
74
  const headers = { Accept: "application/json" };
@@ -35,19 +35,8 @@ export function getEffectiveUseGroup({ file = defaultStateFile() } = {}) {
35
35
  return loadUseGroup({ file });
36
36
  }
37
37
 
38
- // 仅对 opencode 供应商生效:opencode 的模型为裸 id 或 opencode/ 前缀
38
+ // 全局开关:off 则所有供应商都不走组员网络(via-route/hedge/peer/broadband 全禁),仅本机直连
39
39
  export function shouldUseGroupForModel(model, { file = defaultStateFile() } = {}) {
40
- const m = String(model || "").trim();
41
- if (!m) return getEffectiveUseGroup({ file });
42
- // 带前缀:判断是否为 opencode
43
- if (m.includes("/")) {
44
- const head = m.split("/")[0].trim().toLowerCase();
45
- if (head === "opencode" || head === "oc") {
46
- return getEffectiveUseGroup({ file });
47
- }
48
- return true; // 其他供应商不受此开关限制
49
- }
50
- // 裸 id 视为 opencode
51
40
  return getEffectiveUseGroup({ file });
52
41
  }
53
42