@yzdys/dsh-connect-madao 0.0.0-stage → 0.12.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 +181 -0
- package/FAQ.md +327 -0
- package/INSTALL.md +284 -0
- package/LICENSE +21 -0
- package/README.md +326 -2
- package/cordis.patch.yml +5 -0
- package/icons/dsh-connect-madao-128.png +0 -0
- package/lib/bin.js +3062 -0
- package/lib/client.js +1581 -0
- package/lib/index.d.ts +83 -0
- package/lib/index.js +4212 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +85 -4
package/lib/bin.js
ADDED
|
@@ -0,0 +1,3062 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
4
|
+
var __esm = (fn2, res, err) => function __init() {
|
|
5
|
+
if (err) throw err[0];
|
|
6
|
+
try {
|
|
7
|
+
return fn2 && (res = (0, fn2[__getOwnPropNames(fn2)[0]])(fn2 = 0)), res;
|
|
8
|
+
} catch (e) {
|
|
9
|
+
throw err = [e], e;
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
var __export = (target, all) => {
|
|
13
|
+
for (var name in all)
|
|
14
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
// src/protocol/sign.ts
|
|
18
|
+
import { createHash, createHmac } from "node:crypto";
|
|
19
|
+
function formatSdkDate(d = /* @__PURE__ */ new Date()) {
|
|
20
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
21
|
+
return `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}T${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}Z`;
|
|
22
|
+
}
|
|
23
|
+
function canonicalUri(pathname) {
|
|
24
|
+
const encoded = pathname.split("/").map((seg) => encodeURIComponent(seg)).join("/");
|
|
25
|
+
return encoded.endsWith("/") ? encoded : `${encoded}/`;
|
|
26
|
+
}
|
|
27
|
+
function canonicalHeaders(headers) {
|
|
28
|
+
const lower = /* @__PURE__ */ new Map();
|
|
29
|
+
for (const [k, v] of Object.entries(headers)) lower.set(k.toLowerCase(), v);
|
|
30
|
+
const names = [...lower.keys()].sort((a, b) => a.localeCompare(b));
|
|
31
|
+
const block = names.map((n) => `${n}:${(lower.get(n) ?? "").replace(/[\r\n]/g, " ").trim()}
|
|
32
|
+
`).join("");
|
|
33
|
+
return { block, signed: names.join(";") };
|
|
34
|
+
}
|
|
35
|
+
function signRequest(input) {
|
|
36
|
+
const { method, url, contentType, credentials } = input;
|
|
37
|
+
const sdkDate = input.sdkDate ?? formatSdkDate();
|
|
38
|
+
const payloadHash = input.bodyBytes ? createHash("sha256").update(input.bodyBytes).digest("hex") : createHash("sha256").update(input.body ?? "").digest("hex");
|
|
39
|
+
const host = url.port && !isDefaultPort(url.protocol, url.port) ? `${url.hostname}:${url.port}` : url.hostname;
|
|
40
|
+
const toSign = {
|
|
41
|
+
Host: host,
|
|
42
|
+
"X-Sdk-Date": sdkDate,
|
|
43
|
+
"X-Security-Token": credentials.securityToken
|
|
44
|
+
};
|
|
45
|
+
if (contentType) toSign["Content-Type"] = contentType;
|
|
46
|
+
const { block, signed } = canonicalHeaders(toSign);
|
|
47
|
+
const canonicalRequest = [
|
|
48
|
+
method.toUpperCase(),
|
|
49
|
+
canonicalUri(url.pathname),
|
|
50
|
+
url.search ? url.search.slice(1) : "",
|
|
51
|
+
block,
|
|
52
|
+
signed,
|
|
53
|
+
payloadHash
|
|
54
|
+
].join("\n");
|
|
55
|
+
const stringToSign = [
|
|
56
|
+
SIGN_ALGO,
|
|
57
|
+
sdkDate,
|
|
58
|
+
createHash("sha256").update(canonicalRequest).digest("hex")
|
|
59
|
+
].join("\n");
|
|
60
|
+
const signature = createHmac("sha256", credentials.sk).update(stringToSign).digest("hex");
|
|
61
|
+
const out = {
|
|
62
|
+
Host: host,
|
|
63
|
+
"X-Sdk-Date": sdkDate,
|
|
64
|
+
"X-Security-Token": credentials.securityToken,
|
|
65
|
+
Authorization: `${SIGN_ALGO} Access=${credentials.ak}, SignedHeaders=${signed}, Signature=${signature}`
|
|
66
|
+
};
|
|
67
|
+
if (contentType) out["Content-Type"] = contentType;
|
|
68
|
+
return out;
|
|
69
|
+
}
|
|
70
|
+
function isDefaultPort(protocol, port) {
|
|
71
|
+
return protocol === "https:" && port === "443" || protocol === "http:" && port === "80";
|
|
72
|
+
}
|
|
73
|
+
var SIGN_ALGO;
|
|
74
|
+
var init_sign = __esm({
|
|
75
|
+
"src/protocol/sign.ts"() {
|
|
76
|
+
SIGN_ALGO = "SDK-HMAC-SHA256";
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
// src/protocol/sm4.ts
|
|
81
|
+
function rotl(x, n) {
|
|
82
|
+
n &= 31;
|
|
83
|
+
return (x << n | x >>> 32 - n) >>> 0;
|
|
84
|
+
}
|
|
85
|
+
function tau(a) {
|
|
86
|
+
return (SBOX[a >>> 24 & 255] << 24 | SBOX[a >>> 16 & 255] << 16 | SBOX[a >>> 8 & 255] << 8 | SBOX[a & 255]) >>> 0;
|
|
87
|
+
}
|
|
88
|
+
function t1(x) {
|
|
89
|
+
const a = tau(x);
|
|
90
|
+
return (a ^ rotl(a, 2) ^ rotl(a, 10) ^ rotl(a, 18) ^ rotl(a, 24)) >>> 0;
|
|
91
|
+
}
|
|
92
|
+
function t2(x) {
|
|
93
|
+
const a = tau(x);
|
|
94
|
+
return (a ^ rotl(a, 13) ^ rotl(a, 23)) >>> 0;
|
|
95
|
+
}
|
|
96
|
+
function u32be(b, off) {
|
|
97
|
+
return (b[off] << 24 | b[off + 1] << 16 | b[off + 2] << 8 | b[off + 3]) >>> 0;
|
|
98
|
+
}
|
|
99
|
+
function w32be(b, off, v) {
|
|
100
|
+
b[off] = v >>> 24 & 255;
|
|
101
|
+
b[off + 1] = v >>> 16 & 255;
|
|
102
|
+
b[off + 2] = v >>> 8 & 255;
|
|
103
|
+
b[off + 3] = v & 255;
|
|
104
|
+
}
|
|
105
|
+
function expandKey(key) {
|
|
106
|
+
const k = new Uint32Array(36);
|
|
107
|
+
k[0] = (u32be(key, 0) ^ FK[0]) >>> 0;
|
|
108
|
+
k[1] = (u32be(key, 4) ^ FK[1]) >>> 0;
|
|
109
|
+
k[2] = (u32be(key, 8) ^ FK[2]) >>> 0;
|
|
110
|
+
k[3] = (u32be(key, 12) ^ FK[3]) >>> 0;
|
|
111
|
+
const rk = new Uint32Array(32);
|
|
112
|
+
for (let i = 0; i < 32; i++) {
|
|
113
|
+
k[i + 4] = (k[i] ^ t2((k[i + 1] ^ k[i + 2] ^ k[i + 3] ^ CK[i]) >>> 0)) >>> 0;
|
|
114
|
+
rk[i] = k[i + 4];
|
|
115
|
+
}
|
|
116
|
+
return rk;
|
|
117
|
+
}
|
|
118
|
+
function sm4Block(rk, input, off, out, outOff) {
|
|
119
|
+
const x = new Uint32Array(36);
|
|
120
|
+
x[0] = u32be(input, off);
|
|
121
|
+
x[1] = u32be(input, off + 4);
|
|
122
|
+
x[2] = u32be(input, off + 8);
|
|
123
|
+
x[3] = u32be(input, off + 12);
|
|
124
|
+
for (let i = 0; i < 32; i++) {
|
|
125
|
+
x[i + 4] = (x[i] ^ t1((x[i + 1] ^ x[i + 2] ^ x[i + 3] ^ rk[i]) >>> 0)) >>> 0;
|
|
126
|
+
}
|
|
127
|
+
w32be(out, outOff, x[35]);
|
|
128
|
+
w32be(out, outOff + 4, x[34]);
|
|
129
|
+
w32be(out, outOff + 8, x[33]);
|
|
130
|
+
w32be(out, outOff + 12, x[32]);
|
|
131
|
+
}
|
|
132
|
+
function gfMul(x, y) {
|
|
133
|
+
const z = new Uint8Array(16);
|
|
134
|
+
const v = new Uint8Array(y);
|
|
135
|
+
for (let i = 0; i < 128; i++) {
|
|
136
|
+
const bit = x[i >> 3] >>> 7 - (i & 7) & 1;
|
|
137
|
+
if (bit) {
|
|
138
|
+
for (let j = 0; j < 16; j++) z[j] ^= v[j];
|
|
139
|
+
}
|
|
140
|
+
const lsb = v[15] & 1;
|
|
141
|
+
for (let j = 15; j > 0; j--) {
|
|
142
|
+
v[j] = (v[j] >>> 1 | (v[j - 1] & 1) << 7) & 255;
|
|
143
|
+
}
|
|
144
|
+
v[0] = v[0] >>> 1 & 255;
|
|
145
|
+
if (lsb) v[0] ^= 225;
|
|
146
|
+
}
|
|
147
|
+
return z;
|
|
148
|
+
}
|
|
149
|
+
function ghashBlocks(h, data) {
|
|
150
|
+
let y = new Uint8Array(16);
|
|
151
|
+
const nBlocks = Math.ceil(data.length / 16);
|
|
152
|
+
for (let i = 0; i < nBlocks; i++) {
|
|
153
|
+
const block = new Uint8Array(16);
|
|
154
|
+
const start = i * 16;
|
|
155
|
+
block.set(data.subarray(start, Math.min(start + 16, data.length)));
|
|
156
|
+
for (let j = 0; j < 16; j++) y[j] ^= block[j];
|
|
157
|
+
y = gfMul(y, h);
|
|
158
|
+
}
|
|
159
|
+
return y;
|
|
160
|
+
}
|
|
161
|
+
function inc32(counter) {
|
|
162
|
+
for (let i = 15; i >= 12; i--) {
|
|
163
|
+
counter[i] = counter[i] + 1 & 255;
|
|
164
|
+
if (counter[i] !== 0) break;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
function gctr(rk, icb, data) {
|
|
168
|
+
if (data.length === 0) return new Uint8Array(0);
|
|
169
|
+
const out = new Uint8Array(data.length);
|
|
170
|
+
const cb = new Uint8Array(icb);
|
|
171
|
+
const ks = new Uint8Array(16);
|
|
172
|
+
let off = 0;
|
|
173
|
+
while (off < data.length) {
|
|
174
|
+
sm4Block(rk, cb, 0, ks, 0);
|
|
175
|
+
const len = Math.min(16, data.length - off);
|
|
176
|
+
for (let i = 0; i < len; i++) out[off + i] = data[off + i] ^ ks[i];
|
|
177
|
+
off += len;
|
|
178
|
+
inc32(cb);
|
|
179
|
+
}
|
|
180
|
+
return out;
|
|
181
|
+
}
|
|
182
|
+
function ghashInput(aad, ct) {
|
|
183
|
+
const aadPad = Math.ceil(aad.length / 16) * 16;
|
|
184
|
+
const ctPad = Math.ceil(ct.length / 16) * 16;
|
|
185
|
+
const total = aadPad + ctPad + 16;
|
|
186
|
+
const buf = new Uint8Array(total);
|
|
187
|
+
buf.set(aad, 0);
|
|
188
|
+
buf.set(ct, aadPad);
|
|
189
|
+
const aadBits = BigInt(aad.length) * 8n;
|
|
190
|
+
const ctBits = BigInt(ct.length) * 8n;
|
|
191
|
+
const tail = aadPad + ctPad;
|
|
192
|
+
for (let i = 0; i < 8; i++) {
|
|
193
|
+
buf[tail + 7 - i] = Number(aadBits >> BigInt(8 * i) & 0xffn);
|
|
194
|
+
buf[tail + 15 - i] = Number(ctBits >> BigInt(8 * i) & 0xffn);
|
|
195
|
+
}
|
|
196
|
+
return buf;
|
|
197
|
+
}
|
|
198
|
+
function gcmSetup(key, iv) {
|
|
199
|
+
const rk = expandKey(key);
|
|
200
|
+
const h = new Uint8Array(16);
|
|
201
|
+
sm4Block(rk, new Uint8Array(16), 0, h, 0);
|
|
202
|
+
const j0 = new Uint8Array(16);
|
|
203
|
+
j0.set(iv.subarray(0, Math.min(12, iv.length)));
|
|
204
|
+
j0[15] = 1;
|
|
205
|
+
return { rk, h, j0 };
|
|
206
|
+
}
|
|
207
|
+
function computeTag(rk, h, j0, aad, ct) {
|
|
208
|
+
const s = ghashBlocks(h, ghashInput(aad, ct));
|
|
209
|
+
const ekj0 = gctr(rk, j0, new Uint8Array(16));
|
|
210
|
+
const tag = new Uint8Array(16);
|
|
211
|
+
for (let i = 0; i < 16; i++) tag[i] = s[i] ^ ekj0[i];
|
|
212
|
+
return tag;
|
|
213
|
+
}
|
|
214
|
+
function sm4GcmEncrypt(key, iv, plaintext, aad) {
|
|
215
|
+
const { rk, h, j0 } = gcmSetup(new Uint8Array(key), new Uint8Array(iv));
|
|
216
|
+
const icb = new Uint8Array(j0);
|
|
217
|
+
inc32(icb);
|
|
218
|
+
const ct = gctr(rk, icb, new Uint8Array(plaintext));
|
|
219
|
+
const tag = computeTag(rk, h, j0, new Uint8Array(aad), ct);
|
|
220
|
+
return { ciphertext: Buffer.from(ct), tag: Buffer.from(tag) };
|
|
221
|
+
}
|
|
222
|
+
function sm4GcmDecrypt(key, iv, ciphertext, tag, aad) {
|
|
223
|
+
const { rk, h, j0 } = gcmSetup(new Uint8Array(key), new Uint8Array(iv));
|
|
224
|
+
const ct = new Uint8Array(ciphertext);
|
|
225
|
+
const expected = computeTag(rk, h, j0, new Uint8Array(aad), ct);
|
|
226
|
+
if (tag.length !== 16) throw new Error("SM4-GCM: tag must be 16 bytes");
|
|
227
|
+
let diff = 0;
|
|
228
|
+
for (let i = 0; i < 16; i++) diff |= expected[i] ^ tag[i];
|
|
229
|
+
if (diff !== 0) throw new Error("SM4-GCM: authentication tag mismatch");
|
|
230
|
+
const icb = new Uint8Array(j0);
|
|
231
|
+
inc32(icb);
|
|
232
|
+
return Buffer.from(gctr(rk, icb, ct));
|
|
233
|
+
}
|
|
234
|
+
var SBOX, CK, FK;
|
|
235
|
+
var init_sm4 = __esm({
|
|
236
|
+
"src/protocol/sm4.ts"() {
|
|
237
|
+
SBOX = new Uint8Array([
|
|
238
|
+
214,
|
|
239
|
+
144,
|
|
240
|
+
233,
|
|
241
|
+
254,
|
|
242
|
+
204,
|
|
243
|
+
225,
|
|
244
|
+
61,
|
|
245
|
+
183,
|
|
246
|
+
22,
|
|
247
|
+
182,
|
|
248
|
+
20,
|
|
249
|
+
194,
|
|
250
|
+
40,
|
|
251
|
+
251,
|
|
252
|
+
44,
|
|
253
|
+
5,
|
|
254
|
+
43,
|
|
255
|
+
103,
|
|
256
|
+
154,
|
|
257
|
+
118,
|
|
258
|
+
42,
|
|
259
|
+
190,
|
|
260
|
+
4,
|
|
261
|
+
195,
|
|
262
|
+
170,
|
|
263
|
+
68,
|
|
264
|
+
19,
|
|
265
|
+
38,
|
|
266
|
+
73,
|
|
267
|
+
134,
|
|
268
|
+
6,
|
|
269
|
+
153,
|
|
270
|
+
156,
|
|
271
|
+
66,
|
|
272
|
+
80,
|
|
273
|
+
244,
|
|
274
|
+
145,
|
|
275
|
+
239,
|
|
276
|
+
152,
|
|
277
|
+
122,
|
|
278
|
+
51,
|
|
279
|
+
84,
|
|
280
|
+
11,
|
|
281
|
+
67,
|
|
282
|
+
237,
|
|
283
|
+
207,
|
|
284
|
+
172,
|
|
285
|
+
98,
|
|
286
|
+
228,
|
|
287
|
+
179,
|
|
288
|
+
28,
|
|
289
|
+
169,
|
|
290
|
+
201,
|
|
291
|
+
8,
|
|
292
|
+
232,
|
|
293
|
+
149,
|
|
294
|
+
128,
|
|
295
|
+
223,
|
|
296
|
+
148,
|
|
297
|
+
250,
|
|
298
|
+
117,
|
|
299
|
+
143,
|
|
300
|
+
63,
|
|
301
|
+
166,
|
|
302
|
+
71,
|
|
303
|
+
7,
|
|
304
|
+
167,
|
|
305
|
+
252,
|
|
306
|
+
243,
|
|
307
|
+
115,
|
|
308
|
+
23,
|
|
309
|
+
186,
|
|
310
|
+
131,
|
|
311
|
+
89,
|
|
312
|
+
60,
|
|
313
|
+
25,
|
|
314
|
+
230,
|
|
315
|
+
133,
|
|
316
|
+
79,
|
|
317
|
+
168,
|
|
318
|
+
104,
|
|
319
|
+
107,
|
|
320
|
+
129,
|
|
321
|
+
178,
|
|
322
|
+
113,
|
|
323
|
+
100,
|
|
324
|
+
218,
|
|
325
|
+
139,
|
|
326
|
+
248,
|
|
327
|
+
235,
|
|
328
|
+
15,
|
|
329
|
+
75,
|
|
330
|
+
112,
|
|
331
|
+
86,
|
|
332
|
+
157,
|
|
333
|
+
53,
|
|
334
|
+
30,
|
|
335
|
+
36,
|
|
336
|
+
14,
|
|
337
|
+
94,
|
|
338
|
+
99,
|
|
339
|
+
88,
|
|
340
|
+
209,
|
|
341
|
+
162,
|
|
342
|
+
37,
|
|
343
|
+
34,
|
|
344
|
+
124,
|
|
345
|
+
59,
|
|
346
|
+
1,
|
|
347
|
+
33,
|
|
348
|
+
120,
|
|
349
|
+
135,
|
|
350
|
+
212,
|
|
351
|
+
0,
|
|
352
|
+
70,
|
|
353
|
+
87,
|
|
354
|
+
159,
|
|
355
|
+
211,
|
|
356
|
+
39,
|
|
357
|
+
82,
|
|
358
|
+
76,
|
|
359
|
+
54,
|
|
360
|
+
2,
|
|
361
|
+
231,
|
|
362
|
+
160,
|
|
363
|
+
196,
|
|
364
|
+
200,
|
|
365
|
+
158,
|
|
366
|
+
234,
|
|
367
|
+
191,
|
|
368
|
+
138,
|
|
369
|
+
210,
|
|
370
|
+
64,
|
|
371
|
+
199,
|
|
372
|
+
56,
|
|
373
|
+
181,
|
|
374
|
+
163,
|
|
375
|
+
247,
|
|
376
|
+
242,
|
|
377
|
+
206,
|
|
378
|
+
249,
|
|
379
|
+
97,
|
|
380
|
+
21,
|
|
381
|
+
161,
|
|
382
|
+
224,
|
|
383
|
+
174,
|
|
384
|
+
93,
|
|
385
|
+
164,
|
|
386
|
+
155,
|
|
387
|
+
52,
|
|
388
|
+
26,
|
|
389
|
+
85,
|
|
390
|
+
173,
|
|
391
|
+
147,
|
|
392
|
+
50,
|
|
393
|
+
48,
|
|
394
|
+
245,
|
|
395
|
+
140,
|
|
396
|
+
177,
|
|
397
|
+
227,
|
|
398
|
+
29,
|
|
399
|
+
246,
|
|
400
|
+
226,
|
|
401
|
+
46,
|
|
402
|
+
130,
|
|
403
|
+
102,
|
|
404
|
+
202,
|
|
405
|
+
96,
|
|
406
|
+
192,
|
|
407
|
+
41,
|
|
408
|
+
35,
|
|
409
|
+
171,
|
|
410
|
+
13,
|
|
411
|
+
83,
|
|
412
|
+
78,
|
|
413
|
+
111,
|
|
414
|
+
213,
|
|
415
|
+
219,
|
|
416
|
+
55,
|
|
417
|
+
69,
|
|
418
|
+
222,
|
|
419
|
+
253,
|
|
420
|
+
142,
|
|
421
|
+
47,
|
|
422
|
+
3,
|
|
423
|
+
255,
|
|
424
|
+
106,
|
|
425
|
+
114,
|
|
426
|
+
109,
|
|
427
|
+
108,
|
|
428
|
+
91,
|
|
429
|
+
81,
|
|
430
|
+
141,
|
|
431
|
+
27,
|
|
432
|
+
175,
|
|
433
|
+
146,
|
|
434
|
+
187,
|
|
435
|
+
221,
|
|
436
|
+
188,
|
|
437
|
+
127,
|
|
438
|
+
17,
|
|
439
|
+
217,
|
|
440
|
+
92,
|
|
441
|
+
65,
|
|
442
|
+
31,
|
|
443
|
+
16,
|
|
444
|
+
90,
|
|
445
|
+
216,
|
|
446
|
+
10,
|
|
447
|
+
193,
|
|
448
|
+
49,
|
|
449
|
+
136,
|
|
450
|
+
165,
|
|
451
|
+
205,
|
|
452
|
+
123,
|
|
453
|
+
189,
|
|
454
|
+
45,
|
|
455
|
+
116,
|
|
456
|
+
208,
|
|
457
|
+
18,
|
|
458
|
+
184,
|
|
459
|
+
229,
|
|
460
|
+
180,
|
|
461
|
+
176,
|
|
462
|
+
137,
|
|
463
|
+
105,
|
|
464
|
+
151,
|
|
465
|
+
74,
|
|
466
|
+
12,
|
|
467
|
+
150,
|
|
468
|
+
119,
|
|
469
|
+
126,
|
|
470
|
+
101,
|
|
471
|
+
185,
|
|
472
|
+
241,
|
|
473
|
+
9,
|
|
474
|
+
197,
|
|
475
|
+
110,
|
|
476
|
+
198,
|
|
477
|
+
132,
|
|
478
|
+
24,
|
|
479
|
+
240,
|
|
480
|
+
125,
|
|
481
|
+
236,
|
|
482
|
+
58,
|
|
483
|
+
220,
|
|
484
|
+
77,
|
|
485
|
+
32,
|
|
486
|
+
121,
|
|
487
|
+
238,
|
|
488
|
+
95,
|
|
489
|
+
62,
|
|
490
|
+
215,
|
|
491
|
+
203,
|
|
492
|
+
57,
|
|
493
|
+
72
|
|
494
|
+
]);
|
|
495
|
+
CK = new Uint32Array([
|
|
496
|
+
462357,
|
|
497
|
+
472066609,
|
|
498
|
+
943670861,
|
|
499
|
+
1415275113,
|
|
500
|
+
1886879365,
|
|
501
|
+
2358483617,
|
|
502
|
+
2830087869,
|
|
503
|
+
3301692121,
|
|
504
|
+
3773296373,
|
|
505
|
+
4228057617,
|
|
506
|
+
404694573,
|
|
507
|
+
876298825,
|
|
508
|
+
1347903077,
|
|
509
|
+
1819507329,
|
|
510
|
+
2291111581,
|
|
511
|
+
2762715833,
|
|
512
|
+
3234320085,
|
|
513
|
+
3705924337,
|
|
514
|
+
4177462797,
|
|
515
|
+
337322537,
|
|
516
|
+
808926789,
|
|
517
|
+
1280531041,
|
|
518
|
+
1752135293,
|
|
519
|
+
2223739545,
|
|
520
|
+
2695343797,
|
|
521
|
+
3166948049,
|
|
522
|
+
3638552301,
|
|
523
|
+
4110090761,
|
|
524
|
+
269950501,
|
|
525
|
+
741554753,
|
|
526
|
+
1213159005,
|
|
527
|
+
1684763257
|
|
528
|
+
]);
|
|
529
|
+
FK = new Uint32Array([2746333894, 1453994832, 1736282519, 2993693404]);
|
|
530
|
+
}
|
|
531
|
+
});
|
|
532
|
+
|
|
533
|
+
// src/protocol/crypto.ts
|
|
534
|
+
import { createECDH, createHash as createHash2, randomBytes } from "node:crypto";
|
|
535
|
+
function randomIv() {
|
|
536
|
+
return randomBytes(IV_BYTES);
|
|
537
|
+
}
|
|
538
|
+
function deriveSessionKey(sharedSecret) {
|
|
539
|
+
return createHash2("sha256").update(sharedSecret).digest().subarray(0, KEY_BYTES);
|
|
540
|
+
}
|
|
541
|
+
function createEcdhPair() {
|
|
542
|
+
const ecdh = createECDH(CURVE);
|
|
543
|
+
const publicKey = ecdh.generateKeys();
|
|
544
|
+
return { ecdh, publicKeyB64: publicKey.toString("base64") };
|
|
545
|
+
}
|
|
546
|
+
function completeKeyExchange(pair, serverPublicKeyB64, keyId, expiresInSec) {
|
|
547
|
+
const serverPub = Buffer.from(serverPublicKeyB64, "base64");
|
|
548
|
+
const shared = pair.ecdh.computeSecret(serverPub);
|
|
549
|
+
return {
|
|
550
|
+
keyId,
|
|
551
|
+
key: deriveSessionKey(shared),
|
|
552
|
+
expiresAt: Date.now() + (expiresInSec > 0 ? expiresInSec * 1e3 : 72e5)
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
function encryptRequest(key, plaintext, method, pathname, timestamp = Date.now()) {
|
|
556
|
+
const iv = randomIv();
|
|
557
|
+
const aad = Buffer.from(`${method}|${pathname}|${timestamp}`, "utf8");
|
|
558
|
+
const { ciphertext: ct, tag } = sm4GcmEncrypt(key.key, iv, plaintext, aad);
|
|
559
|
+
return {
|
|
560
|
+
body: Buffer.from(ct.toString("base64"), "utf8"),
|
|
561
|
+
headers: {
|
|
562
|
+
"Content-Type": "application/octet-stream",
|
|
563
|
+
"X-Encrypt-Algo": SM4_ALGO,
|
|
564
|
+
"X-Encrypt-Key-Id": key.keyId,
|
|
565
|
+
"X-Encrypt-Iv": iv.toString("base64"),
|
|
566
|
+
"X-Encrypt-Tag": tag.toString("base64"),
|
|
567
|
+
"X-Encrypt-Ts": String(timestamp)
|
|
568
|
+
}
|
|
569
|
+
};
|
|
570
|
+
}
|
|
571
|
+
function decryptStreamChunk(key, block, _method, _pathname, _timestamp, chunkIndex) {
|
|
572
|
+
const parts = block.split(":");
|
|
573
|
+
if (parts.length !== 3) {
|
|
574
|
+
throw new Error(`Invalid encrypted SSE chunk: expected 3 fields, got ${parts.length}`);
|
|
575
|
+
}
|
|
576
|
+
const iv = Buffer.from(parts[0], "base64");
|
|
577
|
+
const tag = Buffer.from(parts[1], "base64");
|
|
578
|
+
const ct = Buffer.from(parts[2], "base64");
|
|
579
|
+
const aad = Buffer.from(`${key.keyId}|${chunkIndex}`, "utf8");
|
|
580
|
+
const plain = sm4GcmDecrypt(key.key, iv, ct, tag, aad);
|
|
581
|
+
return plain.toString("utf8");
|
|
582
|
+
}
|
|
583
|
+
var CURVE, SM4_ALGO, KEY_BYTES, IV_BYTES;
|
|
584
|
+
var init_crypto = __esm({
|
|
585
|
+
"src/protocol/crypto.ts"() {
|
|
586
|
+
init_sm4();
|
|
587
|
+
CURVE = "prime256v1";
|
|
588
|
+
SM4_ALGO = "sm4-gcm";
|
|
589
|
+
KEY_BYTES = 16;
|
|
590
|
+
IV_BYTES = 12;
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
|
|
594
|
+
// src/client.ts
|
|
595
|
+
var client_exports = {};
|
|
596
|
+
__export(client_exports, {
|
|
597
|
+
CHAT_PATH: () => CHAT_PATH,
|
|
598
|
+
DEFAULT_GATEWAY: () => DEFAULT_GATEWAY,
|
|
599
|
+
KEY_EXCHANGE_PATH: () => KEY_EXCHANGE_PATH,
|
|
600
|
+
MODELS_PATH: () => MODELS_PATH,
|
|
601
|
+
MadaoClient: () => MadaoClient,
|
|
602
|
+
decryptSseStream: () => decryptSseStream
|
|
603
|
+
});
|
|
604
|
+
import { createHash as createHash3, randomUUID } from "node:crypto";
|
|
605
|
+
function decryptSseStream(upstream, key, method, pathname, timestamp) {
|
|
606
|
+
const decoder = new TextDecoder();
|
|
607
|
+
const encoder = new TextEncoder();
|
|
608
|
+
let buffer = "";
|
|
609
|
+
let chunkIndex = 0;
|
|
610
|
+
return new ReadableStream({
|
|
611
|
+
async start(controller) {
|
|
612
|
+
const reader = upstream.getReader();
|
|
613
|
+
try {
|
|
614
|
+
for (; ; ) {
|
|
615
|
+
const { done, value } = await reader.read();
|
|
616
|
+
if (done) {
|
|
617
|
+
const rest = buffer.trim();
|
|
618
|
+
if (rest) {
|
|
619
|
+
const plain = decryptStreamChunk(key, rest, method, pathname, timestamp, chunkIndex++);
|
|
620
|
+
controller.enqueue(encoder.encode(plain.endsWith("\n\n") ? plain : `${plain}
|
|
621
|
+
|
|
622
|
+
`));
|
|
623
|
+
}
|
|
624
|
+
controller.close();
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
buffer += decoder.decode(value, { stream: true });
|
|
628
|
+
let sep;
|
|
629
|
+
while ((sep = buffer.indexOf("\n\n")) !== -1) {
|
|
630
|
+
const block = buffer.slice(0, sep).trim();
|
|
631
|
+
buffer = buffer.slice(sep + 2);
|
|
632
|
+
if (!block) continue;
|
|
633
|
+
const plain = decryptStreamChunk(key, block, method, pathname, timestamp, chunkIndex++);
|
|
634
|
+
controller.enqueue(encoder.encode(plain.endsWith("\n\n") ? plain : `${plain}
|
|
635
|
+
|
|
636
|
+
`));
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
} catch (err) {
|
|
640
|
+
controller.error(err);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
});
|
|
644
|
+
}
|
|
645
|
+
function randomHex(bytes) {
|
|
646
|
+
const b = new Uint8Array(bytes);
|
|
647
|
+
globalThis.crypto.getRandomValues(b);
|
|
648
|
+
return Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
|
|
649
|
+
}
|
|
650
|
+
var DEFAULT_GATEWAY, CHAT_PATH, KEY_EXCHANGE_PATH, MODELS_PATH, REFRESH_MARGIN_MS, DEFAULT_IDENTITY, MadaoClient;
|
|
651
|
+
var init_client = __esm({
|
|
652
|
+
"src/client.ts"() {
|
|
653
|
+
init_sign();
|
|
654
|
+
init_crypto();
|
|
655
|
+
DEFAULT_GATEWAY = "https://snap-access.cn-north-4.myhuaweicloud.com";
|
|
656
|
+
CHAT_PATH = "/api/v2/chat/completions";
|
|
657
|
+
KEY_EXCHANGE_PATH = "/api/v1/security/key-exchange";
|
|
658
|
+
MODELS_PATH = "/v1/model/builtin";
|
|
659
|
+
REFRESH_MARGIN_MS = 3e5;
|
|
660
|
+
DEFAULT_IDENTITY = {
|
|
661
|
+
pluginName: "codemate_vscode",
|
|
662
|
+
pluginVersion: "26.11.100",
|
|
663
|
+
ideName: "VSCode",
|
|
664
|
+
ideVersion: "26.11.100"
|
|
665
|
+
};
|
|
666
|
+
MadaoClient = class {
|
|
667
|
+
gateway;
|
|
668
|
+
creds;
|
|
669
|
+
fetchImpl;
|
|
670
|
+
identity;
|
|
671
|
+
language;
|
|
672
|
+
defaultSessionId;
|
|
673
|
+
sessionKey = null;
|
|
674
|
+
negotiating = null;
|
|
675
|
+
constructor(opts) {
|
|
676
|
+
this.gateway = (opts.gateway ?? DEFAULT_GATEWAY).replace(/\/+$/, "");
|
|
677
|
+
this.creds = opts.credentials;
|
|
678
|
+
this.fetchImpl = opts.fetch ?? globalThis.fetch.bind(globalThis);
|
|
679
|
+
this.identity = { ...DEFAULT_IDENTITY, ...opts.identity };
|
|
680
|
+
this.language = opts.language ?? "zh-cn";
|
|
681
|
+
this.defaultSessionId = opts.sessionId ?? `madao-${createHash3("sha256").update(opts.credentials.accessKeyId ?? "default").digest("hex").slice(0, 16)}`;
|
|
682
|
+
}
|
|
683
|
+
// ── 密钥协商 ────────────────────────────────────────────────
|
|
684
|
+
/** 取可用会话密钥;过期或临期则重新协商。并发调用只会触发一次协商。 */
|
|
685
|
+
async ensureSessionKey() {
|
|
686
|
+
if (this.sessionKey && Date.now() < this.sessionKey.expiresAt - REFRESH_MARGIN_MS) {
|
|
687
|
+
return this.sessionKey;
|
|
688
|
+
}
|
|
689
|
+
if (this.negotiating) return this.negotiating;
|
|
690
|
+
this.negotiating = this.negotiate().finally(() => {
|
|
691
|
+
this.negotiating = null;
|
|
692
|
+
});
|
|
693
|
+
return this.negotiating;
|
|
694
|
+
}
|
|
695
|
+
async negotiate() {
|
|
696
|
+
const url = new URL(this.gateway + KEY_EXCHANGE_PATH);
|
|
697
|
+
const pair = createEcdhPair();
|
|
698
|
+
const body = JSON.stringify({
|
|
699
|
+
clientPublicKey: pair.publicKeyB64,
|
|
700
|
+
sessionId: randomHex(16),
|
|
701
|
+
timestamp: Date.now()
|
|
702
|
+
});
|
|
703
|
+
const headers = signRequest({
|
|
704
|
+
method: "POST",
|
|
705
|
+
url,
|
|
706
|
+
contentType: "application/json",
|
|
707
|
+
body,
|
|
708
|
+
credentials: this.creds
|
|
709
|
+
});
|
|
710
|
+
const res = await this.fetchImpl(url, {
|
|
711
|
+
method: "POST",
|
|
712
|
+
headers: { ...headers, "User-Agent": `codearts/${this.identity.ideVersion}` },
|
|
713
|
+
body
|
|
714
|
+
});
|
|
715
|
+
if (!res.ok) {
|
|
716
|
+
const text = await res.text().catch(() => "");
|
|
717
|
+
throw new Error(`key-exchange failed: HTTP ${res.status} ${text.slice(0, 300)}`);
|
|
718
|
+
}
|
|
719
|
+
const json2 = await res.json();
|
|
720
|
+
if (!json2.keyId || !json2.serverPublicKey) {
|
|
721
|
+
throw new Error("key-exchange response missing keyId/serverPublicKey");
|
|
722
|
+
}
|
|
723
|
+
this.sessionKey = completeKeyExchange(pair, json2.serverPublicKey, json2.keyId, json2.expiresIn ?? 7200);
|
|
724
|
+
return this.sessionKey;
|
|
725
|
+
}
|
|
726
|
+
/** 丢弃缓存密钥(凭证轮换后调用)。 */
|
|
727
|
+
resetSessionKey() {
|
|
728
|
+
this.sessionKey = null;
|
|
729
|
+
}
|
|
730
|
+
// ── chat ────────────────────────────────────────────────────
|
|
731
|
+
/**
|
|
732
|
+
* 发起一次加密 chat 请求,返回已解密的 SSE 文本事件流。
|
|
733
|
+
*
|
|
734
|
+
* @param payload 上游期望的请求体(JSON 可序列化)
|
|
735
|
+
*/
|
|
736
|
+
async chatStream(payload, extraHeaders = {}) {
|
|
737
|
+
const key = await this.ensureSessionKey();
|
|
738
|
+
const url = new URL(this.gateway + CHAT_PATH);
|
|
739
|
+
const ts = Date.now();
|
|
740
|
+
const plaintext = Buffer.from(JSON.stringify(payload), "utf8");
|
|
741
|
+
const { body, headers: encHeaders } = encryptRequest(key, plaintext, "POST", CHAT_PATH, ts);
|
|
742
|
+
const signed = signRequest({
|
|
743
|
+
method: "POST",
|
|
744
|
+
url,
|
|
745
|
+
contentType: encHeaders["Content-Type"],
|
|
746
|
+
bodyBytes: body,
|
|
747
|
+
credentials: this.creds
|
|
748
|
+
});
|
|
749
|
+
const res = await this.fetchImpl(url, {
|
|
750
|
+
method: "POST",
|
|
751
|
+
headers: {
|
|
752
|
+
...signed,
|
|
753
|
+
...encHeaders,
|
|
754
|
+
Accept: "text/event-stream",
|
|
755
|
+
"X-Encrypt-Capable": "sm4-gcm",
|
|
756
|
+
"User-Agent": `ai-sdk/provider-utils/4.0.21 runtime/bun/1.3.14`,
|
|
757
|
+
...this.identityHeaders(),
|
|
758
|
+
// 会话与消息标识:网关据此判断"还是同一个会话"。
|
|
759
|
+
// 缺了这两个头,每次请求都会被算作新会话,3 个并发名额很快耗尽
|
|
760
|
+
// 并持续报 TM.00001041。调用方可通过 extraHeaders 覆盖。
|
|
761
|
+
"user-session-id": this.defaultSessionId,
|
|
762
|
+
"user-msg-id": randomUUID(),
|
|
763
|
+
...extraHeaders
|
|
764
|
+
},
|
|
765
|
+
body
|
|
766
|
+
});
|
|
767
|
+
if (!res.ok) {
|
|
768
|
+
const text = await res.text().catch(() => "");
|
|
769
|
+
throw new Error(`chat failed: HTTP ${res.status} ${await this.describeError(text, key)}`);
|
|
770
|
+
}
|
|
771
|
+
const respAlgo = res.headers.get("x-encrypt-algo");
|
|
772
|
+
if (respAlgo !== "sm4-gcm") {
|
|
773
|
+
return res.body;
|
|
774
|
+
}
|
|
775
|
+
return decryptSseStream(res.body, key, "POST", CHAT_PATH, ts);
|
|
776
|
+
}
|
|
777
|
+
// ── 只读接口(明文,无需加密) ──────────────────────────────
|
|
778
|
+
/**
|
|
779
|
+
* 会话心跳。标记当前会话 busy / idle。
|
|
780
|
+
*
|
|
781
|
+
* 网关按 `user-session-id` 计并发会话数(上限 3 个,超了报 TM.00001041)。
|
|
782
|
+
* 对话结束标 idle 能让名额及时释放,不至于挂满两小时。
|
|
783
|
+
*
|
|
784
|
+
* 失败不抛错 —— 这只是优化项,不影响对话本身。
|
|
785
|
+
*/
|
|
786
|
+
async heartbeat(status) {
|
|
787
|
+
try {
|
|
788
|
+
const path = `/snap-manager/v1/chat-session/heartbeat?status=${status}`;
|
|
789
|
+
const url = new URL(this.gateway + path);
|
|
790
|
+
const headers = signRequest({
|
|
791
|
+
method: "PUT",
|
|
792
|
+
url,
|
|
793
|
+
contentType: null,
|
|
794
|
+
body: "",
|
|
795
|
+
credentials: this.creds
|
|
796
|
+
});
|
|
797
|
+
const res = await this.fetchImpl(url, {
|
|
798
|
+
method: "PUT",
|
|
799
|
+
headers: {
|
|
800
|
+
...headers,
|
|
801
|
+
"User-Agent": `codearts/${this.identity.ideVersion}`,
|
|
802
|
+
"Agent-Type": "PromptCenter",
|
|
803
|
+
"x-language": this.language,
|
|
804
|
+
"user-session-id": this.defaultSessionId
|
|
805
|
+
}
|
|
806
|
+
});
|
|
807
|
+
return res.ok;
|
|
808
|
+
} catch {
|
|
809
|
+
return false;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
async getModels() {
|
|
813
|
+
return this.getJson(MODELS_PATH);
|
|
814
|
+
}
|
|
815
|
+
/** 通用 GET,供额度 / 任务等只读接口复用。 */
|
|
816
|
+
async getJson(path) {
|
|
817
|
+
const url = new URL(this.gateway + path);
|
|
818
|
+
const headers = signRequest({
|
|
819
|
+
method: "GET",
|
|
820
|
+
url,
|
|
821
|
+
contentType: null,
|
|
822
|
+
body: "",
|
|
823
|
+
credentials: this.creds
|
|
824
|
+
});
|
|
825
|
+
const res = await this.fetchImpl(url, {
|
|
826
|
+
method: "GET",
|
|
827
|
+
headers: {
|
|
828
|
+
...headers,
|
|
829
|
+
"User-Agent": `codearts/${this.identity.ideVersion}`,
|
|
830
|
+
// 码道网关要求业务头,缺了报 TM.00001001
|
|
831
|
+
"Agent-Type": "PromptCenter",
|
|
832
|
+
"X-Language": "zh-cn"
|
|
833
|
+
}
|
|
834
|
+
});
|
|
835
|
+
if (!res.ok) {
|
|
836
|
+
const t = await res.text().catch(() => "");
|
|
837
|
+
throw new Error(`GET ${path} failed: HTTP ${res.status} ${t.slice(0, 200)}`);
|
|
838
|
+
}
|
|
839
|
+
return res.json();
|
|
840
|
+
}
|
|
841
|
+
/**
|
|
842
|
+
* 通用 POST(JSON 明文,不加密)。
|
|
843
|
+
*
|
|
844
|
+
* 仅用于 `/v1/model/thinking-variants` 这类元数据接口 —— 聊天走 chatStream 的加密通道。
|
|
845
|
+
*/
|
|
846
|
+
async postJson(path, payload) {
|
|
847
|
+
const url = new URL(this.gateway + path);
|
|
848
|
+
const body = JSON.stringify(payload);
|
|
849
|
+
const headers = signRequest({
|
|
850
|
+
method: "POST",
|
|
851
|
+
url,
|
|
852
|
+
contentType: "application/json",
|
|
853
|
+
body,
|
|
854
|
+
credentials: this.creds
|
|
855
|
+
});
|
|
856
|
+
const res = await this.fetchImpl(url, {
|
|
857
|
+
method: "POST",
|
|
858
|
+
headers: {
|
|
859
|
+
...headers,
|
|
860
|
+
"Content-Type": "application/json",
|
|
861
|
+
"User-Agent": `codearts/${this.identity.ideVersion}`,
|
|
862
|
+
"Agent-Type": "PromptCenter",
|
|
863
|
+
"X-Language": "zh-cn"
|
|
864
|
+
},
|
|
865
|
+
body
|
|
866
|
+
});
|
|
867
|
+
if (!res.ok) {
|
|
868
|
+
const t = await res.text().catch(() => "");
|
|
869
|
+
throw new Error(`POST ${path} failed: HTTP ${res.status} ${t.slice(0, 200)}`);
|
|
870
|
+
}
|
|
871
|
+
return res.json();
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* 尽力把错误响应解成明文。
|
|
875
|
+
*
|
|
876
|
+
* 网关的 4xx 响应体也是 `IV:TAG:CIPHERTEXT` 的 SM4-GCM 密文,
|
|
877
|
+
* 直接打印只能看到乱码。解不出来时原样返回前 200 字符。
|
|
878
|
+
*/
|
|
879
|
+
async describeError(raw, key) {
|
|
880
|
+
const text = (raw ?? "").trim();
|
|
881
|
+
if (!text) return "(\u7A7A\u54CD\u5E94\u4F53)";
|
|
882
|
+
try {
|
|
883
|
+
return decryptStreamChunk(key, text, "POST", CHAT_PATH, Date.now(), 0);
|
|
884
|
+
} catch {
|
|
885
|
+
return text.slice(0, 200);
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
identityHeaders() {
|
|
889
|
+
return {
|
|
890
|
+
// 码道网关必需的业务头,缺任一都会 400
|
|
891
|
+
"Agent-Type": "PromptCenter",
|
|
892
|
+
"x-language": this.language,
|
|
893
|
+
"plugin-name": this.identity.pluginName,
|
|
894
|
+
"plugin-version": this.identity.pluginVersion,
|
|
895
|
+
"ide-name": this.identity.ideName,
|
|
896
|
+
"ide-version": this.identity.ideVersion
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
});
|
|
902
|
+
|
|
903
|
+
// src/protocol/huawei-sign.ts
|
|
904
|
+
import { createHash as createHash4, createHmac as createHmac2 } from "node:crypto";
|
|
905
|
+
function huaweiSdkDate(d = /* @__PURE__ */ new Date()) {
|
|
906
|
+
const p = (n) => String(n).padStart(2, "0");
|
|
907
|
+
return `${d.getUTCFullYear()}${p(d.getUTCMonth() + 1)}${p(d.getUTCDate())}T${p(d.getUTCHours())}${p(d.getUTCMinutes())}${p(d.getUTCSeconds())}Z`;
|
|
908
|
+
}
|
|
909
|
+
function signHuawei(opts) {
|
|
910
|
+
const method = opts.method.toUpperCase();
|
|
911
|
+
const sdkDateVal = opts.sdkDate ?? huaweiSdkDate();
|
|
912
|
+
const body = opts.body ?? "";
|
|
913
|
+
const payloadHash = createHash4("sha256").update(body).digest("hex");
|
|
914
|
+
const headers = {
|
|
915
|
+
Host: opts.host,
|
|
916
|
+
"X-Sdk-Date": sdkDateVal
|
|
917
|
+
};
|
|
918
|
+
if (opts.contentType) headers["Content-Type"] = opts.contentType;
|
|
919
|
+
if (opts.securityToken) headers["X-Security-Token"] = opts.securityToken;
|
|
920
|
+
const entries = Object.entries(headers).map(([k, v]) => [k.toLowerCase(), v]).sort((a, b) => a[0].localeCompare(b[0]));
|
|
921
|
+
const canonicalHeaders2 = entries.map(([k, v]) => `${k}:${v.trim()}
|
|
922
|
+
`).join("");
|
|
923
|
+
const signedHeaders = entries.map(([k]) => k).join(";");
|
|
924
|
+
const canonicalRequest = [
|
|
925
|
+
method,
|
|
926
|
+
opts.path,
|
|
927
|
+
opts.query ?? "",
|
|
928
|
+
canonicalHeaders2,
|
|
929
|
+
signedHeaders,
|
|
930
|
+
payloadHash
|
|
931
|
+
].join("\n");
|
|
932
|
+
const stringToSign = [
|
|
933
|
+
"SDK-HMAC-SHA256",
|
|
934
|
+
sdkDateVal,
|
|
935
|
+
createHash4("sha256").update(canonicalRequest).digest("hex")
|
|
936
|
+
].join("\n");
|
|
937
|
+
const signature = createHmac2("sha256", opts.sk).update(stringToSign).digest("hex");
|
|
938
|
+
return {
|
|
939
|
+
...headers,
|
|
940
|
+
Authorization: `SDK-HMAC-SHA256 Access=${opts.ak}, SignedHeaders=${signedHeaders}, Signature=${signature}`
|
|
941
|
+
};
|
|
942
|
+
}
|
|
943
|
+
var init_huawei_sign = __esm({
|
|
944
|
+
"src/protocol/huawei-sign.ts"() {
|
|
945
|
+
}
|
|
946
|
+
});
|
|
947
|
+
|
|
948
|
+
// src/sts.ts
|
|
949
|
+
async function getStsFromIam(ak, sk, durationSeconds = 3600) {
|
|
950
|
+
const body = JSON.stringify({
|
|
951
|
+
auth: {
|
|
952
|
+
identity: {
|
|
953
|
+
methods: ["token"],
|
|
954
|
+
token: { duration_seconds: durationSeconds }
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
});
|
|
958
|
+
const headers = signHuawei({
|
|
959
|
+
method: "POST",
|
|
960
|
+
host: IAM_HOST,
|
|
961
|
+
path: IAM_SIGN_PATH,
|
|
962
|
+
contentType: "application/json;charset=utf8",
|
|
963
|
+
body,
|
|
964
|
+
ak,
|
|
965
|
+
sk
|
|
966
|
+
});
|
|
967
|
+
const res = await fetch(`https://${IAM_HOST}${IAM_REQUEST_PATH}`, {
|
|
968
|
+
method: "POST",
|
|
969
|
+
headers,
|
|
970
|
+
body
|
|
971
|
+
});
|
|
972
|
+
const text = await res.text();
|
|
973
|
+
if (!res.ok) {
|
|
974
|
+
throw new Error(
|
|
975
|
+
`IAM \u6362 STS \u5931\u8D25: HTTP ${res.status}
|
|
976
|
+
${text.slice(0, 800)}`
|
|
977
|
+
);
|
|
978
|
+
}
|
|
979
|
+
let json2;
|
|
980
|
+
try {
|
|
981
|
+
json2 = JSON.parse(text);
|
|
982
|
+
} catch {
|
|
983
|
+
throw new Error(`IAM \u8FD4\u56DE\u975E JSON: ${text.slice(0, 300)}`);
|
|
984
|
+
}
|
|
985
|
+
const cred = json2.credential;
|
|
986
|
+
if (!cred?.access || !cred?.secret || !cred?.securitytoken) {
|
|
987
|
+
throw new Error(`IAM \u54CD\u5E94\u7F3A\u5C11 credential \u5B57\u6BB5:
|
|
988
|
+
${text.slice(0, 800)}`);
|
|
989
|
+
}
|
|
990
|
+
return {
|
|
991
|
+
ak: cred.access,
|
|
992
|
+
sk: cred.secret,
|
|
993
|
+
securityToken: cred.securitytoken,
|
|
994
|
+
expiresAt: cred.expires_at ?? ""
|
|
995
|
+
};
|
|
996
|
+
}
|
|
997
|
+
var IAM_HOST, IAM_REQUEST_PATH, IAM_SIGN_PATH;
|
|
998
|
+
var init_sts = __esm({
|
|
999
|
+
"src/sts.ts"() {
|
|
1000
|
+
init_huawei_sign();
|
|
1001
|
+
IAM_HOST = "iam.cn-north-4.myhuaweicloud.com";
|
|
1002
|
+
IAM_REQUEST_PATH = "/v3.0/OS-CREDENTIAL/securitytokens";
|
|
1003
|
+
IAM_SIGN_PATH = `${IAM_REQUEST_PATH}/`;
|
|
1004
|
+
}
|
|
1005
|
+
});
|
|
1006
|
+
|
|
1007
|
+
// src/sts-provider.ts
|
|
1008
|
+
var sts_provider_exports = {};
|
|
1009
|
+
__export(sts_provider_exports, {
|
|
1010
|
+
StsProvider: () => StsProvider
|
|
1011
|
+
});
|
|
1012
|
+
var REFRESH_MARGIN_MS2, StsProvider;
|
|
1013
|
+
var init_sts_provider = __esm({
|
|
1014
|
+
"src/sts-provider.ts"() {
|
|
1015
|
+
init_sts();
|
|
1016
|
+
REFRESH_MARGIN_MS2 = 10 * 60 * 1e3;
|
|
1017
|
+
StsProvider = class {
|
|
1018
|
+
current = null;
|
|
1019
|
+
pending = null;
|
|
1020
|
+
ak;
|
|
1021
|
+
sk;
|
|
1022
|
+
durationSeconds;
|
|
1023
|
+
constructor(key, durationSeconds = 3600) {
|
|
1024
|
+
this.ak = key.ak;
|
|
1025
|
+
this.sk = key.sk;
|
|
1026
|
+
this.durationSeconds = durationSeconds;
|
|
1027
|
+
}
|
|
1028
|
+
/** 取可用的 STS 凭证;临近过期则续期。 */
|
|
1029
|
+
async get() {
|
|
1030
|
+
if (this.current && !this.isExpiring(this.current)) return this.current;
|
|
1031
|
+
if (this.pending) return this.pending;
|
|
1032
|
+
this.pending = getStsFromIam(this.ak, this.sk, this.durationSeconds).then((c) => {
|
|
1033
|
+
this.current = c;
|
|
1034
|
+
return c;
|
|
1035
|
+
}).finally(() => {
|
|
1036
|
+
this.pending = null;
|
|
1037
|
+
});
|
|
1038
|
+
return this.pending;
|
|
1039
|
+
}
|
|
1040
|
+
/** 直接产出可签名的 Credentials。 */
|
|
1041
|
+
async credentials() {
|
|
1042
|
+
const c = await this.get();
|
|
1043
|
+
return { ak: c.ak, sk: c.sk, securityToken: c.securityToken };
|
|
1044
|
+
}
|
|
1045
|
+
/** 强制丢弃缓存,下次 get() 会重新交换。 */
|
|
1046
|
+
invalidate() {
|
|
1047
|
+
this.current = null;
|
|
1048
|
+
}
|
|
1049
|
+
/**
|
|
1050
|
+
* 只读当前缓存的凭证,不触发交换。
|
|
1051
|
+
*
|
|
1052
|
+
* 面板要展示 STS 身份时需要 securityToken 明文,
|
|
1053
|
+
* 但又不该为了看一眼身份就多换一次 STS(IAM 有限流)。
|
|
1054
|
+
*/
|
|
1055
|
+
peek() {
|
|
1056
|
+
return this.current;
|
|
1057
|
+
}
|
|
1058
|
+
/** 当前 STS 的过期时间(epoch ms),无则为 null。 */
|
|
1059
|
+
expiresAtMs() {
|
|
1060
|
+
if (!this.current?.expiresAt) return null;
|
|
1061
|
+
const t = Date.parse(this.current.expiresAt);
|
|
1062
|
+
return Number.isFinite(t) ? t : null;
|
|
1063
|
+
}
|
|
1064
|
+
isExpiring(c) {
|
|
1065
|
+
if (!c.expiresAt) return false;
|
|
1066
|
+
const t = Date.parse(c.expiresAt);
|
|
1067
|
+
if (!Number.isFinite(t)) return false;
|
|
1068
|
+
return Date.now() > t - REFRESH_MARGIN_MS2;
|
|
1069
|
+
}
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
1072
|
+
});
|
|
1073
|
+
|
|
1074
|
+
// src/codearts-auth.ts
|
|
1075
|
+
import { readFileSync, existsSync } from "node:fs";
|
|
1076
|
+
import { join } from "node:path";
|
|
1077
|
+
import { homedir } from "node:os";
|
|
1078
|
+
function candidateStateDbPaths() {
|
|
1079
|
+
const appData = process.env.APPDATA ?? join(homedir(), "AppData", "Roaming");
|
|
1080
|
+
const base = [
|
|
1081
|
+
join(appData, "codearts-agent", "User", "globalStorage", "state.vscdb"),
|
|
1082
|
+
join(appData, "CodeArts Agent", "User", "globalStorage", "state.vscdb"),
|
|
1083
|
+
join(appData, "codearts", "User", "globalStorage", "state.vscdb")
|
|
1084
|
+
];
|
|
1085
|
+
return base;
|
|
1086
|
+
}
|
|
1087
|
+
function parseFromRaw(raw, sourcePath) {
|
|
1088
|
+
const at = raw.indexOf(ANCHOR);
|
|
1089
|
+
if (at < 0) return null;
|
|
1090
|
+
const seg = raw.slice(at, at + 8192);
|
|
1091
|
+
const grab = (key) => {
|
|
1092
|
+
const m = new RegExp(`"${key}"\\s*:\\s*"([^"]*)"`).exec(seg);
|
|
1093
|
+
return m?.[1] || void 0;
|
|
1094
|
+
};
|
|
1095
|
+
const ak = grab("accessKey");
|
|
1096
|
+
const sk = grab("secretKey");
|
|
1097
|
+
const sts = grab("securityToken");
|
|
1098
|
+
if (!ak || !sk || !sts) return null;
|
|
1099
|
+
const expires = grab("expiresAt");
|
|
1100
|
+
const t = expires ? Date.parse(expires) : NaN;
|
|
1101
|
+
const account = /"account"\s*:\s*\{[^}]*"label"\s*:\s*"([^"]+)"/.exec(seg)?.[1];
|
|
1102
|
+
return {
|
|
1103
|
+
ak,
|
|
1104
|
+
sk,
|
|
1105
|
+
securityToken: sts,
|
|
1106
|
+
expiresAtMs: Number.isFinite(t) ? t : null,
|
|
1107
|
+
account,
|
|
1108
|
+
sourcePath
|
|
1109
|
+
};
|
|
1110
|
+
}
|
|
1111
|
+
function readCodeArtsCredential(minRemainingMs = 5 * 60 * 1e3) {
|
|
1112
|
+
for (const p of candidateStateDbPaths()) {
|
|
1113
|
+
if (!existsSync(p)) continue;
|
|
1114
|
+
let raw;
|
|
1115
|
+
try {
|
|
1116
|
+
raw = readFileSync(p, "utf8");
|
|
1117
|
+
} catch {
|
|
1118
|
+
continue;
|
|
1119
|
+
}
|
|
1120
|
+
const cred = parseFromRaw(raw, p);
|
|
1121
|
+
if (!cred) continue;
|
|
1122
|
+
if (cred.expiresAtMs !== null && cred.expiresAtMs - Date.now() < minRemainingMs) {
|
|
1123
|
+
continue;
|
|
1124
|
+
}
|
|
1125
|
+
return cred;
|
|
1126
|
+
}
|
|
1127
|
+
return null;
|
|
1128
|
+
}
|
|
1129
|
+
var ANCHOR;
|
|
1130
|
+
var init_codearts_auth = __esm({
|
|
1131
|
+
"src/codearts-auth.ts"() {
|
|
1132
|
+
ANCHOR = '"id":"huawei-cloud-authentication"';
|
|
1133
|
+
}
|
|
1134
|
+
});
|
|
1135
|
+
|
|
1136
|
+
// src/dpapi.ts
|
|
1137
|
+
import { execFileSync } from "node:child_process";
|
|
1138
|
+
function run(script, inputB64) {
|
|
1139
|
+
try {
|
|
1140
|
+
const out = execFileSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], {
|
|
1141
|
+
input: inputB64,
|
|
1142
|
+
encoding: "utf8",
|
|
1143
|
+
timeout: 15e3,
|
|
1144
|
+
windowsHide: true
|
|
1145
|
+
});
|
|
1146
|
+
const trimmed = out.trim();
|
|
1147
|
+
return trimmed || null;
|
|
1148
|
+
} catch {
|
|
1149
|
+
return null;
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
function dpapiEncrypt(plaintext) {
|
|
1153
|
+
if (process.platform !== "win32") return null;
|
|
1154
|
+
const b64 = Buffer.from(plaintext, "utf8").toString("base64");
|
|
1155
|
+
const enc = run(PS_PROTECT, b64);
|
|
1156
|
+
if (!enc) return null;
|
|
1157
|
+
try {
|
|
1158
|
+
const back = dpapiDecrypt(enc);
|
|
1159
|
+
if (back !== plaintext) return null;
|
|
1160
|
+
return enc;
|
|
1161
|
+
} catch {
|
|
1162
|
+
return null;
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
function dpapiDecrypt(cipherB64) {
|
|
1166
|
+
if (process.platform !== "win32") return null;
|
|
1167
|
+
const out = run(PS_UNPROTECT, cipherB64.trim());
|
|
1168
|
+
if (!out) return null;
|
|
1169
|
+
try {
|
|
1170
|
+
return Buffer.from(out, "base64").toString("utf8");
|
|
1171
|
+
} catch {
|
|
1172
|
+
return null;
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
var PS_PROTECT, PS_UNPROTECT;
|
|
1176
|
+
var init_dpapi = __esm({
|
|
1177
|
+
"src/dpapi.ts"() {
|
|
1178
|
+
PS_PROTECT = `
|
|
1179
|
+
$ErrorActionPreference = 'Stop'
|
|
1180
|
+
Add-Type -AssemblyName System.Security
|
|
1181
|
+
$raw = [Console]::In.ReadToEnd()
|
|
1182
|
+
$bytes = [Convert]::FromBase64String($raw)
|
|
1183
|
+
$enc = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, 'CurrentUser')
|
|
1184
|
+
[Console]::Out.Write([Convert]::ToBase64String($enc))
|
|
1185
|
+
`;
|
|
1186
|
+
PS_UNPROTECT = `
|
|
1187
|
+
$ErrorActionPreference = 'Stop'
|
|
1188
|
+
Add-Type -AssemblyName System.Security
|
|
1189
|
+
$raw = [Console]::In.ReadToEnd()
|
|
1190
|
+
$bytes = [Convert]::FromBase64String($raw)
|
|
1191
|
+
$dec = [System.Security.Cryptography.ProtectedData]::Unprotect($bytes, $null, 'CurrentUser')
|
|
1192
|
+
[Console]::Out.Write([Convert]::ToBase64String($dec))
|
|
1193
|
+
`;
|
|
1194
|
+
}
|
|
1195
|
+
});
|
|
1196
|
+
|
|
1197
|
+
// src/credentials.ts
|
|
1198
|
+
var credentials_exports = {};
|
|
1199
|
+
__export(credentials_exports, {
|
|
1200
|
+
CRED_DIR: () => CRED_DIR,
|
|
1201
|
+
CRED_ENC_PATH: () => CRED_ENC_PATH,
|
|
1202
|
+
CredentialError: () => CredentialError,
|
|
1203
|
+
DEFAULT_CRED_PATH: () => DEFAULT_CRED_PATH,
|
|
1204
|
+
LEGACY_CRED_PATH: () => LEGACY_CRED_PATH,
|
|
1205
|
+
candidateCredentials: () => candidateCredentials,
|
|
1206
|
+
loadCredentials: () => loadCredentials,
|
|
1207
|
+
maskKey: () => maskKey,
|
|
1208
|
+
migratePlaintextToEncrypted: () => migratePlaintextToEncrypted,
|
|
1209
|
+
saveCredentials: () => saveCredentials
|
|
1210
|
+
});
|
|
1211
|
+
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
1212
|
+
import { homedir as homedir2 } from "node:os";
|
|
1213
|
+
import { join as join2 } from "node:path";
|
|
1214
|
+
function fromEnv() {
|
|
1215
|
+
const ak = process.env.MADAO_AK?.trim();
|
|
1216
|
+
const sk = process.env.MADAO_SK?.trim();
|
|
1217
|
+
if (!ak || !sk) return null;
|
|
1218
|
+
const token = process.env.MADAO_SECURITY_TOKEN?.trim();
|
|
1219
|
+
return { ak, sk, ...token ? { securityToken: token } : {} };
|
|
1220
|
+
}
|
|
1221
|
+
function parseStored(parsed, where) {
|
|
1222
|
+
const ak = parsed.ak ?? parsed.accessKeyId ?? parsed.access_key_id ?? parsed["Access Key Id"];
|
|
1223
|
+
const sk = parsed.sk ?? parsed.secretAccessKey ?? parsed.secret_access_key ?? parsed["Secret Access Key"];
|
|
1224
|
+
const securityToken = parsed.securityToken ?? parsed.security_token ?? parsed.securitytoken ?? parsed.token;
|
|
1225
|
+
if (!ak || !sk) {
|
|
1226
|
+
throw new CredentialError(`${where} \u7F3A\u5C11 ak / sk`);
|
|
1227
|
+
}
|
|
1228
|
+
return {
|
|
1229
|
+
ak: String(ak).trim(),
|
|
1230
|
+
sk: String(sk).trim(),
|
|
1231
|
+
...securityToken ? { securityToken: String(securityToken) } : {},
|
|
1232
|
+
expiresAt: parsed.expiresAt,
|
|
1233
|
+
region: parsed.region,
|
|
1234
|
+
account: parsed.account
|
|
1235
|
+
};
|
|
1236
|
+
}
|
|
1237
|
+
async function fromEncryptedFile() {
|
|
1238
|
+
let cipher;
|
|
1239
|
+
try {
|
|
1240
|
+
cipher = await readFile(CRED_ENC_PATH, "utf8");
|
|
1241
|
+
} catch {
|
|
1242
|
+
return null;
|
|
1243
|
+
}
|
|
1244
|
+
const plain = dpapiDecrypt(cipher);
|
|
1245
|
+
if (!plain) return null;
|
|
1246
|
+
try {
|
|
1247
|
+
return parseStored(JSON.parse(plain), CRED_ENC_PATH);
|
|
1248
|
+
} catch {
|
|
1249
|
+
return null;
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
async function fromFile(path) {
|
|
1253
|
+
let raw;
|
|
1254
|
+
try {
|
|
1255
|
+
raw = await readFile(path, "utf8");
|
|
1256
|
+
} catch {
|
|
1257
|
+
return null;
|
|
1258
|
+
}
|
|
1259
|
+
let parsed;
|
|
1260
|
+
try {
|
|
1261
|
+
parsed = JSON.parse(raw);
|
|
1262
|
+
} catch {
|
|
1263
|
+
throw new CredentialError(`${path} \u4E0D\u662F\u5408\u6CD5 JSON`);
|
|
1264
|
+
}
|
|
1265
|
+
return parseStored(parsed, path);
|
|
1266
|
+
}
|
|
1267
|
+
async function saveCredentials(key) {
|
|
1268
|
+
const payload = JSON.stringify({ ak: key.ak, sk: key.sk }, null, 2);
|
|
1269
|
+
await mkdir(CRED_DIR, { recursive: true });
|
|
1270
|
+
const enc = dpapiEncrypt(payload);
|
|
1271
|
+
if (enc) {
|
|
1272
|
+
await writeFile(CRED_ENC_PATH, enc, "utf8");
|
|
1273
|
+
try {
|
|
1274
|
+
await rename(DEFAULT_CRED_PATH, `${DEFAULT_CRED_PATH}.bak`);
|
|
1275
|
+
} catch {
|
|
1276
|
+
}
|
|
1277
|
+
return { encrypted: true, path: CRED_ENC_PATH };
|
|
1278
|
+
}
|
|
1279
|
+
await writeFile(DEFAULT_CRED_PATH, payload, "utf8");
|
|
1280
|
+
return { encrypted: false, path: DEFAULT_CRED_PATH };
|
|
1281
|
+
}
|
|
1282
|
+
async function migratePlaintextToEncrypted() {
|
|
1283
|
+
try {
|
|
1284
|
+
const already = await readFile(CRED_ENC_PATH, "utf8").catch(() => null);
|
|
1285
|
+
if (already) return false;
|
|
1286
|
+
const plain = await fromFile(DEFAULT_CRED_PATH);
|
|
1287
|
+
if (!plain) return false;
|
|
1288
|
+
const r = await saveCredentials({ ak: plain.ak, sk: plain.sk });
|
|
1289
|
+
return r.encrypted;
|
|
1290
|
+
} catch {
|
|
1291
|
+
return false;
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
async function candidateCredentials(path = DEFAULT_CRED_PATH) {
|
|
1295
|
+
const out = [];
|
|
1296
|
+
const env = fromEnv();
|
|
1297
|
+
if (env) out.push({ key: env, source: "env", label: "\u73AF\u5883\u53D8\u91CF MADAO_AK/MADAO_SK" });
|
|
1298
|
+
const encrypted = await fromEncryptedFile();
|
|
1299
|
+
if (encrypted) {
|
|
1300
|
+
out.push({ key: encrypted, source: "file", path: CRED_ENC_PATH, label: `\u52A0\u5BC6\u51ED\u8BC1 ${CRED_ENC_PATH}` });
|
|
1301
|
+
}
|
|
1302
|
+
const file = await fromFile(path);
|
|
1303
|
+
if (file) out.push({ key: file, source: "file", path, label: `\u51ED\u8BC1\u6587\u4EF6 ${path}\uFF08\u660E\u6587\uFF09` });
|
|
1304
|
+
if (path !== LEGACY_CRED_PATH) {
|
|
1305
|
+
const legacy = await fromFile(LEGACY_CRED_PATH);
|
|
1306
|
+
if (legacy) {
|
|
1307
|
+
out.push({ key: legacy, source: "file", path: LEGACY_CRED_PATH, label: `\u51ED\u8BC1\u6587\u4EF6 ${LEGACY_CRED_PATH}\uFF08\u65E7\u8DEF\u5F84\uFF09` });
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
const borrowed = readCodeArtsCredential();
|
|
1311
|
+
if (borrowed) {
|
|
1312
|
+
out.push({
|
|
1313
|
+
key: {
|
|
1314
|
+
ak: borrowed.ak,
|
|
1315
|
+
sk: borrowed.sk,
|
|
1316
|
+
securityToken: borrowed.securityToken,
|
|
1317
|
+
account: borrowed.account,
|
|
1318
|
+
...borrowed.expiresAtMs ? { expiresAt: borrowed.expiresAtMs } : {}
|
|
1319
|
+
},
|
|
1320
|
+
source: "codearts",
|
|
1321
|
+
path: borrowed.sourcePath,
|
|
1322
|
+
expiresAtMs: borrowed.expiresAtMs,
|
|
1323
|
+
label: `\u7801\u9053\u5BA2\u6237\u7AEF\u767B\u5F55\u6001\uFF08${borrowed.account ?? "\u672A\u77E5\u8D26\u53F7"}\uFF09`
|
|
1324
|
+
});
|
|
1325
|
+
}
|
|
1326
|
+
return out;
|
|
1327
|
+
}
|
|
1328
|
+
async function loadCredentials(path = DEFAULT_CRED_PATH) {
|
|
1329
|
+
const env = fromEnv();
|
|
1330
|
+
if (env) return { key: env, source: "env" };
|
|
1331
|
+
const encrypted = await fromEncryptedFile();
|
|
1332
|
+
if (encrypted) return { key: encrypted, source: "file", path: CRED_ENC_PATH };
|
|
1333
|
+
const file = await fromFile(path);
|
|
1334
|
+
if (file) return { key: file, source: "file", path };
|
|
1335
|
+
if (path !== LEGACY_CRED_PATH) {
|
|
1336
|
+
const legacy = await fromFile(LEGACY_CRED_PATH);
|
|
1337
|
+
if (legacy) return { key: legacy, source: "file", path: LEGACY_CRED_PATH };
|
|
1338
|
+
}
|
|
1339
|
+
const borrowed = readCodeArtsCredential();
|
|
1340
|
+
if (borrowed) {
|
|
1341
|
+
return {
|
|
1342
|
+
key: {
|
|
1343
|
+
ak: borrowed.ak,
|
|
1344
|
+
sk: borrowed.sk,
|
|
1345
|
+
securityToken: borrowed.securityToken,
|
|
1346
|
+
account: borrowed.account,
|
|
1347
|
+
...borrowed.expiresAtMs ? { expiresAt: borrowed.expiresAtMs } : {}
|
|
1348
|
+
},
|
|
1349
|
+
source: "codearts",
|
|
1350
|
+
path: borrowed.sourcePath,
|
|
1351
|
+
expiresAtMs: borrowed.expiresAtMs
|
|
1352
|
+
};
|
|
1353
|
+
}
|
|
1354
|
+
throw new CredentialError(
|
|
1355
|
+
[
|
|
1356
|
+
"\u672A\u627E\u5230\u7801\u9053\u51ED\u8BC1\u3002\u4EFB\u9009\u5176\u4E00\uFF1A",
|
|
1357
|
+
" A) \u73AF\u5883\u53D8\u91CF MADAO_AK / MADAO_SK",
|
|
1358
|
+
` B) \u5199\u5165 ${path}\uFF1A{"ak":"...","sk":"..."}`,
|
|
1359
|
+
" C) \u6253\u5F00\u4E00\u6B21\u7801\u9053\u5BA2\u6237\u7AEF\u5E76\u786E\u8BA4\u5DF2\u767B\u5F55 \u2014\u2014 \u63D2\u4EF6\u4F1A\u81EA\u52A8\u501F\u7528\u5B83\u7684\u4E34\u65F6\u51ED\u8BC1",
|
|
1360
|
+
"ak/sk \u4E3A\u534E\u4E3A\u4E91 IAM \u8BBF\u95EE\u5BC6\u94A5\uFF08\u63A7\u5236\u53F0 \u2192 \u6211\u7684\u51ED\u8BC1 \u2192 \u8BBF\u95EE\u5BC6\u94A5\uFF09\u3002",
|
|
1361
|
+
"STS \u4E34\u65F6\u4EE4\u724C\u4F1A\u5728\u8FD0\u884C\u65F6\u81EA\u52A8\u6362\u53D6\uFF0C\u65E0\u9700\u624B\u586B\u3002"
|
|
1362
|
+
].join("\n")
|
|
1363
|
+
);
|
|
1364
|
+
}
|
|
1365
|
+
function maskKey(ak, sk) {
|
|
1366
|
+
const m = (s) => s.length <= 8 ? "***" : `${s.slice(0, 4)}\u2026${s.slice(-4)}`;
|
|
1367
|
+
return { ak: m(ak), sk: m(sk) };
|
|
1368
|
+
}
|
|
1369
|
+
var CRED_DIR, DEFAULT_CRED_PATH, CRED_ENC_PATH, LEGACY_CRED_PATH, CredentialError;
|
|
1370
|
+
var init_credentials = __esm({
|
|
1371
|
+
"src/credentials.ts"() {
|
|
1372
|
+
init_codearts_auth();
|
|
1373
|
+
init_dpapi();
|
|
1374
|
+
CRED_DIR = join2(process.env.APPDATA || join2(homedir2(), ".config"), "dsh-connect-madao");
|
|
1375
|
+
DEFAULT_CRED_PATH = join2(CRED_DIR, "credentials.json");
|
|
1376
|
+
CRED_ENC_PATH = join2(CRED_DIR, "credentials.enc");
|
|
1377
|
+
LEGACY_CRED_PATH = join2(homedir2(), ".dsh-connect-madao", "credentials.json");
|
|
1378
|
+
CredentialError = class extends Error {
|
|
1379
|
+
constructor(message) {
|
|
1380
|
+
super(message);
|
|
1381
|
+
this.name = "CredentialError";
|
|
1382
|
+
}
|
|
1383
|
+
};
|
|
1384
|
+
}
|
|
1385
|
+
});
|
|
1386
|
+
|
|
1387
|
+
// src/models.ts
|
|
1388
|
+
var models_exports = {};
|
|
1389
|
+
__export(models_exports, {
|
|
1390
|
+
FALLBACK_MODELS: () => FALLBACK_MODELS,
|
|
1391
|
+
discoverModels: () => discoverModels
|
|
1392
|
+
});
|
|
1393
|
+
function clampMaxOutput(fromGateway, fallback) {
|
|
1394
|
+
const base = fromGateway && fromGateway > 0 ? fromGateway : fallback ?? MAX_OUTPUT_CAP;
|
|
1395
|
+
return Math.min(base, MAX_OUTPUT_CAP);
|
|
1396
|
+
}
|
|
1397
|
+
async function discoverModels(client) {
|
|
1398
|
+
try {
|
|
1399
|
+
const raw = await client.getJson("/v1/model/builtin");
|
|
1400
|
+
const list = raw?.builtinModels ?? [];
|
|
1401
|
+
if (list.length === 0) return { models: FALLBACK_MODELS, source: "fallback", error: "\u7F51\u5173\u8FD4\u56DE\u7A7A\u6E05\u5355" };
|
|
1402
|
+
let variants = {};
|
|
1403
|
+
try {
|
|
1404
|
+
const tv = await client.postJson("/v1/model/thinking-variants", {
|
|
1405
|
+
model_names: list.map((m) => m.model_id)
|
|
1406
|
+
});
|
|
1407
|
+
variants = tv?.variants ?? {};
|
|
1408
|
+
} catch {
|
|
1409
|
+
}
|
|
1410
|
+
const models = list.filter((m) => m.model_id && m.enable !== false).map((m) => {
|
|
1411
|
+
const v = variants[m.model_id];
|
|
1412
|
+
const fb = FALLBACK_MODELS.find((f) => f.id === m.model_id);
|
|
1413
|
+
return {
|
|
1414
|
+
id: m.model_id,
|
|
1415
|
+
name: m.model_name || m.model_id,
|
|
1416
|
+
context: m.context_window ?? fb?.context ?? 0,
|
|
1417
|
+
// 单次输出上限不能照抄网关的 max_tokens。DSH 的压缩逻辑会把它
|
|
1418
|
+
// 当作 reservedCompletionTokens 从窗口里扣掉,同时还会再扣一份
|
|
1419
|
+
// headroomTokens(默认 65536)。照抄 65536 的话,202752 的窗口
|
|
1420
|
+
// 只剩 ~71k 可用,稍微长一点的会话就切不过去。
|
|
1421
|
+
// 这里封顶 MAX_OUTPUT_CAP,把剩下的还给对话上下文。
|
|
1422
|
+
maxOutput: clampMaxOutput(m.max_tokens, fb?.maxOutput),
|
|
1423
|
+
ratio: m.credit?.[0]?.ratio_display,
|
|
1424
|
+
supportsImages: m.supports_images === true,
|
|
1425
|
+
strengths: v?.strengths ?? [],
|
|
1426
|
+
defaultStrength: v?.default_strength || void 0,
|
|
1427
|
+
description: m.model_desc
|
|
1428
|
+
};
|
|
1429
|
+
});
|
|
1430
|
+
return { models, source: "gateway" };
|
|
1431
|
+
} catch (e) {
|
|
1432
|
+
return { models: FALLBACK_MODELS, source: "fallback", error: String(e?.message ?? e) };
|
|
1433
|
+
}
|
|
1434
|
+
}
|
|
1435
|
+
var MAX_OUTPUT_CAP, FALLBACK_MODELS;
|
|
1436
|
+
var init_models = __esm({
|
|
1437
|
+
"src/models.ts"() {
|
|
1438
|
+
MAX_OUTPUT_CAP = 32768;
|
|
1439
|
+
FALLBACK_MODELS = [
|
|
1440
|
+
{ id: "deepseek-v4.1-flash", name: "DeepSeek-V4.1-Flash", context: 1048576, maxOutput: 32768, ratio: "0.18x", supportsImages: true, strengths: [] },
|
|
1441
|
+
{ id: "deepseek-v4.1-flash-1017", name: "DeepSeek-V4.1-Flash-1017", context: 1048576, maxOutput: 32768, ratio: "0.18x", supportsImages: true, strengths: [] },
|
|
1442
|
+
{ id: "glm-5.3", name: "GLM-5.3", context: 1048576, maxOutput: 32768, ratio: "0.79x", supportsImages: false, strengths: [] },
|
|
1443
|
+
{ id: "glm-5.3-flash", name: "GLM-5.3-Flash", context: 1048576, maxOutput: 32768, ratio: "0.08x", supportsImages: true, strengths: [] },
|
|
1444
|
+
{ id: "GLM-5.2", name: "GLM-5.2", context: 202752, maxOutput: 32768, ratio: "0.7x", supportsImages: false, strengths: ["high", "max"], defaultStrength: "high" },
|
|
1445
|
+
{ id: "glm-5.2-sft-harmony", name: "GLM-5.2-ArkTS-SPARK", context: 202752, maxOutput: 32768, ratio: "0.7x", supportsImages: false, strengths: ["high", "max"], defaultStrength: "high" },
|
|
1446
|
+
{ id: "kimi-k3", name: "Kimi-K3", context: 1048576, maxOutput: 32768, ratio: "2.38x", supportsImages: true, strengths: [] },
|
|
1447
|
+
{ id: "kimi-k3.1-pro", name: "Kimi-K3.1-Pro", context: 1048576, maxOutput: 32768, ratio: "1.63x", supportsImages: true, strengths: [] },
|
|
1448
|
+
{ id: "openpangu-2.0-pro", name: "OpenPangu-2.0-Pro", context: 524288, maxOutput: 32768, ratio: "0.7x", supportsImages: false, strengths: [] },
|
|
1449
|
+
{ id: "openpangu-2.0-flash", name: "OpenPangu-2.0-Flash", context: 524288, maxOutput: 32768, ratio: "0.32x", supportsImages: false, strengths: [] },
|
|
1450
|
+
{ id: "speed", name: "\u667A\u901F\u6A21\u5F0F", context: 1048576, maxOutput: 32768, ratio: "0.18x", supportsImages: false, strengths: [] }
|
|
1451
|
+
];
|
|
1452
|
+
}
|
|
1453
|
+
});
|
|
1454
|
+
|
|
1455
|
+
// src/server.ts
|
|
1456
|
+
init_client();
|
|
1457
|
+
init_sts_provider();
|
|
1458
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
1459
|
+
import { createServer } from "node:http";
|
|
1460
|
+
import { writeFileSync } from "node:fs";
|
|
1461
|
+
import { join as join5 } from "node:path";
|
|
1462
|
+
|
|
1463
|
+
// src/protocol/body.ts
|
|
1464
|
+
var DEFAULT_MAX_TOKENS = 65536;
|
|
1465
|
+
function normalizePart(raw) {
|
|
1466
|
+
if (!raw || typeof raw !== "object") return null;
|
|
1467
|
+
if (raw.type === "text" && typeof raw.text === "string") {
|
|
1468
|
+
return { type: "text", text: raw.text };
|
|
1469
|
+
}
|
|
1470
|
+
if (raw.type === "image_url" && raw.image_url?.url) {
|
|
1471
|
+
return { type: "image_url", image_url: { url: String(raw.image_url.url) } };
|
|
1472
|
+
}
|
|
1473
|
+
return null;
|
|
1474
|
+
}
|
|
1475
|
+
function normalizeContent(content) {
|
|
1476
|
+
if (typeof content === "string") return content;
|
|
1477
|
+
if (content === null || content === void 0) return "";
|
|
1478
|
+
if (!Array.isArray(content)) {
|
|
1479
|
+
const single = normalizePart(content);
|
|
1480
|
+
if (single) return single.type === "text" ? single.text : [single];
|
|
1481
|
+
try {
|
|
1482
|
+
const s = JSON.stringify(content);
|
|
1483
|
+
return s && s !== "{}" ? s : "";
|
|
1484
|
+
} catch {
|
|
1485
|
+
return "";
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
const parts = [];
|
|
1489
|
+
for (const raw of content) {
|
|
1490
|
+
const p = normalizePart(raw);
|
|
1491
|
+
if (p) parts.push(p);
|
|
1492
|
+
}
|
|
1493
|
+
if (parts.length === 0) return "";
|
|
1494
|
+
if (parts.every((p) => p.type === "text")) {
|
|
1495
|
+
return parts.map((p) => p.text).join("");
|
|
1496
|
+
}
|
|
1497
|
+
return parts;
|
|
1498
|
+
}
|
|
1499
|
+
function hasUnsupportedContent(messages) {
|
|
1500
|
+
for (const m of messages ?? []) {
|
|
1501
|
+
if (!Array.isArray(m?.content)) continue;
|
|
1502
|
+
for (const part of m.content) {
|
|
1503
|
+
const t = part?.type;
|
|
1504
|
+
if (typeof t === "string" && t !== "text" && t !== "image_url") return t;
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
return null;
|
|
1508
|
+
}
|
|
1509
|
+
function buildUpstreamBody(req, overrides = {}) {
|
|
1510
|
+
const messages = (req.messages ?? []).map((m) => ({
|
|
1511
|
+
// 网关不认 `developer` 角色。
|
|
1512
|
+
// OpenAI 新规范里 DSH 用 developer 承载系统提示,而码道网关只接受
|
|
1513
|
+
// system/user/assistant/tool —— 遇到 developer 会**静默返回空响应**
|
|
1514
|
+
// (HTTP 200、finish=stop、content 为空),上层只能看到 EMPTY_RESPONSE,
|
|
1515
|
+
// 完全看不出原因。这里统一降级成 system。
|
|
1516
|
+
role: m.role === "developer" ? "system" : m.role,
|
|
1517
|
+
content: normalizeContent(m.content),
|
|
1518
|
+
...m.name ? { name: m.name } : {},
|
|
1519
|
+
...m.tool_call_id ? { tool_call_id: m.tool_call_id } : {},
|
|
1520
|
+
...m.tool_calls ? { tool_calls: m.tool_calls } : {}
|
|
1521
|
+
}));
|
|
1522
|
+
const body = {
|
|
1523
|
+
model: req.model,
|
|
1524
|
+
messages,
|
|
1525
|
+
max_tokens: req.max_tokens ?? DEFAULT_MAX_TOKENS,
|
|
1526
|
+
stream: true,
|
|
1527
|
+
// stream_options 必须转发。
|
|
1528
|
+
//
|
|
1529
|
+
// 踩过的坑:这里按白名单重建请求体,把 DSH 传来的
|
|
1530
|
+
// `stream_options: { include_usage: true }` 删掉了。而网关只有在
|
|
1531
|
+
// 带这个字段时才返回**完整** usage —— 不带就只给
|
|
1532
|
+
// prompt/completion/total 三个数字,不含
|
|
1533
|
+
// `prompt_tokens_details.cached_tokens`。
|
|
1534
|
+
//
|
|
1535
|
+
// 后果:DSH 的 Token 用量面板永远显示「缓存命中 0%、缓存读取 0」,
|
|
1536
|
+
// 而实际上缓存是工作的(实测同一个 2434 token 的请求,其中 2304
|
|
1537
|
+
// 来自缓存,约 95%),只是数字没被返回上来。
|
|
1538
|
+
...req.stream_options ? { stream_options: req.stream_options } : {},
|
|
1539
|
+
...typeof req.temperature === "number" ? { temperature: req.temperature } : {},
|
|
1540
|
+
...typeof req.top_p === "number" ? { top_p: req.top_p } : {},
|
|
1541
|
+
...req.stop ? { stop: req.stop } : {},
|
|
1542
|
+
...req.tools ? { tools: req.tools } : {},
|
|
1543
|
+
...req.tool_choice ? { tool_choice: req.tool_choice } : {},
|
|
1544
|
+
// 思考强度:取值来自 POST /v1/model/thinking-variants 的 strengths
|
|
1545
|
+
// (目前只有 GLM-5.2 / glm-5.2-sft-harmony 支持 high|max)
|
|
1546
|
+
// 思考强度。
|
|
1547
|
+
//
|
|
1548
|
+
// 网关认的是 **`reasoning_effort`**,不是 `strength` —— 之前一直发
|
|
1549
|
+
// `strength` 字段,网关当未知字段忽略,所以界面上换档位毫无效果。
|
|
1550
|
+
//
|
|
1551
|
+
// 实测(GLM-5.2,同一道题各跑 3 次取平均):
|
|
1552
|
+
// reasoning_effort=high → reasoning 1014 字
|
|
1553
|
+
// 不传 → reasoning 1254 字
|
|
1554
|
+
// reasoning_effort=max → reasoning 1323 字
|
|
1555
|
+
// 组内波动 σ≈75,组间差异 240/69,确认字段真的生效。
|
|
1556
|
+
//
|
|
1557
|
+
// `off` 走网关的 `none`(内核里 forceReasoningNone 也是这么发的)。
|
|
1558
|
+
...typeof req.strength === "string" && req.strength ? { reasoning_effort: req.strength === "off" ? "none" : req.strength } : {}
|
|
1559
|
+
};
|
|
1560
|
+
return { ...body, ...overrides };
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
// src/protocol/sse.ts
|
|
1564
|
+
function makeChunk(id, model, delta, finishReason = null) {
|
|
1565
|
+
return {
|
|
1566
|
+
id,
|
|
1567
|
+
object: "chat.completion.chunk",
|
|
1568
|
+
created: Math.floor(Date.now() / 1e3),
|
|
1569
|
+
model,
|
|
1570
|
+
choices: [{ index: 0, delta, finish_reason: finishReason }]
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
function sseLine(payload) {
|
|
1574
|
+
return `data: ${JSON.stringify(payload)}
|
|
1575
|
+
|
|
1576
|
+
`;
|
|
1577
|
+
}
|
|
1578
|
+
var SSE_DONE = "data: [DONE]\n\n";
|
|
1579
|
+
function parseUpstreamEvent(data) {
|
|
1580
|
+
const trimmed = data.trim();
|
|
1581
|
+
if (!trimmed) return {};
|
|
1582
|
+
if (trimmed === "[DONE]") return { done: true };
|
|
1583
|
+
let obj;
|
|
1584
|
+
try {
|
|
1585
|
+
obj = JSON.parse(trimmed);
|
|
1586
|
+
} catch {
|
|
1587
|
+
return {};
|
|
1588
|
+
}
|
|
1589
|
+
const out = { raw: obj };
|
|
1590
|
+
if (typeof obj.error_code === "string" && obj.error_code) {
|
|
1591
|
+
return {
|
|
1592
|
+
raw: obj,
|
|
1593
|
+
error: { code: obj.error_code, message: String(obj.error_msg ?? obj.error_message ?? "") },
|
|
1594
|
+
done: true
|
|
1595
|
+
};
|
|
1596
|
+
}
|
|
1597
|
+
if (obj.error && typeof obj.error === "object" && !Array.isArray(obj.choices)) {
|
|
1598
|
+
return {
|
|
1599
|
+
raw: obj,
|
|
1600
|
+
error: { code: String(obj.error.code ?? obj.error.type ?? "upstream_error"), message: String(obj.error.message ?? "") },
|
|
1601
|
+
done: true
|
|
1602
|
+
};
|
|
1603
|
+
}
|
|
1604
|
+
if (Array.isArray(obj.choices)) {
|
|
1605
|
+
const out2 = { raw: obj };
|
|
1606
|
+
if (obj.usage) {
|
|
1607
|
+
out2.usage = { ...obj.usage };
|
|
1608
|
+
}
|
|
1609
|
+
const ch = obj.choices[0];
|
|
1610
|
+
if (!ch) return out2;
|
|
1611
|
+
const d = ch.delta ?? ch.message ?? {};
|
|
1612
|
+
if (typeof d.content === "string" && d.content) out2.text = d.content;
|
|
1613
|
+
if (typeof d.reasoning_content === "string" && d.reasoning_content) {
|
|
1614
|
+
out2.reasoning = d.reasoning_content;
|
|
1615
|
+
}
|
|
1616
|
+
if (typeof d.reasoning === "string" && d.reasoning) out2.reasoning = d.reasoning;
|
|
1617
|
+
if (Array.isArray(d.tool_calls) && d.tool_calls.length > 0) out2.toolCalls = d.tool_calls;
|
|
1618
|
+
if (ch.finish_reason) out2.finish = String(ch.finish_reason);
|
|
1619
|
+
return out2;
|
|
1620
|
+
}
|
|
1621
|
+
const type = typeof obj.type === "string" ? obj.type : "";
|
|
1622
|
+
if (type === "text-delta" || type === "text_delta") {
|
|
1623
|
+
out.text = obj.delta ?? obj.textDelta ?? obj.text ?? "";
|
|
1624
|
+
return out;
|
|
1625
|
+
}
|
|
1626
|
+
if (type === "reasoning" || type === "reasoning-delta") {
|
|
1627
|
+
out.reasoning = obj.delta ?? obj.textDelta ?? obj.text ?? "";
|
|
1628
|
+
return out;
|
|
1629
|
+
}
|
|
1630
|
+
if (type === "finish" || type === "finish-step") {
|
|
1631
|
+
out.finish = obj.finishReason ?? obj.finish_reason ?? "stop";
|
|
1632
|
+
if (obj.usage) {
|
|
1633
|
+
out.usage = {
|
|
1634
|
+
...obj.usage,
|
|
1635
|
+
prompt_tokens: obj.usage.promptTokens ?? obj.usage.prompt_tokens ?? 0,
|
|
1636
|
+
completion_tokens: obj.usage.completionTokens ?? obj.usage.completion_tokens ?? 0,
|
|
1637
|
+
total_tokens: obj.usage.totalTokens ?? obj.usage.total_tokens ?? 0
|
|
1638
|
+
};
|
|
1639
|
+
}
|
|
1640
|
+
return out;
|
|
1641
|
+
}
|
|
1642
|
+
if (type === "error") {
|
|
1643
|
+
out.finish = "error";
|
|
1644
|
+
return out;
|
|
1645
|
+
}
|
|
1646
|
+
if (type === "message.part.updated") {
|
|
1647
|
+
const part = obj.part ?? obj.properties?.part ?? {};
|
|
1648
|
+
if (part.type === "text" && typeof part.text === "string") out.text = part.text;
|
|
1649
|
+
if (part.type === "reasoning" && typeof part.text === "string") out.reasoning = part.text;
|
|
1650
|
+
return out;
|
|
1651
|
+
}
|
|
1652
|
+
return out;
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
// src/server.ts
|
|
1656
|
+
init_credentials();
|
|
1657
|
+
init_models();
|
|
1658
|
+
|
|
1659
|
+
// src/identity.ts
|
|
1660
|
+
function findJsonEnd(raw, start) {
|
|
1661
|
+
let depth = 0;
|
|
1662
|
+
let inString = false;
|
|
1663
|
+
let escaped = false;
|
|
1664
|
+
for (let i = start; i < raw.length; i++) {
|
|
1665
|
+
const ch = raw[i];
|
|
1666
|
+
if (inString) {
|
|
1667
|
+
if (escaped) escaped = false;
|
|
1668
|
+
else if (ch === "\\") escaped = true;
|
|
1669
|
+
else if (ch === '"') inString = false;
|
|
1670
|
+
continue;
|
|
1671
|
+
}
|
|
1672
|
+
if (ch === '"') inString = true;
|
|
1673
|
+
else if (ch === "{") depth++;
|
|
1674
|
+
else if (ch === "}") {
|
|
1675
|
+
depth--;
|
|
1676
|
+
if (depth === 0) return i;
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
return -1;
|
|
1680
|
+
}
|
|
1681
|
+
function parseStsIdentity(securityToken) {
|
|
1682
|
+
if (!securityToken) return {};
|
|
1683
|
+
try {
|
|
1684
|
+
const raw = Buffer.from(securityToken, "base64").toString("utf8");
|
|
1685
|
+
const start = raw.indexOf("{");
|
|
1686
|
+
if (start < 0) return {};
|
|
1687
|
+
const end = findJsonEnd(raw, start);
|
|
1688
|
+
if (end < 0) return {};
|
|
1689
|
+
const obj = JSON.parse(raw.slice(start, end + 1));
|
|
1690
|
+
const user = obj?.user ?? {};
|
|
1691
|
+
return {
|
|
1692
|
+
accountName: user?.name ?? user?.domain?.name,
|
|
1693
|
+
domainId: user?.domain?.id,
|
|
1694
|
+
userId: user?.id,
|
|
1695
|
+
userType: typeof user?.user_type === "number" ? user.user_type : void 0
|
|
1696
|
+
};
|
|
1697
|
+
} catch {
|
|
1698
|
+
return {};
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
// src/credit-expiry.ts
|
|
1703
|
+
var WARN_DAYS = 7;
|
|
1704
|
+
var URGENT_DAYS = 2;
|
|
1705
|
+
function evaluateExpiry(credit, now = /* @__PURE__ */ new Date()) {
|
|
1706
|
+
if (!credit) return { level: "none", message: "", expiringAmount: 0, daysLeft: null, dueDate: null };
|
|
1707
|
+
const expiring = Number(credit.expiringAmount ?? 0);
|
|
1708
|
+
if (!Number.isFinite(expiring) || Math.round(expiring) <= 0) {
|
|
1709
|
+
return { level: "none", message: "", expiringAmount: 0, daysLeft: null, dueDate: null };
|
|
1710
|
+
}
|
|
1711
|
+
const due = parseDate(credit.packageEnd);
|
|
1712
|
+
const daysLeft = due ? Math.round((due.getTime() - startOfDay(now).getTime()) / 864e5) : null;
|
|
1713
|
+
let level = "info";
|
|
1714
|
+
if (daysLeft != null) {
|
|
1715
|
+
if (daysLeft <= URGENT_DAYS) level = "urgent";
|
|
1716
|
+
else if (daysLeft <= WARN_DAYS) level = "warn";
|
|
1717
|
+
} else {
|
|
1718
|
+
level = "info";
|
|
1719
|
+
}
|
|
1720
|
+
const amount = formatAmount(expiring);
|
|
1721
|
+
const when = daysLeft == null ? "\u5373\u5C06\u5230\u671F" : daysLeft <= 0 ? "\u5DF2\u5230\u671F" : `\u8FD8\u6709 ${daysLeft} \u5929\u5230\u671F\uFF08${credit.packageEnd}\uFF09`;
|
|
1722
|
+
return {
|
|
1723
|
+
level,
|
|
1724
|
+
expiringAmount: expiring,
|
|
1725
|
+
daysLeft,
|
|
1726
|
+
dueDate: credit.packageEnd ?? null,
|
|
1727
|
+
message: `${amount} \u79EF\u5206${when}\uFF0C\u8FC7\u671F\u5373\u6E05\u96F6`
|
|
1728
|
+
};
|
|
1729
|
+
}
|
|
1730
|
+
function startOfDay(d) {
|
|
1731
|
+
const x = new Date(d.getTime());
|
|
1732
|
+
x.setHours(0, 0, 0, 0);
|
|
1733
|
+
return x;
|
|
1734
|
+
}
|
|
1735
|
+
function parseDate(s) {
|
|
1736
|
+
if (!s) return null;
|
|
1737
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})(?:$|[T\s])/.exec(String(s).trim());
|
|
1738
|
+
if (!m) return null;
|
|
1739
|
+
const month = Number(m[2]);
|
|
1740
|
+
const day = Number(m[3]);
|
|
1741
|
+
if (month < 1 || month > 12 || day < 1 || day > 31) return null;
|
|
1742
|
+
const d = new Date(Number(m[1]), month - 1, day);
|
|
1743
|
+
return Number.isNaN(d.getTime()) ? null : d;
|
|
1744
|
+
}
|
|
1745
|
+
function formatAmount(n) {
|
|
1746
|
+
return Math.round(n).toLocaleString("zh-CN");
|
|
1747
|
+
}
|
|
1748
|
+
|
|
1749
|
+
// src/checkin.ts
|
|
1750
|
+
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
1751
|
+
|
|
1752
|
+
// src/protocol/log.ts
|
|
1753
|
+
import { appendFileSync, mkdirSync } from "node:fs";
|
|
1754
|
+
import { homedir as homedir3 } from "node:os";
|
|
1755
|
+
import { join as join3 } from "node:path";
|
|
1756
|
+
function logDir() {
|
|
1757
|
+
return join3(homedir3(), ".dsh-connect-madao");
|
|
1758
|
+
}
|
|
1759
|
+
function chatLog(line) {
|
|
1760
|
+
try {
|
|
1761
|
+
const dir = logDir();
|
|
1762
|
+
mkdirSync(dir, { recursive: true });
|
|
1763
|
+
appendFileSync(join3(dir, "chat.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${line}
|
|
1764
|
+
`, "utf8");
|
|
1765
|
+
} catch {
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
|
|
1769
|
+
// src/checkin.ts
|
|
1770
|
+
var DAILY_CHECKIN_CAMPAIGN = 34;
|
|
1771
|
+
function isCheckinCampaign(it) {
|
|
1772
|
+
if (!it) return false;
|
|
1773
|
+
const type = String(it?.type ?? "").toUpperCase();
|
|
1774
|
+
const event = String(it?.extra?.triggerEvent ?? "").toLowerCase();
|
|
1775
|
+
const title = String(it?.title ?? "");
|
|
1776
|
+
if (type === "USER_LOGIN") return true;
|
|
1777
|
+
if (event === "user.login") return true;
|
|
1778
|
+
return /签到/.test(title) && !/报名|认证|注册|邀请/.test(title);
|
|
1779
|
+
}
|
|
1780
|
+
function viewOf(it) {
|
|
1781
|
+
return {
|
|
1782
|
+
campaignId: Number(it?.campaignId),
|
|
1783
|
+
title: String(it?.title ?? `campaign=${it?.campaignId}`),
|
|
1784
|
+
type: it?.type ?? null,
|
|
1785
|
+
triggerEvent: it?.extra?.triggerEvent ?? null,
|
|
1786
|
+
triggerMode: it?.extra?.triggerMode ?? null,
|
|
1787
|
+
status: it?.status ?? null,
|
|
1788
|
+
claimable: it?.claimable === true,
|
|
1789
|
+
pendingAmount: Number(it?.pendingTotalAmount ?? 0),
|
|
1790
|
+
benefitAmount: Number(it?.benefitAmount ?? 0),
|
|
1791
|
+
benefitUnit: String(it?.benefitUnit ?? "CREDIT"),
|
|
1792
|
+
expireAt: it?.expireAt ?? null
|
|
1793
|
+
};
|
|
1794
|
+
}
|
|
1795
|
+
async function fetchCampaigns(client) {
|
|
1796
|
+
const d = await client.getJson("/v1/ops/delivery?channel=IDE");
|
|
1797
|
+
const items = d?.data?.items;
|
|
1798
|
+
return Array.isArray(items) ? items : [];
|
|
1799
|
+
}
|
|
1800
|
+
async function queryCheckin(client) {
|
|
1801
|
+
const items = await fetchCampaigns(client);
|
|
1802
|
+
const campaigns = items.map(viewOf);
|
|
1803
|
+
const daily = items.find((x) => Number(x?.campaignId) === DAILY_CHECKIN_CAMPAIGN);
|
|
1804
|
+
if (!daily) {
|
|
1805
|
+
return {
|
|
1806
|
+
ok: true,
|
|
1807
|
+
available: false,
|
|
1808
|
+
reason: "\u7F51\u5173\u7684\u798F\u5229\u5217\u8868\u91CC\u6CA1\u6709\u6BCF\u65E5\u7B7E\u5230\u6D3B\u52A8\uFF08campaignId=34\uFF09",
|
|
1809
|
+
campaigns
|
|
1810
|
+
};
|
|
1811
|
+
}
|
|
1812
|
+
const v = viewOf(daily);
|
|
1813
|
+
return {
|
|
1814
|
+
ok: true,
|
|
1815
|
+
available: true,
|
|
1816
|
+
campaignId: v.campaignId,
|
|
1817
|
+
title: v.title,
|
|
1818
|
+
status: v.status,
|
|
1819
|
+
claimable: v.claimable,
|
|
1820
|
+
pendingAmount: v.pendingAmount,
|
|
1821
|
+
unit: v.benefitUnit,
|
|
1822
|
+
expireAt: v.expireAt,
|
|
1823
|
+
campaigns
|
|
1824
|
+
};
|
|
1825
|
+
}
|
|
1826
|
+
async function claimCheckin(client) {
|
|
1827
|
+
const state = await queryCheckin(client);
|
|
1828
|
+
if (!state.available) return state;
|
|
1829
|
+
if (!state.claimable || state.status !== "ELIGIBLE") {
|
|
1830
|
+
const why = state.status === "CONSUMED" ? "\u4ECA\u65E5\u5DF2\u9886\u53D6\uFF08\u79EF\u5206\u5DF2\u7528\u5B8C\uFF09" : state.status === "CONFIRMED" ? "\u4ECA\u65E5\u5DF2\u9886\u53D6\uFF08\u5DF2\u5230\u8D26\uFF09" : state.status === "CLAIMED" ? "\u4ECA\u65E5\u5DF2\u9886\u53D6\uFF08\u5F85\u786E\u8BA4\uFF0C\u5DF2\u81EA\u52A8\u8865 confirm\uFF09" : "\u5F53\u524D\u4E0D\u53EF\u9886\u53D6";
|
|
1831
|
+
return { ...state, claimed: false, reason: `${why}\uFF08status=${state.status ?? "null"}\uFF09` };
|
|
1832
|
+
}
|
|
1833
|
+
const r = await client.postJson("/v1/ops/claim", {
|
|
1834
|
+
campaignId: DAILY_CHECKIN_CAMPAIGN,
|
|
1835
|
+
idempotentKey: randomUUID2(),
|
|
1836
|
+
channel: "IDE"
|
|
1837
|
+
});
|
|
1838
|
+
const claimed = r?.code === 0;
|
|
1839
|
+
chatLog(
|
|
1840
|
+
`checkin ${claimed ? "OK" : "FAIL"} campaign=${DAILY_CHECKIN_CAMPAIGN} ${JSON.stringify(r?.data ?? r).slice(0, 200)}`
|
|
1841
|
+
);
|
|
1842
|
+
if (claimed) await confirmClaim(client, DAILY_CHECKIN_CAMPAIGN);
|
|
1843
|
+
return {
|
|
1844
|
+
...state,
|
|
1845
|
+
claimed,
|
|
1846
|
+
status: r?.data?.status ?? (claimed ? "CLAIMED" : state.status),
|
|
1847
|
+
amount: r?.data?.totalAmount ?? state.pendingAmount,
|
|
1848
|
+
claimedAt: r?.data?.claimedAt ?? null,
|
|
1849
|
+
...claimed ? {} : { reason: String(r?.message ?? "\u9886\u53D6\u5931\u8D25") }
|
|
1850
|
+
};
|
|
1851
|
+
}
|
|
1852
|
+
async function confirmClaim(client, campaignId) {
|
|
1853
|
+
try {
|
|
1854
|
+
const r = await client.postJson("/v1/ops/confirm", { campaignId });
|
|
1855
|
+
const ok = r?.code === 0;
|
|
1856
|
+
chatLog(`confirm ${ok ? "OK" : "FAIL"} campaign=${campaignId} ${JSON.stringify(r?.data ?? r).slice(0, 160)}`);
|
|
1857
|
+
return ok;
|
|
1858
|
+
} catch (e) {
|
|
1859
|
+
chatLog(`confirm ERROR campaign=${campaignId} ${String(e?.message ?? e).slice(0, 160)}`);
|
|
1860
|
+
return false;
|
|
1861
|
+
}
|
|
1862
|
+
}
|
|
1863
|
+
async function claimAllCheckins(client) {
|
|
1864
|
+
const items = await fetchCampaigns(client);
|
|
1865
|
+
const campaigns = items.map(viewOf);
|
|
1866
|
+
const claimed = [];
|
|
1867
|
+
const skipped = [];
|
|
1868
|
+
for (const it of items) {
|
|
1869
|
+
const id = Number(it?.campaignId);
|
|
1870
|
+
const title = String(it?.title ?? `campaign=${id}`);
|
|
1871
|
+
const mode = it?.extra?.triggerMode;
|
|
1872
|
+
if (!Number.isFinite(id)) continue;
|
|
1873
|
+
if (mode === "AUTO_GRANT") {
|
|
1874
|
+
skipped.push({ campaignId: id, title, reason: "\u81EA\u52A8\u53D1\u653E\uFF0C\u65E0\u9700\u9886\u53D6" });
|
|
1875
|
+
continue;
|
|
1876
|
+
}
|
|
1877
|
+
if (it?.status === "CLAIMED") {
|
|
1878
|
+
const done = await confirmClaim(client, id);
|
|
1879
|
+
skipped.push({
|
|
1880
|
+
campaignId: id,
|
|
1881
|
+
title,
|
|
1882
|
+
reason: done ? "\u5DF2\u8865\u786E\u8BA4\uFF08\u6B64\u524D\u5DF2\u9886\u672A\u786E\u8BA4\uFF09" : "\u8865\u786E\u8BA4\u5931\u8D25\uFF0C\u4E0B\u8F6E\u518D\u8BD5"
|
|
1883
|
+
});
|
|
1884
|
+
continue;
|
|
1885
|
+
}
|
|
1886
|
+
if (!isCheckinCampaign(it)) {
|
|
1887
|
+
skipped.push({
|
|
1888
|
+
campaignId: id,
|
|
1889
|
+
title,
|
|
1890
|
+
reason: `\u975E\u7B7E\u5230\u7C7B\u6D3B\u52A8\uFF0C\u8DF3\u8FC7\u81EA\u52A8\u9886\u53D6\uFF08type=${it?.type ?? "-"}, event=${it?.extra?.triggerEvent ?? "-"}\uFF09`
|
|
1891
|
+
});
|
|
1892
|
+
continue;
|
|
1893
|
+
}
|
|
1894
|
+
if (!it?.claimable || it?.status !== "ELIGIBLE") {
|
|
1895
|
+
skipped.push({
|
|
1896
|
+
campaignId: id,
|
|
1897
|
+
title,
|
|
1898
|
+
reason: `\u5F53\u524D\u4E0D\u53EF\u9886\uFF08status=${it?.status ?? "null"}, claimable=${it?.claimable}\uFF09`
|
|
1899
|
+
});
|
|
1900
|
+
continue;
|
|
1901
|
+
}
|
|
1902
|
+
try {
|
|
1903
|
+
const r = await client.postJson("/v1/ops/claim", {
|
|
1904
|
+
campaignId: id,
|
|
1905
|
+
idempotentKey: randomUUID2(),
|
|
1906
|
+
channel: "IDE"
|
|
1907
|
+
});
|
|
1908
|
+
const ok = r?.code === 0;
|
|
1909
|
+
chatLog(`claimAll ${ok ? "OK" : "FAIL"} campaign=${id} ${JSON.stringify(r?.data ?? r).slice(0, 160)}`);
|
|
1910
|
+
if (ok) {
|
|
1911
|
+
const confirmed = await confirmClaim(client, id);
|
|
1912
|
+
claimed.push({
|
|
1913
|
+
campaignId: id,
|
|
1914
|
+
title,
|
|
1915
|
+
amount: Number(r?.data?.totalAmount ?? it?.pendingTotalAmount ?? it?.benefitAmount ?? 0),
|
|
1916
|
+
confirmed
|
|
1917
|
+
});
|
|
1918
|
+
} else {
|
|
1919
|
+
skipped.push({
|
|
1920
|
+
campaignId: id,
|
|
1921
|
+
title,
|
|
1922
|
+
reason: `${String(r?.message ?? "\u9886\u53D6\u5931\u8D25")}\uFF08code=${r?.code ?? "-"}\uFF09`
|
|
1923
|
+
});
|
|
1924
|
+
}
|
|
1925
|
+
} catch (e) {
|
|
1926
|
+
skipped.push({ campaignId: id, title, reason: String(e?.message ?? e) });
|
|
1927
|
+
}
|
|
1928
|
+
}
|
|
1929
|
+
return { ok: true, claimed, skipped, campaigns };
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
// src/settings.ts
|
|
1933
|
+
import { mkdir as mkdir2, readFile as readFile2, rename as rename2, writeFile as writeFile2 } from "node:fs/promises";
|
|
1934
|
+
import { homedir as homedir4 } from "node:os";
|
|
1935
|
+
import { join as join4 } from "node:path";
|
|
1936
|
+
var SETTINGS_FILENAME = "dsh-connect-madao-state.json";
|
|
1937
|
+
function defaults() {
|
|
1938
|
+
return { schemaVersion: 1, composerChip: true, autoCheckin: false, hiddenModels: [], contextCaps: {} };
|
|
1939
|
+
}
|
|
1940
|
+
var DEFAULT_SETTINGS = Object.freeze(defaults());
|
|
1941
|
+
function normalizeCaps(raw) {
|
|
1942
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return {};
|
|
1943
|
+
const out = {};
|
|
1944
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
1945
|
+
if (key.length === 0) continue;
|
|
1946
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) continue;
|
|
1947
|
+
out[key] = Math.round(value);
|
|
1948
|
+
}
|
|
1949
|
+
return out;
|
|
1950
|
+
}
|
|
1951
|
+
function settingsPath(env = process.env) {
|
|
1952
|
+
const home = typeof env.DSH_HOME === "string" && env.DSH_HOME.length > 0 ? env.DSH_HOME : join4(homedir4(), ".dsh");
|
|
1953
|
+
return join4(home, SETTINGS_FILENAME);
|
|
1954
|
+
}
|
|
1955
|
+
function normalizeSettings(raw) {
|
|
1956
|
+
if (typeof raw !== "object" || raw === null) return defaults();
|
|
1957
|
+
const record = raw;
|
|
1958
|
+
const hiddenModels = Array.isArray(record.hiddenModels) ? Array.from(
|
|
1959
|
+
new Set(
|
|
1960
|
+
record.hiddenModels.filter(
|
|
1961
|
+
(value) => typeof value === "string" && value.length > 0
|
|
1962
|
+
)
|
|
1963
|
+
)
|
|
1964
|
+
) : [];
|
|
1965
|
+
return {
|
|
1966
|
+
schemaVersion: 1,
|
|
1967
|
+
composerChip: typeof record.composerChip === "boolean" ? record.composerChip : DEFAULT_SETTINGS.composerChip,
|
|
1968
|
+
autoCheckin: typeof record.autoCheckin === "boolean" ? record.autoCheckin : DEFAULT_SETTINGS.autoCheckin,
|
|
1969
|
+
hiddenModels,
|
|
1970
|
+
contextCaps: normalizeCaps(record.contextCaps)
|
|
1971
|
+
};
|
|
1972
|
+
}
|
|
1973
|
+
async function readSettings(env = process.env) {
|
|
1974
|
+
let text;
|
|
1975
|
+
try {
|
|
1976
|
+
text = await readFile2(settingsPath(env), "utf8");
|
|
1977
|
+
} catch {
|
|
1978
|
+
return defaults();
|
|
1979
|
+
}
|
|
1980
|
+
try {
|
|
1981
|
+
return normalizeSettings(JSON.parse(text));
|
|
1982
|
+
} catch {
|
|
1983
|
+
return defaults();
|
|
1984
|
+
}
|
|
1985
|
+
}
|
|
1986
|
+
async function writeSettings(next, env = process.env) {
|
|
1987
|
+
const target = settingsPath(env);
|
|
1988
|
+
await mkdir2(join4(target, ".."), { recursive: true });
|
|
1989
|
+
const tmp = `${target}.${process.pid}.tmp`;
|
|
1990
|
+
await writeFile2(tmp, `${JSON.stringify(next, null, 2)}
|
|
1991
|
+
`, { encoding: "utf8", mode: 384 });
|
|
1992
|
+
await rename2(tmp, target);
|
|
1993
|
+
return next;
|
|
1994
|
+
}
|
|
1995
|
+
async function patchSettings(patch, env = process.env) {
|
|
1996
|
+
const current = await readSettings(env);
|
|
1997
|
+
const next = normalizeSettings({ ...current, ...patch });
|
|
1998
|
+
await writeSettings(next, env);
|
|
1999
|
+
chatLog(
|
|
2000
|
+
`settings updated: composerChip=${next.composerChip} autoCheckin=${next.autoCheckin} hiddenModels=${next.hiddenModels.length} contextCaps=${Object.keys(next.contextCaps).length}`
|
|
2001
|
+
);
|
|
2002
|
+
return next;
|
|
2003
|
+
}
|
|
2004
|
+
|
|
2005
|
+
// src/host-patch.ts
|
|
2006
|
+
function displayName(m) {
|
|
2007
|
+
return m.ratio ? `${m.name} \xB7 ${m.ratio}` : m.name;
|
|
2008
|
+
}
|
|
2009
|
+
var CONTEXT_DISPLAY_FACTOR = 1;
|
|
2010
|
+
function displayContextWindow(real) {
|
|
2011
|
+
if (!Number.isFinite(real) || real <= 0) return real;
|
|
2012
|
+
return Math.max(real, Math.round(real * CONTEXT_DISPLAY_FACTOR));
|
|
2013
|
+
}
|
|
2014
|
+
function buildProviderModel(m) {
|
|
2015
|
+
const config = {
|
|
2016
|
+
id: m.id,
|
|
2017
|
+
name: displayName(m),
|
|
2018
|
+
contextWindow: displayContextWindow(m.context),
|
|
2019
|
+
maxTokens: m.maxOutput,
|
|
2020
|
+
// 声明 image 输入,让 DSH 自己把「支持图片」的标记画在它管理的右侧位置,
|
|
2021
|
+
// 而不是把 👁 拼进 name(那样位置会随名字长度浮动,还容易被截断)。
|
|
2022
|
+
//
|
|
2023
|
+
// 代价:DSH 会允许附图。但桥接的 flattenContent 只转发文本,
|
|
2024
|
+
// 所以 server 侧对带图片的请求会返回明确错误,而不是静默丢弃 ——
|
|
2025
|
+
// 见 assertTextOnly()。
|
|
2026
|
+
input: m.supportsImages ? ["text", "image"] : ["text"],
|
|
2027
|
+
reasoningEfforts: false
|
|
2028
|
+
};
|
|
2029
|
+
if (m.strengths.length > 0) {
|
|
2030
|
+
const levels = Array.from(/* @__PURE__ */ new Set(["low", ...m.strengths]));
|
|
2031
|
+
config.reasoningEfforts = Object.fromEntries([["off", null], ...levels.map((lv) => [lv, lv])]);
|
|
2032
|
+
}
|
|
2033
|
+
return config;
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
// src/model-config.ts
|
|
2037
|
+
var PROVIDER_ID = "madao";
|
|
2038
|
+
var PROVIDER_DISPLAY_NAME = "\u7801\u9053 CodeArts";
|
|
2039
|
+
var PROVIDER_HEADERS = { Authorization: "Bearer bridge-local" };
|
|
2040
|
+
function selectModels(models, settings) {
|
|
2041
|
+
const hidden = new Set(settings.hiddenModels ?? []);
|
|
2042
|
+
const caps = settings.contextCaps ?? {};
|
|
2043
|
+
return models.filter((model) => !hidden.has(model.id)).map((model) => {
|
|
2044
|
+
const cap = caps[model.id];
|
|
2045
|
+
if (typeof cap !== "number" || !Number.isFinite(cap) || cap <= 0 || cap >= model.context) {
|
|
2046
|
+
return model;
|
|
2047
|
+
}
|
|
2048
|
+
return { ...model, context: Math.round(cap) };
|
|
2049
|
+
});
|
|
2050
|
+
}
|
|
2051
|
+
function buildProviderEntry(models, port) {
|
|
2052
|
+
return {
|
|
2053
|
+
displayName: PROVIDER_DISPLAY_NAME,
|
|
2054
|
+
api: "openai-completions",
|
|
2055
|
+
baseURL: `http://127.0.0.1:${port}/v1`,
|
|
2056
|
+
headers: { ...PROVIDER_HEADERS },
|
|
2057
|
+
models: models.map(buildProviderModel)
|
|
2058
|
+
};
|
|
2059
|
+
}
|
|
2060
|
+
function mergeProviderConfig(current, inherited, models, port) {
|
|
2061
|
+
const hasCurrent = typeof current === "object" && current !== null && Object.keys(current).length > 0;
|
|
2062
|
+
const base = (hasCurrent ? current : inherited) ?? {};
|
|
2063
|
+
const next = structuredClone(base);
|
|
2064
|
+
const providers = typeof next.providers === "object" && next.providers !== null && !Array.isArray(next.providers) ? next.providers : {};
|
|
2065
|
+
next.providers = { ...providers, [PROVIDER_ID]: buildProviderEntry(models, port) };
|
|
2066
|
+
return next;
|
|
2067
|
+
}
|
|
2068
|
+
async function applyModelSelection(dshCtx, models, settings, port) {
|
|
2069
|
+
const selected = selectModels(models, settings);
|
|
2070
|
+
if (selected.length === 0) {
|
|
2071
|
+
return { mode: "failed", error: "\u81F3\u5C11\u8981\u4FDD\u7559\u4E00\u4E2A\u6A21\u578B\uFF0C\u5426\u5219\u6A21\u578B\u9009\u62E9\u5668\u4F1A\u6574\u4E2A\u7A7A\u6389\u3002", applied: 0 };
|
|
2072
|
+
}
|
|
2073
|
+
const ctx = dshCtx;
|
|
2074
|
+
const editor = ctx?.get?.("configEditor");
|
|
2075
|
+
if (!editor || typeof editor.entries !== "function" || typeof editor.edit !== "function") {
|
|
2076
|
+
return { mode: "unavailable", error: "\u5F53\u524D\u5BBF\u4E3B\u6CA1\u6709\u63D0\u4F9B configEditor \u670D\u52A1\u3002", applied: 0 };
|
|
2077
|
+
}
|
|
2078
|
+
let entry;
|
|
2079
|
+
try {
|
|
2080
|
+
entry = editor.entries().find((candidate) => candidate?.options?.id === "llm-pi-ai");
|
|
2081
|
+
} catch (e) {
|
|
2082
|
+
return { mode: "failed", error: String(e?.message ?? e), applied: 0 };
|
|
2083
|
+
}
|
|
2084
|
+
if (!entry) {
|
|
2085
|
+
return { mode: "unavailable", error: "\u5F53\u524D profile \u91CC\u627E\u4E0D\u5230 llm-pi-ai \u8FD9\u4E00\u884C\u3002", applied: 0 };
|
|
2086
|
+
}
|
|
2087
|
+
const edit = () => editor.edit(entry, (current, inherited) => mergeProviderConfig(current, inherited, selected, port));
|
|
2088
|
+
try {
|
|
2089
|
+
const hmr = ctx?.get?.("hmr");
|
|
2090
|
+
const store = hmr?.executing?.getStore?.();
|
|
2091
|
+
if (store && typeof hmr?.executing?.exit === "function") {
|
|
2092
|
+
await hmr.executing.exit(edit);
|
|
2093
|
+
} else {
|
|
2094
|
+
await edit();
|
|
2095
|
+
}
|
|
2096
|
+
return { mode: "live", applied: selected.length };
|
|
2097
|
+
} catch (e) {
|
|
2098
|
+
return { mode: "failed", error: String(e?.message ?? e), applied: 0 };
|
|
2099
|
+
}
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
// src/server.ts
|
|
2103
|
+
async function ensureFreshClient(ctx) {
|
|
2104
|
+
if (!ctx.sts || !ctx.loaded) return;
|
|
2105
|
+
if (ctx.loaded.key.securityToken) return;
|
|
2106
|
+
try {
|
|
2107
|
+
const creds = await ctx.sts.get();
|
|
2108
|
+
if (ctx.lastCreds !== creds) {
|
|
2109
|
+
ctx.client = new MadaoClient({ credentials: creds });
|
|
2110
|
+
ctx.lastCreds = creds;
|
|
2111
|
+
chatLog("client rebuilt with refreshed STS");
|
|
2112
|
+
}
|
|
2113
|
+
} catch (e) {
|
|
2114
|
+
chatLog(`STS refresh failed: ${String(e?.message ?? e).slice(0, 160)}`);
|
|
2115
|
+
}
|
|
2116
|
+
}
|
|
2117
|
+
async function startServer(opts = {}) {
|
|
2118
|
+
const port = opts.port ?? 8765;
|
|
2119
|
+
const host = opts.host ?? "127.0.0.1";
|
|
2120
|
+
const ctx = {
|
|
2121
|
+
client: null,
|
|
2122
|
+
sts: null,
|
|
2123
|
+
loaded: null,
|
|
2124
|
+
loadError: null,
|
|
2125
|
+
models: opts.models ?? FALLBACK_MODELS,
|
|
2126
|
+
dsh: opts.dsh,
|
|
2127
|
+
port
|
|
2128
|
+
};
|
|
2129
|
+
try {
|
|
2130
|
+
if (await migratePlaintextToEncrypted()) {
|
|
2131
|
+
chatLog("credentials: \u5DF2\u628A\u660E\u6587\u51ED\u8BC1\u8FC1\u79FB\u4E3A DPAPI \u52A0\u5BC6");
|
|
2132
|
+
}
|
|
2133
|
+
const candidates = await candidateCredentials(opts.credentialPath);
|
|
2134
|
+
if (candidates.length === 0) {
|
|
2135
|
+
throw new Error("\u672A\u627E\u5230\u4EFB\u4F55\u53EF\u7528\u51ED\u8BC1\u6765\u6E90\uFF08\u73AF\u5883\u53D8\u91CF / \u51ED\u8BC1\u6587\u4EF6 / \u7801\u9053\u767B\u5F55\u6001\uFF09");
|
|
2136
|
+
}
|
|
2137
|
+
const failures = [];
|
|
2138
|
+
for (const c of candidates) {
|
|
2139
|
+
try {
|
|
2140
|
+
if (c.key.securityToken) {
|
|
2141
|
+
const probe = new MadaoClient({
|
|
2142
|
+
credentials: { ak: c.key.ak, sk: c.key.sk, securityToken: c.key.securityToken },
|
|
2143
|
+
gateway: opts.gateway
|
|
2144
|
+
});
|
|
2145
|
+
await probe.ensureSessionKey();
|
|
2146
|
+
ctx.loaded = c;
|
|
2147
|
+
ctx.client = probe;
|
|
2148
|
+
chatLog(`credentials: \u91C7\u7528 ${c.label}\uFF08\u4E09\u4EF6\u5957\uFF09`);
|
|
2149
|
+
break;
|
|
2150
|
+
}
|
|
2151
|
+
const sts = new StsProvider({ ak: c.key.ak, sk: c.key.sk });
|
|
2152
|
+
const creds = await sts.credentials();
|
|
2153
|
+
ctx.loaded = c;
|
|
2154
|
+
ctx.sts = sts;
|
|
2155
|
+
ctx.client = new MadaoClient({ credentials: creds, gateway: opts.gateway });
|
|
2156
|
+
ctx.lastCreds = creds;
|
|
2157
|
+
chatLog(`credentials: \u91C7\u7528 ${c.label}\uFF08\u5DF2\u6362 STS\uFF09`);
|
|
2158
|
+
break;
|
|
2159
|
+
} catch (e) {
|
|
2160
|
+
const msg = String(e?.message ?? e).slice(0, 200);
|
|
2161
|
+
failures.push(`${c.label} \u2192 ${msg}`);
|
|
2162
|
+
chatLog(`credentials: \u8DF3\u8FC7 ${c.label}\uFF08${msg}\uFF09`);
|
|
2163
|
+
}
|
|
2164
|
+
}
|
|
2165
|
+
if (!ctx.client) {
|
|
2166
|
+
throw new Error(`\u6240\u6709\u51ED\u8BC1\u6765\u6E90\u90FD\u4E0D\u53EF\u7528\uFF1A
|
|
2167
|
+
${failures.map((f) => ` ${f}`).join("\n")}`);
|
|
2168
|
+
}
|
|
2169
|
+
} catch (err) {
|
|
2170
|
+
ctx.loadError = err instanceof Error ? err.message : String(err);
|
|
2171
|
+
}
|
|
2172
|
+
const server = createServer((req, res) => {
|
|
2173
|
+
handle(req, res, ctx).catch((err) => {
|
|
2174
|
+
if (!res.headersSent) {
|
|
2175
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
2176
|
+
res.end(JSON.stringify({ error: { message: String(err?.message ?? err), type: "internal_error" } }));
|
|
2177
|
+
return;
|
|
2178
|
+
}
|
|
2179
|
+
try {
|
|
2180
|
+
res.end();
|
|
2181
|
+
} catch {
|
|
2182
|
+
}
|
|
2183
|
+
});
|
|
2184
|
+
});
|
|
2185
|
+
await new Promise((resolve, reject) => {
|
|
2186
|
+
server.once("error", reject);
|
|
2187
|
+
server.listen(port, host, () => resolve());
|
|
2188
|
+
});
|
|
2189
|
+
const addr = server.address();
|
|
2190
|
+
const actualPort = typeof addr === "object" && addr ? addr.port : port;
|
|
2191
|
+
return {
|
|
2192
|
+
server,
|
|
2193
|
+
port: actualPort,
|
|
2194
|
+
url: `http://${host}:${actualPort}`,
|
|
2195
|
+
close: () => new Promise((resolve, reject) => server.close((e) => e ? reject(e) : resolve())),
|
|
2196
|
+
ctx
|
|
2197
|
+
};
|
|
2198
|
+
}
|
|
2199
|
+
async function handle(req, res, ctx) {
|
|
2200
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "127.0.0.1"}`);
|
|
2201
|
+
res.setHeader("Access-Control-Allow-Origin", req.headers.origin ?? "*");
|
|
2202
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
2203
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
|
2204
|
+
res.setHeader("Access-Control-Max-Age", "600");
|
|
2205
|
+
if (req.method === "OPTIONS") {
|
|
2206
|
+
res.writeHead(204);
|
|
2207
|
+
res.end();
|
|
2208
|
+
return;
|
|
2209
|
+
}
|
|
2210
|
+
if (req.method === "GET" && url.pathname === "/healthz") {
|
|
2211
|
+
return json(res, 200, await healthz(ctx));
|
|
2212
|
+
}
|
|
2213
|
+
if (url.pathname === "/settings" && (req.method === "GET" || req.method === "POST")) {
|
|
2214
|
+
if (req.method === "GET") {
|
|
2215
|
+
const settings = await readSettings();
|
|
2216
|
+
return json(res, 200, {
|
|
2217
|
+
ok: true,
|
|
2218
|
+
settings,
|
|
2219
|
+
autoCheckin: ctx.autoCheckin ? ctx.autoCheckin.state() : null
|
|
2220
|
+
});
|
|
2221
|
+
}
|
|
2222
|
+
let payload = {};
|
|
2223
|
+
try {
|
|
2224
|
+
payload = JSON.parse(await readBody(req));
|
|
2225
|
+
} catch {
|
|
2226
|
+
return json(res, 400, { error: { message: "\u8BF7\u6C42\u4F53\u4E0D\u662F\u5408\u6CD5 JSON" } });
|
|
2227
|
+
}
|
|
2228
|
+
const patch = {};
|
|
2229
|
+
if (typeof payload.composerChip === "boolean") patch.composerChip = payload.composerChip;
|
|
2230
|
+
if (typeof payload.autoCheckin === "boolean") patch.autoCheckin = payload.autoCheckin;
|
|
2231
|
+
if (Array.isArray(payload.hiddenModels)) {
|
|
2232
|
+
patch.hiddenModels = payload.hiddenModels.filter(
|
|
2233
|
+
(value) => typeof value === "string" && value.length > 0
|
|
2234
|
+
);
|
|
2235
|
+
}
|
|
2236
|
+
if (typeof payload.contextCaps === "object" && payload.contextCaps !== null && !Array.isArray(payload.contextCaps)) {
|
|
2237
|
+
patch.contextCaps = payload.contextCaps;
|
|
2238
|
+
}
|
|
2239
|
+
if (Object.keys(patch).length === 0) {
|
|
2240
|
+
return json(res, 400, { error: { message: "\u6CA1\u6709\u53EF\u66F4\u65B0\u7684\u5B57\u6BB5" } });
|
|
2241
|
+
}
|
|
2242
|
+
const wantsModelChange = patch.hiddenModels !== void 0 || patch.contextCaps !== void 0;
|
|
2243
|
+
if (wantsModelChange) {
|
|
2244
|
+
const candidate = normalizeSettings({ ...await readSettings(), ...patch });
|
|
2245
|
+
if (selectModels(ctx.models, candidate).length === 0) {
|
|
2246
|
+
return json(res, 400, { error: { message: "\u81F3\u5C11\u8981\u4FDD\u7559\u4E00\u4E2A\u6A21\u578B\uFF0C\u5426\u5219\u6A21\u578B\u9009\u62E9\u5668\u4F1A\u6574\u4E2A\u7A7A\u6389\u3002" } });
|
|
2247
|
+
}
|
|
2248
|
+
}
|
|
2249
|
+
try {
|
|
2250
|
+
const settings = await patchSettings(patch);
|
|
2251
|
+
if (ctx.autoCheckin && patch.autoCheckin !== void 0) {
|
|
2252
|
+
try {
|
|
2253
|
+
await ctx.autoCheckin.tick();
|
|
2254
|
+
} catch {
|
|
2255
|
+
}
|
|
2256
|
+
}
|
|
2257
|
+
let outcome = null;
|
|
2258
|
+
if (wantsModelChange) {
|
|
2259
|
+
const selected = selectModels(ctx.models, settings);
|
|
2260
|
+
if (ctx.native) {
|
|
2261
|
+
try {
|
|
2262
|
+
ctx.native.update(selected);
|
|
2263
|
+
outcome = { mode: "live" };
|
|
2264
|
+
} catch (e) {
|
|
2265
|
+
outcome = { mode: "failed", error: String(e?.message ?? e) };
|
|
2266
|
+
}
|
|
2267
|
+
} else {
|
|
2268
|
+
outcome = await applyModelSelection(ctx.dsh, ctx.models, settings, ctx.port);
|
|
2269
|
+
}
|
|
2270
|
+
}
|
|
2271
|
+
return json(res, 200, {
|
|
2272
|
+
ok: true,
|
|
2273
|
+
settings,
|
|
2274
|
+
autoCheckin: ctx.autoCheckin ? ctx.autoCheckin.state() : null,
|
|
2275
|
+
modelApply: outcome?.mode ?? null,
|
|
2276
|
+
modelApplyError: outcome?.error
|
|
2277
|
+
});
|
|
2278
|
+
} catch (e) {
|
|
2279
|
+
return json(res, 500, { error: { message: `\u4FDD\u5B58\u8BBE\u7F6E\u5931\u8D25\uFF1A${String(e?.message ?? e)}` } });
|
|
2280
|
+
}
|
|
2281
|
+
}
|
|
2282
|
+
if (req.method === "GET" && (url.pathname === "/diag/account" || url.pathname === "/diag/credit")) {
|
|
2283
|
+
return json(res, 200, await accountInfo(ctx));
|
|
2284
|
+
}
|
|
2285
|
+
if (req.method === "GET" && url.pathname === "/diag/native") {
|
|
2286
|
+
const native = ctx.native;
|
|
2287
|
+
if (!native) return json(res, 200, { ok: false, reason: "native provider not registered" });
|
|
2288
|
+
try {
|
|
2289
|
+
const models = await native.listModels();
|
|
2290
|
+
const llm = ctx.dsh?.get?.("llm");
|
|
2291
|
+
return json(res, 200, {
|
|
2292
|
+
ok: true,
|
|
2293
|
+
provider: native.providerId,
|
|
2294
|
+
count: models.length,
|
|
2295
|
+
models,
|
|
2296
|
+
providers: llm?.listProviders?.(),
|
|
2297
|
+
directory: llm?.listConfigurableProviders?.(),
|
|
2298
|
+
namespaces: (() => {
|
|
2299
|
+
try {
|
|
2300
|
+
const rows = ctx.describe?.();
|
|
2301
|
+
return Array.isArray(rows) ? rows.map((row) => row?.ns) : rows;
|
|
2302
|
+
} catch (e) {
|
|
2303
|
+
return String(e?.message ?? e);
|
|
2304
|
+
}
|
|
2305
|
+
})()
|
|
2306
|
+
});
|
|
2307
|
+
} catch (e) {
|
|
2308
|
+
return json(res, 200, { ok: false, reason: String(e?.message ?? e) });
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
if ((req.method === "POST" || req.method === "GET") && url.pathname === "/diag/test") {
|
|
2312
|
+
return json(res, 200, await runSelfTest(ctx));
|
|
2313
|
+
}
|
|
2314
|
+
if (url.pathname === "/diag/checkin" && (req.method === "GET" || req.method === "POST")) {
|
|
2315
|
+
await ensureFreshClient(ctx);
|
|
2316
|
+
if (!ctx.client) {
|
|
2317
|
+
return json(res, 503, { error: { message: ctx.loadError ?? "\u51ED\u8BC1\u672A\u52A0\u8F7D", type: "credentials_error" } });
|
|
2318
|
+
}
|
|
2319
|
+
try {
|
|
2320
|
+
const state = req.method === "GET" ? await queryCheckin(ctx.client) : await claimCheckin(ctx.client);
|
|
2321
|
+
return json(res, 200, state);
|
|
2322
|
+
} catch (e) {
|
|
2323
|
+
chatLog(`checkin ERROR ${String(e?.message ?? e).slice(0, 200)}`);
|
|
2324
|
+
return json(res, 502, {
|
|
2325
|
+
error: { message: `\u7B7E\u5230\u63A5\u53E3\u8C03\u7528\u5931\u8D25\uFF1A${String(e?.message ?? e)}`, type: "checkin_error" }
|
|
2326
|
+
});
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
if (req.method === "POST" && url.pathname === "/diag/checkin/all") {
|
|
2330
|
+
await ensureFreshClient(ctx);
|
|
2331
|
+
if (!ctx.client) {
|
|
2332
|
+
return json(res, 503, { error: { message: ctx.loadError ?? "\u51ED\u8BC1\u672A\u52A0\u8F7D", type: "credentials_error" } });
|
|
2333
|
+
}
|
|
2334
|
+
try {
|
|
2335
|
+
return json(res, 200, await claimAllCheckins(ctx.client));
|
|
2336
|
+
} catch (e) {
|
|
2337
|
+
chatLog(`checkin/all ERROR ${String(e?.message ?? e).slice(0, 200)}`);
|
|
2338
|
+
return json(res, 502, {
|
|
2339
|
+
error: { message: `\u6279\u91CF\u7B7E\u5230\u5931\u8D25\uFF1A${String(e?.message ?? e)}`, type: "checkin_error" }
|
|
2340
|
+
});
|
|
2341
|
+
}
|
|
2342
|
+
}
|
|
2343
|
+
if (req.method === "POST" && url.pathname === "/diag/credentials") {
|
|
2344
|
+
let payload = {};
|
|
2345
|
+
try {
|
|
2346
|
+
payload = JSON.parse(await readBody(req));
|
|
2347
|
+
} catch {
|
|
2348
|
+
return json(res, 400, { error: { message: "\u8BF7\u6C42\u4F53\u4E0D\u662F\u5408\u6CD5 JSON" } });
|
|
2349
|
+
}
|
|
2350
|
+
const ak = String(payload.ak ?? "").trim();
|
|
2351
|
+
const sk = String(payload.sk ?? "").trim();
|
|
2352
|
+
if (!ak || !sk) {
|
|
2353
|
+
return json(res, 400, { error: { message: "Access Key ID \u4E0E Secret Access Key \u90FD\u4E0D\u80FD\u4E3A\u7A7A" } });
|
|
2354
|
+
}
|
|
2355
|
+
let saved;
|
|
2356
|
+
try {
|
|
2357
|
+
saved = await saveCredentials({ ak, sk });
|
|
2358
|
+
chatLog(
|
|
2359
|
+
`credentials saved via panel \u2192 ${saved.path} (${saved.encrypted ? "DPAPI \u52A0\u5BC6" : "\u26A0 \u660E\u6587\uFF0CDPAPI \u4E0D\u53EF\u7528"}, ak=${ak.slice(0, 4)}\u2026)`
|
|
2360
|
+
);
|
|
2361
|
+
} catch (e) {
|
|
2362
|
+
return json(res, 500, {
|
|
2363
|
+
error: {
|
|
2364
|
+
message: `\u4FDD\u5B58\u51ED\u8BC1\u5931\u8D25\uFF1A${String(e?.message ?? e)}
|
|
2365
|
+
\u53EF\u6539\u7528\u73AF\u5883\u53D8\u91CF MADAO_AK / MADAO_SK\u3002`
|
|
2366
|
+
}
|
|
2367
|
+
});
|
|
2368
|
+
}
|
|
2369
|
+
try {
|
|
2370
|
+
const reloaded = await loadCredentials();
|
|
2371
|
+
ctx.loaded = reloaded;
|
|
2372
|
+
ctx.loadError = null;
|
|
2373
|
+
if (reloaded.key.securityToken) {
|
|
2374
|
+
ctx.client = new MadaoClient({
|
|
2375
|
+
credentials: {
|
|
2376
|
+
ak: reloaded.key.ak,
|
|
2377
|
+
sk: reloaded.key.sk,
|
|
2378
|
+
securityToken: reloaded.key.securityToken
|
|
2379
|
+
}
|
|
2380
|
+
});
|
|
2381
|
+
ctx.sts = null;
|
|
2382
|
+
} else {
|
|
2383
|
+
const sts = new StsProvider({ ak: reloaded.key.ak, sk: reloaded.key.sk });
|
|
2384
|
+
const creds = await sts.credentials();
|
|
2385
|
+
ctx.sts = sts;
|
|
2386
|
+
ctx.client = new MadaoClient({ credentials: creds });
|
|
2387
|
+
ctx.lastCreds = creds;
|
|
2388
|
+
}
|
|
2389
|
+
chatLog(`credentials reloaded after save (source=${reloaded.source})`);
|
|
2390
|
+
} catch (e) {
|
|
2391
|
+
return json(res, 200, {
|
|
2392
|
+
ok: true,
|
|
2393
|
+
warning: `\u5DF2\u5199\u5165\uFF0C\u4F46\u7ACB\u5373\u52A0\u8F7D\u5931\u8D25\uFF08\u91CD\u542F DSH \u540E\u751F\u6548\uFF09\uFF1A${String(e?.message ?? e)}`
|
|
2394
|
+
});
|
|
2395
|
+
}
|
|
2396
|
+
return json(res, 200, { ok: true, source: ctx.loaded?.source });
|
|
2397
|
+
}
|
|
2398
|
+
if (req.method === "GET" && url.pathname === "/v1/models") {
|
|
2399
|
+
return json(res, 200, {
|
|
2400
|
+
object: "list",
|
|
2401
|
+
data: ctx.models.map((m) => ({
|
|
2402
|
+
id: m.id,
|
|
2403
|
+
object: "model",
|
|
2404
|
+
owned_by: "huawei-codearts",
|
|
2405
|
+
name: m.name,
|
|
2406
|
+
// 下划线是 OpenAI 生态的惯例,驼峰给前端面板用。
|
|
2407
|
+
// 之前只给了下划线,而面板读 m.context / m.maxOutput / m.supportsImages,
|
|
2408
|
+
// 结果三列全是 undefined —— `m.context.toLocaleString()` 直接抛错,
|
|
2409
|
+
// 模型 tab 一打开就崩。
|
|
2410
|
+
context_window: m.context,
|
|
2411
|
+
max_output_tokens: m.maxOutput,
|
|
2412
|
+
supports_images: m.supportsImages,
|
|
2413
|
+
default_strength: m.defaultStrength,
|
|
2414
|
+
context: m.context,
|
|
2415
|
+
maxOutput: m.maxOutput,
|
|
2416
|
+
supportsImages: m.supportsImages,
|
|
2417
|
+
defaultStrength: m.defaultStrength,
|
|
2418
|
+
ratio: m.ratio,
|
|
2419
|
+
strengths: m.strengths,
|
|
2420
|
+
description: m.description
|
|
2421
|
+
}))
|
|
2422
|
+
});
|
|
2423
|
+
}
|
|
2424
|
+
if (req.method === "POST" && url.pathname === "/v1/chat/completions") {
|
|
2425
|
+
await ensureFreshClient(ctx);
|
|
2426
|
+
if (!ctx.client) {
|
|
2427
|
+
return json(res, 503, { error: { message: ctx.loadError ?? "\u51ED\u8BC1\u672A\u52A0\u8F7D", type: "credentials_error" } });
|
|
2428
|
+
}
|
|
2429
|
+
if (ctx.loaded?.source === "codearts") {
|
|
2430
|
+
const exp = typeof ctx.loaded.key.expiresAt === "number" ? ctx.loaded.key.expiresAt : ctx.loaded.expiresAtMs;
|
|
2431
|
+
if (typeof exp === "number" && Date.now() > exp) {
|
|
2432
|
+
const mins = Math.max(1, Math.round((Date.now() - exp) / 6e4));
|
|
2433
|
+
chatLog(`chat REJECT codearts credential expired ${mins}min ago`);
|
|
2434
|
+
return json(res, 401, {
|
|
2435
|
+
error: {
|
|
2436
|
+
message: `\u7801\u9053\u767B\u5F55\u6001\u7684\u4E34\u65F6\u51ED\u8BC1\u5DF2\u7ECF\u8FC7\u671F\uFF08\u8FC7\u671F\u7EA6 ${mins} \u5206\u949F\uFF09\u3002
|
|
2437
|
+
\u8FD9\u4E0D\u662F\u6A21\u578B\u6545\u969C\uFF1A\u4E34\u65F6\u51ED\u8BC1\u53EA\u6709\u51E0\u5C0F\u65F6\u5BFF\u547D\uFF0C\u63D2\u4EF6\u65E0\u6CD5\u66FF\u4F60\u7EED\u671F\u3002
|
|
2438
|
+
\u6062\u590D\u529E\u6CD5\uFF1A\u6253\u5F00\u4E00\u6B21\u7801\u9053\u5BA2\u6237\u7AEF\u8BA9\u5B83\u5237\u65B0\u767B\u5F55\u6001 \u2192 \u56DE\u5230\u8FD9\u91CC\u70B9\u300C\u6D4B\u8BD5\u8FDE\u63A5\u300D\u3002
|
|
2439
|
+
\u60F3\u4E00\u52B3\u6C38\u9038\uFF0C\u5C31\u5728\u8D26\u53F7\u9875\u586B\u6C38\u4E45 AK/SK\uFF08\u63D2\u4EF6\u4F1A\u81EA\u52A8\u6362 STS \u5E76\u7EED\u671F\uFF09\u3002`,
|
|
2440
|
+
type: "credentials_expired"
|
|
2441
|
+
}
|
|
2442
|
+
});
|
|
2443
|
+
}
|
|
2444
|
+
}
|
|
2445
|
+
const raw = await readBody(req);
|
|
2446
|
+
let body;
|
|
2447
|
+
try {
|
|
2448
|
+
body = JSON.parse(raw);
|
|
2449
|
+
} catch {
|
|
2450
|
+
return json(res, 400, { error: { message: "\u8BF7\u6C42\u4F53\u4E0D\u662F\u5408\u6CD5 JSON", type: "invalid_request_error" } });
|
|
2451
|
+
}
|
|
2452
|
+
return chatCompletion(res, ctx.client, body, ctx.models);
|
|
2453
|
+
}
|
|
2454
|
+
json(res, 404, { error: { message: `\u672A\u77E5\u8DEF\u5F84 ${url.pathname}`, type: "not_found" } });
|
|
2455
|
+
}
|
|
2456
|
+
var IMAGE_TOKEN_ESTIMATE = 1500;
|
|
2457
|
+
function estimateTokens(value) {
|
|
2458
|
+
let cjk = 0;
|
|
2459
|
+
let other = 0;
|
|
2460
|
+
let images = 0;
|
|
2461
|
+
const text = JSON.stringify(value ?? "", (_k, v) => {
|
|
2462
|
+
if (typeof v === "string" && v.startsWith("data:image/")) {
|
|
2463
|
+
images++;
|
|
2464
|
+
return "__IMG__";
|
|
2465
|
+
}
|
|
2466
|
+
return v;
|
|
2467
|
+
});
|
|
2468
|
+
for (const ch of text) {
|
|
2469
|
+
const c = ch.codePointAt(0) ?? 0;
|
|
2470
|
+
if (c >= 19968 && c <= 40959 || c >= 13312 && c <= 19903 || c >= 63744 && c <= 64255 || c >= 12288 && c <= 12351 || c >= 65280 && c <= 65519) {
|
|
2471
|
+
cjk++;
|
|
2472
|
+
} else {
|
|
2473
|
+
other++;
|
|
2474
|
+
}
|
|
2475
|
+
}
|
|
2476
|
+
return Math.ceil(cjk / 2.5 + other / 5) + images * IMAGE_TOKEN_ESTIMATE;
|
|
2477
|
+
}
|
|
2478
|
+
function resolveModelId(input, models) {
|
|
2479
|
+
const raw = String(input ?? "").trim();
|
|
2480
|
+
if (!raw) return null;
|
|
2481
|
+
const low = raw.toLowerCase();
|
|
2482
|
+
const byId = models.find((m) => m.id.toLowerCase() === low);
|
|
2483
|
+
if (byId) return byId.id;
|
|
2484
|
+
const shown = (m) => m.ratio ? `${m.name} \xB7 ${m.ratio}` : m.name;
|
|
2485
|
+
const byShown = models.find((m) => shown(m) === raw || m.name === raw);
|
|
2486
|
+
if (byShown) return byShown.id;
|
|
2487
|
+
const byShownCi = models.find((m) => shown(m).toLowerCase() === low || m.name.toLowerCase() === low);
|
|
2488
|
+
if (byShownCi) return byShownCi.id;
|
|
2489
|
+
const stripped = raw.split("\xB7")[0].trim();
|
|
2490
|
+
if (stripped && stripped !== raw) {
|
|
2491
|
+
const s = stripped.toLowerCase();
|
|
2492
|
+
const byStrip = models.find((m) => m.id.toLowerCase() === s || m.name.toLowerCase() === s);
|
|
2493
|
+
if (byStrip) return byStrip.id;
|
|
2494
|
+
}
|
|
2495
|
+
return null;
|
|
2496
|
+
}
|
|
2497
|
+
function normalizeRequest(body, models) {
|
|
2498
|
+
const out = { ...body };
|
|
2499
|
+
const resolved = resolveModelId(String(body.model ?? ""), models);
|
|
2500
|
+
out.model = resolved ?? "";
|
|
2501
|
+
const effort = body.strength ?? body.reasoning_effort;
|
|
2502
|
+
if (typeof effort === "string" && effort) out.strength = effort;
|
|
2503
|
+
return out;
|
|
2504
|
+
}
|
|
2505
|
+
async function chatCompletion(res, client, rawBody, ctxModels) {
|
|
2506
|
+
const unsupported = hasUnsupportedContent(rawBody.messages);
|
|
2507
|
+
if (unsupported) {
|
|
2508
|
+
return json(res, 400, {
|
|
2509
|
+
error: {
|
|
2510
|
+
message: `\u4E0D\u652F\u6301\u7684\u5185\u5BB9\u7C7B\u578B\uFF1A${unsupported}\u3002\u6865\u63A5\u76EE\u524D\u8F6C\u53D1 text \u4E0E image_url\uFF08\u56FE\u7247\uFF09\uFF0C\u5176\u4ED6\u7C7B\u578B\uFF08\u97F3\u9891\u3001file \u7B49\uFF09\u7F51\u5173\u4E0D\u8BA4\u3002`,
|
|
2511
|
+
type: "unsupported_content"
|
|
2512
|
+
}
|
|
2513
|
+
});
|
|
2514
|
+
}
|
|
2515
|
+
const body = normalizeRequest(rawBody, ctxModels);
|
|
2516
|
+
const wantStream = body.stream !== false;
|
|
2517
|
+
const upstreamBody = buildUpstreamBody(body);
|
|
2518
|
+
const id = `chatcmpl-${Date.now().toString(36)}`;
|
|
2519
|
+
const model = body.model;
|
|
2520
|
+
if (!model) {
|
|
2521
|
+
const requestId = String(rawBody.model ?? "");
|
|
2522
|
+
chatLog(`chat REJECT unknown model ${JSON.stringify(requestId)}`);
|
|
2523
|
+
return json(res, 400, {
|
|
2524
|
+
error: {
|
|
2525
|
+
message: `\u672A\u77E5\u6A21\u578B\uFF1A${JSON.stringify(requestId)}
|
|
2526
|
+
\u53EF\u7528\u6A21\u578B\uFF08model_id \u6216\u754C\u9762\u4E0A\u7684\u663E\u793A\u540D\u90FD\u53EF\uFF09\uFF1A
|
|
2527
|
+
` + ctxModels.map((m) => ` ${m.id}${m.ratio ? `\uFF08\u663E\u793A\u540D ${m.name} \xB7 ${m.ratio}\uFF09` : ""}`).join("\n"),
|
|
2528
|
+
type: "model_not_found"
|
|
2529
|
+
}
|
|
2530
|
+
});
|
|
2531
|
+
}
|
|
2532
|
+
const info = ctxModels.find((m) => m.id === model);
|
|
2533
|
+
const estMessages = estimateTokens(rawBody.messages);
|
|
2534
|
+
const toolCount = Array.isArray(rawBody.tools) ? rawBody.tools.length : 0;
|
|
2535
|
+
const estTools = toolCount > 0 ? estimateTokens(rawBody.tools) : 0;
|
|
2536
|
+
const estTokens = estMessages + estTools;
|
|
2537
|
+
const BODY_LIMIT_BYTES = 9.5 * 1024 * 1024;
|
|
2538
|
+
let bodyBytes = 0;
|
|
2539
|
+
try {
|
|
2540
|
+
bodyBytes = Buffer.byteLength(JSON.stringify(upstreamBody), "utf8");
|
|
2541
|
+
} catch {
|
|
2542
|
+
bodyBytes = 0;
|
|
2543
|
+
}
|
|
2544
|
+
if (bodyBytes > BODY_LIMIT_BYTES) {
|
|
2545
|
+
const mb = (bodyBytes / 1024 / 1024).toFixed(2);
|
|
2546
|
+
const toolCountForMsg = Array.isArray(rawBody.tools) ? rawBody.tools.length : 0;
|
|
2547
|
+
const msgCount = Array.isArray(rawBody.messages) ? rawBody.messages.length : 0;
|
|
2548
|
+
chatLog(`chat REJECT body ${mb}MB (msgs ${msgCount} + tools ${toolCountForMsg}) > 9.5MB for ${model}`);
|
|
2549
|
+
const smaller = ctxModels.filter((m) => m.context <= 262144).slice(0, 4).map((m) => `${m.name}\uFF08${m.context}\uFF09`);
|
|
2550
|
+
return json(res, 413, {
|
|
2551
|
+
error: {
|
|
2552
|
+
message: `\u5F53\u524D\u4F1A\u8BDD\u7684\u8BF7\u6C42\u4F53 ${mb} MB\uFF0C\u8D85\u8FC7\u7801\u9053\u7F51\u5173\u7EA6 10 MB \u7684\u5355\u6B21\u4E0A\u9650\u3002
|
|
2553
|
+
\u8FD9\u4E0D\u662F\u914D\u7F6E\u95EE\u9898\uFF0C\u7F51\u5173\u4F1A\u8FD4\u56DE\u300C\u53C2\u6570\u65E0\u6548\u300D\u800C\u4E0D\u8BF4\u662F\u4F53\u79EF\u8D85\u4E86\u3002
|
|
2554
|
+
|
|
2555
|
+
\u600E\u4E48\u89E3\u51B3\uFF08\u4EFB\u9009\u5176\u4E00\uFF09\uFF1A
|
|
2556
|
+
1. \u5F00\u65B0\u4F1A\u8BDD\uFF0C\u628A\u9700\u8981\u5EF6\u7EED\u7684\u7ED3\u8BBA\u590D\u5236\u8FC7\u53BB \u2014\u2014 \u6700\u76F4\u63A5
|
|
2557
|
+
2. \u6362\u6210\u7A97\u53E3\u66F4\u5C0F\u7684\u6A21\u578B\uFF0C\u8BA9 DSH \u66F4\u65E9\u538B\u7F29\u5386\u53F2` + (smaller.length ? `\uFF1A${smaller.join("\u3001")}` : "") + `
|
|
2558
|
+
3. \u68C0\u67E5\u4F1A\u8BDD\u91CC\u6709\u6CA1\u6709\u5927\u56FE\u7247\uFF0C\u5B83\u4EEC\u7684 base64 \u5360\u4F53\u79EF\u6700\u591A
|
|
2559
|
+
|
|
2560
|
+
\u5F53\u524D\uFF1A${msgCount} \u6761\u6D88\u606F + ${toolCountForMsg} \u4E2A\u5DE5\u5177\u5B9A\u4E49`,
|
|
2561
|
+
type: "request_too_large"
|
|
2562
|
+
}
|
|
2563
|
+
});
|
|
2564
|
+
}
|
|
2565
|
+
if (info && info.context > 0) {
|
|
2566
|
+
const RESERVED_FOR_OUTPUT = 4096;
|
|
2567
|
+
const realInputLimit = Math.max(1, info.context - RESERVED_FOR_OUTPUT);
|
|
2568
|
+
const limit = Math.floor(realInputLimit * 1.2);
|
|
2569
|
+
if (estTokens > limit) {
|
|
2570
|
+
const bigger = ctxModels.filter((m) => m.context - RESERVED_FOR_OUTPUT > estTokens).sort((a, b) => a.context - b.context).slice(0, 4).map((m) => `${m.name}\uFF08${m.context - RESERVED_FOR_OUTPUT}\uFF09`);
|
|
2571
|
+
chatLog(
|
|
2572
|
+
`chat REJECT context ${estTokens} (msgs ${estMessages} + tools ${estTools}/${toolCount}) > ${limit} for ${model}`
|
|
2573
|
+
);
|
|
2574
|
+
try {
|
|
2575
|
+
writeFileSync(join5(logDir(), "last-rejected.json"), JSON.stringify(rawBody), "utf8");
|
|
2576
|
+
chatLog("chat REJECT \u8BF7\u6C42\u4F53\u5DF2\u5B58\u81F3 ~/.dsh-connect-madao/last-rejected.json");
|
|
2577
|
+
} catch {
|
|
2578
|
+
}
|
|
2579
|
+
const toolsAloneExceed = estTools > limit;
|
|
2580
|
+
return json(res, 400, {
|
|
2581
|
+
error: {
|
|
2582
|
+
message: `\u4E0A\u4E0B\u6587\u8D85\u51FA\u300C${info.name}\u300D\u7684\u7A97\u53E3 ${info.context}\uFF08\u53EF\u7528\u7EA6 ${limit}\uFF09\uFF1A
|
|
2583
|
+
\u5DE5\u5177\u5B9A\u4E49 ${estTools}\uFF08${toolCount} \u4E2A\uFF09
|
|
2584
|
+
\u5BF9\u8BDD\u4E0E\u7CFB\u7EDF\u63D0\u793A ${estMessages}
|
|
2585
|
+
\u5408\u8BA1 ${estTokens} tokens
|
|
2586
|
+
` + (toolsAloneExceed ? `
|
|
2587
|
+
\u6CE8\u610F\uFF1A\u5149\u5DE5\u5177\u5B9A\u4E49\u5C31\u8D85\u8FC7\u4E86\u8BE5\u6A21\u578B\u6574\u4E2A\u7A97\u53E3\uFF0C\u6240\u4EE5\u54EA\u6015\u65B0\u5F00\u4F1A\u8BDD\u3001\u53EA\u53D1\u4E00\u4E2A\u5B57\u4E5F\u88C5\u4E0D\u4E0B\u3002
|
|
2588
|
+
\u8FD9\u4E0D\u662F\u5BF9\u8BDD\u5386\u53F2\u592A\u957F\uFF0C\u538B\u7F29\u4F1A\u8BDD\u6CA1\u6709\u7528 \u2014\u2014 \u9700\u8981\u6362\u7A97\u53E3\u66F4\u5927\u7684\u6A21\u578B\uFF0C\u6216\u8005\u7981\u7528\u4E00\u4E9B\u63D2\u4EF6/MCP \u670D\u52A1\u5668\u6765\u51CF\u5C11\u5DE5\u5177\u6570\u91CF\u3002
|
|
2589
|
+
` : `
|
|
2590
|
+
\u53EF\u4EE5\u538B\u7F29\u4F1A\u8BDD\u3001\u5F00\u65B0\u5BF9\u8BDD\uFF0C\u6216\u6362\u7A97\u53E3\u66F4\u5927\u7684\u6A21\u578B\u3002
|
|
2591
|
+
`) + (bigger.length ? `\u7A97\u53E3\u591F\u7528\u7684\u6A21\u578B\uFF1A${bigger.join("\u3001")}` : `\u8BF7\u51CF\u5C11\u5DE5\u5177\u6570\u91CF\u6216\u6362\u66F4\u5927\u7684\u6A21\u578B\u3002`),
|
|
2592
|
+
type: "context_length_exceeded"
|
|
2593
|
+
}
|
|
2594
|
+
});
|
|
2595
|
+
}
|
|
2596
|
+
}
|
|
2597
|
+
const rb = rawBody;
|
|
2598
|
+
const msgBrief = (rb.messages ?? []).map((m) => `${m.role}:${typeof m.content === "string" ? m.content.length : Array.isArray(m.content) ? "arr" + m.content.length : typeof m.content}`).join(",");
|
|
2599
|
+
const prefixMsg = (rb.messages ?? []).find((m) => m.role === "system" || m.role === "developer");
|
|
2600
|
+
const sysHash = prefixMsg ? createHash5("sha256").update(typeof prefixMsg.content === "string" ? prefixMsg.content : JSON.stringify(prefixMsg.content)).digest("hex").slice(0, 8) : "none";
|
|
2601
|
+
chatLog(
|
|
2602
|
+
`chat in=${JSON.stringify(String(rawBody.model ?? ""))} \u2192 out=${JSON.stringify(model)} strength=${JSON.stringify(body.strength ?? null)} max_tokens=${rb.max_tokens ?? "\u672A\u4F20"} max_completion_tokens=${rb.max_completion_tokens ?? "\u672A\u4F20"} \u2192 \u5B9E\u9645\u53D1\u7ED9\u7F51\u5173=${upstreamBody.max_tokens} stream=${wantStream} est_tokens=${estTokens} msgs=[${msgBrief}] tools=${Array.isArray(rb.tools) ? rb.tools.length : 0} sysHash=${sysHash} \u9876\u5C42\u5B57\u6BB5=${Object.keys(rb).join("|")}`
|
|
2603
|
+
);
|
|
2604
|
+
void client.heartbeat("busy");
|
|
2605
|
+
const markIdle = () => {
|
|
2606
|
+
void client.heartbeat("idle");
|
|
2607
|
+
};
|
|
2608
|
+
const up = await client.chatStream(upstreamBody);
|
|
2609
|
+
const reader = up.getReader();
|
|
2610
|
+
const decoder = new TextDecoder();
|
|
2611
|
+
async function* events() {
|
|
2612
|
+
let buf = "";
|
|
2613
|
+
for (; ; ) {
|
|
2614
|
+
const { done, value } = await reader.read();
|
|
2615
|
+
if (done) {
|
|
2616
|
+
if (buf.trim()) {
|
|
2617
|
+
for (const line of buf.split("\n")) {
|
|
2618
|
+
if (line.startsWith("data:")) yield parseUpstreamEvent(line.slice(5));
|
|
2619
|
+
}
|
|
2620
|
+
}
|
|
2621
|
+
return;
|
|
2622
|
+
}
|
|
2623
|
+
buf += decoder.decode(value, { stream: true });
|
|
2624
|
+
let sep;
|
|
2625
|
+
while ((sep = buf.indexOf("\n\n")) !== -1) {
|
|
2626
|
+
const block = buf.slice(0, sep);
|
|
2627
|
+
buf = buf.slice(sep + 2);
|
|
2628
|
+
for (const line of block.split("\n")) {
|
|
2629
|
+
if (line.startsWith("data:")) yield parseUpstreamEvent(line.slice(5));
|
|
2630
|
+
}
|
|
2631
|
+
}
|
|
2632
|
+
}
|
|
2633
|
+
}
|
|
2634
|
+
if (!wantStream) {
|
|
2635
|
+
let text = "";
|
|
2636
|
+
let reasoning = "";
|
|
2637
|
+
let finish2 = null;
|
|
2638
|
+
let usage2;
|
|
2639
|
+
const mergedCalls = [];
|
|
2640
|
+
for await (const ev of events()) {
|
|
2641
|
+
if (ev.reasoning) reasoning += ev.reasoning;
|
|
2642
|
+
if (ev.text) text += ev.text;
|
|
2643
|
+
if (ev.toolCalls) {
|
|
2644
|
+
for (const tc of ev.toolCalls) {
|
|
2645
|
+
const idx = typeof tc?.index === "number" ? tc.index : mergedCalls.length;
|
|
2646
|
+
const cur = mergedCalls[idx] ?? { id: "", type: "function", function: { name: "", arguments: "" } };
|
|
2647
|
+
if (tc.id) cur.id = tc.id;
|
|
2648
|
+
if (tc.type) cur.type = tc.type;
|
|
2649
|
+
if (tc.function?.name) cur.function.name += tc.function.name;
|
|
2650
|
+
if (tc.function?.arguments) cur.function.arguments += tc.function.arguments;
|
|
2651
|
+
mergedCalls[idx] = cur;
|
|
2652
|
+
}
|
|
2653
|
+
}
|
|
2654
|
+
if (ev.error) {
|
|
2655
|
+
chatLog(`chat UPSTREAM_ERROR model=${model} code=${ev.error.code} msg=${ev.error.message.slice(0, 200)}`);
|
|
2656
|
+
markIdle();
|
|
2657
|
+
return json(res, 400, {
|
|
2658
|
+
error: { message: `${ev.error.message}\uFF08${ev.error.code}\uFF09`, type: "upstream_error", code: ev.error.code }
|
|
2659
|
+
});
|
|
2660
|
+
}
|
|
2661
|
+
if (ev.finish) finish2 = ev.finish;
|
|
2662
|
+
if (ev.usage) usage2 = ev.usage;
|
|
2663
|
+
}
|
|
2664
|
+
chatLog(
|
|
2665
|
+
`chat done model=${model} content_len=${text.length} reasoning_len=${reasoning.length} tool_calls=${mergedCalls.length} cached=${usage2?.prompt_tokens_details?.cached_tokens ?? 0}/${usage2?.prompt_tokens ?? 0} finish=${finish2 ?? "stop"}` + (text.length === 0 && mergedCalls.length === 0 ? " \u26A0 content \u4E3A\u7A7A\u4E14\u65E0\u5DE5\u5177\u8C03\u7528" : "")
|
|
2666
|
+
);
|
|
2667
|
+
markIdle();
|
|
2668
|
+
return json(res, 200, {
|
|
2669
|
+
id,
|
|
2670
|
+
object: "chat.completion",
|
|
2671
|
+
created: Math.floor(Date.now() / 1e3),
|
|
2672
|
+
model,
|
|
2673
|
+
choices: [
|
|
2674
|
+
{
|
|
2675
|
+
index: 0,
|
|
2676
|
+
message: {
|
|
2677
|
+
role: "assistant",
|
|
2678
|
+
content: text,
|
|
2679
|
+
...reasoning ? { reasoning_content: reasoning } : {},
|
|
2680
|
+
...mergedCalls.length > 0 ? { tool_calls: mergedCalls.filter(Boolean) } : {}
|
|
2681
|
+
},
|
|
2682
|
+
finish_reason: finish2 ?? "stop"
|
|
2683
|
+
}
|
|
2684
|
+
],
|
|
2685
|
+
...usage2 ? { usage: usage2 } : {}
|
|
2686
|
+
});
|
|
2687
|
+
}
|
|
2688
|
+
res.writeHead(200, {
|
|
2689
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
2690
|
+
"Cache-Control": "no-cache, no-store, max-age=0, must-revalidate",
|
|
2691
|
+
Connection: "keep-alive",
|
|
2692
|
+
"X-Accel-Buffering": "no"
|
|
2693
|
+
});
|
|
2694
|
+
res.write(sseLine(makeChunk(id, model, { role: "assistant" })));
|
|
2695
|
+
let finish = null;
|
|
2696
|
+
let usage;
|
|
2697
|
+
let contentChars = 0;
|
|
2698
|
+
let reasoningChars = 0;
|
|
2699
|
+
let textEvents = 0;
|
|
2700
|
+
let reasoningEvents = 0;
|
|
2701
|
+
let toolCallEvents = 0;
|
|
2702
|
+
let upstreamErrorMessage = "";
|
|
2703
|
+
try {
|
|
2704
|
+
for await (const ev of events()) {
|
|
2705
|
+
if (ev.reasoning) {
|
|
2706
|
+
reasoningChars += ev.reasoning.length;
|
|
2707
|
+
reasoningEvents++;
|
|
2708
|
+
res.write(sseLine(makeChunk(id, model, { reasoning_content: ev.reasoning })));
|
|
2709
|
+
}
|
|
2710
|
+
if (ev.text) {
|
|
2711
|
+
contentChars += ev.text.length;
|
|
2712
|
+
textEvents++;
|
|
2713
|
+
res.write(sseLine(makeChunk(id, model, { content: ev.text })));
|
|
2714
|
+
}
|
|
2715
|
+
if (ev.toolCalls) {
|
|
2716
|
+
toolCallEvents++;
|
|
2717
|
+
res.write(sseLine(makeChunk(id, model, { tool_calls: ev.toolCalls })));
|
|
2718
|
+
}
|
|
2719
|
+
if (ev.error) {
|
|
2720
|
+
chatLog(`chat stream UPSTREAM_ERROR model=${model} code=${ev.error.code} msg=${ev.error.message.slice(0, 200)}`);
|
|
2721
|
+
res.write(
|
|
2722
|
+
sseLine({
|
|
2723
|
+
error: { message: `${ev.error.message}\uFF08${ev.error.code}\uFF09`, type: "upstream_error", code: ev.error.code }
|
|
2724
|
+
})
|
|
2725
|
+
);
|
|
2726
|
+
upstreamErrorMessage = ev.error.message;
|
|
2727
|
+
break;
|
|
2728
|
+
}
|
|
2729
|
+
if (ev.finish) finish = ev.finish;
|
|
2730
|
+
if (ev.usage) usage = ev.usage;
|
|
2731
|
+
}
|
|
2732
|
+
} catch (err) {
|
|
2733
|
+
res.write(sseLine({ error: { message: String(err?.message ?? err), type: "upstream_error" } }));
|
|
2734
|
+
chatLog(`chat stream ERROR model=${model} ${String(err?.message ?? err).slice(0, 160)}`);
|
|
2735
|
+
}
|
|
2736
|
+
if (usage) {
|
|
2737
|
+
res.write(sseLine({ id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1e3), model, choices: [], usage }));
|
|
2738
|
+
}
|
|
2739
|
+
res.write(sseLine(makeChunk(id, model, {}, finish ?? "stop")));
|
|
2740
|
+
res.write(SSE_DONE);
|
|
2741
|
+
res.end();
|
|
2742
|
+
chatLog(
|
|
2743
|
+
`chat done stream model=${model} finish=${finish ?? "stop"} content=${contentChars}(${textEvents}\u6BB5) reasoning=${reasoningChars}(${reasoningEvents}\u6BB5) tool_calls=${toolCallEvents}\u5E27 cached=${usage?.prompt_tokens_details?.cached_tokens ?? 0}/${usage?.prompt_tokens ?? 0}` + // 有工具调用时 content 为空是正常的(模型在调工具,不是产文本),不能报"空响应"
|
|
2744
|
+
(contentChars === 0 && toolCallEvents === 0 ? reasoningChars === 0 ? " \u26A0 \u5B8C\u5168\u7A7A\u54CD\u5E94" : " \u26A0 content \u4E3A\u7A7A" : "")
|
|
2745
|
+
);
|
|
2746
|
+
markIdle();
|
|
2747
|
+
}
|
|
2748
|
+
async function healthz(ctx) {
|
|
2749
|
+
if (!ctx.loaded || !ctx.client) {
|
|
2750
|
+
return { ok: false, stage: "credentials", error: ctx.loadError };
|
|
2751
|
+
}
|
|
2752
|
+
const masked = maskKey(ctx.loaded.key.ak, ctx.loaded.key.sk);
|
|
2753
|
+
try {
|
|
2754
|
+
const key = await ctx.client.ensureSessionKey();
|
|
2755
|
+
const stsExpiry = ctx.sts?.expiresAtMs() ?? null;
|
|
2756
|
+
return {
|
|
2757
|
+
ok: true,
|
|
2758
|
+
stage: "ready",
|
|
2759
|
+
credentials: { source: ctx.loaded.source, ...masked },
|
|
2760
|
+
sts: stsExpiry ? { expiresAt: new Date(stsExpiry).toISOString() } : "provided",
|
|
2761
|
+
sessionKey: { keyId: key.keyId, ttlSec: Math.round((key.expiresAt - Date.now()) / 1e3) },
|
|
2762
|
+
models: ctx.models.length
|
|
2763
|
+
};
|
|
2764
|
+
} catch (err) {
|
|
2765
|
+
return {
|
|
2766
|
+
ok: false,
|
|
2767
|
+
stage: "handshake",
|
|
2768
|
+
error: String(err?.message ?? err),
|
|
2769
|
+
credentials: { source: ctx.loaded.source, ...masked }
|
|
2770
|
+
};
|
|
2771
|
+
}
|
|
2772
|
+
}
|
|
2773
|
+
function pickMetric(list, name) {
|
|
2774
|
+
return list.find((m) => m?.name === name);
|
|
2775
|
+
}
|
|
2776
|
+
function pickExpiring(list) {
|
|
2777
|
+
for (const name of ["usageTotalPackageCredit", "usageBonusPackageCredit"]) {
|
|
2778
|
+
const m = pickMetric(list, name);
|
|
2779
|
+
if (m && m.package_credit_expiring_amount != null) {
|
|
2780
|
+
const n = Number(m.package_credit_expiring_amount);
|
|
2781
|
+
if (Number.isFinite(n) && n > 0) return n;
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
return 0;
|
|
2785
|
+
}
|
|
2786
|
+
async function queryCredit(client) {
|
|
2787
|
+
try {
|
|
2788
|
+
const r = await client.getJson("/snap-manager/v1/statistics/plugin");
|
|
2789
|
+
const list = r?.metrics ?? [];
|
|
2790
|
+
const total = pickMetric(list, "usageTotalPackageCredit");
|
|
2791
|
+
if (!total) return null;
|
|
2792
|
+
const pkg = (m) => m ? { amount: Number(m.package_credit_amount ?? 0), used: Number(m.package_credit_used ?? 0), remain: Number(m.package_credit_remain ?? 0) } : void 0;
|
|
2793
|
+
const tokens = pickMetric(list, "usageTokenChatMessages");
|
|
2794
|
+
return {
|
|
2795
|
+
total: Number(total.package_credit_amount ?? 0),
|
|
2796
|
+
used: Number(total.package_credit_used ?? 0),
|
|
2797
|
+
remain: Number(total.package_credit_remain ?? 0),
|
|
2798
|
+
basic: pkg(pickMetric(list, "usageBasicPackageCredit")),
|
|
2799
|
+
bonus: pkg(pickMetric(list, "usageBonusPackageCredit")),
|
|
2800
|
+
onDemand: pkg(pickMetric(list, "usageOnDemandPackageCredit")),
|
|
2801
|
+
totalTokens: tokens ? Number(tokens.usage_token_num ?? 0) : void 0,
|
|
2802
|
+
// package_credit_expiring_amount 只在两个「汇总」指标上出现,
|
|
2803
|
+
// 分项指标(basic / onDemand)没有这个字段,所以取汇总那份。
|
|
2804
|
+
expiringAmount: pickExpiring(list),
|
|
2805
|
+
packageStart: typeof r?.start_date === "string" ? r.start_date : void 0,
|
|
2806
|
+
packageEnd: typeof r?.end_date === "string" ? r.end_date : void 0
|
|
2807
|
+
};
|
|
2808
|
+
} catch {
|
|
2809
|
+
return null;
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
async function accountInfo(ctx) {
|
|
2813
|
+
if (!ctx.loaded || !ctx.client) {
|
|
2814
|
+
return { ok: false, stage: "credentials", error: ctx.loadError };
|
|
2815
|
+
}
|
|
2816
|
+
const masked = maskKey(ctx.loaded.key.ak, ctx.loaded.key.sk);
|
|
2817
|
+
let token = ctx.loaded.key.securityToken ?? ctx.sts?.peek()?.securityToken;
|
|
2818
|
+
if (!token && ctx.sts) {
|
|
2819
|
+
try {
|
|
2820
|
+
token = (await ctx.sts.get()).securityToken;
|
|
2821
|
+
} catch {
|
|
2822
|
+
}
|
|
2823
|
+
}
|
|
2824
|
+
const identity = parseStsIdentity(token);
|
|
2825
|
+
const borrowedExpiry = ctx.loaded.source === "codearts" ? typeof ctx.loaded.key.expiresAt === "number" ? ctx.loaded.key.expiresAt : ctx.loaded.expiresAtMs ?? null : null;
|
|
2826
|
+
const base = {
|
|
2827
|
+
ak: masked.ak,
|
|
2828
|
+
sk: masked.sk,
|
|
2829
|
+
source: ctx.loaded.source,
|
|
2830
|
+
account: identity.accountName,
|
|
2831
|
+
userId: identity.userId,
|
|
2832
|
+
/** 码道登录态借来的临时凭证到期时间(epoch ms);永久 AK/SK 为 null */
|
|
2833
|
+
expiresAtMs: borrowedExpiry,
|
|
2834
|
+
/** 是否为临时凭证 —— 面板据此显示过期提示 */
|
|
2835
|
+
temporary: ctx.loaded.source === "codearts"
|
|
2836
|
+
};
|
|
2837
|
+
try {
|
|
2838
|
+
const key = await ctx.client.ensureSessionKey();
|
|
2839
|
+
const stsExpiry = ctx.sts?.expiresAtMs() ?? null;
|
|
2840
|
+
base.sts = stsExpiry ? { expiresAt: new Date(stsExpiry).toISOString(), ttlSec: Math.round((stsExpiry - Date.now()) / 1e3) } : "provided";
|
|
2841
|
+
base.sessionKey = { keyId: key.keyId, ttlSec: Math.round((key.expiresAt - Date.now()) / 1e3) };
|
|
2842
|
+
const credit = await queryCredit(ctx.client);
|
|
2843
|
+
if (credit) {
|
|
2844
|
+
base.credit = credit;
|
|
2845
|
+
const notice = evaluateExpiry(credit);
|
|
2846
|
+
if (notice.level !== "none") base.creditExpiry = notice;
|
|
2847
|
+
}
|
|
2848
|
+
try {
|
|
2849
|
+
const roles = await ctx.client.getJson("/snap-manager/v1/member/roles");
|
|
2850
|
+
base.roles = roles?.enterprise_roles ?? [];
|
|
2851
|
+
} catch {
|
|
2852
|
+
}
|
|
2853
|
+
return { ok: true, stage: "ready", ...base };
|
|
2854
|
+
} catch (err) {
|
|
2855
|
+
return { ok: false, stage: "handshake", error: String(err?.message ?? err), ...base };
|
|
2856
|
+
}
|
|
2857
|
+
}
|
|
2858
|
+
async function runSelfTest(ctx) {
|
|
2859
|
+
if (!ctx.loaded) return { ok: false, steps: [{ name: "\u51ED\u8BC1", ok: false, detail: ctx.loadError ?? "\u672A\u52A0\u8F7D" }] };
|
|
2860
|
+
const steps = [];
|
|
2861
|
+
const step = async (name, fn2) => {
|
|
2862
|
+
const t0 = Date.now();
|
|
2863
|
+
try {
|
|
2864
|
+
const detail = await fn2();
|
|
2865
|
+
steps.push({ name, ok: true, detail: detail || void 0, ms: Date.now() - t0 });
|
|
2866
|
+
return true;
|
|
2867
|
+
} catch (e) {
|
|
2868
|
+
steps.push({ name, ok: false, detail: String(e?.message ?? e).slice(0, 200), ms: Date.now() - t0 });
|
|
2869
|
+
return false;
|
|
2870
|
+
}
|
|
2871
|
+
};
|
|
2872
|
+
const stsOk = await step("\u51ED\u8BC1\u5C31\u7EEA", async () => {
|
|
2873
|
+
let reloaded = null;
|
|
2874
|
+
try {
|
|
2875
|
+
reloaded = await loadCredentials();
|
|
2876
|
+
} catch {
|
|
2877
|
+
}
|
|
2878
|
+
if (reloaded) {
|
|
2879
|
+
ctx.loaded = reloaded;
|
|
2880
|
+
ctx.loadError = null;
|
|
2881
|
+
if (!reloaded.key.securityToken && !ctx.sts) {
|
|
2882
|
+
try {
|
|
2883
|
+
ctx.sts = new StsProvider({ ak: reloaded.key.ak, sk: reloaded.key.sk });
|
|
2884
|
+
} catch {
|
|
2885
|
+
}
|
|
2886
|
+
}
|
|
2887
|
+
}
|
|
2888
|
+
const l = ctx.loaded;
|
|
2889
|
+
if (!l) throw new Error(ctx.loadError ?? "\u672A\u52A0\u8F7D");
|
|
2890
|
+
if (l.key.securityToken) {
|
|
2891
|
+
const left = typeof l.key.expiresAt === "number" ? Math.round((l.key.expiresAt - Date.now()) / 6e4) : null;
|
|
2892
|
+
const from = l.source === "codearts" ? "\u7801\u9053\u767B\u5F55\u6001" : l.source;
|
|
2893
|
+
return `${from} \xB7 \u4E34\u65F6\u51ED\u8BC1${left !== null ? `\uFF0C\u5269 ${left} \u5206\u949F` : ""}`;
|
|
2894
|
+
}
|
|
2895
|
+
const sts = new StsProvider({ ak: l.key.ak, sk: l.key.sk });
|
|
2896
|
+
const creds = await sts.credentials();
|
|
2897
|
+
ctx.sts = sts;
|
|
2898
|
+
ctx.client = new MadaoClient({ credentials: creds });
|
|
2899
|
+
return `\u6C38\u4E45 AK/SK \xB7 \u5DF2\u6362 STS\uFF0C\u6709\u6548\u81F3 ${new Date(sts.expiresAtMs() ?? 0).toLocaleTimeString()}`;
|
|
2900
|
+
});
|
|
2901
|
+
if (!stsOk) return { ok: false, steps };
|
|
2902
|
+
await step("\u5BC6\u94A5\u534F\u5546", async () => {
|
|
2903
|
+
ctx.client.resetSessionKey();
|
|
2904
|
+
const k = await ctx.client.ensureSessionKey();
|
|
2905
|
+
return `keyId ${k.keyId.slice(0, 8)} \xB7 TTL ${Math.round((k.expiresAt - Date.now()) / 1e3)}s`;
|
|
2906
|
+
});
|
|
2907
|
+
await step("\u6A21\u578B\u6E05\u5355", async () => {
|
|
2908
|
+
const { discoverModels: discoverModels2 } = await Promise.resolve().then(() => (init_models(), models_exports));
|
|
2909
|
+
const found = await discoverModels2(ctx.client);
|
|
2910
|
+
if (found.source === "gateway") {
|
|
2911
|
+
ctx.models = found.models;
|
|
2912
|
+
return `${found.models.length} \u4E2A\u6A21\u578B`;
|
|
2913
|
+
}
|
|
2914
|
+
throw new Error(found.error ?? "\u7F51\u5173\u672A\u8FD4\u56DE\u6E05\u5355");
|
|
2915
|
+
});
|
|
2916
|
+
await step("\u79EF\u5206\u989D\u5EA6", async () => {
|
|
2917
|
+
const c = await queryCredit(ctx.client);
|
|
2918
|
+
if (!c) throw new Error("\u989D\u5EA6\u63A5\u53E3\u65E0\u8FD4\u56DE");
|
|
2919
|
+
return `\u5269\u4F59 ${c.remain} / \u5171 ${c.total}`;
|
|
2920
|
+
});
|
|
2921
|
+
const ok = steps.every((s) => s.ok);
|
|
2922
|
+
return { ok, steps };
|
|
2923
|
+
}
|
|
2924
|
+
function readBody(req) {
|
|
2925
|
+
return new Promise((resolve, reject) => {
|
|
2926
|
+
const chunks = [];
|
|
2927
|
+
req.on("data", (c) => chunks.push(Buffer.from(c)));
|
|
2928
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
2929
|
+
req.on("error", reject);
|
|
2930
|
+
});
|
|
2931
|
+
}
|
|
2932
|
+
function json(res, status, payload) {
|
|
2933
|
+
const body = JSON.stringify(payload);
|
|
2934
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Content-Length": Buffer.byteLength(body) });
|
|
2935
|
+
res.end(body);
|
|
2936
|
+
}
|
|
2937
|
+
|
|
2938
|
+
// src/bin.ts
|
|
2939
|
+
init_credentials();
|
|
2940
|
+
init_sts_provider();
|
|
2941
|
+
init_client();
|
|
2942
|
+
function arg(name, fallback) {
|
|
2943
|
+
const i = process.argv.indexOf(`--${name}`);
|
|
2944
|
+
if (i >= 0 && process.argv[i + 1]) return process.argv[i + 1];
|
|
2945
|
+
return fallback;
|
|
2946
|
+
}
|
|
2947
|
+
async function cmdServe() {
|
|
2948
|
+
const port = Number(arg("port", "8765"));
|
|
2949
|
+
const host = arg("host", "127.0.0.1");
|
|
2950
|
+
const gateway = arg("gateway");
|
|
2951
|
+
const srv = await startServer({ port, host, gateway });
|
|
2952
|
+
console.log(`dsh-connect-madao listening on ${srv.url}`);
|
|
2953
|
+
console.log(` OpenAI base URL : ${srv.url}/v1`);
|
|
2954
|
+
console.log(` health : ${srv.url}/healthz`);
|
|
2955
|
+
const shutdown = async () => {
|
|
2956
|
+
await srv.close();
|
|
2957
|
+
process.exit(0);
|
|
2958
|
+
};
|
|
2959
|
+
process.on("SIGINT", shutdown);
|
|
2960
|
+
process.on("SIGTERM", shutdown);
|
|
2961
|
+
}
|
|
2962
|
+
async function cmdDoctor() {
|
|
2963
|
+
console.log("== dsh-connect-madao doctor ==\n");
|
|
2964
|
+
let loaded;
|
|
2965
|
+
try {
|
|
2966
|
+
loaded = await loadCredentials();
|
|
2967
|
+
} catch (err) {
|
|
2968
|
+
console.error("\u2717 \u51ED\u8BC1\u52A0\u8F7D\u5931\u8D25");
|
|
2969
|
+
console.error(String(err.message));
|
|
2970
|
+
process.exit(1);
|
|
2971
|
+
}
|
|
2972
|
+
const m = maskKey(loaded.key.ak, loaded.key.sk);
|
|
2973
|
+
console.log("\u2713 \u51ED\u8BC1\u5DF2\u52A0\u8F7D");
|
|
2974
|
+
console.log(` \u6765\u6E90: ${loaded.source}${loaded.path ? ` (${loaded.path})` : ""}`);
|
|
2975
|
+
console.log(` AK: ${m.ak} SK: ${m.sk}`);
|
|
2976
|
+
console.log(` STS: ${loaded.key.securityToken ? "\u5DF2\u76F4\u63A5\u63D0\u4F9B" : "\u5F85\u6362\u53D6"}
|
|
2977
|
+
`);
|
|
2978
|
+
let creds;
|
|
2979
|
+
if (loaded.key.securityToken) {
|
|
2980
|
+
creds = { ak: loaded.key.ak, sk: loaded.key.sk, securityToken: loaded.key.securityToken };
|
|
2981
|
+
console.log("\u2713 \u4F7F\u7528\u5DF2\u63D0\u4F9B\u7684 STS\n");
|
|
2982
|
+
} else {
|
|
2983
|
+
console.log("== \u6362\u53D6 STS ==");
|
|
2984
|
+
try {
|
|
2985
|
+
const sts = new StsProvider({ ak: loaded.key.ak, sk: loaded.key.sk });
|
|
2986
|
+
creds = await sts.credentials();
|
|
2987
|
+
const exp = sts.expiresAtMs();
|
|
2988
|
+
console.log("\u2713 \u6210\u529F");
|
|
2989
|
+
console.log(` \u4E34\u65F6 AK: ${creds.ak}`);
|
|
2990
|
+
console.log(` STS \u957F\u5EA6: ${creds.securityToken.length}`);
|
|
2991
|
+
if (exp) console.log(` \u8FC7\u671F: ${new Date(exp).toISOString()}`);
|
|
2992
|
+
console.log();
|
|
2993
|
+
} catch (err) {
|
|
2994
|
+
console.error("\u2717 \u5931\u8D25");
|
|
2995
|
+
console.error(String(err.message).slice(0, 600));
|
|
2996
|
+
process.exit(1);
|
|
2997
|
+
}
|
|
2998
|
+
}
|
|
2999
|
+
console.log("== \u5BC6\u94A5\u534F\u5546 ==");
|
|
3000
|
+
const client = new MadaoClient({ credentials: creds });
|
|
3001
|
+
try {
|
|
3002
|
+
const key = await client.ensureSessionKey();
|
|
3003
|
+
console.log("\u2713 \u6210\u529F");
|
|
3004
|
+
console.log(` keyId: ${key.keyId}`);
|
|
3005
|
+
console.log(` TTL: ${Math.round((key.expiresAt - Date.now()) / 1e3)}s
|
|
3006
|
+
`);
|
|
3007
|
+
} catch (err) {
|
|
3008
|
+
console.error("\u2717 \u5931\u8D25");
|
|
3009
|
+
console.error(String(err.message).slice(0, 600));
|
|
3010
|
+
process.exit(1);
|
|
3011
|
+
}
|
|
3012
|
+
console.log("== \u6A21\u578B\u6E05\u5355 ==");
|
|
3013
|
+
try {
|
|
3014
|
+
const models = await client.getModels();
|
|
3015
|
+
const list = models?.builtinModels ?? [];
|
|
3016
|
+
console.log(`\u2713 ${list.length} \u4E2A\u6A21\u578B`);
|
|
3017
|
+
for (const it of list) console.log(` - ${it.model_id} (${it.model_category ?? ""})`);
|
|
3018
|
+
} catch (err) {
|
|
3019
|
+
console.warn("\u26A0 \u62C9\u53D6\u5931\u8D25\uFF08\u4E0D\u5F71\u54CD chat\uFF09:", String(err.message).slice(0, 200));
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
async function cmdModels() {
|
|
3023
|
+
const { loadCredentials: loadCredentials2 } = await Promise.resolve().then(() => (init_credentials(), credentials_exports));
|
|
3024
|
+
const { StsProvider: StsProvider2 } = await Promise.resolve().then(() => (init_sts_provider(), sts_provider_exports));
|
|
3025
|
+
const { MadaoClient: MadaoClient2 } = await Promise.resolve().then(() => (init_client(), client_exports));
|
|
3026
|
+
const { discoverModels: discoverModels2 } = await Promise.resolve().then(() => (init_models(), models_exports));
|
|
3027
|
+
try {
|
|
3028
|
+
const loaded = await loadCredentials2();
|
|
3029
|
+
let creds = loaded.key;
|
|
3030
|
+
if (!creds.securityToken) creds = await new StsProvider2({ ak: creds.ak, sk: creds.sk }).credentials();
|
|
3031
|
+
const client = new MadaoClient2({ credentials: creds });
|
|
3032
|
+
const found = await discoverModels2(client);
|
|
3033
|
+
if (found.source === "fallback") {
|
|
3034
|
+
console.log(`\u7F51\u5173\u4E0D\u53EF\u8FBE\uFF0C\u4EE5\u4E0B\u4E3A\u515C\u5E95\u6E05\u5355\uFF1A${found.error ?? ""}`);
|
|
3035
|
+
}
|
|
3036
|
+
for (const m of found.models) {
|
|
3037
|
+
const tags = [m.supportsImages ? "\u{1F5BC}" : "", m.strengths.length ? `\u601D\u8003:${m.strengths.join("/")}` : ""].filter(Boolean).join(" ");
|
|
3038
|
+
console.log(
|
|
3039
|
+
`${m.id.padEnd(26)} ${m.name.padEnd(22)} ctx=${String(m.context).padEnd(8)} max=${String(m.maxOutput).padEnd(6)} ${(m.ratio ?? "-").padEnd(7)} ${tags}`
|
|
3040
|
+
);
|
|
3041
|
+
}
|
|
3042
|
+
} catch (e) {
|
|
3043
|
+
console.error(`\u8BFB\u53D6\u6A21\u578B\u6E05\u5355\u5931\u8D25\uFF1A${String(e?.message ?? e)}`);
|
|
3044
|
+
process.exitCode = 1;
|
|
3045
|
+
}
|
|
3046
|
+
}
|
|
3047
|
+
var cmd = process.argv[2] ?? "serve";
|
|
3048
|
+
var table = {
|
|
3049
|
+
serve: cmdServe,
|
|
3050
|
+
doctor: cmdDoctor,
|
|
3051
|
+
models: cmdModels
|
|
3052
|
+
};
|
|
3053
|
+
var fn = table[cmd];
|
|
3054
|
+
if (!fn) {
|
|
3055
|
+
console.error(`\u672A\u77E5\u5B50\u547D\u4EE4: ${cmd}
|
|
3056
|
+
\u53EF\u7528: ${Object.keys(table).join(", ")}`);
|
|
3057
|
+
process.exit(2);
|
|
3058
|
+
}
|
|
3059
|
+
fn().catch((err) => {
|
|
3060
|
+
console.error(String(err?.stack ?? err));
|
|
3061
|
+
process.exit(1);
|
|
3062
|
+
});
|