-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
2621 lines (2246 loc) · 104 KB
/
Copy pathbackground.js
File metadata and controls
2621 lines (2246 loc) · 104 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
/**
* CVflash Background Service Worker
* 负责 AI API 调用(避免 CSP 限制)、消息路由、截图捕获
*/
import './lib/model-config.js';
const API_BASES = {
cn: 'https://open.bigmodel.cn/api/paas/v4',
global: 'https://api.z.ai/api/paas/v4',
deepseek: 'https://api.deepseek.com/v1'
};
const modelConfig = globalThis.CVFLASH_MODEL_CONFIG;
// ─── 消息路由 ─────────────────────────────────────────────────────────────────
// 填充状态管理(不依赖 popup 存活)
let fillStatus = { state: 'idle', message: '', progress: 0 };
function updateFillStatus(state, message, progress) {
fillStatus = { state, message, progress: progress || 0, timestamp: Date.now() };
// 广播状态给 popup(如果还开着的话)
chrome.runtime.sendMessage({ action: 'FILL_STATUS_UPDATE', ...fillStatus }).catch(() => {});
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
function shouldReinjectContentScript(error) {
const message = error?.message || '';
return message.includes('Receiving end does not exist') ||
message.includes('Could not establish connection') ||
message.includes('Extension context invalidated');
}
async function ensureContentScriptInjected(tabId) {
try {
await chrome.scripting.executeScript({ target: { tabId }, files: ['content.js'] });
await chrome.scripting.insertCSS({ target: { tabId }, files: ['content.css'] }).catch(() => {});
} catch (error) {
throw new Error('当前页面无法注入扩展脚本,请刷新页面后重试');
}
}
async function sendToTab(tabId, message) {
try {
return await chrome.tabs.sendMessage(tabId, message);
} catch (error) {
if (!shouldReinjectContentScript(error)) throw error;
await ensureContentScriptInjected(tabId);
return chrome.tabs.sendMessage(tabId, message);
}
}
function resolveProvider(providerId, apiBase) {
if (providerId) {
const provider = modelConfig.providers.find((item) => item.id === providerId);
if (provider) return provider;
}
return modelConfig.resolveProviderByBase(apiBase || API_BASES.cn);
}
function resolveDefaultModel(providerId, apiBase) {
return modelConfig.pickDefaultTextModel(providerId || apiBase || API_BASES.cn);
}
function normalizeAuthToken(apiKey, provider) {
if (apiKey) return apiKey;
return provider.requiresKey ? '' : 'local-token';
}
function normalizeBridgeConfig(settings = {}) {
return {
enabled: !!settings.bridgeEnabled,
url: String(settings.bridgeUrl || '').trim(),
token: String(settings.bridgeToken || '').trim(),
timeoutMs: Math.max(5000, (Number(settings.bridgeTimeoutSec) || 45) * 1000)
};
}
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
switch (msg.action) {
case 'AI_MATCH_FIELDS':
handleAIMatch(msg).then(sendResponse).catch(e => sendResponse({ error: e.message }));
return true;
case 'START_FILL': {
handleFullFill(msg).then(sendResponse).catch(e => sendResponse({ error: e.message }));
return true;
}
case 'PRE_ANALYZE': {
handlePreAnalysis(msg).then(sendResponse).catch(e => sendResponse({ error: e.message }));
return true;
}
case 'GET_FILL_STATUS':
sendResponse(fillStatus);
break;
case 'AI_CHAT':
handleAIChat(msg).then(sendResponse).catch(e => sendResponse({ error: e.message }));
return true;
case 'TEST_API':
testAPIConnection(msg.apiKey, msg.apiBase, msg.providerId).then(sendResponse).catch(e => sendResponse({ success: false, message: e.message }));
return true;
case 'TEST_BRIDGE':
testBridgeConnection(msg.bridgeUrl, msg.bridgeToken, msg.bridgeTimeoutSec).then(sendResponse).catch(e => sendResponse({ success: false, message: e.message }));
return true;
case 'PARSE_PDF_RESUME':
handleParsePDF(msg).then(sendResponse).catch(e => sendResponse({ error: e.message }));
return true;
case 'OPEN_OPTIONS':
chrome.runtime.openOptionsPage();
sendResponse({ ok: true });
break;
}
});
// ─── 完整填充流程(在 background 中运行,不受 popup 关闭影响)────────────────
async function handleFullFill({ tabId, resume, apiKey, apiBase, providerId, model, visionModel }) {
try {
const storageData = await chrome.storage.local.get('cvflash_settings');
const bridgeConfig = normalizeBridgeConfig(storageData.cvflash_settings || {});
// 1. 检测字段
updateFillStatus('detecting', '正在检测表单字段...', 10);
const detectResp = await sendToTab(tabId, { action: 'DETECT_FIELDS' });
if (!detectResp?.fields?.length) {
updateFillStatus('error', '未找到可填写的表单字段');
return { error: '未找到可填写的表单字段' };
}
const fields = detectResp.fields;
console.log(`=== 检测到 ${fields.length} 个字段 ===`);
// 2. 按分区分组字段
const sectionGroups = groupFieldsBySection(fields);
console.log('=== 表单分区信息 ===', Object.keys(sectionGroups).map(s => `${s}: ${sectionGroups[s].length}个字段`));
// 问题1提示:检测简历有多少条目 vs 表单有多少对应字段,提示用户是否需要手动添加更多条目
const missingHints = detectMissingEntries(fields, resume, sectionGroups);
if (missingHints.length > 0) {
console.warn('⚠️ 以下简历数据可能没有对应的表单字段(建议先手动添加更多条目):');
missingHints.forEach(h => console.warn(` - ${h}`));
// 通知 popup 显示提示(非阻塞)
chrome.runtime.sendMessage({ action: 'FILL_MISSING_HINT', hints: missingHints }).catch(() => {});
}
// 3. 分区块依次处理
const totalSections = Object.keys(sectionGroups).length;
let currentSection = 0;
const allFieldMap = {};
const allCommands = [];
let totalAiMatched = 0;
for (const [sectionName, sectionFields] of Object.entries(sectionGroups)) {
currentSection++;
const progress = 20 + Math.floor((currentSection / totalSections) * 50);
updateFillStatus('matching', `[${currentSection}/${totalSections}] 正在处理 ${sectionName}...`, progress);
console.log(`\n=== 处理分区: ${sectionName} (${sectionFields.length} 个字段) ===`);
// AI 完全自主决策
const aiResult = await handleAIMatch({
tabId, fields: sectionFields, resume, apiKey, apiBase, providerId, model, visionModel, bridgeConfig,
sectionContext: sectionName
});
if (aiResult.error) {
console.warn(`分区 ${sectionName} AI 匹配失败:`, aiResult.error);
continue; // 分区失败不影响其他分区
}
Object.assign(allFieldMap, aiResult.fieldMap);
allCommands.push(...(aiResult.commands || []));
totalAiMatched += Object.keys(aiResult.fieldMap || {}).length;
console.log(`✓ ${sectionName}: AI匹配 ${Object.keys(aiResult.fieldMap || {}).length} 个`);
}
const matchedCount = Object.keys(allFieldMap).length;
if (matchedCount === 0) {
updateFillStatus('error', 'AI 未能匹配任何字段');
return { error: 'AI 未能匹配任何字段' };
}
// 4. 执行填充
updateFillStatus('filling', `正在填充 ${matchedCount} 个字段...`, 75);
console.log(`\n=== 开始填充 ${matchedCount} 个字段 ===`);
const fillResp = allCommands.length
? await sendToTab(tabId, { action: 'APPLY_COMMANDS', commands: allCommands })
: await sendToTab(tabId, { action: 'AUTOFILL', fieldMap: allFieldMap });
if (fillResp?.error) {
updateFillStatus('error', '填充失败: ' + fillResp.error);
return fillResp;
}
const appliedCount = fillResp?.filledCount ?? fillResp?.appliedCount ?? 0;
// 5. 记录历史(并行读取 tab 信息和历史记录)
const [tab, histData] = await Promise.all([
chrome.tabs.get(tabId),
chrome.storage.local.get('cvflash_history')
]);
const history = histData.cvflash_history || [];
history.unshift({
url: tab.url,
title: tab.title,
resumeName: resume.name || '未命名',
filledCount: appliedCount,
timestamp: new Date().toISOString()
});
if (history.length > 50) history.length = 50;
await chrome.storage.local.set({ cvflash_history: history });
updateFillStatus('done', `已填充 ${appliedCount} 个字段(AI 匹配 ${totalAiMatched})`, 100);
console.log(`=== 填充完成: ${appliedCount}/${fields.length} 个字段 ===`);
return { fieldMap: allFieldMap, filledCount: appliedCount, totalFields: fields.length };
} catch (e) {
updateFillStatus('error', '填充失败: ' + e.message);
console.error('=== 填充流程异常 ===', e);
return { error: e.message };
}
}
// ─── 预分析:AI 对比表单 vs 简历,提示用户添加条目 ──────────────────────────
async function handlePreAnalysis({ tabId, resume, apiKey, apiBase, providerId, model }) {
// 1. 检测字段
const detectResp = await sendToTab(tabId, { action: 'DETECT_FIELDS' });
if (!detectResp?.fields?.length) return { error: '未找到表单字段', sections: [] };
const fields = detectResp.fields;
const sectionGroups = groupFieldsBySection(fields);
// 2. 构建表单结构摘要
const formSummary = [];
for (const [sectionName, sectionFields] of Object.entries(sectionGroups)) {
const groupIds = new Set(sectionFields.map(f => f.group?.id || `single_${f._domIndex}`));
const groupCount = groupIds.size > 1 ? groupIds.size : Math.max(1, Math.ceil(sectionFields.length / 3));
const fieldLabels = sectionFields.map(f => f.label || f.name || f.placeholder || '?').slice(0, 8);
formSummary.push({ name: sectionName, fieldCount: sectionFields.length, groupCount, fieldLabels });
}
// 3. 构建简历摘要(兼容嵌套结构 resume.resume.xxx 或 resume.xxx)
const r = resume.resume || resume;
// 计算各类别的数据量(personal 按非空字段数统计,其他按数组长度)
const personalFields = r.personal ? Object.values(r.personal).filter(v => v && String(v).trim()).length : 0;
const resumeCounts = {
personal: personalFields,
education: r.education?.length || 0,
experience: r.experience?.length || 0,
projects: r.projects?.length || 0,
skills: r.skills?.length || 0,
activities: r.activities?.length || 0,
research: r.research?.length || 0,
summary: r.summary ? 1 : 0
};
console.log('[预分析] resume keys:', Object.keys(resume));
console.log('[预分析] r keys:', Object.keys(r));
console.log('[预分析] r.personal:', r.personal);
console.log('[预分析] 简历数据量:', resumeCounts);
// 4. AI 分析
const base = apiBase || API_BASES.cn;
const provider = resolveProvider(providerId, base);
const authToken = normalizeAuthToken(apiKey, provider);
if (!authToken) {
// 无 API Key 时用本地对比
return { sections: localCompareFormResume(formSummary, resumeCounts), fieldCount: fields.length };
}
const defaultModel = resolveDefaultModel(provider.id, base);
const resolvedModel = resolveFieldMatchModel(provider, model || defaultModel);
const prompt = `你是招聘表单分析助手。请对比表单结构和简历数据,判断用户需要手动添加多少条目。
【表单结构】
${formSummary.map(s => `- "${s.name}": ${s.fieldCount}个字段, 约${s.groupCount}组条目, 字段包含: ${s.fieldLabels.join(', ')}`).join('\n')}
【简历数据量】
- 基本信息(personal): ${resumeCounts.personal} 个字段有值
- 个人简介/求职意向(summary): ${resumeCounts.summary ? '有' : '无'}
- 教育经历: ${resumeCounts.education} 条
- 工作/实习经历: ${resumeCounts.experience} 条
- 项目经历: ${resumeCounts.projects} 条
- 技能(skills): ${resumeCounts.skills} 条
- 校园/社团经历: ${resumeCounts.activities} 条
- 科研经历: ${resumeCounts.research} 条
【任务】
对每个表单分区,判断:
1. 该分区对应简历的哪个类别?
2. 表单有几组条目位?简历有几条数据?
3. 用户是否需要手动在网页上添加更多条目?
返回纯JSON数组(不要解释),每项格式:
{"section":"分区名","category":"personal|summary|education|experience|projects|skills|activities|research|other","formSlots":数字,"resumeEntries":数字,"gap":数字,"action":"ok|need_add|no_data","hint":"提示文字"}
gap = max(0, resumeEntries - formSlots)
action: "ok"=够用, "need_add"=需要手动添加, "no_data"=简历无此类数据`;
try {
const response = await callChatAPI(base, authToken, provider, resolvedModel, [
{ role: 'user', content: prompt }
], { temperature: 0.1, max_tokens: 2048, timeout: 30000 });
const jsonStr = extractJsonCandidate(response);
const analysis = JSON.parse(jsonStr.replace(/,\s*([}\]])/g, '$1'));
return { sections: Array.isArray(analysis) ? analysis : [], fieldCount: fields.length };
} catch (e) {
console.warn('AI 预分析失败,使用本地对比:', e.message);
return { sections: localCompareFormResume(formSummary, resumeCounts), fieldCount: fields.length };
}
}
function localCompareFormResume(formSummary, resumeCounts) {
const results = [];
const categoryMap = {
'基本': 'personal', '个人信息': 'personal', 'Basic': 'personal', 'Personal': 'personal',
'求职意向': 'summary', '自我评价': 'summary', '个人简介': 'summary', 'Summary': 'summary', 'Profile': 'summary',
'教育': 'education', 'Education': 'education',
'实习': 'experience', '工作': 'experience', 'Employment': 'experience', 'Work': 'experience',
'项目': 'projects', 'Project': 'projects',
'技能': 'skills', 'Skill': 'skills',
'校园': 'activities', '社团': 'activities', '活动': 'activities',
'科研': 'research', 'Research': 'research',
'创业': 'experience', '获奖': 'other', '作品': 'other'
};
for (const section of formSummary) {
let category = 'other';
for (const [keyword, cat] of Object.entries(categoryMap)) {
if (section.name.includes(keyword)) { category = cat; break; }
}
const resumeEntries = resumeCounts[category] || 0;
const formSlots = section.groupCount;
// personal/summary 类型不按条目数对比,只看有无数据
if (category === 'personal' || category === 'summary') {
results.push({
section: section.name, category, formSlots: section.fieldCount, resumeEntries,
gap: 0,
action: resumeEntries > 0 ? 'ok' : 'no_data',
hint: resumeEntries > 0 ? `简历有${resumeEntries}项数据` : '简历无此类数据'
});
} else {
const gap = Math.max(0, resumeEntries - formSlots);
results.push({
section: section.name, category, formSlots, resumeEntries, gap,
action: gap > 0 ? 'need_add' : (resumeEntries === 0 ? 'no_data' : 'ok'),
hint: gap > 0 ? `需要手动添加 ${gap} 条` : (resumeEntries === 0 ? '简历无此类数据' : '数量匹配')
});
}
}
return results;
}
// ─── 表单分区分组 ─────────────────────────────────────────────────────────────
function groupFieldsBySection(fields) {
const groups = {};
for (const field of fields) {
const section = field.section || '(无分区)';
if (!groups[section]) groups[section] = [];
groups[section].push(field);
}
// 对分区进行排序:基础信息优先,然后是教育、工作、项目等
const sectionOrder = {
'基本信息': 1,
'个人信息': 1,
'个人资料': 1,
'Basic Information': 1,
'教育经历': 2,
'教育背景': 2,
'Education': 2,
'实习经历': 3,
'工作经历': 4,
'Employment': 4,
'Work Experience': 4,
'项目经历': 5,
'项目经验': 5,
'Projects': 5,
'技能': 6,
'Skills': 6,
};
const sortedSections = Object.keys(groups).sort((a, b) => {
const orderA = sectionOrder[a] ?? 999;
const orderB = sectionOrder[b] ?? 999;
return orderA - orderB;
});
const result = {};
for (const section of sortedSections) {
result[section] = groups[section];
}
return result;
}
// ─── 检测简历条目 vs 表单字段的缺口 ──────────────────────────────────────────
/**
* 检测简历中有多少条目,而表单中对应分区可能字段不够
* 返回提示信息列表,让用户知道需要手动添加更多条目
*/
function detectMissingEntries(fields, resume, sectionGroups) {
const hints = [];
// 计算表单中各类分区的字段组数(每组代表一个条目)
const countGroups = (sectionKeywords) => {
let maxGroups = 0;
for (const [sectionName, sectionFields] of Object.entries(sectionGroups)) {
if (sectionKeywords.some(kw => sectionName.includes(kw))) {
// 计算该分区有多少独立的 group
const groupIds = new Set(sectionFields.map(f => f.group?.id || `single_${f._domIndex}`));
maxGroups = Math.max(maxGroups, groupIds.size > 1 ? groupIds.size : Math.ceil(sectionFields.length / 3));
}
}
return maxGroups;
};
const eduCount = resume.education?.length || 0;
const expCount = resume.experience?.length || 0;
const projCount = resume.projects?.length || 0;
const actCount = resume.activities?.length || 0;
const formEduGroups = countGroups(['教育', 'Education']);
const formExpGroups = countGroups(['工作', '实习', 'Employment', 'Work', 'Experience']);
const formProjGroups = countGroups(['项目', 'Project']);
const formActGroups = countGroups(['校园', '社团', '活动', '创业', 'Activity']);
if (eduCount > formEduGroups && formEduGroups > 0) {
hints.push(`教育经历:简历有 ${eduCount} 条,表单约 ${formEduGroups} 组字段,可能需要手动添加 ${eduCount - formEduGroups} 条`);
}
if (expCount > formExpGroups && formExpGroups > 0) {
hints.push(`工作/实习经历:简历有 ${expCount} 条,表单约 ${formExpGroups} 组字段,可能需要手动添加 ${expCount - formExpGroups} 条`);
}
if (projCount > formProjGroups && formProjGroups > 0) {
hints.push(`项目经历:简历有 ${projCount} 条,表单约 ${formProjGroups} 组字段,可能需要手动添加 ${projCount - formProjGroups} 条`);
}
if (actCount > 0 && formActGroups === 0) {
hints.push(`校园/社团/创业经历:简历有 ${actCount} 条,但表单中未找到对应分区字段`);
}
return hints;
}
// ─── 本地高置信映射 + AI/视觉补齐 ───────────────────────────────────────────
function sortResumeEntries(entries) {
return [...(entries || [])].sort((a, b) => {
const latestDiff = getEntryLatestMonth(b) - getEntryLatestMonth(a);
if (latestDiff !== 0) return latestDiff;
return getEntryStartMonth(b) - getEntryStartMonth(a);
});
}
function getEntryLatestMonth(entry) {
if (!entry) return 0;
if (entry.current) return 999912;
return parseMonthKey(entry.endDate) || parseMonthKey(entry.startDate) || 0;
}
function getEntryStartMonth(entry) {
if (!entry) return 0;
return parseMonthKey(entry.startDate) || 0;
}
function parseMonthKey(raw) {
const str = String(raw || '').trim();
const match = str.match(/(\d{4})[-/.年]?(\d{1,2})?/);
if (!match) return 0;
return Number(match[1]) * 100 + Number(match[2] || '1');
}
function normalizeResumeForFill(resume) {
const source = resume?.resume || resume || {};
return {
...source,
personal: source.personal || {},
summary: source.summary || '',
experience: sortResumeEntries(source.experience || []),
education: sortResumeEntries(source.education || []),
projects: sortResumeEntries(source.projects || []),
research: sortResumeEntries(source.research || []),
activities: sortResumeEntries(source.activities || []),
skills: Array.isArray(source.skills) ? source.skills : [],
languages: Array.isArray(source.languages) ? source.languages : [],
certifications: Array.isArray(source.certifications) ? source.certifications : [],
awards: Array.isArray(source.awards) ? source.awards : [],
hobbies: Array.isArray(source.hobbies) ? source.hobbies : [],
customSections: Array.isArray(source.customSections) ? source.customSections : []
};
}
function sortFieldsForMatching(fields) {
return [...fields].sort((a, b) => {
const yDiff = (a.bbox?.y ?? 0) - (b.bbox?.y ?? 0);
if (Math.abs(yDiff) > 6) return yDiff;
const xDiff = (a.bbox?.x ?? 0) - (b.bbox?.x ?? 0);
if (xDiff !== 0) return xDiff;
return a._domIndex - b._domIndex;
});
}
function inferSectionCategory(sectionContext, fields) {
const scores = {
personal: 0,
summary: 0,
education: 0,
experience: 0,
projects: 0,
research: 0,
activities: 0,
skills: 0,
languages: 0
};
const scoreText = (text, rules) => {
for (const [category, pattern, weight] of rules) {
if (pattern.test(text)) scores[category] += weight;
}
};
scoreText(String(sectionContext || '').toLowerCase(), [
['personal', /基本|个人|信息|profile|personal|contact/, 5],
['summary', /简介|概述|summary|objective|profile|自我评价|求职意向/, 5],
['education', /教育|学历|学校|education/, 5],
['experience', /工作|实习|职业|employment|experience|career/, 5],
['projects', /项目|project|作品/, 5],
['research', /科研|研究|research|lab/, 5],
['activities', /社团|校园|活动|志愿|student|activity/, 5],
['skills', /技能|skill|expertise/, 5],
['languages', /语言|language/, 5]
]);
for (const field of fields) {
const label = `${field.label || ''} ${field.name || ''} ${field.placeholder || ''}`.toLowerCase();
const hint = String(field.hint || '').toLowerCase();
if (['name', 'firstname', 'lastname', 'email', 'phone', 'location', 'linkedin', 'github', 'portfolio'].includes(hint)) scores.personal += 3;
if (['school', 'degree', 'major', 'gpa', 'graduation'].includes(hint)) scores.education += 3;
if (['company', 'position', 'department', 'jobstartdate', 'jobenddate', 'worktype', 'yearsexp'].includes(hint)) scores.experience += 3;
if (hint === 'skills') scores.skills += 3;
if (hint === 'languages') scores.languages += 3;
scoreText(label, [
['personal', /姓名|邮箱|电话|手机|location|地址|linkedin|github/, 2],
['summary', /自我评价|个人简介|求职意向|summary|cover/, 2],
['education', /学校|大学|学历|学位|专业|gpa|毕业/, 2],
['experience', /公司|部门|职位|岗位|工作类型|入职|离职|在职|职责|工作内容/, 2],
['projects', /项目名称|项目角色|项目描述|project/, 2],
['research', /实验室|导师|研究方向|research|advisor/, 2],
['activities', /社团|组织|活动|学生会|志愿/, 2],
['skills', /技能|skill|expertise/, 2],
['languages', /语言|english|英语|日语|德语/, 2]
]);
}
const winner = Object.entries(scores).sort((a, b) => b[1] - a[1])[0];
return winner && winner[1] > 0 ? winner[0] : 'other';
}
function splitPersonName(fullName) {
const name = String(fullName || '').trim();
if (!name) return { firstName: '', lastName: '' };
if (/[\u4e00-\u9fff]/.test(name) && name.length >= 2 && name.length <= 4) {
return { lastName: name.slice(0, 1), firstName: name.slice(1) };
}
const parts = name.split(/\s+/).filter(Boolean);
if (parts.length <= 1) return { firstName: name, lastName: '' };
return { firstName: parts.slice(0, -1).join(' '), lastName: parts.at(-1) || '' };
}
function matchesPattern(text, pattern) {
return pattern.test(String(text || '').toLowerCase());
}
function inferFieldBinding(field, sectionCategory) {
const text = `${field.label || ''} ${field.name || ''} ${field.placeholder || ''}`.toLowerCase();
const hint = String(field.hint || '').toLowerCase();
if (hint === 'name' || matchesPattern(text, /full.?name|姓名|姓名拼音/)) return { scope: 'personal', slot: 'name' };
if (hint === 'firstname' || matchesPattern(text, /first.?name|名(?!称)|given.?name/)) return { scope: 'personal', slot: 'firstName' };
if (hint === 'lastname' || matchesPattern(text, /last.?name|姓|family.?name|surname/)) return { scope: 'personal', slot: 'lastName' };
if (hint === 'email') return { scope: 'personal', slot: 'email' };
if (hint === 'phone') return { scope: 'personal', slot: 'phone' };
if (hint === 'location' || matchesPattern(text, /location|城市|地址|所在地|居住地/)) return { scope: 'personal', slot: 'location' };
if (hint === 'linkedin') return { scope: 'personal', slot: 'linkedin' };
if (hint === 'github') return { scope: 'personal', slot: 'github' };
if (hint === 'portfolio' || matchesPattern(text, /website|portfolio|个人网站|博客/)) return { scope: 'personal', slot: 'website' };
if (sectionCategory === 'summary' || matchesPattern(text, /summary|profile|自我评价|个人简介|求职意向/)) {
return { scope: 'summary', slot: 'summary' };
}
if (sectionCategory === 'skills' || hint === 'skills' || matchesPattern(text, /技能|skill|expertise/)) {
return { scope: 'skills', slot: 'list' };
}
if (sectionCategory === 'languages' || hint === 'languages' || matchesPattern(text, /语言|language|英语|日语|德语|法语/)) {
return { scope: 'languages', slot: 'list' };
}
if (sectionCategory === 'education') {
if (hint === 'school' || matchesPattern(text, /school|university|college|学校|大学|院校/)) return { scope: 'education', slot: 'school' };
if (hint === 'degree' || matchesPattern(text, /degree|学历|学位|education.?level/)) return { scope: 'education', slot: 'degree' };
if (hint === 'major' || matchesPattern(text, /major|专业|field.?of.?study|discipline/)) return { scope: 'education', slot: 'major' };
if (hint === 'gpa' || matchesPattern(text, /gpa|绩点|成绩/)) return { scope: 'education', slot: 'gpa' };
if (hint === 'currentflag' || matchesPattern(text, /至今|在读|current|present|ongoing/)) return { scope: 'education', slot: 'current' };
if (hint === 'startdate' || matchesPattern(text, /start|from|开始|入学/)) return { scope: 'education', slot: 'startDate' };
if (hint === 'graduation' || hint === 'jobenddate' || matchesPattern(text, /graduat|end|to|毕业|结束/)) return { scope: 'education', slot: 'endDate' };
if (hint === 'description' || matchesPattern(text, /课程|补充信息|描述|说明/)) return { scope: 'education', slot: 'description' };
}
if (sectionCategory === 'experience') {
if (hint === 'company' || matchesPattern(text, /company|employer|organization|公司|单位|雇主/)) return { scope: 'experience', slot: 'company' };
if (hint === 'department' || matchesPattern(text, /department|部门/)) return { scope: 'experience', slot: 'department' };
if (hint === 'position' || matchesPattern(text, /position|job.?title|岗位|职位|职务|role/)) return { scope: 'experience', slot: 'position' };
if (hint === 'worktype' || matchesPattern(text, /work.?type|employment.?type|job.?type|全职|兼职|实习/)) return { scope: 'experience', slot: 'workType' };
if (hint === 'currentflag' || matchesPattern(text, /至今|在职|current|present|ongoing/)) return { scope: 'experience', slot: 'current' };
if (hint === 'jobstartdate' || hint === 'startdate' || matchesPattern(text, /start|from|开始|入职|任职/)) return { scope: 'experience', slot: 'startDate' };
if (hint === 'jobenddate' || matchesPattern(text, /end|to|until|结束|离职|在职/)) return { scope: 'experience', slot: 'endDate' };
if (hint === 'description' || matchesPattern(text, /description|responsibilit|duties|工作内容|职责|经历描述|工作描述/)) return { scope: 'experience', slot: 'description' };
}
if (sectionCategory === 'projects') {
if (matchesPattern(text, /project.?name|项目名称|项目名|课题名称|名称/)) return { scope: 'projects', slot: 'name' };
if (hint === 'position' || matchesPattern(text, /role|职责|角色|担任/)) return { scope: 'projects', slot: 'role' };
if (hint === 'currentflag' || matchesPattern(text, /至今|当前|current|present|ongoing/)) return { scope: 'projects', slot: 'current' };
if (hint === 'startdate' || matchesPattern(text, /start|from|开始/)) return { scope: 'projects', slot: 'startDate' };
if (hint === 'jobenddate' || matchesPattern(text, /end|to|结束/)) return { scope: 'projects', slot: 'endDate' };
if (hint === 'description' || matchesPattern(text, /description|项目描述|介绍|内容/)) return { scope: 'projects', slot: 'description' };
if (hint === 'portfolio' || matchesPattern(text, /url|link|链接|网址|仓库/)) return { scope: 'projects', slot: 'url' };
}
if (sectionCategory === 'research') {
if (matchesPattern(text, /institution|lab|实验室|研究机构|大学|院系/)) return { scope: 'research', slot: 'institution' };
if (hint === 'position' || matchesPattern(text, /role|角色|职务|身份/)) return { scope: 'research', slot: 'role' };
if (matchesPattern(text, /advisor|导师|pi/)) return { scope: 'research', slot: 'advisor' };
if (hint === 'currentflag' || matchesPattern(text, /至今|当前|current|present|ongoing/)) return { scope: 'research', slot: 'current' };
if (hint === 'startdate' || matchesPattern(text, /start|from|开始/)) return { scope: 'research', slot: 'startDate' };
if (hint === 'jobenddate' || matchesPattern(text, /end|to|结束/)) return { scope: 'research', slot: 'endDate' };
if (hint === 'description' || matchesPattern(text, /research|研究内容|描述|方向/)) return { scope: 'research', slot: 'description' };
}
if (sectionCategory === 'activities') {
if (matchesPattern(text, /organization|社团|组织|学生会|协会|活动单位/)) return { scope: 'activities', slot: 'organization' };
if (hint === 'position' || matchesPattern(text, /role|角色|职务|岗位/)) return { scope: 'activities', slot: 'role' };
if (hint === 'currentflag' || matchesPattern(text, /至今|当前|current|present|ongoing/)) return { scope: 'activities', slot: 'current' };
if (hint === 'startdate' || matchesPattern(text, /start|from|开始/)) return { scope: 'activities', slot: 'startDate' };
if (hint === 'jobenddate' || matchesPattern(text, /end|to|结束/)) return { scope: 'activities', slot: 'endDate' };
if (hint === 'description' || matchesPattern(text, /活动内容|描述|经历|工作内容/)) return { scope: 'activities', slot: 'description' };
}
return null;
}
function buildLocalFieldMap(fields, resume, sectionContext = '') {
const sectionCategory = inferSectionCategory(sectionContext, fields);
const result = {};
for (const group of buildSectionEntryGroups(fields, sectionCategory)) {
for (const field of group.fields) {
const binding = inferFieldBinding(field, sectionCategory);
if (!binding) continue;
const entryIndex = isRepeatableSectionCategory(binding.scope) ? group.index : 0;
const rawValue = getBindingValue(binding, resume, field, entryIndex);
const normalizedValue = normalizeValueForField(rawValue, field, binding);
if (normalizedValue == null) continue;
result[field._domIndex] = normalizedValue;
}
}
return result;
}
function getBindingValue(binding, resume, field, entryIndex) {
if (binding.scope === 'personal') {
const personal = resume.personal || {};
if (binding.slot === 'firstName') return splitPersonName(personal.name).firstName;
if (binding.slot === 'lastName') return splitPersonName(personal.name).lastName;
return personal[binding.slot] ?? '';
}
if (binding.scope === 'summary') {
return resume.summary || '';
}
if (binding.scope === 'skills') {
return joinListForField(resume.skills || [], field);
}
if (binding.scope === 'languages') {
return joinListForField(resume.languages || [], field);
}
const entries = Array.isArray(resume[binding.scope]) ? resume[binding.scope] : [];
const entry = entries[entryIndex];
if (!entry) return '';
if (binding.scope === 'experience' && binding.slot === 'company') {
return entry.company || entry.employer || entry.organization || '';
}
if (binding.scope === 'experience' && binding.slot === 'department') {
return entry.department || entry.team || entry.businessUnit || '';
}
if (binding.scope === 'experience' && binding.slot === 'position') {
return entry.position || entry.role || entry.title || entry.jobTitle || '';
}
if (binding.scope === 'experience' && binding.slot === 'workType') {
return entry.workType || inferEmploymentType(entry, field);
}
if (binding.slot === 'current') {
return !!entry.current;
}
if (binding.scope === 'experience' && binding.slot === 'endDate') {
return entry.current ? '' : (entry.endDate || '');
}
if (binding.scope === 'education' && binding.slot === 'endDate') {
return entry.endDate || '';
}
if (binding.scope === 'projects' && binding.slot === 'role') {
return entry.role || entry.position || entry.title || '';
}
return entry[binding.slot] ?? '';
}
function joinListForField(items, field) {
const values = (items || []).map(item => String(item || '').trim()).filter(Boolean);
if (!values.length) return '';
return field.type === 'textarea' || field.type === 'contenteditable'
? values.join('\n')
: values.join(', ');
}
function inferEmploymentType(entry, field) {
const desired = entry?.isInternship || /实习|intern/i.test(`${entry?.position || ''} ${entry?.company || ''}`)
? '实习'
: '全职';
return field.options?.length ? pickBestOption(field.options, desired) : desired;
}
function normalizeValueForField(value, field, binding = null) {
if (value == null) return null;
if (field.type === 'checkbox') {
if (typeof value === 'boolean') return value;
const str = String(value).trim().toLowerCase();
if (!str) return false;
return ['true', '1', 'yes', 'checked', '至今', '当前', 'current', 'present'].includes(str);
}
if (typeof value === 'string' && !value.trim()) return '';
let normalized = String(value).trim();
const hint = String(field.hint || '').toLowerCase();
const label = `${field.label || ''} ${field.name || ''}`.toLowerCase();
if (binding?.slot?.toLowerCase().includes('date') || field.type === 'date' || field.type === 'month' || /日期|时间|from|to|start|end|毕业|入学|在职/.test(label)) {
normalized = normalizeMonthValue(normalized);
}
if (hint === 'phone' || /电话|手机|tel|phone/.test(label)) {
normalized = normalized.replace(/[^\d+]/g, '');
}
if (hint === 'email') {
normalized = normalized.toLowerCase();
}
if (field.options?.length) {
normalized = pickBestOption(field.options, normalized);
}
return normalized;
}
function normalizeMonthValue(value) {
const str = String(value || '').trim();
if (!str) return '';
if (/^\d{4}-\d{2}$/.test(str) || /^\d{4}-\d{2}-\d{2}$/.test(str)) return str;
const match = str.match(/(\d{4})[./年-](\d{1,2})/);
if (match) return `${match[1]}-${String(match[2]).padStart(2, '0')}`;
if (/^\d{4}$/.test(str)) return `${str}-01`;
return str;
}
function pickBestOption(options, desiredValue) {
const desired = String(desiredValue || '').trim();
if (!desired) return '';
const normalize = (text) => String(text || '').replace(/[\s\-_.,()()【】/]/g, '').toLowerCase();
const desiredNorm = normalize(desired);
const candidates = options.map(option => String(option || '').trim()).filter(Boolean);
const exact = candidates.find(option => option === desired);
if (exact) return exact;
const lowered = desired.toLowerCase();
const contains = candidates.find(option => option.toLowerCase() === lowered || option.toLowerCase().includes(lowered) || lowered.includes(option.toLowerCase()));
if (contains) return contains;
const normalizedMatch = candidates.find(option => normalize(option) === desiredNorm || normalize(option).includes(desiredNorm) || desiredNorm.includes(normalize(option)));
if (normalizedMatch) return normalizedMatch;
const synonymMap = [
[['实习', 'internship', 'intern'], /实习|intern/],
[['全职', 'fulltime', 'full-time'], /全职|full.?time|正式/],
[['兼职', 'parttime', 'part-time'], /兼职|part.?time/],
[['本科', 'bachelor', '学士'], /本科|学士|bachelor/],
[['硕士', 'master'], /硕士|master|msc|ma/],
[['博士', 'phd', 'doctor'], /博士|phd|doctor/]
];
for (const [keywords, pattern] of synonymMap) {
if (!pattern.test(desired.toLowerCase())) continue;
const synonym = candidates.find(option => keywords.some(keyword => normalize(option).includes(normalize(keyword))));
if (synonym) return synonym;
}
return desired;
}
function isSelectLikeField(field) {
return field?.tagName === 'SELECT'
|| field?.type === 'aria-combobox'
|| !!field?.options?.length;
}
function buildCommandForField(field, value) {
if (value == null) return null;
if (value === '') {
return { action: 'clear', domIndex: field._domIndex };
}
if (field.type === 'checkbox') {
return { action: 'toggle', domIndex: field._domIndex, value: Boolean(value) };
}
if (isSelectLikeField(field)) {
return { action: 'select', domIndex: field._domIndex, value: String(value) };
}
return { action: 'set', domIndex: field._domIndex, value: String(value) };
}
function fieldMapToCommands(fieldMap, fields) {
return Object.entries(fieldMap || {})
.map(([domIndex, value]) => {
const field = fields.find(item => item._domIndex === Number(domIndex));
if (!field) return null;
return buildCommandForField(field, value);
})
.filter(Boolean);
}
function isRepeatableSectionCategory(sectionCategory) {
return ['education', 'experience', 'projects', 'research', 'activities'].includes(sectionCategory);
}
function buildSectionEntryGroups(fields, sectionCategory) {
const sortedFields = sortFieldsForMatching(fields);
if (!sortedFields.length) return [];
if (!isRepeatableSectionCategory(sectionCategory)) {
return [{ key: 'single', index: 0, fields: sortedFields }];
}
const explicitGroups = new Map();
for (const field of sortedFields) {
const key = field.group?.id || '';
if (!key) continue;
if (!explicitGroups.has(key)) explicitGroups.set(key, []);
explicitGroups.get(key).push(field);
}
const meaningfulGroups = [...explicitGroups.entries()]
.filter(([, groupFields]) => groupFields.length >= 2)
.sort((a, b) => getGroupTop(a[1]) - getGroupTop(b[1]));
if (meaningfulGroups.length >= 2) {
return meaningfulGroups.map(([key, groupFields], index) => ({
key,
index,
fields: sortFieldsForMatching(groupFields)
}));
}
return [{ key: 'single', index: 0, fields: sortedFields }];
}
function getGroupTop(fields) {
return Math.min(...fields.map(field => field.bbox?.y ?? 0));
}
// ─── AI 字段匹配(纯文本模式)────────────────────────────────────────────────
async function handleAIMatch({ tabId, fields, resume, apiKey, apiBase, providerId, model, visionModel, bridgeConfig, sectionContext = '' }) {
const base = apiBase || API_BASES.cn;
const provider = resolveProvider(providerId, base);
const normalizedResume = normalizeResumeForFill(resume);
const resumeSummary = buildResumeSummary(normalizedResume);
let fieldMap = buildLocalFieldMap(fields, normalizedResume, sectionContext);
let commands = fieldMapToCommands(fieldMap, fields);
console.log('=== 开始 AI 字段匹配 ===');
console.log(`分区: ${sectionContext || '全表单'}`);
console.log(`字段数量: ${fields.length}`);
console.log(`API 端点: ${base}`);
console.log(`供应商: ${provider.label}`);
console.log(`使用模型: ${model || 'default'}`);
let unresolvedFields = fields.filter(field => fieldMap[field._domIndex] == null);
if (!unresolvedFields.length) {
return { fieldMap, commands };
}
if (bridgeConfig?.enabled && bridgeConfig.url) {
try {
updateFillStatus('matching', `正在通过 Bridge 处理 ${sectionContext || '当前分区'}...`, 46);
const bridgeResult = await callBridgeAPI({
tabId,
bridgeConfig,
fields: unresolvedFields,
allFields: fields,
resume: normalizedResume,
sectionContext,
existingFieldMap: fieldMap,
includeScreenshot: !!visionModel
});
const bridgeCommands = parseBridgeCommands(bridgeResult, unresolvedFields, normalizedResume);
if (bridgeCommands.length) {
const bridgeMap = commandsToFieldMap(bridgeCommands, unresolvedFields);
fieldMap = { ...fieldMap, ...bridgeMap };
commands.push(...bridgeCommands);
unresolvedFields = fields.filter(field => fieldMap[field._domIndex] == null);
if (!unresolvedFields.length) {
return { fieldMap, commands: dedupeCommands(commands) };
}
}
} catch (error) {
console.warn('Bridge 调用失败,回退内置模型链路:', error.message);
}
}
updateFillStatus('matching', `正在补齐 ${sectionContext || '当前分区'} 的剩余 ${unresolvedFields.length} 个字段...`, 48);
const structuredPrompt = buildStructuredFieldPrompt(unresolvedFields);
const authToken = normalizeAuthToken(apiKey, provider);
if (!authToken) {
throw new Error('Bridge 未返回有效命令,且未配置 API Key,无法继续使用内置模型链路');
}
// 纯文本模式:仅发送结构化字段数据(AI 完全自主决策,不受本地规则干扰)
const messages = [{
role: 'user',
content: buildCommandFillPrompt(structuredPrompt, resumeSummary, fields, sectionContext, fieldMap)
}];
console.log('准备调用 API...');
const defaultModel = resolveDefaultModel(provider.id, base);
const resolvedModel = resolveFieldMatchModel(provider, model || defaultModel);
const requestOpts = {
temperature: 0.25,
max_tokens: 4096,
timeout: 90000,
response_format: buildJsonResponseFormat(provider, base)
};
// 智能降级:先尝试完整 prompt,超时后降级到简化 prompt
let response;
try {
response = await callChatAPI(base, authToken, provider, resolvedModel, messages, requestOpts);
} catch (error) {
// 检查是否是超时错误
if (error.message.includes('超时') || error.message.includes('timeout')) {
console.warn('⚠️ API 超时,降级到简化 prompt...');
updateFillStatus('matching', '响应较慢,正在重试简化模式...', 50);
// 降级:使用简化 prompt(完全依赖 AI,不传递本地规则)
const simplifiedPrompt = buildSimplifiedCommandPrompt(unresolvedFields, resumeSummary, fieldMap, fields);
const simplifiedMessages = [{
role: 'user',
content: simplifiedPrompt
}];
response = await callChatAPI(base, authToken, provider, resolvedModel, simplifiedMessages, {