mslxdff 0.1.228 → 0.1.230

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 (104) hide show
  1. package/bin/mslxdff.js +3 -3
  2. package/package.json +1 -1
  3. package/src/anthropic/request-shape.js +13 -0
  4. package/src/auto.js +254 -254
  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 +145 -145
  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/cline-free.js +19 -9
  26. package/src/cli/commands/provider/index.js +139 -139
  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 +57 -10
  30. package/src/cli/commands/sync.js +310 -310
  31. package/src/cli/status.js +279 -279
  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 +225 -225
  37. package/src/peers.js +345 -345
  38. package/src/providers/agentrouter.js +231 -0
  39. package/src/providers/cline/allowlist-sync.js +76 -38
  40. package/src/providers/cline/auth.js +228 -228
  41. package/src/providers/cline/chat.js +307 -307
  42. package/src/providers/cline/free-catalog.js +9 -6
  43. package/src/providers/cline.js +2 -2
  44. package/src/providers/codearts/chat.js +207 -207
  45. package/src/providers/dispatcher.js +1 -1
  46. package/src/providers/globalqwenwork/cosy.js +123 -123
  47. package/src/providers/globalqwenwork/crypto.js +218 -218
  48. package/src/providers/globalqwenwork/http.js +20 -20
  49. package/src/providers/globalqwenwork/rsa.js +54 -54
  50. package/src/providers/globalqwenwork/sse.js +268 -268
  51. package/src/providers/globalqwenwork/stream.js +130 -130
  52. package/src/providers/globalqwenwork/upstream.js +122 -122
  53. package/src/providers/keyring.js +60 -60
  54. package/src/providers/qoder/chat.js +203 -203
  55. package/src/providers/qoder/index.js +249 -249
  56. package/src/providers/qoder/sse.js +145 -145
  57. package/src/providers/qwenwork/account-store.js +133 -133
  58. package/src/providers/qwenwork/constants.js +67 -67
  59. package/src/providers/qwenwork/cosy.js +120 -120
  60. package/src/providers/qwenwork/crypto.js +218 -218
  61. package/src/providers/qwenwork/http.js +20 -20
  62. package/src/providers/qwenwork/index.js +337 -337
  63. package/src/providers/qwenwork/payload.js +144 -144
  64. package/src/providers/qwenwork/rsa.js +54 -54
  65. package/src/providers/qwenwork/sse.js +268 -268
  66. package/src/providers/qwenwork/stream.js +130 -130
  67. package/src/providers/qwenwork/upstream.js +120 -120
  68. package/src/providers/qwenwork.js +1 -1
  69. package/src/providers/raccoon/const.js +22 -0
  70. package/src/providers/raccoon/credits.js +105 -5
  71. package/src/providers/raccoon/sse.js +1 -1
  72. package/src/providers/registry.js +93 -86
  73. package/src/providers/workbuddy/chat.js +264 -264
  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 +156 -156
  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 +347 -347
  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 +72 -23
  90. package/src/server.js +85 -85
  91. package/src/state/schemas/allowlist.js +92 -92
  92. package/src/sync-opencode.js +280 -280
  93. package/src/transport/index.js +244 -244
  94. package/src/transport/pool.js +56 -56
  95. package/src/transport/retry.js +24 -24
  96. package/src/transport/sse.js +93 -93
  97. package/src/upstream-probe/display.js +52 -52
  98. package/src/upstream-probe/probe.js +49 -49
  99. package/src/upstream-probe/rotate.js +110 -110
  100. package/src/upstream-probe/start.js +45 -45
  101. package/src/upstream.js +355 -355
  102. package/docs/cli_help_mini.md +0 -151
  103. package/src/providers/AGENTS.md +0 -49
  104. package/src/routes/AGENTS.md +0 -37
