mslxdff 0.1.236 → 0.1.238

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 (105) hide show
  1. package/bin/mslxdff.js +3 -3
  2. package/package.json +1 -1
  3. package/src/auto.js +264 -264
  4. package/src/autostart.js +62 -15
  5. package/src/bench/cline-bench.js +42 -42
  6. package/src/bench/probe.js +70 -70
  7. package/src/bench/report.js +162 -162
  8. package/src/bench/runner.js +77 -77
  9. package/src/bench/via-probe.js +124 -124
  10. package/src/bench/via-routes.js +87 -87
  11. package/src/bench/workbuddy-bench.js +54 -54
  12. package/src/chat/engine.js +160 -160
  13. package/src/chat/gateway.js +163 -163
  14. package/src/chat/orchestrator.js +234 -234
  15. package/src/chat/prompt.js +70 -70
  16. package/src/chat/repl.js +88 -88
  17. package/src/chat/terminal.js +135 -135
  18. package/src/chat/tools.js +306 -306
  19. package/src/chat-pipeline/index.js +155 -155
  20. package/src/chat-pipeline/policy.js +84 -84
  21. package/src/cli/commands/group.js +266 -266
  22. package/src/cli/commands/model/picks.js +50 -50
  23. package/src/cli/commands/provider/bench-via.js +247 -247
  24. package/src/cli/commands/provider/bench.js +141 -141
  25. package/src/cli/commands/provider/index.js +139 -139
  26. package/src/cli/commands/provider/keys-guard.js +20 -0
  27. package/src/cli/commands/provider/models.js +149 -149
  28. package/src/cli/commands/provider/qwenwork-login.js +119 -119
  29. package/src/cli/commands/provider/raccoon-quota.js +156 -156
  30. package/src/cli/commands/sync.js +310 -310
  31. package/src/cli/status.js +282 -282
  32. package/src/daemon.js +246 -246
  33. package/src/model-capabilities/enrich.js +86 -86
  34. package/src/model-capabilities/index.js +183 -183
  35. package/src/model-capabilities/parse.js +70 -70
  36. package/src/models.js +293 -293
  37. package/src/peers.js +389 -389
  38. package/src/providers/agentrouter.js +238 -238
  39. package/src/providers/base.js +164 -164
  40. package/src/providers/cline/auth.js +228 -228
  41. package/src/providers/cline/chat.js +307 -307
  42. package/src/providers/cline.js +2 -2
  43. package/src/providers/codearts/chat.js +207 -207
  44. package/src/providers/codearts/const.js +12 -5
  45. package/src/providers/codearts/models.js +23 -5
  46. package/src/providers/dispatcher.js +147 -147
  47. package/src/providers/globalqwenwork/cosy.js +123 -123
  48. package/src/providers/globalqwenwork/crypto.js +218 -218
  49. package/src/providers/globalqwenwork/http.js +20 -20
  50. package/src/providers/globalqwenwork/rsa.js +54 -54
  51. package/src/providers/globalqwenwork/sse.js +268 -268
  52. package/src/providers/globalqwenwork/stream.js +130 -130
  53. package/src/providers/globalqwenwork/upstream.js +122 -122
  54. package/src/providers/keyring.js +60 -60
  55. package/src/providers/qoder/chat.js +292 -292
  56. package/src/providers/qoder/index.js +311 -311
  57. package/src/providers/qoder/sse.js +233 -233
  58. package/src/providers/qwenwork/account-store.js +133 -133
  59. package/src/providers/qwenwork/constants.js +67 -67
  60. package/src/providers/qwenwork/cosy.js +120 -120
  61. package/src/providers/qwenwork/crypto.js +218 -218
  62. package/src/providers/qwenwork/http.js +20 -20
  63. package/src/providers/qwenwork/index.js +337 -337
  64. package/src/providers/qwenwork/payload.js +144 -144
  65. package/src/providers/qwenwork/rsa.js +54 -54
  66. package/src/providers/qwenwork/sse.js +268 -268
  67. package/src/providers/qwenwork/stream.js +130 -130
  68. package/src/providers/qwenwork/upstream.js +120 -120
  69. package/src/providers/qwenwork.js +1 -1
  70. package/src/providers/raccoon/const.js +219 -219
  71. package/src/providers/raccoon/credits.js +285 -285
  72. package/src/providers/registry.js +89 -89
  73. package/src/providers/workbuddy/chat.js +298 -298
  74. package/src/providers/workbuddy/reshape.js +152 -152
  75. package/src/providers/workbuddy.js +2 -2
  76. package/src/reasoning.js +32 -32
  77. package/src/routes/chat/broadband-handler.js +80 -80
  78. package/src/routes/chat/gateway.js +46 -46
  79. package/src/routes/chat/relay-pipeline.js +282 -282
  80. package/src/routes/chat/via-route-handler.js +158 -158
  81. package/src/routes/hedge.js +260 -260
  82. package/src/routes/models-route.js +167 -167
  83. package/src/routes/peers.js +373 -373
  84. package/src/routes/stream.js +364 -364
  85. package/src/runtime/bootstrap.js +75 -75
  86. package/src/runtime/keep-warm.js +135 -135
  87. package/src/runtime/provider-gate.js +75 -75
  88. package/src/runtime/providers-setup.js +187 -187
  89. package/src/runtime/raccoon-checkin.js +175 -175
  90. package/src/runtime/server-lifecycle.js +34 -10
  91. package/src/server.js +85 -85
  92. package/src/state/schemas/allowlist.js +92 -92
  93. package/src/sync-opencode.js +280 -280
  94. package/src/transport/index.js +244 -244
  95. package/src/transport/pool.js +56 -56
  96. package/src/transport/retry.js +24 -24
  97. package/src/transport/sse.js +93 -93
  98. package/src/upstream-probe/display.js +52 -52
  99. package/src/upstream-probe/probe.js +49 -49
  100. package/src/upstream-probe/rotate.js +110 -110
  101. package/src/upstream-probe/start.js +45 -45
  102. package/src/upstream.js +355 -355
  103. package/docs/cli_help_mini.md +0 -149
  104. package/src/providers/AGENTS.md +0 -49
  105. package/src/routes/AGENTS.md +0 -37
