mslxdff 0.1.156 → 0.1.158

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 (144) hide show
  1. package/bin/mslxdff.js +4 -4
  2. package/docs/ARCHITECTURE.md +426 -0
  3. package/docs/FEATURE_TREE.md +164 -0
  4. package/docs/MOBILE.md +82 -0
  5. package/docs/adr/0001-reasoning-content-injection.md +14 -0
  6. package/docs/adr/0002-models-free-filter.md +12 -0
  7. package/docs/adr/0003-zero-state-no-auth.md +10 -0
  8. package/docs/adr/0004-bearer-token.md +18 -0
  9. package/docs/adr/0005-peer-mesh.md +53 -0
  10. package/docs/adr/0006-broadband-member.md +103 -0
  11. package/docs/adr/0007-multi-provider-prefix.md +25 -0
  12. package/docs/adr/0008-share-keys-to-peers.md +52 -0
  13. package/docs/adr/0009-chat-repl.md +37 -0
  14. package/docs/adr/0010-allowlist.md +36 -0
  15. package/docs/adr/0011-broadband-stream.md +30 -0
  16. package/docs/adr/0012-responses-endpoint-codex-sync.md +48 -0
  17. package/docs/adr/0013-node16-compat.md +41 -0
  18. package/docs/adr/0014-deepseek-provider.md +52 -0
  19. package/docs/adr/0015-upstream-probe-routing.md +50 -0
  20. package/docs/adr/0016-model-capabilities.md +27 -0
  21. package/docs/adr/0017-ai-sdk-upstream-engine.md +59 -0
  22. package/docs/adr/0018-zen-client-identity.md +52 -0
  23. package/docs/adr/0019-share-keys-always-lend.md +59 -0
  24. package/docs/adr/0020-zen-free-lane-agent-shape.md +52 -0
  25. package/docs/adr/0021-usage-report-jsonl.md +47 -0
  26. package/docs/adr/0022-models-capability-merge.md +61 -0
  27. package/docs/adr/0023-key-provider-default-direct.md +58 -0
  28. package/docs/adr/0024-node18-baseline.md +63 -0
  29. package/docs/adr/0025-workbuddy-authdir-follows-state.md +71 -0
  30. package/docs/adr/0026-cline-provider-id-unify.md +67 -0
  31. package/docs/adr/0027-codearts-provider.md +48 -0
  32. package/docs/adr/0028-traework-provider.md +34 -0
  33. package/docs/adr/0029-qoder-native-provider.md +60 -0
  34. package/docs/adr/0030-models-list-scoped-by-picks.md +53 -0
  35. package/docs/adr/0031-qoder-true-streaming.md +50 -0
  36. package/docs/adr/0032-generic-responses-channel.md +72 -0
  37. package/docs/adr/0033-cline-allowlist-auto-sync.md +75 -0
  38. package/docs/adr/0034-request-level-human-readable-observability.md +60 -0
  39. package/docs/adr/0035-sdk-channel-headers-timeout.md +49 -0
  40. package/docs/adr/0036-qoder-per-request-sticky-account.md +82 -0
  41. package/docs/adr/0037-qwenwork-independent-provider.md +82 -0
  42. package/docs/adr/0038-zcode-provider.md +140 -0
  43. package/docs/agents/domain.md +51 -0
  44. package/docs/agents/issue-tracker.md +30 -0
  45. package/docs/agents/triage-labels.md +15 -0
  46. package/docs/cli_help.md +1391 -0
  47. package/docs/cli_help_mini.md +133 -0
  48. package/docs/plans/bench-via-latency-2026-09-01.md +215 -0
  49. package/docs/plugins.md +187 -0
  50. package/package.json +1 -1
  51. package/src/auto.js +254 -254
  52. package/src/bench/cline-bench.js +42 -42
  53. package/src/bench/probe.js +70 -70
  54. package/src/bench/report.js +162 -162
  55. package/src/bench/runner.js +77 -77
  56. package/src/bench/via-probe.js +124 -124
  57. package/src/bench/via-routes.js +87 -87
  58. package/src/bench/workbuddy-bench.js +54 -54
  59. package/src/chat/engine.js +160 -160
  60. package/src/chat/gateway.js +163 -163
  61. package/src/chat/orchestrator.js +234 -234
  62. package/src/chat/prompt.js +70 -70
  63. package/src/chat/repl.js +88 -88
  64. package/src/chat/terminal.js +135 -135
  65. package/src/chat/tools.js +306 -306
  66. package/src/chat-pipeline/index.js +123 -123
  67. package/src/chat-pipeline/policy.js +76 -76
  68. package/src/chat-pipeline/serial-trial.js +210 -210
  69. package/src/cli/commands/group.js +249 -249
  70. package/src/cli/commands/model/list-providers.js +1 -1
  71. package/src/cli/commands/model/picks.js +50 -50
  72. package/src/cli/commands/provider/bench-via.js +247 -247
  73. package/src/cli/commands/provider/bench.js +141 -141
  74. package/src/cli/commands/provider/index.js +124 -116
  75. package/src/cli/commands/provider/models.js +139 -128
  76. package/src/cli/commands/provider/qwenwork-login.js +119 -0
  77. package/src/cli/commands/provider/zcode-login.js +77 -0
  78. package/src/cli/commands/provider/zcode-quota.js +55 -0
  79. package/src/cli/commands/sync.js +232 -232
  80. package/src/cli/provider-row.js +2 -2
  81. package/src/cli/status.js +279 -279
  82. package/src/daemon.js +96 -96
  83. package/src/model-capabilities/enrich.js +86 -86
  84. package/src/model-capabilities/index.js +183 -183
  85. package/src/model-capabilities/parse.js +70 -70
  86. package/src/models.js +225 -225
  87. package/src/providers/classify.js +1 -1
  88. package/src/providers/cline/auth.js +228 -228
  89. package/src/providers/cline/chat.js +307 -307
  90. package/src/providers/cline.js +2 -2
  91. package/src/providers/keyring.js +60 -56
  92. package/src/providers/qoder/chat.js +183 -174
  93. package/src/providers/qoder/index.js +230 -185
  94. package/src/providers/qoder/sse.js +103 -62
  95. package/src/providers/qwenwork/account-store.js +133 -0
  96. package/src/providers/qwenwork/constants.js +67 -0
  97. package/src/providers/qwenwork/cosy.js +120 -0
  98. package/src/providers/qwenwork/crypto.js +218 -0
  99. package/src/providers/qwenwork/http.js +20 -0
  100. package/src/providers/qwenwork/index.js +327 -0
  101. package/src/providers/qwenwork/payload.js +142 -0
  102. package/src/providers/qwenwork/rsa.js +54 -0
  103. package/src/providers/qwenwork/sse.js +268 -0
  104. package/src/providers/qwenwork/stream.js +130 -0
  105. package/src/providers/qwenwork/upstream.js +120 -0
  106. package/src/providers/qwenwork.js +1 -0
  107. package/src/providers/registry.js +66 -56
  108. package/src/providers/share-keys.js +2 -2
  109. package/src/providers/workbuddy/chat.js +248 -248
  110. package/src/providers/workbuddy/reshape.js +152 -152
  111. package/src/providers/workbuddy.js +2 -2
  112. package/src/providers/zcode/account-store.js +129 -0
  113. package/src/providers/zcode/auth.js +28 -0
  114. package/src/providers/zcode/chat.js +171 -0
  115. package/src/providers/zcode/const.js +54 -0
  116. package/src/providers/zcode/headers.js +55 -0
  117. package/src/providers/zcode/index.js +124 -0
  118. package/src/providers/zcode/models.js +65 -0
  119. package/src/providers/zcode/oauth.js +120 -0
  120. package/src/providers/zcode/quota.js +176 -0
  121. package/src/providers/zcode/sse.js +179 -0
  122. package/src/reasoning.js +32 -32
  123. package/src/routes/chat/gateway.js +46 -46
  124. package/src/routes/chat/relay-pipeline.js +250 -250
  125. package/src/routes/chat/via-route-handler.js +144 -144
  126. package/src/routes/hedge.js +255 -255
  127. package/src/routes/models-route.js +167 -167
  128. package/src/routes/peers.js +273 -273
  129. package/src/routes/stream.js +438 -438
  130. package/src/runtime/bootstrap.js +45 -45
  131. package/src/runtime/provider-gate.js +33 -30
  132. package/src/runtime/providers-setup.js +165 -165
  133. package/src/server.js +64 -64
  134. package/src/state/schemas/allowlist.js +92 -92
  135. package/src/sync-opencode.js +280 -280
  136. package/src/transport/index.js +244 -244
  137. package/src/transport/pool.js +56 -56
  138. package/src/transport/retry.js +24 -24
  139. package/src/transport/sse.js +93 -93
  140. package/src/upstream-probe/display.js +52 -52
  141. package/src/upstream-probe/probe.js +49 -49
  142. package/src/upstream-probe/rotate.js +110 -110
  143. package/src/upstream-probe/start.js +45 -45
  144. package/src/upstream.js +289 -289
