@bokutake/dsh-connect-qoder 0.0.0-stage → 1.28.0
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/CHANGELOG.md +4860 -0
- package/LICENSE +21 -0
- package/LICENSE-MODIFICATIONS.md +60 -0
- package/README.en.md +492 -0
- package/README.md +498 -2
- package/THIRD_PARTY_NOTICES.md +60 -0
- package/cordis.patch.yml +12 -0
- package/docs/DESIGN.md +249 -0
- package/docs/DSH-0.2.1-RC1-FOLLOWUP.md +348 -0
- package/docs/DSH-0.2.2-RC1-FOLLOWUP.md +328 -0
- package/docs/DSH-0.2.2-RC2-FOLLOWUP.md +342 -0
- package/docs/DSH-0.2.2-RC3-FOLLOWUP.md +317 -0
- package/docs/DSH-0.2.2-RC5-FOLLOWUP.md +219 -0
- package/docs/PAT.md +191 -0
- package/docs/PRIVACY.md +109 -0
- package/docs/PROMO_BADGE.md +293 -0
- package/docs/assets/dsh-connect-qoder-composer-credits.png +0 -0
- package/docs/assets/dsh-connect-qoder-model-management.png +0 -0
- package/docs/assets/dsh-connect-qoder-model-picker.png +0 -0
- package/docs/assets/dsh-connect-qoder-promo-badge.png +0 -0
- package/docs/assets/dsh-connect-qoder-settings-page.png +0 -0
- package/docs/assets/dsh-connect-qoder-usage-card.png +0 -0
- package/docs/issues/magpie-330-billing-count.md +91 -0
- package/icons/dsh-connect-qoder-128.png +0 -0
- package/icons/dsh-connect-qoder-64.png +0 -0
- package/lib/bin.d.ts +26 -0
- package/lib/bin.js +219 -0
- package/lib/client.js +9252 -0
- package/lib/host-heartbeat-Daj8rZV0.js +4497 -0
- package/lib/index.d.ts +872 -0
- package/lib/index.js +6567 -0
- package/lib/transfer-pMn4lOHy.js +171 -0
- package/package.json +151 -4
- package/screenshots.json +8 -0
|
@@ -0,0 +1,4497 @@
|
|
|
1
|
+
import { createCipheriv, createHash, publicEncrypt, randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import { execFile, execFileSync } from "node:child_process";
|
|
3
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
import { readFile, rm, writeFile } from "node:fs/promises";
|
|
7
|
+
import { homedir, hostname } from "node:os";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { withFileLock, writeFileAtomic } from "@deepseek-ai/dsh-atomic-write";
|
|
10
|
+
import { resolveDshHome } from "@deepseek-ai/dsh-home-paths";
|
|
11
|
+
//#region src/cosy.ts
|
|
12
|
+
/**
|
|
13
|
+
* Qoder cosy 协议:加密与签名原语(TypeScript 移植)。
|
|
14
|
+
*
|
|
15
|
+
* 协议来源(社区逆向 + 官方产物核对):
|
|
16
|
+
* - fengyinxia/qoder2api(MIT):qoder_auth.py —— PAT→jobToken 交换、cosy
|
|
17
|
+
* 签名、自定义 base64、RSA/AES 会话构建,实测可用(CN 网关)。
|
|
18
|
+
* - x_Zhengyuuuui/qoder2api(Go 版):internal/cosy/* —— 同一协议的 Go
|
|
19
|
+
* 实现,含设备指纹派生(fingerprint.go),并有 CN / Global 双区域端点。
|
|
20
|
+
* - @qoder-ai/qoder-agent-sdk 官方 .d.ts:模型字段、用量字段的官方命名。
|
|
21
|
+
*
|
|
22
|
+
* 本模块只做「无状态纯函数 + 加密原语」,不触网;网络与流程在 upstream.ts。
|
|
23
|
+
*
|
|
24
|
+
* @module dsh-connect-qoder/cosy
|
|
25
|
+
*/
|
|
26
|
+
/** cosy 自定义 base64 字母表(与 qoder2api 逐字节一致)。 */
|
|
27
|
+
const CUSTOM_ALPHABET = "_doRTgHZBKcGVjlvpC,@aFSx#DPuNJme&i*MzLOEn)sUrthbf%Y^w.(kIQyXqWA!";
|
|
28
|
+
const STD_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
29
|
+
const s2c = /* @__PURE__ */ new Map();
|
|
30
|
+
const c2s = /* @__PURE__ */ new Map();
|
|
31
|
+
for (let i = 0; i < 64; i += 1) {
|
|
32
|
+
s2c.set(STD_ALPHABET[i], CUSTOM_ALPHABET[i]);
|
|
33
|
+
c2s.set(CUSTOM_ALPHABET[i], STD_ALPHABET[i]);
|
|
34
|
+
}
|
|
35
|
+
s2c.set("=", "$");
|
|
36
|
+
c2s.set("$", "=");
|
|
37
|
+
/**
|
|
38
|
+
* Qoder 自定义 base64 编码:先标准 base64,再按 `n/3` 三块重排,
|
|
39
|
+
* 最后把每个字符映射到自定义字母表(含自定义 pad `$`)。
|
|
40
|
+
*/
|
|
41
|
+
function cosyEncode(plaintext) {
|
|
42
|
+
const std = Buffer.from(plaintext).toString("base64");
|
|
43
|
+
const n = std.length;
|
|
44
|
+
const a = Math.floor(n / 3);
|
|
45
|
+
const rearranged = std.slice(n - a) + std.slice(a, n - a) + std.slice(0, a);
|
|
46
|
+
let out = "";
|
|
47
|
+
for (const ch of rearranged) {
|
|
48
|
+
const mapped = s2c.get(ch);
|
|
49
|
+
if (mapped === void 0) throw new Error(`cosy encode: char out of alphabet: ${ch}`);
|
|
50
|
+
out += mapped;
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
/** RFC1123 格式的当前 UTC 时间,用于旧式签名头。 */
|
|
55
|
+
function currentRfc1123Date() {
|
|
56
|
+
return (/* @__PURE__ */ new Date()).toUTCString();
|
|
57
|
+
}
|
|
58
|
+
function md5Hex(input) {
|
|
59
|
+
return createHash("md5").update(input, "utf8").digest("hex");
|
|
60
|
+
}
|
|
61
|
+
function sha512Base64Url(input) {
|
|
62
|
+
return createHash("sha512").update(input, "utf8").digest("base64url");
|
|
63
|
+
}
|
|
64
|
+
/** cosy 签名常量。 */
|
|
65
|
+
const COSY_APPCODE = "cosy";
|
|
66
|
+
const COSY_SECRET_B64 = "d2FyLCB3YXIgbmV2ZXIgY2hhbmdlcw==";
|
|
67
|
+
/** 旧式请求签名:md5("cosy&<secret>&<rfc1123date>")。 */
|
|
68
|
+
function signLegacy(date) {
|
|
69
|
+
return md5Hex(`${COSY_APPCODE}&${COSY_SECRET_B64}&${date}`);
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Qoder 网关 RSA 公钥(客户端用它加密会话临时密钥)。
|
|
73
|
+
* 与 qoder2api / Go 克隆一致。
|
|
74
|
+
*/
|
|
75
|
+
const SERVER_PUBKEY_PEM = `-----BEGIN PUBLIC KEY-----
|
|
76
|
+
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA8iMH5c02LilrsERw9t6Pv5Nc
|
|
77
|
+
4k6Pz1EaDicBMpdpxKduSZu5OANqUq8er4GM95omAGIOPOh+Nx0spthYA2BqGz+l
|
|
78
|
+
6HRkPJ7S236FZz73In/KVuLnwI8JJ2CbuJap8kvheCCZpmAWpb/cPx/3Vr/J6I17
|
|
79
|
+
XcW+ML9FoCI6AOvOzwIDAQAB
|
|
80
|
+
-----END PUBLIC KEY-----`;
|
|
81
|
+
/** cosy 版本号(客户端身份的一部分,与 qoder2api 实测一致)。 */
|
|
82
|
+
const COSY_VERSION = "0.1.43";
|
|
83
|
+
/** AES-CBC + PKCS7 填充。 */
|
|
84
|
+
function aesCbcEncrypt(plain, key) {
|
|
85
|
+
const iv = key;
|
|
86
|
+
const blockSize = 16;
|
|
87
|
+
const padLen = blockSize - plain.length % blockSize;
|
|
88
|
+
const padded = new Uint8Array(plain.length + padLen);
|
|
89
|
+
padded.set(plain);
|
|
90
|
+
padded.fill(padLen, plain.length);
|
|
91
|
+
const cipher = createCipheriv("aes-128-cbc", key, iv);
|
|
92
|
+
const out = Buffer.concat([cipher.update(padded), cipher.final()]);
|
|
93
|
+
return new Uint8Array(out);
|
|
94
|
+
}
|
|
95
|
+
/** RSA PKCS1v1.5 加密(用网关公钥加密会话临时密钥)。 */
|
|
96
|
+
function rsaEncrypt(plain) {
|
|
97
|
+
const { publicKey } = requirePublicKey();
|
|
98
|
+
const out = publicEncrypt({
|
|
99
|
+
key: publicKey,
|
|
100
|
+
padding: 1
|
|
101
|
+
}, Buffer.from(plain));
|
|
102
|
+
return new Uint8Array(out);
|
|
103
|
+
}
|
|
104
|
+
let cachedPublicKey;
|
|
105
|
+
function requirePublicKey() {
|
|
106
|
+
if (cachedPublicKey === void 0) cachedPublicKey = { publicKey: SERVER_PUBKEY_PEM };
|
|
107
|
+
return cachedPublicKey;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* 新会话:生成临时密钥 → RSA 加密得 cosyKey → AES 加密身份载荷得 info。
|
|
111
|
+
* `tempKey` 用 16 字节随机数的 hex 前 16 字符(与 qoder2api 一致)。
|
|
112
|
+
*/
|
|
113
|
+
function newCosySession(identity, machineId, machineToken, machineType) {
|
|
114
|
+
const tempKey = new Uint8Array(Buffer.from(randomBytes(16).toString("hex").slice(0, 16), "utf8"));
|
|
115
|
+
const cosyKeyBytes = rsaEncrypt(tempKey);
|
|
116
|
+
const cosyKey = Buffer.from(cosyKeyBytes).toString("base64");
|
|
117
|
+
const payload = JSON.stringify(identityPayload(identity));
|
|
118
|
+
return {
|
|
119
|
+
tempKey,
|
|
120
|
+
cosyKey,
|
|
121
|
+
info: Buffer.from(aesCbcEncrypt(new Uint8Array(Buffer.from(payload, "utf8")), tempKey)).toString("base64"),
|
|
122
|
+
identity,
|
|
123
|
+
machineId,
|
|
124
|
+
machineToken,
|
|
125
|
+
machineType
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
function identityPayload(identity) {
|
|
129
|
+
return {
|
|
130
|
+
name: identity.name,
|
|
131
|
+
aid: identity.aid,
|
|
132
|
+
uid: identity.uid,
|
|
133
|
+
yx_uid: identity.yx_uid,
|
|
134
|
+
organization_id: identity.organization_id,
|
|
135
|
+
organization_name: identity.organization_name,
|
|
136
|
+
user_type: identity.user_type,
|
|
137
|
+
security_oauth_token: identity.security_oauth_token,
|
|
138
|
+
refresh_token: identity.refresh_token
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* Bearer 载荷:{cosyVersion, ideVersion, info, requestId, version} 的
|
|
143
|
+
* 标准 base64(键序按字典序,与 qoder2api 一致)。
|
|
144
|
+
*
|
|
145
|
+
* `cosyVersion` 必须与 `cosy-version` **请求头**同值。实测抓包(qoderclicn
|
|
146
|
+
* 1.1.94)解出的载荷是 `{version:"v1", requestId, info, cosyVersion:"1.1.94",
|
|
147
|
+
* ideVersion:""}` —— 头上发什么版本,载荷里就是什么版本。
|
|
148
|
+
*
|
|
149
|
+
* 此前这里用独立的 `COSY_VERSION`(`0.1.43`),与头部的 `1.1.69` 并不一致,
|
|
150
|
+
* 相当于同一个请求里声明了两个不同的客户端版本。它能跑通,但那是自相矛盾的
|
|
151
|
+
* 身份;统一之后两者同源。
|
|
152
|
+
*/
|
|
153
|
+
function buildPayloadB64(info, cosyVersion = COSY_VERSION) {
|
|
154
|
+
const payload = {
|
|
155
|
+
cosyVersion,
|
|
156
|
+
ideVersion: "",
|
|
157
|
+
info,
|
|
158
|
+
requestId: randomUUID(),
|
|
159
|
+
version: "v1"
|
|
160
|
+
};
|
|
161
|
+
const sorted = Object.fromEntries(Object.entries(payload).sort(([a], [b]) => a < b ? -1 : 1));
|
|
162
|
+
return Buffer.from(JSON.stringify(sorted)).toString("base64");
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* 请求签名:md5(payloadB64 \n cosyKey \n date \n body \n pathWithoutAlgo)。
|
|
166
|
+
*/
|
|
167
|
+
function signRequest(payloadB64, cosyKey, cosyDate, body, pathSig) {
|
|
168
|
+
return md5Hex(`${payloadB64}\n${cosyKey}\n${cosyDate}\n${body}\n${pathSig}`);
|
|
169
|
+
}
|
|
170
|
+
/** 组装 Authorization 头:`Bearer COSY.<payloadB64>.<sig>`。 */
|
|
171
|
+
function composeBearer(payloadB64, sig) {
|
|
172
|
+
return `Bearer COSY.${payloadB64}.${sig}`;
|
|
173
|
+
}
|
|
174
|
+
/** 从完整 URL 派生签名路径:去掉 `/algo` 前缀(不含查询串)。 */
|
|
175
|
+
function pathSigFrom(fullUrl) {
|
|
176
|
+
let path;
|
|
177
|
+
try {
|
|
178
|
+
path = new URL(fullUrl).pathname;
|
|
179
|
+
} catch {
|
|
180
|
+
path = fullUrl;
|
|
181
|
+
}
|
|
182
|
+
return path.startsWith("/algo") ? path.slice(5) : path;
|
|
183
|
+
}
|
|
184
|
+
function saltedSeed(seed, installSalt) {
|
|
185
|
+
return installSalt ? `${seed}|salt:${installSalt}` : seed;
|
|
186
|
+
}
|
|
187
|
+
function deriveId(seed, salt, installSalt) {
|
|
188
|
+
return md5Hex(`${salt}:${saltedSeed(seed, installSalt)}`);
|
|
189
|
+
}
|
|
190
|
+
/**
|
|
191
|
+
* 派生设备指纹。seed 优先取账号 UID;未知时回退 `cred:<credential>`,
|
|
192
|
+
* 保证同一凭证跨次调用派生结果一致。
|
|
193
|
+
*/
|
|
194
|
+
function deriveFingerprint(uid, credential, installSalt) {
|
|
195
|
+
const seed = uid !== "" ? uid : `cred:${credential}`;
|
|
196
|
+
return {
|
|
197
|
+
machineId: deriveId(seed, "machine", installSalt),
|
|
198
|
+
machineType: deriveId(seed, "machinetype", installSalt).slice(0, 18),
|
|
199
|
+
machineToken: sha512Base64Url(`machinetoken:${saltedSeed(seed, installSalt)}`).slice(0, 43)
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
//#endregion
|
|
203
|
+
//#region src/messages.ts
|
|
204
|
+
/**
|
|
205
|
+
* 按区域取 `session_type`(客户端 `SPr = ti ? "qoderclicn" : "qodercli"`)。
|
|
206
|
+
*
|
|
207
|
+
* 国内外是**两套**会话类型,不是同一套换个名字:写死国际版的值,
|
|
208
|
+
* 国内版请求就带着一个不属于它的会话类型出去。
|
|
209
|
+
*/
|
|
210
|
+
function sessionTypeOf(region) {
|
|
211
|
+
return region === "cn" ? "qoderclicn" : "qodercli";
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* 给模板挂上 `business` 的**身份**字段(product / type / version / stage)。
|
|
215
|
+
*
|
|
216
|
+
* 拆成独立函数是因为它只负责「这台机器 / 这条产品线是谁」,而 `id` / `begin_at`
|
|
217
|
+
* 这类「这场会话是哪一场」由调用方的会话表管(见 `upstream.ts` 的 `sessionOf`)。
|
|
218
|
+
* 两者都是**整场会话内恒定**的:`id` 每轮换新会让服务端把一场会话记成 N 条
|
|
219
|
+
* 互不相干的记录,见 `QoderBusiness` 的说明。`stage` 由调用方按生命周期推进。
|
|
220
|
+
*/
|
|
221
|
+
function applyBusinessIdentity(body, identity) {
|
|
222
|
+
body.business.product = identity.product;
|
|
223
|
+
body.business.type = "agent";
|
|
224
|
+
body.business.version = identity.version;
|
|
225
|
+
if (identity.stage !== void 0) body.business.stage = identity.stage;
|
|
226
|
+
if (identity.modelKey !== void 0) body.business.model_key = identity.modelKey;
|
|
227
|
+
}
|
|
228
|
+
/** 构建一份全新的聊天请求体(每个请求必须换 ID)。 */
|
|
229
|
+
function createChatBodyTemplate() {
|
|
230
|
+
return {
|
|
231
|
+
request_id: "",
|
|
232
|
+
request_set_id: "",
|
|
233
|
+
chat_record_id: "",
|
|
234
|
+
stream: true,
|
|
235
|
+
chat_task: "FREE_INPUT",
|
|
236
|
+
chat_context: {
|
|
237
|
+
extra: {
|
|
238
|
+
modelConfig: {
|
|
239
|
+
is_reasoning: false,
|
|
240
|
+
key: "lite"
|
|
241
|
+
},
|
|
242
|
+
originalContent: {
|
|
243
|
+
type: "text",
|
|
244
|
+
text: ""
|
|
245
|
+
}
|
|
246
|
+
},
|
|
247
|
+
text: {
|
|
248
|
+
type: "text",
|
|
249
|
+
text: ""
|
|
250
|
+
}
|
|
251
|
+
},
|
|
252
|
+
session_id: "",
|
|
253
|
+
source: 1,
|
|
254
|
+
version: "3",
|
|
255
|
+
aliyun_user_type: "personal_standard",
|
|
256
|
+
session_type: "qodercli",
|
|
257
|
+
agent_id: "agent_common",
|
|
258
|
+
task_id: "common",
|
|
259
|
+
model_config: {
|
|
260
|
+
key: "lite",
|
|
261
|
+
is_vl: false,
|
|
262
|
+
is_reasoning: false,
|
|
263
|
+
source: "system"
|
|
264
|
+
},
|
|
265
|
+
messages: [],
|
|
266
|
+
business: {
|
|
267
|
+
id: "",
|
|
268
|
+
name: "hi",
|
|
269
|
+
begin_at: 0
|
|
270
|
+
}
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
function blankResponseMeta() {
|
|
274
|
+
return {
|
|
275
|
+
id: "",
|
|
276
|
+
usage: {
|
|
277
|
+
prompt_tokens: 0,
|
|
278
|
+
completion_tokens: 0,
|
|
279
|
+
total_tokens: 0,
|
|
280
|
+
completion_tokens_details: { reasoning_tokens: 0 },
|
|
281
|
+
prompt_tokens_details: { cached_tokens: 0 }
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
function structuredMessage(role, text) {
|
|
286
|
+
return {
|
|
287
|
+
role,
|
|
288
|
+
content: text,
|
|
289
|
+
response_meta: blankResponseMeta(),
|
|
290
|
+
reasoning_content_signature: ""
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
function userMessage(text, images = []) {
|
|
294
|
+
const parts = [];
|
|
295
|
+
for (const url of images) parts.push({
|
|
296
|
+
type: "image_url",
|
|
297
|
+
image_url: { url }
|
|
298
|
+
});
|
|
299
|
+
if (text.trim()) parts.push({
|
|
300
|
+
type: "text",
|
|
301
|
+
text
|
|
302
|
+
});
|
|
303
|
+
if (parts.length === 0) parts.push({
|
|
304
|
+
type: "text",
|
|
305
|
+
text: ""
|
|
306
|
+
});
|
|
307
|
+
return {
|
|
308
|
+
role: "user",
|
|
309
|
+
content: "",
|
|
310
|
+
contents: parts,
|
|
311
|
+
response_meta: blankResponseMeta(),
|
|
312
|
+
reasoning_content_signature: ""
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
function toolMessage(message, text) {
|
|
316
|
+
const out = structuredMessage("tool", text);
|
|
317
|
+
if (typeof message.name === "string") out.name = message.name;
|
|
318
|
+
if (typeof message.tool_call_id === "string") out.tool_call_id = message.tool_call_id;
|
|
319
|
+
return out;
|
|
320
|
+
}
|
|
321
|
+
function assistantToolCallMessage(text, toolCalls) {
|
|
322
|
+
const out = structuredMessage("assistant", text);
|
|
323
|
+
out.tool_calls = toolCalls;
|
|
324
|
+
return out;
|
|
325
|
+
}
|
|
326
|
+
/** 从 OpenAI 消息提取纯文本(content 字符串、contents parts、named 等)。 */
|
|
327
|
+
function normalizeMessageText(message) {
|
|
328
|
+
const content = message.content;
|
|
329
|
+
if (typeof content === "string") return content;
|
|
330
|
+
if (Array.isArray(content)) {
|
|
331
|
+
const parts = [];
|
|
332
|
+
for (const part of content) if (typeof part === "string") parts.push(part);
|
|
333
|
+
else if (part && typeof part === "object") {
|
|
334
|
+
const t = part.text;
|
|
335
|
+
if (typeof t === "string") parts.push(t);
|
|
336
|
+
else if (typeof part.value === "string") parts.push(part.value);
|
|
337
|
+
}
|
|
338
|
+
return parts.join("");
|
|
339
|
+
}
|
|
340
|
+
return "";
|
|
341
|
+
}
|
|
342
|
+
/** 提取消息里的图片 URL(user 消息的 image_url parts)。 */
|
|
343
|
+
function extractMessageImages(message) {
|
|
344
|
+
if (message.role !== "user") return [];
|
|
345
|
+
const content = message.content;
|
|
346
|
+
if (!Array.isArray(content)) return [];
|
|
347
|
+
const urls = [];
|
|
348
|
+
for (const part of content) {
|
|
349
|
+
const iu = part.image_url;
|
|
350
|
+
if (iu && typeof iu.url === "string") urls.push(iu.url);
|
|
351
|
+
}
|
|
352
|
+
return urls;
|
|
353
|
+
}
|
|
354
|
+
const TOOL_CALLS_TEXT_RE = /Tool calls:\s*(\[[\s\S]*?\])/;
|
|
355
|
+
/** 尝试从文本解析 "Tool calls: [...]" 形状的 tool_calls(兜底)。 */
|
|
356
|
+
function parseToolCallsText(text) {
|
|
357
|
+
if (!text) return void 0;
|
|
358
|
+
const m = TOOL_CALLS_TEXT_RE.exec(text);
|
|
359
|
+
if (!m?.[1]) return void 0;
|
|
360
|
+
try {
|
|
361
|
+
const parsed = JSON.parse(m[1]);
|
|
362
|
+
if (Array.isArray(parsed) && parsed.every((item) => item && typeof item === "object")) return normalizeToolCalls(parsed);
|
|
363
|
+
} catch {
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
function normalizeToolCalls(raw) {
|
|
368
|
+
return raw.map((tc) => {
|
|
369
|
+
if (tc && typeof tc === "object" && !("function" in tc)) {
|
|
370
|
+
const r = tc;
|
|
371
|
+
if (r.id && r.name && r.input) return {
|
|
372
|
+
id: r.id,
|
|
373
|
+
type: "function",
|
|
374
|
+
function: {
|
|
375
|
+
name: r.name,
|
|
376
|
+
arguments: JSON.stringify(r.input)
|
|
377
|
+
}
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
return tc;
|
|
381
|
+
});
|
|
382
|
+
}
|
|
383
|
+
/** 检测 assistant 消息之后是否有已解析的 tool 响应(决定结构化 tool_calls 传输)。 */
|
|
384
|
+
function hasResolvedToolResponse(messages, assistantIndex) {
|
|
385
|
+
const message = messages[assistantIndex];
|
|
386
|
+
if (message === void 0 || message.role !== "assistant") return false;
|
|
387
|
+
const tc = message.tool_calls;
|
|
388
|
+
if (!(Array.isArray(tc) && tc.length > 0) && !parseToolCallsText(normalizeMessageText(message))) return false;
|
|
389
|
+
for (let i = assistantIndex + 1; i < messages.length; i += 1) {
|
|
390
|
+
const next = messages[i];
|
|
391
|
+
if (next?.role === "tool") return true;
|
|
392
|
+
if (next !== void 0 && (next.role === "assistant" || next.role === "user" || next.role === "system")) return false;
|
|
393
|
+
}
|
|
394
|
+
return false;
|
|
395
|
+
}
|
|
396
|
+
function renderToolCalls(toolCalls) {
|
|
397
|
+
return `Tool calls:\n${JSON.stringify(toolCalls)}`;
|
|
398
|
+
}
|
|
399
|
+
function renderToolResult(message, text) {
|
|
400
|
+
const name = typeof message.name === "string" ? message.name : "";
|
|
401
|
+
const toolCallId = typeof message.tool_call_id === "string" ? message.tool_call_id : "";
|
|
402
|
+
let out = "Tool result";
|
|
403
|
+
if (name) out += ` (${name})`;
|
|
404
|
+
if (toolCallId) out += ` [${toolCallId}]`;
|
|
405
|
+
if (text.trim()) out += `:\n${text}`;
|
|
406
|
+
return out;
|
|
407
|
+
}
|
|
408
|
+
/**
|
|
409
|
+
* 把一条 OpenAI 消息转换为 Qoder 消息形状;返回 null 表示该条无法表示(跳过)。
|
|
410
|
+
*/
|
|
411
|
+
function convertIncomingMessage(message, toolsEnabled, allowStructuredToolCalls) {
|
|
412
|
+
const role = typeof message.role === "string" ? message.role : "user";
|
|
413
|
+
const text = normalizeMessageText(message);
|
|
414
|
+
let structuredToolCalls;
|
|
415
|
+
if (toolsEnabled && allowStructuredToolCalls) {
|
|
416
|
+
const tc = Array.isArray(message.tool_calls) && message.tool_calls.length > 0 ? message.tool_calls : parseToolCallsText(text);
|
|
417
|
+
if (tc) structuredToolCalls = tc;
|
|
418
|
+
}
|
|
419
|
+
if (role === "assistant" && structuredToolCalls) return assistantToolCallMessage(text, structuredToolCalls);
|
|
420
|
+
if (role === "tool") {
|
|
421
|
+
if (toolsEnabled) return toolMessage(message, text);
|
|
422
|
+
return structuredMessage("user", renderToolResult(message, text));
|
|
423
|
+
}
|
|
424
|
+
let finalText = text;
|
|
425
|
+
if (role === "assistant" && !toolsEnabled && Array.isArray(message.tool_calls) && message.tool_calls.length > 0) finalText = [text, renderToolCalls(message.tool_calls)].filter(Boolean).join("\n\n");
|
|
426
|
+
const images = role === "user" ? extractMessageImages(message) : [];
|
|
427
|
+
if (!finalText.trim() && images.length === 0) return null;
|
|
428
|
+
if (role === "user") return userMessage(images.length > 0 ? finalText.split("\n\n").filter((s) => !s.trim().startsWith("[image] ")).join("\n\n") : finalText, images);
|
|
429
|
+
return structuredMessage(role, finalText);
|
|
430
|
+
}
|
|
431
|
+
/**
|
|
432
|
+
* 构建发往 Qoder 网关的 messages 数组。OpenAI 形状入参 → Qoder 形状。
|
|
433
|
+
*/
|
|
434
|
+
function buildQoderMessages(incoming, prompt, toolsEnabled) {
|
|
435
|
+
const rebuilt = [];
|
|
436
|
+
if (incoming.length > 0) for (let i = 0; i < incoming.length; i += 1) {
|
|
437
|
+
const allowStructured = toolsEnabled && hasResolvedToolResponse(incoming, i);
|
|
438
|
+
const converted = convertIncomingMessage(incoming[i], toolsEnabled, allowStructured);
|
|
439
|
+
if (converted !== null) rebuilt.push(converted);
|
|
440
|
+
}
|
|
441
|
+
if (rebuilt.length === 0 && prompt.trim()) rebuilt.push(userMessage(prompt));
|
|
442
|
+
return rebuilt;
|
|
443
|
+
}
|
|
444
|
+
/** 取最后一条 user 消息的纯文本(供 chat_context / business.name 使用)。 */
|
|
445
|
+
function extractLatestUserPrompt(messages) {
|
|
446
|
+
for (let i = messages.length - 1; i >= 0; i -= 1) {
|
|
447
|
+
const m = messages[i];
|
|
448
|
+
if (m?.role === "user") {
|
|
449
|
+
const text = normalizeMessageText(m);
|
|
450
|
+
if (text.trim()) return text;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
return "";
|
|
454
|
+
}
|
|
455
|
+
/** 任意 JSON 深拷贝(模板必须逐请求独立)。 */
|
|
456
|
+
function deepClone(value) {
|
|
457
|
+
return structuredClone(value);
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* 给「最后一条 system 消息的最后一个非空文本块」打 `cache_control: ephemeral`。
|
|
461
|
+
*
|
|
462
|
+
* ## 标记点为什么是 system 消息,而不是 magpie 说的「最后一个 user turn」
|
|
463
|
+
*
|
|
464
|
+
* magpie(`packages/qoder/index.mjs` 的 `cacheMarked`)标的是最后一个 user turn
|
|
465
|
+
* 的最后一个非 thinking/tool 块。真实客户端(app.asar.unpacked 里
|
|
466
|
+
* `qoder-worker-runtime.obf.mjs`)的 `BHc(A,e)` 恰好相反:
|
|
467
|
+
*
|
|
468
|
+
* ```js
|
|
469
|
+
* function BHc(A,e){
|
|
470
|
+
* let t=A.findIndex(A=>"system"!==A.role), i=(t<0?A.length:t)-1, n=A[i];
|
|
471
|
+
* if("system"!==n?.role) return; // 只标 system
|
|
472
|
+
* let r=n.content.findLastIndex(A=>A.text.length>0); // 最后一个非空文本块
|
|
473
|
+
* return r<0?void 0:{index:i, message:{role:"system",
|
|
474
|
+
* content:n.content.map((A,t)=>t===r?{...A,cacheControl:e}:A)}}
|
|
475
|
+
* }
|
|
476
|
+
* ```
|
|
477
|
+
*
|
|
478
|
+
* 即:从数组头起第一条非 system 的位置往前推一格,**只标那条 system 消息**,
|
|
479
|
+
* 标它内部最后一个非空文本块;其余消息一概不动。`IHc` 负责把已有的 tool 块
|
|
480
|
+
* 标记按当前开关值重写或剥掉(我们不发 tool 块级别的标记,故无需对应逻辑)。
|
|
481
|
+
*
|
|
482
|
+
* ## 为什么默认关闭(这是取舍,不是遗漏)
|
|
483
|
+
*
|
|
484
|
+
* 客户端里这个开关的值来自 `Pjc(A)`:只有**模型自己声明了**
|
|
485
|
+
* `capabilities.cacheControl`(或 anthropic-compatible 适配器 + `cache.mode ===
|
|
486
|
+
* "auto"`)才进 `promptCache` 表;而 `promptCache` 只有 `cde`(自定义 provider)
|
|
487
|
+
* 去读,调用点是 `ZPi`,`ZPi` 的唯一调用方是自定义 provider 的 `inference`。
|
|
488
|
+
*
|
|
489
|
+
* 换句话说:**Qoder 内建通道根本不吃这个字段**。它的缓存是服务端按
|
|
490
|
+
* `session_id` 分桶自动做的(issue #42 的实测:固定 session_id 后命中率
|
|
491
|
+
* 99.8%)。对一个没声明该能力的模型硬发 `cache_control`,是在递一个它没要的
|
|
492
|
+
* 字段 —— 轻则被忽略,重则被当成不认识的块类型拒掉。
|
|
493
|
+
*
|
|
494
|
+
* 所以这里做成显式开关:`undefined` 即原样返回,调用方按实测结论决定开不开。
|
|
495
|
+
* 想验证它有没有用,用 `QoderUpstreamOptions.cacheControl` 打开做 A/B。
|
|
496
|
+
*
|
|
497
|
+
* ## 形状:`content` 从字符串变成 parts 数组
|
|
498
|
+
*
|
|
499
|
+
* 客户端标记后 `content` 就是 parts 数组(`n.content.map(...)`),未标记时字节
|
|
500
|
+
* 串与数组都接受(它的 system 投影里 `1===t.length && "string"==typeof t[0]`
|
|
501
|
+
* 就直出字符串)。所以我们只在**真要标记**时才把 `content` 转成数组,与客户端
|
|
502
|
+
* 标记后的形状一致;不标记时一个字都不改。
|
|
503
|
+
*/
|
|
504
|
+
function applyCacheControl(messages, cacheControl) {
|
|
505
|
+
if (cacheControl === void 0) return messages;
|
|
506
|
+
const firstNonSystem = messages.findIndex((m) => m.role !== "system");
|
|
507
|
+
const at = (firstNonSystem < 0 ? messages.length : firstNonSystem) - 1;
|
|
508
|
+
const target = messages[at];
|
|
509
|
+
if (target === void 0 || target.role !== "system") return messages;
|
|
510
|
+
const parts = Array.isArray(target.content) ? target.content : typeof target.content === "string" && target.content.length > 0 ? [{
|
|
511
|
+
type: "text",
|
|
512
|
+
text: target.content
|
|
513
|
+
}] : [];
|
|
514
|
+
let blockAt = -1;
|
|
515
|
+
for (let i = parts.length - 1; i >= 0; i -= 1) {
|
|
516
|
+
const text = parts[i]?.text;
|
|
517
|
+
if (typeof text === "string" && text.length > 0) {
|
|
518
|
+
blockAt = i;
|
|
519
|
+
break;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
if (blockAt < 0) return messages;
|
|
523
|
+
const marked = parts.map((part, i) => i === blockAt ? {
|
|
524
|
+
...part,
|
|
525
|
+
cache_control: cacheControl
|
|
526
|
+
} : part);
|
|
527
|
+
const out = messages.slice();
|
|
528
|
+
out[at] = {
|
|
529
|
+
...target,
|
|
530
|
+
content: marked
|
|
531
|
+
};
|
|
532
|
+
return out;
|
|
533
|
+
}
|
|
534
|
+
/** 模型名 → 是否需要图像输入(is_vl)。两个入口都改:model_config 与 chat_context.extra.modelConfig。 */
|
|
535
|
+
function applyModelKey(body, key, userType, isVl) {
|
|
536
|
+
body.model_config.key = key;
|
|
537
|
+
body.model_config.is_vl = isVl;
|
|
538
|
+
body.chat_context.extra.modelConfig.key = key;
|
|
539
|
+
body.aliyun_user_type = userType;
|
|
540
|
+
}
|
|
541
|
+
//#endregion
|
|
542
|
+
//#region src/device-risk.ts
|
|
543
|
+
/**
|
|
544
|
+
* 设备风控身份(国际版签到依赖)。
|
|
545
|
+
*
|
|
546
|
+
* 背景:国际版的每日签到活动**只下发给带设备风控头的请求**
|
|
547
|
+
* (`Cosy-MachineToken` / `Cosy-MachineCode` / `Cosy-MachineType`)。国内版不需要。
|
|
548
|
+
* 这三件套由 Qoder 客户端自带的 UMID 组件(`runtime-info`)在本机生成 —— 它不是
|
|
549
|
+
* 随机数,而是与这台机器绑定的标识,所以**不能**由插件伪造或缓存到别的机器。
|
|
550
|
+
*
|
|
551
|
+
* 来源:社区参考实现 L0NE-6/Qoder-Daily(MIT)的做法是先在 Qoder 客户端资源目录里
|
|
552
|
+
* 找 `umid/runtime-info`,找不到才去官方 qodercli 包里提取。本插件只做前者:本机装了
|
|
553
|
+
* Qoder 就有,没装就如实报「取不到」,不去下载任何东西。
|
|
554
|
+
*
|
|
555
|
+
* 组件位置按两层探测:静态候选表(macOS App 内、Windows 默认安装位置)先走,没命中
|
|
556
|
+
* 再向 Windows 卸载登记表问「Qoder 装在哪儿」—— 安装器允许改目录,默认位置不是唯一
|
|
557
|
+
* 位置,详见 {@link resolveDeviceRiskComponent}。
|
|
558
|
+
*
|
|
559
|
+
* 为什么不在插件里缓存:组件本身每次调用都会给出当前有效值(参考实现按 50 分钟
|
|
560
|
+
* 刷新)。这里按 {@link RISK_TTL_MS} 做进程内缓存,避免每次签到都 fork 一个进程。
|
|
561
|
+
*
|
|
562
|
+
* @module dsh-connect-qoder/device-risk
|
|
563
|
+
*/
|
|
564
|
+
const run = promisify(execFile);
|
|
565
|
+
/** 组件输出的大小上限:超过即视为异常输出,不解析。 */
|
|
566
|
+
const MAX_OUTPUT_BYTES = 1048576;
|
|
567
|
+
/**
|
|
568
|
+
* 组件进程的 spawn 选项。
|
|
569
|
+
*
|
|
570
|
+
* `windowsHide` 与 `host-heartbeat.ts` 的 `PROCESS_PROBE_OPTIONS` 同因(家族
|
|
571
|
+
* 教训,见其注释):DSH Desktop 宿主是 Electron GUI 进程(无 console),
|
|
572
|
+
* Windows 会给这种父进程的控制台子程序**新建一个可见窗口** —— 每次读设备
|
|
573
|
+
* 身份都会闪一个黑框。POSIX 上该选项被忽略。
|
|
574
|
+
*/
|
|
575
|
+
const RISK_PROCESS_OPTIONS = {
|
|
576
|
+
timeout: 25e3,
|
|
577
|
+
maxBuffer: MAX_OUTPUT_BYTES,
|
|
578
|
+
windowsHide: true
|
|
579
|
+
};
|
|
580
|
+
/**
|
|
581
|
+
* 每个区域的 UMID 组件搜索路径,按优先级排列。
|
|
582
|
+
*
|
|
583
|
+
* 区域与 App 的对应关系沿用参考实现:国际版优先 `Qoder`,国内版优先 `Qoder CN`。
|
|
584
|
+
* 两个 App 都装时,各自优先自己那个 —— 设备身份与区域是绑定的,用错一侧的组件
|
|
585
|
+
* 会被风控拒绝。
|
|
586
|
+
*
|
|
587
|
+
* 这里是 **macOS** 的安装位置;Windows 的安装位置(`%LOCALAPPDATA%\Programs\…`)
|
|
588
|
+
* 由 {@link windowsUmidCandidates} 动态展开后**追加**在 macOS 候选之后 —— Windows
|
|
589
|
+
* 上没有 `/Applications` 目录,不追加的话 find 永远落空,国际版积分/签到就会
|
|
590
|
+
* 因为「取不到设备身份」而读不到。
|
|
591
|
+
*
|
|
592
|
+
* 这张表只认**默认**安装位置;装在别处的由 {@link resolveDeviceRiskComponent}
|
|
593
|
+
* 追加查卸载登记表,见其注释。
|
|
594
|
+
*/
|
|
595
|
+
const UMID_CANDIDATES = {
|
|
596
|
+
cn: ["/Applications/Qoder CN.app/Contents/Resources/umid/runtime-info", "/Applications/Qoder.app/Contents/Resources/umid/runtime-info"],
|
|
597
|
+
global: ["/Applications/Qoder.app/Contents/Resources/umid/runtime-info", "/Applications/Qoder CN.app/Contents/Resources/umid/runtime-info"]
|
|
598
|
+
};
|
|
599
|
+
/**
|
|
600
|
+
* 某个 Qoder 安装目录下的 UMID 组件路径。
|
|
601
|
+
*
|
|
602
|
+
* 手写拼接而不是复用 `node:path` 的 `join`:注册表里的安装目录是 **Windows** 路径
|
|
603
|
+
* (`D:\…\Qoder`),而本模块的用例跑在 ubuntu 与 windows 两个 CI job 上 —— POSIX 的
|
|
604
|
+
* `join` 会把 `D:\…\Qoder` 当成一个普通文件名,拼出 `D:\…\Qoder/resources/umid/…`
|
|
605
|
+
* 这种半截路径,于是「解析出来的候选」本身就没法跨平台断言。这里按目录里实际出现的
|
|
606
|
+
* 分隔符拼接,把「解析」与「宿主平台」解耦。
|
|
607
|
+
*/
|
|
608
|
+
function windowsUmidPath(installDir) {
|
|
609
|
+
const trimmed = installDir.replace(/[\\/]+$/u, "");
|
|
610
|
+
const separator = trimmed.includes("\\") ? "\\" : "/";
|
|
611
|
+
return [
|
|
612
|
+
trimmed,
|
|
613
|
+
"resources",
|
|
614
|
+
"umid",
|
|
615
|
+
"runtime-info.exe"
|
|
616
|
+
].join(separator);
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* Windows 上 Qoder 客户端的 UMID 组件位置(`%LOCALAPPDATA%\Programs\<App>\resources\
|
|
620
|
+
* umid\runtime-info.exe`),区域 → App 的优先级与 macOS 候选一致。
|
|
621
|
+
*
|
|
622
|
+
* `%LOCALAPPDATA%` 可能未定义(无窗口会话 / CI),此时返回空数组 —— 调用方照常
|
|
623
|
+
* 走「macOS 候选 + 环境变量」的既有路径,不报错。
|
|
624
|
+
*
|
|
625
|
+
* 这里展开的是**默认**安装位置。安装器允许改目录,改过之后这条路径整族落空 ——
|
|
626
|
+
* 那种机器由 {@link findInWindowsUninstallRegistry} 兜底:向系统问「Qoder 装在哪」,
|
|
627
|
+
* 而不是假定它装在哪。
|
|
628
|
+
*/
|
|
629
|
+
function windowsUmidCandidates(region) {
|
|
630
|
+
const local = process.env.LOCALAPPDATA;
|
|
631
|
+
if (!local) return [];
|
|
632
|
+
const pathOf = (app) => windowsUmidPath(join(local, "Programs", app));
|
|
633
|
+
return region === "cn" ? [pathOf("Qoder CN"), pathOf("Qoder")] : [pathOf("Qoder"), pathOf("Qoder CN")];
|
|
634
|
+
}
|
|
635
|
+
/** 允许用户显式指定组件路径(参考实现的 `QODER_UMID_PATH` 同规)。 */
|
|
636
|
+
const UMID_PATH_ENV = "QODER_UMID_PATH";
|
|
637
|
+
const cache = {};
|
|
638
|
+
/**
|
|
639
|
+
* 找本机可用的 UMID 组件 —— **同步快速路径**(不起任何进程)。
|
|
640
|
+
*
|
|
641
|
+
* 覆盖:显式指定的路径、macOS App 内的组件、Windows 的**默认**安装位置。Windows 上装在
|
|
642
|
+
* 别处的情况不在这里 —— 那要起一个 `reg.exe` 去问卸载登记表,代价与这里不同类,所以
|
|
643
|
+
* 单独放在 {@link resolveDeviceRiskComponent} 里。要「找得到就一定能用」的调用方调那个;
|
|
644
|
+
* 这个函数只回答「不用起进程就能确定的那部分」。
|
|
645
|
+
*
|
|
646
|
+
* @returns 组件绝对路径;快速路径没命中时 undefined(**不代表本机没有**)。
|
|
647
|
+
*/
|
|
648
|
+
function findDeviceRiskComponent(region) {
|
|
649
|
+
const custom = process.env[UMID_PATH_ENV];
|
|
650
|
+
if (typeof custom === "string" && custom !== "" && existsSync(custom)) return custom;
|
|
651
|
+
for (const candidate of [...UMID_CANDIDATES[region], ...windowsUmidCandidates(region)]) if (existsSync(candidate)) return candidate;
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Windows 卸载登记表的三个根,按查询优先级排列:当前用户 → 本机 64 位 → 本机 32 位。
|
|
655
|
+
*
|
|
656
|
+
* Qoder 的安装器是 per-user 安装(`UninstallString` 结尾带 `/currentuser`),实测登记项落在
|
|
657
|
+
* HKCU —— 所以它排第一,命中即停,省掉后面两次查询。后两个根是给「装给所有用户」的形态
|
|
658
|
+
* 留的,不是摆设。
|
|
659
|
+
*/
|
|
660
|
+
const WINDOWS_UNINSTALL_ROOTS = [
|
|
661
|
+
String.raw`HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall`,
|
|
662
|
+
String.raw`HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall`,
|
|
663
|
+
String.raw`HKLM\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall`
|
|
664
|
+
];
|
|
665
|
+
/**
|
|
666
|
+
* 卸载登记表里 Qoder 系产品的 `DisplayName` → 区域。
|
|
667
|
+
*
|
|
668
|
+
* **顺序即优先级**:`Qoder CN 0.4.9` 同时满足下面两条(`^Qoder\b` 在空格处也算词边界),
|
|
669
|
+
* 所以 CN 必须排在前面 —— 设备身份与区域绑定,把国内版认成国际版会被风控拒绝。
|
|
670
|
+
*
|
|
671
|
+
* 认不出区域的一律**跳过**(而不是猜一侧):没有 DisplayName、或名字不叫 Qoder 系产品时,
|
|
672
|
+
* 宁可当作「这一条没给出东西」。
|
|
673
|
+
*/
|
|
674
|
+
const WINDOWS_DISPLAY_NAME_REGIONS = [[/^Qoder\s*CN\b/iu, "cn"], [/^Qoder\b/iu, "global"]];
|
|
675
|
+
/** `reg query` 输出里的一行值:` DisplayName REG_SZ Qoder 0.4.9`。 */
|
|
676
|
+
const REG_VALUE_LINE = /^\s+(.+?)\s+REG_SZ\s+(.*)$/u;
|
|
677
|
+
/**
|
|
678
|
+
* `reg.exe` 查询的 spawn 选项。
|
|
679
|
+
*
|
|
680
|
+
* `windowsHide` 与 {@link RISK_PROCESS_OPTIONS} 同因(见其注释:GUI 宿主 spawn 控制台子程序
|
|
681
|
+
* 会闪黑窗);超时取得比组件本身短 —— 读注册表是本地操作,25s 是给组件留的余量,不该照抄。
|
|
682
|
+
*/
|
|
683
|
+
const REG_QUERY_OPTIONS = {
|
|
684
|
+
timeout: 1e4,
|
|
685
|
+
maxBuffer: MAX_OUTPUT_BYTES,
|
|
686
|
+
windowsHide: true
|
|
687
|
+
};
|
|
688
|
+
/**
|
|
689
|
+
* 从卸载登记表的值里还原出**安装目录**。
|
|
690
|
+
*
|
|
691
|
+
* 三种实测形态都要认:
|
|
692
|
+
*
|
|
693
|
+
* - `"D:\…\Qoder\Uninstall Qoder.exe" /currentuser` —— 带引号且尾巴上有参数(Qoder 的
|
|
694
|
+
* `UninstallString` 就是这种)。**必须先看引号**:卸载器名字里自带空格
|
|
695
|
+
* (`Uninstall Qoder.exe`),按空白切会切在名字中间。
|
|
696
|
+
* - `D:\…\Qoder\uninstallerIcon.ico` —— `DisplayIcon` 那种裸路径。
|
|
697
|
+
* - `D:\…\Qoder.exe /S` —— 没引号但带参数,截到 `.exe` 为止。
|
|
698
|
+
*
|
|
699
|
+
* 只认「盘符 + 分隔符」或 UNC 开头的绝对路径:相对路径与残缺值不该变成候选,否则
|
|
700
|
+
* `existsSync` 会在当前工作目录下瞎撞,把「没找到」伪装成「找到了」。
|
|
701
|
+
*/
|
|
702
|
+
function windowsInstallDirOf(value) {
|
|
703
|
+
const text = value.trim();
|
|
704
|
+
if (text === "") return void 0;
|
|
705
|
+
const quoted = /^"(?<path>[^"]+)"/u.exec(text)?.groups?.path;
|
|
706
|
+
const executable = /^.+?\.exe\b/iu.exec(text)?.[0];
|
|
707
|
+
const file = (quoted ?? executable ?? text).trim();
|
|
708
|
+
const cut = Math.max(file.lastIndexOf("\\"), file.lastIndexOf("/"));
|
|
709
|
+
if (cut <= 0) return void 0;
|
|
710
|
+
const dir = file.slice(0, cut);
|
|
711
|
+
return /^(?:[A-Za-z]:[\\/]|\\\\)/u.test(dir) ? dir : void 0;
|
|
712
|
+
}
|
|
713
|
+
/**
|
|
714
|
+
* 把 `reg query … /s /f Qoder /t REG_SZ` 的输出解析成**该区域**的安装目录,按登记顺序。
|
|
715
|
+
*
|
|
716
|
+
* 纯函数:不碰注册表、不碰文件系统。查询那一侧在 CI 上没东西可查(runner 上没装 Qoder),
|
|
717
|
+
* 只有把「解析」与「查询」分开,才能把真实输出固化成用例 —— 而这个 bug 的本质,恰恰是
|
|
718
|
+
* 解析侧漏掉了一种安装位置,不是查询侧拿不到数据。
|
|
719
|
+
*/
|
|
720
|
+
function parseWindowsUninstallDirs(output, region) {
|
|
721
|
+
const dirs = [];
|
|
722
|
+
let displayName = "";
|
|
723
|
+
let uninstallString = "";
|
|
724
|
+
let displayIcon = "";
|
|
725
|
+
/** 结算一条登记项:名字认得出区域、且能取出安装目录时才算数。 */
|
|
726
|
+
const settle = () => {
|
|
727
|
+
if (WINDOWS_DISPLAY_NAME_REGIONS.find(([pattern]) => pattern.test(displayName))?.[1] === region) {
|
|
728
|
+
const dir = windowsInstallDirOf(uninstallString) ?? windowsInstallDirOf(displayIcon);
|
|
729
|
+
if (dir !== void 0 && !dirs.includes(dir)) dirs.push(dir);
|
|
730
|
+
}
|
|
731
|
+
displayName = "";
|
|
732
|
+
uninstallString = "";
|
|
733
|
+
displayIcon = "";
|
|
734
|
+
};
|
|
735
|
+
for (const line of output.split(/\r?\n/u)) {
|
|
736
|
+
if (line.startsWith("HKEY_")) {
|
|
737
|
+
settle();
|
|
738
|
+
continue;
|
|
739
|
+
}
|
|
740
|
+
const value = REG_VALUE_LINE.exec(line);
|
|
741
|
+
if (value === null) continue;
|
|
742
|
+
const name = value[1].trim().toLowerCase();
|
|
743
|
+
if (name === "displayname") displayName = value[2].trim();
|
|
744
|
+
else if (name === "uninstallstring") uninstallString = value[2].trim();
|
|
745
|
+
else if (name === "displayicon") displayIcon = value[2].trim();
|
|
746
|
+
}
|
|
747
|
+
settle();
|
|
748
|
+
return dirs;
|
|
749
|
+
}
|
|
750
|
+
/**
|
|
751
|
+
* `reg.exe` 的绝对路径。
|
|
752
|
+
*
|
|
753
|
+
* 不靠 PATH:宿主是 Electron GUI 进程,PATH 来自用户环境(被裁剪过的环境里 `reg.exe` 找不到)。
|
|
754
|
+
* `%SystemRoot%\System32\reg.exe` 在任何 Windows 上都存在;`%SystemRoot%` 缺失这种极端情况
|
|
755
|
+
* 退回裸名字,由 PATH 兜底。
|
|
756
|
+
*/
|
|
757
|
+
function windowsRegExe() {
|
|
758
|
+
const root = process.env.SystemRoot;
|
|
759
|
+
return root === void 0 || root === "" ? "reg.exe" : join(root, "System32", "reg.exe");
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* 向 Windows 卸载登记表问「Qoder 装在哪儿」,返回该区域**确实存在**的组件路径。
|
|
763
|
+
*
|
|
764
|
+
* 为什么需要它:`%LOCALAPPDATA%\Programs\<App>` 只是默认值,安装器允许改目录 —— 实测一台
|
|
765
|
+
* 机器上 Qoder 装在 `D:\Users\<user>\AppData\Local\Programs\Qoder`,登记表里写得清清楚楚,
|
|
766
|
+
* 而候选表整族落空,于是国际版签到只剩「未找到设备风控组件」一条路。
|
|
767
|
+
*
|
|
768
|
+
* 三个根依次查、命中即停。任何一步失败(`reg.exe` 不在、项读不到、超时、没有匹配项)都
|
|
769
|
+
* **静默跳过**:找不到组件时该由调用方给出那条统一、可操作的报错;在这里抛只会把
|
|
770
|
+
* 「不知道装在哪」和「读不出来」混成同一句话。
|
|
771
|
+
*/
|
|
772
|
+
async function findInWindowsUninstallRegistry(region) {
|
|
773
|
+
for (const root of WINDOWS_UNINSTALL_ROOTS) {
|
|
774
|
+
let stdout;
|
|
775
|
+
try {
|
|
776
|
+
stdout = (await run(windowsRegExe(), [
|
|
777
|
+
"query",
|
|
778
|
+
root,
|
|
779
|
+
"/s",
|
|
780
|
+
"/f",
|
|
781
|
+
"Qoder",
|
|
782
|
+
"/t",
|
|
783
|
+
"REG_SZ"
|
|
784
|
+
], REG_QUERY_OPTIONS)).stdout;
|
|
785
|
+
} catch {
|
|
786
|
+
continue;
|
|
787
|
+
}
|
|
788
|
+
for (const dir of parseWindowsUninstallDirs(stdout, region)) {
|
|
789
|
+
const candidate = windowsUmidPath(dir);
|
|
790
|
+
if (existsSync(candidate)) return candidate;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
/**
|
|
795
|
+
* 找本机可用的 UMID 组件 —— **完整探测**。
|
|
796
|
+
*
|
|
797
|
+
* 分两层是因为代价不同类:{@link findDeviceRiskComponent} 是几次 `existsSync`(同步、不起进程),
|
|
798
|
+
* 注册表那层要起一个 `reg.exe`。第一层命中就不付第二层的钱;第一层落空、且确实在 Windows 上
|
|
799
|
+
* 时,才去问系统 Qoder 装在哪儿。
|
|
800
|
+
*
|
|
801
|
+
* 非 Windows 不查注册表:macOS 那边安装位置就是固定的 `/Applications`,第一层已经覆盖完了。
|
|
802
|
+
*
|
|
803
|
+
* @returns 组件绝对路径;两层都没有时 undefined(调用方据此如实降级)。
|
|
804
|
+
*/
|
|
805
|
+
async function resolveDeviceRiskComponent(region, probeRegistry = findInWindowsUninstallRegistry) {
|
|
806
|
+
const found = findDeviceRiskComponent(region);
|
|
807
|
+
if (found !== void 0) return found;
|
|
808
|
+
if (process.platform !== "win32") return void 0;
|
|
809
|
+
return probeRegistry(region);
|
|
810
|
+
}
|
|
811
|
+
/**
|
|
812
|
+
* 读取设备风控身份。
|
|
813
|
+
*
|
|
814
|
+
* 组件把 JSON 打在第一行 stdout。任何一步不符合预期(找不到组件、超时、输出不是
|
|
815
|
+
* JSON、字段缺失或过长)都**抛错**而不是返回半个对象 —— 半个身份发上去只会被风控
|
|
816
|
+
* 当成伪造,反而更难诊断。
|
|
817
|
+
*
|
|
818
|
+
* 结果按 {@link RISK_TTL_MS} 在进程内缓存。
|
|
819
|
+
*/
|
|
820
|
+
async function readDeviceRisk(region, nowMs = Date.now()) {
|
|
821
|
+
const hit = cache[region];
|
|
822
|
+
if (hit !== void 0 && nowMs - hit.atMs < 3e6) return hit.risk;
|
|
823
|
+
const component = await resolveDeviceRiskComponent(region);
|
|
824
|
+
if (component === void 0) throw new Error(`未找到 Qoder 设备风控组件(umid/runtime-info)。国际版签到需要它:请安装 Qoder 客户端,或用 ${UMID_PATH_ENV} 指定组件路径`);
|
|
825
|
+
let stdout;
|
|
826
|
+
try {
|
|
827
|
+
stdout = (await run(component, [], RISK_PROCESS_OPTIONS)).stdout;
|
|
828
|
+
} catch (error) {
|
|
829
|
+
throw new Error(`设备风控组件执行失败: ${String(error?.message ?? error)}`);
|
|
830
|
+
}
|
|
831
|
+
const firstLine = stdout.split("\n").map((line) => line.trim()).find((line) => line !== "") ?? "";
|
|
832
|
+
let parsed;
|
|
833
|
+
try {
|
|
834
|
+
parsed = JSON.parse(firstLine);
|
|
835
|
+
} catch {
|
|
836
|
+
throw new Error(`设备风控组件输出不是 JSON: ${firstLine.slice(0, 120)}`);
|
|
837
|
+
}
|
|
838
|
+
if (parsed === null || typeof parsed !== "object") throw new Error("设备风控组件输出不是对象");
|
|
839
|
+
const record = parsed;
|
|
840
|
+
const pick = (key) => {
|
|
841
|
+
const value = record[key];
|
|
842
|
+
if (typeof value !== "string" || value.trim() === "" || value.length > 4096) throw new Error(`设备风控组件输出缺少 ${key}`);
|
|
843
|
+
return value.trim();
|
|
844
|
+
};
|
|
845
|
+
const risk = {
|
|
846
|
+
machineToken: pick("machineToken"),
|
|
847
|
+
machineCode: pick("machineCode"),
|
|
848
|
+
machineType: pick("machineType")
|
|
849
|
+
};
|
|
850
|
+
cache[region] = {
|
|
851
|
+
risk,
|
|
852
|
+
atMs: nowMs
|
|
853
|
+
};
|
|
854
|
+
return risk;
|
|
855
|
+
}
|
|
856
|
+
//#endregion
|
|
857
|
+
//#region src/device-identity.ts
|
|
858
|
+
/**
|
|
859
|
+
* 向 Qoder 声明的**设备身份**——`cosy-machineid` / `cosy-machinetoken` /
|
|
860
|
+
* `cosy-machinetype` / `cosy-machinecode` 四个头的取值来源。
|
|
861
|
+
*
|
|
862
|
+
* ## 为什么需要这一层
|
|
863
|
+
*
|
|
864
|
+
* 改动前,聊天路径的身份是 `deriveFingerprint('', credential, installSalt)` 从
|
|
865
|
+
* **PAT 摘要**派生出来的:`machineId` / `machineToken` / `machineType` 三个值全部
|
|
866
|
+
* 由同一个种子算出。这在两处是错的:
|
|
867
|
+
*
|
|
868
|
+
* 1. **`machineId` 与 `machineToken` 在真实客户端里是两个不同来源的值。** 实测
|
|
869
|
+
* 抓包(qoderclicn 1.1.94)里 `cosy-machineid` 是一个 UUID(等于
|
|
870
|
+
* `~/.qoder-cn/.auth/machine_id`),`cosy-machinetoken` 则是 88 字符的独立
|
|
871
|
+
* 令牌(来自桌面客户端的 UMID 组件)。dsh 此前两个都由 **PAT 摘要**派生:
|
|
872
|
+
* 取值确实不同(一个是 md5、一个是 43 字符的 sha512),但**两个都不是真实
|
|
873
|
+
* 值**。pi 与 magpie 更进一步,把同一个值同时填进两个头。
|
|
874
|
+
*
|
|
875
|
+
* 2. **本仓库已经有真实身份的读取器,只是聊天路径没用它。**
|
|
876
|
+
* `device-risk.ts` 会执行 Qoder 桌面客户端自带的 `umid/runtime-info` 组件,
|
|
877
|
+
* 拿到真实的 `machineToken` / `machineCode` / `machineType`;但它只服务签到
|
|
878
|
+
* 与额度查询(`deviceRiskHeaders()`,且要求 `region.requiresDeviceRisk`)。
|
|
879
|
+
* 结果是同一个账号、同一个进程对上游呈现**两套不同的设备身份** —— 这比
|
|
880
|
+
* 「一律用假值」更糟,因为它自相矛盾。
|
|
881
|
+
*
|
|
882
|
+
* ## 三种模式
|
|
883
|
+
*
|
|
884
|
+
* | 模式 | `machineId` | `machineToken` / `machineCode` / `machineType` |
|
|
885
|
+
* | --- | --- | --- |
|
|
886
|
+
* | `derived`(旧行为) | PAT 派生 | PAT 派生 |
|
|
887
|
+
* | `real`(默认) | 本机 `machine_id` 文件,缺失则派生 | UMID 组件,缺失则派生 |
|
|
888
|
+
* | `manual` | 用户填 | 用户填,缺失项各自派生 |
|
|
889
|
+
*
|
|
890
|
+
* `real` 是默认值,因为它是**唯一与官方客户端一致**的取值;它不会让插件比现状
|
|
891
|
+
* 更「像机器人」—— 恰恰相反,它让插件不再声称一个凭据哈希。
|
|
892
|
+
*
|
|
893
|
+
* 降级必须**显式记录**:`readDeviceRisk` 在组件缺失、超时、输出不成形时抛错,
|
|
894
|
+
* 这里接住它并退回派生值,同时把原因写进日志。静默降级会让「为什么我的身份
|
|
895
|
+
* 和签到路径不一样」变成一个查不出来的问题。
|
|
896
|
+
*
|
|
897
|
+
* @module dsh-connect-qoder/device-identity
|
|
898
|
+
*/
|
|
899
|
+
/**
|
|
900
|
+
* 各区域 `machine_id` 文件的位置。
|
|
901
|
+
*
|
|
902
|
+
* 与官方 CLI 的配置根一致(`~/.qoder-cn` 国内版、`~/.qoder` 国际版)。这个文件
|
|
903
|
+
* 是 CLI 登录时写入的,**不是**我们从凭据派生的东西——读它才是「本机真实身份」。
|
|
904
|
+
*/
|
|
905
|
+
const MACHINE_ID_PATHS = {
|
|
906
|
+
cn: [join(".qoder-cn", ".auth", "machine_id"), join(".qoder", ".auth", "machine_id")],
|
|
907
|
+
global: [join(".qoder", ".auth", "machine_id"), join(".qoder-cn", ".auth", "machine_id")]
|
|
908
|
+
};
|
|
909
|
+
/** 一个值看起来像不像一个可用的标识(非空、不含空白、长度合理)。 */
|
|
910
|
+
function usable(value) {
|
|
911
|
+
return typeof value === "string" && value.trim() !== "" && value.length <= 4096 && !/\s/.test(value.trim());
|
|
912
|
+
}
|
|
913
|
+
/**
|
|
914
|
+
* `machineId` 的校验:真实值是 UUID 形状,但**不强制**要求 UUID —— 见过 32 位
|
|
915
|
+
* 无横线的写法。只挡明显不可能的东西(空、空白、超长)。
|
|
916
|
+
*/
|
|
917
|
+
function usableMachineId(value) {
|
|
918
|
+
return usable(value) && value.trim().length >= 8;
|
|
919
|
+
}
|
|
920
|
+
/** 读本机的 `machine_id` 文件;没有/读不动都返回 `undefined`(不抛)。 */
|
|
921
|
+
async function defaultReadMachineIdFile(path) {
|
|
922
|
+
try {
|
|
923
|
+
const text = (await readFile(path, "utf8")).trim();
|
|
924
|
+
return usableMachineId(text) ? text : void 0;
|
|
925
|
+
} catch {
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* 解析本区域的 `machineId`:按候选顺序找第一个能读到的文件。
|
|
931
|
+
*
|
|
932
|
+
* 校验放在这里而不是只在默认读取器里:`readFileImpl` 是公开注入点,注进来的
|
|
933
|
+
* 实现没义务(也没能力)知道「什么算可用」。公共入口自己收口,两种调用路径
|
|
934
|
+
* 才会得到同一个判据。
|
|
935
|
+
*
|
|
936
|
+
* 找不到就返回 `undefined`,由调用方退回派生值 —— 这是**唯一**允许的降级方向:
|
|
937
|
+
* 宁可发一个凭据哈希,也不发一个空字符串(空值会被当成缺字段,比错值更显眼)。
|
|
938
|
+
*/
|
|
939
|
+
async function readLocalMachineId(region, options = {}) {
|
|
940
|
+
const home = options.home ?? homedir();
|
|
941
|
+
const read = options.readFileImpl ?? defaultReadMachineIdFile;
|
|
942
|
+
for (const relative of MACHINE_ID_PATHS[region]) {
|
|
943
|
+
let found;
|
|
944
|
+
try {
|
|
945
|
+
found = await read(join(home, relative));
|
|
946
|
+
} catch {
|
|
947
|
+
continue;
|
|
948
|
+
}
|
|
949
|
+
if (usableMachineId(found)) return found.trim();
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
/**
|
|
953
|
+
* 解析一次请求要用的设备身份。
|
|
954
|
+
*
|
|
955
|
+
* **永不抛。** 任何一路失败都退回派生值,并把原因写进 `log`。
|
|
956
|
+
*/
|
|
957
|
+
async function resolveDeviceIdentity(options) {
|
|
958
|
+
const mode = options.mode ?? "real";
|
|
959
|
+
const fallback = deriveFingerprint("", options.credential, options.installSalt);
|
|
960
|
+
const log = options.log ?? (() => {});
|
|
961
|
+
const override = options.override ?? {};
|
|
962
|
+
const identity = {
|
|
963
|
+
machineId: fallback.machineId,
|
|
964
|
+
machineToken: fallback.machineToken,
|
|
965
|
+
machineType: fallback.machineType,
|
|
966
|
+
machineCode: "",
|
|
967
|
+
origin: {
|
|
968
|
+
id: "fallback",
|
|
969
|
+
token: "fallback",
|
|
970
|
+
type: "fallback",
|
|
971
|
+
code: "fallback"
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
if (mode === "manual") {
|
|
975
|
+
if (usableMachineId(override.machineId)) {
|
|
976
|
+
identity.machineId = override.machineId.trim();
|
|
977
|
+
identity.origin.id = "manual";
|
|
978
|
+
}
|
|
979
|
+
if (usable(override.machineToken)) {
|
|
980
|
+
identity.machineToken = override.machineToken.trim();
|
|
981
|
+
identity.origin.token = "manual";
|
|
982
|
+
}
|
|
983
|
+
if (usable(override.machineType)) {
|
|
984
|
+
identity.machineType = override.machineType.trim();
|
|
985
|
+
identity.origin.type = "manual";
|
|
986
|
+
}
|
|
987
|
+
if (usable(override.machineCode)) {
|
|
988
|
+
identity.machineCode = override.machineCode.trim();
|
|
989
|
+
identity.origin.code = "manual";
|
|
990
|
+
}
|
|
991
|
+
return identity;
|
|
992
|
+
}
|
|
993
|
+
const localId = await readLocalMachineId(options.region, {
|
|
994
|
+
...options.home === void 0 ? {} : { home: options.home },
|
|
995
|
+
...options.readMachineIdFile === void 0 ? {} : { readFileImpl: options.readMachineIdFile }
|
|
996
|
+
});
|
|
997
|
+
if (localId !== void 0) {
|
|
998
|
+
identity.machineId = localId;
|
|
999
|
+
identity.origin.id = mode === "real" ? "real" : "derived";
|
|
1000
|
+
} else if (mode === "real") log("本机没有 machine_id 文件(CLI 未登录过?),machineId 退回凭据派生值");
|
|
1001
|
+
if (mode === "derived") return identity;
|
|
1002
|
+
const read = options.readRisk ?? readDeviceRisk;
|
|
1003
|
+
let risk;
|
|
1004
|
+
try {
|
|
1005
|
+
risk = await read(options.region);
|
|
1006
|
+
} catch (error) {
|
|
1007
|
+
log(`读不到本机设备三件套,machineToken/type/code 退回凭据派生值:${String(error?.message ?? error)}`);
|
|
1008
|
+
}
|
|
1009
|
+
if (risk !== void 0) {
|
|
1010
|
+
if (usable(risk.machineToken)) {
|
|
1011
|
+
identity.machineToken = risk.machineToken;
|
|
1012
|
+
identity.origin.token = "real";
|
|
1013
|
+
}
|
|
1014
|
+
if (usable(risk.machineType)) {
|
|
1015
|
+
identity.machineType = risk.machineType;
|
|
1016
|
+
identity.origin.type = "real";
|
|
1017
|
+
}
|
|
1018
|
+
if (usable(risk.machineCode)) {
|
|
1019
|
+
identity.machineCode = risk.machineCode;
|
|
1020
|
+
identity.origin.code = "real";
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
return identity;
|
|
1024
|
+
}
|
|
1025
|
+
/**
|
|
1026
|
+
* 把一次解析结果渲染成设备身份请求头。
|
|
1027
|
+
*
|
|
1028
|
+
* 除了那四件套,还补上官方 CLI 每次都带的两个**环境**头:
|
|
1029
|
+
*
|
|
1030
|
+
* - `cosy-machineos` —— 抓包实测是 `x86_64_win32`(架构_平台,小写);
|
|
1031
|
+
* - `cosy-machinehostname` —— 主机名。
|
|
1032
|
+
*
|
|
1033
|
+
* 这两个此前完全没发。它们不是身份令牌,但它们是**同一组一致性声明**的一部分:
|
|
1034
|
+
* 声称了 `machineid` 却不说明跑在什么系统上,本身就是一条可筛的差异。
|
|
1035
|
+
* `machineCode` 为空时整个头不发 —— 空串与「没有这个字段」在上游看来是两件事。
|
|
1036
|
+
*/
|
|
1037
|
+
function identityHeaders(identity, env = {}) {
|
|
1038
|
+
const headers = {
|
|
1039
|
+
"cosy-machineid": identity.machineId,
|
|
1040
|
+
"cosy-machinetoken": identity.machineToken,
|
|
1041
|
+
"cosy-machinetype": identity.machineType
|
|
1042
|
+
};
|
|
1043
|
+
if (identity.machineCode !== "") headers["cosy-machinecode"] = identity.machineCode;
|
|
1044
|
+
if (env.os !== void 0 && env.os !== "") headers["cosy-machineos"] = env.os;
|
|
1045
|
+
if (env.hostname !== void 0 && env.hostname !== "") headers["cosy-machinehostname"] = env.hostname;
|
|
1046
|
+
return headers;
|
|
1047
|
+
}
|
|
1048
|
+
/**
|
|
1049
|
+
* 本机的 `cosy-machineos` / `cosy-machinehostname` 取值。
|
|
1050
|
+
*
|
|
1051
|
+
* 格式照抓包:`${arch}_${platform}`,平台名用 **Node 的** `process.platform`
|
|
1052
|
+
* (`win32` / `darwin` / `linux`)—— 实测 CLI 在 Windows 上发的正是
|
|
1053
|
+
* `x86_64_win32`,与 Node 的说法一致(不是 `windows`、也不是 `win64`)。
|
|
1054
|
+
*
|
|
1055
|
+
* 架构名做一次归一:Node 的 `x64` 在客户端那边写作 `x86_64`。
|
|
1056
|
+
*/
|
|
1057
|
+
function localMachineEnv() {
|
|
1058
|
+
const arch = process.arch === "x64" ? "x86_64" : process.arch;
|
|
1059
|
+
let hostname$1 = "";
|
|
1060
|
+
try {
|
|
1061
|
+
hostname$1 = hostname();
|
|
1062
|
+
} catch {}
|
|
1063
|
+
return {
|
|
1064
|
+
os: `${arch}_${process.platform}`,
|
|
1065
|
+
hostname: hostname$1
|
|
1066
|
+
};
|
|
1067
|
+
}
|
|
1068
|
+
//#endregion
|
|
1069
|
+
//#region src/client-version.ts
|
|
1070
|
+
/**
|
|
1071
|
+
* 我们向 Qoder 声明的**客户端版本号**——全插件唯一的来源。
|
|
1072
|
+
*
|
|
1073
|
+
* ## 为什么不能硬编一个数
|
|
1074
|
+
*
|
|
1075
|
+
* 这个值同时出现在三个地方,三处必须同值:
|
|
1076
|
+
*
|
|
1077
|
+
* 1. `cosy-version` 请求头;
|
|
1078
|
+
* 2. `Authorization: Bearer COSY.<payload>` 载荷里的 `cosyVersion`(实测抓包
|
|
1079
|
+
* 解出的载荷是 `{version:"v1", requestId, info, cosyVersion:"1.1.94",
|
|
1080
|
+
* ideVersion:""}`,与请求头逐字相同);
|
|
1081
|
+
* 3. 请求体 `business.version`。
|
|
1082
|
+
*
|
|
1083
|
+
* ## 为什么不能填「一个看起来新」的编造值
|
|
1084
|
+
*
|
|
1085
|
+
* 服务端如果按这个字段核对客户端版本,那么一个**不存在**的版本号比一个「旧但
|
|
1086
|
+
* 真实」的版本号更显眼——旧版本是合法历史,不存在的版本是筛出来的异常。所以
|
|
1087
|
+
* 这里的取值顺序是「真实的版本号」优先,而不是「最大的数字」优先:
|
|
1088
|
+
*
|
|
1089
|
+
* 1. 用户显式配置的值({@link resolveClientVersion} 的 `override`);
|
|
1090
|
+
* 2. 从 Qoder 自己的 releases 接口拿到的最新 CLI 版本(真实存在);
|
|
1091
|
+
* 3. 内置兜底 {@link BUNDLED_CLIENT_VERSION}(一个确实发布过的版本)。
|
|
1092
|
+
*
|
|
1093
|
+
* 这与 magpie 的取法不同:它把 `1.1.69` 写死,注释说「跟随 App 而非 CLI」,
|
|
1094
|
+
* 同时声称 `Cosy-ClientType: 10`(桌面通道)。那是自洽的,但我们是 CLI 通道
|
|
1095
|
+
* (`cosy-clienttype: 5`),所以版本也该跟 CLI。
|
|
1096
|
+
*
|
|
1097
|
+
* ## 只升不降
|
|
1098
|
+
*
|
|
1099
|
+
* 缓存里的值一旦比内置值新就保留,**不因为某次拉取失败或接口回退而降低**:
|
|
1100
|
+
* 版本号回退意味着「用新版本跑过之后又退回旧版本」,那在服务端看起来同样是
|
|
1101
|
+
* 异常行为,而它只会由我们这边的网络抖动引起,不是真实情况。
|
|
1102
|
+
*
|
|
1103
|
+
* @module dsh-connect-qoder/client-version
|
|
1104
|
+
*/
|
|
1105
|
+
/** 内置兜底:一个**确实发布过**的 CN CLI 版本(实测抓包用的就是它)。 */
|
|
1106
|
+
const BUNDLED_CLIENT_VERSION = "1.1.94";
|
|
1107
|
+
/** Qoder CLI 的发布列表(两个区域共用,返回的是公开的版本清单)。 */
|
|
1108
|
+
const QODER_CLI_RELEASES_URL = "https://repo.qoder.com/repos/QoderAI/changelog-CLI/releases?per_page=5&page=1";
|
|
1109
|
+
/** 拉取超时:拿不到就用缓存/兜底,不能让目录请求等着它。 */
|
|
1110
|
+
const FETCH_TIMEOUT_MS = 3e3;
|
|
1111
|
+
/**
|
|
1112
|
+
* 比较两个 `major.minor.patch` 形状的版本号。
|
|
1113
|
+
*
|
|
1114
|
+
* 只认三段纯数字;任一侧形状不对时返回 `undefined`(调用方按「比不出来」处理,
|
|
1115
|
+
* 保守地不采用新值)。预发布后缀(`-beta.1`)在 Qoder CLI 的发布里不存在,
|
|
1116
|
+
* 出现时整段丢掉。
|
|
1117
|
+
*/
|
|
1118
|
+
function compareVersions(a, b) {
|
|
1119
|
+
const parse = (v) => {
|
|
1120
|
+
const parts = (v.trim().split("-")[0] ?? "").split(".");
|
|
1121
|
+
if (parts.length !== 3) return void 0;
|
|
1122
|
+
const nums = parts.map((p) => /^\d+$/.test(p) ? Number(p) : NaN);
|
|
1123
|
+
return nums.every((n) => Number.isSafeInteger(n) && n >= 0) ? nums : void 0;
|
|
1124
|
+
};
|
|
1125
|
+
const pa = parse(a);
|
|
1126
|
+
const pb = parse(b);
|
|
1127
|
+
if (pa === void 0 || pb === void 0) return void 0;
|
|
1128
|
+
for (let i = 0; i < 3; i += 1) {
|
|
1129
|
+
const x = pa[i] ?? 0;
|
|
1130
|
+
const y = pb[i] ?? 0;
|
|
1131
|
+
if (x !== y) return x < y ? -1 : 1;
|
|
1132
|
+
}
|
|
1133
|
+
return 0;
|
|
1134
|
+
}
|
|
1135
|
+
/** 从 releases 接口的响应里取最新的、形状合法的版本号。 */
|
|
1136
|
+
function pickLatestVersion(body) {
|
|
1137
|
+
const list = Array.isArray(body) ? body : typeof body === "object" && body !== null && Array.isArray(body["data"]) ? body["data"] : [];
|
|
1138
|
+
let best;
|
|
1139
|
+
for (const entry of list) {
|
|
1140
|
+
if (typeof entry !== "object" || entry === null) continue;
|
|
1141
|
+
const raw = entry;
|
|
1142
|
+
const candidate = [
|
|
1143
|
+
raw["tag_name"],
|
|
1144
|
+
raw["name"],
|
|
1145
|
+
raw["version"]
|
|
1146
|
+
].find((v) => typeof v === "string" && v.trim() !== "");
|
|
1147
|
+
if (typeof candidate !== "string") continue;
|
|
1148
|
+
const version = candidate.trim().replace(/^v/i, "");
|
|
1149
|
+
if (compareVersions(version, "0.0.0") === void 0) continue;
|
|
1150
|
+
if (best === void 0 || (compareVersions(version, best) ?? 0) > 0) best = version;
|
|
1151
|
+
}
|
|
1152
|
+
return best;
|
|
1153
|
+
}
|
|
1154
|
+
/**
|
|
1155
|
+
* 版本的解析器。
|
|
1156
|
+
*
|
|
1157
|
+
* 一个实例一份状态:缓存路径可注入(测试用),`fetchImpl` 可注入(离线测试)。
|
|
1158
|
+
*/
|
|
1159
|
+
var ClientVersionResolver = class {
|
|
1160
|
+
options;
|
|
1161
|
+
cached;
|
|
1162
|
+
loading;
|
|
1163
|
+
constructor(options = {}) {
|
|
1164
|
+
this.options = options;
|
|
1165
|
+
}
|
|
1166
|
+
/** 当前该用的版本号。同步返回,永不抛。 */
|
|
1167
|
+
current() {
|
|
1168
|
+
const override = this.options.override?.trim();
|
|
1169
|
+
if (override !== void 0 && compareVersions(override, "0.0.0") !== void 0) return override;
|
|
1170
|
+
const cached = this.cached?.version;
|
|
1171
|
+
if (cached !== void 0 && (compareVersions(cached, "1.1.94") ?? 0) > 0) return cached;
|
|
1172
|
+
return BUNDLED_CLIENT_VERSION;
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* 必要时刷新一次缓存。**永不抛**,失败就保持现状。
|
|
1176
|
+
*
|
|
1177
|
+
* 并发调用共享同一次拉取(`loading`),避免一次启动里打十几次 releases。
|
|
1178
|
+
*/
|
|
1179
|
+
async refresh() {
|
|
1180
|
+
if (this.options.override?.trim() !== void 0 && this.options.override.trim() !== "") return this.current();
|
|
1181
|
+
const now = this.options.now?.() ?? Date.now();
|
|
1182
|
+
if (this.cached !== void 0 && now - this.cached.fetchedAtMs < 864e5) return this.current();
|
|
1183
|
+
if (this.loading !== void 0) return this.loading;
|
|
1184
|
+
this.loading = this.load(now).finally(() => {
|
|
1185
|
+
this.loading = void 0;
|
|
1186
|
+
});
|
|
1187
|
+
return this.loading;
|
|
1188
|
+
}
|
|
1189
|
+
async load(now) {
|
|
1190
|
+
const path = this.options.cachePath;
|
|
1191
|
+
if (this.cached === void 0 && path !== void 0) {
|
|
1192
|
+
const fromDisk = await this.readCache(path);
|
|
1193
|
+
if (fromDisk !== void 0) {
|
|
1194
|
+
this.cached = fromDisk;
|
|
1195
|
+
if (now - fromDisk.fetchedAtMs < 864e5) return this.current();
|
|
1196
|
+
}
|
|
1197
|
+
}
|
|
1198
|
+
const fetched = await this.fetchLatest();
|
|
1199
|
+
if (fetched !== void 0) {
|
|
1200
|
+
if ((compareVersions(fetched, this.current()) ?? 0) > 0) {
|
|
1201
|
+
this.cached = {
|
|
1202
|
+
version: fetched,
|
|
1203
|
+
fetchedAtMs: now
|
|
1204
|
+
};
|
|
1205
|
+
if (path !== void 0) await this.writeCache(path, this.cached);
|
|
1206
|
+
} else if (this.cached === void 0) {
|
|
1207
|
+
this.cached = {
|
|
1208
|
+
version: this.current(),
|
|
1209
|
+
fetchedAtMs: now
|
|
1210
|
+
};
|
|
1211
|
+
if (path !== void 0) await this.writeCache(path, this.cached);
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
return this.current();
|
|
1215
|
+
}
|
|
1216
|
+
async fetchLatest() {
|
|
1217
|
+
const impl = this.options.fetchImpl ?? globalThis.fetch;
|
|
1218
|
+
if (typeof impl !== "function") return void 0;
|
|
1219
|
+
const controller = new AbortController();
|
|
1220
|
+
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
|
1221
|
+
timer.unref?.();
|
|
1222
|
+
try {
|
|
1223
|
+
const res = await impl(QODER_CLI_RELEASES_URL, {
|
|
1224
|
+
method: "GET",
|
|
1225
|
+
headers: { accept: "application/json" },
|
|
1226
|
+
signal: controller.signal
|
|
1227
|
+
});
|
|
1228
|
+
if (!res.ok) return void 0;
|
|
1229
|
+
return pickLatestVersion(await res.json());
|
|
1230
|
+
} catch {
|
|
1231
|
+
return;
|
|
1232
|
+
} finally {
|
|
1233
|
+
clearTimeout(timer);
|
|
1234
|
+
}
|
|
1235
|
+
}
|
|
1236
|
+
async readCache(path) {
|
|
1237
|
+
try {
|
|
1238
|
+
const parsed = JSON.parse(await readFile(path, "utf8"));
|
|
1239
|
+
if (typeof parsed !== "object" || parsed === null) return void 0;
|
|
1240
|
+
const raw = parsed;
|
|
1241
|
+
const version = raw["version"];
|
|
1242
|
+
const fetchedAtMs = raw["fetchedAtMs"];
|
|
1243
|
+
if (typeof version !== "string" || compareVersions(version, "0.0.0") === void 0) return void 0;
|
|
1244
|
+
if (typeof fetchedAtMs !== "number" || !Number.isFinite(fetchedAtMs) || fetchedAtMs <= 0) return void 0;
|
|
1245
|
+
return {
|
|
1246
|
+
version,
|
|
1247
|
+
fetchedAtMs
|
|
1248
|
+
};
|
|
1249
|
+
} catch {
|
|
1250
|
+
return;
|
|
1251
|
+
}
|
|
1252
|
+
}
|
|
1253
|
+
async writeCache(path, cache) {
|
|
1254
|
+
try {
|
|
1255
|
+
await writeFile(path, JSON.stringify(cache, null, 2), "utf8");
|
|
1256
|
+
} catch {}
|
|
1257
|
+
}
|
|
1258
|
+
};
|
|
1259
|
+
//#endregion
|
|
1260
|
+
//#region src/status-paths.ts
|
|
1261
|
+
/** Plugin-owned usage endpoint consumed by its browser half. */
|
|
1262
|
+
const QODER_USAGE_PATH = "/plugins/dsh-connect-qoder/usage";
|
|
1263
|
+
/**
|
|
1264
|
+
* Plugin-owned campaign feed endpoint for one region.
|
|
1265
|
+
*
|
|
1266
|
+
* Answers the card's activity area: the daily 100-Credits check-in row plus every
|
|
1267
|
+
* `VIEW_DETAILS` banner upstream currently serves (集结 / 首月翻倍 / …), each with
|
|
1268
|
+
* its title, description and detail link. Read-only and lazy like the credits
|
|
1269
|
+
* endpoint — the activities live next to the usage readout and are only worth one
|
|
1270
|
+
* upstream read while the panel is open.
|
|
1271
|
+
*/
|
|
1272
|
+
const QODER_CAMPAIGNS_PATH = "/plugins/dsh-connect-qoder/campaigns";
|
|
1273
|
+
/**
|
|
1274
|
+
* Per-account credit balances for one region, read ONLY while the composer
|
|
1275
|
+
* panel is open.
|
|
1276
|
+
*
|
|
1277
|
+
* Separate from {@link QODER_USAGE_PATH} because its cost is different in
|
|
1278
|
+
* kind: the usage document is one upstream read for the selected account,
|
|
1279
|
+
* while this is one read PER account in the region. Folding it into the usage
|
|
1280
|
+
* route would make every 5-minute refresh pay for a table nobody is looking
|
|
1281
|
+
* at, so it is fetched on demand instead — the same principle the pool
|
|
1282
|
+
* applies to its per-account figures.
|
|
1283
|
+
*/
|
|
1284
|
+
const QODER_ACCOUNT_CREDITS_PATH = "/plugins/dsh-connect-qoder/account-credits";
|
|
1285
|
+
/**
|
|
1286
|
+
* The project's public repository.
|
|
1287
|
+
*
|
|
1288
|
+
* Lives here rather than beside one component because TWO sections link to it
|
|
1289
|
+
* — the model section and the account pool — and a second copy of a URL is a
|
|
1290
|
+
* second thing to forget when it moves. Node-free and side-effect free, so it
|
|
1291
|
+
* costs nothing on the Host side either.
|
|
1292
|
+
*
|
|
1293
|
+
* **指向本分叉,不是上游**:这个链接是给用户点「项目主页 / 反馈问题」用的,
|
|
1294
|
+
* 指到已停止维护的上游只会让人把 issue 提给一个不再看的仓库。上游地址仍然
|
|
1295
|
+
* 保留在 README 与 `LICENSE-MODIFICATIONS.md` 里(署名与来源要留),只是
|
|
1296
|
+
* 不复用这个「当前项目」常量。
|
|
1297
|
+
*/
|
|
1298
|
+
const QODER_GITHUB_URL = "https://github.com/bokutake/dsh-connect-qoder";
|
|
1299
|
+
/** Plugin-owned live model refresh endpoint. */
|
|
1300
|
+
const QODER_MODELS_REFRESH_PATH = "/plugins/dsh-connect-qoder/models/refresh";
|
|
1301
|
+
/** Plugin-owned account rescan endpoint (re-reads settings / env / vault). */
|
|
1302
|
+
const QODER_ACCOUNTS_REFRESH_PATH = "/plugins/dsh-connect-qoder/accounts/refresh";
|
|
1303
|
+
/**
|
|
1304
|
+
* Plugin-owned account mutation endpoint: add or remove one account.
|
|
1305
|
+
*
|
|
1306
|
+
* `?action=add` POSTs `{ pat, name? }`: the Host validates the PAT against
|
|
1307
|
+
* the region's gateway (a jobToken exchange doubles as the cheapest
|
|
1308
|
+
* authenticated check and yields the account's display name) and stores it in
|
|
1309
|
+
* the plugin-owned vault. `?action=remove` POSTs `{ accountId }` and deletes
|
|
1310
|
+
* the vault entry. POST + loopback-only: both carry token material or mutate
|
|
1311
|
+
* stored credentials.
|
|
1312
|
+
*/
|
|
1313
|
+
const QODER_ACCOUNTS_PATH = "/plugins/dsh-connect-qoder/accounts";
|
|
1314
|
+
/**
|
|
1315
|
+
* Plugin-owned model probe endpoint.
|
|
1316
|
+
*
|
|
1317
|
+
* Sends one minimal chat request per named model so the card can answer "is
|
|
1318
|
+
* this model usable right now, and if it is limited, when can it be used
|
|
1319
|
+
* again?". Lives on the Host because the credential must never reach the
|
|
1320
|
+
* browser half.
|
|
1321
|
+
*/
|
|
1322
|
+
const QODER_PROBE_PATH = "/plugins/dsh-connect-qoder/probe";
|
|
1323
|
+
/**
|
|
1324
|
+
* Plugin-owned account-pool endpoint: one batch action per call.
|
|
1325
|
+
*
|
|
1326
|
+
* `?action=test` probes every checked account against the region's target
|
|
1327
|
+
* model; `?action=remove` drops one account's membership. Both are POST and
|
|
1328
|
+
* loopback-only because a probe spends credits and removal mutates a
|
|
1329
|
+
* preference.
|
|
1330
|
+
*
|
|
1331
|
+
* Deliberately ONE endpoint rather than two: the actions share every guard
|
|
1332
|
+
* (method, origin, region) and differ only in the work, so splitting them
|
|
1333
|
+
* would duplicate the guards and invite them to drift apart.
|
|
1334
|
+
*/
|
|
1335
|
+
const QODER_POOL_PATH = "/plugins/dsh-connect-qoder/pool";
|
|
1336
|
+
/**
|
|
1337
|
+
* Plugin-owned account transfer endpoint: the batch export / import of PAT
|
|
1338
|
+
* credentials between machines.
|
|
1339
|
+
*
|
|
1340
|
+
* `?action=export` POSTs account ids, answers a JSON ARRAY of credential
|
|
1341
|
+
* records; `?action=preview` POSTs file text, answers a token-free listing;
|
|
1342
|
+
* `?action=import` POSTs file text plus selected indexes, merges into the
|
|
1343
|
+
* vault. POST + loopback-only like every other mutation: the file content is
|
|
1344
|
+
* arbitrary user data and export carries token material.
|
|
1345
|
+
*/
|
|
1346
|
+
const QODER_TRANSFER_PATH = "/plugins/dsh-connect-qoder/transfer";
|
|
1347
|
+
/**
|
|
1348
|
+
* Plugin-owned settings write fallback: the card's writes go through the
|
|
1349
|
+
* settings mirror when it is healthy, and through this Host-side endpoint
|
|
1350
|
+
* when the mirror refuses or lags (a measured 0.1.7 behaviour the sibling
|
|
1351
|
+
* plugin hit: `settings/mutate` from the browser can leave the mirror stale
|
|
1352
|
+
* while the Host accepted the write).
|
|
1353
|
+
*/
|
|
1354
|
+
const QODER_SAVE_PATH = "/plugins/dsh-connect-qoder/__save";
|
|
1355
|
+
/** Query parameter naming the region a card request addresses. */
|
|
1356
|
+
const QODER_REGION_PARAM = "region";
|
|
1357
|
+
/** Every region, in card tab order. */
|
|
1358
|
+
const QODER_REGIONS$1 = ["cn", "global"];
|
|
1359
|
+
/**
|
|
1360
|
+
* Query parameter selecting HOW MUCH of the usage document a request wants.
|
|
1361
|
+
*
|
|
1362
|
+
* Absent means the full document — every caller written before this parameter
|
|
1363
|
+
* existed keeps getting exactly what it used to, which is why the default is
|
|
1364
|
+
* `full` rather than an opt-in flag.
|
|
1365
|
+
*/
|
|
1366
|
+
const QODER_DETAIL_PARAM = "detail";
|
|
1367
|
+
/**
|
|
1368
|
+
* The one non-default detail level: a first-paint document built from LOCAL
|
|
1369
|
+
* state only.
|
|
1370
|
+
*
|
|
1371
|
+
* The card's first paint used to wait for the full document, whose tail
|
|
1372
|
+
* includes one live upstream read for the selected account's credits plus one
|
|
1373
|
+
* per pool member. Each of those can stall for seconds, and the card rendered
|
|
1374
|
+
* nothing about accounts until all of them came back — the complaint this
|
|
1375
|
+
* exists to fix (同一族插件的 issue #77,见 dsh-connect-workbuddy)。
|
|
1376
|
+
*
|
|
1377
|
+
* A `fast` document answers from what the Host already knows: the stored
|
|
1378
|
+
* credential (no token refresh), the cached credit reading, the pool's saved
|
|
1379
|
+
* member list and the check-in state measured this process. It never performs
|
|
1380
|
+
* an upstream read, so it cannot be held by a slow upstream.
|
|
1381
|
+
*/
|
|
1382
|
+
const QODER_DETAIL_FAST = "fast";
|
|
1383
|
+
/**
|
|
1384
|
+
* Does this request URL ask for the first-paint document?
|
|
1385
|
+
*
|
|
1386
|
+
* Only the exact value `fast` counts. Anything else — a typo, a future level
|
|
1387
|
+
* this build does not know, an empty value — degrades to the FULL document.
|
|
1388
|
+
* That direction is deliberate: a typo must cost a slow paint, never an
|
|
1389
|
+
* emptier panel that looks like data loss.
|
|
1390
|
+
*/
|
|
1391
|
+
function fastDetailOf(url) {
|
|
1392
|
+
const at = url.indexOf("?");
|
|
1393
|
+
if (at === -1) return false;
|
|
1394
|
+
return new URLSearchParams(url.slice(at + 1)).get(QODER_DETAIL_PARAM) === QODER_DETAIL_FAST;
|
|
1395
|
+
}
|
|
1396
|
+
/**
|
|
1397
|
+
* Read the region parameter off a status-route URL. Absent means the domestic
|
|
1398
|
+
* tab (`cn`); a present-but-unknown value returns undefined so the route can
|
|
1399
|
+
* answer 400 instead of guessing.
|
|
1400
|
+
*/
|
|
1401
|
+
function regionOfStatusUrl(url) {
|
|
1402
|
+
const at = url.indexOf("?");
|
|
1403
|
+
const value = at === -1 ? null : new URLSearchParams(url.slice(at + 1)).get(QODER_REGION_PARAM);
|
|
1404
|
+
if (value === null || value === "") return "cn";
|
|
1405
|
+
return QODER_REGIONS$1.includes(value) ? value : void 0;
|
|
1406
|
+
}
|
|
1407
|
+
/** Query parameter selecting which action a request means. */
|
|
1408
|
+
const QODER_ACTION_PARAM = "action";
|
|
1409
|
+
/** Read the pool action off a request URL; unknown/absent means undefined. */
|
|
1410
|
+
function poolActionOf(url) {
|
|
1411
|
+
const value = actionParamOf(url);
|
|
1412
|
+
if (value === "checkin" || value === "test" || value === "remove" || value === "progress") return value;
|
|
1413
|
+
}
|
|
1414
|
+
/** Read the account action off a request URL; unknown/absent means undefined. */
|
|
1415
|
+
function accountActionOf(url) {
|
|
1416
|
+
const value = actionParamOf(url);
|
|
1417
|
+
return value === "add" || value === "remove" ? value : void 0;
|
|
1418
|
+
}
|
|
1419
|
+
/** Read the transfer action off a request URL; unknown/absent means undefined. */
|
|
1420
|
+
function transferActionOf(url) {
|
|
1421
|
+
const value = actionParamOf(url);
|
|
1422
|
+
return value === "export" || value === "preview" || value === "import" ? value : void 0;
|
|
1423
|
+
}
|
|
1424
|
+
/** Read the shared action parameter; unknown/absent means undefined. */
|
|
1425
|
+
function actionParamOf(url) {
|
|
1426
|
+
const at = url.indexOf("?");
|
|
1427
|
+
if (at === -1) return void 0;
|
|
1428
|
+
const value = new URLSearchParams(url.slice(at + 1)).get(QODER_ACTION_PARAM);
|
|
1429
|
+
return value === null || value === "" ? void 0 : value;
|
|
1430
|
+
}
|
|
1431
|
+
/** Query parameter naming ONE pool account a per-row request addresses. */
|
|
1432
|
+
const QODER_POOL_ACCOUNT_PARAM = "accountId";
|
|
1433
|
+
/** Read the per-row account id off a request URL, when the action takes one. */
|
|
1434
|
+
function poolAccountIdOf(url) {
|
|
1435
|
+
const at = url.indexOf("?");
|
|
1436
|
+
if (at === -1) return void 0;
|
|
1437
|
+
const value = new URLSearchParams(url.slice(at + 1)).get(QODER_POOL_ACCOUNT_PARAM);
|
|
1438
|
+
return value !== null && value !== "" ? value : void 0;
|
|
1439
|
+
}
|
|
1440
|
+
/** All region keys, in display order. The single source for region loops. */
|
|
1441
|
+
const QODER_WEB_REGIONS = ["cn", "global"];
|
|
1442
|
+
/** Every domain {@link knownQoderRegionOfDomain} admits, i.e. the transfer domains. */
|
|
1443
|
+
const TRANSFER_DOMAINS = ["qoder.com.cn", "qoder.sh"];
|
|
1444
|
+
/**
|
|
1445
|
+
* The login domain a transfer record must carry to belong to a region.
|
|
1446
|
+
*
|
|
1447
|
+
* Qoder has two gateways with distinct hosts, so a transferred PAT identifies
|
|
1448
|
+
* its region by the host it was minted against — `qoder.com.cn` is the CN
|
|
1449
|
+
* gateway's domain, `qoder.sh` the international one.
|
|
1450
|
+
*/
|
|
1451
|
+
function knownQoderRegionOfDomain(domain) {
|
|
1452
|
+
if (domain === "qoder.com.cn") return "cn";
|
|
1453
|
+
if (domain === "qoder.sh") return "global";
|
|
1454
|
+
}
|
|
1455
|
+
/**
|
|
1456
|
+
* 该区域的**传输域名**:导出账号时写进 transfer 文件的 `domain` 字段。
|
|
1457
|
+
*
|
|
1458
|
+
* 与 {@link knownQoderRegionOfDomain}(域名 → 区域)是同一组事实的**反向读法**,
|
|
1459
|
+
* 所以在这里定义、并从那张反查表**推导**出来,而不是再手抄一遍域名 —— 手抄才是
|
|
1460
|
+
* 这两处漂移过一次就很难被发现的原因。推导失败即抛错,让漏登记的区域在编译期
|
|
1461
|
+
* 与首屏就暴露,而不是等到用户导出才发现。
|
|
1462
|
+
*
|
|
1463
|
+
* 注意这与 {@link QODER_CONSOLE_DOMAIN} **不是同一个域名**:那边是用户浏览器里
|
|
1464
|
+
* 申请 PAT 的控制台(国际版是 `qoder.com`),这边是 PAT 实际发证方所在的网关域
|
|
1465
|
+
* (国际版是 `qoder.sh`),导入时的区域门只认后者。
|
|
1466
|
+
*/
|
|
1467
|
+
const QODER_REGION_TRANSFER_DOMAIN = (() => {
|
|
1468
|
+
const table = {};
|
|
1469
|
+
for (const region of QODER_WEB_REGIONS) table[region] = "";
|
|
1470
|
+
for (const domain of TRANSFER_DOMAINS) {
|
|
1471
|
+
const region = knownQoderRegionOfDomain(domain);
|
|
1472
|
+
if (region === void 0) throw new Error(`transfer domain is not a known Qoder region: ${domain}`);
|
|
1473
|
+
table[region] = domain;
|
|
1474
|
+
}
|
|
1475
|
+
for (const region of QODER_WEB_REGIONS) if (table[region] === "") throw new Error(`region has no transfer domain: ${region}`);
|
|
1476
|
+
return table;
|
|
1477
|
+
})();
|
|
1478
|
+
/**
|
|
1479
|
+
* 该区域请求实际打到的**网关主机名**(不含协议),只用于诊断展示。
|
|
1480
|
+
*
|
|
1481
|
+
* 为什么要有这一行:卡片的「诊断」栏要如实回答「这次请求打到哪个域名」,而这句话
|
|
1482
|
+
* 必须与 `QODER_REGIONS[region].gateway` **同一个事实**。此前卡片只有
|
|
1483
|
+
* {@link QODER_CONSOLE_DOMAIN}(用户浏览器里申请 PAT 的控制台),两者在区域之间
|
|
1484
|
+
* 恰好是相反的形状(控制台是 `qoder.com`,网关却是 `api1.qoder.sh`)—— 拿控制台
|
|
1485
|
+
* 域名去回答诊断问题会给出一个**看起来对、实际不是请求目标**的答案。所以这张表
|
|
1486
|
+
* 放在这里,并由 `upstream.ts` 的 `QODER_REGIONS` **直接消费**(见那里的
|
|
1487
|
+
* `gateway` 字段),不手抄第二遍:两处域名漂移过一次就很难被发现。
|
|
1488
|
+
*/
|
|
1489
|
+
const QODER_UPSTREAM_DOMAIN = {
|
|
1490
|
+
cn: "gateway.qoder.com.cn",
|
|
1491
|
+
global: "api1.qoder.sh"
|
|
1492
|
+
};
|
|
1493
|
+
/**
|
|
1494
|
+
* Deep copy of a settings value with every `{get(): T}` live reference
|
|
1495
|
+
* replaced by the value it resolves to.
|
|
1496
|
+
*
|
|
1497
|
+
* `regions` is declared `asVolatile(...)`, and schemastery resolves a volatile
|
|
1498
|
+
* field to a live reference. A live reference is still `typeof === 'object'`,
|
|
1499
|
+
* so `{ ...reference }` does NOT read the field: it produces
|
|
1500
|
+
* `{ get: <function> }`. Any caller that spreads the resolved field to
|
|
1501
|
+
* preserve its siblings would otherwise DROP every sibling and leak a
|
|
1502
|
+
* function into the document. Both halves therefore unwrap before touching a
|
|
1503
|
+
* resolved field.
|
|
1504
|
+
*/
|
|
1505
|
+
function unwrapVolatileDeep(value) {
|
|
1506
|
+
if (value === null || typeof value !== "object") return value;
|
|
1507
|
+
if (typeof value.get === "function") return unwrapVolatileDeep(value.get());
|
|
1508
|
+
if (Array.isArray(value)) return value.map((entry) => unwrapVolatileDeep(entry));
|
|
1509
|
+
const source = value;
|
|
1510
|
+
const out = {};
|
|
1511
|
+
for (const key of Object.keys(source)) out[key] = unwrapVolatileDeep(source[key]);
|
|
1512
|
+
return out;
|
|
1513
|
+
}
|
|
1514
|
+
/** 界面上给的全部档位,升序。默认值不在这里 —— 见 {@link pollMinutesOf}。 */
|
|
1515
|
+
const QODER_POLL_MINUTES_OPTIONS = [
|
|
1516
|
+
1,
|
|
1517
|
+
5,
|
|
1518
|
+
10,
|
|
1519
|
+
30,
|
|
1520
|
+
60
|
|
1521
|
+
];
|
|
1522
|
+
/**
|
|
1523
|
+
* 读全局的刷新间隔。
|
|
1524
|
+
*
|
|
1525
|
+
* 与 `sidebarPanelEnabledOf` 同规:先 `unwrapVolatileDeep`(cosmokit 的活引用
|
|
1526
|
+
* 不解包时 `===` 恒假),再**白名单**校验 —— 配置是用户可编辑的 JSON,任何不在
|
|
1527
|
+
* 五档里的值(手改的 `0`、`"5"`、`2.5`)都退回默认,而不是把 `setInterval` 交给
|
|
1528
|
+
* 一个没校验过的数。
|
|
1529
|
+
*/
|
|
1530
|
+
function pollMinutesOf(value) {
|
|
1531
|
+
const unwrapped = unwrapVolatileDeep(value);
|
|
1532
|
+
const minutes = unwrapVolatileDeep(typeof unwrapped === "object" && unwrapped !== null && !Array.isArray(unwrapped) ? unwrapped["pollMinutes"] : void 0);
|
|
1533
|
+
return QODER_POLL_MINUTES_OPTIONS.includes(minutes) ? minutes : 5;
|
|
1534
|
+
}
|
|
1535
|
+
/**
|
|
1536
|
+
* 侧边栏面板这一行的**顶层**设置字段名(不在 `regions.<region>.` 下)。
|
|
1537
|
+
*
|
|
1538
|
+
* 参考:dsh-connect-workbuddy 的 `Config.sidebarPanel`(PR #188,MIT,
|
|
1539
|
+
* Copyright (c) 2026 LaoDing)。
|
|
1540
|
+
*
|
|
1541
|
+
* 与积分读数那几个开关不同,这一项**没有区域轴**:侧边栏只有一条 Qoder 行、
|
|
1542
|
+
* 一个整页,不随「国内版 / 国际版」变。所以它住在配置顶层,而不是每个区域槽
|
|
1543
|
+
* 各存一份——存两份就会出现「cn 开着、global 关着,那这一行到底算谁的」这种
|
|
1544
|
+
* 没有答案的状态。
|
|
1545
|
+
*/
|
|
1546
|
+
const QODER_SIDEBAR_PANEL_FIELD = "sidebarPanel";
|
|
1547
|
+
/** The top-level settings field carrying the global upstream-refresh interval. */
|
|
1548
|
+
const QODER_POLL_MINUTES_FIELD = "pollMinutes";
|
|
1549
|
+
/**
|
|
1550
|
+
* 是否在 DSH 侧边栏加一个 Qoder 面板行(+ 对应的整页)。
|
|
1551
|
+
*
|
|
1552
|
+
* **默认关闭**,且判据是 `=== true` 而不是 `!== false`:这一行占的是
|
|
1553
|
+
* `sidebar.panellist` 这个**所有插件共用的全局座位**,点开还会接管中央面板。
|
|
1554
|
+
* 打开它是对用户整个侧边栏的决定,不是对这张卡片的偏好——所以「没写过」
|
|
1555
|
+
* 必须读成「没要」,升级不能替用户重新排一次侧边栏。
|
|
1556
|
+
*
|
|
1557
|
+
* 参考 workbuddy 的 `unwrapVolatile(current().sidebarPanel) === true`(同一条
|
|
1558
|
+
* 理由);Qoder 这边的字段同样声明成 volatile(见 `src/index.ts` 的
|
|
1559
|
+
* `Config`),所以这里先解包再判。
|
|
1560
|
+
*/
|
|
1561
|
+
function sidebarPanelEnabledOf(value) {
|
|
1562
|
+
const unwrapped = unwrapVolatileDeep(value);
|
|
1563
|
+
return unwrapVolatileDeep(typeof unwrapped === "object" && unwrapped !== null && !Array.isArray(unwrapped) ? unwrapped[QODER_SIDEBAR_PANEL_FIELD] : void 0) === true;
|
|
1564
|
+
}
|
|
1565
|
+
/**
|
|
1566
|
+
* The plugin's DECLARED settings namespace — the fallback name, not the value
|
|
1567
|
+
* the host necessarily serves.
|
|
1568
|
+
*
|
|
1569
|
+
* On 0.1.7 the settings service keys every form by the plugin's Loader entry
|
|
1570
|
+
* id (`describe()` returns `ns: entry.options.id`), and the harness resolves
|
|
1571
|
+
* a provider's namespace by EXACT match. The entry id is chosen by the
|
|
1572
|
+
* profile patch (`cordis.patch.yml`), so the declared id mirrors it.
|
|
1573
|
+
*/
|
|
1574
|
+
const QODER_SETTINGS_NS = "dsh-connect-qoder";
|
|
1575
|
+
//#endregion
|
|
1576
|
+
//#region src/native-modality.ts
|
|
1577
|
+
/**
|
|
1578
|
+
* 已核对的分类,按**精确 model id**(绝不用前缀匹配)键控。
|
|
1579
|
+
* 不在本表中的 id 一律 `unknown` —— 见 {@link nativeModalityOf}。
|
|
1580
|
+
*
|
|
1581
|
+
* 主键是 Qoder 的**内部短 id**(稳定),厂商显示名作别名(见文件头
|
|
1582
|
+
* 「为什么按短 id 键控」)。两个键指向同一结论,`imageDefaultFor` 会依次试。
|
|
1583
|
+
*/
|
|
1584
|
+
const NATIVE_MODALITY_BY_MODEL_ID = {
|
|
1585
|
+
"qmodel_38max": "multimodal",
|
|
1586
|
+
"qfmodel": "multimodal",
|
|
1587
|
+
"dmodel": "multimodal",
|
|
1588
|
+
"dfmodel": "multimodal",
|
|
1589
|
+
"gmodel": "multimodal",
|
|
1590
|
+
"gfmodel": "multimodal",
|
|
1591
|
+
"kmodel_latest": "multimodal",
|
|
1592
|
+
"kmodel": "multimodal",
|
|
1593
|
+
"mmodel": "multimodal",
|
|
1594
|
+
"fast": "multimodal",
|
|
1595
|
+
"ultimate": "multimodal",
|
|
1596
|
+
"efficient": "multimodal",
|
|
1597
|
+
"smodel": "multimodal",
|
|
1598
|
+
"cmodel": "multimodal",
|
|
1599
|
+
"qwen3.8-max": "multimodal",
|
|
1600
|
+
"qwen3.8-flash": "multimodal",
|
|
1601
|
+
"deepseek-v4-pro": "multimodal",
|
|
1602
|
+
"deepseek-flash": "multimodal",
|
|
1603
|
+
"glm-5.3": "multimodal",
|
|
1604
|
+
"glm-5.3-flash": "multimodal",
|
|
1605
|
+
"kimi-k3.1-pro": "multimodal",
|
|
1606
|
+
"kimi-k2.8-preview": "multimodal",
|
|
1607
|
+
"minimax-m3.1-flash": "multimodal",
|
|
1608
|
+
"sonus": "multimodal",
|
|
1609
|
+
"cantus": "multimodal",
|
|
1610
|
+
"kimi-k2.7-code": "multimodal",
|
|
1611
|
+
"qwen3.7-max": "multimodal",
|
|
1612
|
+
"qwen3.8-max-preview": "multimodal",
|
|
1613
|
+
"qwen3.7-plus": "multimodal",
|
|
1614
|
+
"qwen3.6-flash": "multimodal",
|
|
1615
|
+
"gm51model": "multimodal",
|
|
1616
|
+
"glm-5.2": "multimodal",
|
|
1617
|
+
"minimax-m2.7": "multimodal"
|
|
1618
|
+
};
|
|
1619
|
+
/**
|
|
1620
|
+
* 上游的**路由器**(router),不是模型。
|
|
1621
|
+
*
|
|
1622
|
+
* `auto` 是一个「挑模型的入口」:网关在**请求时**才决定把它解析成哪一个模型。
|
|
1623
|
+
* 所以它的上下文窗口、思考档位与计费对象都由别人临时决定,插件无法如实描述
|
|
1624
|
+
* ——本仓库保存下来的真实目录里,`auto` 正是**唯一没有思考档位**、却带着
|
|
1625
|
+
* `isDefault: true` 的那一行。把它列成一个可勾选的模型,用户勾的是一个「未知
|
|
1626
|
+
* 会变成谁」的条目。
|
|
1627
|
+
*
|
|
1628
|
+
* **用显式表而不是名字启发式**:路由是上游的概念,没有声明字段可查;按名字
|
|
1629
|
+
* 猜(比如「叫 auto 的都丢」)迟早会误伤一个真的叫这个名字的模型。要往这里
|
|
1630
|
+
* 加 id,先拿到与 `auto` 同等强度的证据。
|
|
1631
|
+
*
|
|
1632
|
+
* 参考:dingminhua/dsh-connect-workbuddy(MIT,Copyright (c) 2026 LaoDing)的
|
|
1633
|
+
* `ROUTER_MODEL_IDS` / `isRouterModelId`——那边同样用显式表而非启发式。
|
|
1634
|
+
*/
|
|
1635
|
+
const ROUTER_MODEL_IDS = /* @__PURE__ */ new Set(["auto"]);
|
|
1636
|
+
/** 这个 id 是不是上游路由器(而不是模型)。 */
|
|
1637
|
+
function isRouterModelId(modelId) {
|
|
1638
|
+
return ROUTER_MODEL_IDS.has(normalizeModelId(modelId));
|
|
1639
|
+
}
|
|
1640
|
+
/**
|
|
1641
|
+
* 一次模型刷新是否应当**预勾选**该模型的图片开关。
|
|
1642
|
+
*
|
|
1643
|
+
* 只有表里确认 `multimodal` 的会被预勾选。`text` 已写明不能读图,而
|
|
1644
|
+
* `unknown` 是刻意留空而非猜测——这张表存在的全部理由就是平台标记猜错过。
|
|
1645
|
+
* 平台的 `supportsImages: false` 仍然拥有一票否决权,所以一个表里 multimodal
|
|
1646
|
+
* 的 id 也不会在平台明确说「不支持」时被预勾选。
|
|
1647
|
+
*
|
|
1648
|
+
* 用户始终可以手动勾选;这里只决定**默认值**,运行时生效的仍是用户保存的
|
|
1649
|
+
* `imageModelKeys` 之类的持久选择。
|
|
1650
|
+
*
|
|
1651
|
+
* **`name` 是必须传的第二个候选键**(issue #22 的根因)。表的主键是 Qoder 内部
|
|
1652
|
+
* 短 id(`qmodel_38max`),但旧存档、外部选择器与旧表都以**厂商显示名**
|
|
1653
|
+
* (`Qwen3.8-Max`)称呼同一个模型。调用方此前只传 `key`,两边结构上不可能
|
|
1654
|
+
* 相等 ⇒ 每一次 seed 查表都落到 `undefined` ⇒ 整张表是死代码。传两个候选键
|
|
1655
|
+
* 就是把这张表真正接上线。
|
|
1656
|
+
*
|
|
1657
|
+
* 仍然是**精确**匹配、不做模糊匹配:短 id 与显示名各查一次同样的表,查不到
|
|
1658
|
+
* 就是 unknown。**不**从同族前缀继承(`qwen3.9-max` 不会因为 `qwen3.8-max`
|
|
1659
|
+
* 是 multimodal 而被勾上)。
|
|
1660
|
+
*/
|
|
1661
|
+
function imageDefaultFor(info) {
|
|
1662
|
+
if (info.supportsImages === false) return false;
|
|
1663
|
+
if (NATIVE_MODALITY_BY_MODEL_ID[normalizeModelId(info.id)] === "multimodal") return true;
|
|
1664
|
+
if (info.name === void 0 || info.name === "") return false;
|
|
1665
|
+
return NATIVE_MODALITY_BY_MODEL_ID[normalizeModelId(info.name).replace(/\s+/gu, "-")] === "multimodal";
|
|
1666
|
+
}
|
|
1667
|
+
/**
|
|
1668
|
+
* 把 Qoder 的内部短 id(`qmodel_latest` 等)或显示名归一到本表键。
|
|
1669
|
+
*
|
|
1670
|
+
* 内置目录里 `key` 是短 id、`displayName` 是厂商模型名,两处都可能被当成
|
|
1671
|
+
* 「模型 id」传进来;先按原样查表,查不到再用显示名的小写连字符形式兜底。
|
|
1672
|
+
* 仍然查不到就是 unknown——兜底只是多给一次**精确**匹配机会,绝不做模糊匹配。
|
|
1673
|
+
*/
|
|
1674
|
+
function normalizeModelId(modelId) {
|
|
1675
|
+
return modelId.trim().toLowerCase();
|
|
1676
|
+
}
|
|
1677
|
+
//#endregion
|
|
1678
|
+
//#region src/endpoints.ts
|
|
1679
|
+
/**
|
|
1680
|
+
* 发现端点路径。
|
|
1681
|
+
*
|
|
1682
|
+
* `v3` 是客户端 `aAt` / `Axg` 用的那条;`v5`(`I9i` / `txg`,前缀 `/algo`)是
|
|
1683
|
+
* 同一份表的另一个版本。只打 v3:v5 在客户端里是可选/灰度路径,且返回形状
|
|
1684
|
+
* 还需 `data` 包装,多打一条没有收益。
|
|
1685
|
+
*/
|
|
1686
|
+
const REGION_ENDPOINTS_PATH = "/api/v3/service/region/endpoints";
|
|
1687
|
+
/** 与客户端 `B9i = 3e5` 同值:5 分钟。 */
|
|
1688
|
+
const ENDPOINTS_TTL_MS = 3e5;
|
|
1689
|
+
/** 与客户端选举超时同量级:发现失败要立刻退回默认,不能拖慢首包。 */
|
|
1690
|
+
const ENDPOINTS_TIMEOUT_MS = 1e3;
|
|
1691
|
+
function asRecord(value) {
|
|
1692
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
1693
|
+
}
|
|
1694
|
+
/**
|
|
1695
|
+
* 规范成 `https://host/` 形式;无效项返回 undefined。
|
|
1696
|
+
*
|
|
1697
|
+
* 与 pi 的 `normalizeBaseUrl` 同法:允许上游只给主机名(客户端也这么处理:
|
|
1698
|
+
* `/^[a-z][a-z\d+.-]*:\/\//i.test(A) ? A : \`https://${A}\``)。
|
|
1699
|
+
*/
|
|
1700
|
+
function normalizeNodeUrl(raw) {
|
|
1701
|
+
const trimmed = raw.trim();
|
|
1702
|
+
if (trimmed === "") return void 0;
|
|
1703
|
+
const withScheme = /^[a-z][a-z\d+.-]*:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
|
|
1704
|
+
return withScheme.endsWith("/") ? withScheme : `${withScheme}/`;
|
|
1705
|
+
}
|
|
1706
|
+
/**
|
|
1707
|
+
* 解析一条节点数组。
|
|
1708
|
+
*
|
|
1709
|
+
* `enterprise` 类型的节点在这里**一律跳过**:本插件走个人 PAT,不是企业环境,
|
|
1710
|
+
* 而客户端在非企业环境下也是跳过它们的(`A$c`)。把企业节点当普通节点轮换,
|
|
1711
|
+
* 只会撞到「该节点不接受你」的 403。
|
|
1712
|
+
*/
|
|
1713
|
+
function parseNodes(value) {
|
|
1714
|
+
if (!Array.isArray(value)) return [];
|
|
1715
|
+
const out = [];
|
|
1716
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1717
|
+
for (const item of value) {
|
|
1718
|
+
let raw;
|
|
1719
|
+
if (typeof item === "string") raw = item;
|
|
1720
|
+
else {
|
|
1721
|
+
const record = asRecord(item);
|
|
1722
|
+
if (record === void 0) continue;
|
|
1723
|
+
if ((typeof record.type === "string" ? record.type : "public") === "enterprise") continue;
|
|
1724
|
+
if (typeof record.url !== "string") continue;
|
|
1725
|
+
raw = record.url;
|
|
1726
|
+
}
|
|
1727
|
+
const normalized = normalizeNodeUrl(raw);
|
|
1728
|
+
if (normalized === void 0 || seen.has(normalized)) continue;
|
|
1729
|
+
seen.add(normalized);
|
|
1730
|
+
out.push(normalized);
|
|
1731
|
+
}
|
|
1732
|
+
return out;
|
|
1733
|
+
}
|
|
1734
|
+
/**
|
|
1735
|
+
* 解析发现响应。整体形状不成立时返回 undefined(调用方退回默认网关)。
|
|
1736
|
+
*
|
|
1737
|
+
* 接受两种包装:直接在根上(`{centerNodes,...}`),或包在 `data` 里
|
|
1738
|
+
* (`{version, data:{centerNodes,...}}`,客户端 `createEndpointTopology` 的形状)。
|
|
1739
|
+
*
|
|
1740
|
+
* 只要**有任何一个**节点列表非空就算成功 —— 与客户端一致(它的
|
|
1741
|
+
* `createEndpointTopology` 只在「所有集合都空」时才放弃)。
|
|
1742
|
+
*/
|
|
1743
|
+
function parseRegionEndpoints(payload) {
|
|
1744
|
+
const root = asRecord(payload);
|
|
1745
|
+
if (root === void 0) return void 0;
|
|
1746
|
+
const source = asRecord(root.data) ?? root;
|
|
1747
|
+
const nodes = {
|
|
1748
|
+
center: parseNodes(source.centerNodes),
|
|
1749
|
+
inference: parseNodes(source.inferNodes),
|
|
1750
|
+
securityInference: parseNodes(source.security),
|
|
1751
|
+
openapi: parseNodes(source.openapiNodes)
|
|
1752
|
+
};
|
|
1753
|
+
return nodes.center.length + nodes.inference.length + nodes.securityInference.length + nodes.openapi.length === 0 ? void 0 : nodes;
|
|
1754
|
+
}
|
|
1755
|
+
/**
|
|
1756
|
+
* 把「上一次用的节点」排到最前,其余保持原序。
|
|
1757
|
+
*
|
|
1758
|
+
* 这就是客户端 `orderEndpointSet` 的做法(`let t = ...candidates[0]?.origin`,
|
|
1759
|
+
* 然后把 `t` 提到首位):**上次成功的节点优先**,但不丢弃其余候选。这样既不会
|
|
1760
|
+
* 每轮跳节点(跳节点等于丢 KV cache),又能在它坏掉时自然滑到下一个。
|
|
1761
|
+
*/
|
|
1762
|
+
function orderWithLastFirst(nodes, lastUsed) {
|
|
1763
|
+
if (lastUsed === void 0 || !nodes.includes(lastUsed)) return nodes.slice();
|
|
1764
|
+
return [lastUsed, ...nodes.filter((node) => node !== lastUsed)];
|
|
1765
|
+
}
|
|
1766
|
+
/**
|
|
1767
|
+
* 缓存节点表。
|
|
1768
|
+
*
|
|
1769
|
+
* 刻意用**实例**而不是模块级单例:上游客户端在测试里会被反复新建,模块级状态
|
|
1770
|
+
* 会让测试互相污染(pi 那边为此专门加了 `QODER_ENDPOINTS_CACHE_PATH` 环境变量
|
|
1771
|
+
* 来隔离,说明模块级状态确实咬过人)。
|
|
1772
|
+
*/
|
|
1773
|
+
var QoderEndpointCache = class {
|
|
1774
|
+
ttlMs;
|
|
1775
|
+
nodes;
|
|
1776
|
+
fetchedAtMs = 0;
|
|
1777
|
+
constructor(ttlMs = ENDPOINTS_TTL_MS) {
|
|
1778
|
+
this.ttlMs = ttlMs;
|
|
1779
|
+
}
|
|
1780
|
+
/** 缓存是否仍然新鲜。 */
|
|
1781
|
+
isFresh(nowMs = Date.now()) {
|
|
1782
|
+
return this.nodes !== void 0 && nowMs - this.fetchedAtMs < this.ttlMs;
|
|
1783
|
+
}
|
|
1784
|
+
/** 读缓存(不新鲜则为 undefined)。 */
|
|
1785
|
+
read(nowMs = Date.now()) {
|
|
1786
|
+
return this.isFresh(nowMs) ? this.nodes : void 0;
|
|
1787
|
+
}
|
|
1788
|
+
/** 写入缓存。 */
|
|
1789
|
+
write(nodes, nowMs = Date.now()) {
|
|
1790
|
+
this.nodes = nodes;
|
|
1791
|
+
this.fetchedAtMs = nowMs;
|
|
1792
|
+
}
|
|
1793
|
+
/** 清空(登出/换账号时用:节点表按账号下发)。 */
|
|
1794
|
+
clear() {
|
|
1795
|
+
this.nodes = void 0;
|
|
1796
|
+
this.fetchedAtMs = 0;
|
|
1797
|
+
}
|
|
1798
|
+
};
|
|
1799
|
+
//#endregion
|
|
1800
|
+
//#region src/upstream.ts
|
|
1801
|
+
/**
|
|
1802
|
+
* Qoder 上游 HTTP 客户端:cosy 签名请求、jobToken 交换、聊天 SSE、
|
|
1803
|
+
* 模型目录与用量查询。
|
|
1804
|
+
*
|
|
1805
|
+
* 端点映射(CN 与 Global 双区域)。两区域**各自一个网关主机**,chat / models /
|
|
1806
|
+
* jobToken 三个端点共用它(见 `QODER_REGIONS` 的 `gateway` 字段):
|
|
1807
|
+
*
|
|
1808
|
+
* ```text
|
|
1809
|
+
* CN gateway: gateway.qoder.com.cn
|
|
1810
|
+
* chat: /algo/api/v2/service/pro/sse/agent_chat_generation
|
|
1811
|
+
* models: /algo/api/v2/model/list
|
|
1812
|
+
* jobToken: /algo/api/v3/user/jobToken
|
|
1813
|
+
* openapi: openapi.qoder.com.cn
|
|
1814
|
+
* Global gateway: api1.qoder.sh
|
|
1815
|
+
* chat: /algo/api/v2/service/pro/sse/agent_chat_generation
|
|
1816
|
+
* models: /algo/api/v2/model/list
|
|
1817
|
+
* jobToken: /algo/api/v3/user/jobToken
|
|
1818
|
+
* openapi: openapi.qoder.sh
|
|
1819
|
+
* ```
|
|
1820
|
+
*
|
|
1821
|
+
* 注:早期注释称国际版的 models 走 `api2.qoder.sh`、jobToken 走
|
|
1822
|
+
* `center.qoder.sh`。实测(2026-10)三者对本插件用到的端点**完全等效**——
|
|
1823
|
+
* 对同一个假 PAT 都回 `401 personal token is invalid`(凭据层被拒,而非
|
|
1824
|
+
* `Signature invalid`),说明三者都接受同一套 cosy 签名、只是拒绝坏凭据。
|
|
1825
|
+
* 所以国际版统一用 `api1.qoder.sh`,不按端点分主机;若将来真要分流,请改
|
|
1826
|
+
* `QODER_REGIONS` 的配置表,而不是只改这段注释。
|
|
1827
|
+
*
|
|
1828
|
+
* @module dsh-connect-qoder/upstream
|
|
1829
|
+
*/
|
|
1830
|
+
const CHAT_PATH = "/algo/api/v2/service/pro/sse/agent_chat_generation?FetchKeys=llm_model_result&AgentId=agent_common&Encode=1";
|
|
1831
|
+
/**
|
|
1832
|
+
* 轮次闭合端点。官方客户端在一轮用户提示结束时**必发**一次(实测:每轮恰好
|
|
1833
|
+
* 1 次,与补全次数无关 —— 一轮 2 次补全仍是 1 次闭合)。
|
|
1834
|
+
*
|
|
1835
|
+
* 客户端源码里的位置是 `business/finish`(`Qd.finish()`),body 形状见
|
|
1836
|
+
* {@link QoderUpstreamClient.finishTurn} 的使用处。
|
|
1837
|
+
*
|
|
1838
|
+
* 不发它,服务端只能等 TTL 释放租约:那一轮在记账上永远是「进行中」,控制台
|
|
1839
|
+
* 里也就不产生逐条消费行 —— 这正是本插件长期缺的那一环。
|
|
1840
|
+
*/
|
|
1841
|
+
const FINISH_PATH = "/algo/api/v2/service/business/finish?Encode=1";
|
|
1842
|
+
/**
|
|
1843
|
+
* 每日签到走 `sash` 的**活动**接口。路径里没有「签到」二字(叫 campaigns),
|
|
1844
|
+
* 所以照着 checkin / signin / reward 猜永远猜不到——实测猜了 13 个全 404。
|
|
1845
|
+
* 注意是 **v1**(用量那套是 v2)。
|
|
1846
|
+
*/
|
|
1847
|
+
const CAMPAIGNS_PATH = "/sash/api/v1/me/campaigns";
|
|
1848
|
+
/**
|
|
1849
|
+
* sash 面专用的令牌交换端点(CLI / 网页那一族)。
|
|
1850
|
+
*
|
|
1851
|
+
* 与 {@link JOB_TOKEN_PATH}(桌面客户端那一族)**并存**,不是替代 —— 实测国际版
|
|
1852
|
+
* 的 chat 面只认前者换来的 `securityOauthToken`,而 sash / 额度面只认这里换来的
|
|
1853
|
+
* `token`;国内版两族等价。见 `QoderSessionHolder.sashToken`。
|
|
1854
|
+
*/
|
|
1855
|
+
const SASH_TOKEN_PATH = "/api/v1/jobToken/exchange";
|
|
1856
|
+
const CAMPAIGNS_QUERY = "?forceRefresh=true";
|
|
1857
|
+
/** sash 接口要求的客户端标识(参考实现如此,缺了会被拒)。 */
|
|
1858
|
+
const SASH_CLIENT_TYPE = "10";
|
|
1859
|
+
const SASH_USER_AGENT = "Qoder";
|
|
1860
|
+
/**
|
|
1861
|
+
* **cosy 面**(chat + models)的客户端身份:`cosy-clienttype` 与 `cosy-version`。
|
|
1862
|
+
*
|
|
1863
|
+
* 上游按这两个头决定下发哪一套模型目录。旧值 `5` / `0.1.43` 是 2026-10-11 写下
|
|
1864
|
+
* 时正确的身份,那时上游还没有 Sonus/Cantus/Fast;上游后来把新模型只发给新
|
|
1865
|
+
* 协议,于是旧身份拿到的是**静默的旧目录**——目录照常返回、对话照常能跑,只是
|
|
1866
|
+
* 少几个模型,没有任何报错指向这里(issue #21)。
|
|
1867
|
+
*
|
|
1868
|
+
* 实测(2026-10-29,两个区域各一枚真实 PAT,只读目录 + 一次对话):
|
|
1869
|
+
*
|
|
1870
|
+
* | 区域 | `5` / `0.1.43` | `10` / `1.1.69` |
|
|
1871
|
+
* | ------ | -------------- | ---------------------- |
|
|
1872
|
+
* | cn | 9 条 | 10 条(+`fast`) |
|
|
1873
|
+
* | global | 11 条 | 14 条(+`smodel`/`cmodel`/`fast`) |
|
|
1874
|
+
*
|
|
1875
|
+
* 两个值必须**成对**改:国内版只把 clienttype 提到 `10`、version 留在 `0.1.43`
|
|
1876
|
+
* 时,目录仍只有 9 条(拿不到 `fast`),而 chat 直接报
|
|
1877
|
+
* `HTTP 403 code 112`(「协议半改」的坏状态)。成对改之后 chat 两个区域都正常
|
|
1878
|
+
* 吐字,`qfmodel` / `dfmodel` 与新增的 `fast` / `smodel` 都实测通过。
|
|
1879
|
+
*
|
|
1880
|
+
* ## `clienttype` 为什么是 `5` 不是 `10`(2026-11-21 抓包纠正)
|
|
1881
|
+
*
|
|
1882
|
+
* 上面那次是**只读探测**得出的「能拿到更多模型」的组合,不是「真实客户端发什么」。
|
|
1883
|
+
* 对官方 CN CLI(qoderclicn 1.1.94)实测抓包 105 个请求,`cosy-clienttype`
|
|
1884
|
+
* **全部是 `5`**,一次 `10` 都没有;同时它的目录里 13 个模型一个不少
|
|
1885
|
+
* (`auto`/`fast`/`qmodel_latest`/`qmodel_38max`/`qfmodel`/`dmodel`/`dfmodel`/
|
|
1886
|
+
* `gmodel`/`gfmodel`/`kmodel_latest`/`kmodel`/`jmodel`/`mmodel`)。
|
|
1887
|
+
*
|
|
1888
|
+
* 所以 `10` 是「桌面 App 通道」的值(magpie 至今用它,并配套 `product: app`、
|
|
1889
|
+
* `Cosy-Version: 1.1.69`)。我们用 `cli` 产品线、走 PAT,就该是 `5` —— 与真实
|
|
1890
|
+
* CLI 逐字一致,同时并不损失目录。**`10` 曾解决的是旧 `0.1.43` 版本号的目录
|
|
1891
|
+
* 缩水问题,那个问题的真解是把版本号提上去,不是把 clienttype 换成桌面通道。**
|
|
1892
|
+
*
|
|
1893
|
+
* `cosy-version` 不再在这里写死:它必须与 bearer 载荷里的 `cosyVersion` 同值,
|
|
1894
|
+
* 由 {@link QoderUpstreamClient.clientVersion} 统一提供(见 `client-version.ts`)。
|
|
1895
|
+
*
|
|
1896
|
+
* 与 sash 面**无关**:`sashRequest` / `fetchUsageDirect` / `jobTokenGet` 是逐条
|
|
1897
|
+
* 手写请求头,没有展开 {@link DEFAULT_HEADERS},所以这条改动碰不到签到与用量
|
|
1898
|
+
* (实测改完两个区域的用量与活动列表照常 200)。
|
|
1899
|
+
*/
|
|
1900
|
+
const COSY_CLIENT_TYPE = "5";
|
|
1901
|
+
const MODELS_PATH = "/algo/api/v2/model/list?Encode=1";
|
|
1902
|
+
const JOB_TOKEN_PATH = "/algo/api/v3/user/jobToken?Encode=1";
|
|
1903
|
+
/**
|
|
1904
|
+
* `business.product` 的默认值:`cli`。
|
|
1905
|
+
*
|
|
1906
|
+
* 官方客户端有两条产品线,**默认值不同**:
|
|
1907
|
+
*
|
|
1908
|
+
* | 通道 | `product` | 证据 |
|
|
1909
|
+
* | --- | --- | --- |
|
|
1910
|
+
* | CLI / PAT | `cli` | `MKA = "cli"`,`Cs()` → `product: rtA() ?? process.env[...] ?? MKA` |
|
|
1911
|
+
* | 桌面 App | `app` | `electronMain.js`:`Od = {clientType:10, businessProduct:"app"}` |
|
|
1912
|
+
*
|
|
1913
|
+
* 我们这条路径是「PAT → `/algo/api/v3/user/jobToken` → 聊天」,形态上是 CLI
|
|
1914
|
+
* 通道,所以默认 `cli`。**这是实测结论,不是推断**:2026-11-21 抓 CN CLI
|
|
1915
|
+
* 1.1.94 全程,`cosy-business-product` 出现 6 次,值全是 `cli`。
|
|
1916
|
+
*
|
|
1917
|
+
* 一条曾经的错误说法(本注释上一版写着、并在 CHANGELOG 里复述过)必须纠正:
|
|
1918
|
+
* 它说「`Cosy-Business-Product` 这个头出现 **0 次**,`ide` 是从网页版抄来的
|
|
1919
|
+
* 假设」。**头并不缺席** —— 它每次业务请求都带,只是取值在我们这边一直是错的
|
|
1920
|
+
* (`ide`,既不是 `cli` 也不是 `app`)。「头不存在」与「头的值抄错了」是两回事,
|
|
1921
|
+
* 前者会让人以为根本不用发这个头。
|
|
1922
|
+
*/
|
|
1923
|
+
const DEFAULT_BUSINESS_PRODUCT = "cli";
|
|
1924
|
+
/**
|
|
1925
|
+
* `max_tokens` 的兜底上限。
|
|
1926
|
+
*
|
|
1927
|
+
* 与官方客户端的 `defaultTokens: 32e3` 同值 —— 这是客户端的**全局默认**,不是
|
|
1928
|
+
* 我们发明的数。它只在两层上游信息都缺失时生效:
|
|
1929
|
+
*
|
|
1930
|
+
* 1. 调用方传入的 `maxOutputTokens`(来自 `/model/list` 的 `max_output_tokens`);
|
|
1931
|
+
* 2. 兜底 32 768。
|
|
1932
|
+
*
|
|
1933
|
+
* 客户端那套是三层的(`cYa(A,e) = j6r(e) ?? yTg(A)`,`yTg` 查
|
|
1934
|
+
* `model_max_output_tokens` 的逐模型表再退 `default`),但那张表在本机
|
|
1935
|
+
* **是空的**:它读环境变量 `QODER_CONFIG_MODEL_MAX_OUTPUT_TOKENS`,而
|
|
1936
|
+
* `electronMain.js` 里根本不设置这个键(搜到 0 次)。所以官方客户端在同样
|
|
1937
|
+
* 条件下发出的也是 32e3 —— 我们与它一致。
|
|
1938
|
+
*/
|
|
1939
|
+
const DEFAULT_MAX_OUTPUT_TOKENS = 32768;
|
|
1940
|
+
/**
|
|
1941
|
+
* 从上游 400 的报错文案里学 `max_tokens` 的实际上限。
|
|
1942
|
+
*
|
|
1943
|
+
* 抄的是 magpie(`packages/qoder/index.mjs` 的 `LEARNED_CAPS`):上游对越界
|
|
1944
|
+
* 值的回话是 `Range of max_tokens should be [1, N]`,把 N 取出来记住,下一次
|
|
1945
|
+
* 就夹到 N 以内。这比猜一个上限稳 —— 上限会随模型变,而报错文案是上游自己说的。
|
|
1946
|
+
*/
|
|
1947
|
+
const MAX_TOKENS_RANGE_RE = /max_tokens[^0-9]{0,40}\[\s*\d+\s*,\s*(\d+)\s*\]/i;
|
|
1948
|
+
/**
|
|
1949
|
+
* 轮次表的容量上限。
|
|
1950
|
+
*
|
|
1951
|
+
* 表按**轮次**存一条短记录(id / begin_at / stage / end_at),512 轮也就几十 KB
|
|
1952
|
+
* —— 这个数不是性能调优,是给「表不该无限长」一个明确上界。超出时淘汰**最早**
|
|
1953
|
+
* 进来的那一轮(Map 插入序)。被淘汰的轮次不能再闭合(`closeTurn` 返回
|
|
1954
|
+
* undefined),代价是那一轮在服务端靠 TTL 收口,而不是被记成别的阶段。
|
|
1955
|
+
*/
|
|
1956
|
+
const STAGE_MAP_LIMIT = 512;
|
|
1957
|
+
/**
|
|
1958
|
+
* 结束原因 → `business.stage` 终态。逐字照抄客户端 `kVe()`:
|
|
1959
|
+
*
|
|
1960
|
+
* ```js
|
|
1961
|
+
* function kVe(e){switch(e){case"abort":case"repeated_tool_call_denied":return hpe;
|
|
1962
|
+
* case"error":case"max_turns":return gpe;case"end_turn":default:return fpe}}
|
|
1963
|
+
* ```
|
|
1964
|
+
*
|
|
1965
|
+
* 即 `abort` / `repeated_tool_call_denied` → `abort`,`error` / `max_turns` →
|
|
1966
|
+
* `error`,其余(含 `end_turn`)→ `complete`。**没有 `default` 之外的兜底值** ——
|
|
1967
|
+
* 认不出的原因一律记为 `complete`,与客户端一致。
|
|
1968
|
+
*/
|
|
1969
|
+
function endStageOf(reason) {
|
|
1970
|
+
switch (reason) {
|
|
1971
|
+
case "abort":
|
|
1972
|
+
case "repeated_tool_call_denied": return "abort";
|
|
1973
|
+
case "error":
|
|
1974
|
+
case "max_turns": return "error";
|
|
1975
|
+
default: return "complete";
|
|
1976
|
+
}
|
|
1977
|
+
}
|
|
1978
|
+
const QODER_REGIONS = {
|
|
1979
|
+
cn: {
|
|
1980
|
+
gateway: `https://${QODER_UPSTREAM_DOMAIN.cn}`,
|
|
1981
|
+
openapi: "https://openapi.qoder.com.cn",
|
|
1982
|
+
chatPath: CHAT_PATH,
|
|
1983
|
+
modelsPath: MODELS_PATH,
|
|
1984
|
+
jobTokenPath: JOB_TOKEN_PATH,
|
|
1985
|
+
campaignsPath: CAMPAIGNS_PATH,
|
|
1986
|
+
requiresDeviceRisk: false
|
|
1987
|
+
},
|
|
1988
|
+
global: {
|
|
1989
|
+
gateway: `https://${QODER_UPSTREAM_DOMAIN.global}`,
|
|
1990
|
+
openapi: "https://openapi.qoder.sh",
|
|
1991
|
+
chatPath: CHAT_PATH,
|
|
1992
|
+
modelsPath: "/algo/api/v2/model/list?Encode=1",
|
|
1993
|
+
jobTokenPath: "/algo/api/v3/user/jobToken?Encode=1",
|
|
1994
|
+
campaignsPath: CAMPAIGNS_PATH,
|
|
1995
|
+
requiresDeviceRisk: true
|
|
1996
|
+
}
|
|
1997
|
+
};
|
|
1998
|
+
var QoderUpstreamError = class extends Error {
|
|
1999
|
+
kind;
|
|
2000
|
+
status;
|
|
2001
|
+
code;
|
|
2002
|
+
/**
|
|
2003
|
+
* 上游**自己申报**的「请等这么久再试」,毫秒(issue #24)。
|
|
2004
|
+
*
|
|
2005
|
+
* 来自 `10605 / RESOURCE_LIMIT` 信封里的 `retryAfterSeconds`(实测形状:
|
|
2006
|
+
* `{"isQueued":false,"queueCount":0,"retryAfterSeconds":5,"serviceAvailable":true}`),
|
|
2007
|
+
* 或 HTTP `Retry-After` 头。取不到就是 `undefined` —— 「上游没说」与「上游说
|
|
2008
|
+
* 等 0 秒」是两件事,抽取层不替它下结论。
|
|
2009
|
+
*
|
|
2010
|
+
* 这个值的去向有两处,都必须有:①写进给宿主的失败文案(否则用户只看到
|
|
2011
|
+
* 「上游报了个 4xx」,看不到「上游只要求等 5 秒」);②非流式失败响应上的
|
|
2012
|
+
* `Retry-After` 头。宿主在 pi-ai 那条路由上**只从文案分类**,不读头,所以
|
|
2013
|
+
* ①是唯一能让「申报值」影响等待的一条。
|
|
2014
|
+
*/
|
|
2015
|
+
retryAfterMs;
|
|
2016
|
+
/**
|
|
2017
|
+
* 上游说「我在排队」的证据(issue #26)。
|
|
2018
|
+
*
|
|
2019
|
+
* 与 {@link retryAfterMs} 分开是因为它们是**两件事**:`retryAfterMs` 说
|
|
2020
|
+
* 「等多久再来」,`queue` 说「你现在排在第几位、服务本身是好的」。前者决定
|
|
2021
|
+
* 冷却多长,后者决定**怎么跟用户说** —— 把排队说成「连不上上游」是错的
|
|
2022
|
+
* (用户实拍:账号完全正常,六个模型同时可用)。
|
|
2023
|
+
*/
|
|
2024
|
+
queue;
|
|
2025
|
+
constructor(kind, message, status = 0, code, retryAfterMs, queue) {
|
|
2026
|
+
super(message);
|
|
2027
|
+
this.name = "QoderUpstreamError";
|
|
2028
|
+
this.kind = kind;
|
|
2029
|
+
this.status = status;
|
|
2030
|
+
this.code = code;
|
|
2031
|
+
if (retryAfterMs !== void 0 && Number.isFinite(retryAfterMs) && retryAfterMs > 0) this.retryAfterMs = retryAfterMs;
|
|
2032
|
+
if (queue !== void 0) this.queue = queue;
|
|
2033
|
+
}
|
|
2034
|
+
};
|
|
2035
|
+
function isQoderUpstreamError(error) {
|
|
2036
|
+
return error instanceof QoderUpstreamError;
|
|
2037
|
+
}
|
|
2038
|
+
/**
|
|
2039
|
+
* cosy 面(chat + models)的公共请求头。
|
|
2040
|
+
*
|
|
2041
|
+
* 协议版本见 {@link COSY_CLIENT_TYPE}:它决定上游下发哪套模型目录,改之前先读
|
|
2042
|
+
* 那段注释(issue #21 的实测表 + 2026-11-21 抓包对 clienttype 的纠正)。
|
|
2043
|
+
*
|
|
2044
|
+
* `user-agent` 与 `cosy-business-product` 都是**抓包实测**的值:官方 CN CLI
|
|
2045
|
+
* 1.1.94 发的是 `Bun/1.4.4`(它是 Bun 编译的单文件可执行程序)与 `cli`。
|
|
2046
|
+
* 这里此前是 `Go-http-client/2.0` 与 `ide` —— 两个都不对:前者是早期照着
|
|
2047
|
+
* 别人的 Go 实现抄的,后者是从网页版猜的(头名是真的,值不是)。
|
|
2048
|
+
*
|
|
2049
|
+
* ## `user-agent` 为什么是写死的常量,而不是像 `cosy-version` 那样动态解析
|
|
2050
|
+
*
|
|
2051
|
+
* 两者的性质不同,别把它们混成一条规则:
|
|
2052
|
+
*
|
|
2053
|
+
* | 头 | 含义 | 该不该动态 |
|
|
2054
|
+
* | --- | --- | --- |
|
|
2055
|
+
* | `cosy-version` | **Qoder CLI 自己的版本号** | 该 —— 它随 CLI 发布变化,且要在头、bearer 载荷、`business.version` 三处同值 |
|
|
2056
|
+
* | `user-agent` | **编译出那个 CLI 的 Bun 运行时的版本** | 不该 —— 它与 CLI 的版本号没有对应关系,`1.4.4` 是 Bun 的版本,不是 Qoder 的 |
|
|
2057
|
+
*
|
|
2058
|
+
* 具体说:如果把它改成「跟随 `clientVersion`」,就会发出 `Bun/1.1.94` —— 那是
|
|
2059
|
+
* 一个**从未存在过的 Bun 版本**。这恰恰是本仓库反复强调要避免的那类编造:
|
|
2060
|
+
* 一个不存在的版本号比一个「旧但真实」的版本号更显眼。
|
|
2061
|
+
*
|
|
2062
|
+
* 它也不是「我们自己的 UA」:我们跑在 Node 上,但这条链路在协议上**扮演 CLI**,
|
|
2063
|
+
* 所以它必须报 CLI 报的那个值。这与 `cosy-clienttype: 5` 是同一性质 ——
|
|
2064
|
+
* 协议常量,不是运行时事实。Bun 真升级到 1.5 时这个值会变旧,那是可接受的
|
|
2065
|
+
* 陈旧(旧值是合法历史);编一个假值才是筛得出来的异常。
|
|
2066
|
+
*/
|
|
2067
|
+
const DEFAULT_HEADERS = {
|
|
2068
|
+
"cosy-data-policy": "agree",
|
|
2069
|
+
"content-type": "application/json",
|
|
2070
|
+
"cosy-clienttype": COSY_CLIENT_TYPE,
|
|
2071
|
+
"login-version": "v2",
|
|
2072
|
+
"user-agent": "Bun/1.4.4",
|
|
2073
|
+
"cosy-scene": "assistant",
|
|
2074
|
+
"cosy-business-product": DEFAULT_BUSINESS_PRODUCT,
|
|
2075
|
+
"cosy-business-type": "agent"
|
|
2076
|
+
};
|
|
2077
|
+
/**
|
|
2078
|
+
* Qoder 上游客户端。每个区域一个实例;会话按需惰性交换与续期。
|
|
2079
|
+
*/
|
|
2080
|
+
var QoderUpstreamClient = class {
|
|
2081
|
+
region;
|
|
2082
|
+
/** 本实例所属区域(`region` 是它的配置表;这里保留区域名本身)。 */
|
|
2083
|
+
regionKey;
|
|
2084
|
+
logger;
|
|
2085
|
+
installSalt;
|
|
2086
|
+
fetchImpl;
|
|
2087
|
+
/**
|
|
2088
|
+
* 按凭证键控的会话缓存。
|
|
2089
|
+
*
|
|
2090
|
+
* 一个区域实例会同时服务多个账号(账号池批量探测、按账号查额度),
|
|
2091
|
+
* 不同 PAT 的 cosy 会话互不相通,所以会话必须按凭证分开缓存——用单个
|
|
2092
|
+
* 字段会互相覆盖(上一个账号的会话被下一个冲掉)。键是 PAT 本身:
|
|
2093
|
+
* 会话不可再交换,必须绑定到它交换来的那份凭证。
|
|
2094
|
+
*/
|
|
2095
|
+
holders = /* @__PURE__ */ new Map();
|
|
2096
|
+
/** 最近使用的主会话(默认解析路径复用它)。 */
|
|
2097
|
+
currentKey;
|
|
2098
|
+
/**
|
|
2099
|
+
* 每条**用户轮次**的 `business` 生命周期:`id`、`begin_at`、`stage`、`endAt`。
|
|
2100
|
+
*
|
|
2101
|
+
* ## 粒度是「轮次」,不是「会话」,也不是「请求」(这条被实测纠正过两次)
|
|
2102
|
+
*
|
|
2103
|
+
* 官方客户端的 `AgentLifecycle`(`Mh` 类)在**每条用户提示**上 `create` 一次,
|
|
2104
|
+
* `business.id` / `begin_at` 在这一轮的全部工具循环里不变,轮次结束时 `finalize`
|
|
2105
|
+
* 写终态并 `POST /algo/api/v2/service/business/finish` 闭合。
|
|
2106
|
+
*
|
|
2107
|
+
* 实测抓包(qoderclicn 1.1.94,`business/finish` 次数恒为 1):
|
|
2108
|
+
*
|
|
2109
|
+
* | 场景 | `agent_chat_generation` | `business/finish` |
|
|
2110
|
+
* | --- | --- | --- |
|
|
2111
|
+
* | 单轮、无工具 | 1 | 1 |
|
|
2112
|
+
* | 单轮、1 次工具调用 | **3** | **1** |
|
|
2113
|
+
* | 恢复会话后第二轮 | 1 | 1 |
|
|
2114
|
+
*
|
|
2115
|
+
* 即一次用户输入 → 一个 id → N 次补全(N 随工具调用增加)→ 结束时 1 次闭合。
|
|
2116
|
+
*
|
|
2117
|
+
* ## 走过的两条弯路(都别再走回去)
|
|
2118
|
+
*
|
|
2119
|
+
* 1. **每轮 `randomId()`**:最初这个字段和 `request_id` 一样每轮换新,注释还
|
|
2120
|
+
* 写着「它们是单次请求标识」。那让一场会话在服务端被记成 N 条互不相干、
|
|
2121
|
+
* 且从来没被结束过的记录 —— 控制台里一条消费行都不显示。
|
|
2122
|
+
* 2. **整场会话固定**:随后的修法把 `id` 钉在 `session_id` 上。这同样不对:
|
|
2123
|
+
* 会话里第 2、3 轮会复用第 1 轮的 id,服务端把整场会话记成**一条**永远
|
|
2124
|
+
* 不闭合的记录,同样出不了逐轮消费行。
|
|
2125
|
+
*
|
|
2126
|
+
* 正确的键是「会话 + 该轮的用户输入」:同一轮的多次补全命中同一条,跨轮必然
|
|
2127
|
+
* 不同;连用户连说两遍「继续」也是两条 —— 因为上一轮闭合时**这条记录已经从
|
|
2128
|
+
* 表里删掉了**,第二轮必然新建。
|
|
2129
|
+
*
|
|
2130
|
+
* 表只在轮内存在,所以通常只有「正在跑的那几轮」几条记录;LRU 截断
|
|
2131
|
+
* ({@link STAGE_MAP_LIMIT})防的是「发出去了但轮末从未到来」的那些异常轮次
|
|
2132
|
+
* 无限堆积。
|
|
2133
|
+
*/
|
|
2134
|
+
turns = /* @__PURE__ */ new Map();
|
|
2135
|
+
/**
|
|
2136
|
+
* 已经闭合过的 `business.id`。重复闭合同一轮是**绝不**该发生的事:客户端
|
|
2137
|
+
* 每轮只 `finalize()` 一次,多发一条 `BUSINESS_FINISH` 会让服务端对同一轮
|
|
2138
|
+
* 记两次收口。
|
|
2139
|
+
*
|
|
2140
|
+
* 容量上限与轮次表同值({@link STAGE_MAP_LIMIT})。它只是幂等闸,不是账本:
|
|
2141
|
+
* 被淘汰之后重复闭合才有可能漏过,而那时那条记录本来也已不在表里了。
|
|
2142
|
+
*/
|
|
2143
|
+
endTurnClosed = /* @__PURE__ */ new Set();
|
|
2144
|
+
/**
|
|
2145
|
+
* 从上游报错里学到的 `max_tokens` 上限,按模型 key 缓存。
|
|
2146
|
+
*
|
|
2147
|
+
* 上游对越界值的回话是 `Range of max_tokens should be [1, N]`;学到 N 之后
|
|
2148
|
+
* 后续请求直接夹到 N 以内,不再撞同一堵墙(magpie 的 `LEARNED_CAPS` 同法)。
|
|
2149
|
+
*/
|
|
2150
|
+
maxTokensCaps = /* @__PURE__ */ new Map();
|
|
2151
|
+
/** `business.product`(见 {@link DEFAULT_BUSINESS_PRODUCT})。 */
|
|
2152
|
+
businessProduct;
|
|
2153
|
+
/** 显式配置的 `business.version`;缺席时跟随 {@link clientVersion}。 */
|
|
2154
|
+
businessVersionOverride;
|
|
2155
|
+
/** 设备身份来源模式(见 {@link QoderUpstreamOptions.deviceIdentity})。 */
|
|
2156
|
+
deviceIdentity;
|
|
2157
|
+
/** 人工身份覆盖值(只在 `manual` 模式生效)。 */
|
|
2158
|
+
identityOverride;
|
|
2159
|
+
/** 客户端版本解析器:头、bearer 载荷、`business.version` 三处同源。 */
|
|
2160
|
+
clientVersionResolver;
|
|
2161
|
+
/** prompt-cache 标记(默认 undefined = 不标记)。 */
|
|
2162
|
+
cacheControl;
|
|
2163
|
+
/**
|
|
2164
|
+
* 这次请求该声明的客户端版本。
|
|
2165
|
+
*
|
|
2166
|
+
* 三处必须同值:`cosy-version` 头、bearer 载荷的 `cosyVersion`、
|
|
2167
|
+
* `business.version`。取一次、用三处,避免它们各自漂移。
|
|
2168
|
+
*/
|
|
2169
|
+
get clientVersion() {
|
|
2170
|
+
return this.clientVersionResolver.current();
|
|
2171
|
+
}
|
|
2172
|
+
/** `business.version`:显式配置优先,否则与客户端版本同值。 */
|
|
2173
|
+
get businessVersion() {
|
|
2174
|
+
return this.businessVersionOverride ?? this.clientVersion;
|
|
2175
|
+
}
|
|
2176
|
+
/**
|
|
2177
|
+
* 某会话要发的设备身份头。
|
|
2178
|
+
*
|
|
2179
|
+
* 取值优先用会话里记下的那份 `identity`(`exchangeJobToken` 时解析出来的,
|
|
2180
|
+
* 含逐字段来源);没有就退回会话自己的三个字段 + 本机环境 —— 这条兜底是给
|
|
2181
|
+
* 手工构造 holder 的测试用的。
|
|
2182
|
+
*
|
|
2183
|
+
* 环境头(`machineos` / `machinehostname`)**每次现取**,不缓存进 identity:
|
|
2184
|
+
* 它们是「这台机器现在是什么」,不是身份的一部分。
|
|
2185
|
+
*/
|
|
2186
|
+
machineHeaders(holder) {
|
|
2187
|
+
const env = localMachineEnv();
|
|
2188
|
+
const identity = holder.identity;
|
|
2189
|
+
if (identity !== void 0) return identityHeaders(identity, env);
|
|
2190
|
+
return {
|
|
2191
|
+
"cosy-machineid": holder.session.machineId,
|
|
2192
|
+
"cosy-machinetoken": holder.session.machineToken,
|
|
2193
|
+
"cosy-machinetype": holder.session.machineType,
|
|
2194
|
+
"cosy-machineos": env.os,
|
|
2195
|
+
"cosy-machinehostname": env.hostname
|
|
2196
|
+
};
|
|
2197
|
+
}
|
|
2198
|
+
/**
|
|
2199
|
+
* 节点表缓存(按客户端 5 分钟 TTL)。
|
|
2200
|
+
*
|
|
2201
|
+
* 一个实例一份缓存:节点表是**按账号**下发的,跨账号复用会拿错表。
|
|
2202
|
+
*/
|
|
2203
|
+
endpoints = new QoderEndpointCache();
|
|
2204
|
+
/**
|
|
2205
|
+
* 上次成功聊天的 inference 节点(用于「上次优先」,见 `orderWithLastFirst`)。
|
|
2206
|
+
*
|
|
2207
|
+
* 记住它不只是提速:节点之间不共享 KV cache,每轮跳节点等于每轮重算整段
|
|
2208
|
+
* 历史。只有它失败时才换下一个。
|
|
2209
|
+
*/
|
|
2210
|
+
lastInferenceNode;
|
|
2211
|
+
/**
|
|
2212
|
+
* 当前轮次的 business 上下文,供 {@link finishTurn} 闭合时取用。
|
|
2213
|
+
*
|
|
2214
|
+
* 一次 `chatStream` 只覆盖一次补全,而一轮用户提示可能包含 N 次补全(工具
|
|
2215
|
+
* 循环),所以这里记的是**最近一次**补全所属的那一轮;`shim` 在这一轮的最后
|
|
2216
|
+
* 一次补全(`finish_reason === 'stop'`)之后才调 {@link finishTurn}。
|
|
2217
|
+
*/
|
|
2218
|
+
currentTurn;
|
|
2219
|
+
/**
|
|
2220
|
+
* 取(或新建)本轮用户输入的 `business` 记录,并按客户端 `changeBusinessState()`
|
|
2221
|
+
* 推进阶段。
|
|
2222
|
+
*
|
|
2223
|
+
* ## 键为什么是「会话 + 用户提示」
|
|
2224
|
+
*
|
|
2225
|
+
* 客户端里 `business.id` 就是**这条用户消息的 `requestSetId`**
|
|
2226
|
+
* (`Mh.create(sessionId, …, userMessage.requestSetId, …)` → `Fz` 的
|
|
2227
|
+
* `id: o || randomUUID()`)。所以粒度是**一条用户输入一条记录**,
|
|
2228
|
+
* 一条输出了 prompt 之后那一串工具循环里的 N 次补全共用同一个 id。
|
|
2229
|
+
*
|
|
2230
|
+
* 我们这边没有宿主的 `requestSetId`,可用且等价的锚点是「会话 + 最近一条用户
|
|
2231
|
+
* 提示」:一轮工具循环里最后一条 user 消息**不变**,下一轮用户输入一定会变。
|
|
2232
|
+
* 键里带上提示文本,就是为了让「同一个会话里问了两遍一样的话」也得到两条
|
|
2233
|
+
* 记录 —— 靠会话内序号做不到这一点(序号要等闭合才知道,而闭合只在轮末)。
|
|
2234
|
+
*
|
|
2235
|
+
* ## 阶段推进
|
|
2236
|
+
*
|
|
2237
|
+
* 规则照抄客户端 `Mh`:`init`/首次 → `start`,之后 → `processing`,再之后保持
|
|
2238
|
+
* `processing`(客户端的第三个分支只 warn、不再推进)。**终态不在这里推进** ——
|
|
2239
|
+
* 客户端由 `finalize()` 在轮次结束时一次写定,对应到我们这边是
|
|
2240
|
+
* {@link finishTurn}。
|
|
2241
|
+
*
|
|
2242
|
+
* 会话标识或缺席提示时无法归组 —— 每次都是一条新的 `start` 记录,至少不会
|
|
2243
|
+
* 声称一个错的阶段(宁可少聚合,不可错聚合)。
|
|
2244
|
+
*/
|
|
2245
|
+
sessionOf(sessionId, prompt) {
|
|
2246
|
+
if (sessionId === void 0 || sessionId === "") return {
|
|
2247
|
+
key: "",
|
|
2248
|
+
id: randomId(),
|
|
2249
|
+
beginAt: Date.now(),
|
|
2250
|
+
stage: "start"
|
|
2251
|
+
};
|
|
2252
|
+
const key = `${sessionId}\u0000${prompt}`;
|
|
2253
|
+
const existing = this.turns.get(key);
|
|
2254
|
+
if (existing === void 0) {
|
|
2255
|
+
const fresh = {
|
|
2256
|
+
id: randomId(),
|
|
2257
|
+
beginAt: Date.now(),
|
|
2258
|
+
stage: "start"
|
|
2259
|
+
};
|
|
2260
|
+
this.rememberTurn(key, fresh);
|
|
2261
|
+
return {
|
|
2262
|
+
key,
|
|
2263
|
+
...fresh
|
|
2264
|
+
};
|
|
2265
|
+
}
|
|
2266
|
+
const advanced = existing.stage === "init" || existing.stage === "start" ? {
|
|
2267
|
+
...existing,
|
|
2268
|
+
stage: "processing"
|
|
2269
|
+
} : existing;
|
|
2270
|
+
this.rememberTurn(key, advanced);
|
|
2271
|
+
return {
|
|
2272
|
+
key,
|
|
2273
|
+
id: advanced.id,
|
|
2274
|
+
beginAt: advanced.beginAt,
|
|
2275
|
+
stage: advanced.stage
|
|
2276
|
+
};
|
|
2277
|
+
}
|
|
2278
|
+
/**
|
|
2279
|
+
* 结束当前轮次:写终态与 `end_at`,并**把这条记录从表里删掉**。
|
|
2280
|
+
*
|
|
2281
|
+
* 删除(而不是留在表里加个「已闭合」标记)是「一条用户输入 = 一条消费记录」
|
|
2282
|
+
* 能成立的关键:留着的话,下一轮若用户问了同样的话,会命中同一个键、并进
|
|
2283
|
+
* 上一条已闭合的记录里 —— 那正是「整场会话固定 id」那种错法的变体,只是
|
|
2284
|
+
* 晚一轮才发作。删掉之后下一次必然新建,`id` 与 `begin_at` 都是新的。
|
|
2285
|
+
*
|
|
2286
|
+
* 返回 `undefined` = 这一轮已经闭合过(或被 LRU 淘汰),调用方据此跳过上报。
|
|
2287
|
+
* 这个判据落在 `business.id` 上而不是轮次表上:`finishTurn` 也允许调用方直接
|
|
2288
|
+
* 递一个轮次上下文过来(测试与外部调用就是这条路),那时表里根本没有记录,
|
|
2289
|
+
* 拿「表里有没有」当闸会把合法的闭合挡掉。
|
|
2290
|
+
*
|
|
2291
|
+
* 终态取值照客户端 `kVe()`:`abort`/`repeated_tool_call_denied` → `abort`,
|
|
2292
|
+
* `error`/`max_turns` → `error`,其余(含 `end_turn`)→ `complete`。
|
|
2293
|
+
*/
|
|
2294
|
+
closeTurn(sessionId, key, businessId, fallbackBeginAt, stage) {
|
|
2295
|
+
if (businessId === "") return void 0;
|
|
2296
|
+
if (this.endTurnClosed.has(businessId)) return void 0;
|
|
2297
|
+
this.endTurnClosed.add(businessId);
|
|
2298
|
+
while (this.endTurnClosed.size > STAGE_MAP_LIMIT) {
|
|
2299
|
+
const oldest = this.endTurnClosed.values().next();
|
|
2300
|
+
if (oldest.done === true) break;
|
|
2301
|
+
this.endTurnClosed.delete(oldest.value);
|
|
2302
|
+
}
|
|
2303
|
+
const entry = sessionId === void 0 || key === "" ? void 0 : this.turns.get(key);
|
|
2304
|
+
if (sessionId !== void 0 && key !== "") this.turns.delete(key);
|
|
2305
|
+
return {
|
|
2306
|
+
id: businessId,
|
|
2307
|
+
beginAt: entry?.beginAt ?? fallbackBeginAt,
|
|
2308
|
+
stage,
|
|
2309
|
+
endAt: Date.now()
|
|
2310
|
+
};
|
|
2311
|
+
}
|
|
2312
|
+
/** 写轮次记录并按 LRU 截断(Map 的插入序即访问序,重插一次即可上浮)。 */
|
|
2313
|
+
rememberTurn(key, entry) {
|
|
2314
|
+
this.turns.delete(key);
|
|
2315
|
+
this.turns.set(key, entry);
|
|
2316
|
+
while (this.turns.size > STAGE_MAP_LIMIT) {
|
|
2317
|
+
const oldest = this.turns.keys().next();
|
|
2318
|
+
if (oldest.done === true) break;
|
|
2319
|
+
this.turns.delete(oldest.value);
|
|
2320
|
+
}
|
|
2321
|
+
}
|
|
2322
|
+
/**
|
|
2323
|
+
* 决定本次请求的 `max_tokens`:调用方给的 → 学到的上限夹一下。
|
|
2324
|
+
*
|
|
2325
|
+
* 三层里的第三层(客户端的逐模型 override 表)在本机是空的,所以这里只有
|
|
2326
|
+
* 「调用方值(来自 `/model/list` 的 `max_output_tokens`)」与兜底常量两层。
|
|
2327
|
+
*/
|
|
2328
|
+
maxTokensFor(modelKey, requested) {
|
|
2329
|
+
const base = requested !== void 0 && Number.isFinite(requested) && requested > 0 ? Math.floor(requested) : DEFAULT_MAX_OUTPUT_TOKENS;
|
|
2330
|
+
const learned = this.maxTokensCaps.get(modelKey);
|
|
2331
|
+
return learned === void 0 ? base : Math.min(base, learned);
|
|
2332
|
+
}
|
|
2333
|
+
/**
|
|
2334
|
+
* 从上游报错文案里学 `max_tokens` 的实际上限。
|
|
2335
|
+
*
|
|
2336
|
+
* 只在确实认出了 `[1, N]` 形状时记 —— 认不出就不动,绝不猜一个更小的值
|
|
2337
|
+
* (猜小了会让回答被提前截断,而截断是静默的)。
|
|
2338
|
+
*/
|
|
2339
|
+
learnMaxTokens(modelKey, errorText) {
|
|
2340
|
+
const match = MAX_TOKENS_RANGE_RE.exec(errorText);
|
|
2341
|
+
if (match?.[1] === void 0) return;
|
|
2342
|
+
const cap = Number(match[1]);
|
|
2343
|
+
if (!Number.isSafeInteger(cap) || cap <= 0) return;
|
|
2344
|
+
if (this.maxTokensCaps.get(modelKey) === cap) return;
|
|
2345
|
+
this.maxTokensCaps.set(modelKey, cap);
|
|
2346
|
+
this.log(`上游申报 max_tokens 上限 ${cap}(模型 ${modelKey}),后续请求夹到该值以内`);
|
|
2347
|
+
}
|
|
2348
|
+
constructor(region, options = {}) {
|
|
2349
|
+
this.region = QODER_REGIONS[region];
|
|
2350
|
+
this.regionKey = region;
|
|
2351
|
+
this.logger = options.logger ?? (() => {});
|
|
2352
|
+
this.installSalt = options.installSalt;
|
|
2353
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch;
|
|
2354
|
+
this.businessProduct = options.businessProduct ?? DEFAULT_BUSINESS_PRODUCT;
|
|
2355
|
+
this.businessVersionOverride = options.businessVersion !== void 0 && options.businessVersion !== "" ? options.businessVersion : void 0;
|
|
2356
|
+
this.deviceIdentity = options.deviceIdentity ?? "real";
|
|
2357
|
+
this.identityOverride = options.identityOverride;
|
|
2358
|
+
this.clientVersionResolver = new ClientVersionResolver(options.clientVersion !== void 0 && options.clientVersion !== "" ? {
|
|
2359
|
+
override: options.clientVersion,
|
|
2360
|
+
...options.fetch === void 0 ? {} : { fetchImpl: options.fetch }
|
|
2361
|
+
} : options.fetch === void 0 ? {} : { fetchImpl: options.fetch });
|
|
2362
|
+
this.cacheControl = options.cacheControl;
|
|
2363
|
+
}
|
|
2364
|
+
log(message) {
|
|
2365
|
+
this.logger(`dsh-connect-qoder: ${message}`);
|
|
2366
|
+
}
|
|
2367
|
+
/** 某一凭证的会话是否已过期(或即将过期)。 */
|
|
2368
|
+
isSessionValid(credential, nowMs = Date.now()) {
|
|
2369
|
+
const holder = this.holders.get(credential);
|
|
2370
|
+
if (holder === void 0) return false;
|
|
2371
|
+
return holder.expireAtMs - nowMs > 3e5;
|
|
2372
|
+
}
|
|
2373
|
+
/** 最近使用的凭证,沿用直觉意义上「当前账号」的引用。 */
|
|
2374
|
+
currentCredential() {
|
|
2375
|
+
return this.holders.has(this.currentKey ?? "") ? this.currentKey : void 0;
|
|
2376
|
+
}
|
|
2377
|
+
/**
|
|
2378
|
+
* 用 PAT(`pt-...` 或任意凭证)或 refresh token(`drt-...`)交换 jobToken。
|
|
2379
|
+
*
|
|
2380
|
+
* 设备身份不再是「整份从凭据派生」:见 {@link resolveDeviceIdentity}。默认
|
|
2381
|
+
* 模式下 `machineId` 读本机 `machine_id` 文件、`machineToken/Type/Code` 读
|
|
2382
|
+
* UMID 组件,任何一路取不到才退回派生值并记录原因。
|
|
2383
|
+
*/
|
|
2384
|
+
async exchangeJobToken(credential) {
|
|
2385
|
+
const fingerprint = deriveFingerprint("", credential, this.installSalt);
|
|
2386
|
+
const device = await resolveDeviceIdentity({
|
|
2387
|
+
region: this.regionKey,
|
|
2388
|
+
credential,
|
|
2389
|
+
mode: this.deviceIdentity,
|
|
2390
|
+
...this.identityOverride === void 0 ? {} : { override: this.identityOverride },
|
|
2391
|
+
...this.installSalt === void 0 ? {} : { installSalt: this.installSalt },
|
|
2392
|
+
log: (message) => this.log(message)
|
|
2393
|
+
});
|
|
2394
|
+
const body = jobTokenBody(credential);
|
|
2395
|
+
const date = currentRfc1123Date();
|
|
2396
|
+
const sig = signLegacy(date);
|
|
2397
|
+
const headers = {
|
|
2398
|
+
...identityHeaders(device),
|
|
2399
|
+
"login-version": "v2",
|
|
2400
|
+
appcode: "cosy",
|
|
2401
|
+
accept: "application/json",
|
|
2402
|
+
"accept-encoding": "identity",
|
|
2403
|
+
"cosy-version": this.clientVersion,
|
|
2404
|
+
"cosy-clienttype": COSY_CLIENT_TYPE,
|
|
2405
|
+
date,
|
|
2406
|
+
signature: sig,
|
|
2407
|
+
"content-type": "application/json",
|
|
2408
|
+
"user-agent": DEFAULT_HEADERS["user-agent"] ?? "Bun/1.4.4"
|
|
2409
|
+
};
|
|
2410
|
+
const url = `${this.region.gateway}${this.region.jobTokenPath}`;
|
|
2411
|
+
const resp = await this.fetchImpl(url, {
|
|
2412
|
+
method: "POST",
|
|
2413
|
+
headers,
|
|
2414
|
+
body
|
|
2415
|
+
});
|
|
2416
|
+
const text = await resp.text();
|
|
2417
|
+
if (resp.status !== 200) throw new QoderUpstreamError(classifyFailure(resp.status, text), `jobToken 交换失败: HTTP ${resp.status} ${truncate(text, 200)}`, resp.status, deepestBusinessCode(text));
|
|
2418
|
+
let data;
|
|
2419
|
+
try {
|
|
2420
|
+
data = JSON.parse(text);
|
|
2421
|
+
} catch {
|
|
2422
|
+
throw new QoderUpstreamError("unknown", `jobToken 响应不是 JSON: ${truncate(text, 200)}`, resp.status);
|
|
2423
|
+
}
|
|
2424
|
+
const jobToken = {
|
|
2425
|
+
id: String(data.id ?? ""),
|
|
2426
|
+
name: String(data.name ?? ""),
|
|
2427
|
+
expireTime: Number(data.expireTime ?? 0),
|
|
2428
|
+
securityOauthToken: String(data.securityOauthToken ?? ""),
|
|
2429
|
+
refreshToken: String(data.refreshToken ?? ""),
|
|
2430
|
+
userType: String(data.userType ?? "personal_standard")
|
|
2431
|
+
};
|
|
2432
|
+
if (!jobToken.id && !jobToken.securityOauthToken) throw new QoderUpstreamError("auth", `jobToken 交换响应缺少身份字段: ${truncate(text, 200)}`, resp.status);
|
|
2433
|
+
const holder = {
|
|
2434
|
+
session: newCosySession({
|
|
2435
|
+
name: jobToken.name,
|
|
2436
|
+
aid: jobToken.id,
|
|
2437
|
+
uid: jobToken.id,
|
|
2438
|
+
yx_uid: "",
|
|
2439
|
+
organization_id: "",
|
|
2440
|
+
organization_name: "",
|
|
2441
|
+
user_type: jobToken.userType,
|
|
2442
|
+
security_oauth_token: jobToken.securityOauthToken,
|
|
2443
|
+
refresh_token: jobToken.refreshToken
|
|
2444
|
+
}, device.machineId, device.machineToken, device.machineType),
|
|
2445
|
+
fingerprint,
|
|
2446
|
+
identity: device,
|
|
2447
|
+
jobToken,
|
|
2448
|
+
expireAtMs: jobToken.expireTime > 0 ? jobToken.expireTime : 0
|
|
2449
|
+
};
|
|
2450
|
+
await this.refreshSashToken(credential, holder);
|
|
2451
|
+
this.holders.set(credential, holder);
|
|
2452
|
+
this.currentKey = credential;
|
|
2453
|
+
this.log(`jobToken 已交换: ${jobToken.name} (${jobToken.id})`);
|
|
2454
|
+
return jobToken;
|
|
2455
|
+
}
|
|
2456
|
+
/**
|
|
2457
|
+
* 换一枚 sash 面专用的令牌(`POST /api/v1/jobToken/exchange`)。
|
|
2458
|
+
*
|
|
2459
|
+
* **不抛**:这一族换不到时 sash 那一支会回落到旧令牌(国内版本来就够用),
|
|
2460
|
+
* 而整条交换失败只该让「积分读不到」,不该让 chat / 对话跟着挂 —— 那是完全
|
|
2461
|
+
* 不同的两条链路。
|
|
2462
|
+
*
|
|
2463
|
+
* body 键是 `personal_token`:实测 `personal_access_token`(eghrhegpe 那个 fork
|
|
2464
|
+
* 用的拼写)在当前上游回 **400 BadRequest**,两个区域都是。
|
|
2465
|
+
*/
|
|
2466
|
+
async refreshSashToken(credential, holder) {
|
|
2467
|
+
const url = `${this.region.openapi}${SASH_TOKEN_PATH}`;
|
|
2468
|
+
try {
|
|
2469
|
+
const resp = await this.fetchImpl(url, {
|
|
2470
|
+
method: "POST",
|
|
2471
|
+
headers: {
|
|
2472
|
+
"content-type": "application/json",
|
|
2473
|
+
accept: "application/json"
|
|
2474
|
+
},
|
|
2475
|
+
body: JSON.stringify({ personal_token: credential })
|
|
2476
|
+
});
|
|
2477
|
+
const text = await resp.text();
|
|
2478
|
+
if (resp.status !== 200) {
|
|
2479
|
+
this.log(`sash 令牌交换失败(HTTP ${resp.status}),sash 面将回落到旧令牌: ${truncate(text, 120)}`);
|
|
2480
|
+
return;
|
|
2481
|
+
}
|
|
2482
|
+
const data = parseJson(text);
|
|
2483
|
+
const raw = data === void 0 ? {} : data;
|
|
2484
|
+
const token = typeof raw["token"] === "string" && raw["token"] !== "" ? raw["token"] : typeof raw["job_token"] === "string" && raw["job_token"] !== "" ? raw["job_token"] : typeof raw["jobToken"] === "string" && raw["jobToken"] !== "" ? raw["jobToken"] : "";
|
|
2485
|
+
if (token === "") {
|
|
2486
|
+
this.log(`sash 令牌交换响应里没有 token 字段: ${truncate(text, 120)}`);
|
|
2487
|
+
return;
|
|
2488
|
+
}
|
|
2489
|
+
holder.sashToken = token;
|
|
2490
|
+
const expiry = typeof raw["expires_at"] === "string" ? Date.parse(raw["expires_at"]) : NaN;
|
|
2491
|
+
holder.sashExpireAtMs = Number.isFinite(expiry) ? expiry : 0;
|
|
2492
|
+
this.log(`sash 令牌已交换(有效期至 ${holder.sashExpireAtMs > 0 ? new Date(holder.sashExpireAtMs).toISOString() : "未知"})`);
|
|
2493
|
+
} catch (error) {
|
|
2494
|
+
this.log(`sash 令牌交换异常,sash 面将回落到旧令牌: ${String(error?.message ?? error).slice(0, 120)}`);
|
|
2495
|
+
}
|
|
2496
|
+
}
|
|
2497
|
+
/**
|
|
2498
|
+
* 取该会话用于 **sash 面** 的 Authorization 值。
|
|
2499
|
+
*
|
|
2500
|
+
* 新令牌优先(国际版必需);没有就回落到旧的 `securityOauthToken`(国内版
|
|
2501
|
+
* 两个面都认它,而且它是 chat 在用的那一个 —— 回落不会破坏任何东西)。
|
|
2502
|
+
*
|
|
2503
|
+
* 返回 `''` 表示两族都没有:那一支必须报「读不到」,绝不能带上一个空 bearer
|
|
2504
|
+
* 去换一个 401 回来(那样分不清是没令牌还是令牌被拒)。
|
|
2505
|
+
*/
|
|
2506
|
+
sashBearerOf(holder) {
|
|
2507
|
+
if (typeof holder.sashToken === "string" && holder.sashToken !== "") return holder.sashToken;
|
|
2508
|
+
return holder.jobToken.securityOauthToken;
|
|
2509
|
+
}
|
|
2510
|
+
/**
|
|
2511
|
+
* 确保存在未过期会话。credential 提供 PAT 或 refreshToken(`drt-` 前缀)。
|
|
2512
|
+
* 已有有效会话时直接复用(不重复交换)。
|
|
2513
|
+
*/
|
|
2514
|
+
async ensureSession(credential) {
|
|
2515
|
+
if (this.isSessionValid(credential)) return this.holders.get(credential);
|
|
2516
|
+
await this.exchangeJobToken(credential);
|
|
2517
|
+
return this.holders.get(credential);
|
|
2518
|
+
}
|
|
2519
|
+
/**
|
|
2520
|
+
* 取一份可用的节点表,失败时静默返回 undefined。
|
|
2521
|
+
*
|
|
2522
|
+
* **绝不因为发现失败就挡住聊天**:客户端对选举只给 1 秒(`NCn=2e3` / `1e3`),
|
|
2523
|
+
* 超时就退回环境默认端点继续跑。这里同法 —— 发现是优化,不是前置条件。
|
|
2524
|
+
*
|
|
2525
|
+
* 请求本身走 center 主机(即本区域的 `openapi` 主机:客户端的 `ste()` 返回
|
|
2526
|
+
* `Rp("center")`,`Gde` 里 center 与 openapi 指向同一台 `$9`);鉴权与
|
|
2527
|
+
* `fetchModels` 一样用 bearer。失败原因只记 debug 级别 —— 它是常态,不是故障。
|
|
2528
|
+
*/
|
|
2529
|
+
async discoverNodes(holder, signal) {
|
|
2530
|
+
if (this.endpoints.isFresh()) return;
|
|
2531
|
+
const url = `${this.region.openapi}${REGION_ENDPOINTS_PATH}`;
|
|
2532
|
+
const controller = new AbortController();
|
|
2533
|
+
const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error("endpoint election timed out")), ENDPOINTS_TIMEOUT_MS);
|
|
2534
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
2535
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
2536
|
+
try {
|
|
2537
|
+
const parsed = parseRegionEndpoints(await this.bearerGet(holder, url, controller.signal));
|
|
2538
|
+
if (parsed === void 0) {
|
|
2539
|
+
this.log(`节点表为空或形状不识别(${REGION_ENDPOINTS_PATH}),继续用默认网关`);
|
|
2540
|
+
return;
|
|
2541
|
+
}
|
|
2542
|
+
this.endpoints.write(parsed);
|
|
2543
|
+
} catch (error) {
|
|
2544
|
+
this.log(`节点发现失败,继续用默认网关:${error instanceof Error ? error.message : String(error)}`);
|
|
2545
|
+
} finally {
|
|
2546
|
+
clearTimeout(timer);
|
|
2547
|
+
signal?.removeEventListener("abort", onAbort);
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
/**
|
|
2551
|
+
* 本次聊天该用的 base URL(**不带尾斜杠**)。
|
|
2552
|
+
*
|
|
2553
|
+
* 顺序:上次成功的 inference 节点 → 节点表里的第一个 → 区域默认网关。前两个都
|
|
2554
|
+
* 来自节点发现,最后一个保证**永远有一个能用的**。
|
|
2555
|
+
*
|
|
2556
|
+
* 统一去掉尾斜杠:节点表里的 URL 被规范成带尾斜杠(`normalizeNodeUrl`),而
|
|
2557
|
+
* `region.gateway` 不带。不归一的话拼 `chatPath`(以 `/` 开头)就会出现
|
|
2558
|
+
* `//api/...` 双斜杠 —— 它能不能被容忍取决于网关,不该赌。
|
|
2559
|
+
*/
|
|
2560
|
+
chatBaseUrl() {
|
|
2561
|
+
return (orderWithLastFirst(this.endpoints.read()?.inference ?? [], this.lastInferenceNode)[0] ?? this.region.gateway).replace(/\/+$/, "");
|
|
2562
|
+
}
|
|
2563
|
+
/**
|
|
2564
|
+
* 拉取模型目录。响应形状(服务端 snake_case):
|
|
2565
|
+
* `{"chat":[{key, display_name, enable, is_vl, is_default, ...}], ...}`
|
|
2566
|
+
*/
|
|
2567
|
+
async fetchModels(credential, signal) {
|
|
2568
|
+
const holder = await this.ensureSession(credential);
|
|
2569
|
+
await this.discoverNodes(holder, signal);
|
|
2570
|
+
const url = `${(this.endpoints.read()?.openapi[0] ?? `${this.region.gateway}/`).replace(/\/$/, "")}${this.region.modelsPath}`;
|
|
2571
|
+
const data = await this.bearerGet(holder, url, signal);
|
|
2572
|
+
return (Array.isArray(data.chat) ? data.chat : []).map((entry) => {
|
|
2573
|
+
if (!entry || typeof entry !== "object") return void 0;
|
|
2574
|
+
const raw = entry;
|
|
2575
|
+
const key = typeof raw.key === "string" ? raw.key : "";
|
|
2576
|
+
const displayName = typeof raw.display_name === "string" ? raw.display_name : "";
|
|
2577
|
+
if (!key || !displayName) return void 0;
|
|
2578
|
+
return {
|
|
2579
|
+
key,
|
|
2580
|
+
display_name: displayName,
|
|
2581
|
+
enable: raw.enable !== false,
|
|
2582
|
+
is_default: raw.is_default === true,
|
|
2583
|
+
is_vl: raw.is_vl === true,
|
|
2584
|
+
is_reasoning: raw.is_reasoning === true,
|
|
2585
|
+
is_free: raw.is_free === true,
|
|
2586
|
+
price_factor: typeof raw.price_factor === "number" ? raw.price_factor : void 0,
|
|
2587
|
+
max_input_tokens: typeof raw.max_input_tokens === "number" ? raw.max_input_tokens : void 0,
|
|
2588
|
+
max_output_tokens: typeof raw.max_output_tokens === "number" ? raw.max_output_tokens : void 0,
|
|
2589
|
+
thinking_config: typeof raw.thinking_config === "object" ? raw.thinking_config : void 0,
|
|
2590
|
+
context_config: typeof raw.context_config === "object" ? raw.context_config : void 0,
|
|
2591
|
+
raw
|
|
2592
|
+
};
|
|
2593
|
+
}).filter((m) => m !== void 0).filter((model) => !isRouterModelId(model.key));
|
|
2594
|
+
}
|
|
2595
|
+
/**
|
|
2596
|
+
* 聊天 SSE 流。onDelta 逐行回调;返回 null 表示正常结束。
|
|
2597
|
+
* 令牌:`credential` 只在会话续期时使用。
|
|
2598
|
+
*/
|
|
2599
|
+
async chatStream(credential, modelKey, messages, options) {
|
|
2600
|
+
const holder = await this.ensureSession(credential);
|
|
2601
|
+
const template = deepClone(createChatBodyTemplate());
|
|
2602
|
+
applyModelKey(template, modelKey, options.userType ?? holder.jobToken.userType, options.isVl ?? false);
|
|
2603
|
+
template.session_type = sessionTypeOf(this.regionKey);
|
|
2604
|
+
if (options.isReasoning) {
|
|
2605
|
+
template.model_config.is_reasoning = true;
|
|
2606
|
+
template.chat_context.extra.modelConfig.is_reasoning = true;
|
|
2607
|
+
}
|
|
2608
|
+
const maxTokens = this.maxTokensFor(modelKey, options.maxOutputTokens);
|
|
2609
|
+
template.parameters = {
|
|
2610
|
+
...template.parameters ?? {},
|
|
2611
|
+
max_tokens: maxTokens
|
|
2612
|
+
};
|
|
2613
|
+
if (options.reasoningEffort !== void 0 && options.reasoningEffort !== "") {
|
|
2614
|
+
template.reasoningEffort = options.reasoningEffort;
|
|
2615
|
+
template.parameters = {
|
|
2616
|
+
...template.parameters,
|
|
2617
|
+
reasoning_effort: options.reasoningEffort
|
|
2618
|
+
};
|
|
2619
|
+
}
|
|
2620
|
+
const prompt = extractLatestUserPrompt(messages);
|
|
2621
|
+
template.messages = applyCacheControl(buildQoderMessages(messages, prompt, Array.isArray(options.tools) && options.tools.length > 0), this.cacheControl);
|
|
2622
|
+
if (options.tools !== void 0) template.tools = options.tools;
|
|
2623
|
+
template.request_id = randomId();
|
|
2624
|
+
template.chat_record_id = template.request_id;
|
|
2625
|
+
template.request_set_id = randomId();
|
|
2626
|
+
template.session_id = options.sessionId !== void 0 && options.sessionId !== "" ? options.sessionId : randomId();
|
|
2627
|
+
const turn = this.sessionOf(template.session_id, prompt);
|
|
2628
|
+
applyBusinessIdentity(template, {
|
|
2629
|
+
product: this.businessProduct,
|
|
2630
|
+
version: this.businessVersion,
|
|
2631
|
+
stage: turn.stage,
|
|
2632
|
+
modelKey
|
|
2633
|
+
});
|
|
2634
|
+
template.business.id = turn.id;
|
|
2635
|
+
template.business.begin_at = turn.beginAt;
|
|
2636
|
+
template.business.name = prompt.slice(0, 30) || "hi";
|
|
2637
|
+
this.currentTurn = {
|
|
2638
|
+
sessionId: options.sessionId,
|
|
2639
|
+
key: turn.key,
|
|
2640
|
+
businessId: turn.id,
|
|
2641
|
+
beginAt: turn.beginAt,
|
|
2642
|
+
name: template.business.name,
|
|
2643
|
+
modelKey,
|
|
2644
|
+
product: this.businessProduct,
|
|
2645
|
+
version: this.businessVersion
|
|
2646
|
+
};
|
|
2647
|
+
const body = JSON.stringify(template);
|
|
2648
|
+
await this.discoverNodes(holder, options.signal);
|
|
2649
|
+
const chatBase = this.chatBaseUrl();
|
|
2650
|
+
/**
|
|
2651
|
+
* 按某个 base 发出一次聊天请求。
|
|
2652
|
+
*
|
|
2653
|
+
* `pathSig` 与 `cosy-date` 都**依赖最终 URL**(签名覆盖路径),所以每换一个
|
|
2654
|
+
* base 就必须重新签一次 —— 不能复用上一份 header 换个 host 发出去,那样网关
|
|
2655
|
+
* 会判签名不匹配。这也正是把它写成闭包而不是循环的原因。
|
|
2656
|
+
*/
|
|
2657
|
+
const send = async (base) => {
|
|
2658
|
+
const url = `${base}${this.region.chatPath}`;
|
|
2659
|
+
const pathSig = pathSigFrom(url);
|
|
2660
|
+
const encoded = cosyEncode(new TextEncoder().encode(body));
|
|
2661
|
+
const date = String(Math.floor(Date.now() / 1e3));
|
|
2662
|
+
const payloadB64 = buildPayloadB64(holder.session.info, this.clientVersion);
|
|
2663
|
+
const bearer = composeBearer(payloadB64, signRequest(payloadB64, holder.session.cosyKey, date, encoded, pathSig));
|
|
2664
|
+
const headers = {
|
|
2665
|
+
...DEFAULT_HEADERS,
|
|
2666
|
+
"cosy-machinetype": holder.session.machineType,
|
|
2667
|
+
"cosy-date": date,
|
|
2668
|
+
"cosy-user": holder.session.identity.uid,
|
|
2669
|
+
"cosy-key": holder.session.cosyKey,
|
|
2670
|
+
"cache-control": "no-cache",
|
|
2671
|
+
accept: "text/event-stream",
|
|
2672
|
+
authorization: bearer,
|
|
2673
|
+
"cosy-version": this.clientVersion,
|
|
2674
|
+
"x-model-key": modelKey,
|
|
2675
|
+
"x-model-source": "system",
|
|
2676
|
+
...this.machineHeaders(holder)
|
|
2677
|
+
};
|
|
2678
|
+
return this.fetchImpl(url, {
|
|
2679
|
+
method: "POST",
|
|
2680
|
+
headers,
|
|
2681
|
+
body: encoded,
|
|
2682
|
+
...options.signal === void 0 ? {} : { signal: options.signal }
|
|
2683
|
+
});
|
|
2684
|
+
};
|
|
2685
|
+
let resp;
|
|
2686
|
+
/** 实际发出这次请求的 base(用于记录「这个节点可用」)。 */
|
|
2687
|
+
let usedBase = chatBase;
|
|
2688
|
+
try {
|
|
2689
|
+
resp = await send(chatBase);
|
|
2690
|
+
} catch (error) {
|
|
2691
|
+
const fallback = this.region.gateway;
|
|
2692
|
+
if (chatBase === fallback || isAbortError(error)) throw error;
|
|
2693
|
+
this.log(`节点 ${chatBase} 不可达(${error instanceof Error ? error.message : String(error)}),改用默认网关`);
|
|
2694
|
+
this.lastInferenceNode = void 0;
|
|
2695
|
+
this.endpoints.clear();
|
|
2696
|
+
resp = await send(fallback);
|
|
2697
|
+
usedBase = fallback;
|
|
2698
|
+
}
|
|
2699
|
+
if (resp.status !== 200) {
|
|
2700
|
+
const errText = await resp.text();
|
|
2701
|
+
this.learnMaxTokens(modelKey, errText);
|
|
2702
|
+
throw new QoderUpstreamError(classifyFailure(resp.status, errText), `聊天请求失败: HTTP ${resp.status} ${truncate(errText, 300)}`, resp.status, deepestBusinessCode(errText), retryAfterMsOf(errText) ?? retryAfterMsOfHeader(resp.headers.get("retry-after")), queueOf(errText));
|
|
2703
|
+
}
|
|
2704
|
+
if (!resp.body) throw new QoderUpstreamError("transient", "聊天响应没有 body");
|
|
2705
|
+
if (this.endpoints.read() !== void 0) this.lastInferenceNode = usedBase;
|
|
2706
|
+
const reader = resp.body.getReader();
|
|
2707
|
+
const decoder = new TextDecoder();
|
|
2708
|
+
let buffer = "";
|
|
2709
|
+
try {
|
|
2710
|
+
for (;;) {
|
|
2711
|
+
const { done, value } = await reader.read();
|
|
2712
|
+
if (done) break;
|
|
2713
|
+
buffer += decoder.decode(value, { stream: true });
|
|
2714
|
+
const lines = buffer.split("\n");
|
|
2715
|
+
buffer = lines.pop() ?? "";
|
|
2716
|
+
for (const line of lines) {
|
|
2717
|
+
const trimmed = line.trim();
|
|
2718
|
+
if (trimmed === "" || !trimmed.startsWith("data:")) continue;
|
|
2719
|
+
const payload = trimmed.slice(5).trim();
|
|
2720
|
+
if (payload === "[DONE]") continue;
|
|
2721
|
+
const delta = parseStreamDelta(payload);
|
|
2722
|
+
if (delta !== void 0) options.onDelta(delta);
|
|
2723
|
+
}
|
|
2724
|
+
}
|
|
2725
|
+
} finally {
|
|
2726
|
+
reader.releaseLock();
|
|
2727
|
+
}
|
|
2728
|
+
}
|
|
2729
|
+
/**
|
|
2730
|
+
* 查询用量(只读)。`GET {openapi}/sash/api/v2/me/usage`。
|
|
2731
|
+
*
|
|
2732
|
+
* **认证用的是 jobToken 里的 `securityOauthToken`(`jt-…`),不是 PAT,
|
|
2733
|
+
* 也不是 COSY 签名 bearer。** 三者实测(2026-10,CN):
|
|
2734
|
+
*
|
|
2735
|
+
* | 凭据 | 结果 |
|
|
2736
|
+
* | --- | --- |
|
|
2737
|
+
* | 裸 PAT `pt-…` | 401 `TOKEN_EXPIRE / token is not active` |
|
|
2738
|
+
* | COSY 签名 bearer(chat/models 用的那套) | 401 `TOKEN_INVALID / invalid token` |
|
|
2739
|
+
* | `jt-…`(jobToken 交换产出) | **200,返回完整 qoderUsage** |
|
|
2740
|
+
*
|
|
2741
|
+
* 前两种之所以失败,是因为 `sash` 是**浏览器会话面**的接口:它既不收 PAT,
|
|
2742
|
+
* 也不认 cosy 协议头(缺 Authorization 时它回
|
|
2743
|
+
* `UNAUTHORIZED / missing cookie header`,可见它本来是给 cookie 会话用的)。
|
|
2744
|
+
* 这解释了「令牌明明是好的、聊天也正常,积分却永远拿不到」——以前用错凭据。
|
|
2745
|
+
*/
|
|
2746
|
+
async fetchUsage(credential, signal) {
|
|
2747
|
+
const url = `${this.region.openapi}/sash/api/v2/me/usage`;
|
|
2748
|
+
try {
|
|
2749
|
+
const holder = await this.ensureSession(credential);
|
|
2750
|
+
return parseUsage(await this.jobTokenGet(holder, url, signal));
|
|
2751
|
+
} catch (error) {
|
|
2752
|
+
if (error instanceof QoderUpstreamError && (error.status === 401 || error.status === 403)) {
|
|
2753
|
+
const direct = await this.fetchUsageDirect(url, credential, signal);
|
|
2754
|
+
if (direct !== void 0) return direct;
|
|
2755
|
+
throw error;
|
|
2756
|
+
}
|
|
2757
|
+
return;
|
|
2758
|
+
}
|
|
2759
|
+
}
|
|
2760
|
+
/**
|
|
2761
|
+
* `sash` 系列接口的取数:带 `Authorization: Bearer <jobToken.securityOauthToken>`。
|
|
2762
|
+
*
|
|
2763
|
+
* 与 {@link bearerGet} 的区别只有一个——**认证凭据不同**:`sash` 要的是
|
|
2764
|
+
* jobToken 交换产出的 `jt-…`,不是 COSY 签名 bearer(实测后者回
|
|
2765
|
+
* `TOKEN_INVALID / invalid token`),也不是裸 PAT(回 `TOKEN_EXPIRE`)。
|
|
2766
|
+
* 也正因为如此,这里**不**带那套 cosy-* 协议头:它们属于 cosy 协议面。
|
|
2767
|
+
* 但**设备风控三件套属于 sash 面**,按 `requiresDeviceRisk` 附加 —— 见下。
|
|
2768
|
+
*/
|
|
2769
|
+
async jobTokenGet(holder, url, signal) {
|
|
2770
|
+
const oauthToken = this.sashBearerOf(holder);
|
|
2771
|
+
if (oauthToken === "") throw new QoderUpstreamError("auth", "两次令牌交换都没有拿到可用令牌,无法查询用量", 401);
|
|
2772
|
+
const resp = await this.fetchImpl(url, {
|
|
2773
|
+
headers: {
|
|
2774
|
+
accept: "application/json",
|
|
2775
|
+
authorization: `Bearer ${oauthToken}`,
|
|
2776
|
+
...await this.deviceRiskHeaders()
|
|
2777
|
+
},
|
|
2778
|
+
...signal === void 0 ? {} : { signal }
|
|
2779
|
+
});
|
|
2780
|
+
const text = await resp.text();
|
|
2781
|
+
if (resp.status !== 200) throw new QoderUpstreamError(classifyFailure(resp.status, text), `请求失败: HTTP ${resp.status} ${truncate(text, 200)}`, resp.status, deepestBusinessCode(text));
|
|
2782
|
+
try {
|
|
2783
|
+
return JSON.parse(text);
|
|
2784
|
+
} catch {
|
|
2785
|
+
throw new QoderUpstreamError("unknown", `响应不是 JSON: ${truncate(text, 200)}`, resp.status);
|
|
2786
|
+
}
|
|
2787
|
+
}
|
|
2788
|
+
/**
|
|
2789
|
+
* 闭合**最近一次** `chatStream` 所属的轮次。供 `shim` 在轮次真正结束时调用。
|
|
2790
|
+
*
|
|
2791
|
+
* 与 {@link finishTurn} 的分工:那个是「给我一个轮次上下文,我来闭合」,这个
|
|
2792
|
+
* 是「把刚才那次请求所属的轮次闭合掉」,省得把 `QoderTurnContext` 泄漏到
|
|
2793
|
+
* 调用方去。
|
|
2794
|
+
*
|
|
2795
|
+
* 并发的两个会话会互相覆盖 `currentTurn` —— 但 `closeTurn` 按轮次键去重,且
|
|
2796
|
+
* 每个键只闭合一次,所以最坏情况是**漏闭合**(该轮靠 TTL 收口),不会把
|
|
2797
|
+
* A 会话的 id 配到 B 会话的终态上:`turn.sessionId` 与 `turn.key` 是同一次
|
|
2798
|
+
* 请求里一起记下的,不存在错配的可能。
|
|
2799
|
+
*/
|
|
2800
|
+
async finishCurrentTurn(credential, reason = "end_turn") {
|
|
2801
|
+
const turn = this.currentTurn;
|
|
2802
|
+
if (turn === void 0) return;
|
|
2803
|
+
await this.finishTurn(credential, turn, reason);
|
|
2804
|
+
}
|
|
2805
|
+
/**
|
|
2806
|
+
* 闭合当前轮次:把终态与 `end_at` 写进请求体,`POST business/finish`。
|
|
2807
|
+
*
|
|
2808
|
+
* ## 为什么必须有这一步
|
|
2809
|
+
*
|
|
2810
|
+
* 官方客户端在一轮用户提示结束时**必发一次**闭合(实测:一轮 2 次补全仍是
|
|
2811
|
+
* 1 次闭合)。不发它,服务端只能等 TTL 释放租约 —— 那一轮在记账上永远是
|
|
2812
|
+
* 「进行中」,控制台也就不产生逐条消费行。这是本插件长期缺失的一环。
|
|
2813
|
+
*
|
|
2814
|
+
* ## 三道闸(照抄客户端 `Qd.finish()`)
|
|
2815
|
+
*
|
|
2816
|
+
* 1. 没有 `business.id` → 不发(客户端 `if (!businessInfo.id) return`);
|
|
2817
|
+
* 2. 子 agent 的轮次 → 不发(客户端 `if (this._isSubagent) return`;我们这里
|
|
2818
|
+
* 没有子 agent 概念,由调用方保证只对主轮次调用);
|
|
2819
|
+
* 3. 同一轮已被闭合过 → 不发(客户端每轮 `finalize` 一次)。
|
|
2820
|
+
*
|
|
2821
|
+
* ## 为什么少了 `sub_task` / `orphan` / `feature_switches`
|
|
2822
|
+
*
|
|
2823
|
+
* 客户端 `Qd.finish()` 的模板里有这三个键,但**实测抓包里它们不出现**。
|
|
2824
|
+
* 不是我们漏了 —— 它们在客户端那边本来就是 `undefined`:
|
|
2825
|
+
*
|
|
2826
|
+
* - `sub_task`:只有子 agent / `title_generation` 这类任务才由 `$o()` 填值,
|
|
2827
|
+
* 主对话永远是 `undefined`;
|
|
2828
|
+
* - `orphan`:只在 `createForSubagent` 找不到父 business 时置 `true`,
|
|
2829
|
+
* 主轮次不带;
|
|
2830
|
+
* - `feature_switches`:来自 `envInfo` 的账号级开关,我们这条 PAT 链路拿不到,
|
|
2831
|
+
* 也不该编。
|
|
2832
|
+
*
|
|
2833
|
+
* `JSON.stringify` 会把 `undefined` 值整个省掉,所以官方 CLI 的明文里根本没
|
|
2834
|
+
* 这三项。解密 `captures/20261121-050020` 的 `0039-req.bin` 可以逐字核对:
|
|
2835
|
+
* 它的 `business` 只有九个键(product / version / type / id / model_key /
|
|
2836
|
+
* begin_at / end_at / stage / name),与本函数发出的完全一致。
|
|
2837
|
+
*
|
|
2838
|
+
* 所以这里**刻意不写**这三个键:手写一个 `feature_switches: {}` 或
|
|
2839
|
+
* `orphan: false` 反而会造出一项官方客户端不发的内容,那才是偏差。
|
|
2840
|
+
*
|
|
2841
|
+
* ## **不抛**
|
|
2842
|
+
*
|
|
2843
|
+
* 闭合失败只影响「记账何时收口」,不该让已经把答案交给用户的请求变成失败。
|
|
2844
|
+
* 失败按 warn 记一条日志 —— 它必须是**可见的**,否则「消费行还是不出现」
|
|
2845
|
+
* 会退化成又一个查不出来的问题。
|
|
2846
|
+
*/
|
|
2847
|
+
async finishTurn(credential, turn, reason = "end_turn") {
|
|
2848
|
+
if (turn.businessId === "" || turn.key === "") return;
|
|
2849
|
+
const stage = endStageOf(reason);
|
|
2850
|
+
const closed = this.closeTurn(turn.sessionId, turn.key, turn.businessId, turn.beginAt, stage);
|
|
2851
|
+
if (closed === void 0) return;
|
|
2852
|
+
let holder;
|
|
2853
|
+
try {
|
|
2854
|
+
holder = await this.ensureSession(credential);
|
|
2855
|
+
} catch (error) {
|
|
2856
|
+
this.log(`轮次闭合跳过(会话不可用):${String(error?.message ?? error)}`);
|
|
2857
|
+
return;
|
|
2858
|
+
}
|
|
2859
|
+
const body = JSON.stringify({
|
|
2860
|
+
payload: JSON.stringify({
|
|
2861
|
+
event_time: Date.now(),
|
|
2862
|
+
event_type: "BUSINESS_FINISH",
|
|
2863
|
+
aid: "",
|
|
2864
|
+
rid: randomId(),
|
|
2865
|
+
oid: "",
|
|
2866
|
+
yid: "",
|
|
2867
|
+
uid: "",
|
|
2868
|
+
event_data: {
|
|
2869
|
+
session_id: turn.sessionId,
|
|
2870
|
+
business: {
|
|
2871
|
+
product: turn.product,
|
|
2872
|
+
version: turn.version,
|
|
2873
|
+
type: "agent",
|
|
2874
|
+
id: closed.id,
|
|
2875
|
+
model_key: turn.modelKey,
|
|
2876
|
+
begin_at: closed.beginAt,
|
|
2877
|
+
end_at: closed.endAt,
|
|
2878
|
+
stage: closed.stage,
|
|
2879
|
+
name: turn.name
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
}),
|
|
2883
|
+
encodeVersion: "1"
|
|
2884
|
+
});
|
|
2885
|
+
try {
|
|
2886
|
+
const url = `${this.chatBaseUrl()}${FINISH_PATH}`;
|
|
2887
|
+
const pathSig = pathSigFrom(url);
|
|
2888
|
+
const encoded = cosyEncode(new TextEncoder().encode(body));
|
|
2889
|
+
const date = String(Math.floor(Date.now() / 1e3));
|
|
2890
|
+
const payloadB64 = buildPayloadB64(holder.session.info, this.clientVersion);
|
|
2891
|
+
const sig = signRequest(payloadB64, holder.session.cosyKey, date, encoded, pathSig);
|
|
2892
|
+
const resp = await this.fetchImpl(url, {
|
|
2893
|
+
method: "POST",
|
|
2894
|
+
headers: {
|
|
2895
|
+
...DEFAULT_HEADERS,
|
|
2896
|
+
"cosy-date": date,
|
|
2897
|
+
"cosy-user": holder.session.identity.uid,
|
|
2898
|
+
"cosy-key": holder.session.cosyKey,
|
|
2899
|
+
accept: "*/*",
|
|
2900
|
+
authorization: composeBearer(payloadB64, sig),
|
|
2901
|
+
"cosy-version": this.clientVersion,
|
|
2902
|
+
...this.machineHeaders(holder)
|
|
2903
|
+
},
|
|
2904
|
+
body: encoded
|
|
2905
|
+
});
|
|
2906
|
+
if (resp.status !== 200) {
|
|
2907
|
+
const text = await resp.text().catch(() => "");
|
|
2908
|
+
this.log(`轮次闭合失败: HTTP ${resp.status} ${truncate(text, 200)}`);
|
|
2909
|
+
}
|
|
2910
|
+
} catch (error) {
|
|
2911
|
+
this.log(`轮次闭合失败: ${String(error?.message ?? error)}`);
|
|
2912
|
+
}
|
|
2913
|
+
}
|
|
2914
|
+
/**
|
|
2915
|
+
* 活动列表(`GET /sash/api/v1/me/campaigns?forceRefresh=true`)。
|
|
2916
|
+
* 协议来自社区参考实现(L0NE-6/Qoder-Daily),已在本机 CN 账号实测通过:
|
|
2917
|
+
* `GET {openapi}/sash/api/v1/me/campaigns?forceRefresh=true`,认证用与用量
|
|
2918
|
+
* 查询同一套 `jt-` 令牌(`jobToken.securityOauthToken`)。
|
|
2919
|
+
*
|
|
2920
|
+
* 注意路径里**没有**「签到」二字——它叫 campaigns(活动/权益)。这也是我早期
|
|
2921
|
+
* 把 `checkinSupported` 写死成 false 的原因:照着 checkin / signin / reward
|
|
2922
|
+
* 猜路径一律 404(实测猜了 13 个),于是误判成「Qoder 没有签到」。
|
|
2923
|
+
*
|
|
2924
|
+
* 旧语义(签到挑用的那一小片)保留在这里:它就是 `fetchCampaignFeed` 的
|
|
2925
|
+
* `campaigns` 投影,免得签到路径与卡片展示路径各写一份解析、日后漂移。
|
|
2926
|
+
*/
|
|
2927
|
+
async fetchCampaigns(credential, signal) {
|
|
2928
|
+
return (await this.fetchCampaignFeed(credential, signal)).campaigns;
|
|
2929
|
+
}
|
|
2930
|
+
/**
|
|
2931
|
+
* 完整活动面(含 `VIEW_DETAILS` banner 与顶层字段),给卡片「活动」区用。
|
|
2932
|
+
*
|
|
2933
|
+
* 实测(CN,2026-10-25)返回的整份形状:
|
|
2934
|
+
* `{ uid, showCampaign, claimable, campaignUrl, campaigns:[{ campaignId, campaignKey,
|
|
2935
|
+
* actionType, startAt, endAt, claimStatus, benefit:{...},
|
|
2936
|
+
* placements:[{ type, campaignUrl, content:{ zh:{title,description,detailUrl},
|
|
2937
|
+
* en:{...} } }] }] }`。标题 / 描述 / 「查看详情」链接都在 `placements[*].content`
|
|
2938
|
+
* 里,按语言各一份;上游只下发它有的语言,所以这里原样收拢,不做翻译。
|
|
2939
|
+
*
|
|
2940
|
+
* 解析对字段缺席是**宽容**的:活动形状常按节日变(1024 集结、首月翻倍这类只在
|
|
2941
|
+
* 当期下发),缺字段就少渲染一点,绝不替上游编标题或链接。
|
|
2942
|
+
*/
|
|
2943
|
+
async fetchCampaignFeed(credential, signal) {
|
|
2944
|
+
const holder = await this.ensureSession(credential);
|
|
2945
|
+
const url = `${this.region.openapi}${this.region.campaignsPath}${CAMPAIGNS_QUERY}`;
|
|
2946
|
+
const data = await this.sashRequest("GET", holder, url, void 0, signal);
|
|
2947
|
+
return {
|
|
2948
|
+
campaigns: (Array.isArray(data.campaigns) ? data.campaigns : Array.isArray(data.data?.campaigns) ? data.data.campaigns : []).map((entry) => projectCampaignEntry(entry)).filter((c) => c !== void 0),
|
|
2949
|
+
...typeof data.campaignUrl === "string" && data.campaignUrl !== "" ? { campaignUrl: data.campaignUrl } : {},
|
|
2950
|
+
...typeof data.showCampaign === "boolean" ? { showCampaign: data.showCampaign } : {},
|
|
2951
|
+
...typeof data.claimable === "boolean" ? { claimable: data.claimable } : {}
|
|
2952
|
+
};
|
|
2953
|
+
}
|
|
2954
|
+
/**
|
|
2955
|
+
* 签到:领取今天那一份每日 Credits。
|
|
2956
|
+
*
|
|
2957
|
+
* 一次调用自足——先拉活动列表找出可领的那条,再领取。三种结果分得很清:
|
|
2958
|
+
* - `claimed`:领到了(带回数额与有效期);
|
|
2959
|
+
* - `already-claimed`:今天已经领过(`CLAIMED` / 409 / `ALREADY_CLAIMED` /
|
|
2960
|
+
* `replayed`),**不是错误**——重复调用是幂等的;
|
|
2961
|
+
* - `unavailable`:今天上游没下发活动(未开窗 / 已领到活动行消失 / 企业号
|
|
2962
|
+
* 不支持该活动),带上说明。
|
|
2963
|
+
*/
|
|
2964
|
+
async claimDailyCredits(credential, signal) {
|
|
2965
|
+
const campaigns = await this.fetchCampaigns(credential, signal);
|
|
2966
|
+
const daily = campaigns.find((c) => c.actionType === "CLAIM_BENEFIT");
|
|
2967
|
+
const claimable = campaigns.find((c) => c.actionType === "CLAIM_BENEFIT" && c.claimStatus === "CLAIMABLE");
|
|
2968
|
+
const nextRefreshAtMs = daily?.endAt === void 0 ? void 0 : daily.endAt * 1e3;
|
|
2969
|
+
if (claimable === void 0) return daily?.claimStatus === "CLAIMED" ? {
|
|
2970
|
+
status: "already-claimed",
|
|
2971
|
+
...nextRefreshAtMs === void 0 ? {} : { nextRefreshAtMs }
|
|
2972
|
+
} : {
|
|
2973
|
+
status: "unavailable",
|
|
2974
|
+
message: "上游今日没有下发可领取的签到活动"
|
|
2975
|
+
};
|
|
2976
|
+
const holder = await this.ensureSession(credential);
|
|
2977
|
+
const url = `${this.region.openapi}${this.region.campaignsPath}/${encodeURIComponent(claimable.campaignId)}/claim`;
|
|
2978
|
+
try {
|
|
2979
|
+
const data = await this.sashRequest("POST", holder, url, {}, signal);
|
|
2980
|
+
if (String(data.status ?? "") === "CLAIMED") return {
|
|
2981
|
+
status: "claimed",
|
|
2982
|
+
...claimable.amount === void 0 ? {} : { amount: claimable.amount },
|
|
2983
|
+
...claimable.validityDays === void 0 ? {} : { validityDays: claimable.validityDays },
|
|
2984
|
+
...nextRefreshAtMs === void 0 ? {} : { nextRefreshAtMs }
|
|
2985
|
+
};
|
|
2986
|
+
return {
|
|
2987
|
+
status: "unavailable",
|
|
2988
|
+
message: `签到未完成(上游状态 ${String(data.status ?? "未知")})`
|
|
2989
|
+
};
|
|
2990
|
+
} catch (error) {
|
|
2991
|
+
if (error instanceof QoderUpstreamError && error.status === 409) return {
|
|
2992
|
+
status: "already-claimed",
|
|
2993
|
+
...nextRefreshAtMs === void 0 ? {} : { nextRefreshAtMs }
|
|
2994
|
+
};
|
|
2995
|
+
throw error;
|
|
2996
|
+
}
|
|
2997
|
+
}
|
|
2998
|
+
/**
|
|
2999
|
+
* `sash` 接口的通用请求(活动列表 / 领取共用)。
|
|
3000
|
+
*
|
|
3001
|
+
* 认证与用量查询同一套:`Authorization: Bearer <jobToken.securityOauthToken>`。
|
|
3002
|
+
* 但那两个接口需要 `cosy-clienttype: 10` 与 `user-agent: Qoder`——参考实现
|
|
3003
|
+
* 如此,缺了会被拒;而夹带 cosy 协议头(chat/models 那套)反而不认。
|
|
3004
|
+
*
|
|
3005
|
+
* 这里的 `10` 与 cosy 面的 {@link COSY_CLIENT_TYPE} **恰好同值但不同源**:
|
|
3006
|
+
* 这条是 sash 面自己的客户端标识(`SASH_CLIENT_TYPE`,逐条手写请求头),
|
|
3007
|
+
* 改 cosy 面的协议版本不该顺手动它,反之亦然。两个数字各自独立被测。sash 面
|
|
3008
|
+
* 也**不**发 `cosy-version`:它本来就不带那套协议头。
|
|
3009
|
+
*
|
|
3010
|
+
* **国际版额外需要设备风控头**(`Cosy-MachineToken/Code/Type`,见 device-risk.ts):
|
|
3011
|
+
* 签到活动只下发给带这些头的请求,缺了就拿不到活动列表。国内版不需要,所以按
|
|
3012
|
+
* region 条件附加 —— 不要无条件发,多余的头在另一侧是噪音。
|
|
3013
|
+
*/
|
|
3014
|
+
async sashRequest(method, holder, url, body, signal) {
|
|
3015
|
+
const oauthToken = this.sashBearerOf(holder);
|
|
3016
|
+
if (oauthToken === "") throw new QoderUpstreamError("auth", "两次令牌交换都没有拿到可用令牌,无法访问签到接口", 401);
|
|
3017
|
+
const resp = await this.fetchImpl(url, {
|
|
3018
|
+
method,
|
|
3019
|
+
headers: {
|
|
3020
|
+
authorization: `Bearer ${oauthToken}`,
|
|
3021
|
+
"cosy-clienttype": SASH_CLIENT_TYPE,
|
|
3022
|
+
accept: "application/json",
|
|
3023
|
+
"accept-language": "zh-CN",
|
|
3024
|
+
"user-agent": SASH_USER_AGENT,
|
|
3025
|
+
...await this.deviceRiskHeaders(),
|
|
3026
|
+
...method === "POST" ? {
|
|
3027
|
+
"content-type": "application/json",
|
|
3028
|
+
origin: this.region.openapi
|
|
3029
|
+
} : {}
|
|
3030
|
+
},
|
|
3031
|
+
...method === "POST" ? { body: JSON.stringify(body ?? {}) } : {},
|
|
3032
|
+
...signal === void 0 ? {} : { signal }
|
|
3033
|
+
});
|
|
3034
|
+
const text = await resp.text();
|
|
3035
|
+
if (resp.status !== 200 && resp.status !== 201) throw new QoderUpstreamError(classifyFailure(resp.status, text), `请求失败: HTTP ${resp.status} ${truncate(text, 200)}`, resp.status, deepestBusinessCode(text));
|
|
3036
|
+
try {
|
|
3037
|
+
return JSON.parse(text);
|
|
3038
|
+
} catch {
|
|
3039
|
+
throw new QoderUpstreamError("unknown", `响应不是 JSON: ${truncate(text, 200)}`, resp.status);
|
|
3040
|
+
}
|
|
3041
|
+
}
|
|
3042
|
+
/**
|
|
3043
|
+
* 本区域签到需要的设备风控头。
|
|
3044
|
+
*
|
|
3045
|
+
* 国内版返回空对象(不需要,发了反而是噪音);国际版读取本机 UMID 组件的
|
|
3046
|
+
* 三件套。读取失败**不**静默降级成「无头请求」——那样只会拿到一个空的活动
|
|
3047
|
+
* 列表,用户看到「今天没有活动」而真实原因是取不到设备身份。所以这里让错误
|
|
3048
|
+
* 抛出去,由调用方带着原因回报。
|
|
3049
|
+
*/
|
|
3050
|
+
async deviceRiskHeaders() {
|
|
3051
|
+
if (!this.region.requiresDeviceRisk) return {};
|
|
3052
|
+
const risk = await readDeviceRisk(this.regionKey);
|
|
3053
|
+
return {
|
|
3054
|
+
"cosy-machinetoken": risk.machineToken,
|
|
3055
|
+
"cosy-machinecode": risk.machineCode,
|
|
3056
|
+
"cosy-machinetype": risk.machineType
|
|
3057
|
+
};
|
|
3058
|
+
}
|
|
3059
|
+
/**
|
|
3060
|
+
* 直连回退:`Bearer <PAT>` 打同一个端点。返回 undefined 表示这条回退路径
|
|
3061
|
+
* 也没给出 200(端点不接受直连 PAT,或网络失败)——由调用方决定是否把原始
|
|
3062
|
+
* 的凭据被拒错误抛出去。
|
|
3063
|
+
*/
|
|
3064
|
+
async fetchUsageDirect(url, credential, signal) {
|
|
3065
|
+
try {
|
|
3066
|
+
const resp = await this.fetchImpl(url, {
|
|
3067
|
+
headers: {
|
|
3068
|
+
authorization: `Bearer ${credential}`,
|
|
3069
|
+
accept: "application/json",
|
|
3070
|
+
"cosy-clienttype": "10",
|
|
3071
|
+
"user-agent": "Qoder",
|
|
3072
|
+
...await this.deviceRiskHeaders()
|
|
3073
|
+
},
|
|
3074
|
+
...signal === void 0 ? {} : { signal }
|
|
3075
|
+
});
|
|
3076
|
+
if (resp.status === 200) return parseUsage(await resp.json());
|
|
3077
|
+
if (resp.status === 401 || resp.status === 403) return;
|
|
3078
|
+
} catch {}
|
|
3079
|
+
}
|
|
3080
|
+
async bearerGet(holder, url, signal) {
|
|
3081
|
+
const pathSig = pathSigFrom(url);
|
|
3082
|
+
const payloadB64 = buildPayloadB64(holder.session.info, this.clientVersion);
|
|
3083
|
+
const date = String(Math.floor(Date.now() / 1e3));
|
|
3084
|
+
const bearer = composeBearer(payloadB64, signRequest(payloadB64, holder.session.cosyKey, date, "", pathSig));
|
|
3085
|
+
const headers = {
|
|
3086
|
+
...DEFAULT_HEADERS,
|
|
3087
|
+
"cosy-date": date,
|
|
3088
|
+
"cosy-user": holder.session.identity.uid,
|
|
3089
|
+
"cosy-key": holder.session.cosyKey,
|
|
3090
|
+
accept: "application/json",
|
|
3091
|
+
authorization: bearer,
|
|
3092
|
+
"cosy-version": this.clientVersion,
|
|
3093
|
+
...this.machineHeaders(holder)
|
|
3094
|
+
};
|
|
3095
|
+
const resp = await this.fetchImpl(url, {
|
|
3096
|
+
headers,
|
|
3097
|
+
...signal === void 0 ? {} : { signal }
|
|
3098
|
+
});
|
|
3099
|
+
const text = await resp.text();
|
|
3100
|
+
if (resp.status !== 200) throw new QoderUpstreamError(classifyFailure(resp.status, text), `请求失败: HTTP ${resp.status} ${truncate(text, 200)}`, resp.status, deepestBusinessCode(text));
|
|
3101
|
+
try {
|
|
3102
|
+
return JSON.parse(text);
|
|
3103
|
+
} catch {
|
|
3104
|
+
throw new QoderUpstreamError("unknown", `响应不是 JSON: ${truncate(text, 200)}`, resp.status);
|
|
3105
|
+
}
|
|
3106
|
+
}
|
|
3107
|
+
};
|
|
3108
|
+
/**
|
|
3109
|
+
* 把上游的一条 campaign 投影成 `QoderCampaign`(宽容:缺字段就少渲染,不编造)。
|
|
3110
|
+
*
|
|
3111
|
+
* `placements` 是数组,每个元素带 `content: { zh?: {…}, en?: {…} }`(POPUP / USAGE
|
|
3112
|
+
* 各一份)。同一语言的文案取**第一份非空**:同一活动通常多份完全相同,重复渲染
|
|
3113
|
+
* 只会让卡片上出现两行一样的东西。
|
|
3114
|
+
*/
|
|
3115
|
+
function projectCampaignEntry(entry) {
|
|
3116
|
+
if (!entry || typeof entry !== "object") return void 0;
|
|
3117
|
+
const raw = entry;
|
|
3118
|
+
const campaignId = typeof raw.campaignId === "string" ? raw.campaignId : "";
|
|
3119
|
+
if (campaignId === "") return void 0;
|
|
3120
|
+
const benefit = typeof raw.benefit === "object" && raw.benefit !== null ? raw.benefit : {};
|
|
3121
|
+
const validity = typeof benefit.validity === "object" && benefit.validity !== null ? benefit.validity : {};
|
|
3122
|
+
const placements = Array.isArray(raw.placements) ? raw.placements : [];
|
|
3123
|
+
let campaignUrl = "";
|
|
3124
|
+
const content = {};
|
|
3125
|
+
for (const p of placements) {
|
|
3126
|
+
if (!p || typeof p !== "object") continue;
|
|
3127
|
+
const slot = p;
|
|
3128
|
+
if (campaignUrl === "" && typeof slot.campaignUrl === "string") campaignUrl = slot.campaignUrl;
|
|
3129
|
+
const slotContent = slot.content;
|
|
3130
|
+
if (!slotContent || typeof slotContent !== "object") continue;
|
|
3131
|
+
for (const [lang, text] of Object.entries(slotContent)) {
|
|
3132
|
+
if (!text || typeof text !== "object") continue;
|
|
3133
|
+
const t = text;
|
|
3134
|
+
const row = {
|
|
3135
|
+
...typeof t.title === "string" ? { title: t.title } : {},
|
|
3136
|
+
...typeof t.description === "string" ? { description: t.description } : {},
|
|
3137
|
+
...typeof t.detailUrl === "string" ? { detailUrl: t.detailUrl } : {},
|
|
3138
|
+
...typeof t.buttonText === "string" ? { buttonText: t.buttonText } : {}
|
|
3139
|
+
};
|
|
3140
|
+
const prior = content[lang];
|
|
3141
|
+
if (prior === void 0 || Object.keys(prior).length === 0 && Object.keys(row).length > 0) content[lang] = row;
|
|
3142
|
+
}
|
|
3143
|
+
}
|
|
3144
|
+
return {
|
|
3145
|
+
campaignId,
|
|
3146
|
+
actionType: typeof raw.actionType === "string" ? raw.actionType : "",
|
|
3147
|
+
claimStatus: typeof raw.claimStatus === "string" ? raw.claimStatus : "",
|
|
3148
|
+
...typeof raw.campaignKey === "string" && raw.campaignKey !== "" ? { campaignKey: raw.campaignKey } : {},
|
|
3149
|
+
...campaignUrl !== "" ? { campaignUrl } : {},
|
|
3150
|
+
...typeof benefit.amount === "number" ? { amount: benefit.amount } : {},
|
|
3151
|
+
...typeof validity.days === "number" && (validity.mode === void 0 || validity.mode === "RELATIVE_DAYS") ? { validityDays: validity.days } : {},
|
|
3152
|
+
...typeof raw.startAt === "number" ? { startAt: raw.startAt } : {},
|
|
3153
|
+
...typeof raw.endAt === "number" ? { endAt: raw.endAt } : {},
|
|
3154
|
+
...Object.keys(content).length > 0 ? { content } : {}
|
|
3155
|
+
};
|
|
3156
|
+
}
|
|
3157
|
+
/** jobToken 交换请求体。PAT 或 `drt-` refreshToken 二选一。 */
|
|
3158
|
+
function jobTokenBody(credential) {
|
|
3159
|
+
const isRefresh = credential.startsWith("drt-");
|
|
3160
|
+
const outer = {
|
|
3161
|
+
payload: JSON.stringify({
|
|
3162
|
+
personalToken: isRefresh ? "" : credential,
|
|
3163
|
+
securityOauthToken: "",
|
|
3164
|
+
refreshToken: isRefresh ? credential : "",
|
|
3165
|
+
needRefresh: isRefresh,
|
|
3166
|
+
authInfo: {}
|
|
3167
|
+
}),
|
|
3168
|
+
encodeVersion: "1"
|
|
3169
|
+
};
|
|
3170
|
+
const plain = JSON.stringify(outer);
|
|
3171
|
+
return cosyEncode(new TextEncoder().encode(plain));
|
|
3172
|
+
}
|
|
3173
|
+
function randomId() {
|
|
3174
|
+
return crypto.randomUUID();
|
|
3175
|
+
}
|
|
3176
|
+
/**
|
|
3177
|
+
* 解析一条 SSE 帧:
|
|
3178
|
+
* `data: {"headers":{...},"body":"<inner json>","statusCodeValue":200}`
|
|
3179
|
+
* 内层:`{"choices":[{"delta":{...}}], "usage":{...}}` 或业务错误 `{"code":"115","message":"..."}`。
|
|
3180
|
+
* 返回 undefined 表示本帧无可消费内容(或 [DONE] 之前的空帧)。
|
|
3181
|
+
*/
|
|
3182
|
+
function parseStreamDelta(dataPayload) {
|
|
3183
|
+
let wrapper;
|
|
3184
|
+
try {
|
|
3185
|
+
wrapper = JSON.parse(dataPayload);
|
|
3186
|
+
} catch {
|
|
3187
|
+
return;
|
|
3188
|
+
}
|
|
3189
|
+
const scv = wrapper.statusCodeValue;
|
|
3190
|
+
if (scv !== void 0 && scv !== null && Number(scv) !== 200) {
|
|
3191
|
+
const detail = typeof wrapper.body === "string" ? wrapper.body : dataPayload.slice(0, 400);
|
|
3192
|
+
throw new QoderUpstreamError(classifyFailure(Number(scv), detail), `上游信封错误: HTTP ${scv} ${truncate(detail, 300)}`, Number(scv), deepestBusinessCode(detail), retryAfterMsOf(detail), queueOf(detail));
|
|
3193
|
+
}
|
|
3194
|
+
const innerStr = wrapper.body;
|
|
3195
|
+
if (typeof innerStr !== "string" || innerStr === "") return void 0;
|
|
3196
|
+
let inner;
|
|
3197
|
+
try {
|
|
3198
|
+
inner = JSON.parse(innerStr);
|
|
3199
|
+
} catch {
|
|
3200
|
+
return;
|
|
3201
|
+
}
|
|
3202
|
+
if (inner === null || typeof inner !== "object") return void 0;
|
|
3203
|
+
if (typeof inner.code === "string" && inner.code !== "" && inner.code !== "0") {
|
|
3204
|
+
const detail = typeof inner.message === "string" ? inner.message : JSON.stringify(inner.message ?? "");
|
|
3205
|
+
throw new QoderUpstreamError(classifyBusinessCode(inner.code), `上游业务错误 code=${inner.code}: ${String(inner.message ?? "")}`, 0, inner.code, retryAfterMsOf(detail), queueOf(detail));
|
|
3206
|
+
}
|
|
3207
|
+
const usageIn = readTokens(inner.usage, "prompt_tokens");
|
|
3208
|
+
const usageOut = readTokens(inner.usage, "completion_tokens");
|
|
3209
|
+
const usageCached = readCachedTokens(inner.usage);
|
|
3210
|
+
const tokens = usageCached === void 0 ? {
|
|
3211
|
+
inputTokens: usageIn,
|
|
3212
|
+
outputTokens: usageOut
|
|
3213
|
+
} : {
|
|
3214
|
+
inputTokens: usageIn,
|
|
3215
|
+
outputTokens: usageOut,
|
|
3216
|
+
cachedTokens: usageCached
|
|
3217
|
+
};
|
|
3218
|
+
const choices = Array.isArray(inner.choices) ? inner.choices : [];
|
|
3219
|
+
for (const ch of choices) {
|
|
3220
|
+
const delta = ch.delta;
|
|
3221
|
+
if (!delta) continue;
|
|
3222
|
+
const role = typeof delta.role === "string" ? delta.role : "";
|
|
3223
|
+
const content = typeof delta.content === "string" ? delta.content : "";
|
|
3224
|
+
const reasoning = typeof delta.reasoning_content === "string" ? delta.reasoning_content : "";
|
|
3225
|
+
const toolCalls = Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0 ? delta.tool_calls : void 0;
|
|
3226
|
+
if (role !== "" || content !== "" || reasoning !== "" || toolCalls !== void 0) return {
|
|
3227
|
+
role,
|
|
3228
|
+
content,
|
|
3229
|
+
reasoningContent: reasoning,
|
|
3230
|
+
toolCalls,
|
|
3231
|
+
...tokens
|
|
3232
|
+
};
|
|
3233
|
+
}
|
|
3234
|
+
if (usageIn > 0 || usageOut > 0) return {
|
|
3235
|
+
role: "",
|
|
3236
|
+
content: "",
|
|
3237
|
+
reasoningContent: "",
|
|
3238
|
+
toolCalls: void 0,
|
|
3239
|
+
...tokens
|
|
3240
|
+
};
|
|
3241
|
+
}
|
|
3242
|
+
function readTokens(usage, key) {
|
|
3243
|
+
if (!usage || typeof usage !== "object") return 0;
|
|
3244
|
+
const v = usage[key];
|
|
3245
|
+
return typeof v === "number" ? v : 0;
|
|
3246
|
+
}
|
|
3247
|
+
/**
|
|
3248
|
+
* 读缓存命中的输入 token 数(issue #4)。
|
|
3249
|
+
*
|
|
3250
|
+
* 为什么这里值得一个专门的函数、而不是顺手写进 `readTokens`:**它有三个可能的
|
|
3251
|
+
* 位置**,而各家的写法不统一(宿主 `parseChunkUsage` 里列过同一张表):
|
|
3252
|
+
*
|
|
3253
|
+
* 1. `prompt_tokens_details.cached_tokens` —— OpenAI / OpenRouter,也是实测
|
|
3254
|
+
* 上 Qoder 网关正在用的那个(见 `QoderChatDelta.cachedTokens` 的真实样本)。
|
|
3255
|
+
* 2. `prompt_cache_hit_tokens` —— DeepSeek 系,顶层的另一个拼法。
|
|
3256
|
+
* 3. `cached_tokens` —— Kimi 文档里放顶层。
|
|
3257
|
+
*
|
|
3258
|
+
* 取**第一个存在**的那个,不做相加:它们是同一个量的三种写法,不是三个分量。
|
|
3259
|
+
*
|
|
3260
|
+
* 返回 `undefined` 表示「上游没报」。**不要**把它折成 0:那会让「这一帧没有
|
|
3261
|
+
* usage」与「这次一个都没命中」变成同一个数字,而宿主的百分比正是拿它算的
|
|
3262
|
+
* ——issue #4 的整个症状就是「0% 不可信」,用一个默认 0 去修它等于把病保留下来。
|
|
3263
|
+
*
|
|
3264
|
+
* 另一条**不可踩的坑**:`cached_tokens` 是 `prompt_tokens` 的**子集**(实测
|
|
3265
|
+
* 2032 / 2038),所以绝不能加进 `prompt_tokens`。宿主侧自己会做
|
|
3266
|
+
* `input = prompt_tokens - cacheRead`,两边各按「子集」理解才对得上。
|
|
3267
|
+
*/
|
|
3268
|
+
function readCachedTokens(usage) {
|
|
3269
|
+
if (!usage || typeof usage !== "object") return void 0;
|
|
3270
|
+
const record = usage;
|
|
3271
|
+
const details = record["prompt_tokens_details"];
|
|
3272
|
+
const fromDetails = details !== null && typeof details === "object" && !Array.isArray(details) ? readCount(details["cached_tokens"]) : void 0;
|
|
3273
|
+
if (fromDetails !== void 0) return fromDetails;
|
|
3274
|
+
const fromHit = readCount(record["prompt_cache_hit_tokens"]);
|
|
3275
|
+
if (fromHit !== void 0) return fromHit;
|
|
3276
|
+
return readCount(record["cached_tokens"]);
|
|
3277
|
+
}
|
|
3278
|
+
/** 有限、非负的数字;其它一律 `undefined`(`NaN` / 负数 / 字符串都不算数)。 */
|
|
3279
|
+
function readCount(value) {
|
|
3280
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : void 0;
|
|
3281
|
+
}
|
|
3282
|
+
/** 解析用量响应(兼容 qoderUsage 内层与平铺两种形状)。 */
|
|
3283
|
+
function parseUsage(data) {
|
|
3284
|
+
const source = data.qoderUsage ?? data;
|
|
3285
|
+
const userQuota = readBucket(source.userQuota);
|
|
3286
|
+
const addOn = source.addOnQuota;
|
|
3287
|
+
const org = source.orgResourcePackage;
|
|
3288
|
+
const out = {
|
|
3289
|
+
userType: typeof source.userType === "string" ? source.userType : void 0,
|
|
3290
|
+
expiresAt: typeof source.expiresAt === "number" ? source.expiresAt : void 0,
|
|
3291
|
+
upgradeUrl: typeof source.upgradeUrl === "string" ? source.upgradeUrl : void 0,
|
|
3292
|
+
isQuotaExceeded: source.isQuotaExceeded === true
|
|
3293
|
+
};
|
|
3294
|
+
if (userQuota) out.userQuota = userQuota;
|
|
3295
|
+
if (addOn) out.addOnQuota = {
|
|
3296
|
+
...readBucket(addOn),
|
|
3297
|
+
detailUrl: typeof addOn.detailUrl === "string" ? addOn.detailUrl : void 0
|
|
3298
|
+
};
|
|
3299
|
+
if (org) out.orgResourcePackage = {
|
|
3300
|
+
used: num(org.used),
|
|
3301
|
+
cap: num(org.cap),
|
|
3302
|
+
remaining: num(org.remaining),
|
|
3303
|
+
percentage: num(org.percentage),
|
|
3304
|
+
available: org.available === true
|
|
3305
|
+
};
|
|
3306
|
+
const dedicated = readDedicatedPackages(source.dedicatedResourcePackages);
|
|
3307
|
+
if (dedicated.length > 0) out.dedicatedResourcePackages = dedicated;
|
|
3308
|
+
return out;
|
|
3309
|
+
}
|
|
3310
|
+
/**
|
|
3311
|
+
* 读 `dedicatedResourcePackages`(issue #38)。
|
|
3312
|
+
*
|
|
3313
|
+
* 三条取舍,都对应上游这一块真实存在的形态:
|
|
3314
|
+
*
|
|
3315
|
+
* 1. **整块读不懂就当没有**:不是数组、或者元素不是对象 → `[]`。一个读不懂的
|
|
3316
|
+
* 专属包不该让整次用量解析失败(那会把「有积分」变成「积分读不出来」)。
|
|
3317
|
+
* 2. **筛掉明确停用的**:`available === false` 直接丢;`status` 有值却不等于
|
|
3318
|
+
* ACTIVE 也丢。两个字段是同一件事的两种写法,只认**明确说不**的那一侧 ——
|
|
3319
|
+
* 字段缺席不构成停用证据(老上游可能只发其中一个)。不筛的话,一个已过期 /
|
|
3320
|
+
* 已停用的包会顶着一行「剩余 888」出现在读数里,用户会以为那笔钱还在。
|
|
3321
|
+
* 3. **`remaining` 缺席不折成 0**(与 `readBucket` 同一条规矩):0 是「这个包
|
|
3322
|
+
* 用完了」的断言,缺席只是「上游这一行没写」。界面把缺席画成「—」。
|
|
3323
|
+
*/
|
|
3324
|
+
function readDedicatedPackages(value) {
|
|
3325
|
+
if (!Array.isArray(value)) return [];
|
|
3326
|
+
const out = [];
|
|
3327
|
+
for (const item of value) {
|
|
3328
|
+
if (item === null || typeof item !== "object" || Array.isArray(item)) continue;
|
|
3329
|
+
const raw = item;
|
|
3330
|
+
if (raw["available"] === false) continue;
|
|
3331
|
+
const status = typeof raw["status"] === "string" ? raw["status"] : void 0;
|
|
3332
|
+
if (status !== void 0 && status !== DEDICATED_ACTIVE_STATUS) continue;
|
|
3333
|
+
const title = readI18nLabel(raw["displayLabels"], "title");
|
|
3334
|
+
const description = readI18nLabel(raw["displayLabels"], "description");
|
|
3335
|
+
out.push({
|
|
3336
|
+
id: typeof raw["id"] === "string" && raw["id"] !== "" ? raw["id"] : typeof raw["name"] === "string" ? raw["name"] : "",
|
|
3337
|
+
...title === void 0 ? {} : { title },
|
|
3338
|
+
...description === void 0 ? {} : { description },
|
|
3339
|
+
...!isFiniteNumber(num(raw["remaining"])) ? {} : { remaining: Math.max(num(raw["remaining"]), 0) },
|
|
3340
|
+
...!isFiniteNumber(num(raw["total"])) ? {} : { total: num(raw["total"]) },
|
|
3341
|
+
...!isFiniteNumber(num(raw["expiresAt"])) ? {} : { expiresAtMs: num(raw["expiresAt"]) },
|
|
3342
|
+
...status === void 0 ? {} : { status }
|
|
3343
|
+
});
|
|
3344
|
+
}
|
|
3345
|
+
return out;
|
|
3346
|
+
}
|
|
3347
|
+
/** 上游声明的「这个专属包还在生效」。 */
|
|
3348
|
+
const DEDICATED_ACTIVE_STATUS = "QUOTA_DETAIL_STATUS_ACTIVE";
|
|
3349
|
+
/** 有限数才算「上游报了」。`NaN` / `Infinity` 与缺席同义(`num` 只筛 typeof)。 */
|
|
3350
|
+
function isFiniteNumber(value) {
|
|
3351
|
+
return value !== void 0 && Number.isFinite(value);
|
|
3352
|
+
}
|
|
3353
|
+
/**
|
|
3354
|
+
* 从 `displayLabels[]` 里取某一条双语文案。
|
|
3355
|
+
*
|
|
3356
|
+
* 形状是 `[{ dimension: 'title', value: 'zh 原文', valueI18n: { 'zh-CN': …, 'en-US': … } }, …]`。
|
|
3357
|
+
* **两种语言都收**,界面按当前语言挑:这一层不知道也不该猜读者用哪种语言
|
|
3358
|
+
* (客户端才握着宿主语言,见 `promo-badge.ts` 的 `hostLanguage`)。
|
|
3359
|
+
*
|
|
3360
|
+
* `valueI18n` 缺席时退回裸 `value`:那至少是上游自己的一句话,比没有强。
|
|
3361
|
+
*/
|
|
3362
|
+
function readI18nLabel(labels, dimension) {
|
|
3363
|
+
if (!Array.isArray(labels)) return void 0;
|
|
3364
|
+
for (const entry of labels) {
|
|
3365
|
+
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) continue;
|
|
3366
|
+
const row = entry;
|
|
3367
|
+
if (row["dimension"] !== dimension) continue;
|
|
3368
|
+
const i18n = row["valueI18n"];
|
|
3369
|
+
const zh = i18n !== null && typeof i18n === "object" && !Array.isArray(i18n) ? textOf(i18n["zh-CN"]) ?? textOf(i18n["zh"]) : void 0;
|
|
3370
|
+
const en = i18n !== null && typeof i18n === "object" && !Array.isArray(i18n) ? textOf(i18n["en-US"]) ?? textOf(i18n["en"]) : void 0;
|
|
3371
|
+
const plain = textOf(row["value"]);
|
|
3372
|
+
if (zh === void 0 && en === void 0 && plain === void 0) return void 0;
|
|
3373
|
+
return {
|
|
3374
|
+
...zh === void 0 && plain === void 0 ? {} : { zh: zh ?? plain },
|
|
3375
|
+
...en === void 0 && plain === void 0 ? {} : { en: en ?? plain }
|
|
3376
|
+
};
|
|
3377
|
+
}
|
|
3378
|
+
}
|
|
3379
|
+
/** 非空、非全空白的字符串。 */
|
|
3380
|
+
function textOf(value) {
|
|
3381
|
+
if (typeof value !== "string") return void 0;
|
|
3382
|
+
const trimmed = value.trim();
|
|
3383
|
+
return trimmed === "" ? void 0 : trimmed;
|
|
3384
|
+
}
|
|
3385
|
+
function readBucket(value) {
|
|
3386
|
+
if (!value || typeof value !== "object") return void 0;
|
|
3387
|
+
const v = value;
|
|
3388
|
+
return {
|
|
3389
|
+
total: num(v.total),
|
|
3390
|
+
used: num(v.used),
|
|
3391
|
+
remaining: num(v.remaining),
|
|
3392
|
+
percentage: num(v.percentage)
|
|
3393
|
+
};
|
|
3394
|
+
}
|
|
3395
|
+
function num(v) {
|
|
3396
|
+
return typeof v === "number" ? v : void 0;
|
|
3397
|
+
}
|
|
3398
|
+
/** HTTP 状态 → 错误分类(内容审核标记优先于状态码,与 Go 版一致)。 */
|
|
3399
|
+
function classifyHttpStatus(status, detail) {
|
|
3400
|
+
if (isContentPolicy(detail)) return "content-policy";
|
|
3401
|
+
if (status === 401 || status === 403) return "auth";
|
|
3402
|
+
if (status === 429) return "rate-limited";
|
|
3403
|
+
if (status === 400) return "invalid-request";
|
|
3404
|
+
if (status === 418 || status >= 500) return "transient";
|
|
3405
|
+
return "unknown";
|
|
3406
|
+
}
|
|
3407
|
+
/**
|
|
3408
|
+
* 下钻的最大层数:防自嵌套/循环引用把解析变成死循环。
|
|
3409
|
+
*
|
|
3410
|
+
* 实测最深的两层就够(issue #6 的真实帧是「外层信封 → 内层业务码」),但这里给
|
|
3411
|
+
* 一点余量,因为上游换一次包装就会多一层,而多一层只是多一次 JSON.parse。
|
|
3412
|
+
*/
|
|
3413
|
+
const MAX_CODE_NESTING = 6;
|
|
3414
|
+
/**
|
|
3415
|
+
* 取上游申报的「请等这么久再试」,毫秒(issue #24)。
|
|
3416
|
+
*
|
|
3417
|
+
* 实测形状(`HTTP 4xx` + `code 10605 / subCode RESOURCE_LIMIT`):
|
|
3418
|
+
*
|
|
3419
|
+
* ```json
|
|
3420
|
+
* {"code":"10605","message":"{\"isQueued\":false,\"modelKey\":\"…\",
|
|
3421
|
+
* \"queueCount\":0,\"queueType\":\"p2\",\"retryAfterSeconds\":5,
|
|
3422
|
+
* \"serviceAvailable\":true,\"waitTime\":0}","subCode":"RESOURCE_LIMIT"}
|
|
3423
|
+
* ```
|
|
3424
|
+
*
|
|
3425
|
+
* 与 {@link deepestBusinessCode} 走同一条路(只沿 `message` 往里剥、有深度上限),
|
|
3426
|
+
* 因为这两个值在同一个信封里,分头解析迟早漂移。
|
|
3427
|
+
*
|
|
3428
|
+
* **只认 JSON 里的数字秒。** 不解析 HTTP `Retry-After` 头:宿主在 pi-ai 路由上
|
|
3429
|
+
* 只从文案分类、不读头(见 `llm-pi-ai/src/stream.ts` 的 `classifyPiAiError`),
|
|
3430
|
+
* 所以头带了也没人读;而这里读到的值会进文案,是**真的**能影响等待的那条路。
|
|
3431
|
+
* 头仍然照发(`Retry-After`),那是给别的消费者看的,不是本插件的判据。
|
|
3432
|
+
*
|
|
3433
|
+
* 上限 1 小时:超过就当上游没申报。一个离谱的值会让宿主放弃这次重试
|
|
3434
|
+
* (`llm-retry` 在 `> maxDelayMs` 时 `next()`),比不报更糟。
|
|
3435
|
+
*/
|
|
3436
|
+
const MAX_RETRY_AFTER_MS = 36e5;
|
|
3437
|
+
/**
|
|
3438
|
+
* 解析 HTTP `Retry-After` 头(两种合法形式:秒数 / HTTP-date)。
|
|
3439
|
+
*
|
|
3440
|
+
* 只作**兜底**:上游的申报值在 body 里(`retryAfterSeconds`),头是次要来源。
|
|
3441
|
+
* 判据同 {@link retryAfterMsOf}:正数、且不超过 1 小时。
|
|
3442
|
+
*/
|
|
3443
|
+
function retryAfterMsOfHeader(value, nowMs = Date.now()) {
|
|
3444
|
+
if (typeof value !== "string" || value.trim() === "") return void 0;
|
|
3445
|
+
const text = value.trim();
|
|
3446
|
+
if (/^\d+$/u.test(text)) {
|
|
3447
|
+
const seconds = Number(text);
|
|
3448
|
+
const ms = Math.round(seconds * 1e3);
|
|
3449
|
+
return ms > 0 && ms <= MAX_RETRY_AFTER_MS ? ms : void 0;
|
|
3450
|
+
}
|
|
3451
|
+
const at = Date.parse(text);
|
|
3452
|
+
if (!Number.isFinite(at)) return void 0;
|
|
3453
|
+
const ms = at - nowMs;
|
|
3454
|
+
return ms > 0 && ms <= MAX_RETRY_AFTER_MS ? ms : void 0;
|
|
3455
|
+
}
|
|
3456
|
+
function retryAfterMsOf(detail) {
|
|
3457
|
+
for (const record of envelopeRecords(detail)) {
|
|
3458
|
+
const seconds = record.retryAfterSeconds;
|
|
3459
|
+
if (typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0) {
|
|
3460
|
+
const ms = Math.round(seconds * 1e3);
|
|
3461
|
+
return ms <= MAX_RETRY_AFTER_MS ? ms : void 0;
|
|
3462
|
+
}
|
|
3463
|
+
}
|
|
3464
|
+
}
|
|
3465
|
+
/**
|
|
3466
|
+
* 沿一条失败信封往里剥,产出每一层的记录对象。
|
|
3467
|
+
*
|
|
3468
|
+
* **为什么需要它(issue #26)**:上游的信封有两种「往里包」的方式,两种都在
|
|
3469
|
+
* 现场出现过:
|
|
3470
|
+
*
|
|
3471
|
+
* ```json
|
|
3472
|
+
* { "code": "403", "message": "{\"code\":\"10605\",\"message\":\"…\"}" } // 字符串
|
|
3473
|
+
* { "code": "403", "message": "{\"code\":\"10605\",\"message\":{…}}" } // 对象
|
|
3474
|
+
* ```
|
|
3475
|
+
*
|
|
3476
|
+
* 第二种里,`message` **不是**字符串而是对象,而此前 `retryAfterMsOf` 与
|
|
3477
|
+
* `deepestBusinessCode` 都写着「`message` 是字符串才继续往里走」—— 于是
|
|
3478
|
+
* 走到第二层就停下,`retryAfterSeconds` 明明就在那层的 `message` 对象里,
|
|
3479
|
+
* 却读不出来。现场后果:上游说「等 30 秒」,插件读成「上游没说」,于是按
|
|
3480
|
+
* 30 分钟兜底冷却(差 60 倍)。
|
|
3481
|
+
*
|
|
3482
|
+
* 这里把「剥信封」收成**一处**实现,两个读者共用,避免两处再次漂移。深度
|
|
3483
|
+
* 上限沿用 {@link MAX_CODE_NESTING}。
|
|
3484
|
+
*/
|
|
3485
|
+
function envelopeRecords(detail) {
|
|
3486
|
+
const records = [];
|
|
3487
|
+
let text = typeof detail === "string" ? detail.trim() : "";
|
|
3488
|
+
for (let depth = 0; depth < MAX_CODE_NESTING; depth += 1) {
|
|
3489
|
+
let record;
|
|
3490
|
+
if (typeof text === "string") {
|
|
3491
|
+
if (!text.startsWith("{")) break;
|
|
3492
|
+
const parsed = parseJson(text);
|
|
3493
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) break;
|
|
3494
|
+
record = parsed;
|
|
3495
|
+
} else if (typeof text === "object" && text !== null && !Array.isArray(text)) record = text;
|
|
3496
|
+
else break;
|
|
3497
|
+
records.push(record);
|
|
3498
|
+
const message = record.message;
|
|
3499
|
+
if (typeof message === "string") text = message.trim();
|
|
3500
|
+
else if (typeof message === "object" && message !== null && !Array.isArray(message)) text = message;
|
|
3501
|
+
else break;
|
|
3502
|
+
}
|
|
3503
|
+
return records;
|
|
3504
|
+
}
|
|
3505
|
+
/**
|
|
3506
|
+
* 上游的排队状态(issue #26)。
|
|
3507
|
+
*
|
|
3508
|
+
* 判据是上游**自己说的** `isQueued: true`;`serviceAvailable` 一并带出
|
|
3509
|
+
* (issue #29):`true` 是「服务是好的,只是排在队里」,`false` 是「上游整体
|
|
3510
|
+
* 在拒服务」,两者对用户的行动指导完全不同 —— 判断见
|
|
3511
|
+
* {@link upstreamUnavailableOf}。返回 undefined 表示上游没提排队 —— 那时
|
|
3512
|
+
* 不许把任何失败说成「排队中」。
|
|
3513
|
+
*
|
|
3514
|
+
* `queueCount` 与 `retryAfterSeconds` 一并带出:前者让用户看到「排在第 1027
|
|
3515
|
+
* 位」,后者是「等 30 秒」—— 上游给了就显示,没给就不编。
|
|
3516
|
+
*/
|
|
3517
|
+
function queueOf(detail) {
|
|
3518
|
+
for (const record of envelopeRecords(detail)) {
|
|
3519
|
+
const isQueued = record.isQueued;
|
|
3520
|
+
if (typeof isQueued !== "boolean") continue;
|
|
3521
|
+
const count = record.queueCount;
|
|
3522
|
+
const queueType = record.queueType;
|
|
3523
|
+
const seconds = record.retryAfterSeconds;
|
|
3524
|
+
const serviceAvailable = record.serviceAvailable;
|
|
3525
|
+
return {
|
|
3526
|
+
isQueued,
|
|
3527
|
+
...typeof count === "number" && Number.isFinite(count) && count >= 0 ? { queueCount: count } : {},
|
|
3528
|
+
...typeof queueType === "string" && queueType !== "" ? { queueType } : {},
|
|
3529
|
+
...typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0 ? { retryAfterSeconds: seconds } : {},
|
|
3530
|
+
...typeof serviceAvailable === "boolean" ? { serviceAvailable } : {}
|
|
3531
|
+
};
|
|
3532
|
+
}
|
|
3533
|
+
}
|
|
3534
|
+
/**
|
|
3535
|
+
* 上游是不是在说「**整体**拒服务」,而不是「你这个账号在排队」(issue #29)。
|
|
3536
|
+
*
|
|
3537
|
+
* 判据只认上游自己给的字段,且必须是 `isQueued: true` + 显式的
|
|
3538
|
+
* `serviceAvailable: false` 两条同时成立:
|
|
3539
|
+
*
|
|
3540
|
+
* - 只有 `isQueued` 而没有 `serviceAvailable` ⇒ **不是**这个结论(上游没说,
|
|
3541
|
+
* 不推断;退回旧的「排队」语义)。
|
|
3542
|
+
* - `serviceAvailable: true` ⇒ 服务是好的,就是排队,正常等即可。
|
|
3543
|
+
*
|
|
3544
|
+
* 为什么要分开:现场证据(issue #29)里 `queueCount: 0` 与
|
|
3545
|
+
* `serviceAvailable: false` 同时出现 —— 队列里一个人都没有,是上游整体在拒。
|
|
3546
|
+
* 这种形态下换号、换 PAT 都无效,把它记成账号级冷却会误导用户去重配凭据。
|
|
3547
|
+
*/
|
|
3548
|
+
function upstreamUnavailableOf(queue) {
|
|
3549
|
+
if (queue === void 0) return false;
|
|
3550
|
+
if (queue.isQueued !== true) return false;
|
|
3551
|
+
return queue.serviceAvailable === false;
|
|
3552
|
+
}
|
|
3553
|
+
/**
|
|
3554
|
+
* 取**最深一层认识的**业务码(`{"code":"10605","message":"…"}`)。
|
|
3555
|
+
*
|
|
3556
|
+
* 为什么不能只看最外层(issue #6):上游的失败帧常是外层信封继续往里包,实拍帧:
|
|
3557
|
+
*
|
|
3558
|
+
* ```json
|
|
3559
|
+
* { "code": 403, "message": "{\"code\":\"10605\",\"message\":\"qmodel 排队中,请稍后重试\"}" }
|
|
3560
|
+
* ```
|
|
3561
|
+
*
|
|
3562
|
+
* 外层那个 `403` 是 HTTP 语义的码(`classifyBusinessCode('403')` → `unknown`),
|
|
3563
|
+
* 真正的业务码 `10605`(排队)藏在内层 `message` 里。只剥一层 ⇒ 读不到码 ⇒ 回落
|
|
3564
|
+
* HTTP 状态 ⇒ `403 → auth → credential-rejected → 永久剔除账号 + 叫用户换 PAT`。
|
|
3565
|
+
* 而 `10605`/`10408` 本来就在 `TRANSIENT_CODES` 里 —— 码表没缺,缺的是「读到它」。
|
|
3566
|
+
*
|
|
3567
|
+
* 三条纪律(都来自现场形态,不是风格偏好):
|
|
3568
|
+
*
|
|
3569
|
+
* 1. **只沿 `parsed.message` 往里走。** 改成遍历 `error`/`data`/`result` 之类更宽
|
|
3570
|
+
* 的键集合,会把外层信封那个 HTTP 语义的 `code`(或 `code: 0` 之类无关字段)
|
|
3571
|
+
* 当成业务码返回 —— 那比现在更糟,因为 `classifyBusinessCode` 一旦命中就可能
|
|
3572
|
+
* 盖住真码。
|
|
3573
|
+
* 2. **认不出的码要记进 `fallback` 并继续往里找**,不能直接 return。用例
|
|
3574
|
+
* 「外层 403 + 内层 10605/402」就靠这条才过:外层认不出、里层才认得出,先
|
|
3575
|
+
* 返回外层就还是 `auth`。
|
|
3576
|
+
* 3. **认不出就原样回落 `classifyHttpStatus`** —— `TOKEN_EXPIRE` 这类字符串码、
|
|
3577
|
+
* 非 JSON body、空 body 的行为与改动前逐字一致(真被拒的那一侧不能被改坏)。
|
|
3578
|
+
*/
|
|
3579
|
+
function deepestBusinessCode(detail) {
|
|
3580
|
+
let fallback;
|
|
3581
|
+
for (const record of envelopeRecords(detail)) {
|
|
3582
|
+
const raw = record.code;
|
|
3583
|
+
let code;
|
|
3584
|
+
if (typeof raw === "string" && raw !== "") code = raw;
|
|
3585
|
+
else if (typeof raw === "number" && Number.isInteger(raw)) code = String(raw);
|
|
3586
|
+
if (code !== void 0) {
|
|
3587
|
+
if (classifyBusinessCode(code) !== "unknown") return code;
|
|
3588
|
+
if (fallback === void 0) fallback = code;
|
|
3589
|
+
}
|
|
3590
|
+
}
|
|
3591
|
+
return fallback;
|
|
3592
|
+
}
|
|
3593
|
+
/**
|
|
3594
|
+
* 一次失败的分类:**业务码优先于 HTTP 状态**,状态只作兜底。
|
|
3595
|
+
*
|
|
3596
|
+
* 这是本轮的根因所在(用户实拍:国际版「Qoder 拒绝了这个账号的 PAT」)。实测
|
|
3597
|
+
* 上游对**当日用量用尽**回的是
|
|
3598
|
+
*
|
|
3599
|
+
* ```
|
|
3600
|
+
* HTTP 403 {"code":"110","message":"Billing daily count exceeded"}
|
|
3601
|
+
* ```
|
|
3602
|
+
*
|
|
3603
|
+
* 而旧实现只看状态:`403 → auth → credential-rejected → 「请添加新 PAT」`。
|
|
3604
|
+
* 那句话不只是文案难听 —— `credential-rejected` 在账号池里是**无条件永久排除**
|
|
3605
|
+
* (`exclusionOf` 连冷却期都不看,理由写得很对:令牌被拒,等也没用)。于是
|
|
3606
|
+
* 一个只是今天用满、明天自动恢复的账号被踢出池且**不会自愈**,同时被要求去做
|
|
3607
|
+
* 一件根本无效的事(换 PAT)。
|
|
3608
|
+
*
|
|
3609
|
+
* 官方码表(docs.qoder.com/zh/cli/sdk/errors)里 `105` 才是「登录态或 Access
|
|
3610
|
+
* Token 已过期」;`110`/`113`/`115`–`119`/`122` 全是**用量与配额**族。也就是说
|
|
3611
|
+
* 「403 就是凭据坏了」这个推断在协议层面根本不成立。
|
|
3612
|
+
*
|
|
3613
|
+
* 认识的码说了算;不认识的(如 `TOKEN_EXPIRE` 这类字符串码)回落状态分类,
|
|
3614
|
+
* 行为与改动前一致。
|
|
3615
|
+
*
|
|
3616
|
+
* 取码用 {@link deepestBusinessCode} 而不是 {@link businessCodeOf}:业务码可能
|
|
3617
|
+
* 藏在第二/三层包装里(issue #6 的实拍帧),只剥一层就会把「排队」当成
|
|
3618
|
+
* 「凭据被拒」,进而永久剔除一个其实几分钟就自愈的账号。
|
|
3619
|
+
*/
|
|
3620
|
+
function classifyFailure(status, detail) {
|
|
3621
|
+
const code = deepestBusinessCode(detail);
|
|
3622
|
+
if (code !== void 0) {
|
|
3623
|
+
const byCode = classifyBusinessCode(code);
|
|
3624
|
+
if (byCode !== "unknown") return byCode;
|
|
3625
|
+
}
|
|
3626
|
+
return classifyHttpStatus(status, detail);
|
|
3627
|
+
}
|
|
3628
|
+
/** 业务 code → 错误分类(官方码表,见 {@link classifyFailure})。 */
|
|
3629
|
+
function classifyBusinessCode(code) {
|
|
3630
|
+
if (code === "105") return "auth";
|
|
3631
|
+
if (QUOTA_CODES.has(code)) return "quota-exhausted";
|
|
3632
|
+
if (code === "406") return "content-policy";
|
|
3633
|
+
if (REQUEST_CODES.has(code)) return "invalid-request";
|
|
3634
|
+
if (TRANSIENT_CODES.has(code)) return "transient";
|
|
3635
|
+
return "unknown";
|
|
3636
|
+
}
|
|
3637
|
+
const QUOTA_CODES = /* @__PURE__ */ new Set([
|
|
3638
|
+
"110",
|
|
3639
|
+
"112",
|
|
3640
|
+
"113",
|
|
3641
|
+
"115",
|
|
3642
|
+
"116",
|
|
3643
|
+
"117",
|
|
3644
|
+
"118",
|
|
3645
|
+
"119",
|
|
3646
|
+
"122",
|
|
3647
|
+
"144",
|
|
3648
|
+
"147",
|
|
3649
|
+
"402",
|
|
3650
|
+
"6004"
|
|
3651
|
+
]);
|
|
3652
|
+
/** 416 范围/结构无法满足 · 430 能力不支持 · 80411 输入过长 · 80412 媒体过多。 */
|
|
3653
|
+
const REQUEST_CODES = /* @__PURE__ */ new Set([
|
|
3654
|
+
"416",
|
|
3655
|
+
"430",
|
|
3656
|
+
"80411",
|
|
3657
|
+
"80412"
|
|
3658
|
+
]);
|
|
3659
|
+
const TRANSIENT_CODES = /* @__PURE__ */ new Set([
|
|
3660
|
+
"500",
|
|
3661
|
+
"10408",
|
|
3662
|
+
"10500",
|
|
3663
|
+
"10605"
|
|
3664
|
+
]);
|
|
3665
|
+
const CONTENT_POLICY_MARKERS = [
|
|
3666
|
+
"DataInspectionFailed",
|
|
3667
|
+
"inappropriate content",
|
|
3668
|
+
"input text data may contain",
|
|
3669
|
+
"ContentFilter",
|
|
3670
|
+
"SensitiveContent"
|
|
3671
|
+
];
|
|
3672
|
+
function isContentPolicy(detail) {
|
|
3673
|
+
return CONTENT_POLICY_MARKERS.some((marker) => detail.includes(marker));
|
|
3674
|
+
}
|
|
3675
|
+
/** Parse JSON, or undefined when the body is not JSON at all. Never throws. */
|
|
3676
|
+
function parseJson(text) {
|
|
3677
|
+
try {
|
|
3678
|
+
return JSON.parse(text);
|
|
3679
|
+
} catch {
|
|
3680
|
+
return;
|
|
3681
|
+
}
|
|
3682
|
+
}
|
|
3683
|
+
function truncate(text, max) {
|
|
3684
|
+
return text.length <= max ? text : `${text.slice(0, max)}…`;
|
|
3685
|
+
}
|
|
3686
|
+
/**
|
|
3687
|
+
* 这次失败是不是「用户/宿主主动取消」。
|
|
3688
|
+
*
|
|
3689
|
+
* 取消必须**原样抛出**:它不是一个可以换节点重试的失败,退回默认网关再发一遍
|
|
3690
|
+
* 只会让一场已经结束的对话多打一次上游(还可能计一次费)。`signal.reason` 在
|
|
3691
|
+
* 不同运行时里是 `DOMException` 或普通 `Error`,所以按 `name` 判而不按类型。
|
|
3692
|
+
*/
|
|
3693
|
+
function isAbortError(error) {
|
|
3694
|
+
return error instanceof Error && error.name === "AbortError";
|
|
3695
|
+
}
|
|
3696
|
+
//#endregion
|
|
3697
|
+
//#region src/pi-ai-runtime.ts
|
|
3698
|
+
/**
|
|
3699
|
+
* Which `@earendil-works/pi-ai` copy THIS plugin actually resolves at runtime.
|
|
3700
|
+
*
|
|
3701
|
+
* 参考:dsh-connect-workbuddy(MIT,Copyright (c) 2026 LaoDing)的同名模块
|
|
3702
|
+
* 改动:纯改名移植(workbuddy → qoder,模块 doc 提及),检测机制与决策表原样沿用。
|
|
3703
|
+
*
|
|
3704
|
+
* WHY THIS EXISTS (issues #24 / #25 / #26, and the 0.2.1-rc.1 regression).
|
|
3705
|
+
* The plugin declares pi-ai as a peer (`>=0.85.0 <0.88.0 || >=1.0.0 <2.0.0`),
|
|
3706
|
+
* so the module it imports is whatever the host environment provides — and the
|
|
3707
|
+
* two generations consume DIFFERENT context shapes:
|
|
3708
|
+
*
|
|
3709
|
+
* - **modern** (0.87 … 1.x) hands providers a normalized transcript:
|
|
3710
|
+
* `{ messages: [ {role:'system', content, toolsAdded}, … ] }`. The system
|
|
3711
|
+
* prompt and the tool declarations live ONLY on that leading system message;
|
|
3712
|
+
* the top-level `systemPrompt` / `tools` fields are gone, and the api module
|
|
3713
|
+
* never reads them back. In 0.87 this normalization happens inside the api
|
|
3714
|
+
* modules; from 0.87/1.x it happens one layer up, in pi-ai's **Models layer**
|
|
3715
|
+
* (`createModels().stream*` → `normalizeContext`), which sits between the
|
|
3716
|
+
* host and the api module. Either way the api sees a transcript.
|
|
3717
|
+
* - **legacy** (0.85) expects `{ systemPrompt, tools, messages }` and has no
|
|
3718
|
+
* branch for a `system` message inside `messages` at all: its token
|
|
3719
|
+
* estimator crashes on one (issue #24), and its wire converter silently
|
|
3720
|
+
* drops it.
|
|
3721
|
+
*
|
|
3722
|
+
* Which copy resolves is NOT predictable from the host version alone: a
|
|
3723
|
+
* nested 0.85.1 on disk shadows the host's 0.87.1 (the plugin author's own
|
|
3724
|
+
* symlinked checkout does exactly that), while a clean market install has no
|
|
3725
|
+
* local copy at all and resolves the host's (issue #26's reporter). The
|
|
3726
|
+
* adapter therefore gates on what THIS plugin resolves.
|
|
3727
|
+
*
|
|
3728
|
+
* HOW it is detected — deliberately WITHOUT importing pi-ai:
|
|
3729
|
+
* `import.meta.resolve` locates the entry file (executing nothing), the
|
|
3730
|
+
* package manifest sitting beside it names the version, and the generation is
|
|
3731
|
+
* decided from that version (0.87+ **and every 1.x** → modern; see
|
|
3732
|
+
* {@link generationOf}, whose failure to handle the 1.x major was the
|
|
3733
|
+
* 0.2.1-rc.1 regression). A static import would drag
|
|
3734
|
+
* pi-ai into the standalone `doctor` CLI, which must also run from market
|
|
3735
|
+
* installs where NO local pi-ai exists and the module is only provided inside
|
|
3736
|
+
* the DSH host — a static import there is a load-time crash. Resolution
|
|
3737
|
+
* itself does not need the module: within the peer range, the manifest
|
|
3738
|
+
* version and the `normalizeContext` feature (present from 0.87 on, not
|
|
3739
|
+
* before) agree.
|
|
3740
|
+
*
|
|
3741
|
+
* When resolution FAILS — the normal state of a market install probed outside
|
|
3742
|
+
* the host — there is no local copy, so inside DSH the host supplies pi-ai.
|
|
3743
|
+
* Every DSH host that normalizes contexts (0.2.0+ ships 0.87.1; 0.2.1 ships
|
|
3744
|
+
* pi-ai 1.x) supplies a self-normalizing pi-ai, so the reported generation
|
|
3745
|
+
* defaults to `modern` (pass-through). That default is safe on older hosts
|
|
3746
|
+
* too: they never normalize, and a native 0.85-shaped context is an identity
|
|
3747
|
+
* under BOTH branches of the adapter gate.
|
|
3748
|
+
*
|
|
3749
|
+
* `doctor` prints the resolved version and path so mixed-generation setups —
|
|
3750
|
+
* the silent kind that produced #24 and #26 — become visible on demand.
|
|
3751
|
+
*
|
|
3752
|
+
* @module dsh-connect-qoder/pi-ai-runtime
|
|
3753
|
+
*/
|
|
3754
|
+
let cached;
|
|
3755
|
+
/** Resolve (once) which pi-ai copy this plugin runs against. */
|
|
3756
|
+
function piAiRuntimeInfo() {
|
|
3757
|
+
cached ??= piAiRuntimeFor(resolveModuleFile());
|
|
3758
|
+
return cached;
|
|
3759
|
+
}
|
|
3760
|
+
/**
|
|
3761
|
+
* The decision table for one resolution result, exported so the branch that
|
|
3762
|
+
* only ever runs on OTHER machines (a market install with no local pi-ai) is
|
|
3763
|
+
* pinned by tests rather than by this comment.
|
|
3764
|
+
*
|
|
3765
|
+
* `undefined` means nothing local resolved — inside DSH the host supplies the
|
|
3766
|
+
* module, and every host that normalizes contexts (0.2.0+, via 0.87.1) ships
|
|
3767
|
+
* the modern generation, so that is the default. Older hosts never normalize,
|
|
3768
|
+
* and their native 0.85-shaped context is an identity under either gate
|
|
3769
|
+
* branch, so the default cannot hurt them.
|
|
3770
|
+
*/
|
|
3771
|
+
function piAiRuntimeFor(resolvedFrom) {
|
|
3772
|
+
if (resolvedFrom === void 0) return {
|
|
3773
|
+
generation: "modern",
|
|
3774
|
+
resolvedFrom: void 0,
|
|
3775
|
+
version: void 0,
|
|
3776
|
+
resolvedLocally: false
|
|
3777
|
+
};
|
|
3778
|
+
const version = readVersion(resolvedFrom);
|
|
3779
|
+
return {
|
|
3780
|
+
generation: generationOf(version),
|
|
3781
|
+
resolvedFrom,
|
|
3782
|
+
version,
|
|
3783
|
+
resolvedLocally: true
|
|
3784
|
+
};
|
|
3785
|
+
}
|
|
3786
|
+
/**
|
|
3787
|
+
* The file the main entry resolved to; undefined when resolution itself fails.
|
|
3788
|
+
*
|
|
3789
|
+
* `import.meta.resolve` (not `require.resolve`): pi-ai's exports map exposes
|
|
3790
|
+
* "." under the `import` condition only, so the CJS resolver refuses the bare
|
|
3791
|
+
* specifier outright — the ESM resolver is the one this plugin actually
|
|
3792
|
+
* imports with, so it is also the one whose answer is meaningful here.
|
|
3793
|
+
*/
|
|
3794
|
+
function resolveModuleFile() {
|
|
3795
|
+
try {
|
|
3796
|
+
return fileURLToPath(import.meta.resolve("@earendil-works/pi-ai"));
|
|
3797
|
+
} catch {
|
|
3798
|
+
return;
|
|
3799
|
+
}
|
|
3800
|
+
}
|
|
3801
|
+
/**
|
|
3802
|
+
* The version of the package owning `moduleFile`. pi-ai's exports map does
|
|
3803
|
+
* not expose `./package.json`, so the manifest is found by walking up from
|
|
3804
|
+
* the resolved entry — `dist/index.js` sits directly inside the package —
|
|
3805
|
+
* and claiming it only when its `name` matches, so a same-named ancestor
|
|
3806
|
+
* (a pnpm virtual-store parent, for instance) cannot be misread.
|
|
3807
|
+
*/
|
|
3808
|
+
function readVersion(moduleFile) {
|
|
3809
|
+
if (moduleFile === void 0) return void 0;
|
|
3810
|
+
let directory = dirname(moduleFile);
|
|
3811
|
+
for (let depth = 0; depth < 4; depth++) {
|
|
3812
|
+
try {
|
|
3813
|
+
const parsed = JSON.parse(readFileSync(join(directory, "package.json"), "utf8"));
|
|
3814
|
+
if (parsed.name === "@earendil-works/pi-ai" && typeof parsed.version === "string") return parsed.version;
|
|
3815
|
+
} catch {}
|
|
3816
|
+
const parent = dirname(directory);
|
|
3817
|
+
if (parent === directory) return void 0;
|
|
3818
|
+
directory = parent;
|
|
3819
|
+
}
|
|
3820
|
+
}
|
|
3821
|
+
/**
|
|
3822
|
+
* The generation a manifest version belongs to.
|
|
3823
|
+
*
|
|
3824
|
+
* The context-shape split is by CAPABILITY, and it moved twice:
|
|
3825
|
+
*
|
|
3826
|
+
* - `0.87.x` … `0.x` — normalizes contexts in its api modules (`0.87+`).
|
|
3827
|
+
* - `1.x` — normalizes in the **Models layer** (`createModels().stream*` →
|
|
3828
|
+
* `normalizeContext`), which sits between the host and the api module. The
|
|
3829
|
+
* provider-facing contract is the same normalized transcript, so 1.x is
|
|
3830
|
+
* `modern` for this plugin's purposes.
|
|
3831
|
+
*
|
|
3832
|
+
* ⚠️ THE 1.x BRANCH IS THE 0.2.1-rc.1 REGRESSION. This function used to read
|
|
3833
|
+
* `/^0\.(\d+)\./` only, so any `1.x.y` failed to match and fell through to
|
|
3834
|
+
* `legacy`. The adapter then applied `adaptLegacyPiAiContext` to a transcript
|
|
3835
|
+
* that pi-ai had already normalized, and every request went upstream with NO
|
|
3836
|
+
* system prompt and NO tool declarations — silently (measured on the real
|
|
3837
|
+
* 0.2.1-rc.1 stack: `roles:["user"]`, `system:null`, `tools:0`).
|
|
3838
|
+
*
|
|
3839
|
+
* The guard that should have caught this did not: the old test recomputed the
|
|
3840
|
+
* SAME buggy formula (`minor >= 87`, which is `NaN >= 87 === false` for `1.x`)
|
|
3841
|
+
* and asserted `legacy`, so it certified the defect. The replacement asserts a
|
|
3842
|
+
* written-down version table instead of re-deriving it.
|
|
3843
|
+
*
|
|
3844
|
+
* A major version of 2 or more is unknown to this table, and an unreadable
|
|
3845
|
+
* version is unknown too. Both conservatively report `legacy`: the legacy
|
|
3846
|
+
* branch is the identity on an already-flat 0.85 context and its fold is a
|
|
3847
|
+
* no-op on a context that has no system message, so guessing `legacy` degrades
|
|
3848
|
+
* to "possibly a redundant fold" rather than "definitely drops the prompt".
|
|
3849
|
+
* `doctor` prints the resolved version so a guess is visible, not silent.
|
|
3850
|
+
*/
|
|
3851
|
+
function generationOf(version) {
|
|
3852
|
+
if (version === void 0) return "legacy";
|
|
3853
|
+
const match = /^(\d+)\.(\d+)\./u.exec(version);
|
|
3854
|
+
if (match === null) return "legacy";
|
|
3855
|
+
const major = Number(match[1]);
|
|
3856
|
+
const minor = Number(match[2]);
|
|
3857
|
+
if (major >= 1) return "modern";
|
|
3858
|
+
if (major === 0) return minor >= 87 ? "modern" : "legacy";
|
|
3859
|
+
return "legacy";
|
|
3860
|
+
}
|
|
3861
|
+
//#endregion
|
|
3862
|
+
//#region src/credentials.ts
|
|
3863
|
+
/**
|
|
3864
|
+
* Qoder 凭据解析:PAT(Personal Access Token)来源与账号 id 派生。
|
|
3865
|
+
*
|
|
3866
|
+
* PAT 优先级(每个区域独立):
|
|
3867
|
+
* 1. 设置卡片里用户显式填写的 PAT(`config.regions.<region>.pat`);
|
|
3868
|
+
* 2. 环境变量(`QODER_PERSONAL_ACCESS_TOKEN` / `QODERCN_PERSONAL_ACCESS_TOKEN`);
|
|
3869
|
+
* 3. 插件自有保险库(`src/accounts.ts`)里登记的其余 PAT。
|
|
3870
|
+
*
|
|
3871
|
+
* 说明:Qoder CLI 的交互式登录凭据(`~/.qoder/qoder-cli-credentials.json`
|
|
3872
|
+
* 等)是 AES-256-GCM 加密存储的,密钥派生在 qodercli 二进制内,插件不做
|
|
3873
|
+
* 二进制逆向;本插件通过 PAT 接入。
|
|
3874
|
+
*
|
|
3875
|
+
* @module dsh-connect-qoder/credentials
|
|
3876
|
+
*/
|
|
3877
|
+
/** 各区域对应的 PAT 环境变量名。 */
|
|
3878
|
+
const QODER_PAT_ENV_VARS = {
|
|
3879
|
+
global: "QODER_PERSONAL_ACCESS_TOKEN",
|
|
3880
|
+
cn: "QODERCN_PERSONAL_ACCESS_TOKEN"
|
|
3881
|
+
};
|
|
3882
|
+
/** 从环境变量取该区域的 PAT。 */
|
|
3883
|
+
function patFromEnv(region, env = process.env) {
|
|
3884
|
+
const value = env[QODER_PAT_ENV_VARS[region]]?.trim();
|
|
3885
|
+
return value ? value : void 0;
|
|
3886
|
+
}
|
|
3887
|
+
/**
|
|
3888
|
+
* 一个 PAT 的稳定账号 id:`pat-` + sha256 前 16 位十六进制。
|
|
3889
|
+
*
|
|
3890
|
+
* 为什么不用上游的 uid:jobToken 交换能给出 uid,但那要求添加/导入时
|
|
3891
|
+
* 必须联机,而且 vault 里还没验证过的记录会没有 id 可用。从 PAT 本身派生
|
|
3892
|
+
* 的 id 离线可得、永不变化,且单向散列不把 token 材料泄进设置文件、
|
|
3893
|
+
* 日志或浏览器快照(id 会出现在卡片的 DOM 与 URL 参数里)。
|
|
3894
|
+
*/
|
|
3895
|
+
function qoderAccountId(pat) {
|
|
3896
|
+
return `pat-${createHash("sha256").update(pat, "utf8").digest("hex").slice(0, 16)}`;
|
|
3897
|
+
}
|
|
3898
|
+
/** 判断一个 id 是否由本插件的 PAT 派生规则产生。 */
|
|
3899
|
+
function isQoderAccountId(id) {
|
|
3900
|
+
return /^pat-[0-9a-f]{16}$/.test(id);
|
|
3901
|
+
}
|
|
3902
|
+
/** 展示用的 PAT 掩码:只留头尾,绝不出现完整 token。 */
|
|
3903
|
+
function maskPat(pat) {
|
|
3904
|
+
if (pat.length <= 10) return "…";
|
|
3905
|
+
return `${pat.slice(0, 5)}…${pat.slice(-4)}`;
|
|
3906
|
+
}
|
|
3907
|
+
//#endregion
|
|
3908
|
+
//#region src/accounts.ts
|
|
3909
|
+
/**
|
|
3910
|
+
* Qoder 账号库:按区域隔离的 PAT 保险库 + 账号解析。
|
|
3911
|
+
*
|
|
3912
|
+
* 参考:dsh-connect-workbuddy(MIT,Copyright (c) 2026 LaoDing)的
|
|
3913
|
+
* `src/auth.ts` —— 插件自有凭据文件的约定(`$DSH_HOME` 下按区域分文件、
|
|
3914
|
+
* `withFileLock` + `writeFileAtomic`、`mode: 0o600`)、「账号列表与选中
|
|
3915
|
+
* 分离,选中存设置」「读取永不抛异常」的语义沿用其做法。
|
|
3916
|
+
* 改动:WorkBuddy 的账号来自桌面端登录文件 + OAuth 扫码;Qoder 的账号
|
|
3917
|
+
* 就是 PAT 本身,来源三种——设置卡片的 PAT 字段、环境变量、以及本模块
|
|
3918
|
+
* 维护的插件自有保险库(卡片「添加账号」与转账导入写入)。账号 id 由
|
|
3919
|
+
* PAT 单向派生(见 `credentials.ts` 的 `qoderAccountId`),不依赖联机
|
|
3920
|
+
* 验证,也不把 token 材料泄进 id。
|
|
3921
|
+
*
|
|
3922
|
+
* 本模块不碰网络:PAT 的有效性验证(jobToken 交换)在 Host 路由层完成,
|
|
3923
|
+
* 这里只负责持久化与解析。
|
|
3924
|
+
*
|
|
3925
|
+
* @module dsh-connect-qoder/accounts
|
|
3926
|
+
*/
|
|
3927
|
+
/** On-disk format version; readers reject anything else. */
|
|
3928
|
+
const VAULT_FORMAT_VERSION = 1;
|
|
3929
|
+
/** Filename prefix for one region's account vault. */
|
|
3930
|
+
const VAULT_PREFIX = ".qoder-accounts";
|
|
3931
|
+
/** Whether a parsed value looks like a stored account entry. */
|
|
3932
|
+
function isStoredAccount(value) {
|
|
3933
|
+
if (typeof value !== "object" || value === null) return false;
|
|
3934
|
+
const candidate = value;
|
|
3935
|
+
return typeof candidate["id"] === "string" && candidate["id"] !== "" && typeof candidate["pat"] === "string" && candidate["pat"] !== "" && typeof candidate["accountName"] === "string" && typeof candidate["addedAtMs"] === "number";
|
|
3936
|
+
}
|
|
3937
|
+
/** One region's vault path. */
|
|
3938
|
+
function qoderAccountsPath(region) {
|
|
3939
|
+
return join(resolveDshHome(), `${VAULT_PREFIX}.${region}.json`);
|
|
3940
|
+
}
|
|
3941
|
+
/**
|
|
3942
|
+
* One region's account store.
|
|
3943
|
+
*
|
|
3944
|
+
* Reads never throw: a missing, unreadable, malformed, or version-mismatched
|
|
3945
|
+
* vault all mean "no stored accounts", which is a valid state — the pool and
|
|
3946
|
+
* the card simply show an empty account list. Writes go through the file lock
|
|
3947
|
+
* and an atomic replace, same as the credential copies in the sibling plugin.
|
|
3948
|
+
*/
|
|
3949
|
+
var QoderAccountStore = class {
|
|
3950
|
+
region;
|
|
3951
|
+
constructor(region) {
|
|
3952
|
+
this.region = region;
|
|
3953
|
+
}
|
|
3954
|
+
/** The vault entries, in insertion order. */
|
|
3955
|
+
async vaultAccounts() {
|
|
3956
|
+
let raw;
|
|
3957
|
+
try {
|
|
3958
|
+
raw = await readFile(qoderAccountsPath(this.region), "utf8");
|
|
3959
|
+
} catch {
|
|
3960
|
+
return [];
|
|
3961
|
+
}
|
|
3962
|
+
let parsed;
|
|
3963
|
+
try {
|
|
3964
|
+
parsed = JSON.parse(raw);
|
|
3965
|
+
} catch {
|
|
3966
|
+
return [];
|
|
3967
|
+
}
|
|
3968
|
+
if (typeof parsed !== "object" || parsed === null) return [];
|
|
3969
|
+
const document = parsed;
|
|
3970
|
+
if (document.version !== VAULT_FORMAT_VERSION) return [];
|
|
3971
|
+
if (!Array.isArray(document.accounts)) return [];
|
|
3972
|
+
return document.accounts.filter(isStoredAccount);
|
|
3973
|
+
}
|
|
3974
|
+
/**
|
|
3975
|
+
* Every account this region can bill, merged from all three sources.
|
|
3976
|
+
*
|
|
3977
|
+
* Order is the resolution priority: the settings PAT first, then the
|
|
3978
|
+
* environment PAT, then the vault. A PAT appearing in two sources is listed
|
|
3979
|
+
* ONCE, under the higher-priority source — the id is derived from the PAT
|
|
3980
|
+
* itself, so duplicates are exact.
|
|
3981
|
+
*/
|
|
3982
|
+
async accounts(sources) {
|
|
3983
|
+
const out = [];
|
|
3984
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3985
|
+
const settingsPat = sources.settingsPat?.trim();
|
|
3986
|
+
if (settingsPat) {
|
|
3987
|
+
const id = qoderAccountId(settingsPat);
|
|
3988
|
+
seen.add(id);
|
|
3989
|
+
out.push({
|
|
3990
|
+
id,
|
|
3991
|
+
accountName: "",
|
|
3992
|
+
source: "settings"
|
|
3993
|
+
});
|
|
3994
|
+
}
|
|
3995
|
+
const envPat = sources.envPat?.trim();
|
|
3996
|
+
if (envPat) {
|
|
3997
|
+
const id = qoderAccountId(envPat);
|
|
3998
|
+
if (!seen.has(id)) {
|
|
3999
|
+
seen.add(id);
|
|
4000
|
+
out.push({
|
|
4001
|
+
id,
|
|
4002
|
+
accountName: "",
|
|
4003
|
+
source: "env"
|
|
4004
|
+
});
|
|
4005
|
+
}
|
|
4006
|
+
}
|
|
4007
|
+
for (const stored of await this.vaultAccounts()) {
|
|
4008
|
+
if (seen.has(stored.id)) continue;
|
|
4009
|
+
seen.add(stored.id);
|
|
4010
|
+
out.push({
|
|
4011
|
+
id: stored.id,
|
|
4012
|
+
accountName: stored.accountName,
|
|
4013
|
+
source: "vault"
|
|
4014
|
+
});
|
|
4015
|
+
}
|
|
4016
|
+
return out;
|
|
4017
|
+
}
|
|
4018
|
+
/**
|
|
4019
|
+
* The PAT for one account id, from whichever source holds it.
|
|
4020
|
+
*
|
|
4021
|
+
* Resolving by id — rather than touching the region's selection — is what
|
|
4022
|
+
* lets a pool batch address every account while the user's chosen account
|
|
4023
|
+
* keeps serving traffic.
|
|
4024
|
+
*/
|
|
4025
|
+
async credentialFor(accountId, sources) {
|
|
4026
|
+
const settingsPat = sources.settingsPat?.trim();
|
|
4027
|
+
if (settingsPat && qoderAccountId(settingsPat) === accountId) return {
|
|
4028
|
+
id: accountId,
|
|
4029
|
+
accountName: "",
|
|
4030
|
+
source: "settings",
|
|
4031
|
+
pat: settingsPat
|
|
4032
|
+
};
|
|
4033
|
+
const envPat = sources.envPat?.trim();
|
|
4034
|
+
if (envPat && qoderAccountId(envPat) === accountId) return {
|
|
4035
|
+
id: accountId,
|
|
4036
|
+
accountName: "",
|
|
4037
|
+
source: "env",
|
|
4038
|
+
pat: envPat
|
|
4039
|
+
};
|
|
4040
|
+
const stored = (await this.vaultAccounts()).find((account) => account.id === accountId);
|
|
4041
|
+
return stored === void 0 ? void 0 : {
|
|
4042
|
+
id: stored.id,
|
|
4043
|
+
accountName: stored.accountName,
|
|
4044
|
+
source: "vault",
|
|
4045
|
+
pat: stored.pat
|
|
4046
|
+
};
|
|
4047
|
+
}
|
|
4048
|
+
/**
|
|
4049
|
+
* The credential that serves traffic right now.
|
|
4050
|
+
*
|
|
4051
|
+
* `selectedId` is the user's explicit per-region choice (`''`/undefined =
|
|
4052
|
+
* automatic). Automatic resolution follows source priority: settings PAT,
|
|
4053
|
+
* then env PAT, then the first vault entry. An explicit id that resolves to
|
|
4054
|
+
* nothing falls back to automatic rather than stranding the region — the
|
|
4055
|
+
* card reports `selectionLost` so the user sees why.
|
|
4056
|
+
*/
|
|
4057
|
+
async resolve(sources, selectedId) {
|
|
4058
|
+
if (selectedId !== void 0 && selectedId !== "") {
|
|
4059
|
+
const chosen = await this.credentialFor(selectedId, sources);
|
|
4060
|
+
if (chosen !== void 0) return chosen;
|
|
4061
|
+
}
|
|
4062
|
+
const settingsPat = sources.settingsPat?.trim();
|
|
4063
|
+
if (settingsPat) return {
|
|
4064
|
+
id: qoderAccountId(settingsPat),
|
|
4065
|
+
accountName: "",
|
|
4066
|
+
source: "settings",
|
|
4067
|
+
pat: settingsPat
|
|
4068
|
+
};
|
|
4069
|
+
const envPat = sources.envPat?.trim();
|
|
4070
|
+
if (envPat) return {
|
|
4071
|
+
id: qoderAccountId(envPat),
|
|
4072
|
+
accountName: "",
|
|
4073
|
+
source: "env",
|
|
4074
|
+
pat: envPat
|
|
4075
|
+
};
|
|
4076
|
+
const first = (await this.vaultAccounts())[0];
|
|
4077
|
+
return first === void 0 ? void 0 : {
|
|
4078
|
+
id: first.id,
|
|
4079
|
+
accountName: first.accountName,
|
|
4080
|
+
source: "vault",
|
|
4081
|
+
pat: first.pat
|
|
4082
|
+
};
|
|
4083
|
+
}
|
|
4084
|
+
/**
|
|
4085
|
+
* Add (or refresh) one vault entry. Keyed by the PAT-derived id: re-adding
|
|
4086
|
+
* the same token updates its name in place rather than duplicating it.
|
|
4087
|
+
*/
|
|
4088
|
+
async add(pat, accountName) {
|
|
4089
|
+
const entry = {
|
|
4090
|
+
id: qoderAccountId(pat),
|
|
4091
|
+
accountName,
|
|
4092
|
+
pat,
|
|
4093
|
+
addedAtMs: Date.now()
|
|
4094
|
+
};
|
|
4095
|
+
await this.mutate((accounts) => {
|
|
4096
|
+
const index = accounts.findIndex((account) => account.id === entry.id);
|
|
4097
|
+
if (index === -1) return [...accounts, entry];
|
|
4098
|
+
const next = [...accounts];
|
|
4099
|
+
next[index] = {
|
|
4100
|
+
...next[index],
|
|
4101
|
+
accountName: entry.accountName,
|
|
4102
|
+
pat: entry.pat
|
|
4103
|
+
};
|
|
4104
|
+
return next;
|
|
4105
|
+
});
|
|
4106
|
+
return entry;
|
|
4107
|
+
}
|
|
4108
|
+
/**
|
|
4109
|
+
* Remove one vault entry. Only vault entries are removable — the settings
|
|
4110
|
+
* and env PATs are managed outside the plugin. Returns whether anything
|
|
4111
|
+
* was actually removed.
|
|
4112
|
+
*/
|
|
4113
|
+
async remove(accountId) {
|
|
4114
|
+
let removed = false;
|
|
4115
|
+
await this.mutate((accounts) => {
|
|
4116
|
+
const next = accounts.filter((account) => account.id !== accountId);
|
|
4117
|
+
removed = next.length !== accounts.length;
|
|
4118
|
+
return next;
|
|
4119
|
+
});
|
|
4120
|
+
return removed;
|
|
4121
|
+
}
|
|
4122
|
+
/** Backfill a display name learned later (from a jobToken exchange). */
|
|
4123
|
+
async rename(accountId, accountName) {
|
|
4124
|
+
if (accountName === "") return;
|
|
4125
|
+
await this.mutate((accounts) => accounts.map((account) => account.id === accountId && account.accountName !== accountName ? {
|
|
4126
|
+
...account,
|
|
4127
|
+
accountName
|
|
4128
|
+
} : account));
|
|
4129
|
+
}
|
|
4130
|
+
/** Empty the vault. Used by the CLI's `logout`. */
|
|
4131
|
+
async clear() {
|
|
4132
|
+
await this.mutate(() => []);
|
|
4133
|
+
}
|
|
4134
|
+
/** One locked read-modify-write of the vault document. */
|
|
4135
|
+
async mutate(edit) {
|
|
4136
|
+
const path = qoderAccountsPath(this.region);
|
|
4137
|
+
await withFileLock(path, async () => {
|
|
4138
|
+
const accounts = edit(await this.vaultAccounts());
|
|
4139
|
+
await writeFileAtomic(path, `${JSON.stringify({
|
|
4140
|
+
version: VAULT_FORMAT_VERSION,
|
|
4141
|
+
accounts
|
|
4142
|
+
}, null, 2)}\n`, {
|
|
4143
|
+
mode: 384,
|
|
4144
|
+
dirMode: 448
|
|
4145
|
+
});
|
|
4146
|
+
});
|
|
4147
|
+
}
|
|
4148
|
+
};
|
|
4149
|
+
//#endregion
|
|
4150
|
+
//#region src/version.ts
|
|
4151
|
+
/** The npm package version this build was produced from. */
|
|
4152
|
+
const QODER_CONNECT_VERSION = "1.28.0";
|
|
4153
|
+
//#endregion
|
|
4154
|
+
//#region src/account-pool-store.ts
|
|
4155
|
+
/**
|
|
4156
|
+
* The account pool's RUNTIME store: measured facts, on disk, outside settings.
|
|
4157
|
+
*
|
|
4158
|
+
* 参考:dingminhua/dsh-connect-workbuddy(MIT)的 `src/account-pool-store.ts`。
|
|
4159
|
+
* 改动:文件名前缀换成本插件的 `.qoder-pool`;其余逐行沿用 —— 同一套
|
|
4160
|
+
* `$DSH_HOME` 落盘约定(`withFileLock` + `writeFileAtomic`、`0o600`)、
|
|
4161
|
+
* 「观测数据与用户设置分开落盘」(否则卡片草稿保存会用几分钟前的草稿覆盖掉
|
|
4162
|
+
* 探测结果)、以及「读写从不抛异常给调用方」。
|
|
4163
|
+
*
|
|
4164
|
+
* @module dsh-connect-qoder/account-pool-store
|
|
4165
|
+
*/
|
|
4166
|
+
/** On-disk format version; readers reject anything else. */
|
|
4167
|
+
const STORE_FORMAT_VERSION = 1;
|
|
4168
|
+
/** Filename prefix for one region's measured pool facts. */
|
|
4169
|
+
const POOL_STORE_PREFIX = ".qoder-pool";
|
|
4170
|
+
/** Whether a parsed value looks like a stored probe. */
|
|
4171
|
+
function isProbe(value) {
|
|
4172
|
+
if (typeof value !== "object" || value === null) return false;
|
|
4173
|
+
const candidate = value;
|
|
4174
|
+
return typeof candidate["outcome"] === "string" && typeof candidate["atMs"] === "number" && (candidate["retryAtMs"] === void 0 || typeof candidate["retryAtMs"] === "number") && (candidate["message"] === void 0 || typeof candidate["message"] === "string") && (candidate["source"] === void 0 || typeof candidate["source"] === "string");
|
|
4175
|
+
}
|
|
4176
|
+
/**
|
|
4177
|
+
* 一条落盘的签到批次,形状不对就丢掉(不猜)。
|
|
4178
|
+
*
|
|
4179
|
+
* `validityDays` 必须是正的有限数:0 或负数会让「到期时刻」落在领取之前,
|
|
4180
|
+
* 于是「最近到期」被算成一个已经过去的时刻 —— 那正是 issue #31 前半要修的症状。
|
|
4181
|
+
*/
|
|
4182
|
+
function knownBatch(value) {
|
|
4183
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
4184
|
+
const record = value;
|
|
4185
|
+
const atMs = record["atMs"];
|
|
4186
|
+
const validityDays = record["validityDays"];
|
|
4187
|
+
const amount = record["amount"];
|
|
4188
|
+
if (typeof atMs !== "number" || !Number.isFinite(atMs) || atMs <= 0) return void 0;
|
|
4189
|
+
if (typeof validityDays !== "number" || !Number.isFinite(validityDays) || validityDays <= 0) return void 0;
|
|
4190
|
+
return {
|
|
4191
|
+
atMs,
|
|
4192
|
+
validityDays,
|
|
4193
|
+
...typeof amount === "number" && Number.isFinite(amount) ? { amount } : {}
|
|
4194
|
+
};
|
|
4195
|
+
}
|
|
4196
|
+
/** One region's path for measured pool facts. */
|
|
4197
|
+
function qoderPoolStorePath(region) {
|
|
4198
|
+
return join(resolveDshHome(), `${POOL_STORE_PREFIX}.${region}.json`);
|
|
4199
|
+
}
|
|
4200
|
+
/**
|
|
4201
|
+
* 读出整个文档;任何一项坏了只丢那一项,不连坐。
|
|
4202
|
+
*
|
|
4203
|
+
* 分成三项而不是一个联合类型:三者来自三个不同的上游事实(探针、签到数额、
|
|
4204
|
+
* 签到窗口),缺任何一项都**不影响**另外两项可用。旧文件没有 `credits` /
|
|
4205
|
+
* `windows` 两个键,读出来是空表 —— 这正是「这一版还没量过」的自然表达。
|
|
4206
|
+
*/
|
|
4207
|
+
async function readPoolDocument(region) {
|
|
4208
|
+
const empty = {
|
|
4209
|
+
probes: {},
|
|
4210
|
+
credits: {},
|
|
4211
|
+
windows: {}
|
|
4212
|
+
};
|
|
4213
|
+
let raw;
|
|
4214
|
+
try {
|
|
4215
|
+
raw = await readFile(qoderPoolStorePath(region), "utf8");
|
|
4216
|
+
} catch {
|
|
4217
|
+
return empty;
|
|
4218
|
+
}
|
|
4219
|
+
let parsed;
|
|
4220
|
+
try {
|
|
4221
|
+
parsed = JSON.parse(raw);
|
|
4222
|
+
} catch {
|
|
4223
|
+
return empty;
|
|
4224
|
+
}
|
|
4225
|
+
if (typeof parsed !== "object" || parsed === null) return empty;
|
|
4226
|
+
const document = parsed;
|
|
4227
|
+
if (document.version !== STORE_FORMAT_VERSION) return empty;
|
|
4228
|
+
if (typeof document.probes !== "object" || document.probes === null) return empty;
|
|
4229
|
+
const probes = {};
|
|
4230
|
+
for (const [accountId, probe] of Object.entries(document.probes)) {
|
|
4231
|
+
if (accountId === "" || !isProbe(probe)) continue;
|
|
4232
|
+
probes[accountId] = {
|
|
4233
|
+
outcome: probe.outcome,
|
|
4234
|
+
atMs: probe.atMs,
|
|
4235
|
+
...knownProbeSource(probe.source) === void 0 ? {} : { source: knownProbeSource(probe.source) },
|
|
4236
|
+
...probe.retryAtMs === void 0 ? {} : { retryAtMs: probe.retryAtMs },
|
|
4237
|
+
...knownRetrySource(probe.retrySource) === void 0 ? {} : { retrySource: knownRetrySource(probe.retrySource) },
|
|
4238
|
+
...knownQueue(probe.queue) === void 0 ? {} : { queue: knownQueue(probe.queue) },
|
|
4239
|
+
...probe.message === void 0 ? {} : { message: probe.message },
|
|
4240
|
+
...probe.modelId === void 0 || probe.modelId === "" ? {} : { modelId: probe.modelId }
|
|
4241
|
+
};
|
|
4242
|
+
}
|
|
4243
|
+
const credits = {};
|
|
4244
|
+
if (typeof document.credits === "object" && document.credits !== null) for (const [accountId, batches] of Object.entries(document.credits)) {
|
|
4245
|
+
if (accountId === "" || !Array.isArray(batches)) continue;
|
|
4246
|
+
const kept = batches.map(knownBatch).filter((b) => b !== void 0);
|
|
4247
|
+
if (kept.length > 0) credits[accountId] = kept;
|
|
4248
|
+
}
|
|
4249
|
+
const windows = {};
|
|
4250
|
+
if (typeof document.windows === "object" && document.windows !== null) for (const [accountId, atMs] of Object.entries(document.windows)) {
|
|
4251
|
+
if (accountId === "" || typeof atMs !== "number" || !Number.isFinite(atMs) || atMs <= 0) continue;
|
|
4252
|
+
windows[accountId] = atMs;
|
|
4253
|
+
}
|
|
4254
|
+
return {
|
|
4255
|
+
probes,
|
|
4256
|
+
credits,
|
|
4257
|
+
windows
|
|
4258
|
+
};
|
|
4259
|
+
}
|
|
4260
|
+
/**
|
|
4261
|
+
* 落盘的排队信息,只保留形状对的那些字段(issue #26)。
|
|
4262
|
+
*
|
|
4263
|
+
* 形状不对就返回 undefined(**丢掉**而不是留半个对象)—— 半个对象读起来会像
|
|
4264
|
+
* 「上游说队列里有 0 个人」,那不是上游说过的话。
|
|
4265
|
+
*/
|
|
4266
|
+
function knownQueue(value) {
|
|
4267
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
4268
|
+
const record = value;
|
|
4269
|
+
const count = record["queueCount"];
|
|
4270
|
+
const type = record["queueType"];
|
|
4271
|
+
const out = {};
|
|
4272
|
+
if (typeof count === "number" && Number.isFinite(count) && count >= 0) out.queueCount = count;
|
|
4273
|
+
if (typeof type === "string" && type !== "") out.queueType = type;
|
|
4274
|
+
return Object.keys(out).length === 0 ? void 0 : out;
|
|
4275
|
+
}
|
|
4276
|
+
/** A stored source string reduced to a source this build understands. */
|
|
4277
|
+
function knownProbeSource(value) {
|
|
4278
|
+
return value === "test-batch" || value === "live-request" ? value : void 0;
|
|
4279
|
+
}
|
|
4280
|
+
/** 同上,`retryAtMs` 的来源(issue #32);不认识的丢掉。 */
|
|
4281
|
+
function knownRetrySource(value) {
|
|
4282
|
+
switch (value) {
|
|
4283
|
+
case "retry-after":
|
|
4284
|
+
case "upstream-message":
|
|
4285
|
+
case "quota-refresh":
|
|
4286
|
+
case "upstream-reported":
|
|
4287
|
+
case "unknown-cooldown": return value;
|
|
4288
|
+
default: return;
|
|
4289
|
+
}
|
|
4290
|
+
}
|
|
4291
|
+
/**
|
|
4292
|
+
* Merge measurements into one region's store and write it atomically.
|
|
4293
|
+
*
|
|
4294
|
+
* A MERGE rather than a replace, because batches measure one account at a time
|
|
4295
|
+
* and a partial failure must not erase what earlier runs learned. Never
|
|
4296
|
+
* throws: a failed write loses only the newest measurements.
|
|
4297
|
+
*/
|
|
4298
|
+
async function writePoolProbes(region, updates) {
|
|
4299
|
+
await writePoolDocument(region, { probes: updates });
|
|
4300
|
+
}
|
|
4301
|
+
/**
|
|
4302
|
+
* 合并写整个文档:三个键各自 merge,只写调用方给了的那一项。
|
|
4303
|
+
*
|
|
4304
|
+
* 为什么不复用 `writePoolProbes` 再读改写:那会把「读」放在锁外,两个不同的
|
|
4305
|
+
* 写入者(探针与签到)交错时后写的会吞掉先写的。这里在**同一次** `withFileLock`
|
|
4306
|
+
* 里读、合并、写。
|
|
4307
|
+
*/
|
|
4308
|
+
async function writePoolDocument(region, updates) {
|
|
4309
|
+
const probes = updates.probes ?? {};
|
|
4310
|
+
const credits = updates.credits ?? {};
|
|
4311
|
+
const windows = updates.windows ?? {};
|
|
4312
|
+
if (Object.keys(probes).length === 0 && Object.keys(credits).length === 0 && Object.keys(windows).length === 0) return;
|
|
4313
|
+
const path = qoderPoolStorePath(region);
|
|
4314
|
+
try {
|
|
4315
|
+
await withFileLock(path, async () => {
|
|
4316
|
+
const existing = await readPoolDocument(region);
|
|
4317
|
+
const mergedCredits = { ...existing.credits };
|
|
4318
|
+
for (const [accountId, batches] of Object.entries(credits)) mergedCredits[accountId] = [...batches];
|
|
4319
|
+
const document = {
|
|
4320
|
+
version: STORE_FORMAT_VERSION,
|
|
4321
|
+
probes: {
|
|
4322
|
+
...existing.probes,
|
|
4323
|
+
...probes
|
|
4324
|
+
},
|
|
4325
|
+
credits: mergedCredits,
|
|
4326
|
+
windows: {
|
|
4327
|
+
...existing.windows,
|
|
4328
|
+
...windows
|
|
4329
|
+
}
|
|
4330
|
+
};
|
|
4331
|
+
await writeFileAtomic(path, `${JSON.stringify(document, null, 2)}\n`, {
|
|
4332
|
+
mode: 384,
|
|
4333
|
+
dirMode: 448
|
|
4334
|
+
});
|
|
4335
|
+
});
|
|
4336
|
+
} catch {}
|
|
4337
|
+
}
|
|
4338
|
+
//#endregion
|
|
4339
|
+
//#region src/host-heartbeat.ts
|
|
4340
|
+
/**
|
|
4341
|
+
* Host-side heartbeat: a small JSON file written under `$DSH_HOME` once the
|
|
4342
|
+
* `qoder` provider is registered. The status CLI reads it to report
|
|
4343
|
+
* whether the host bundle is alive, independent of the browser card.
|
|
4344
|
+
*
|
|
4345
|
+
* 参考:corrinehu/dsh-workbuddy-connect(MIT,Copyright (c) 2026 Corrine Hu)
|
|
4346
|
+
* — 该机制由其设计:浏览器端无法写文件,其健康只能靠 console.error 上报,
|
|
4347
|
+
* 因此由宿主写心跳文件,缺失即代表宿主从未启动;崩溃后的陈旧心跳
|
|
4348
|
+
* 通过 PID 存活检查识别。
|
|
4349
|
+
* 参考:dsh-connect-workbuddy(MIT,Copyright (c) 2026 LaoDing)的同名模块
|
|
4350
|
+
* 改动:纯改名移植(WorkBuddy → Qoder,包名/版本常量/心跳文件名),机制、
|
|
4351
|
+
* `windowsHide`、PID 与 start-time 逻辑原样沿用。
|
|
4352
|
+
*
|
|
4353
|
+
* @module dsh-connect-qoder/host-heartbeat
|
|
4354
|
+
*/
|
|
4355
|
+
/** Basename of the host heartbeat file inside the Harness home. */
|
|
4356
|
+
const QODER_HOST_HEARTBEAT_FILENAME = ".qoder-host-heartbeat.json";
|
|
4357
|
+
/** Current on-disk heartbeat format; readers reject others. */
|
|
4358
|
+
const HEARTBEAT_FORMAT_VERSION = 1;
|
|
4359
|
+
/** Absolute path of the host heartbeat file. */
|
|
4360
|
+
function qoderHostHeartbeatPath() {
|
|
4361
|
+
return join(resolveDshHome(), QODER_HOST_HEARTBEAT_FILENAME);
|
|
4362
|
+
}
|
|
4363
|
+
/**
|
|
4364
|
+
* Spawn options every external probe in this module is run with.
|
|
4365
|
+
*
|
|
4366
|
+
* `windowsHide` is REQUIRED here, not cosmetic. Windows hands a console-program
|
|
4367
|
+
* child a brand-new console window whenever its PARENT has none — and the
|
|
4368
|
+
* parent frequently has none: the DSH Desktop host is an Electron GUI process
|
|
4369
|
+
* (`MainWindowHandle = 0`, verified on the live host), as are Task Scheduler
|
|
4370
|
+
* jobs and CI services. That window is created VISIBLE, so every start-time
|
|
4371
|
+
* probe would flash a black box on the user's screen.
|
|
4372
|
+
*
|
|
4373
|
+
* Evidence (real Windows 11, parent created console-less through the WMI
|
|
4374
|
+
* service — the same condition as the Electron host; the child reports the
|
|
4375
|
+
* console it actually owns):
|
|
4376
|
+
*
|
|
4377
|
+
* - without `windowsHide`: `NEW-console hwnd=1573500 visible=True`
|
|
4378
|
+
* - with `windowsHide: true`: `no-console`
|
|
4379
|
+
*
|
|
4380
|
+
* Invoked from a terminal the parent HAS a console and the child simply
|
|
4381
|
+
* inherits it (no new window), which is why this never showed up in local
|
|
4382
|
+
* runs — the same blind spot `docs/WINDOWS.md` §0 describes. The sibling call
|
|
4383
|
+
* site `src/at-rest.ts` (the at-rest key fetch) already sets this option; this
|
|
4384
|
+
* module did not, and that inconsistency is what the test pins.
|
|
4385
|
+
*
|
|
4386
|
+
* On POSIX the option is ignored.
|
|
4387
|
+
*/
|
|
4388
|
+
const PROCESS_PROBE_OPTIONS = {
|
|
4389
|
+
encoding: "utf8",
|
|
4390
|
+
windowsHide: true
|
|
4391
|
+
};
|
|
4392
|
+
/**
|
|
4393
|
+
* The command one start-time probe runs, per platform.
|
|
4394
|
+
*
|
|
4395
|
+
* Split out as a value so the spawn can be asserted WITHOUT a Windows machine:
|
|
4396
|
+
* `tests/host-heartbeat.spec.ts` checks the platform branch and the options
|
|
4397
|
+
* object directly, which is the only way a Windows-only spawn defect here can
|
|
4398
|
+
* be caught on the macOS development machine (§0: not "unreproduced" but
|
|
4399
|
+
* "impossible to reproduce").
|
|
4400
|
+
*
|
|
4401
|
+
* `platform` is injectable for the same reason, in the same spirit as
|
|
4402
|
+
* `defaultDesktopAuthDirs()` and `qoderAppExecutableCandidates()`.
|
|
4403
|
+
*/
|
|
4404
|
+
function processStartProbe(pid, platform = process.platform) {
|
|
4405
|
+
if (platform === "win32") return {
|
|
4406
|
+
file: "powershell",
|
|
4407
|
+
args: [
|
|
4408
|
+
"-NoProfile",
|
|
4409
|
+
"-NonInteractive",
|
|
4410
|
+
"-Command",
|
|
4411
|
+
`(Get-Process -Id ${pid} -ErrorAction SilentlyContinue).StartTime.ToUniversalTime().ToString('o')`
|
|
4412
|
+
]
|
|
4413
|
+
};
|
|
4414
|
+
return {
|
|
4415
|
+
file: "ps",
|
|
4416
|
+
args: [
|
|
4417
|
+
"-o",
|
|
4418
|
+
"lstart=",
|
|
4419
|
+
"-p",
|
|
4420
|
+
String(pid)
|
|
4421
|
+
]
|
|
4422
|
+
};
|
|
4423
|
+
}
|
|
4424
|
+
/**
|
|
4425
|
+
* Process start time in epoch milliseconds; undefined when unavailable.
|
|
4426
|
+
*
|
|
4427
|
+
* POSIX reads `ps -o lstart=`; Windows has no such command, so the creation
|
|
4428
|
+
* time is taken from PowerShell's `Get-Process` StartTime, emitted as UTC ISO
|
|
4429
|
+
* 8601 so `Date.parse` understands it without locale assumptions. Absent or
|
|
4430
|
+
* unqueryable processes (other users' processes) degrade to undefined.
|
|
4431
|
+
*/
|
|
4432
|
+
function processStartTimeMs(pid) {
|
|
4433
|
+
try {
|
|
4434
|
+
const probe = processStartProbe(pid);
|
|
4435
|
+
const output = execFileSync(probe.file, probe.args, PROCESS_PROBE_OPTIONS);
|
|
4436
|
+
const parsed = Date.parse(output.trim());
|
|
4437
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
4438
|
+
} catch {
|
|
4439
|
+
return;
|
|
4440
|
+
}
|
|
4441
|
+
}
|
|
4442
|
+
/**
|
|
4443
|
+
* Whether the recorded host process still matches the heartbeat's PID.
|
|
4444
|
+
*
|
|
4445
|
+
* A PID can be reused after a crash, so the recorded start time is compared
|
|
4446
|
+
* against the live process: a different start time means a different process.
|
|
4447
|
+
*/
|
|
4448
|
+
function isHeartbeatProcessAlive(heartbeat) {
|
|
4449
|
+
if (!Number.isInteger(heartbeat.pid) || heartbeat.pid <= 0) return false;
|
|
4450
|
+
try {
|
|
4451
|
+
process.kill(heartbeat.pid, 0);
|
|
4452
|
+
} catch {
|
|
4453
|
+
return false;
|
|
4454
|
+
}
|
|
4455
|
+
const startedAt = processStartTimeMs(heartbeat.pid);
|
|
4456
|
+
if (startedAt === void 0) return true;
|
|
4457
|
+
return Math.abs(startedAt - heartbeat.registeredAt) < 6e4;
|
|
4458
|
+
}
|
|
4459
|
+
/** Read the heartbeat; absent or unparsable files report undefined. */
|
|
4460
|
+
async function readHostHeartbeat() {
|
|
4461
|
+
try {
|
|
4462
|
+
const parsed = JSON.parse(await readFile(qoderHostHeartbeatPath(), "utf8"));
|
|
4463
|
+
if (typeof parsed !== "object" || parsed === null) return void 0;
|
|
4464
|
+
const document = parsed;
|
|
4465
|
+
if (document["version"] !== HEARTBEAT_FORMAT_VERSION) return void 0;
|
|
4466
|
+
if (document["package"] !== "dsh-connect-qoder") return void 0;
|
|
4467
|
+
const pid = document["pid"];
|
|
4468
|
+
const registeredAt = document["registeredAt"];
|
|
4469
|
+
if (typeof pid !== "number" || typeof registeredAt !== "number") return void 0;
|
|
4470
|
+
return {
|
|
4471
|
+
version: HEARTBEAT_FORMAT_VERSION,
|
|
4472
|
+
package: "dsh-connect-qoder",
|
|
4473
|
+
pluginVersion: typeof document["pluginVersion"] === "string" ? document["pluginVersion"] : QODER_CONNECT_VERSION,
|
|
4474
|
+
registeredAt,
|
|
4475
|
+
pid
|
|
4476
|
+
};
|
|
4477
|
+
} catch {
|
|
4478
|
+
return;
|
|
4479
|
+
}
|
|
4480
|
+
}
|
|
4481
|
+
/** Write the heartbeat for the current process. */
|
|
4482
|
+
async function writeHostHeartbeat() {
|
|
4483
|
+
const heartbeat = {
|
|
4484
|
+
version: HEARTBEAT_FORMAT_VERSION,
|
|
4485
|
+
package: "dsh-connect-qoder",
|
|
4486
|
+
pluginVersion: QODER_CONNECT_VERSION,
|
|
4487
|
+
registeredAt: Date.now(),
|
|
4488
|
+
pid: process.pid
|
|
4489
|
+
};
|
|
4490
|
+
await writeFile(qoderHostHeartbeatPath(), `${JSON.stringify(heartbeat, null, 2)}\n`, { mode: 384 });
|
|
4491
|
+
}
|
|
4492
|
+
/** Remove the heartbeat; called when the plugin is disposed. */
|
|
4493
|
+
async function clearHostHeartbeat() {
|
|
4494
|
+
await rm(qoderHostHeartbeatPath(), { force: true });
|
|
4495
|
+
}
|
|
4496
|
+
//#endregion
|
|
4497
|
+
export { QODER_GITHUB_URL as A, QODER_TRANSFER_PATH as B, upstreamUnavailableOf as C, QODER_ACCOUNTS_REFRESH_PATH as D, QODER_ACCOUNTS_PATH as E, QODER_REGIONS$1 as F, poolAccountIdOf as G, accountActionOf as H, QODER_REGION_TRANSFER_DOMAIN as I, sidebarPanelEnabledOf as J, poolActionOf as K, QODER_SAVE_PATH as L, QODER_POLL_MINUTES_FIELD as M, QODER_POOL_PATH as N, QODER_ACCOUNT_CREDITS_PATH as O, QODER_PROBE_PATH as P, QODER_SETTINGS_NS as R, isQoderUpstreamError as S, isRouterModelId as T, fastDetailOf as U, QODER_USAGE_PATH as V, pollMinutesOf as W, unwrapVolatileDeep as X, transferActionOf as Y, deriveFingerprint as Z, qoderAccountId as _, writeHostHeartbeat as a, QoderUpstreamClient as b, writePoolDocument as c, QoderAccountStore as d, qoderAccountsPath as f, patFromEnv as g, maskPat as h, readHostHeartbeat as i, QODER_MODELS_REFRESH_PATH as j, QODER_CAMPAIGNS_PATH as k, writePoolProbes as l, isQoderAccountId as m, isHeartbeatProcessAlive as n, qoderPoolStorePath as o, QODER_PAT_ENV_VARS as p, regionOfStatusUrl as q, qoderHostHeartbeatPath as r, readPoolDocument as s, clearHostHeartbeat as t, QODER_CONNECT_VERSION as u, piAiRuntimeInfo as v, imageDefaultFor as w, QoderUpstreamError as x, QODER_REGIONS as y, QODER_SIDEBAR_PANEL_FIELD as z };
|