@@ -1,130 +1,130 @@
1
- // vendor 自 _shared/sse.js 的 transform(真流式:上游 SSE → OpenAI chunk,边收边吐)。
2
- // 唯一一处**有意偏离**原作者实现:把 chunk 里的 `model` 回写成客户端请求的模型名。
3
- // 上游实际返回的是池名(实测 `qwork-openai-chat-mode-pool`),直接透传会让客户端按模型名匹配失败,
4
- // 违反本仓契约 1「model 原样透传」。原作者的非流式路径同样做了 `completion.model = wantModel`。
5
- import { handleLine } from "./sse.js";
6
-
7
- function rewriteModel(frameText, model) {
8
- if (!model) return frameText;
9
- const body = frameText.slice(6, -2);
10
- let obj;
11
- try {
12
- obj = JSON.parse(body);
13
- } catch {
14
- return frameText;
15
- }
16
- if (!obj || typeof obj !== "object") return frameText;
17
- obj.model = model;
18
- return `data: ${JSON.stringify(obj)}\n\n`;
19
- }
20
-
21
- export function transformStream(upstreamBody, model, onUsage, { heartbeatMs = 15000 } = {}) {
22
- const reader = upstreamBody.getReader();
23
- const decoder = new TextDecoder();
24
- const encoder = new TextEncoder();
25
- let buffer = "";
26
- let notified = false;
27
- let heartbeat = null;
28
- const state = { usage: null, error: null };
29
-
30
- const notify = () => {
31
- if (notified) return;
32
- notified = true;
33
- if (onUsage) onUsage(state.usage);
34
- };
35
-
36
- const emitError = (controller, message) => {
37
- try {
38
- controller.enqueue(encoder.encode(`data: ${JSON.stringify({ error: { message, type: "upstream_error" } })}\n\n`));
39
- controller.enqueue(encoder.encode("data: [DONE]\n\n"));
40
- controller.close();
41
- } catch {
42
- /* 客户端已断开 */
43
- }
44
- };
45
-
46
- const stopHeartbeat = () => {
47
- if (heartbeat) {
48
- clearInterval(heartbeat);
49
- heartbeat = null;
50
- }
51
- };
52
-
53
- const finish = () => {
54
- stopHeartbeat();
55
- notify();
56
- };
57
-
58
- return new ReadableStream({
59
- start(controller) {
60
- if (heartbeatMs > 0) {
61
- heartbeat = setInterval(() => {
62
- try {
63
- controller.enqueue(encoder.encode(": ping\n\n"));
64
- } catch {
65
- /* 已关闭 */
66
- }
67
- }, heartbeatMs);
68
- if (heartbeat.unref) heartbeat.unref();
69
- }
70
- },
71
- async pull(controller) {
72
- try {
73
- for (;;) {
74
- let read;
75
- try {
76
- read = await reader.read();
77
- } catch (err) {
78
- const message = `upstream stream read error: ${err && err.message ? err.message : err}`;
79
- stopHeartbeat();
80
- emitError(controller, message);
81
- notify();
82
- return;
83
- }
84
- if (read.done) {
85
- stopHeartbeat();
86
- if (buffer) {
87
- const out = handleLine(buffer, state);
88
- if (out) controller.enqueue(encoder.encode(rewriteModel(out, model)));
89
- buffer = "";
90
- }
91
- if (state.error) emitError(controller, state.error);
92
- else {
93
- try {
94
- controller.enqueue(encoder.encode("data: [DONE]\n\n"));
95
- controller.close();
96
- } catch {
97
- /* 客户端已断开 */
98
- }
99
- }
100
- finish();
101
- return;
102
- }
103
- buffer += decoder.decode(read.value, { stream: true });
104
- const lines = buffer.split("\n");
105
- buffer = lines.pop() || "";
106
- let out = "";
107
- for (const line of lines) {
108
- const frame = handleLine(line, state);
109
- if (frame) out += rewriteModel(frame, model);
110
- }
111
- if (out) {
112
- controller.enqueue(encoder.encode(out));
113
- return;
114
- }
115
- }
116
- } catch (err) {
117
- finish();
118
- try {
119
- emitError(controller, `stream error: ${err && err.message ? err.message : err}`);
120
- } catch {
121
- /* 已关闭 */
122
- }
123
- }
124
- },
125
- cancel(reason) {
126
- finish();
127
- if (reader.cancel) reader.cancel(reason);
128
- },
129
- });
130
- }
1
+ // vendor 自 _shared/sse.js 的 transform(真流式:上游 SSE → OpenAI chunk,边收边吐)。
2
+ // 唯一一处**有意偏离**原作者实现:把 chunk 里的 `model` 回写成客户端请求的模型名。
3
+ // 上游实际返回的是池名(实测 `qwork-openai-chat-mode-pool`),直接透传会让客户端按模型名匹配失败,
4
+ // 违反本仓契约 1「model 原样透传」。原作者的非流式路径同样做了 `completion.model = wantModel`。
5
+ import { handleLine } from "./sse.js";
6
+
7
+ function rewriteModel(frameText, model) {
8
+ if (!model) return frameText;
9
+ const body = frameText.slice(6, -2);
10
+ let obj;
11
+ try {
12
+ obj = JSON.parse(body);
13
+ } catch {
14
+ return frameText;
15
+ }
16
+ if (!obj || typeof obj !== "object") return frameText;
17
+ obj.model = model;
18
+ return `data: ${JSON.stringify(obj)}\n\n`;
19
+ }
20
+
21
+ export function transformStream(upstreamBody, model, onUsage, { heartbeatMs = 15000 } = {}) {
22
+ const reader = upstreamBody.getReader();
23
+ const decoder = new TextDecoder();
24
+ const encoder = new TextEncoder();
25
+ let buffer = "";
26
+ let notified = false;
27
+ let heartbeat = null;
28
+ const state = { usage: null, error: null };
29
+
30
+ const notify = () => {
31
+ if (notified) return;
32
+ notified = true;
33
+ if (onUsage) onUsage(state.usage);
34
+ };
35
+
36
+ const emitError = (controller, message) => {
37
+ try {
38
+ controller.enqueue(encoder.encode(`data: ${JSON.stringify({ error: { message, type: "upstream_error" } })}\n\n`));
39
+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));
40
+ controller.close();
41
+ } catch {
42
+ /* 客户端已断开 */
43
+ }
44
+ };
45
+
46
+ const stopHeartbeat = () => {
47
+ if (heartbeat) {
48
+ clearInterval(heartbeat);
49
+ heartbeat = null;
50
+ }
51
+ };
52
+
53
+ const finish = () => {
54
+ stopHeartbeat();
55
+ notify();
56
+ };
57
+
58
+ return new ReadableStream({
59
+ start(controller) {
60
+ if (heartbeatMs > 0) {
61
+ heartbeat = setInterval(() => {
62
+ try {
63
+ controller.enqueue(encoder.encode(": ping\n\n"));
64
+ } catch {
65
+ /* 已关闭 */
66
+ }
67
+ }, heartbeatMs);
68
+ if (heartbeat.unref) heartbeat.unref();
69
+ }
70
+ },
71
+ async pull(controller) {
72
+ try {
73
+ for (;;) {
74
+ let read;
75
+ try {
76
+ read = await reader.read();
77
+ } catch (err) {
78
+ const message = `upstream stream read error: ${err && err.message ? err.message : err}`;
79
+ stopHeartbeat();
80
+ emitError(controller, message);
81
+ notify();
82
+ return;
83
+ }
84
+ if (read.done) {
85
+ stopHeartbeat();
86
+ if (buffer) {
87
+ const out = handleLine(buffer, state);
88
+ if (out) controller.enqueue(encoder.encode(rewriteModel(out, model)));
89
+ buffer = "";
90
+ }
91
+ if (state.error) emitError(controller, state.error);
92
+ else {
93
+ try {
94
+ controller.enqueue(encoder.encode("data: [DONE]\n\n"));
95
+ controller.close();
96
+ } catch {
97
+ /* 客户端已断开 */
98
+ }
99
+ }
100
+ finish();
101
+ return;
102
+ }
103
+ buffer += decoder.decode(read.value, { stream: true });
104
+ const lines = buffer.split("\n");
105
+ buffer = lines.pop() || "";
106
+ let out = "";
107
+ for (const line of lines) {
108
+ const frame = handleLine(line, state);
109
+ if (frame) out += rewriteModel(frame, model);
110
+ }
111
+ if (out) {
112
+ controller.enqueue(encoder.encode(out));
113
+ return;
114
+ }
115
+ }
116
+ } catch (err) {
117
+ finish();
118
+ try {
119
+ emitError(controller, `stream error: ${err && err.message ? err.message : err}`);
120
+ } catch {
121
+ /* 已关闭 */
122
+ }
123
+ }
124
+ },
125
+ cancel(reason) {
126
+ finish();
127
+ if (reader.cancel) reader.cancel(reason);
128
+ },
129
+ });
130
+ }
@@ -1,120 +1,120 @@
1
- // vendor 自 _shared/upstream.js(签名请求装配 + OAuth 设备流),逐字搬;
2
- // 唯一改动:fetch 实现改为注入(默认本仓统一的 compatFetch,走 undici 连接池,勿混用 globalThis.fetch)。
3
- import { compatFetch } from "../../compat.js";
4
- import { uuid, b64url, utf8 } from "./crypto.js";
5
- import { signHeaders } from "./cosy.js";
6
- import {
7
- UA, CLIENT_ID, REDIRECT_URI, DEVICE_AUTH_URL, CHAT_URL, MODELS_URL,
8
- USERINFO_URL, ACCOUNT_CONTEXT_URL, POLL_URL, REFRESH_URL, MODEL_SLICE,
9
- } from "./constants.js";
10
-
11
- function plainHeaders() {
12
- return {
13
- accept: "application/json, text/plain, */*",
14
- "content-type": "application/json",
15
- "user-agent": UA,
16
- };
17
- }
18
-
19
- export function chatRequest(account, modelKey, bodyStr, signal, fetchImpl = compatFetch) {
20
- const headers = signHeaders(account, bodyStr, CHAT_URL, modelKey, "text/event-stream");
21
- return fetchImpl(CHAT_URL, { method: "POST", headers, body: bodyStr, signal });
22
- }
23
-
24
- export async function modelList(account, fetchImpl = compatFetch) {
25
- const headers = signHeaders(account, "", MODELS_URL, "", "application/json");
26
- const res = await fetchImpl(MODELS_URL, { headers });
27
- if (!res.ok) throw new Error(`models http ${res.status}`);
28
- const data = await res.json();
29
- // 实测 11 个根切片只有 `qwork` 非空(其余 n=0);切片名见 constants.MODEL_SLICE
30
- const list = Array.isArray(data && data[MODEL_SLICE]) ? data[MODEL_SLICE] : [];
31
- return list
32
- .filter((m) => m && m.enable !== false && m.key)
33
- .map((m) => ({
34
- key: m.key,
35
- name: m.display_name || m.key,
36
- isReasoning: !!m.is_reasoning,
37
- isVL: !!m.is_vl,
38
- maxInputTokens: m.max_input_tokens || 0,
39
- maxOutputTokens: m.max_output_tokens || 0,
40
- priceFactor: typeof m.price_factor === "number" ? m.price_factor : 0,
41
- description: typeof m.description === "string" ? m.description : "",
42
- }));
43
- }
44
-
45
- export async function userInfo(accessToken, fetchImpl = compatFetch) {
46
- const res = await fetchImpl(USERINFO_URL, {
47
- headers: { ...plainHeaders(), authorization: `Bearer ${accessToken}` },
48
- });
49
- if (!res.ok) throw new Error(`userinfo http ${res.status}`);
50
- return res.json();
51
- }
52
-
53
- /** 额度/套餐:data.{user,plan,quota};quota.remaining 即积分余量。 */
54
- export async function accountContext(accessToken, fetchImpl = compatFetch) {
55
- const res = await fetchImpl(ACCOUNT_CONTEXT_URL, {
56
- headers: { ...plainHeaders(), authorization: `Bearer ${accessToken}` },
57
- });
58
- if (!res.ok) throw new Error(`account-context http ${res.status}`);
59
- const body = await res.json();
60
- if (!body || (body.code && body.code !== "ok")) throw new Error(`account-context code=${body && body.code}`);
61
- return (body && body.data) || {};
62
- }
63
-
64
- export async function refreshDeviceToken(refreshToken, fetchImpl = compatFetch) {
65
- const res = await fetchImpl(REFRESH_URL, {
66
- method: "POST",
67
- headers: plainHeaders(),
68
- body: JSON.stringify({ refresh_token: refreshToken }),
69
- });
70
- if (!res.ok) throw new Error(`refresh http ${res.status}`);
71
- const data = await res.json();
72
- const access = data && (data.token || data.device_token);
73
- if (!access || !data.refresh_token) throw new Error("refresh: incomplete token pair");
74
- return data;
75
- }
76
-
77
- export async function pollGrant(nonce, verifier, fetchImpl = compatFetch) {
78
- const q = new URLSearchParams({ nonce, verifier, challenge_method: "S256" });
79
- const res = await fetchImpl(`${POLL_URL}?${q.toString()}`, {
80
- headers: { accept: "application/json", "user-agent": UA },
81
- });
82
- if (res.status === 404 || res.status === 202) return { pending: true };
83
- if (!res.ok) throw new Error(`poll http ${res.status}`);
84
- const data = await res.json();
85
- if (!data || !(data.token || data.device_token)) return { pending: true };
86
- return { pending: false, grant: data };
87
- }
88
-
89
- export async function newDeviceFlow() {
90
- const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
91
- const raw = new Uint8Array(64);
92
- crypto.getRandomValues(raw);
93
- let verifier = "";
94
- for (let i = 0; i < raw.length; i++) verifier += alphabet[raw[i] % alphabet.length];
95
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8(verifier)));
96
- const challenge = b64url(digest);
97
- const nonce = uuid();
98
- const machineID = uuid();
99
- const q = new URLSearchParams({
100
- challenge,
101
- challenge_method: "S256",
102
- nonce,
103
- machine_id: machineID,
104
- client_id: CLIENT_ID,
105
- redirect_uri: REDIRECT_URI,
106
- });
107
- return { verifier, nonce, url: `${DEVICE_AUTH_URL}?${q.toString()}` };
108
- }
109
-
110
- export function expiryUnix(grant) {
111
- if (grant && grant.expires_at) {
112
- const t = Date.parse(grant.expires_at);
113
- if (!Number.isNaN(t)) return Math.floor(t / 1000);
114
- }
115
- if (grant && grant.expires_in > 0) {
116
- const ms = grant.expires_in > 10000000 ? grant.expires_in : grant.expires_in * 1000;
117
- return Math.floor((Date.now() + ms) / 1000);
118
- }
119
- return Math.floor((Date.now() + 30 * 24 * 3600 * 1000) / 1000);
120
- }
1
+ // vendor 自 _shared/upstream.js(签名请求装配 + OAuth 设备流),逐字搬;
2
+ // 唯一改动:fetch 实现改为注入(默认本仓统一的 compatFetch,走 undici 连接池,勿混用 globalThis.fetch)。
3
+ import { compatFetch } from "../../compat.js";
4
+ import { uuid, b64url, utf8 } from "./crypto.js";
5
+ import { signHeaders } from "./cosy.js";
6
+ import {
7
+ UA, CLIENT_ID, REDIRECT_URI, DEVICE_AUTH_URL, CHAT_URL, MODELS_URL,
8
+ USERINFO_URL, ACCOUNT_CONTEXT_URL, POLL_URL, REFRESH_URL, MODEL_SLICE,
9
+ } from "./constants.js";
10
+
11
+ function plainHeaders() {
12
+ return {
13
+ accept: "application/json, text/plain, */*",
14
+ "content-type": "application/json",
15
+ "user-agent": UA,
16
+ };
17
+ }
18
+
19
+ export function chatRequest(account, modelKey, bodyStr, signal, fetchImpl = compatFetch) {
20
+ const headers = signHeaders(account, bodyStr, CHAT_URL, modelKey, "text/event-stream");
21
+ return fetchImpl(CHAT_URL, { method: "POST", headers, body: bodyStr, signal });
22
+ }
23
+
24
+ export async function modelList(account, fetchImpl = compatFetch) {
25
+ const headers = signHeaders(account, "", MODELS_URL, "", "application/json");
26
+ const res = await fetchImpl(MODELS_URL, { headers });
27
+ if (!res.ok) throw new Error(`models http ${res.status}`);
28
+ const data = await res.json();
29
+ // 实测 11 个根切片只有 `qwork` 非空(其余 n=0);切片名见 constants.MODEL_SLICE
30
+ const list = Array.isArray(data && data[MODEL_SLICE]) ? data[MODEL_SLICE] : [];
31
+ return list
32
+ .filter((m) => m && m.enable !== false && m.key)
33
+ .map((m) => ({
34
+ key: m.key,
35
+ name: m.display_name || m.key,
36
+ isReasoning: !!m.is_reasoning,
37
+ isVL: !!m.is_vl,
38
+ maxInputTokens: m.max_input_tokens || 0,
39
+ maxOutputTokens: m.max_output_tokens || 0,
40
+ priceFactor: typeof m.price_factor === "number" ? m.price_factor : 0,
41
+ description: typeof m.description === "string" ? m.description : "",
42
+ }));
43
+ }
44
+
45
+ export async function userInfo(accessToken, fetchImpl = compatFetch) {
46
+ const res = await fetchImpl(USERINFO_URL, {
47
+ headers: { ...plainHeaders(), authorization: `Bearer ${accessToken}` },
48
+ });
49
+ if (!res.ok) throw new Error(`userinfo http ${res.status}`);
50
+ return res.json();
51
+ }
52
+
53
+ /** 额度/套餐:data.{user,plan,quota};quota.remaining 即积分余量。 */
54
+ export async function accountContext(accessToken, fetchImpl = compatFetch) {
55
+ const res = await fetchImpl(ACCOUNT_CONTEXT_URL, {
56
+ headers: { ...plainHeaders(), authorization: `Bearer ${accessToken}` },
57
+ });
58
+ if (!res.ok) throw new Error(`account-context http ${res.status}`);
59
+ const body = await res.json();
60
+ if (!body || (body.code && body.code !== "ok")) throw new Error(`account-context code=${body && body.code}`);
61
+ return (body && body.data) || {};
62
+ }
63
+
64
+ export async function refreshDeviceToken(refreshToken, fetchImpl = compatFetch) {
65
+ const res = await fetchImpl(REFRESH_URL, {
66
+ method: "POST",
67
+ headers: plainHeaders(),
68
+ body: JSON.stringify({ refresh_token: refreshToken }),
69
+ });
70
+ if (!res.ok) throw new Error(`refresh http ${res.status}`);
71
+ const data = await res.json();
72
+ const access = data && (data.token || data.device_token);
73
+ if (!access || !data.refresh_token) throw new Error("refresh: incomplete token pair");
74
+ return data;
75
+ }
76
+
77
+ export async function pollGrant(nonce, verifier, fetchImpl = compatFetch) {
78
+ const q = new URLSearchParams({ nonce, verifier, challenge_method: "S256" });
79
+ const res = await fetchImpl(`${POLL_URL}?${q.toString()}`, {
80
+ headers: { accept: "application/json", "user-agent": UA },
81
+ });
82
+ if (res.status === 404 || res.status === 202) return { pending: true };
83
+ if (!res.ok) throw new Error(`poll http ${res.status}`);
84
+ const data = await res.json();
85
+ if (!data || !(data.token || data.device_token)) return { pending: true };
86
+ return { pending: false, grant: data };
87
+ }
88
+
89
+ export async function newDeviceFlow() {
90
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
91
+ const raw = new Uint8Array(64);
92
+ crypto.getRandomValues(raw);
93
+ let verifier = "";
94
+ for (let i = 0; i < raw.length; i++) verifier += alphabet[raw[i] % alphabet.length];
95
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8(verifier)));
96
+ const challenge = b64url(digest);
97
+ const nonce = uuid();
98
+ const machineID = uuid();
99
+ const q = new URLSearchParams({
100
+ challenge,
101
+ challenge_method: "S256",
102
+ nonce,
103
+ machine_id: machineID,
104
+ client_id: CLIENT_ID,
105
+ redirect_uri: REDIRECT_URI,
106
+ });
107
+ return { verifier, nonce, url: `${DEVICE_AUTH_URL}?${q.toString()}` };
108
+ }
109
+
110
+ export function expiryUnix(grant) {
111
+ if (grant && grant.expires_at) {
112
+ const t = Date.parse(grant.expires_at);
113
+ if (!Number.isNaN(t)) return Math.floor(t / 1000);
114
+ }
115
+ if (grant && grant.expires_in > 0) {
116
+ const ms = grant.expires_in > 10000000 ? grant.expires_in : grant.expires_in * 1000;
117
+ return Math.floor((Date.now() + ms) / 1000);
118
+ }
119
+ return Math.floor((Date.now() + 30 * 24 * 3600 * 1000) / 1000);
120
+ }
@@ -1 +1 @@
1
- export * from "./qwenwork/index.js";
1
+ export * from "./qwenwork/index.js";
@@ -37,6 +37,28 @@ export const raccoonBillsUrl = (limit = 50) =>
37
37
  `${RACCOON_ORIGIN}${RACCOON_POINTS_PREFIX}/bills?paging.limit=${Number(limit) || 50}&paging.offset=0`;
