-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathcore.js
More file actions
2158 lines (1953 loc) · 73.4 KB
/
Copy pathcore.js
File metadata and controls
2158 lines (1953 loc) · 73.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 核心业务逻辑 - 所有平台共用
*/
// ============================================
// UUID 生成 (内联,避免 ESM 问题)
// ============================================
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = Math.random() * 16 | 0;
return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
}
// ============================================
// 配置
// ============================================
const BAXIA_VERSION = '2.5.36';
const CACHE_TTL = 4 * 60 * 1000;
const QWEN_BASE_URL = 'https://chat.qwen.ai';
const QWEN_WEB_REFERER = `${QWEN_BASE_URL}/`;
const QWEN_GUEST_REFERER = `${QWEN_BASE_URL}/c/guest`;
const WEB_USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36';
const WEB_ACCEPT_LANGUAGE = 'zh-CN,zh;q=0.9,en;q=0.8';
let tokenCache = null;
let tokenCacheTime = 0;
// ============================================
// Baxia Token 生成
// ============================================
function randomString(length) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
let result = '';
const randomBytes = cryptoRandomBytes(length);
for (let i = 0; i < length; i++) {
result += chars[randomBytes[i] % chars.length];
}
return result;
}
function cryptoRandomBytes(length) {
// Node.js 环境 (包括 Vercel/Netlify)
if (typeof process !== 'undefined' && process.versions && process.versions.node) {
return require('crypto').randomBytes(length);
}
// Cloudflare Workers / 浏览器
const bytes = new Uint8Array(length);
crypto.getRandomValues(bytes);
return bytes;
}
function cryptoHash(data) {
// Node.js 环境 (包括 Vercel/Netlify)
if (typeof process !== 'undefined' && process.versions && process.versions.node) {
return require('crypto').createHash('md5').update(data).digest('base64').substring(0, 32);
}
// Cloudflare Workers / 浏览器 - 返回随机字符串
return randomString(32);
}
function generateWebGLFingerprint() {
const renderers = [
'ANGLE (Intel, Intel(R) UHD Graphics 630, OpenGL 4.6)',
'ANGLE (NVIDIA, NVIDIA GeForce GTX 1080, OpenGL 4.6)',
'ANGLE (AMD, AMD Radeon RX 580, OpenGL 4.6)',
];
return { renderer: renderers[Math.floor(Math.random() * renderers.length)], vendor: 'Google Inc. (Intel)' };
}
async function collectFingerprintData() {
const platforms = ['Win32', 'Linux x86_64', 'MacIntel'];
const languages = ['en-US', 'zh-CN', 'en-GB'];
const canvas = cryptoHash(cryptoRandomBytes(32));
return {
p: platforms[Math.floor(Math.random() * platforms.length)],
l: languages[Math.floor(Math.random() * languages.length)],
hc: 4 + Math.floor(Math.random() * 12),
dm: [4, 8, 16, 32][Math.floor(Math.random() * 4)],
to: [-480, -300, 0, 60, 480][Math.floor(Math.random() * 5)],
sw: 1920 + Math.floor(Math.random() * 200),
sh: 1080 + Math.floor(Math.random() * 100),
cd: 24,
pr: [1, 1.25, 1.5, 2][Math.floor(Math.random() * 4)],
wf: generateWebGLFingerprint().renderer.substring(0, 20),
cf: canvas,
af: (124.04347527516074 + Math.random() * 0.001).toFixed(14),
ts: Date.now(),
r: Math.random(),
};
}
function encodeBaxiaToken(data) {
const jsonStr = JSON.stringify(data);
let encoded;
if (typeof Buffer === 'undefined') {
encoded = btoa(unescape(encodeURIComponent(jsonStr)));
} else {
encoded = Buffer.from(jsonStr).toString('base64');
}
return `${BAXIA_VERSION.replace(/\./g, '')}!${encoded}`;
}
async function getBaxiaTokens() {
const now = Date.now();
if (tokenCache && (now - tokenCacheTime) < CACHE_TTL) {
return tokenCache;
}
const bxUa = encodeBaxiaToken(await collectFingerprintData());
let bxUmidToken;
try {
const resp = await fetch('https://sg-wum.alibaba.com/w/wu.json', {
headers: { 'User-Agent': WEB_USER_AGENT }
});
bxUmidToken = resp.headers.get('etag') || 'T2gA' + randomString(40);
} catch { bxUmidToken = 'T2gA' + randomString(40); }
const result = { bxUa, bxUmidToken, bxV: BAXIA_VERSION };
tokenCache = result;
tokenCacheTime = now;
return result;
}
// ============================================
// 认证
// ============================================
function getApiTokens(env) {
const tokens = env?.API_TOKENS || process?.env?.API_TOKENS;
if (!tokens) return [];
return tokens.split(',').map(t => t.trim()).filter(t => t);
}
function validateToken(authHeader, env) {
const tokens = getApiTokens(env);
if (tokens.length === 0) return true;
const token = authHeader && authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : '';
return tokens.includes(token);
}
// ============================================
// 响应工具
// ============================================
function createResponse(body, status = 200, headers = {}) {
return {
statusCode: status,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
...headers,
},
body: typeof body === 'string' ? body : JSON.stringify(body),
};
}
function createStreamResponse(body) {
return {
statusCode: 200,
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
},
body,
};
}
function previewBody(rawText, maxLen = 240) {
const text = normalizeInputString(rawText || '');
if (!text) return '';
return text.length > maxLen ? `${text.slice(0, maxLen)}...` : text;
}
async function safeReadJson(response) {
const status = response?.status;
const rawText = await response.text().catch(() => '');
if (!rawText) {
return { ok: false, status, data: null, rawText: '', parseError: new Error('Empty response body') };
}
try {
return { ok: true, status, data: JSON.parse(rawText), rawText, parseError: null };
} catch (parseError) {
return { ok: false, status, data: null, rawText, parseError };
}
}
function logChatDetail(runtime, event, detail = {}) {
const rawFlag = (typeof process !== 'undefined' && process?.env?.CHAT_DETAIL_LOG) || '';
const enabled = ['1', 'true', 'yes', 'on'].includes(String(rawFlag).toLowerCase());
if (!enabled) return;
const prefix = `[qwen2api][${runtime}][chat]`;
try {
console.log(`${prefix} ${event}`, JSON.stringify(detail));
} catch {
console.log(`${prefix} ${event}`);
}
}
function toArray(value) {
return Array.isArray(value) ? value : [];
}
function normalizeMimeType(mimeType) {
return (mimeType || 'application/octet-stream').toLowerCase();
}
function inferFileCategory(mimeType, explicitType) {
if (explicitType === 'image' || explicitType === 'audio' || explicitType === 'video' || explicitType === 'document') {
return explicitType;
}
const mime = normalizeMimeType(mimeType);
if (mime.startsWith('image/')) return 'image';
if (mime.startsWith('audio/')) return 'audio';
if (mime.startsWith('video/')) return 'video';
return 'document';
}
function fileExtensionFromMime(mimeType) {
const mime = normalizeMimeType(mimeType);
const mapping = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/jpg': 'jpg',
'image/webp': 'webp',
'image/gif': 'gif',
'image/bmp': 'bmp',
'image/svg+xml': 'svg',
'application/pdf': 'pdf',
'text/plain': 'txt',
'text/markdown': 'md',
'application/json': 'json',
'audio/mpeg': 'mp3',
'audio/wav': 'wav',
'audio/x-wav': 'wav',
'audio/mp4': 'm4a',
'audio/ogg': 'ogg',
'video/mp4': 'mp4',
'video/webm': 'webm',
'video/quicktime': 'mov',
'video/x-matroska': 'mkv',
'video/avi': 'avi',
};
return mapping[mime] || 'bin';
}
function decodeBase64ToBytes(base64) {
if (typeof Buffer !== 'undefined') {
return new Uint8Array(Buffer.from(base64, 'base64'));
}
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
function parseDataUrl(dataUrl) {
if (typeof dataUrl !== 'string') return null;
const matched = dataUrl.match(/^data:([^;,]+)?;base64,(.+)$/i);
if (!matched) return null;
return {
mimeType: normalizeMimeType(matched[1] || 'application/octet-stream'),
bytes: decodeBase64ToBytes(matched[2]),
};
}
function inferFilename(rawFilename, mimeType) {
const name = normalizeInputString(rawFilename);
if (name) {
return name;
}
return `attachment-${uuidv4()}.${fileExtensionFromMime(mimeType)}`;
}
function normalizeInputString(value) {
if (typeof value !== 'string') return '';
const trimmed = value.trim();
if (!trimmed) return '';
const lower = trimmed.toLowerCase();
if (lower === '[undefined]' || lower === 'undefined' || lower === '[null]' || lower === 'null') {
return '';
}
return trimmed;
}
function normalizeReasoningFragments(value) {
if (typeof value === 'string') {
const text = normalizeReasoningString(value);
return text ? [text] : [];
}
if (!Array.isArray(value)) return [];
const out = [];
for (const item of value) {
if (typeof item === 'string') {
const text = normalizeReasoningString(item);
if (text) out.push(text);
} else if (item && typeof item === 'object') {
const text = normalizeReasoningString(item.text || item.content || item.value);
if (text) out.push(text);
}
}
return out;
}
function normalizeReasoningString(value) {
if (typeof value !== 'string') return '';
const lowered = value.trim().toLowerCase();
if (lowered === '[undefined]' || lowered === 'undefined' || lowered === '[null]' || lowered === 'null') {
return '';
}
return value;
}
function extractReasoningContentFromDelta(delta) {
if (!delta || typeof delta !== 'object') return '';
const direct = normalizeReasoningString(delta.reasoning_content || delta.reasoning || '');
if (direct) return direct;
const phase = typeof delta.phase === 'string' ? delta.phase : '';
if (phase !== 'thinking_summary') return '';
const thoughtContent = normalizeReasoningFragments(delta?.extra?.summary_thought?.content);
if (thoughtContent.length > 0) return thoughtContent.join('\n');
return '';
}
function mapUpstreamDeltaToOpenAI(delta) {
if (!delta || typeof delta !== 'object') return null;
const mapped = {};
// OpenAI API 规范: 流式响应中 delta.role 只能是 "assistant" 或不设置
// 当上游返回 "function" 等角色时,不设置 role 字段
if (delta.role === 'assistant') mapped.role = delta.role;
if (typeof delta.content === 'string') mapped.content = delta.content;
const reasoningContent = extractReasoningContentFromDelta(delta);
if (reasoningContent) mapped.reasoning_content = reasoningContent;
return Object.keys(mapped).length > 0 ? mapped : null;
}
function parseQwenSsePayload(rawPayload) {
const payload = typeof rawPayload === 'string' ? rawPayload : '';
const events = [];
const contentParts = [];
const reasoningParts = [];
let usage = null;
for (const line of payload.split('\n')) {
const trimmed = line.trimStart();
if (!trimmed.startsWith('data:')) continue;
const data = trimmed.slice(5).trim();
if (!data || data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
if (parsed?.usage && typeof parsed.usage === 'object') {
usage = parsed.usage;
}
const upstreamDelta = parsed?.choices?.[0]?.delta;
const delta = mapUpstreamDeltaToOpenAI(upstreamDelta);
const finishReason = parsed?.choices?.[0]?.finish_reason || null;
if (delta || finishReason) {
events.push({ delta: delta || {}, finish_reason: finishReason });
}
if (delta?.content) contentParts.push(delta.content);
if (delta?.reasoning_content) reasoningParts.push(delta.reasoning_content);
} catch (parseError) {
void parseError;
}
}
return {
events,
content: contentParts.join(''),
reasoning_content: reasoningParts.join(''),
usage,
};
}
function mapUsageToOpenAI(usage) {
const inputTokens = Number(usage?.input_tokens || 0);
const outputTokens = Number(usage?.output_tokens || 0);
const totalTokens = Number(usage?.total_tokens || (inputTokens + outputTokens));
const mapped = {
prompt_tokens: inputTokens,
completion_tokens: outputTokens,
total_tokens: totalTokens,
};
const inputDetails = usage?.input_tokens_details && typeof usage.input_tokens_details === 'object'
? { ...usage.input_tokens_details }
: null;
const outputDetails = usage?.output_tokens_details && typeof usage.output_tokens_details === 'object'
? { ...usage.output_tokens_details }
: null;
if (inputDetails && Object.keys(inputDetails).length > 0) {
mapped.prompt_tokens_details = inputDetails;
}
if (outputDetails && Object.keys(outputDetails).length > 0) {
mapped.completion_tokens_details = outputDetails;
}
return mapped;
}
function tryParseOpenAiImageSize(size) {
const text = normalizeInputString(size);
if (!text) return null;
const m = text.toLowerCase().match(/^(\d{2,5})\s*x\s*(\d{2,5})$/);
if (!m) return null;
const width = Number(m[1]);
const height = Number(m[2]);
if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) return null;
return { width, height };
}
function tryParseRatioString(size) {
const text = normalizeInputString(size);
if (!text) return null;
const m = text.toLowerCase().match(/^(\d{1,2}):(\d{1,2})$/);
if (!m) return null;
const w = Number(m[1]);
const h = Number(m[2]);
if (!Number.isFinite(w) || !Number.isFinite(h) || w <= 0 || h <= 0) return null;
return `${w}:${h}`;
}
function mapOpenAiImageSizeToQwenRatio(size) {
// Qwen Web t2i 在抓包中使用 ratio 文本,例如 "16:9"。
// 支持两种格式:
// 1. 直接比例字符串:"1:1", "16:9", "9:16", "4:3", "3:4"
// 2. OpenAI 格式:"1024x1024" (映射到最接近的比例)
// 首先尝试直接解析比例字符串
const ratio = tryParseRatioString(size);
if (ratio) {
// 验证是否为支持的比例
const validRatios = ['1:1', '16:9', '9:16', '4:3', '3:4'];
if (validRatios.includes(ratio)) {
return ratio;
}
}
// 否则尝试解析 OpenAI 尺寸格式并映射到最近比例
const parsed = tryParseOpenAiImageSize(size);
if (!parsed) return '1:1';
const { width, height } = parsed;
const r = width / height;
// 常见目标比例
const candidates = [
{ key: '1:1', r: 1 },
{ key: '16:9', r: 16 / 9 },
{ key: '9:16', r: 9 / 16 },
{ key: '4:3', r: 4 / 3 },
{ key: '3:4', r: 3 / 4 },
];
let best = candidates[0];
let bestDiff = Infinity;
for (const c of candidates) {
const diff = Math.abs(r - c.r);
if (diff < bestDiff) {
best = c;
bestDiff = diff;
}
}
return best.key;
}
function extractImageUrlsFromUpstreamSse(rawPayload) {
const payload = typeof rawPayload === 'string' ? rawPayload : '';
const urls = [];
for (const line of payload.split('\n')) {
const trimmed = line.trimStart();
if (!trimmed.startsWith('data:')) continue;
const data = trimmed.slice(5).trim();
if (!data || data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const delta = parsed?.choices?.[0]?.delta;
if (!delta || typeof delta !== 'object') continue;
const phase = typeof delta.phase === 'string' ? delta.phase : '';
if (phase !== 'image_gen') continue;
const content = delta.content;
if (typeof content !== 'string') continue;
const url = content.trim();
if (!url) continue;
if (!/^https?:\/\//i.test(url)) continue;
urls.push(url);
} catch {
// ignore
}
}
// 去重但保持顺序
const seen = new Set();
const out = [];
for (const u of urls) {
if (seen.has(u)) continue;
seen.add(u);
out.push(u);
}
return out;
}
function extractUpstreamErrorFromSse(rawPayload) {
const payload = typeof rawPayload === 'string' ? rawPayload : '';
for (const line of payload.split('\n')) {
const trimmed = line.trimStart();
if (!trimmed.startsWith('data:')) continue;
const data = trimmed.slice(5).trim();
if (!data || data === '[DONE]') continue;
try {
const parsed = JSON.parse(data);
const err = parsed?.error;
if (err && err.code === 'data_inspection_failed') {
return { message: err.details || err.message || '内容安全警告', code: err.code };
}
} catch {}
}
return null;
}
async function fetchImageAsBase64(url) {
const resp = await fetch(url);
if (!resp.ok) {
throw new Error(`Failed to fetch image: HTTP ${resp.status}`);
}
const arrayBuffer = await resp.arrayBuffer();
const bytes = Buffer.from(arrayBuffer);
return bytes.toString('base64');
}
function decodeUtf8(bytes) {
try {
return new TextDecoder('utf-8', { fatal: false }).decode(bytes || new Uint8Array());
} catch {
return '';
}
}
function extractInlineTextFromAttachment(source, mimeType, filename) {
const mime = normalizeMimeType(mimeType);
const isTextLike = mime.startsWith('text/') || mime === 'application/json' || mime === 'application/xml' || mime === 'text/markdown';
if (!isTextLike) return '';
const parsed = parseDataUrl(source);
if (!parsed) return '';
const text = normalizeInputString(decodeUtf8(parsed.bytes));
if (!text) return '';
const label = normalizeInputString(filename) || 'unnamed.txt';
const capped = text.length > 12000 ? `${text.slice(0, 12000)}\n...[truncated]` : text;
return `[附件文本 ${label}]\n${capped}`;
}
function pushTextPart(parts, value) {
const text = normalizeInputString(value);
if (text) {
parts.push(text);
}
}
function normalizeContentParts(content) {
if (typeof content === 'string') {
const text = normalizeInputString(content);
return {
text,
attachments: [],
};
}
if (!Array.isArray(content)) {
return {
text: '',
attachments: [],
};
}
const textParts = [];
const attachments = [];
for (const part of content) {
if (!part) continue;
if (typeof part === 'string') {
pushTextPart(textParts, part);
continue;
}
const type = part.type || '';
if (type === 'text' || type === 'input_text') {
pushTextPart(textParts, part.text || part.input_text);
continue;
}
if (type === 'image_url' || type === 'input_image') {
const imageUrl = normalizeInputString(
part.image_url?.url ||
part.image_url ||
part.url ||
part.file_url ||
part.file_data
);
if (imageUrl) {
attachments.push({
source: imageUrl,
filename: normalizeInputString(part.filename) || normalizeInputString(part.name),
mimeType: normalizeInputString(part.mime_type) || normalizeInputString(part.content_type),
explicitType: 'image',
});
}
continue;
}
if (type === 'file' || type === 'input_file' || type === 'audio' || type === 'input_audio' || type === 'video' || type === 'input_video') {
const fileSource = normalizeInputString(part.file_data || part.url || part.file_url || part.data);
if (fileSource) {
const normalizedFilename = normalizeInputString(part.filename) || normalizeInputString(part.name);
const normalizedMimeType = normalizeInputString(part.mime_type) || normalizeInputString(part.content_type);
const explicitType = type.includes('audio') ? 'audio' : (type.includes('video') ? 'video' : undefined);
attachments.push({
source: fileSource,
filename: normalizedFilename,
mimeType: normalizedMimeType,
explicitType,
});
}
continue;
}
if (typeof part.text === 'string') {
pushTextPart(textParts, part.text);
}
}
return {
text: textParts.join('\n'),
attachments,
};
}
function normalizeLegacyFiles(message) {
const attachments = [];
const candidates = [...toArray(message?.attachments), ...toArray(message?.files)];
for (const item of candidates) {
if (!item) continue;
const source = normalizeInputString(item.data || item.file_data || item.url || item.file_url);
if (!source) continue;
attachments.push({
source,
filename: normalizeInputString(item.filename) || normalizeInputString(item.name),
mimeType: normalizeInputString(item.mime_type) || normalizeInputString(item.content_type) || normalizeInputString(item.type),
explicitType: item.type,
});
}
return attachments;
}
function parseIncomingMessages(messages) {
const safeMessages = Array.isArray(messages) ? messages : [];
const normalized = safeMessages.map(message => {
const parsed = normalizeContentParts(message?.content);
return {
role: message?.role || 'user',
text: parsed.text,
attachments: [...parsed.attachments, ...normalizeLegacyFiles(message)],
};
});
if (normalized.length === 0) {
return { content: '', attachments: [] };
}
const last = normalized[normalized.length - 1];
const history = normalized.slice(0, -1)
.map(m => {
if (!m.text) return '';
const role = m.role === 'assistant' ? 'Assistant' : m.role === 'system' ? 'System' : 'User';
return `[${role}]: ${m.text}`;
})
.filter(Boolean)
.join('\n\n');
const lastText = last.text || (last.attachments.length > 0 ? '请结合附件内容回答。' : '');
const merged = history
? `${history}\n\n[User]: ${lastText}`
: lastText;
return {
content: merged,
attachments: last.attachments,
};
}
async function getAttachmentBytes(attachment) {
const dataParsed = parseDataUrl(attachment.source);
if (dataParsed) {
return {
bytes: dataParsed.bytes,
mimeType: attachment.mimeType || dataParsed.mimeType,
filename: inferFilename(attachment.filename, attachment.mimeType || dataParsed.mimeType),
};
}
if (/^https?:\/\//i.test(attachment.source)) {
const resp = await fetch(attachment.source);
if (!resp.ok) {
throw new Error(`Failed to fetch attachment URL: ${resp.status}`);
}
const mimeType = attachment.mimeType || resp.headers.get('content-type') || 'application/octet-stream';
const bytes = new Uint8Array(await resp.arrayBuffer());
return {
bytes,
mimeType,
filename: inferFilename(attachment.filename, mimeType),
};
}
const maybeBase64 = attachment.source.replace(/\s+/g, '');
const bytes = decodeBase64ToBytes(maybeBase64);
const mimeType = attachment.mimeType || 'application/octet-stream';
return {
bytes,
mimeType,
filename: inferFilename(attachment.filename, mimeType),
};
}
async function requestUploadToken(file, baxiaTokens) {
const filetype = inferFileCategory(file.mimeType, file.explicitType);
const resp = await fetch(`${QWEN_BASE_URL}/api/v2/files/getstsToken`, {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'bx-ua': baxiaTokens.bxUa,
'bx-umidtoken': baxiaTokens.bxUmidToken,
'bx-v': baxiaTokens.bxV,
'source': 'web',
'timezone': new Date().toUTCString(),
'Referer': QWEN_WEB_REFERER,
'x-request-id': uuidv4(),
},
body: JSON.stringify({
filename: file.filename,
filesize: file.bytes.length,
filetype,
}),
});
const data = await resp.json();
if (!resp.ok || !data?.success || !data?.data?.file_url) {
throw new Error(`Failed to get upload token: ${resp.status}`);
}
return {
tokenData: data.data,
filetype,
};
}
function toHex(bytes) {
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
}
function formatOssDate(date = new Date()) {
const yyyy = date.getUTCFullYear();
const mm = String(date.getUTCMonth() + 1).padStart(2, '0');
const dd = String(date.getUTCDate()).padStart(2, '0');
const hh = String(date.getUTCHours()).padStart(2, '0');
const mi = String(date.getUTCMinutes()).padStart(2, '0');
const ss = String(date.getUTCSeconds()).padStart(2, '0');
return `${yyyy}${mm}${dd}T${hh}${mi}${ss}Z`;
}
function formatOssDateScope(date = new Date()) {
const yyyy = date.getUTCFullYear();
const mm = String(date.getUTCMonth() + 1).padStart(2, '0');
const dd = String(date.getUTCDate()).padStart(2, '0');
return `${yyyy}${mm}${dd}`;
}
function getWebCrypto() {
if (globalThis.crypto && globalThis.crypto.subtle) {
return globalThis.crypto;
}
if (typeof require === 'function') {
const nodeCrypto = require('crypto');
if (nodeCrypto.webcrypto && nodeCrypto.webcrypto.subtle) {
return nodeCrypto.webcrypto;
}
}
throw new Error('WebCrypto is not available');
}
async function sha256Hex(input) {
const cryptoApi = getWebCrypto();
const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input;
const hash = await cryptoApi.subtle.digest('SHA-256', bytes);
return toHex(new Uint8Array(hash));
}
async function hmacSha256(keyBytes, content) {
const cryptoApi = getWebCrypto();
const cryptoKey = await cryptoApi.subtle.importKey(
'raw',
keyBytes,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['sign']
);
const message = typeof content === 'string' ? new TextEncoder().encode(content) : content;
const signature = await cryptoApi.subtle.sign('HMAC', cryptoKey, message);
return new Uint8Array(signature);
}
async function buildOssSignedHeaders(uploadUrl, tokenData, file) {
const parsedUrl = new URL(uploadUrl);
const query = parsedUrl.searchParams;
const credentialFromQuery = decodeURIComponent(query.get('x-oss-credential') || '');
const credentialParts = credentialFromQuery.split('/');
const dateScope = credentialParts[1] || formatOssDateScope();
const region = credentialParts[2] || 'ap-southeast-1';
const xOssDate = query.get('x-oss-date') || formatOssDate();
const hostParts = parsedUrl.hostname.split('.');
const bucket = hostParts.length > 0 ? hostParts[0] : '';
const objectPath = parsedUrl.pathname || '/';
const canonicalUri = bucket ? `/${bucket}${objectPath}` : objectPath;
const xOssUserAgent = 'aliyun-sdk-js/6.23.0';
const canonicalHeaders = [
`content-type:${file.mimeType}`,
'x-oss-content-sha256:UNSIGNED-PAYLOAD',
`x-oss-date:${xOssDate}`,
`x-oss-security-token:${tokenData.security_token}`,
`x-oss-user-agent:${xOssUserAgent}`,
].join('\n') + '\n';
const canonicalRequest = [
'PUT',
canonicalUri,
'',
canonicalHeaders,
'',
'UNSIGNED-PAYLOAD',
].join('\n');
const credentialScope = `${dateScope}/${region}/oss/aliyun_v4_request`;
const stringToSign = [
'OSS4-HMAC-SHA256',
xOssDate,
credentialScope,
await sha256Hex(canonicalRequest),
].join('\n');
const kDate = await hmacSha256(new TextEncoder().encode(`aliyun_v4${tokenData.access_key_secret}`), dateScope);
const kRegion = await hmacSha256(kDate, region);
const kService = await hmacSha256(kRegion, 'oss');
const kSigning = await hmacSha256(kService, 'aliyun_v4_request');
const signature = toHex(await hmacSha256(kSigning, stringToSign));
return {
'Accept': '*/*',
'Content-Type': file.mimeType,
'authorization': `OSS4-HMAC-SHA256 Credential=${tokenData.access_key_id}/${credentialScope},Signature=${signature}`,
'x-oss-content-sha256': 'UNSIGNED-PAYLOAD',
'x-oss-date': xOssDate,
'x-oss-security-token': tokenData.security_token,
'x-oss-user-agent': xOssUserAgent,
'Referer': QWEN_WEB_REFERER,
};
}
async function uploadFileToQwenOss(file, tokenData) {
const uploadUrl = typeof tokenData.file_url === 'string' ? tokenData.file_url.split('?')[0] : '';
if (!uploadUrl) {
throw new Error('Upload failed: missing upload URL');
}
const signedHeaders = await buildOssSignedHeaders(tokenData.file_url, tokenData, file);
const resp = await fetch(uploadUrl, {
method: 'PUT',
headers: signedHeaders,
body: file.bytes,
});
if (!resp.ok) {
const detail = await resp.text().catch(() => '');
throw new Error(`Upload failed with status ${resp.status}${detail ? `: ${detail}` : ''}`);
}
}
async function parseDocumentIfNeeded(qwenFilePayload, filetype, file, baxiaTokens) {
if (filetype !== 'document') return;
const resp = await fetch(`${QWEN_BASE_URL}/api/v2/files/parse`, {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'bx-ua': baxiaTokens.bxUa,
'bx-umidtoken': baxiaTokens.bxUmidToken,
'bx-v': baxiaTokens.bxV,
'source': 'web',
'timezone': new Date().toUTCString(),
'Referer': QWEN_WEB_REFERER,
'x-request-id': uuidv4(),
},
body: JSON.stringify({ file_id: qwenFilePayload.id }),
});
const detail = await resp.text().catch(() => '');
if (!resp.ok) {
logChatDetail('core', 'attachments.parse.document.skip', {
fileId: qwenFilePayload.id,
filename: file.filename,
status: resp.status,
detail,
});
throw new Error(`Document parse failed with status ${resp.status}${detail ? `: ${detail}` : ''}`);
}
let payload = {};
try {
payload = detail ? JSON.parse(detail) : {};
} catch {}
if (payload && payload.success === false) {
logChatDetail('core', 'attachments.parse.document.skip', {
fileId: qwenFilePayload.id,
filename: file.filename,
status: resp.status,
detail,
});
throw new Error(`Document parse rejected${payload?.msg ? `: ${payload.msg}` : ''}`);
}
logChatDetail('core', 'attachments.parse.document.done', {
fileId: qwenFilePayload.id,
filename: file.filename,
});
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function ensureUploadStatusForNonVideo(filetype, baxiaTokens) {
if (filetype === 'video') return;
const maxAttempts = 6;
let lastPayload = null;
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
const resp = await fetch(`${QWEN_BASE_URL}/api/v2/users/status`, {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json',
'bx-v': baxiaTokens.bxV,
'source': 'web',
'timezone': new Date().toUTCString(),
'Referer': QWEN_WEB_REFERER,
'x-request-id': uuidv4(),
},
body: JSON.stringify({
typarms: {
typarm1: 'web',
typarm2: '',
typarm3: 'prod',
typarm4: 'qwen_chat',
typarm5: 'product',
orgid: 'tongyi',
}
}),
});
if (!resp.ok) {
const detail = await resp.text().catch(() => '');
throw new Error(`Upload status check failed with status ${resp.status}${detail ? `: ${detail}` : ''}`);
}
const payload = await resp.json().catch(() => ({}));
lastPayload = payload;
if (payload?.data === true) {
return;
}
if (attempt < maxAttempts) {
await sleep(400);
}
}
throw new Error(`Upload status not ready for non-video file${lastPayload ? `: ${JSON.stringify(lastPayload)}` : ''}`);
}
function extractUploadedFileId(fileUrl) {
try {
const pathname = decodeURIComponent(new URL(fileUrl).pathname);
const filename = pathname.split('/').pop() || '';
if (filename.includes('_')) {
return filename.split('_')[0];
}
} catch {}
return uuidv4();
}
function buildQwenFilePayload(file, tokenData, filetype) {
const now = Date.now();
const id = normalizeInputString(tokenData?.file_id) || extractUploadedFileId(tokenData.file_url);