@@ -0,0 +1,133 @@
1
+ // qwenwork 账号落盘单一源:auths/qwenwork-<uid>.json(0600 tmp+rename)+ state.json 双写。
2
+ // 照 src/providers/qwenwork/providers/qoder/account-store.js 的写法,命名空间独立(不得与 qoder 混)。
3
+ import { writeFileSync, mkdirSync, existsSync, renameSync, unlinkSync, readdirSync, readFileSync, chmodSync } from "node:fs";
4
+ import { join, dirname } from "node:path";
5
+ import { tmpdir } from "node:os";
6
+ import { isTestEnv, defaultStateFile } from "../../state/store.js";
7
+
8
+ export function authDirFor({ explicit = "", testEnv = false, stateFile } = {}) {
9
+ if (explicit) return explicit;
10
+ if (testEnv) return join(tmpdir(), "mslxdff-test-auths");
11
+ return join(dirname(stateFile), "auths");
12
+ }
13
+
14
+ export function resolveAuthDir() {
15
+ return authDirFor({
16
+ explicit: process.env.QWENWORK_AUTH_DIR || "",
17
+ testEnv: isTestEnv(),
18
+ stateFile: defaultStateFile(),
19
+ });
20
+ }
21
+
22
+ export function resolveAuthDirs() {
23
+ const primary = resolveAuthDir();
24
+ const cwdDir = join(process.cwd(), "auths");
25
+ return primary === cwdDir ? [primary] : [primary, cwdDir];
26
+ }
27
+
28
+ export function listAccountDocs({ dirs } = {}) {
29
+ const out = [];
30
+ const seen = new Set();
31
+ for (const dir of dirs || resolveAuthDirs()) {
32
+ let files = [];
33
+ try {
34
+ if (!existsSync(dir)) continue;
35
+ files = readdirSync(dir).filter((f) => f.startsWith("qwenwork-") && f.endsWith(".json"));
36
+ } catch { continue; }
37
+ for (const f of files) {
38
+ try {
39
+ const doc = JSON.parse(readFileSync(join(dir, f), "utf8"));
40
+ const uid = doc?.account?.uid;
41
+ if (!uid || !doc?.auth?.accessToken) continue;
42
+ if (seen.has(String(uid))) continue;
43
+ seen.add(String(uid));
44
+ out.push({ uid: String(uid), file: join(dir, f), dir, doc });
45
+ } catch {}
46
+ }
47
+ }
48
+ return out;
49
+ }
50
+
51
+ function writeAccountFile({ uid, accessToken, refreshToken = "", expiresAt = 0, name = "", email = "" }) {
52
+ const authDir = resolveAuthDir();
53
+ mkdirSync(authDir, { recursive: true });
54
+ const doc = {
55
+ account: { uid, name, email },
56
+ auth: { accessToken, refreshToken, expiresAt },
57
+ };
58
+ const fp = join(authDir, `qwenwork-${uid}.json`);
59
+ const tmp = `${fp}.tmp`;
60
+ writeFileSync(tmp, JSON.stringify(doc, null, 2), { mode: 0o600 });
61
+ try {
62
+ if (existsSync(fp)) { try { chmodSync(fp, 0o600); } catch {} unlinkSync(fp); }
63
+ renameSync(tmp, fp);
64
+ } catch {
65
+ writeFileSync(fp, JSON.stringify(doc, null, 2), { mode: 0o600 });
66
+ try { unlinkSync(tmp); } catch {}
67
+ }
68
+ try { chmodSync(fp, 0o600); } catch {}
69
+ return fp;
70
+ }
71
+
72
+ // state 落盘:keys[i] 存 JSON blob({device_token, refresh_token},对齐家族形状),auths 存 uid 索引行。
73
+ async function persistAccounts(accounts, file) {
74
+ const { loadProviderConfigs } = await import("../../state.js");
75
+ const { saveProviderConfig } = await import("../../state.js");
76
+ const cfg = (loadProviderConfigs(file ? { file } : {})?.qwenwork) || {};
77
+ const keys = [...(Array.isArray(cfg.keys) ? cfg.keys : [])];
78
+ const auths = [...(Array.isArray(cfg.auths) ? cfg.auths : [])];
79
+ let updated = 0;
80
+ for (const acc of accounts) {
81
+ if (!acc?.uid || !acc?.accessToken) continue;
82
+ const blob = JSON.stringify({ device_token: acc.accessToken, refresh_token: acc.refreshToken || "" });
83
+ const row = { uid: acc.uid, name: acc.name || "", refreshToken: acc.refreshToken || "" };
84
+ const idx = auths.findIndex((a) => String(a?.uid) === String(acc.uid));
85
+ if (idx >= 0) { keys[idx] = blob; auths[idx] = row; updated += 1; }
86
+ else { keys.push(blob); auths.push(row); }
87
+ }
88
+ // saveProviderConfig 起手保留 allowAnyModels(已在 state 层修复,见 ADR-0033 字段保留修复)
89
+ saveProviderConfig("qwenwork", { baseUrl: cfg.baseUrl || "", keys, auths }, file ? { file } : {});
90
+ return { keys, auths, updated };
91
+ }
92
+
93
+ export async function saveQwenworkAccount({ uid, accessToken, refreshToken = "", expiresAt = 0, name = "", email = "", file } = {}) {
94
+ if (!uid || !accessToken) throw new Error("saveQwenworkAccount: 缺少 uid/accessToken");
95
+ const fp = writeAccountFile({ uid, accessToken, refreshToken, expiresAt, name, email });
96
+ const st = await persistAccounts([{ uid, accessToken, refreshToken, name }], file);
97
+ return { file: fp, accounts: st.keys.length, updated: st.updated > 0 };
98
+ }
99
+
100
+ /** 回写刷新后的 token(上游每次 refresh 会轮换 refreshToken,必须落盘)。 */
101
+ export async function updateQwenworkTokens({ uid, accessToken, refreshToken = "", expiresAt = 0, file } = {}) {
102
+ if (!uid || !accessToken) throw new Error("updateQwenworkTokens: 缺少 uid/accessToken");
103
+ const docs = listAccountDocs();
104
+ const hit = docs.find((d) => String(d.uid) === String(uid));
105
+ const prev = hit?.doc || {};
106
+ const fp = writeAccountFile({
107
+ uid,
108
+ accessToken,
109
+ refreshToken: refreshToken || prev?.auth?.refreshToken || "",
110
+ expiresAt: expiresAt || 0,
111
+ name: prev?.account?.name || "",
112
+ email: prev?.account?.email || "",
113
+ });
114
+ await persistAccounts([{ uid, accessToken, refreshToken: refreshToken || prev?.auth?.refreshToken || "", name: prev?.account?.name || "" }], file);
115
+ try {
116
+ const { invalidateSession } = await import("./cosy.js");
117
+ invalidateSession({ uid, accessToken: prev?.auth?.accessToken });
118
+ } catch {}
119
+ return { file: fp };
120
+ }
121
+
122
+ // 从 provider keys 的 blob 还原凭据(device_token/deviceToken 双形状兼容)
123
+ export function accountFromBlob(blob) {
124
+ try {
125
+ const j = JSON.parse(String(blob || "{}"));
126
+ const accessToken = String(j.device_token || j.accessToken || "");
127
+ const refreshToken = String(j.refresh_token || j.refreshToken || "");
128
+ if (!accessToken) return null;
129
+ return { accessToken, refreshToken };
130
+ } catch {
131
+ return null;
132
+ }
133
+ }
@@ -0,0 +1,67 @@
1
+ // qwenwork(千问办公 gateway.qwenwork.cn)上游技术常量。
2
+ // 转译自 qwenwork2api-makers 的 edge-functions/_shared/config.js —— **禁止凭记忆改值**;
3
+ // 要改先现网复测(客户端一升级这些快照就可能 403)。
4
+ // Note: 为何独立 provider 而非 qoder 的新 region — 见 docs/adr/0037-qwenwork-independent-provider.md
5
+ export const BASE = "https://gateway.qwenwork.cn";
6
+
7
+ // OAuth 设备授权。client_id 与 qoder 恰好同值,但**不得 import qoder 常量**:
8
+ // 同 client_id 不代表同租户(RSA 模数/模型池/额度池均不同,实测见 ADR-0037)。
9
+ export const CLIENT_ID = "e883ade2-e6e3-4d6d-adf7-f92ceff5fdcb";
10
+ export const REDIRECT_URI = "qwenwork-cn://";
11
+
12
+ export const DEVICE_AUTH_URL = `${BASE}/device/selectAccounts`;
13
+ export const POLL_URL = `${BASE}/api/v1/deviceToken/poll`;
14
+ export const REFRESH_URL = `${BASE}/api/v1/deviceToken/refresh`;
15
+ export const USERINFO_URL = `${BASE}/api/v1/userinfo`;
16
+ // 额度/套餐:data.{user,plan,quota},quota.remaining 即积分余量(实测新免费号 2099.277)
17
+ export const ACCOUNT_CONTEXT_URL = `${BASE}/api/v1/adapter/user/account-context?include=user,plan,quota`;
18
+ // 无 `Encode=1`:请求体走**纯 JSON**,不像 qoder 那样过自定义 base64 字母表
19
+ export const CHAT_URL = `${BASE}/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common`;
20
+ export const MODELS_URL = `${BASE}/algo/api/v2/model/list`;
21
+
22
+ export function envStr(name, fallback) {
23
+ const v = process.env[name];
24
+ return typeof v === "string" && v.trim() ? v.trim() : fallback;
25
+ }
26
+
27
+ /** env 可覆盖,排障不必改代码(改后必须现网复测)。 */
28
+ export const UA = envStr("MSLXDFF_QWENWORK_UA", "qoderwork/1.0.5");
29
+ export const COSY_VERSION = envStr("MSLXDFF_QWENWORK_COSY_VERSION", "1.1.18");
30
+ export const IDE_VERSION = envStr("MSLXDFF_QWENWORK_IDE_VERSION", "1.0.5");
31
+ export const RELEASE_VERSION = envStr("MSLXDFF_QWENWORK_RELEASE_VERSION", "1.0.5-26090901");
32
+ export const BUILD = envStr("MSLXDFF_QWENWORK_BUILD", "26090901");
33
+ export const CLIENT_TYPE = "6";
34
+ export const BUSINESS_PRODUCT = "qoder_work";
35
+ export const BUSINESS_TYPE = "agent";
36
+ export const SCENE = "qwork";
37
+ export const MACHINE_OS = "x86_64_win32";
38
+
39
+ // 上游 model/list 返回 11 个根切片,实测**只有 `qwork` 非空**(其余 n=0):
40
+ // chat/developer/assistant/inline/quest/nap/experts/qwake 全 0 —— 与 qoder 的 `chat` 切片零交集。
41
+ export const MODEL_SLICE = "qwork";
42
+ export const DEFAULT_MODEL = "flash";
43
+ export const CONTEXT_LENGTH = 180000;
44
+ export const MAX_TOKENS_DEFAULT = 32000;
45
+
46
+ // 实测模型池(2026-09-29 真号取证):flash price_factor=0.1 / pro=1 / qwen3.8-max-preview=1.8,
47
+ // 三者均 is_reasoning=true、is_vl=true、context_config 1M(默认)/200K/400K。
48
+ // 仅作取数失败时的兜底展示,真实目录以 /model/list 为准。
49
+ export const KNOWN_MODELS = [
50
+ { key: "flash", name: "标准", priceFactor: 0.1 },
51
+ { key: "pro", name: "高级", priceFactor: 1 },
52
+ { key: "qwen3.8-max-preview", name: "Qwen3.8-Max", priceFactor: 1.8 },
53
+ ];
54
+
55
+ // RSA-1024 模数(逐字符转译 _shared/crypto.js 的 RSA_N,勿改)
56
+ export const RSA_MODULUS_HEX =
57
+ "c0f22307e5cd362e296bb04470f6de8fbf935ce24e8fcf511a0e2701329769c4" +
58
+ "a76e499bb938036a52af1eaf818cf79a2600620e3ce87e371d2ca6d85803606a" +
59
+ "1b3fa5e874643c9ed2db7e85673ef7227fca56e2e7c08f0927609bb896a9f24b" +
60
+ "e1782099a66016a5bfdc3f1ff756bfc9e88d7b5dc5be30bf45a0223a00ebcecf";
61
+ export const RSA_EXPONENT = 65537;
62
+
63
+ export const LOGIN_TTL_MS = 10 * 60 * 1000;
64
+ export const COOLDOWN_MS = 30_000;
65
+ export const QUOTA_COOLDOWN_MS = 60 * 60 * 1000;
66
+ export const REFRESH_MARGIN_MS = 30 * 60 * 1000;
67
+ export const MODELS_CACHE_MS = 10 * 60 * 1000;
@@ -0,0 +1,120 @@
1
+ // vendor 自 _shared/cosy.js(COSY 会话 + 签名头),逐字搬,仅把常量来源改指 constants.js。
2
+ // 关键不变式(改动即 403):
3
+ // · identity/payload 都必须 key 升序紧凑 JSON(sortedCompact)
4
+ // · 签名 = md5(payloadB64 \n cosyKey \n date \n body \n pathSig),pathSig 去 /algo 前缀、不含 query
5
+ // · authorization = `Bearer COSY.${payloadB64}.${sig}`;payloadB64 是**标准 base64(带 padding)**
6
+ // · 同一 requestId 重放会被上游判 `code 103 Duplicate request`
7
+ import { uuid, b64, b64url, utf8, aesCbcEncrypt, md5 } from "./crypto.js";
8
+ import { rsaPkcs1Encrypt } from "./rsa.js";
9
+ import {
10
+ COSY_VERSION, IDE_VERSION, RELEASE_VERSION, BUILD, CLIENT_TYPE,
11
+ BUSINESS_PRODUCT, BUSINESS_TYPE, SCENE, MACHINE_OS, UA,
12
+ } from "./constants.js";
13
+
14
+ const cache = new Map();
15
+
16
+ function sortedCompact(obj) {
17
+ const keys = Object.keys(obj).sort();
18
+ let out = "{";
19
+ for (let i = 0; i < keys.length; i++) {
20
+ if (i > 0) out += ",";
21
+ out += JSON.stringify(keys[i]) + ":" + JSON.stringify(obj[keys[i]]);
22
+ }
23
+ return out + "}";
24
+ }
25
+
26
+ function newSession(account) {
27
+ const machineID = uuid();
28
+ const seed = (uuid() + uuid()).slice(0, 50);
29
+ const machineToken = b64url(utf8(seed));
30
+ const machineType = uuid().replace(/-/g, "").slice(0, 18);
31
+ const tempKey = uuid().replace(/-/g, "").slice(0, 16);
32
+
33
+ const identity = sortedCompact({
34
+ uid: account.uid || "",
35
+ aid: account.uid || "",
36
+ name: account.nickname || "",
37
+ email: account.email || "",
38
+ security_oauth_token: account.accessToken,
39
+ });
40
+
41
+ return {
42
+ machineID,
43
+ machineToken,
44
+ machineType,
45
+ tempKey,
46
+ cosyKey: rsaPkcs1Encrypt(utf8(tempKey)),
47
+ info: b64(aesCbcEncrypt(utf8(identity), utf8(tempKey))),
48
+ accessToken: account.accessToken,
49
+ };
50
+ }
51
+
52
+ export function sessionFor(account) {
53
+ if (!account || !account.accessToken) throw new Error("cosy: empty access token");
54
+ const key = account.id || account.uid || account.accessToken.slice(0, 16);
55
+ const hit = cache.get(key);
56
+ if (hit && hit.accessToken === account.accessToken) return hit;
57
+ if (cache.size > 128) cache.clear();
58
+ const sess = newSession(account);
59
+ cache.set(key, sess);
60
+ return sess;
61
+ }
62
+
63
+ export function invalidateSession(account) {
64
+ const key = account && (account.id || account.uid);
65
+ if (key) cache.delete(key);
66
+ }
67
+
68
+ function pathSig(rawURL) {
69
+ const u = new URL(rawURL);
70
+ let p = u.pathname;
71
+ if (p.startsWith("/algo")) p = p.slice("/algo".length);
72
+ return p;
73
+ }
74
+
75
+ export function signHeaders(account, body, rawURL, modelKey, accept) {
76
+ const sess = sessionFor(account);
77
+ const payload = sortedCompact({
78
+ cosyVersion: COSY_VERSION,
79
+ ideVersion: IDE_VERSION,
80
+ info: sess.info,
81
+ requestId: uuid(),
82
+ version: "v1",
83
+ });
84
+ const payloadB64 = b64(utf8(payload));
85
+ const date = Math.floor(Date.now() / 1000).toString();
86
+ const sig = md5(`${payloadB64}\n${sess.cosyKey}\n${date}\n${body}\n${pathSig(rawURL)}`);
87
+
88
+ const headers = {
89
+ accept: accept || "text/event-stream",
90
+ "content-type": "application/json",
91
+ "user-agent": UA,
92
+ "x-request-id": uuid(),
93
+ "x-qwenwork-version": IDE_VERSION,
94
+ "x-qwenwork-release-version": RELEASE_VERSION,
95
+ "x-qwenwork-build": BUILD,
96
+ "x-qwenwork-platform": "win32",
97
+ "x-qwenwork-arch": "x64",
98
+ "x-qwenwork-channel": "stable",
99
+ "cosy-version": COSY_VERSION,
100
+ "cosy-clienttype": CLIENT_TYPE,
101
+ "cosy-business-product": BUSINESS_PRODUCT,
102
+ "cosy-business-type": BUSINESS_TYPE,
103
+ "cosy-scene": SCENE,
104
+ "cosy-machineos": MACHINE_OS,
105
+ "login-version": "v2",
106
+ authorization: `Bearer COSY.${payloadB64}.${sig}`,
107
+ "cosy-key": sess.cosyKey,
108
+ "cosy-user": account.uid || "",
109
+ "cosy-date": date,
110
+ "cosy-machineid": sess.machineID,
111
+ "accept-encoding": "identity",
112
+ connection: "keep-alive",
113
+ "cache-control": "no-cache",
114
+ };
115
+ if (modelKey) {
116
+ headers["x-model-key"] = modelKey;
117
+ headers["x-model-source"] = "system";
118
+ }
119
+ return headers;
120
+ }
@@ -0,0 +1,218 @@
1
+ // vendor 自 qwenwork2api-makers 的 edge-functions/_shared/crypto.js(逐字搬,仅加 webcrypto 兜底)。
2
+ // 原作者手写 AES/RSA/MD5 是因为 Cloudflare Workers 无 node:crypto;**不要**"顺手优化"成原生实现 ——
3
+ // 实测换成 node:crypto 后上游回 `code 101 Signature invalid`(RSA/AES 材料与上游期望不等价)。
4
+ // Node 侧需要 globalThis.crypto(getRandomValues / subtle.digest);<19 用 node:crypto 的 webcrypto 兜底。
5
+ if (!globalThis.crypto || !globalThis.crypto.subtle) {
6
+ const { webcrypto } = await import("node:crypto");
7
+ globalThis.crypto = webcrypto;
8
+ }
9
+
10
+ const SBOX = (() => {
11
+ const s = new Uint8Array(256);
12
+ let p = 1;
13
+ let q = 1;
14
+ do {
15
+ p = p ^ ((p << 1) & 0xff) ^ (p & 0x80 ? 0x1b : 0);
16
+ q ^= q << 1;
17
+ q ^= q << 2;
18
+ q ^= q << 4;
19
+ if (q & 0x80) q ^= 0x09;
20
+ q &= 0xff;
21
+ const x = q ^ ((q << 1) | (q >> 7)) ^ ((q << 2) | (q >> 6)) ^ ((q << 3) | (q >> 5)) ^ ((q << 4) | (q >> 4));
22
+ s[p] = (x ^ 0x63) & 0xff;
23
+ } while (p !== 1);
24
+ s[0] = 0x63;
25
+ return s;
26
+ })();
27
+
28
+ const RCON = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
29
+
30
+ export function utf8(str) {
31
+ return new TextEncoder().encode(str);
32
+ }
33
+
34
+ export function hex(bytes) {
35
+ let out = "";
36
+ for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
37
+ return out;
38
+ }
39
+
40
+ export function b64(bytes) {
41
+ let s = "";
42
+ for (let i = 0; i < bytes.length; i++) s += String.fromCharCode(bytes[i]);
43
+ return btoa(s);
44
+ }
45
+
46
+ export function unb64(str) {
47
+ const s = atob(str);
48
+ const out = new Uint8Array(s.length);
49
+ for (let i = 0; i < s.length; i++) out[i] = s.charCodeAt(i);
50
+ return out;
51
+ }
52
+
53
+ export function b64url(bytes) {
54
+ return b64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
55
+ }
56
+
57
+ export function uuid() {
58
+ const r = new Uint8Array(16);
59
+ crypto.getRandomValues(r);
60
+ r[6] = (r[6] & 0x0f) | 0x40;
61
+ r[8] = (r[8] & 0x3f) | 0x80;
62
+ const h = hex(r);
63
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
64
+ }
65
+
66
+ const MD5_S = [
67
+ 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
68
+ 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
69
+ ];
70
+
71
+ const MD5_K = new Int32Array(64);
72
+ for (let i = 0; i < 64; i++) MD5_K[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 4294967296) | 0;
73
+
74
+ function rotl(x, n) {
75
+ return (x << n) | (x >>> (32 - n));
76
+ }
77
+
78
+ export function md5(input) {
79
+ const msg = typeof input === "string" ? utf8(input) : input;
80
+ const len = msg.length;
81
+ const bitLen = len * 8;
82
+ const padLen = (56 - ((len + 1) % 64) + 64) % 64;
83
+ const total = len + 1 + padLen + 8;
84
+ const buf = new Uint8Array(total);
85
+ buf.set(msg, 0);
86
+ buf[len] = 0x80;
87
+ const view = new DataView(buf.buffer);
88
+ view.setUint32(total - 8, bitLen >>> 0, true);
89
+ view.setUint32(total - 4, Math.floor(bitLen / 4294967296), true);
90
+
91
+ let a0 = 0x67452301;
92
+ let b0 = 0xefcdab89;
93
+ let c0 = 0x98badcfe;
94
+ let d0 = 0x10325476;
95
+
96
+ for (let i = 0; i < total; i += 64) {
97
+ const m = new Int32Array(16);
98
+ for (let j = 0; j < 16; j++) m[j] = view.getInt32(i + j * 4, true);
99
+ let a = a0;
100
+ let b = b0;
101
+ let c = c0;
102
+ let d = d0;
103
+ for (let j = 0; j < 64; j++) {
104
+ let f;
105
+ let g;
106
+ if (j < 16) {
107
+ f = (b & c) | (~b & d);
108
+ g = j;
109
+ } else if (j < 32) {
110
+ f = (d & b) | (~d & c);
111
+ g = (5 * j + 1) % 16;
112
+ } else if (j < 48) {
113
+ f = b ^ c ^ d;
114
+ g = (3 * j + 5) % 16;
115
+ } else {
116
+ f = c ^ (b | ~d);
117
+ g = (7 * j) % 16;
118
+ }
119
+ f = (f + a + MD5_K[j] + m[g]) | 0;
120
+ a = d;
121
+ d = c;
122
+ c = b;
123
+ b = (b + rotl(f, MD5_S[j])) | 0;
124
+ }
125
+ a0 = (a0 + a) | 0;
126
+ b0 = (b0 + b) | 0;
127
+ c0 = (c0 + c) | 0;
128
+ d0 = (d0 + d) | 0;
129
+ }
130
+
131
+ const out = new Uint8Array(16);
132
+ const ov = new DataView(out.buffer);
133
+ ov.setInt32(0, a0, true);
134
+ ov.setInt32(4, b0, true);
135
+ ov.setInt32(8, c0, true);
136
+ ov.setInt32(12, d0, true);
137
+ return hex(out);
138
+ }
139
+
140
+ function xtime(a) {
141
+ return ((a << 1) ^ (a & 0x80 ? 0x1b : 0)) & 0xff;
142
+ }
143
+
144
+ function keyExpansion(key) {
145
+ const w = new Uint8Array(176);
146
+ w.set(key, 0);
147
+ for (let i = 4; i < 44; i++) {
148
+ const t = [w[(i - 1) * 4], w[(i - 1) * 4 + 1], w[(i - 1) * 4 + 2], w[(i - 1) * 4 + 3]];
149
+ if (i % 4 === 0) {
150
+ const r = t[0];
151
+ t[0] = t[1];
152
+ t[1] = t[2];
153
+ t[2] = t[3];
154
+ t[3] = r;
155
+ for (let j = 0; j < 4; j++) t[j] = SBOX[t[j]];
156
+ t[0] ^= RCON[i / 4 - 1];
157
+ }
158
+ for (let j = 0; j < 4; j++) w[i * 4 + j] = w[(i - 4) * 4 + j] ^ t[j];
159
+ }
160
+ return w;
161
+ }
162
+
163
+ function addRoundKey(state, w, round) {
164
+ for (let c = 0; c < 4; c++) {
165
+ for (let r = 0; r < 4; r++) state[c * 4 + r] ^= w[round * 16 + c * 4 + r];
166
+ }
167
+ }
168
+
169
+ function subBytes(state) {
170
+ for (let i = 0; i < 16; i++) state[i] = SBOX[state[i]];
171
+ }
172
+
173
+ function shiftRows(s) {
174
+ const t = s.slice();
175
+ const map = [0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, 1, 6, 11];
176
+ for (let i = 0; i < 16; i++) s[i] = t[map[i]];
177
+ }
178
+
179
+ function mixColumns(s) {
180
+ for (let c = 0; c < 4; c++) {
181
+ const i = c * 4;
182
+ const a0 = s[i];
183
+ const a1 = s[i + 1];
184
+ const a2 = s[i + 2];
185
+ const a3 = s[i + 3];
186
+ s[i] = xtime(a0) ^ (xtime(a1) ^ a1) ^ a2 ^ a3;
187
+ s[i + 1] = a0 ^ xtime(a1) ^ (xtime(a2) ^ a2) ^ a3;
188
+ s[i + 2] = a0 ^ a1 ^ xtime(a2) ^ (xtime(a3) ^ a3);
189
+ s[i + 3] = (xtime(a0) ^ a0) ^ a1 ^ a2 ^ xtime(a3);
190
+ }
191
+ }
192
+
193
+ export function aesCbcEncrypt(plain, key) {
194
+ const w = keyExpansion(key);
195
+ const padLen = 16 - (plain.length % 16);
196
+ const data = new Uint8Array(plain.length + padLen);
197
+ data.set(plain, 0);
198
+ for (let i = plain.length; i < data.length; i++) data[i] = padLen;
199
+ const out = new Uint8Array(data.length);
200
+ const block = new Uint8Array(16);
201
+ let prev = key.slice(0, 16);
202
+ for (let off = 0; off < data.length; off += 16) {
203
+ for (let i = 0; i < 16; i++) block[i] = data[off + i] ^ prev[i];
204
+ addRoundKey(block, w, 0);
205
+ for (let round = 1; round < 10; round++) {
206
+ subBytes(block);
207
+ shiftRows(block);
208
+ mixColumns(block);
209
+ addRoundKey(block, w, round);
210
+ }
211
+ subBytes(block);
212
+ shiftRows(block);
213
+ addRoundKey(block, w, 10);
214
+ out.set(block, off);
215
+ prev = block.slice(0, 16);
216
+ }
217
+ return out;
218
+ }
@@ -0,0 +1,20 @@
1
+ // vendor 自 _shared/http.js(只保留本 provider 用得上的部分;CORS/preflight 属原项目的边缘层,不带)。
2
+ export function cleanErrorText(value) {
3
+ let s = String(value === undefined || value === null ? "" : value);
4
+ s = s
5
+ .replace(/<script[\s\S]*?<\/script>/gi, " ")
6
+ .replace(/<style[\s\S]*?<\/style>/gi, " ")
7
+ .replace(/<[^>]*>/g, " ")
8
+ .replace(/[\r\n\t]+/g, " ")
9
+ .replace(/[^\S ]+/g, "")
10
+ .replace(/\s+/g, " ")
11
+ .trim();
12
+ if (s.length > 200) s = s.slice(0, 200);
13
+ return s;
14
+ }
15
+
16
+ export function timeoutSignal(ms) {
17
+ const controller = new AbortController();
18
+ const timer = setTimeout(() => controller.abort(), ms);
19
+ return { signal: controller.signal, done: () => clearTimeout(timer) };
20
+ }