38
38
  export const raccoonLoginGrantUrl = () => `${RACCOON_ORIGIN}${RACCOON_DESKTOP_PREFIX}/login/points/grant`;
39
39
 
40
+ /**
41
+ * 每日积分结算触发器:`GET /api/web/office/v3/setting_info`。
42
+ *
43
+ * 2026-10-21 账单实测(这家的每日积分是**惰性结算**,不是签到):
44
+ * · 每日积分由服务端按天挂账,**当天第一次访问这个端点时才真正入账**
45
+ * (此前账单里连 `daily_grant` 都没有,`balance.daily_points` 恒 0);
46
+ * · 入账后 `expire_at` 直接是 T+6 的 23:59:59 —— 对应官方文案
47
+ * 「每日积分每天 00:00 发放,默认当日 24:00 清零,**当天登录后有效期延长至 7 天**」;
48
+ * · 完全幂等:连打 4 次只有第一次产生账单,其余静默返回(可放心每天重试)。
49
+ * 官方前端把这个端点挂在登录后拉设置信息的路径上,等价于「登录」这个动作本身。
50
+ * 端点选型实测:`/auth/v1/setting_info` 404、`/setting/v1/setting_info` 404,只有 office/v3 这条通。
51
+ */
52
+ export const raccoonOfficeSettingUrl = () => `${RACCOON_ORIGIN}/api/web/office/v3/setting_info`;
53
+ /**
54
+ * 每日积分账单的 `event_name` 字面量 —— 判「今天结算过没有」只认它(`biz_type` 是 `daily_grant`)。
55
+ * ⚠ 定位必须先按 biz_type 过滤再比 event_name:重度使用号的账单会被「对话消耗」刷满,
56
+ * 窗口里根本翻不到那条陈旧的 grant(这是 claimRaccoonLoginReward 注释里踩过的同一个坑)。
57
+ */
58
+ export const RACCOON_DAILY_GRANT_EVENT_NAME = "每日积分发放";
59
+ /** 账单分页上限实测值:一次 200 条,足够覆盖一天的重度用量(对话消耗)而仍能捞到当天的 grant。 */
60
+ export const RACCOON_BILLS_PAGE_LIMIT = 200;
61
+
40
62
  /** 服务端签发二维码(POST,body 可带 `{ product_codes: [] }`)。 */