@@ -1,228 +1,228 @@
1
- import { joinUrl, sleep } from "../base.js";
2
- import { compatFetch } from "../../compat.js";
3
- import { appendEvent } from "../../logs.js";
4
- import { createHash } from "node:crypto";
5
-
6
- /**
7
- * Cline Token 池:多账号 round-robin + refresh 换 accessToken + 冷却 + 队列
8
- * 对标 pingmike2/cline2api-workers 的 accounts / getAccountToken / parseCooldown / enqueue
9
- */
10
-
11
-
12
- // 只记哈希标识,不落邮箱 / refreshToken(events.log 可读不可泄)
13
- function acctId(account) {
14
- const seed = String(account?.refreshToken || "");
15
- if (!seed) return "slot-unknown";
16
- return `acct_${createHash("sha256").update(seed).digest("hex").slice(0, 8)}`;
17
- }
18
- export function parseCooldown(body, status) {
19
- const m = String(body || "").match(/try again in (?:(\d+)\s*h)?\s*(?:(\d+)\s*m)?\s*(?:(\d+)\s*s)?/i);
20
- if (m) {
21
- const h = parseInt(m[1] || 0, 10);
22
- const min = parseInt(m[2] || 0, 10);
23
- const s = parseInt(m[3] || 0, 10);
24
- const ms = (h * 3600 + min * 60 + s) * 1000;
25
- if (ms > 0) return Math.min(ms, 6 * 3600 * 1000);
26
- }
27
- if (status === 429) return 5 * 60 * 1000;
28
- return 60 * 1000;
29
- }
30
-
31
- /**
32
- * 真死 vs 假死:对标官方 getValidClineCredentials 契约——只有 invalid_grant
33
- *(refresh token 被拒)才判死,需重新授权;网络抖动/5xx/超时是瞬时失败,
34
- * 手里 token 仍有效时继续用,且绝不清掉已存凭证。
35
- */
36
- export function isInvalidGrant(bodyText, status) {
37
- const t = String(bodyText || "").toLowerCase();
38
- if (/invalid_grant|invalid_token/.test(t)) return true;
39
- // 路由拼错/版本提示类 401("...latest version...re-authenticate your Cline account")
40
- // 只是打错了地址,不是 token 死,绝不能判死,否则好号会被永久冷冻。
41
- if (/latest version|re-authenticate/.test(t)) return false;
42
- if ((status === 400 || status === 403) && /invalid|expired|revoked/.test(t)) return true;
43
- if (status === 401 && /invalid_grant|invalid token|token[^.]{0,30}(expired|revoked|invalid)/.test(t)) return true;
44
- return false;
45
- }
46
-
47
- /**
48
- * 一次性 refresh:bench/诊断用,不落盘、不建池。
49
- * 返回 accessToken 或 null。
50
- */
51
- export async function refreshTokenForBase({ refreshToken, baseUrl = "https://api.cline.bot", fetchImpl = compatFetch, dispatcher } = {}) {
52
- const rt = String(refreshToken || "").trim();
53
- if (!rt) return null;
54
- const resolvedBase = String(baseUrl).trim().replace(/\/+$/, "") || "https://api.cline.bot";
55
- const baseNoV1 = resolvedBase.endsWith("/api/v1") ? resolvedBase.slice(0, -7) : resolvedBase;
56
- const url = joinUrl(baseNoV1, "/api/v1/auth/refresh");
57
- const opts = {
58
- method: "POST",
59
- headers: { "Content-Type": "application/json" },
60
- body: JSON.stringify({ refreshToken: rt, grantType: "refresh_token" }),
61
- };
62
- if (dispatcher) opts.dispatcher = dispatcher;
63
- try {
64
- const res = await fetchImpl(url, opts);
65
- if (!res.ok) return null;
66
- const data = await res.json();
67
- return data?.data?.accessToken || data?.accessToken || data?.access_token || null;
68
- } catch {
69
- return null;
70
- }
71
- }
72
-
73
- export function createAuthPool({
74
- id = "cline",
75
- keys = [],
76
- fetchImpl,
77
- dispatcher,
78
- baseUrl = "https://api.cline.bot",
79
- file,
80
- clock = Date.now,
81
- saveFn,
82
- } = {}) {
83
- const resolvedBase = String(baseUrl).trim().replace(/\/+$/, "") || "https://api.cline.bot";
84
- let accounts = [];
85
- let accountIndex = 0;
86
- let currentAccount = null;
87
- let queueTail = Promise.resolve();
88
- const MIN_GAP_MS = 800;
89
-
90
- function parseAccounts(tokens) {
91
- const list = [...new Set((tokens || []).map((s) => String(s).trim()).filter((s) => s.length > 8))];
92
- if (list.length === 0) {
93
- accounts = [];
94
- return accounts;
95
- }
96
- const changed = accounts.length !== list.length || accounts.some((a, i) => a.refreshToken !== list[i]);
97
- if (changed) {
98
- accounts = list.map((rt) => ({ refreshToken: rt, accessToken: null, expiry: 0, cooldownUntil: 0, limits: {} }));
99
- accountIndex = 0;
100
- }
101
- return accounts;
102
- }
103
-
104
- // 初始解析
105
- parseAccounts(keys);
106
-
107
- function enqueue(fn) {
108
- const run = queueTail.then(() => sleep(MIN_GAP_MS)).then(fn);
109
- queueTail = run.catch(() => {});
110
- return run;
111
- }
112
- // 模型级限流:Cline 免费额度按「账号 × 模型」计,429 只应挡该模型,
113
- // 不得把整个号冻住(muse-spark 被限时 deepseek 仍须能用同一账号)。
114
- function markLimit(account, model, cooldownMs) {
115
- if (!account || !model) return;
116
- if (!account.limits) account.limits = {};
117
- account.limits[model] = clock() + cooldownMs;
118
- }
119
- // 账号可用性:dead(账号死)/ cooldownUntil(refresh 失败,账号级)/ limits[model](该模型 429)三关
120
- function accountAvailable(acc, model, now = clock()) {
121
- if (!acc || acc.dead) return false;
122
- if (acc.cooldownUntil && acc.cooldownUntil > now) return false;
123
- if (model && acc.limits && acc.limits[model] && acc.limits[model] > now) return false;
124
- return true;
125
- }
126
-
127
- function pickAccount(pool, model) {
128
- const list = pool || accounts;
129
- for (let k = 0; k < list.length; k++) {
130
- const acc = list[accountIndex % list.length];
131
- accountIndex = (accountIndex + 1) % list.length;
132
- if (accountAvailable(acc, model)) {
133
- currentAccount = acc;
134
- return acc;
135
- }
136
- }
137
- return null;
138
- }
139
-
140
- async function refreshOne(account) {
141
- const now = clock();
142
- if (account.dead) throw new Error("invalid_grant");
143
- if (account.cooldownUntil > now) throw new Error("account_cooldown");
144
- if (account.accessToken && now < account.expiry) return account.accessToken;
145
- // base 可能已含 /api/v1(老 clinebot 配置就是 …/api/v1),直接拼会 double 成
146
- // …/api/v1/api/v1/auth/refresh → 上游回 401 Unauthorized(版本/重认证提示),绝不能当 token 死。
147
- const baseNoV1 = resolvedBase.replace(/\/api\/v1\/?$/, "");
148
- const url = joinUrl(baseNoV1, "/api/v1/auth/refresh");
149
- const opts = {
150
- method: "POST",
151
- headers: { "Content-Type": "application/json" },
152
- body: JSON.stringify({ refreshToken: account.refreshToken, grantType: "refresh_token" }),
153
- };
154
- if (dispatcher) opts.dispatcher = dispatcher;
155
- let res;
156
- try { res = await fetchImpl(url, opts); } catch { account.cooldownUntil = now + 60 * 1000; throw new Error("refresh_failed"); }
157
- if (!res.ok) {
158
- let t = "";
159
- try { t = await res.text(); } catch {}
160
- if (isInvalidGrant(t, res.status)) {
161
- account.dead = true;
162
- appendEvent({ type: "cline-account-state", provider: id, state: "dead", accountId: acctId(account), status: res.status, reason: "invalid_grant" });
163
- throw new Error("invalid_grant");
164
- }
165
- account.cooldownUntil = now + 60 * 1000;
166
- appendEvent({ type: "cline-account-state", provider: id, state: "refresh-failed", accountId: acctId(account), status: res.status, cooldownMs: 60_000 });
167
- throw new Error("refresh_failed");
168
- }
169
- let data;
170
- try { data = await res.json(); } catch { account.cooldownUntil = now + 60 * 1000; throw new Error("refresh_no_token"); }
171
- const accessToken = data?.data?.accessToken || data?.accessToken || data?.access_token;
172
- if (!accessToken) { account.cooldownUntil = now + 60 * 1000; throw new Error("refresh_no_token"); }
173
- const newRt = typeof data?.data?.refreshToken === "string" && data.data.refreshToken.trim() ? data.data.refreshToken.trim() : null;
174
- if (newRt && newRt !== account.refreshToken) {
175
- const oldRt = account.refreshToken;
176
- account.refreshToken = newRt;
177
- if (saveFn) {
178
- try { await saveFn({ oldRefreshToken: oldRt, newRefreshToken: newRt, newAccessToken: accessToken }); } catch {}
179
- }
180
- }
181
- account.accessToken = accessToken;
182
- const expiresAt = data?.data?.expiresAt ?? data?.expiresAt;
183
- let expiry = now + 10 * 60 * 1000;
184
- if (typeof expiresAt === "number") expiry = expiresAt;
185
- else if (typeof expiresAt === "string") { const t = Date.parse(expiresAt); if (!isNaN(t)) expiry = t; }
186
- account.expiry = expiry - 60 * 1000;
187
- return accessToken;
188
- }
189
-
190
- async function getAccessToken(model) {
191
- const pool = accounts;
192
- if (pool.length === 0) throw new Error("缺少 CLINE_REFRESH_TOKEN(请用 cline_oauth.py 获取)");
193
- for (let attempt = 0; attempt < pool.length; attempt++) {
194
- const acc = pool[attempt % pool.length];
195
- if (!accountAvailable(acc, model)) continue;
196
- currentAccount = acc;
197
- try { return await refreshOne(acc); } catch (e) { if (e.message === "account_cooldown") continue; continue; }
198
- }
199
- const acc = pool.find((a) => !a.dead) || null;
200
- if (!acc) throw new Error("无可用 Cline 账号");
201
- currentAccount = acc;
202
- // 防锁死:该模型全部号被限时,清掉这一号的该模型限制强取重试(只清模型维度,
203
- // 不动账号级 cooldownUntil——那是 refresh 失败的冷却,仍由 accountAvailable 把关)。
204
- if (model && acc.limits) delete acc.limits[model];
205
- if (acc.cooldownUntil && acc.cooldownUntil > clock()) acc.cooldownUntil = 0;
206
- appendEvent({
207
- type: "cline-account-state",
208
- provider: id,
209
- state: "force-retry",
210
- accountId: acctId(acc),
211
- model,
212
- reason: "all-accounts-cooling",
213
- pool: {
214
- total: pool.length,
215
- cooling: pool.filter((a) => !accountAvailable(a, model)).length,
216
- dead: pool.filter((a) => a.dead).length,
217
- ready: pool.filter((a) => accountAvailable(a, model)).length,
218
- },
219
- });
220
- return refreshOne(acc);
221
- }
222
-
223
- function getCurrentAccount() { return currentAccount; }
224
- function getAccounts() { return accounts; }
225
- function updateKeys(newKeys) { parseAccounts(newKeys); }
226
-
227
- return { parseAccounts, getAccessToken, refreshOne, pickAccount, parseCooldown, enqueue, getCurrentAccount, getAccounts, updateKeys, markLimit, accountAvailable, _accounts: () => accounts };
228
- }
1
+ import { joinUrl, sleep } from "../base.js";
2
+ import { compatFetch } from "../../compat.js";
3
+ import { appendEvent } from "../../logs.js";
4
+ import { createHash } from "node:crypto";
5
+
6
+ /**
7
+ * Cline Token 池:多账号 round-robin + refresh 换 accessToken + 冷却 + 队列
8
+ * 对标 pingmike2/cline2api-workers 的 accounts / getAccountToken / parseCooldown / enqueue
9
+ */
10
+
11
+
12
+ // 只记哈希标识,不落邮箱 / refreshToken(events.log 可读不可泄)
13
+ function acctId(account) {
14
+ const seed = String(account?.refreshToken || "");
15
+ if (!seed) return "slot-unknown";
16
+ return `acct_${createHash("sha256").update(seed).digest("hex").slice(0, 8)}`;
17
+ }
18
+ export function parseCooldown(body, status) {
19
+ const m = String(body || "").match(/try again in (?:(\d+)\s*h)?\s*(?:(\d+)\s*m)?\s*(?:(\d+)\s*s)?/i);
20
+ if (m) {
21
+ const h = parseInt(m[1] || 0, 10);
22
+ const min = parseInt(m[2] || 0, 10);
23
+ const s = parseInt(m[3] || 0, 10);
24
+ const ms = (h * 3600 + min * 60 + s) * 1000;
25
+ if (ms > 0) return Math.min(ms, 6 * 3600 * 1000);
26
+ }
27
+ if (status === 429) return 5 * 60 * 1000;
28
+ return 60 * 1000;
29
+ }
30
+
31
+ /**
32
+ * 真死 vs 假死:对标官方 getValidClineCredentials 契约——只有 invalid_grant
33
+ *(refresh token 被拒)才判死,需重新授权;网络抖动/5xx/超时是瞬时失败,
34
+ * 手里 token 仍有效时继续用,且绝不清掉已存凭证。
35
+ */
36
+ export function isInvalidGrant(bodyText, status) {
37
+ const t = String(bodyText || "").toLowerCase();
38
+ if (/invalid_grant|invalid_token/.test(t)) return true;
39
+ // 路由拼错/版本提示类 401("...latest version...re-authenticate your Cline account")
40
+ // 只是打错了地址,不是 token 死,绝不能判死,否则好号会被永久冷冻。
41
+ if (/latest version|re-authenticate/.test(t)) return false;
42
+ if ((status === 400 || status === 403) && /invalid|expired|revoked/.test(t)) return true;
43
+ if (status === 401 && /invalid_grant|invalid token|token[^.]{0,30}(expired|revoked|invalid)/.test(t)) return true;
44
+ return false;
45
+ }
46
+
47
+ /**
48
+ * 一次性 refresh:bench/诊断用,不落盘、不建池。
49
+ * 返回 accessToken 或 null。
50
+ */
51
+ export async function refreshTokenForBase({ refreshToken, baseUrl = "https://api.cline.bot", fetchImpl = compatFetch, dispatcher } = {}) {
52
+ const rt = String(refreshToken || "").trim();
53
+ if (!rt) return null;
54
+ const resolvedBase = String(baseUrl).trim().replace(/\/+$/, "") || "https://api.cline.bot";
55
+ const baseNoV1 = resolvedBase.endsWith("/api/v1") ? resolvedBase.slice(0, -7) : resolvedBase;
56
+ const url = joinUrl(baseNoV1, "/api/v1/auth/refresh");
57
+ const opts = {
58
+ method: "POST",
59
+ headers: { "Content-Type": "application/json" },
60
+ body: JSON.stringify({ refreshToken: rt, grantType: "refresh_token" }),
61
+ };
62
+ if (dispatcher) opts.dispatcher = dispatcher;
63
+ try {
64
+ const res = await fetchImpl(url, opts);
65
+ if (!res.ok) return null;
66
+ const data = await res.json();
67
+ return data?.data?.accessToken || data?.accessToken || data?.access_token || null;
68
+ } catch {
69
+ return null;
70
+ }
71
+ }
72
+
73
+ export function createAuthPool({
74
+ id = "cline",
75
+ keys = [],
76
+ fetchImpl,
77
+ dispatcher,
78
+ baseUrl = "https://api.cline.bot",
79
+ file,
80
+ clock = Date.now,
81
+ saveFn,
82
+ } = {}) {
83
+ const resolvedBase = String(baseUrl).trim().replace(/\/+$/, "") || "https://api.cline.bot";
84
+ let accounts = [];
85
+ let accountIndex = 0;
86
+ let currentAccount = null;
87
+ let queueTail = Promise.resolve();
88
+ const MIN_GAP_MS = 800;
89
+
90
+ function parseAccounts(tokens) {
91
+ const list = [...new Set((tokens || []).map((s) => String(s).trim()).filter((s) => s.length > 8))];
92
+ if (list.length === 0) {
93
+ accounts = [];
94
+ return accounts;
95
+ }
96
+ const changed = accounts.length !== list.length || accounts.some((a, i) => a.refreshToken !== list[i]);
97
+ if (changed) {
98
+ accounts = list.map((rt) => ({ refreshToken: rt, accessToken: null, expiry: 0, cooldownUntil: 0, limits: {} }));
99
+ accountIndex = 0;
100
+ }
101
+ return accounts;
102
+ }
103
+
104
+ // 初始解析
105
+ parseAccounts(keys);
106
+
107
+ function enqueue(fn) {
108
+ const run = queueTail.then(() => sleep(MIN_GAP_MS)).then(fn);
109
+ queueTail = run.catch(() => {});
110
+ return run;
111
+ }
112
+ // 模型级限流:Cline 免费额度按「账号 × 模型」计,429 只应挡该模型,
113
+ // 不得把整个号冻住(muse-spark 被限时 deepseek 仍须能用同一账号)。
114
+ function markLimit(account, model, cooldownMs) {
115
+ if (!account || !model) return;
116
+ if (!account.limits) account.limits = {};
117
+ account.limits[model] = clock() + cooldownMs;
118
+ }
119
+ // 账号可用性:dead(账号死)/ cooldownUntil(refresh 失败,账号级)/ limits[model](该模型 429)三关
120
+ function accountAvailable(acc, model, now = clock()) {
121
+ if (!acc || acc.dead) return false;
122
+ if (acc.cooldownUntil && acc.cooldownUntil > now) return false;
123
+ if (model && acc.limits && acc.limits[model] && acc.limits[model] > now) return false;
124
+ return true;
125
+ }
126
+
127
+ function pickAccount(pool, model) {
128
+ const list = pool || accounts;
129
+ for (let k = 0; k < list.length; k++) {
130
+ const acc = list[accountIndex % list.length];
131
+ accountIndex = (accountIndex + 1) % list.length;
132
+ if (accountAvailable(acc, model)) {
133
+ currentAccount = acc;
134
+ return acc;
135
+ }
136
+ }
137
+ return null;
138
+ }
139
+
140
+ async function refreshOne(account) {
141
+ const now = clock();
142
+ if (account.dead) throw new Error("invalid_grant");
143
+ if (account.cooldownUntil > now) throw new Error("account_cooldown");
144
+ if (account.accessToken && now < account.expiry) return account.accessToken;
145
+ // base 可能已含 /api/v1(老 clinebot 配置就是 …/api/v1),直接拼会 double 成
146
+ // …/api/v1/api/v1/auth/refresh → 上游回 401 Unauthorized(版本/重认证提示),绝不能当 token 死。
147
+ const baseNoV1 = resolvedBase.replace(/\/api\/v1\/?$/, "");
148
+ const url = joinUrl(baseNoV1, "/api/v1/auth/refresh");
149
+ const opts = {
150
+ method: "POST",
151
+ headers: { "Content-Type": "application/json" },
152
+ body: JSON.stringify({ refreshToken: account.refreshToken, grantType: "refresh_token" }),
153
+ };
154
+ if (dispatcher) opts.dispatcher = dispatcher;
155
+ let res;
156
+ try { res = await fetchImpl(url, opts); } catch { account.cooldownUntil = now + 60 * 1000; throw new Error("refresh_failed"); }
157
+ if (!res.ok) {
158
+ let t = "";
159
+ try { t = await res.text(); } catch {}
160
+ if (isInvalidGrant(t, res.status)) {
161
+ account.dead = true;
162
+ appendEvent({ type: "cline-account-state", provider: id, state: "dead", accountId: acctId(account), status: res.status, reason: "invalid_grant" });
163
+ throw new Error("invalid_grant");
164
+ }
165
+ account.cooldownUntil = now + 60 * 1000;
166
+ appendEvent({ type: "cline-account-state", provider: id, state: "refresh-failed", accountId: acctId(account), status: res.status, cooldownMs: 60_000 });
167
+ throw new Error("refresh_failed");
168
+ }
169
+ let data;
170
+ try { data = await res.json(); } catch { account.cooldownUntil = now + 60 * 1000; throw new Error("refresh_no_token"); }
171
+ const accessToken = data?.data?.accessToken || data?.accessToken || data?.access_token;
172
+ if (!accessToken) { account.cooldownUntil = now + 60 * 1000; throw new Error("refresh_no_token"); }
173
+ const newRt = typeof data?.data?.refreshToken === "string" && data.data.refreshToken.trim() ? data.data.refreshToken.trim() : null;
174
+ if (newRt && newRt !== account.refreshToken) {
175
+ const oldRt = account.refreshToken;
176
+ account.refreshToken = newRt;
177
+ if (saveFn) {
178
+ try { await saveFn({ oldRefreshToken: oldRt, newRefreshToken: newRt, newAccessToken: accessToken }); } catch {}
179
+ }
180
+ }
181
+ account.accessToken = accessToken;
182
+ const expiresAt = data?.data?.expiresAt ?? data?.expiresAt;
183
+ let expiry = now + 10 * 60 * 1000;
184
+ if (typeof expiresAt === "number") expiry = expiresAt;
185
+ else if (typeof expiresAt === "string") { const t = Date.parse(expiresAt); if (!isNaN(t)) expiry = t; }
186
+ account.expiry = expiry - 60 * 1000;
187
+ return accessToken;
188
+ }
189
+
190
+ async function getAccessToken(model) {
191
+ const pool = accounts;
192
+ if (pool.length === 0) throw new Error("缺少 CLINE_REFRESH_TOKEN(请用 cline_oauth.py 获取)");
193
+ for (let attempt = 0; attempt < pool.length; attempt++) {
194
+ const acc = pool[attempt % pool.length];
195
+ if (!accountAvailable(acc, model)) continue;
196
+ currentAccount = acc;
197
+ try { return await refreshOne(acc); } catch (e) { if (e.message === "account_cooldown") continue; continue; }
198
+ }
199
+ const acc = pool.find((a) => !a.dead) || null;
200
+ if (!acc) throw new Error("无可用 Cline 账号");
201
+ currentAccount = acc;
202
+ // 防锁死:该模型全部号被限时,清掉这一号的该模型限制强取重试(只清模型维度,
203
+ // 不动账号级 cooldownUntil——那是 refresh 失败的冷却,仍由 accountAvailable 把关)。
204
+ if (model && acc.limits) delete acc.limits[model];
205
+ if (acc.cooldownUntil && acc.cooldownUntil > clock()) acc.cooldownUntil = 0;
206
+ appendEvent({
207
+ type: "cline-account-state",
208
+ provider: id,
209
+ state: "force-retry",
210
+ accountId: acctId(acc),
211
+ model,
212
+ reason: "all-accounts-cooling",
213
+ pool: {
214
+ total: pool.length,
215
+ cooling: pool.filter((a) => !accountAvailable(a, model)).length,
216
+ dead: pool.filter((a) => a.dead).length,
217
+ ready: pool.filter((a) => accountAvailable(a, model)).length,
218
+ },
219
+ });
220
+ return refreshOne(acc);
221
+ }
222
+
223
+ function getCurrentAccount() { return currentAccount; }
224
+ function getAccounts() { return accounts; }
225
+ function updateKeys(newKeys) { parseAccounts(newKeys); }
226
+
227
+ return { parseAccounts, getAccessToken, refreshOne, pickAccount, parseCooldown, enqueue, getCurrentAccount, getAccounts, updateKeys, markLimit, accountAvailable, _accounts: () => accounts };
228
+ }