41
63
  export const raccoonQrCreateUrl = () => `${RACCOON_ORIGIN}${RACCOON_IAM_PREFIX}/auth/mp/qrcode`;
42
64
  /** 轮询扫码状态(POST,body `{ qrcode_code }`)。 */
@@ -1,17 +1,24 @@
1
- // raccoon 积分:余额五分项查询 + 登录奖励领取(幂等,判据只认账单)。
2
- // 这家是**积分制**,三种积分来源的性质(2026-10-10 账单流水实测 + 参考实现双向取证):
1
+ // raccoon 积分:余额五分项查询 + 每日积分结算 + 登录奖励领取(幂等,判据只认账单)。
2
+ // 这家是**积分制**,四种积分来源的性质(2026-10-21 账单流水实测,此前 2026-10-10 的结论已被上游改版推翻):
3
3
  // · 新人注册礼包 3000 —— 注册时服务端自动发,**无端点可领**
4
- // · 每日积分发放 300 —— 每天服务端自动发,**当天 23:59:59 清零**(账单里有 `daily_expire`),也**无端点可领**
5
- // · 桌面端登录奖励 3000 —— **每号一次性**,走 `POST /desktop/v1/login/points/grant`,唯一需要领的
4
+ // · 每日积分 500 —— 服务端按天挂账,**当天第一次访问 `/office/v3/setting_info` 才入账**
5
+ // (惰性结算,不是签到;入账即有效期到 T+6 的 23:59:59,即官方文案的「登录后延长至 7 天」)
6
+ // · 桌面端登录奖励 3000 —— **每号一次性**,走 `POST /desktop/v1/login/points/grant`,唯一「领取」式接口
7
+ // · 充值加油包 —— 用户自购
8
+ // ⚠ 2026-10-10 的旧结论「每日 300、当天 23:59:59 清零、无端点可领」**已过时**:现为 500 分、有效期 7 天、
9
+ // 有明确触发端点。别再照旧注释写代码。
6
10
  // ⚠ 上游对「已经领过」的重复请求**照样回 code:0**,但积分一分不到账 —— 所以 `code:0` 绝不能当成功凭据,
7
- // 必须用账单流水裁决(见 claimRaccoonLoginReward)。谎报成功会让 daemon/CLI 输出假到账,比报错更坏。
11
+ // 必须用账单流水裁决(见 claimRaccoonLoginReward / claimRaccoonDailyPoints)。谎报成功会让 daemon/CLI 输出假到账,比报错更坏。
8
12
  import {
13
+ RACCOON_BILLS_PAGE_LIMIT,
14
+ RACCOON_DAILY_GRANT_EVENT_NAME,
9
15
  RACCOON_LOGIN_REWARD_EVENT_NAME,
10
16
  RACCOON_LOGIN_REWARD_POINTS,
11
17
  RACCOON_REQUEST_TIMEOUT_MS,
12
18
  raccoonBalanceUrl,
13
19
  raccoonBillsUrl,
14
20
  raccoonLoginGrantUrl,
21
+ raccoonOfficeSettingUrl,
15
22
  } from "./const.js";
16
23
  import { raccoonAuthHeaders } from "./headers.js";
17
24
  import { confirmRaccoonSession } from "./login.js";
@@ -183,3 +190,96 @@ export function raccoonClaimStatus(r) {
183
190
  if (r?.unverified) return "unverified";
184
191
  return "error";
185
192
  }
193
+
194
+ // —— 每日积分(惰性结算,每日可重复触发;与上面的一次性登录奖励是两件事) ——
195
+
196
+ /** 从账单里找「今天那笔每日积分发放」,返回 `{ points, at, expireAt }` 或 undefined。 */
197
+ export function findDailyGrantInBills(data, now = Date.now()) {
198
+ const rows = billsRows(data) || [];
199
+ const today = localDateKey(now);
200
+ for (const item of rows) {
201
+ if (item.biz_type !== "daily_grant") continue;
202
+ if (item.event_name && item.event_name !== RACCOON_DAILY_GRANT_EVENT_NAME) continue;
203
+ // 归属日以 grant_at 为准(上游把它固定成当天 00:00),缺失时回落到 created_at
204
+ const at = billTimeMs({ created_at: item.grant_at ?? item.created_at });
205
+ if (at === undefined || localDateKey(at) !== today) continue;
206
+ const expireAt = billTimeMs({ created_at: item.expire_at });
207
+ return {
208
+ points: num(item.points) ?? 0,
209
+ at,
210
+ ...(expireAt === undefined ? {} : { expireAt }),
211
+ };
212
+ }
213
+ return undefined;
214
+ }
215
+
216
+ /** 本地日期键 YYYY-MM-DD —— 上游的日界按 +08:00 切,用本机时区判同一天即可。 */
217
+ function localDateKey(ms) {
218
+ const d = new Date(ms);
219
+ if (!Number.isFinite(d.getTime())) return "";
220
+ const p = (n) => String(n).padStart(2, "0");
221
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
222
+ }
223
+
224
+ /** 拉当天账单(限量 200:够覆盖一天的重度对话消耗)。失败返回 undefined(判定降级,不抛)。 */
225
+ async function readBillsWide(opts) {
226
+ try {
227
+ const envelope = await request(raccoonBillsUrl(RACCOON_BILLS_PAGE_LIMIT), opts);
228
+ return envelope?.code === 0 ? billsRows(envelope.data) : undefined;
229
+ } catch {
230
+ return undefined;
231
+ }
232
+ }
233
+
234
+ /**
235
+ * 结算当日每日积分(可每天重复调用,上游幂等)。
236
+ *
237
+ * 机制:`GET /api/web/office/v3/setting_info` 是服务端的惰性结算钩子 ——
238
+ * 当天第一次访问它,服务端才把当天的每日积分真正挂账,并把有效期延到 T+6。
239
+ * 不调用的话,`balance.daily_points` 一直是 0、账单里也压根没有 `daily_grant`(2026-10-21 实测)。
240
+ *
241
+ * 返回四种非抛错结果之一:
242
+ * - `{ claimed: true, points, expireAt }` 本次真结算入账(账单里出现了今天那笔)
243
+ * - `{ claimed: false, alreadyToday: true, points, expireAt }` 今天已经结算过(正常态,不是失败)
244
+ * - `{ claimed: false, unverified: true }` 账单查不动,无法确认(不猜、不谎报)
245
+ * - 结算请求本身失败(业务码非 0 / 网络错误)→ 抛错(如实透出)
246
+ */
247
+ export async function claimRaccoonDailyPoints({ credential, fetchImpl = fetch, env = process.env, timeoutMs, now = Date.now() } = {}) {
248
+ const opts = { credential, fetchImpl, env, timeoutMs };
249
+
250
+ // 先查账单:今天已经结算过就别再打结算端点(省一次请求,也让日志含义更准确)
251
+ const before = await readBillsWide(opts);
252
+ if (before !== undefined) {
253
+ const hit = findDailyGrantInBills(before, now);
254
+ if (hit) return { claimed: false, alreadyToday: true, points: hit.points, ...(hit.expireAt === undefined ? {} : { expireAt: hit.expireAt }) };
255
+ }
256
+
257
+ const envelope = await request(raccoonOfficeSettingUrl(), opts);
258
+ if (envelope?.code !== 0) {
259
+ const err = new Error(`raccoon: 每日积分结算失败:${raccoonEnvelopeText(envelope, "上游未返回原因")}`);
260
+ err.code = envelope?.code;
261
+ err.status = envelope?.status;
262
+ throw err;
263
+ }
264
+
265
+ // 到账凭据只认账单:上游对已结算的重复请求同样回 code:0,回执不足以证明「这次发了」
266
+ const after = await readBillsWide(opts);
267
+ if (after === undefined) return { claimed: false, unverified: true, points: 0 };
268
+ const landed = findDailyGrantInBills(after, now);
269
+ if (!landed) {
270
+ // 连打两次 code:0 都没在账单里看到今天这笔 → 上游改了结算规则或账单口径,如实说未确认,别谎报
271
+ return { claimed: false, unverified: true, points: 0 };
272
+ }
273
+ return { claimed: true, points: landed.points, ...(landed.expireAt === undefined ? {} : { expireAt: landed.expireAt }) };
274
+ }
275
+
276
+ /**
277
+ * claimRaccoonDailyPoints 的结果 → 统一状态字(daemon 与 CLI 共用)。
278
+ * claimed=本次真入账 · already=今天已结算过(正常态) · unverified=账单查不动/没看到这笔,不下结论 · error=真失败。
279
+ */
280
+ export function raccoonDailyStatus(r) {
281
+ if (r?.claimed) return "claimed";
282
+ if (r?.alreadyToday) return "already";
283
+ if (r?.unverified) return "unverified";
284
+ return "error";
285
+ }