@reconcrap/boss-recommend-mcp 1.2.2 → 1.2.4

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/src/pipeline.js CHANGED
@@ -1,1432 +1,1432 @@
1
- import path from "node:path";
2
- import { parseRecommendInstruction } from "./parser.js";
3
- import {
4
- attemptPipelineAutoRepair,
5
- ensureBossRecommendPageReady,
6
- ensureFeaturedCalibrationReady,
7
- listRecommendJobs,
8
- readRecommendTabState,
9
- refreshBossRecommendList,
10
- reloadBossRecommendPage,
11
- runPipelinePreflight,
12
- runRecommendSearchCli,
13
- runRecommendScreenCli,
14
- switchRecommendTab
15
- } from "./adapters.js";
16
-
17
- const FORCED_RECENT_NOT_VIEW_ON_SCREEN_RECOVERY = "近14天没有";
18
- const MAX_SCREEN_AUTO_RECOVERY_ATTEMPTS = 5;
19
- const PAGE_SCOPE_TO_TAB_STATUS = {
20
- recommend: "0",
21
- latest: "1",
22
- featured: "3"
23
- };
24
- const TAB_STATUS_TO_PAGE_SCOPE = {
25
- "0": "recommend",
26
- "1": "latest",
27
- "3": "featured"
28
- };
29
- const PAGE_SCOPE_LABELS = {
30
- recommend: "推荐",
31
- latest: "最新",
32
- featured: "精选"
33
- };
34
-
35
- function dedupe(values = []) {
36
- return [...new Set(values.filter(Boolean))];
37
- }
38
-
39
- function normalizeText(value) {
40
- return String(value || "").replace(/\s+/g, " ").trim();
41
- }
42
-
43
- function normalizePageScope(value) {
44
- const normalized = normalizeText(value).toLowerCase();
45
- if (!normalized) return null;
46
- if (["recommend", "推荐", "推荐页", "推荐页面"].includes(normalized)) return "recommend";
47
- if (["latest", "最新", "最新页", "最新页面"].includes(normalized)) return "latest";
48
- if (["featured", "精选", "精选页", "精选页面", "精选牛人"].includes(normalized)) return "featured";
49
- return null;
50
- }
51
-
52
- function resolvePipelinePageScope(parsed, confirmation, overrides) {
53
- const parsedResolved = normalizePageScope(parsed?.page_scope);
54
- if (parsedResolved) return parsedResolved;
55
- const fromConfirmation = normalizePageScope(confirmation?.page_value);
56
- if (fromConfirmation) return fromConfirmation;
57
- return "recommend";
58
- }
59
-
60
- function pageScopeToTabStatus(scope) {
61
- return PAGE_SCOPE_TO_TAB_STATUS[scope] || "0";
62
- }
63
-
64
- function tabStatusToPageScope(status) {
65
- return TAB_STATUS_TO_PAGE_SCOPE[String(status || "")] || "recommend";
66
- }
67
-
68
- function normalizeJobTitle(value) {
69
- const text = normalizeText(value);
70
- if (!text) return "";
71
- const byGap = text.split(/\s{2,}/).map((item) => item.trim()).filter(Boolean)[0] || text;
72
- const strippedRange = byGap
73
- .replace(/\s+\d+(?:\.\d+)?\s*(?:-|~|—|至)\s*\d+(?:\.\d+)?\s*(?:k|K|千|万|元\/天|元\/月|元\/年|K\/月|k\/月|万\/月|万\/年)?$/u, "")
74
- .trim();
75
- const strippedSingle = strippedRange
76
- .replace(/\s+\d+(?:\.\d+)?\s*(?:k|K|千|万|元\/天|元\/月|元\/年|K\/月|k\/月|万\/月|万\/年)$/u, "")
77
- .trim();
78
- return strippedSingle || byGap;
79
- }
80
-
81
- function normalizeJobOptions(jobOptions = []) {
82
- const normalized = [];
83
- const seen = new Set();
84
- for (const item of jobOptions) {
85
- if (!item || typeof item !== "object") continue;
86
- const value = normalizeText(item.value);
87
- const label = normalizeText(item.label);
88
- const title = normalizeJobTitle(item.title || label);
89
- const optionKey = value || title || label;
90
- if (!optionKey || seen.has(optionKey)) continue;
91
- seen.add(optionKey);
92
- normalized.push({
93
- value: value || null,
94
- title: title || label || null,
95
- label: label || title || null,
96
- current: item.current === true
97
- });
98
- }
99
- return normalized;
100
- }
101
-
102
- function resolveSelectedJob(jobOptions = [], requestedRaw) {
103
- const requested = normalizeText(requestedRaw);
104
- if (!requested) {
105
- return { job: null, ambiguous: false, candidates: [] };
106
- }
107
- const requestedTitle = normalizeJobTitle(requested).toLowerCase();
108
- const requestedLower = requested.toLowerCase();
109
- const byValue = jobOptions.find((item) => normalizeText(item.value || "").toLowerCase() === requestedLower);
110
- if (byValue) return { job: byValue, ambiguous: false, candidates: [] };
111
- const byTitle = jobOptions.find((item) => normalizeJobTitle(item.title || "").toLowerCase() === requestedTitle);
112
- if (byTitle) return { job: byTitle, ambiguous: false, candidates: [] };
113
- const byLabel = jobOptions.find((item) => normalizeText(item.label || "").toLowerCase() === requestedLower);
114
- if (byLabel) return { job: byLabel, ambiguous: false, candidates: [] };
115
- const partialMatches = jobOptions.filter((item) => {
116
- const title = normalizeJobTitle(item.title || "").toLowerCase();
117
- const label = normalizeText(item.label || "").toLowerCase();
118
- return (
119
- (title && (title.includes(requestedTitle) || requestedTitle.includes(title)))
120
- || (label && (label.includes(requestedLower) || requestedLower.includes(label)))
121
- );
122
- });
123
- if (partialMatches.length === 1) {
124
- return { job: partialMatches[0], ambiguous: false, candidates: [] };
125
- }
126
- if (partialMatches.length > 1) {
127
- return {
128
- job: null,
129
- ambiguous: true,
130
- candidates: partialMatches.map((item) => item.title || item.label || "").filter(Boolean)
131
- };
132
- }
133
- return { job: null, ambiguous: false, candidates: [] };
134
- }
135
-
136
- function buildJobPendingQuestion(jobOptions = [], selectedHint = null, reason = null) {
137
- const options = jobOptions.map((item) => ({
138
- label: item.title || item.label || item.value,
139
- value: item.value || item.title || item.label
140
- }));
141
- return {
142
- field: "job",
143
- question: reason
144
- || "已识别当前推荐页岗位列表,请确认本次要执行的岗位。确认后会先点击该岗位,再开始 search 和 screen。",
145
- value: normalizeText(selectedHint) || null,
146
- options
147
- };
148
- }
149
-
150
- function failedCheckSet(checks = []) {
151
- const failed = checks
152
- .filter((item) => item && item.ok === false && typeof item.key === "string")
153
- .map((item) => item.key);
154
- return new Set(failed);
155
- }
156
-
157
- function collectNpmInstallDirs(checks = [], workspaceRoot) {
158
- const npmCheckKeys = new Set([
159
- "npm_dep_chrome_remote_interface_search",
160
- "npm_dep_chrome_remote_interface_screen",
161
- "npm_dep_ws",
162
- "npm_dep_sharp"
163
- ]);
164
- const dirs = checks
165
- .filter((item) => item && item.ok === false && npmCheckKeys.has(item.key))
166
- .map((item) => item.install_cwd)
167
- .filter((value) => typeof value === "string" && value.trim());
168
- if (dirs.length > 0) return dedupe(dirs);
169
- return workspaceRoot ? [workspaceRoot] : [];
170
- }
171
-
172
- function quoteForCommand(value) {
173
- return JSON.stringify(String(value));
174
- }
175
-
176
- function buildNpmInstallCommands(checks = [], workspaceRoot) {
177
- const dirs = collectNpmInstallDirs(checks, workspaceRoot);
178
- const commands = [];
179
- for (const dir of dirs) {
180
- commands.push(`npm install --prefix ${quoteForCommand(dir)}`);
181
- }
182
- return commands;
183
- }
184
-
185
- function getNodeInstallCommands() {
186
- if (process.platform === "win32") {
187
- return [
188
- "winget install OpenJS.NodeJS.LTS",
189
- "node --version"
190
- ];
191
- }
192
- if (process.platform === "darwin") {
193
- return [
194
- "brew install node",
195
- "node --version"
196
- ];
197
- }
198
- return [
199
- "使用系统包管理器安装 Node.js >= 18(例如 apt / yum / brew)",
200
- "node --version"
201
- ];
202
- }
203
-
204
- function formatCommandBlock(commands = []) {
205
- return commands.map((command) => `- ${command}`).join("\n");
206
- }
207
-
208
- function buildPreflightRecovery(checks = [], workspaceRoot) {
209
- const failed = failedCheckSet(checks);
210
- if (failed.size === 0) return null;
211
-
212
- const needScreenConfig = failed.has("screen_config");
213
- const needNode = failed.has("node_cli");
214
- const needNpm = (
215
- failed.has("npm_dep_chrome_remote_interface_search")
216
- || failed.has("npm_dep_chrome_remote_interface_screen")
217
- || failed.has("npm_dep_ws")
218
- || failed.has("npm_dep_sharp")
219
- );
220
-
221
- const ordered_steps = [];
222
- if (needScreenConfig) {
223
- const configCheck = checks.find((item) => item?.key === "screen_config");
224
- ordered_steps.push({
225
- id: "fill_screening_config",
226
- title: "填写 screening-config.json(baseUrl / apiKey / model)",
227
- blocked_by: [],
228
- commands: [
229
- `打开并填写:${configCheck?.path || "~/.boss-recommend-mcp/screening-config.json"}`,
230
- "确认 baseUrl、apiKey、model 都是可用值(不要保留模板占位符)。"
231
- ]
232
- });
233
- }
234
- if (needNode) {
235
- ordered_steps.push({
236
- id: "install_nodejs",
237
- title: "安装 Node.js >= 18",
238
- blocked_by: [],
239
- commands: getNodeInstallCommands()
240
- });
241
- }
242
- if (needNpm) {
243
- ordered_steps.push({
244
- id: "install_npm_dependencies",
245
- title: "安装 npm 依赖(chrome-remote-interface / ws / sharp)",
246
- blocked_by: needNode ? ["install_nodejs"] : [],
247
- commands: buildNpmInstallCommands(checks, workspaceRoot)
248
- });
249
- }
250
-
251
- const promptLines = [
252
- "你是环境修复 agent。请先读取 diagnostics.checks,再严格按下面顺序执行,不要并行跳步:",
253
- "1) node_cli 失败 -> 先安装 Node.js,未成功前禁止执行 npm install。",
254
- "2) npm_dep_* 失败 -> 再安装 npm 依赖(chrome-remote-interface / ws / sharp)。",
255
- "每一步完成后都重新运行 doctor,直到所有检查通过后再重试流水线。"
256
- ];
257
- if (needScreenConfig) {
258
- promptLines.splice(
259
- 1,
260
- 0,
261
- "0) 若 screen_config 失败:先让用户提供并填写 baseUrl、apiKey、model(不得使用模板占位符)。"
262
- );
263
- }
264
-
265
- if (needNpm) {
266
- const npmCommands = buildNpmInstallCommands(checks, workspaceRoot);
267
- if (npmCommands.length > 0) {
268
- promptLines.push("建议执行的 npm 命令:");
269
- promptLines.push(formatCommandBlock(npmCommands));
270
- }
271
- }
272
-
273
- return {
274
- failed_check_keys: [...failed],
275
- ordered_steps,
276
- agent_prompt: promptLines.join("\n")
277
- };
278
- }
279
-
280
- function buildRequiredConfirmations(parsedResult) {
281
- const confirmations = [];
282
- if (parsedResult.needs_page_confirmation) confirmations.push("page_scope");
283
- if (parsedResult.needs_filters_confirmation) confirmations.push("filters");
284
- if (parsedResult.needs_school_tag_confirmation) confirmations.push("school_tag");
285
- if (parsedResult.needs_degree_confirmation) confirmations.push("degree");
286
- if (parsedResult.needs_gender_confirmation) confirmations.push("gender");
287
- if (parsedResult.needs_recent_not_view_confirmation) confirmations.push("recent_not_view");
288
- if (parsedResult.needs_criteria_confirmation) confirmations.push("criteria");
289
- if (parsedResult.needs_target_count_confirmation) confirmations.push("target_count");
290
- if (parsedResult.needs_post_action_confirmation) confirmations.push("post_action");
291
- if (parsedResult.needs_max_greet_count_confirmation) confirmations.push("max_greet_count");
292
- return confirmations;
293
- }
294
-
295
- function buildNeedInputResponse(parsedResult) {
296
- return {
297
- status: "NEED_INPUT",
298
- missing_fields: parsedResult.missing_fields,
299
- required_confirmations: buildRequiredConfirmations(parsedResult),
300
- selected_page: parsedResult.proposed_page_scope || parsedResult.page_scope || "recommend",
301
- search_params: parsedResult.searchParams,
302
- screen_params: parsedResult.screenParams,
303
- pending_questions: parsedResult.pending_questions,
304
- review: parsedResult.review,
305
- error: {
306
- code: "MISSING_REQUIRED_FIELDS",
307
- message: "缺少必要的筛选 criteria,请先补充或通过 overrides.criteria 明确传入。",
308
- retryable: true
309
- }
310
- };
311
- }
312
-
313
- function buildNeedConfirmationResponse(parsedResult) {
314
- return {
315
- status: "NEED_CONFIRMATION",
316
- required_confirmations: buildRequiredConfirmations(parsedResult),
317
- selected_page: parsedResult.proposed_page_scope || parsedResult.page_scope || "recommend",
318
- search_params: parsedResult.searchParams,
319
- screen_params: {
320
- ...parsedResult.screenParams,
321
- target_count: parsedResult.proposed_target_count ?? parsedResult.screenParams.target_count,
322
- post_action: parsedResult.proposed_post_action || parsedResult.screenParams.post_action,
323
- max_greet_count: parsedResult.proposed_max_greet_count || parsedResult.screenParams.max_greet_count
324
- },
325
- pending_questions: parsedResult.pending_questions,
326
- review: parsedResult.review
327
- };
328
- }
329
-
330
- function buildFinalReviewQuestion({ searchParams, screenParams, selectedJob, selectedPage }) {
331
- return {
332
- field: "final_review",
333
- question: "开始执行搜索和筛选前,请最后确认全部参数(岗位/页面/筛选条件/筛选 criteria/目标人数/post_action/max_greet_count)无误。",
334
- value: {
335
- job: selectedJob?.title || selectedJob?.label || selectedJob?.value || null,
336
- page_scope: selectedPage || "recommend",
337
- search_params: searchParams,
338
- screen_params: screenParams
339
- }
340
- };
341
- }
342
-
343
- function buildFailedResponse(code, message, extra = {}) {
344
- return {
345
- status: "FAILED",
346
- error: {
347
- code,
348
- message,
349
- retryable: true
350
- },
351
- ...extra
352
- };
353
- }
354
-
355
- function buildPausedResponse(message, extra = {}) {
356
- return {
357
- status: "PAUSED",
358
- message: normalizeText(message || "") || "Recommend 流水线已暂停。",
359
- ...extra
360
- };
361
- }
362
-
363
- class PipelineAbortError extends Error {
364
- constructor(message = "Pipeline execution aborted") {
365
- super(message);
366
- this.name = "PipelineAbortError";
367
- this.code = "PIPELINE_ABORTED";
368
- }
369
- }
370
-
371
- function isAbortSignalTriggered(signal) {
372
- return Boolean(signal && signal.aborted);
373
- }
374
-
375
- function ensurePipelineNotAborted(signal) {
376
- if (isAbortSignalTriggered(signal)) {
377
- throw new PipelineAbortError("Pipeline execution aborted by caller.");
378
- }
379
- }
380
-
381
- function safeInvokeRuntimeCallback(callback, payload) {
382
- if (typeof callback !== "function") return;
383
- try {
384
- callback(payload);
385
- } catch {
386
- // Keep pipeline stable even if runtime callback fails.
387
- }
388
- }
389
-
390
- function createPipelineRuntime(runtime = null) {
391
- const signal = runtime?.signal;
392
- const heartbeatIntervalMs = Number.isFinite(runtime?.heartbeatIntervalMs) && runtime.heartbeatIntervalMs > 0
393
- ? runtime.heartbeatIntervalMs
394
- : 10_000;
395
- const isPauseRequested = typeof runtime?.isPauseRequested === "function"
396
- ? runtime.isPauseRequested
397
- : () => false;
398
-
399
- function setStage(stage, message = null) {
400
- safeInvokeRuntimeCallback(runtime?.onStage, {
401
- stage,
402
- message: normalizeText(message || "") || null,
403
- at: new Date().toISOString()
404
- });
405
- }
406
-
407
- function heartbeat(stage, details = null) {
408
- safeInvokeRuntimeCallback(runtime?.onHeartbeat, {
409
- stage,
410
- details: details || null,
411
- at: new Date().toISOString()
412
- });
413
- }
414
-
415
- function output(stage, event) {
416
- safeInvokeRuntimeCallback(runtime?.onOutput, {
417
- stage,
418
- ...(event || {}),
419
- at: new Date().toISOString()
420
- });
421
- }
422
-
423
- function progress(stage, payload) {
424
- safeInvokeRuntimeCallback(runtime?.onProgress, {
425
- stage,
426
- ...(payload || {}),
427
- at: new Date().toISOString()
428
- });
429
- }
430
-
431
- function adapterRuntime(stage) {
432
- return {
433
- signal,
434
- heartbeatIntervalMs,
435
- onOutput: (event) => output(stage, event),
436
- onHeartbeat: (event) => heartbeat(stage, event),
437
- onProgress: (payload) => progress(stage, payload)
438
- };
439
- }
440
-
441
- return {
442
- signal,
443
- heartbeatIntervalMs,
444
- isPauseRequested,
445
- setStage,
446
- heartbeat,
447
- output,
448
- progress,
449
- adapterRuntime
450
- };
451
- }
452
-
453
- function isProcessAbortError(errorLike) {
454
- const code = normalizeText(errorLike?.code || "").toUpperCase();
455
- return code === "PROCESS_ABORTED" || code === "ABORTED";
456
- }
457
-
458
- function isPauseRequested(runtimeHooks) {
459
- try {
460
- return runtimeHooks?.isPauseRequested?.() === true;
461
- } catch {
462
- return false;
463
- }
464
- }
465
-
466
- function buildChromeSetupGuidance({ debugPort, pageState }) {
467
- const expectedUrl = pageState?.expected_url || "https://www.zhipin.com/web/chat/recommend";
468
- const loginUrl = pageState?.login_url || "https://www.zhipin.com/web/user/?ka=bticket";
469
- const currentUrl = pageState?.current_url || null;
470
- const state = pageState?.state || "UNKNOWN";
471
- const isPortIssue = state === "DEBUG_PORT_UNREACHABLE";
472
- const needsLogin = state === "LOGIN_REQUIRED" || state === "LOGIN_REQUIRED_AFTER_REDIRECT";
473
- const launchAttempt = pageState?.launch_attempt || null;
474
- const launchLine = launchAttempt?.ok
475
- ? `已自动启动 Chrome(--remote-debugging-port=${debugPort},--user-data-dir=${launchAttempt.user_data_dir || "auto"})。`
476
- : null;
477
- const launchExample = process.platform === "win32"
478
- ? `chrome.exe --remote-debugging-port=${debugPort} --user-data-dir=<profile-dir>`
479
- : process.platform === "darwin"
480
- ? `'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' --remote-debugging-port=${debugPort} --user-data-dir=<profile-dir>`
481
- : `google-chrome --remote-debugging-port=${debugPort} --user-data-dir=<profile-dir>`;
482
- const steps = [
483
- `请先在可连接到 DevTools 端口 ${debugPort} 的 Chrome 实例中完成以下操作:`,
484
- ...(launchLine ? [launchLine] : []),
485
- "1) 确认当前 Chrome 与本次运行使用同一个远程调试端口。",
486
- isPortIssue
487
- ? `2) 若端口不可连接,请用远程调试方式启动 Chrome(示例:${launchExample})。`
488
- : "2) 确认端口可连接且浏览器窗口保持打开。",
489
- needsLogin
490
- ? `3) 当前检测到 Boss 未登录,请先打开并完成登录:${loginUrl}`
491
- : "3) 如 Boss 登录态失效,请先重新登录。",
492
- `4) 登录完成后先导航并停留在推荐页:${expectedUrl}`,
493
- "5) 完成后回复“已就绪”,我会继续执行并优先自动导航到推荐页。"
494
- ];
495
- return {
496
- debug_port: debugPort,
497
- expected_url: expectedUrl,
498
- current_url: currentUrl,
499
- page_state: state,
500
- agent_prompt: steps.join("\n")
501
- };
502
- }
503
-
504
- const defaultDependencies = {
505
- attemptPipelineAutoRepair,
506
- parseRecommendInstruction,
507
- ensureBossRecommendPageReady,
508
- ensureFeaturedCalibrationReady,
509
- listRecommendJobs,
510
- readRecommendTabState,
511
- refreshBossRecommendList,
512
- reloadBossRecommendPage,
513
- runPipelinePreflight,
514
- runRecommendSearchCli,
515
- runRecommendScreenCli,
516
- switchRecommendTab
517
- };
518
-
519
- export async function runRecommendPipeline(
520
- { workspaceRoot, instruction, confirmation, overrides, resume = null },
521
- dependencies = defaultDependencies,
522
- runtime = null
523
- ) {
524
- const injectedDependencies = dependencies || {};
525
- const resolvedDependencies = { ...defaultDependencies, ...(dependencies || {}) };
526
- const {
527
- attemptPipelineAutoRepair: attemptAutoRepair,
528
- parseRecommendInstruction: parseInstruction,
529
- ensureBossRecommendPageReady: ensureRecommendPageReady,
530
- ensureFeaturedCalibrationReady: ensureCalibrationReady,
531
- listRecommendJobs: listJobs,
532
- readRecommendTabState: readTabState,
533
- refreshBossRecommendList: refreshRecommendList,
534
- reloadBossRecommendPage: reloadRecommendPage,
535
- runPipelinePreflight: runPreflight,
536
- runRecommendSearchCli: searchCli,
537
- runRecommendScreenCli: screenCli,
538
- switchRecommendTab: switchTab
539
- } = resolvedDependencies;
540
- const runtimeHooks = createPipelineRuntime(runtime);
541
- ensurePipelineNotAborted(runtimeHooks.signal);
542
-
543
- const startedAt = Date.now();
544
- const parsed = parseInstruction({ instruction, confirmation, overrides });
545
- const selectedPage = resolvePipelinePageScope(parsed, confirmation, overrides);
546
-
547
- if (parsed.missing_fields.length > 0) {
548
- return buildNeedInputResponse(parsed);
549
- }
550
-
551
- if (
552
- parsed.needs_page_confirmation
553
- || parsed.needs_filters_confirmation
554
- || parsed.needs_school_tag_confirmation
555
- || parsed.needs_degree_confirmation
556
- || parsed.needs_gender_confirmation
557
- || parsed.needs_recent_not_view_confirmation
558
- || parsed.needs_criteria_confirmation
559
- || parsed.needs_target_count_confirmation
560
- || parsed.needs_post_action_confirmation
561
- || parsed.needs_max_greet_count_confirmation
562
- ) {
563
- return buildNeedConfirmationResponse(parsed);
564
- }
565
-
566
- ensurePipelineNotAborted(runtimeHooks.signal);
567
- runtimeHooks.setStage("preflight", "开始执行 preflight 检查。");
568
- runtimeHooks.heartbeat("preflight");
569
-
570
- let preflight = runPreflight(workspaceRoot, { pageScope: selectedPage });
571
- let autoRepair = null;
572
- const shouldAttemptAutoRepair = (
573
- dependencies === defaultDependencies
574
- || Object.prototype.hasOwnProperty.call(injectedDependencies, "attemptPipelineAutoRepair")
575
- );
576
- if (!preflight.ok) {
577
- if (shouldAttemptAutoRepair && typeof attemptAutoRepair === "function") {
578
- autoRepair = attemptAutoRepair(workspaceRoot, preflight);
579
- if (autoRepair?.preflight) {
580
- preflight = autoRepair.preflight;
581
- }
582
- }
583
- }
584
-
585
- const shouldCheckFeaturedCalibration = (
586
- dependencies === defaultDependencies
587
- || Object.prototype.hasOwnProperty.call(injectedDependencies, "ensureFeaturedCalibrationReady")
588
- );
589
- const featuredCalibrationCheck = preflight.checks?.find((item) => item?.key === "favorite_calibration");
590
- if (
591
- selectedPage === "featured"
592
- && shouldCheckFeaturedCalibration
593
- && featuredCalibrationCheck
594
- && featuredCalibrationCheck.ok === false
595
- ) {
596
- runtimeHooks.setStage("calibration", "检测到精选页缺少可用收藏校准文件,开始自动执行校准。");
597
- runtimeHooks.heartbeat("calibration");
598
- const calibrationResult = await ensureCalibrationReady(workspaceRoot, {
599
- port: preflight.debug_port,
600
- timeoutMs: 60000,
601
- autoCalibrate: true,
602
- runtime: runtimeHooks.adapterRuntime("calibration")
603
- });
604
- ensurePipelineNotAborted(runtimeHooks.signal);
605
- if (!calibrationResult?.ok) {
606
- return buildFailedResponse(
607
- "CALIBRATION_REQUIRED",
608
- calibrationResult?.error?.message || "精选页收藏校准失败,请先完成校准后重试。",
609
- {
610
- selected_page: selectedPage,
611
- search_params: parsed.searchParams,
612
- screen_params: parsed.screenParams,
613
- required_user_action: "run_featured_calibration",
614
- guidance: {
615
- calibration_path: calibrationResult?.calibration_path || featuredCalibrationCheck.path || null,
616
- debug_port: calibrationResult?.debug_port || preflight.debug_port,
617
- calibration_script_path: calibrationResult?.calibration_script_path || null,
618
- tip: "请在 Boss 推荐页切换到精选 tab 后打开候选人详情,按提示先收藏再取消收藏完成校准后重试。"
619
- },
620
- diagnostics: {
621
- checks: preflight.checks,
622
- calibration: calibrationResult || null
623
- }
624
- }
625
- );
626
- }
627
- preflight = runPreflight(workspaceRoot, { pageScope: selectedPage });
628
- }
629
-
630
- if (!preflight.ok) {
631
- runtimeHooks.heartbeat("preflight", {
632
- status: "failed"
633
- });
634
- const screenConfigCheck = preflight.checks?.find((item) => item?.key === "screen_config" && item?.ok === false);
635
- const screenConfigPath = String(screenConfigCheck?.path || "");
636
- const screenConfigDir = screenConfigPath ? path.dirname(screenConfigPath) : null;
637
- const screenConfigReason = String(screenConfigCheck?.reason || "").trim().toUpperCase();
638
- const screenConfigMessage = String(screenConfigCheck?.message || "");
639
- const screenConfigHasPlaceholder = (
640
- screenConfigReason.includes("PLACEHOLDER")
641
- || /占位符|默认模板值|replace-with-openai-api-key/i.test(screenConfigMessage)
642
- );
643
- const recovery = buildPreflightRecovery(preflight.checks, workspaceRoot);
644
- return buildFailedResponse(
645
- "PIPELINE_PREFLIGHT_FAILED",
646
- "Recommend 流水线运行前检查失败,请先修复缺失的本地依赖或配置文件。",
647
- {
648
- search_params: parsed.searchParams,
649
- screen_params: parsed.screenParams,
650
- required_user_action: screenConfigCheck
651
- ? (screenConfigHasPlaceholder ? "confirm_screening_config_updated" : "provide_screening_config")
652
- : undefined,
653
- guidance: screenConfigCheck
654
- ? {
655
- config_path: screenConfigCheck.path,
656
- config_dir: screenConfigDir,
657
- agent_prompt: [
658
- ...(screenConfigHasPlaceholder
659
- ? [
660
- "检测到 screening-config.json 仍包含默认占位词,当前禁止继续执行。",
661
- `请引导用户在以下目录修改配置文件:${screenConfigDir || "(unknown)"}`,
662
- `配置文件路径:${screenConfigCheck.path}`,
663
- "必须替换为真实可用值:baseUrl、apiKey、model(不要保留任何模板占位符)。",
664
- "修改完成后,必须先让用户明确回复“已修改完成”,再继续下一步。"
665
- ]
666
- : [
667
- "请先让用户填写 screening-config.json 的以下字段:",
668
- "1) baseUrl",
669
- "2) apiKey",
670
- "3) model",
671
- `配置文件路径:${screenConfigCheck.path}`,
672
- "注意:不要使用模板占位符(例如 replace-with-openai-api-key),也不要由 agent 自行猜测或代填示例值。必须向用户逐项确认真实可用值后再重试。"
673
- ])
674
- ].join("\n")
675
- }
676
- : undefined,
677
- diagnostics: {
678
- checks: preflight.checks,
679
- debug_port: preflight.debug_port,
680
- config_resolution: preflight.config_resolution,
681
- auto_repair: autoRepair,
682
- recovery
683
- }
684
- }
685
- );
686
- }
687
-
688
- ensurePipelineNotAborted(runtimeHooks.signal);
689
- runtimeHooks.setStage("page_ready", "preflight 完成,开始检查 recommend 页面就绪状态。");
690
- runtimeHooks.heartbeat("page_ready");
691
-
692
- const pageCheck = await ensureRecommendPageReady(workspaceRoot, {
693
- port: preflight.debug_port
694
- });
695
- ensurePipelineNotAborted(runtimeHooks.signal);
696
- if (!pageCheck.ok) {
697
- const loginRelated = new Set(["LOGIN_REQUIRED", "LOGIN_REQUIRED_AFTER_REDIRECT"]);
698
- const connectivityRelated = new Set(["DEBUG_PORT_UNREACHABLE"]);
699
- const guidance = buildChromeSetupGuidance({
700
- debugPort: preflight.debug_port,
701
- pageState: pageCheck.page_state
702
- });
703
- return buildFailedResponse(
704
- connectivityRelated.has(pageCheck.state)
705
- ? "BOSS_CHROME_NOT_CONNECTED"
706
- : loginRelated.has(pageCheck.state)
707
- ? "BOSS_LOGIN_REQUIRED"
708
- : "BOSS_RECOMMEND_PAGE_NOT_READY",
709
- loginRelated.has(pageCheck.state)
710
- ? `开始执行搜索和筛选前,请先在端口 ${preflight.debug_port} 的 Chrome 完成 Boss 登录并停留在 recommend 页面。`
711
- : connectivityRelated.has(pageCheck.state)
712
- ? `开始执行搜索和筛选前,需要先连接到端口 ${preflight.debug_port} 的 Chrome 远程调试实例。`
713
- : `开始执行搜索和筛选前,请先在端口 ${preflight.debug_port} 的 Chrome 停留在 Boss recommend 页面。`,
714
- {
715
- search_params: parsed.searchParams,
716
- screen_params: parsed.screenParams,
717
- required_user_action: "prepare_boss_recommend_page",
718
- guidance,
719
- diagnostics: {
720
- debug_port: preflight.debug_port,
721
- page_state: pageCheck.page_state
722
- }
723
- }
724
- );
725
- }
726
-
727
- runtimeHooks.setStage("job_list", "页面就绪,开始读取岗位列表。");
728
- runtimeHooks.heartbeat("job_list");
729
- const jobListResult = await listJobs({
730
- workspaceRoot,
731
- port: preflight.debug_port,
732
- runtime: runtimeHooks.adapterRuntime("job_list")
733
- });
734
- ensurePipelineNotAborted(runtimeHooks.signal);
735
- if (isProcessAbortError(jobListResult.error)) {
736
- throw new PipelineAbortError(jobListResult.error?.message || "岗位列表读取已取消。");
737
- }
738
- if (!jobListResult.ok) {
739
- const jobListErrorCode = String(jobListResult.error?.code || "");
740
- const jobListErrorMessage = String(jobListResult.error?.message || "");
741
- const pageReadinessFailure = (
742
- jobListErrorCode === "JOB_TRIGGER_NOT_FOUND"
743
- || jobListErrorCode === "NO_RECOMMEND_IFRAME"
744
- || jobListErrorCode === "LOGIN_REQUIRED"
745
- || jobListErrorMessage.includes("JOB_TRIGGER_NOT_FOUND")
746
- || jobListErrorMessage.includes("NO_RECOMMEND_IFRAME")
747
- || jobListErrorMessage.includes("LOGIN_REQUIRED")
748
- );
749
- if (pageReadinessFailure) {
750
- const recheck = await ensureRecommendPageReady(workspaceRoot, {
751
- port: preflight.debug_port
752
- });
753
- const loginRelated = new Set(["LOGIN_REQUIRED", "LOGIN_REQUIRED_AFTER_REDIRECT"]);
754
- const connectivityRelated = new Set(["DEBUG_PORT_UNREACHABLE"]);
755
- const guidance = buildChromeSetupGuidance({
756
- debugPort: preflight.debug_port,
757
- pageState: recheck.page_state
758
- });
759
- if (!recheck.ok || loginRelated.has(recheck.state) || connectivityRelated.has(recheck.state)) {
760
- return buildFailedResponse(
761
- connectivityRelated.has(recheck.state)
762
- ? "BOSS_CHROME_NOT_CONNECTED"
763
- : loginRelated.has(recheck.state)
764
- ? "BOSS_LOGIN_REQUIRED"
765
- : "BOSS_RECOMMEND_PAGE_NOT_READY",
766
- loginRelated.has(recheck.state)
767
- ? `检测到当前 Boss 处于未登录状态,请先登录后再继续。登录页:https://www.zhipin.com/web/user/?ka=bticket`
768
- : connectivityRelated.has(recheck.state)
769
- ? `读取岗位列表前需要先连接到端口 ${preflight.debug_port} 的 Chrome 远程调试实例。`
770
- : `读取岗位列表前,请先在端口 ${preflight.debug_port} 的 Chrome 停留在 Boss recommend 页面。`,
771
- {
772
- search_params: parsed.searchParams,
773
- screen_params: parsed.screenParams,
774
- required_user_action: "prepare_boss_recommend_page",
775
- guidance,
776
- diagnostics: {
777
- debug_port: preflight.debug_port,
778
- page_state: recheck.page_state,
779
- stdout: jobListResult.stdout?.slice(-1000),
780
- stderr: jobListResult.stderr?.slice(-1000),
781
- result: jobListResult.structured || null
782
- }
783
- }
784
- );
785
- }
786
- }
787
- return buildFailedResponse(
788
- jobListResult.error?.code || "RECOMMEND_JOB_LIST_FAILED",
789
- jobListResult.error?.message || "读取推荐岗位列表失败,无法开始筛选。",
790
- {
791
- search_params: parsed.searchParams,
792
- screen_params: parsed.screenParams,
793
- diagnostics: {
794
- debug_port: preflight.debug_port,
795
- stdout: jobListResult.stdout?.slice(-1000),
796
- stderr: jobListResult.stderr?.slice(-1000),
797
- result: jobListResult.structured || null
798
- }
799
- }
800
- );
801
- }
802
- const jobOptions = normalizeJobOptions(jobListResult.jobs);
803
- if (jobOptions.length === 0) {
804
- return buildFailedResponse(
805
- "RECOMMEND_JOB_LIST_EMPTY",
806
- "未识别到可选岗位,暂时无法开始筛选。",
807
- {
808
- search_params: parsed.searchParams,
809
- screen_params: parsed.screenParams,
810
- diagnostics: {
811
- debug_port: preflight.debug_port,
812
- result: jobListResult.structured || null
813
- }
814
- }
815
- );
816
- }
817
-
818
- const selectedJobHint = normalizeText(confirmation?.job_value || parsed.job_selection_hint || "");
819
- const selectedJobResolution = resolveSelectedJob(jobOptions, selectedJobHint);
820
- const jobConfirmed = confirmation?.job_confirmed === true;
821
- const selectedTabStatus = pageScopeToTabStatus(selectedPage);
822
- if (!jobConfirmed || !selectedJobResolution.job) {
823
- const reason = selectedJobResolution.ambiguous
824
- ? `你提供的岗位“${selectedJobHint}”匹配到多个选项:${selectedJobResolution.candidates.join(" / ")}。请明确选择其中一个岗位。`
825
- : selectedJobHint
826
- ? `未在当前岗位列表中找到“${selectedJobHint}”,请从以下岗位中重新确认一个。`
827
- : "已识别当前推荐页岗位列表,请先确认本次要执行的岗位;确认后会先点击该岗位,再开始 search 和 screen。";
828
- const pendingQuestions = (parsed.pending_questions || []).filter((item) => item?.field !== "job");
829
- pendingQuestions.push(buildJobPendingQuestion(jobOptions, selectedJobHint, reason));
830
- const requiredConfirmations = dedupe([...buildRequiredConfirmations(parsed), "job"]);
831
- return {
832
- status: "NEED_CONFIRMATION",
833
- required_confirmations: requiredConfirmations,
834
- selected_page: selectedPage,
835
- search_params: parsed.searchParams,
836
- screen_params: {
837
- ...parsed.screenParams,
838
- target_count: parsed.proposed_target_count ?? parsed.screenParams.target_count,
839
- post_action: parsed.proposed_post_action || parsed.screenParams.post_action,
840
- max_greet_count: parsed.proposed_max_greet_count || parsed.screenParams.max_greet_count
841
- },
842
- pending_questions: pendingQuestions,
843
- review: parsed.review,
844
- job_options: jobOptions
845
- };
846
- }
847
- const selectedJob = selectedJobResolution.job;
848
- const selectedJobToken = selectedJob.value || selectedJob.title || selectedJob.label;
849
- if (confirmation?.final_confirmed !== true) {
850
- const pendingQuestions = (parsed.pending_questions || []).filter((item) => item?.field !== "final_review");
851
- pendingQuestions.push(buildFinalReviewQuestion({
852
- searchParams: parsed.searchParams,
853
- screenParams: {
854
- ...parsed.screenParams,
855
- target_count: parsed.proposed_target_count ?? parsed.screenParams.target_count,
856
- post_action: parsed.proposed_post_action || parsed.screenParams.post_action,
857
- max_greet_count: parsed.proposed_max_greet_count || parsed.screenParams.max_greet_count
858
- },
859
- selectedJob,
860
- selectedPage
861
- }));
862
- return {
863
- status: "NEED_CONFIRMATION",
864
- required_confirmations: dedupe([...buildRequiredConfirmations(parsed), "final_review"]),
865
- selected_page: selectedPage,
866
- search_params: parsed.searchParams,
867
- screen_params: {
868
- ...parsed.screenParams,
869
- target_count: parsed.proposed_target_count ?? parsed.screenParams.target_count,
870
- post_action: parsed.proposed_post_action || parsed.screenParams.post_action,
871
- max_greet_count: parsed.proposed_max_greet_count || parsed.screenParams.max_greet_count
872
- },
873
- selected_job: selectedJob,
874
- pending_questions: pendingQuestions,
875
- review: parsed.review,
876
- job_options: jobOptions
877
- };
878
- }
879
-
880
- const resumeCompletionReason = normalizeText(resume?.previous_completion_reason || "").toLowerCase();
881
- const isResumeRun = resume?.resume === true;
882
- const resumeFromPausedBeforeScreen = isResumeRun && resumeCompletionReason === "paused_before_screen";
883
- const skipSearchOnResume = isResumeRun && !resumeFromPausedBeforeScreen;
884
- let effectiveSearchParams = { ...parsed.searchParams };
885
- let searchSummary = null;
886
- let shouldRunSearch = !skipSearchOnResume;
887
- let screenAutoRecoveryCount = 0;
888
- let lastAutoRecovery = null;
889
- let activeTabStatus = null;
890
- let currentResumeConfig = {
891
- checkpoint_path: resume?.checkpoint_path || null,
892
- pause_control_path: resume?.pause_control_path || null,
893
- output_csv: resume?.output_csv || null,
894
- resume: resume?.resume === true,
895
- require_checkpoint: skipSearchOnResume
896
- };
897
-
898
- const ensureSelectedPageTab = async () => {
899
- if (selectedPage === "recommend") {
900
- activeTabStatus = selectedTabStatus;
901
- return {
902
- ok: true,
903
- switched: false,
904
- before_state: null,
905
- after_state: null
906
- };
907
- }
908
- const expectedStatus = selectedTabStatus;
909
- let beforeState = null;
910
- if (typeof readTabState === "function") {
911
- beforeState = await readTabState(workspaceRoot, { port: preflight.debug_port });
912
- if (beforeState?.ok && normalizeText(beforeState.active_status)) {
913
- activeTabStatus = normalizeText(beforeState.active_status);
914
- }
915
- }
916
- if (String(activeTabStatus || "") === String(expectedStatus)) {
917
- return {
918
- ok: true,
919
- switched: false,
920
- before_state: beforeState || null,
921
- after_state: beforeState || null
922
- };
923
- }
924
- if (typeof switchTab !== "function") {
925
- return {
926
- ok: false,
927
- error: {
928
- code: "RECOMMEND_TAB_SWITCH_ADAPTER_MISSING",
929
- message: "缺少 recommend tab 切换适配器。"
930
- },
931
- before_state: beforeState || null,
932
- after_state: null
933
- };
934
- }
935
- const switchResult = await switchTab(workspaceRoot, {
936
- port: preflight.debug_port,
937
- target_status: expectedStatus
938
- });
939
- if (!switchResult?.ok) {
940
- return {
941
- ok: false,
942
- error: {
943
- code: switchResult?.state || "RECOMMEND_TAB_SWITCH_FAILED",
944
- message: switchResult?.message || `切换到${PAGE_SCOPE_LABELS[selectedPage]} tab 失败。`
945
- },
946
- before_state: beforeState || null,
947
- after_state: switchResult?.tab_state || null
948
- };
949
- }
950
- activeTabStatus = normalizeText(switchResult.active_status || switchResult.tab_state?.active_status || expectedStatus);
951
- return {
952
- ok: true,
953
- switched: true,
954
- before_state: beforeState || null,
955
- after_state: switchResult.tab_state || null
956
- };
957
- };
958
-
959
- while (true) {
960
- if (shouldRunSearch) {
961
- ensurePipelineNotAborted(runtimeHooks.signal);
962
- runtimeHooks.setStage(
963
- "search",
964
- screenAutoRecoveryCount > 0
965
- ? `自动恢复第 ${screenAutoRecoveryCount} 次:重新执行 recommend search(强制 recent_not_view=${FORCED_RECENT_NOT_VIEW_ON_SCREEN_RECOVERY})。`
966
- : "岗位已确认,开始执行 recommend search。"
967
- );
968
- runtimeHooks.heartbeat("search", lastAutoRecovery);
969
- const searchResult = await searchCli({
970
- workspaceRoot,
971
- searchParams: effectiveSearchParams,
972
- selectedJob: selectedJobToken,
973
- pageScope: selectedPage,
974
- runtime: runtimeHooks.adapterRuntime("search")
975
- });
976
- ensurePipelineNotAborted(runtimeHooks.signal);
977
- if (isProcessAbortError(searchResult.error)) {
978
- throw new PipelineAbortError(searchResult.error?.message || "推荐筛选已取消。");
979
- }
980
- if (!searchResult.ok) {
981
- const searchErrorCode = String(searchResult.error?.code || "");
982
- const searchErrorMessage = String(searchResult.error?.message || "");
983
- const loginRelatedSearchFailure = (
984
- searchErrorCode === "LOGIN_REQUIRED"
985
- || searchErrorCode === "NO_RECOMMEND_IFRAME"
986
- || searchErrorMessage.includes("LOGIN_REQUIRED")
987
- || searchErrorMessage.includes("NO_RECOMMEND_IFRAME")
988
- );
989
- if (loginRelatedSearchFailure) {
990
- const recheck = await ensureRecommendPageReady(workspaceRoot, {
991
- port: preflight.debug_port
992
- });
993
- if (recheck.state === "LOGIN_REQUIRED" || recheck.state === "LOGIN_REQUIRED_AFTER_REDIRECT") {
994
- const guidance = buildChromeSetupGuidance({
995
- debugPort: preflight.debug_port,
996
- pageState: recheck.page_state
997
- });
998
- return buildFailedResponse(
999
- "BOSS_LOGIN_REQUIRED",
1000
- "检测到当前 Boss 处于未登录状态,请先登录后再继续。登录页:https://www.zhipin.com/web/user/?ka=bticket",
1001
- {
1002
- search_params: effectiveSearchParams,
1003
- screen_params: parsed.screenParams,
1004
- selected_job: selectedJob,
1005
- required_user_action: "prepare_boss_recommend_page",
1006
- guidance,
1007
- diagnostics: {
1008
- debug_port: preflight.debug_port,
1009
- page_state: recheck.page_state,
1010
- stdout: searchResult.stdout?.slice(-1000),
1011
- stderr: searchResult.stderr?.slice(-1000),
1012
- result: searchResult.structured || null,
1013
- auto_recovery: lastAutoRecovery
1014
- }
1015
- }
1016
- );
1017
- }
1018
- }
1019
- return buildFailedResponse(
1020
- searchResult.error?.code || "RECOMMEND_SEARCH_FAILED",
1021
- searchResult.error?.message || "推荐页筛选执行失败。",
1022
- {
1023
- search_params: effectiveSearchParams,
1024
- screen_params: parsed.screenParams,
1025
- selected_job: selectedJob,
1026
- diagnostics: {
1027
- debug_port: preflight.debug_port,
1028
- stdout: searchResult.stdout?.slice(-1000),
1029
- stderr: searchResult.stderr?.slice(-1000),
1030
- result: searchResult.structured || null,
1031
- auto_recovery: lastAutoRecovery
1032
- }
1033
- }
1034
- );
1035
- }
1036
-
1037
- searchSummary = searchResult.summary || {};
1038
- if (isPauseRequested(runtimeHooks)) {
1039
- return buildPausedResponse("已在 screen 阶段开始前暂停 Recommend 流水线。", {
1040
- selected_page: selectedPage,
1041
- active_tab_status: activeTabStatus || null,
1042
- search_params: effectiveSearchParams,
1043
- screen_params: parsed.screenParams,
1044
- selected_job: selectedJob,
1045
- partial_result: {
1046
- candidate_count: searchSummary.candidate_count ?? null,
1047
- applied_filters: searchSummary.applied_filters || effectiveSearchParams,
1048
- output_csv: currentResumeConfig.output_csv || null,
1049
- completion_reason: "paused_before_screen"
1050
- }
1051
- });
1052
- }
1053
- const tabSwitchResult = await ensureSelectedPageTab();
1054
- if (!tabSwitchResult.ok) {
1055
- return buildFailedResponse(
1056
- tabSwitchResult.error?.code || "RECOMMEND_TAB_SWITCH_FAILED",
1057
- tabSwitchResult.error?.message || `切换到${PAGE_SCOPE_LABELS[selectedPage]} tab 失败。`,
1058
- {
1059
- selected_page: selectedPage,
1060
- active_tab_status: activeTabStatus || null,
1061
- search_params: effectiveSearchParams,
1062
- screen_params: parsed.screenParams,
1063
- selected_job: selectedJob,
1064
- required_user_action: "retry_switch_recommend_tab",
1065
- guidance: {
1066
- expected_tab_status: selectedTabStatus,
1067
- expected_page_scope: selectedPage,
1068
- expected_page_label: PAGE_SCOPE_LABELS[selectedPage]
1069
- },
1070
- diagnostics: {
1071
- debug_port: preflight.debug_port,
1072
- tab_switch: tabSwitchResult
1073
- }
1074
- }
1075
- );
1076
- }
1077
- ensurePipelineNotAborted(runtimeHooks.signal);
1078
- runtimeHooks.setStage(
1079
- "screen",
1080
- selectedPage !== "recommend"
1081
- ? `search 完成,已切换到${PAGE_SCOPE_LABELS[selectedPage]} tab,开始执行 recommend screen。`
1082
- : "search 完成,开始执行 recommend screen。"
1083
- );
1084
- } else {
1085
- const tabSwitchResult = await ensureSelectedPageTab();
1086
- if (!tabSwitchResult.ok) {
1087
- return buildFailedResponse(
1088
- tabSwitchResult.error?.code || "RECOMMEND_TAB_SWITCH_FAILED",
1089
- tabSwitchResult.error?.message || `切换到${PAGE_SCOPE_LABELS[selectedPage]} tab 失败。`,
1090
- {
1091
- selected_page: selectedPage,
1092
- active_tab_status: activeTabStatus || null,
1093
- search_params: effectiveSearchParams,
1094
- screen_params: parsed.screenParams,
1095
- selected_job: selectedJob,
1096
- required_user_action: "retry_switch_recommend_tab",
1097
- guidance: {
1098
- expected_tab_status: selectedTabStatus,
1099
- expected_page_scope: selectedPage,
1100
- expected_page_label: PAGE_SCOPE_LABELS[selectedPage]
1101
- },
1102
- diagnostics: {
1103
- debug_port: preflight.debug_port,
1104
- tab_switch: tabSwitchResult
1105
- }
1106
- }
1107
- );
1108
- }
1109
- ensurePipelineNotAborted(runtimeHooks.signal);
1110
- runtimeHooks.setStage("screen", "检测到可续跑 checkpoint,跳过 search,直接恢复 recommend screen。");
1111
- }
1112
-
1113
- runtimeHooks.heartbeat("screen", lastAutoRecovery);
1114
- const screenResult = await screenCli({
1115
- workspaceRoot,
1116
- screenParams: parsed.screenParams,
1117
- pageScope: selectedPage,
1118
- resume: currentResumeConfig,
1119
- runtime: runtimeHooks.adapterRuntime("screen")
1120
- });
1121
- ensurePipelineNotAborted(runtimeHooks.signal);
1122
- if (isProcessAbortError(screenResult.error)) {
1123
- throw new PipelineAbortError(screenResult.error?.message || "推荐筛选已取消。");
1124
- }
1125
- if (screenResult.paused) {
1126
- return buildPausedResponse("Recommend 流水线已暂停,可使用 resume 继续。", {
1127
- selected_page: selectedPage,
1128
- active_tab_status: activeTabStatus || null,
1129
- search_params: effectiveSearchParams,
1130
- screen_params: parsed.screenParams,
1131
- selected_job: selectedJob,
1132
- partial_result: screenResult.summary || screenResult.structured?.result || null
1133
- });
1134
- }
1135
- if (!screenResult.ok) {
1136
- const screenErrorCode = String(screenResult.error?.code || "");
1137
- const partialScreenResult = screenResult.summary || screenResult.structured?.result || null;
1138
- const resumeOutputCsv = normalizeText(partialScreenResult?.output_csv || currentResumeConfig.output_csv || "");
1139
- const hasCheckpointForRecovery = Boolean(normalizeText(currentResumeConfig.checkpoint_path || ""));
1140
- const screenPartialForRecovery = partialScreenResult
1141
- ? {
1142
- processed_count: partialScreenResult.processed_count ?? null,
1143
- passed_count: partialScreenResult.passed_count ?? null,
1144
- skipped_count: partialScreenResult.skipped_count ?? null,
1145
- output_csv: partialScreenResult.output_csv || currentResumeConfig.output_csv || null,
1146
- checkpoint_path: partialScreenResult.checkpoint_path || currentResumeConfig.checkpoint_path || null,
1147
- completion_reason: partialScreenResult.completion_reason || null
1148
- }
1149
- : null;
1150
- const isResumeCaptureRecovery = screenErrorCode === "RESUME_CAPTURE_FAILED_CONSECUTIVE_LIMIT";
1151
- const isPageExhaustedRecovery = screenErrorCode === "TARGET_COUNT_NOT_REACHED_PAGE_EXHAUSTED";
1152
- const isRecoverableScreenFailure = isResumeCaptureRecovery || isPageExhaustedRecovery;
1153
- const canRecoverSafely = hasCheckpointForRecovery && Boolean(resumeOutputCsv);
1154
- const hasRecoveryAttemptsRemaining = screenAutoRecoveryCount < MAX_SCREEN_AUTO_RECOVERY_ATTEMPTS;
1155
-
1156
- if (isRecoverableScreenFailure && !canRecoverSafely) {
1157
- return buildFailedResponse(
1158
- "SCREEN_AUTO_RECOVERY_UNSAFE",
1159
- "检测到 recommend 自动恢复触发,但缺少 checkpoint 或 output_csv,无法安全续跑。",
1160
- {
1161
- search_params: effectiveSearchParams,
1162
- screen_params: parsed.screenParams,
1163
- selected_job: selectedJob,
1164
- partial_result: partialScreenResult,
1165
- diagnostics: {
1166
- debug_port: preflight.debug_port,
1167
- stdout: screenResult.stdout?.slice(-1000),
1168
- stderr: screenResult.stderr?.slice(-1000),
1169
- result: screenResult.structured || null,
1170
- auto_recovery: {
1171
- trigger: screenErrorCode,
1172
- attempt: screenAutoRecoveryCount,
1173
- max_attempts: MAX_SCREEN_AUTO_RECOVERY_ATTEMPTS,
1174
- original_recent_not_view: parsed.searchParams.recent_not_view,
1175
- effective_recent_not_view: effectiveSearchParams.recent_not_view,
1176
- partial_result: screenPartialForRecovery
1177
- }
1178
- }
1179
- }
1180
- );
1181
- }
1182
-
1183
- if (isRecoverableScreenFailure && !hasRecoveryAttemptsRemaining) {
1184
- return buildFailedResponse(
1185
- screenResult.error?.code || "RECOMMEND_SCREEN_FAILED",
1186
- `${screenResult.error?.message || "推荐页筛选执行失败。"} 已达到自动恢复上限 ${MAX_SCREEN_AUTO_RECOVERY_ATTEMPTS} 次。`,
1187
- {
1188
- search_params: effectiveSearchParams,
1189
- screen_params: parsed.screenParams,
1190
- selected_job: selectedJob,
1191
- partial_result: partialScreenResult,
1192
- diagnostics: {
1193
- debug_port: preflight.debug_port,
1194
- stdout: screenResult.stdout?.slice(-1000),
1195
- stderr: screenResult.stderr?.slice(-1000),
1196
- result: screenResult.structured || null,
1197
- auto_recovery: lastAutoRecovery
1198
- }
1199
- }
1200
- );
1201
- }
1202
-
1203
- if (isRecoverableScreenFailure && canRecoverSafely && hasRecoveryAttemptsRemaining) {
1204
- screenAutoRecoveryCount += 1;
1205
- lastAutoRecovery = {
1206
- trigger: screenErrorCode,
1207
- attempt: screenAutoRecoveryCount,
1208
- max_attempts: MAX_SCREEN_AUTO_RECOVERY_ATTEMPTS,
1209
- original_recent_not_view: parsed.searchParams.recent_not_view,
1210
- effective_recent_not_view: effectiveSearchParams.recent_not_view,
1211
- partial_result: screenPartialForRecovery,
1212
- page_exhaustion: screenResult.error?.page_exhaustion || null
1213
- };
1214
-
1215
- if (isPageExhaustedRecovery) {
1216
- runtimeHooks.setStage(
1217
- "screen_recovery",
1218
- `推荐列表已到底但未达目标,开始自动补货(第 ${screenAutoRecoveryCount} 次):优先尝试页内刷新。`
1219
- );
1220
- runtimeHooks.heartbeat("screen_recovery", lastAutoRecovery);
1221
-
1222
- const refreshResult = typeof refreshRecommendList === "function"
1223
- ? await refreshRecommendList(workspaceRoot, {
1224
- port: preflight.debug_port
1225
- })
1226
- : {
1227
- ok: false,
1228
- action: "in_page_refresh",
1229
- state: "REFRESH_ADAPTER_MISSING",
1230
- message: "缺少页内刷新适配器。"
1231
- };
1232
- ensurePipelineNotAborted(runtimeHooks.signal);
1233
-
1234
- lastAutoRecovery = {
1235
- ...lastAutoRecovery,
1236
- refresh: refreshResult
1237
- ? {
1238
- ok: refreshResult.ok,
1239
- state: refreshResult.state || null,
1240
- message: refreshResult.message || null,
1241
- before_state: refreshResult.before_state || null,
1242
- after_state: refreshResult.after_state || null
1243
- }
1244
- : null
1245
- };
1246
-
1247
- if (refreshResult?.ok) {
1248
- lastAutoRecovery = {
1249
- ...lastAutoRecovery,
1250
- action: "in_page_refresh"
1251
- };
1252
- currentResumeConfig = {
1253
- checkpoint_path: currentResumeConfig.checkpoint_path || null,
1254
- pause_control_path: currentResumeConfig.pause_control_path || null,
1255
- output_csv: resumeOutputCsv || null,
1256
- resume: true,
1257
- require_checkpoint: true
1258
- };
1259
- shouldRunSearch = false;
1260
- searchSummary = null;
1261
- continue;
1262
- }
1263
-
1264
- runtimeHooks.setStage(
1265
- "screen_recovery",
1266
- `页内刷新不可用(${refreshResult?.state || "unknown"}),改为刷新 recommend 页面并重跑 search。`
1267
- );
1268
- runtimeHooks.heartbeat("screen_recovery", lastAutoRecovery);
1269
- } else {
1270
- const recoveryFailureText = selectedPage === "featured" ? "network 简历获取失败" : "截图失败";
1271
- runtimeHooks.setStage(
1272
- "screen_recovery",
1273
- `screen 连续${recoveryFailureText},开始自动恢复(第 ${screenAutoRecoveryCount} 次):刷新 recommend 页面并重跑 search。`
1274
- );
1275
- runtimeHooks.heartbeat("screen_recovery", lastAutoRecovery);
1276
- }
1277
-
1278
- effectiveSearchParams = {
1279
- ...effectiveSearchParams,
1280
- recent_not_view: FORCED_RECENT_NOT_VIEW_ON_SCREEN_RECOVERY
1281
- };
1282
- lastAutoRecovery = {
1283
- ...lastAutoRecovery,
1284
- action: "reload_page_and_rerun_search",
1285
- effective_recent_not_view: effectiveSearchParams.recent_not_view
1286
- };
1287
-
1288
- const reloadResult = typeof reloadRecommendPage === "function"
1289
- ? await reloadRecommendPage(workspaceRoot, {
1290
- port: preflight.debug_port
1291
- })
1292
- : null;
1293
- ensurePipelineNotAborted(runtimeHooks.signal);
1294
-
1295
- lastAutoRecovery = {
1296
- ...lastAutoRecovery,
1297
- reload: reloadResult
1298
- ? {
1299
- ok: reloadResult.ok,
1300
- state: reloadResult.state || null,
1301
- message: reloadResult.message || null,
1302
- reloaded_url: reloadResult.reloaded_url || null
1303
- }
1304
- : null
1305
- };
1306
-
1307
- const recoveryPageCheck = await ensureRecommendPageReady(workspaceRoot, {
1308
- port: preflight.debug_port
1309
- });
1310
- ensurePipelineNotAborted(runtimeHooks.signal);
1311
- if (!recoveryPageCheck.ok) {
1312
- const guidance = buildChromeSetupGuidance({
1313
- debugPort: preflight.debug_port,
1314
- pageState: recoveryPageCheck.page_state
1315
- });
1316
- return buildFailedResponse(
1317
- recoveryPageCheck.state === "LOGIN_REQUIRED" || recoveryPageCheck.state === "LOGIN_REQUIRED_AFTER_REDIRECT"
1318
- ? "BOSS_LOGIN_REQUIRED"
1319
- : recoveryPageCheck.state === "DEBUG_PORT_UNREACHABLE"
1320
- ? "BOSS_CHROME_NOT_CONNECTED"
1321
- : "BOSS_RECOMMEND_PAGE_NOT_READY",
1322
- "自动恢复时无法重新就绪 recommend 页面,请先处理页面状态后再继续。",
1323
- {
1324
- search_params: effectiveSearchParams,
1325
- screen_params: parsed.screenParams,
1326
- selected_job: selectedJob,
1327
- partial_result: partialScreenResult,
1328
- required_user_action: "prepare_boss_recommend_page",
1329
- guidance,
1330
- diagnostics: {
1331
- debug_port: preflight.debug_port,
1332
- page_state: recoveryPageCheck.page_state,
1333
- stdout: screenResult.stdout?.slice(-1000),
1334
- stderr: screenResult.stderr?.slice(-1000),
1335
- result: screenResult.structured || null,
1336
- auto_recovery: lastAutoRecovery
1337
- }
1338
- }
1339
- );
1340
- }
1341
-
1342
- currentResumeConfig = {
1343
- checkpoint_path: currentResumeConfig.checkpoint_path || null,
1344
- pause_control_path: currentResumeConfig.pause_control_path || null,
1345
- output_csv: resumeOutputCsv || null,
1346
- resume: true,
1347
- require_checkpoint: true
1348
- };
1349
- shouldRunSearch = true;
1350
- searchSummary = null;
1351
- continue;
1352
- }
1353
-
1354
- return buildFailedResponse(
1355
- screenResult.error?.code || "RECOMMEND_SCREEN_FAILED",
1356
- screenResult.error?.message || "推荐页筛选执行失败。",
1357
- {
1358
- search_params: effectiveSearchParams,
1359
- screen_params: parsed.screenParams,
1360
- selected_job: selectedJob,
1361
- partial_result: partialScreenResult,
1362
- diagnostics: {
1363
- debug_port: preflight.debug_port,
1364
- stdout: screenResult.stdout?.slice(-1000),
1365
- stderr: screenResult.stderr?.slice(-1000),
1366
- result: screenResult.structured || null,
1367
- auto_recovery: lastAutoRecovery
1368
- }
1369
- }
1370
- );
1371
- }
1372
-
1373
- runtimeHooks.setStage("finalize", "screen 完成,正在汇总结果。");
1374
- runtimeHooks.heartbeat("finalize");
1375
- const durationSec = Math.max(1, Math.round((Date.now() - startedAt) / 1000));
1376
- const finalSearchSummary = searchSummary || {};
1377
- const screenSummary = screenResult.summary || {};
1378
- const resolvedActiveTabStatus = normalizeText(
1379
- screenSummary.active_tab_status
1380
- || finalSearchSummary.active_tab_status
1381
- || activeTabStatus
1382
- || selectedTabStatus
1383
- ) || selectedTabStatus;
1384
- const resolvedSelectedPage = normalizePageScope(
1385
- screenSummary.selected_page
1386
- || finalSearchSummary.selected_page
1387
- || selectedPage
1388
- || tabStatusToPageScope(resolvedActiveTabStatus)
1389
- ) || selectedPage;
1390
- const resolvedResumeSourceRaw = normalizeText(screenSummary.resume_source || "").toLowerCase();
1391
- const resolvedResumeSource = resolvedResumeSourceRaw === "network"
1392
- ? "network"
1393
- : resolvedSelectedPage === "featured"
1394
- ? "network"
1395
- : "image_fallback";
1396
- runtimeHooks.progress("finalize", {
1397
- processed: screenSummary.processed_count ?? 0,
1398
- passed: screenSummary.passed_count ?? 0,
1399
- skipped: screenSummary.skipped_count ?? 0,
1400
- greet_count: screenSummary.greet_count ?? 0
1401
- });
1402
-
1403
- return {
1404
- status: "COMPLETED",
1405
- search_params: effectiveSearchParams,
1406
- screen_params: parsed.screenParams,
1407
- result: {
1408
- candidate_count: finalSearchSummary.candidate_count ?? null,
1409
- applied_filters: finalSearchSummary.applied_filters || effectiveSearchParams,
1410
- processed_count: screenSummary.processed_count ?? 0,
1411
- passed_count: screenSummary.passed_count ?? 0,
1412
- skipped_count: screenSummary.skipped_count ?? 0,
1413
- duration_sec: durationSec,
1414
- output_csv: screenSummary.output_csv || null,
1415
- completion_reason: screenSummary.completion_reason || "screen_completed",
1416
- page_state: finalSearchSummary.page_state || pageCheck.page_state,
1417
- selected_job: finalSearchSummary.selected_job || selectedJob,
1418
- selected_page: resolvedSelectedPage,
1419
- active_tab_status: resolvedActiveTabStatus,
1420
- resume_source: resolvedResumeSource,
1421
- post_action: parsed.screenParams.post_action,
1422
- max_greet_count: parsed.screenParams.max_greet_count,
1423
- greet_count: screenSummary.greet_count ?? 0,
1424
- greet_limit_fallback_count: screenSummary.greet_limit_fallback_count ?? 0,
1425
- auto_recovery: lastAutoRecovery
1426
- },
1427
- message: parsed.screenParams.post_action === "none"
1428
- ? "Recommend 流水线已完成。本次 post_action=none:符合条件的人选仅记录到 CSV,不执行收藏或打招呼。"
1429
- : "Recommend 流水线已完成。post_action 在运行开始时已一次性确认;若选择打招呼并设置上限,超出上限后会自动改为收藏。"
1430
- };
1431
- }
1432
- }
1
+ import path from "node:path";
2
+ import { parseRecommendInstruction } from "./parser.js";
3
+ import {
4
+ attemptPipelineAutoRepair,
5
+ ensureBossRecommendPageReady,
6
+ ensureFeaturedCalibrationReady,
7
+ listRecommendJobs,
8
+ readRecommendTabState,
9
+ refreshBossRecommendList,
10
+ reloadBossRecommendPage,
11
+ runPipelinePreflight,
12
+ runRecommendSearchCli,
13
+ runRecommendScreenCli,
14
+ switchRecommendTab
15
+ } from "./adapters.js";
16
+
17
+ const FORCED_RECENT_NOT_VIEW_ON_SCREEN_RECOVERY = "近14天没有";
18
+ const MAX_SCREEN_AUTO_RECOVERY_ATTEMPTS = 5;
19
+ const PAGE_SCOPE_TO_TAB_STATUS = {
20
+ recommend: "0",
21
+ latest: "1",
22
+ featured: "3"
23
+ };
24
+ const TAB_STATUS_TO_PAGE_SCOPE = {
25
+ "0": "recommend",
26
+ "1": "latest",
27
+ "3": "featured"
28
+ };
29
+ const PAGE_SCOPE_LABELS = {
30
+ recommend: "推荐",
31
+ latest: "最新",
32
+ featured: "精选"
33
+ };
34
+
35
+ function dedupe(values = []) {
36
+ return [...new Set(values.filter(Boolean))];
37
+ }
38
+
39
+ function normalizeText(value) {
40
+ return String(value || "").replace(/\s+/g, " ").trim();
41
+ }
42
+
43
+ function normalizePageScope(value) {
44
+ const normalized = normalizeText(value).toLowerCase();
45
+ if (!normalized) return null;
46
+ if (["recommend", "推荐", "推荐页", "推荐页面"].includes(normalized)) return "recommend";
47
+ if (["latest", "最新", "最新页", "最新页面"].includes(normalized)) return "latest";
48
+ if (["featured", "精选", "精选页", "精选页面", "精选牛人"].includes(normalized)) return "featured";
49
+ return null;
50
+ }
51
+
52
+ function resolvePipelinePageScope(parsed, confirmation, overrides) {
53
+ const parsedResolved = normalizePageScope(parsed?.page_scope);
54
+ if (parsedResolved) return parsedResolved;
55
+ const fromConfirmation = normalizePageScope(confirmation?.page_value);
56
+ if (fromConfirmation) return fromConfirmation;
57
+ return "recommend";
58
+ }
59
+
60
+ function pageScopeToTabStatus(scope) {
61
+ return PAGE_SCOPE_TO_TAB_STATUS[scope] || "0";
62
+ }
63
+
64
+ function tabStatusToPageScope(status) {
65
+ return TAB_STATUS_TO_PAGE_SCOPE[String(status || "")] || "recommend";
66
+ }
67
+
68
+ function normalizeJobTitle(value) {
69
+ const text = normalizeText(value);
70
+ if (!text) return "";
71
+ const byGap = text.split(/\s{2,}/).map((item) => item.trim()).filter(Boolean)[0] || text;
72
+ const strippedRange = byGap
73
+ .replace(/\s+\d+(?:\.\d+)?\s*(?:-|~|—|至)\s*\d+(?:\.\d+)?\s*(?:k|K|千|万|元\/天|元\/月|元\/年|K\/月|k\/月|万\/月|万\/年)?$/u, "")
74
+ .trim();
75
+ const strippedSingle = strippedRange
76
+ .replace(/\s+\d+(?:\.\d+)?\s*(?:k|K|千|万|元\/天|元\/月|元\/年|K\/月|k\/月|万\/月|万\/年)$/u, "")
77
+ .trim();
78
+ return strippedSingle || byGap;
79
+ }
80
+
81
+ function normalizeJobOptions(jobOptions = []) {
82
+ const normalized = [];
83
+ const seen = new Set();
84
+ for (const item of jobOptions) {
85
+ if (!item || typeof item !== "object") continue;
86
+ const value = normalizeText(item.value);
87
+ const label = normalizeText(item.label);
88
+ const title = normalizeJobTitle(item.title || label);
89
+ const optionKey = value || title || label;
90
+ if (!optionKey || seen.has(optionKey)) continue;
91
+ seen.add(optionKey);
92
+ normalized.push({
93
+ value: value || null,
94
+ title: title || label || null,
95
+ label: label || title || null,
96
+ current: item.current === true
97
+ });
98
+ }
99
+ return normalized;
100
+ }
101
+
102
+ function resolveSelectedJob(jobOptions = [], requestedRaw) {
103
+ const requested = normalizeText(requestedRaw);
104
+ if (!requested) {
105
+ return { job: null, ambiguous: false, candidates: [] };
106
+ }
107
+ const requestedTitle = normalizeJobTitle(requested).toLowerCase();
108
+ const requestedLower = requested.toLowerCase();
109
+ const byValue = jobOptions.find((item) => normalizeText(item.value || "").toLowerCase() === requestedLower);
110
+ if (byValue) return { job: byValue, ambiguous: false, candidates: [] };
111
+ const byTitle = jobOptions.find((item) => normalizeJobTitle(item.title || "").toLowerCase() === requestedTitle);
112
+ if (byTitle) return { job: byTitle, ambiguous: false, candidates: [] };
113
+ const byLabel = jobOptions.find((item) => normalizeText(item.label || "").toLowerCase() === requestedLower);
114
+ if (byLabel) return { job: byLabel, ambiguous: false, candidates: [] };
115
+ const partialMatches = jobOptions.filter((item) => {
116
+ const title = normalizeJobTitle(item.title || "").toLowerCase();
117
+ const label = normalizeText(item.label || "").toLowerCase();
118
+ return (
119
+ (title && (title.includes(requestedTitle) || requestedTitle.includes(title)))
120
+ || (label && (label.includes(requestedLower) || requestedLower.includes(label)))
121
+ );
122
+ });
123
+ if (partialMatches.length === 1) {
124
+ return { job: partialMatches[0], ambiguous: false, candidates: [] };
125
+ }
126
+ if (partialMatches.length > 1) {
127
+ return {
128
+ job: null,
129
+ ambiguous: true,
130
+ candidates: partialMatches.map((item) => item.title || item.label || "").filter(Boolean)
131
+ };
132
+ }
133
+ return { job: null, ambiguous: false, candidates: [] };
134
+ }
135
+
136
+ function buildJobPendingQuestion(jobOptions = [], selectedHint = null, reason = null) {
137
+ const options = jobOptions.map((item) => ({
138
+ label: item.title || item.label || item.value,
139
+ value: item.value || item.title || item.label
140
+ }));
141
+ return {
142
+ field: "job",
143
+ question: reason
144
+ || "已识别当前推荐页岗位列表,请确认本次要执行的岗位。确认后会先点击该岗位,再开始 search 和 screen。",
145
+ value: normalizeText(selectedHint) || null,
146
+ options
147
+ };
148
+ }
149
+
150
+ function failedCheckSet(checks = []) {
151
+ const failed = checks
152
+ .filter((item) => item && item.ok === false && typeof item.key === "string")
153
+ .map((item) => item.key);
154
+ return new Set(failed);
155
+ }
156
+
157
+ function collectNpmInstallDirs(checks = [], workspaceRoot) {
158
+ const npmCheckKeys = new Set([
159
+ "npm_dep_chrome_remote_interface_search",
160
+ "npm_dep_chrome_remote_interface_screen",
161
+ "npm_dep_ws",
162
+ "npm_dep_sharp"
163
+ ]);
164
+ const dirs = checks
165
+ .filter((item) => item && item.ok === false && npmCheckKeys.has(item.key))
166
+ .map((item) => item.install_cwd)
167
+ .filter((value) => typeof value === "string" && value.trim());
168
+ if (dirs.length > 0) return dedupe(dirs);
169
+ return workspaceRoot ? [workspaceRoot] : [];
170
+ }
171
+
172
+ function quoteForCommand(value) {
173
+ return JSON.stringify(String(value));
174
+ }
175
+
176
+ function buildNpmInstallCommands(checks = [], workspaceRoot) {
177
+ const dirs = collectNpmInstallDirs(checks, workspaceRoot);
178
+ const commands = [];
179
+ for (const dir of dirs) {
180
+ commands.push(`npm install --prefix ${quoteForCommand(dir)}`);
181
+ }
182
+ return commands;
183
+ }
184
+
185
+ function getNodeInstallCommands() {
186
+ if (process.platform === "win32") {
187
+ return [
188
+ "winget install OpenJS.NodeJS.LTS",
189
+ "node --version"
190
+ ];
191
+ }
192
+ if (process.platform === "darwin") {
193
+ return [
194
+ "brew install node",
195
+ "node --version"
196
+ ];
197
+ }
198
+ return [
199
+ "使用系统包管理器安装 Node.js >= 18(例如 apt / yum / brew)",
200
+ "node --version"
201
+ ];
202
+ }
203
+
204
+ function formatCommandBlock(commands = []) {
205
+ return commands.map((command) => `- ${command}`).join("\n");
206
+ }
207
+
208
+ function buildPreflightRecovery(checks = [], workspaceRoot) {
209
+ const failed = failedCheckSet(checks);
210
+ if (failed.size === 0) return null;
211
+
212
+ const needScreenConfig = failed.has("screen_config");
213
+ const needNode = failed.has("node_cli");
214
+ const needNpm = (
215
+ failed.has("npm_dep_chrome_remote_interface_search")
216
+ || failed.has("npm_dep_chrome_remote_interface_screen")
217
+ || failed.has("npm_dep_ws")
218
+ || failed.has("npm_dep_sharp")
219
+ );
220
+
221
+ const ordered_steps = [];
222
+ if (needScreenConfig) {
223
+ const configCheck = checks.find((item) => item?.key === "screen_config");
224
+ ordered_steps.push({
225
+ id: "fill_screening_config",
226
+ title: "填写 screening-config.json(baseUrl / apiKey / model)",
227
+ blocked_by: [],
228
+ commands: [
229
+ `打开并填写:${configCheck?.path || "~/.boss-recommend-mcp/screening-config.json"}`,
230
+ "确认 baseUrl、apiKey、model 都是可用值(不要保留模板占位符)。"
231
+ ]
232
+ });
233
+ }
234
+ if (needNode) {
235
+ ordered_steps.push({
236
+ id: "install_nodejs",
237
+ title: "安装 Node.js >= 18",
238
+ blocked_by: [],
239
+ commands: getNodeInstallCommands()
240
+ });
241
+ }
242
+ if (needNpm) {
243
+ ordered_steps.push({
244
+ id: "install_npm_dependencies",
245
+ title: "安装 npm 依赖(chrome-remote-interface / ws / sharp)",
246
+ blocked_by: needNode ? ["install_nodejs"] : [],
247
+ commands: buildNpmInstallCommands(checks, workspaceRoot)
248
+ });
249
+ }
250
+
251
+ const promptLines = [
252
+ "你是环境修复 agent。请先读取 diagnostics.checks,再严格按下面顺序执行,不要并行跳步:",
253
+ "1) node_cli 失败 -> 先安装 Node.js,未成功前禁止执行 npm install。",
254
+ "2) npm_dep_* 失败 -> 再安装 npm 依赖(chrome-remote-interface / ws / sharp)。",
255
+ "每一步完成后都重新运行 doctor,直到所有检查通过后再重试流水线。"
256
+ ];
257
+ if (needScreenConfig) {
258
+ promptLines.splice(
259
+ 1,
260
+ 0,
261
+ "0) 若 screen_config 失败:先让用户提供并填写 baseUrl、apiKey、model(不得使用模板占位符)。"
262
+ );
263
+ }
264
+
265
+ if (needNpm) {
266
+ const npmCommands = buildNpmInstallCommands(checks, workspaceRoot);
267
+ if (npmCommands.length > 0) {
268
+ promptLines.push("建议执行的 npm 命令:");
269
+ promptLines.push(formatCommandBlock(npmCommands));
270
+ }
271
+ }
272
+
273
+ return {
274
+ failed_check_keys: [...failed],
275
+ ordered_steps,
276
+ agent_prompt: promptLines.join("\n")
277
+ };
278
+ }
279
+
280
+ function buildRequiredConfirmations(parsedResult) {
281
+ const confirmations = [];
282
+ if (parsedResult.needs_page_confirmation) confirmations.push("page_scope");
283
+ if (parsedResult.needs_filters_confirmation) confirmations.push("filters");
284
+ if (parsedResult.needs_school_tag_confirmation) confirmations.push("school_tag");
285
+ if (parsedResult.needs_degree_confirmation) confirmations.push("degree");
286
+ if (parsedResult.needs_gender_confirmation) confirmations.push("gender");
287
+ if (parsedResult.needs_recent_not_view_confirmation) confirmations.push("recent_not_view");
288
+ if (parsedResult.needs_criteria_confirmation) confirmations.push("criteria");
289
+ if (parsedResult.needs_target_count_confirmation) confirmations.push("target_count");
290
+ if (parsedResult.needs_post_action_confirmation) confirmations.push("post_action");
291
+ if (parsedResult.needs_max_greet_count_confirmation) confirmations.push("max_greet_count");
292
+ return confirmations;
293
+ }
294
+
295
+ function buildNeedInputResponse(parsedResult) {
296
+ return {
297
+ status: "NEED_INPUT",
298
+ missing_fields: parsedResult.missing_fields,
299
+ required_confirmations: buildRequiredConfirmations(parsedResult),
300
+ selected_page: parsedResult.proposed_page_scope || parsedResult.page_scope || "recommend",
301
+ search_params: parsedResult.searchParams,
302
+ screen_params: parsedResult.screenParams,
303
+ pending_questions: parsedResult.pending_questions,
304
+ review: parsedResult.review,
305
+ error: {
306
+ code: "MISSING_REQUIRED_FIELDS",
307
+ message: "缺少必要的筛选 criteria,请先补充或通过 overrides.criteria 明确传入。",
308
+ retryable: true
309
+ }
310
+ };
311
+ }
312
+
313
+ function buildNeedConfirmationResponse(parsedResult) {
314
+ return {
315
+ status: "NEED_CONFIRMATION",
316
+ required_confirmations: buildRequiredConfirmations(parsedResult),
317
+ selected_page: parsedResult.proposed_page_scope || parsedResult.page_scope || "recommend",
318
+ search_params: parsedResult.searchParams,
319
+ screen_params: {
320
+ ...parsedResult.screenParams,
321
+ target_count: parsedResult.proposed_target_count ?? parsedResult.screenParams.target_count,
322
+ post_action: parsedResult.proposed_post_action || parsedResult.screenParams.post_action,
323
+ max_greet_count: parsedResult.proposed_max_greet_count || parsedResult.screenParams.max_greet_count
324
+ },
325
+ pending_questions: parsedResult.pending_questions,
326
+ review: parsedResult.review
327
+ };
328
+ }
329
+
330
+ function buildFinalReviewQuestion({ searchParams, screenParams, selectedJob, selectedPage }) {
331
+ return {
332
+ field: "final_review",
333
+ question: "开始执行搜索和筛选前,请最后确认全部参数(岗位/页面/筛选条件/筛选 criteria/目标人数/post_action/max_greet_count)无误。",
334
+ value: {
335
+ job: selectedJob?.title || selectedJob?.label || selectedJob?.value || null,
336
+ page_scope: selectedPage || "recommend",
337
+ search_params: searchParams,
338
+ screen_params: screenParams
339
+ }
340
+ };
341
+ }
342
+
343
+ function buildFailedResponse(code, message, extra = {}) {
344
+ return {
345
+ status: "FAILED",
346
+ error: {
347
+ code,
348
+ message,
349
+ retryable: true
350
+ },
351
+ ...extra
352
+ };
353
+ }
354
+
355
+ function buildPausedResponse(message, extra = {}) {
356
+ return {
357
+ status: "PAUSED",
358
+ message: normalizeText(message || "") || "Recommend 流水线已暂停。",
359
+ ...extra
360
+ };
361
+ }
362
+
363
+ class PipelineAbortError extends Error {
364
+ constructor(message = "Pipeline execution aborted") {
365
+ super(message);
366
+ this.name = "PipelineAbortError";
367
+ this.code = "PIPELINE_ABORTED";
368
+ }
369
+ }
370
+
371
+ function isAbortSignalTriggered(signal) {
372
+ return Boolean(signal && signal.aborted);
373
+ }
374
+
375
+ function ensurePipelineNotAborted(signal) {
376
+ if (isAbortSignalTriggered(signal)) {
377
+ throw new PipelineAbortError("Pipeline execution aborted by caller.");
378
+ }
379
+ }
380
+
381
+ function safeInvokeRuntimeCallback(callback, payload) {
382
+ if (typeof callback !== "function") return;
383
+ try {
384
+ callback(payload);
385
+ } catch {
386
+ // Keep pipeline stable even if runtime callback fails.
387
+ }
388
+ }
389
+
390
+ function createPipelineRuntime(runtime = null) {
391
+ const signal = runtime?.signal;
392
+ const heartbeatIntervalMs = Number.isFinite(runtime?.heartbeatIntervalMs) && runtime.heartbeatIntervalMs > 0
393
+ ? runtime.heartbeatIntervalMs
394
+ : 10_000;
395
+ const isPauseRequested = typeof runtime?.isPauseRequested === "function"
396
+ ? runtime.isPauseRequested
397
+ : () => false;
398
+
399
+ function setStage(stage, message = null) {
400
+ safeInvokeRuntimeCallback(runtime?.onStage, {
401
+ stage,
402
+ message: normalizeText(message || "") || null,
403
+ at: new Date().toISOString()
404
+ });
405
+ }
406
+
407
+ function heartbeat(stage, details = null) {
408
+ safeInvokeRuntimeCallback(runtime?.onHeartbeat, {
409
+ stage,
410
+ details: details || null,
411
+ at: new Date().toISOString()
412
+ });
413
+ }
414
+
415
+ function output(stage, event) {
416
+ safeInvokeRuntimeCallback(runtime?.onOutput, {
417
+ stage,
418
+ ...(event || {}),
419
+ at: new Date().toISOString()
420
+ });
421
+ }
422
+
423
+ function progress(stage, payload) {
424
+ safeInvokeRuntimeCallback(runtime?.onProgress, {
425
+ stage,
426
+ ...(payload || {}),
427
+ at: new Date().toISOString()
428
+ });
429
+ }
430
+
431
+ function adapterRuntime(stage) {
432
+ return {
433
+ signal,
434
+ heartbeatIntervalMs,
435
+ onOutput: (event) => output(stage, event),
436
+ onHeartbeat: (event) => heartbeat(stage, event),
437
+ onProgress: (payload) => progress(stage, payload)
438
+ };
439
+ }
440
+
441
+ return {
442
+ signal,
443
+ heartbeatIntervalMs,
444
+ isPauseRequested,
445
+ setStage,
446
+ heartbeat,
447
+ output,
448
+ progress,
449
+ adapterRuntime
450
+ };
451
+ }
452
+
453
+ function isProcessAbortError(errorLike) {
454
+ const code = normalizeText(errorLike?.code || "").toUpperCase();
455
+ return code === "PROCESS_ABORTED" || code === "ABORTED";
456
+ }
457
+
458
+ function isPauseRequested(runtimeHooks) {
459
+ try {
460
+ return runtimeHooks?.isPauseRequested?.() === true;
461
+ } catch {
462
+ return false;
463
+ }
464
+ }
465
+
466
+ function buildChromeSetupGuidance({ debugPort, pageState }) {
467
+ const expectedUrl = pageState?.expected_url || "https://www.zhipin.com/web/chat/recommend";
468
+ const loginUrl = pageState?.login_url || "https://www.zhipin.com/web/user/?ka=bticket";
469
+ const currentUrl = pageState?.current_url || null;
470
+ const state = pageState?.state || "UNKNOWN";
471
+ const isPortIssue = state === "DEBUG_PORT_UNREACHABLE";
472
+ const needsLogin = state === "LOGIN_REQUIRED" || state === "LOGIN_REQUIRED_AFTER_REDIRECT";
473
+ const launchAttempt = pageState?.launch_attempt || null;
474
+ const launchLine = launchAttempt?.ok
475
+ ? `已自动启动 Chrome(--remote-debugging-port=${debugPort},--user-data-dir=${launchAttempt.user_data_dir || "auto"})。`
476
+ : null;
477
+ const launchExample = process.platform === "win32"
478
+ ? `chrome.exe --remote-debugging-port=${debugPort} --user-data-dir=<profile-dir>`
479
+ : process.platform === "darwin"
480
+ ? `'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' --remote-debugging-port=${debugPort} --user-data-dir=<profile-dir>`
481
+ : `google-chrome --remote-debugging-port=${debugPort} --user-data-dir=<profile-dir>`;
482
+ const steps = [
483
+ `请先在可连接到 DevTools 端口 ${debugPort} 的 Chrome 实例中完成以下操作:`,
484
+ ...(launchLine ? [launchLine] : []),
485
+ "1) 确认当前 Chrome 与本次运行使用同一个远程调试端口。",
486
+ isPortIssue
487
+ ? `2) 若端口不可连接,请用远程调试方式启动 Chrome(示例:${launchExample})。`
488
+ : "2) 确认端口可连接且浏览器窗口保持打开。",
489
+ needsLogin
490
+ ? `3) 当前检测到 Boss 未登录,请先打开并完成登录:${loginUrl}`
491
+ : "3) 如 Boss 登录态失效,请先重新登录。",
492
+ `4) 登录完成后先导航并停留在推荐页:${expectedUrl}`,
493
+ "5) 完成后回复“已就绪”,我会继续执行并优先自动导航到推荐页。"
494
+ ];
495
+ return {
496
+ debug_port: debugPort,
497
+ expected_url: expectedUrl,
498
+ current_url: currentUrl,
499
+ page_state: state,
500
+ agent_prompt: steps.join("\n")
501
+ };
502
+ }
503
+
504
+ const defaultDependencies = {
505
+ attemptPipelineAutoRepair,
506
+ parseRecommendInstruction,
507
+ ensureBossRecommendPageReady,
508
+ ensureFeaturedCalibrationReady,
509
+ listRecommendJobs,
510
+ readRecommendTabState,
511
+ refreshBossRecommendList,
512
+ reloadBossRecommendPage,
513
+ runPipelinePreflight,
514
+ runRecommendSearchCli,
515
+ runRecommendScreenCli,
516
+ switchRecommendTab
517
+ };
518
+
519
+ export async function runRecommendPipeline(
520
+ { workspaceRoot, instruction, confirmation, overrides, resume = null },
521
+ dependencies = defaultDependencies,
522
+ runtime = null
523
+ ) {
524
+ const injectedDependencies = dependencies || {};
525
+ const resolvedDependencies = { ...defaultDependencies, ...(dependencies || {}) };
526
+ const {
527
+ attemptPipelineAutoRepair: attemptAutoRepair,
528
+ parseRecommendInstruction: parseInstruction,
529
+ ensureBossRecommendPageReady: ensureRecommendPageReady,
530
+ ensureFeaturedCalibrationReady: ensureCalibrationReady,
531
+ listRecommendJobs: listJobs,
532
+ readRecommendTabState: readTabState,
533
+ refreshBossRecommendList: refreshRecommendList,
534
+ reloadBossRecommendPage: reloadRecommendPage,
535
+ runPipelinePreflight: runPreflight,
536
+ runRecommendSearchCli: searchCli,
537
+ runRecommendScreenCli: screenCli,
538
+ switchRecommendTab: switchTab
539
+ } = resolvedDependencies;
540
+ const runtimeHooks = createPipelineRuntime(runtime);
541
+ ensurePipelineNotAborted(runtimeHooks.signal);
542
+
543
+ const startedAt = Date.now();
544
+ const parsed = parseInstruction({ instruction, confirmation, overrides });
545
+ const selectedPage = resolvePipelinePageScope(parsed, confirmation, overrides);
546
+
547
+ if (parsed.missing_fields.length > 0) {
548
+ return buildNeedInputResponse(parsed);
549
+ }
550
+
551
+ if (
552
+ parsed.needs_page_confirmation
553
+ || parsed.needs_filters_confirmation
554
+ || parsed.needs_school_tag_confirmation
555
+ || parsed.needs_degree_confirmation
556
+ || parsed.needs_gender_confirmation
557
+ || parsed.needs_recent_not_view_confirmation
558
+ || parsed.needs_criteria_confirmation
559
+ || parsed.needs_target_count_confirmation
560
+ || parsed.needs_post_action_confirmation
561
+ || parsed.needs_max_greet_count_confirmation
562
+ ) {
563
+ return buildNeedConfirmationResponse(parsed);
564
+ }
565
+
566
+ ensurePipelineNotAborted(runtimeHooks.signal);
567
+ runtimeHooks.setStage("preflight", "开始执行 preflight 检查。");
568
+ runtimeHooks.heartbeat("preflight");
569
+
570
+ let preflight = runPreflight(workspaceRoot, { pageScope: selectedPage });
571
+ let autoRepair = null;
572
+ const shouldAttemptAutoRepair = (
573
+ dependencies === defaultDependencies
574
+ || Object.prototype.hasOwnProperty.call(injectedDependencies, "attemptPipelineAutoRepair")
575
+ );
576
+ if (!preflight.ok) {
577
+ if (shouldAttemptAutoRepair && typeof attemptAutoRepair === "function") {
578
+ autoRepair = attemptAutoRepair(workspaceRoot, preflight);
579
+ if (autoRepair?.preflight) {
580
+ preflight = autoRepair.preflight;
581
+ }
582
+ }
583
+ }
584
+
585
+ const shouldCheckFeaturedCalibration = (
586
+ dependencies === defaultDependencies
587
+ || Object.prototype.hasOwnProperty.call(injectedDependencies, "ensureFeaturedCalibrationReady")
588
+ );
589
+ const featuredCalibrationCheck = preflight.checks?.find((item) => item?.key === "favorite_calibration");
590
+ if (
591
+ selectedPage === "featured"
592
+ && shouldCheckFeaturedCalibration
593
+ && featuredCalibrationCheck
594
+ && featuredCalibrationCheck.ok === false
595
+ ) {
596
+ runtimeHooks.setStage("calibration", "检测到精选页缺少可用收藏校准文件,开始自动执行校准。");
597
+ runtimeHooks.heartbeat("calibration");
598
+ const calibrationResult = await ensureCalibrationReady(workspaceRoot, {
599
+ port: preflight.debug_port,
600
+ timeoutMs: 60000,
601
+ autoCalibrate: true,
602
+ runtime: runtimeHooks.adapterRuntime("calibration")
603
+ });
604
+ ensurePipelineNotAborted(runtimeHooks.signal);
605
+ if (!calibrationResult?.ok) {
606
+ return buildFailedResponse(
607
+ "CALIBRATION_REQUIRED",
608
+ calibrationResult?.error?.message || "精选页收藏校准失败,请先完成校准后重试。",
609
+ {
610
+ selected_page: selectedPage,
611
+ search_params: parsed.searchParams,
612
+ screen_params: parsed.screenParams,
613
+ required_user_action: "run_featured_calibration",
614
+ guidance: {
615
+ calibration_path: calibrationResult?.calibration_path || featuredCalibrationCheck.path || null,
616
+ debug_port: calibrationResult?.debug_port || preflight.debug_port,
617
+ calibration_script_path: calibrationResult?.calibration_script_path || null,
618
+ tip: "请在 Boss 推荐页切换到精选 tab 后打开候选人详情,按提示先收藏再取消收藏完成校准后重试。"
619
+ },
620
+ diagnostics: {
621
+ checks: preflight.checks,
622
+ calibration: calibrationResult || null
623
+ }
624
+ }
625
+ );
626
+ }
627
+ preflight = runPreflight(workspaceRoot, { pageScope: selectedPage });
628
+ }
629
+
630
+ if (!preflight.ok) {
631
+ runtimeHooks.heartbeat("preflight", {
632
+ status: "failed"
633
+ });
634
+ const screenConfigCheck = preflight.checks?.find((item) => item?.key === "screen_config" && item?.ok === false);
635
+ const screenConfigPath = String(screenConfigCheck?.path || "");
636
+ const screenConfigDir = screenConfigPath ? path.dirname(screenConfigPath) : null;
637
+ const screenConfigReason = String(screenConfigCheck?.reason || "").trim().toUpperCase();
638
+ const screenConfigMessage = String(screenConfigCheck?.message || "");
639
+ const screenConfigHasPlaceholder = (
640
+ screenConfigReason.includes("PLACEHOLDER")
641
+ || /占位符|默认模板值|replace-with-openai-api-key/i.test(screenConfigMessage)
642
+ );
643
+ const recovery = buildPreflightRecovery(preflight.checks, workspaceRoot);
644
+ return buildFailedResponse(
645
+ "PIPELINE_PREFLIGHT_FAILED",
646
+ "Recommend 流水线运行前检查失败,请先修复缺失的本地依赖或配置文件。",
647
+ {
648
+ search_params: parsed.searchParams,
649
+ screen_params: parsed.screenParams,
650
+ required_user_action: screenConfigCheck
651
+ ? (screenConfigHasPlaceholder ? "confirm_screening_config_updated" : "provide_screening_config")
652
+ : undefined,
653
+ guidance: screenConfigCheck
654
+ ? {
655
+ config_path: screenConfigCheck.path,
656
+ config_dir: screenConfigDir,
657
+ agent_prompt: [
658
+ ...(screenConfigHasPlaceholder
659
+ ? [
660
+ "检测到 screening-config.json 仍包含默认占位词,当前禁止继续执行。",
661
+ `请引导用户在以下目录修改配置文件:${screenConfigDir || "(unknown)"}`,
662
+ `配置文件路径:${screenConfigCheck.path}`,
663
+ "必须替换为真实可用值:baseUrl、apiKey、model(不要保留任何模板占位符)。",
664
+ "修改完成后,必须先让用户明确回复“已修改完成”,再继续下一步。"
665
+ ]
666
+ : [
667
+ "请先让用户填写 screening-config.json 的以下字段:",
668
+ "1) baseUrl",
669
+ "2) apiKey",
670
+ "3) model",
671
+ `配置文件路径:${screenConfigCheck.path}`,
672
+ "注意:不要使用模板占位符(例如 replace-with-openai-api-key),也不要由 agent 自行猜测或代填示例值。必须向用户逐项确认真实可用值后再重试。"
673
+ ])
674
+ ].join("\n")
675
+ }
676
+ : undefined,
677
+ diagnostics: {
678
+ checks: preflight.checks,
679
+ debug_port: preflight.debug_port,
680
+ config_resolution: preflight.config_resolution,
681
+ auto_repair: autoRepair,
682
+ recovery
683
+ }
684
+ }
685
+ );
686
+ }
687
+
688
+ ensurePipelineNotAborted(runtimeHooks.signal);
689
+ runtimeHooks.setStage("page_ready", "preflight 完成,开始检查 recommend 页面就绪状态。");
690
+ runtimeHooks.heartbeat("page_ready");
691
+
692
+ const pageCheck = await ensureRecommendPageReady(workspaceRoot, {
693
+ port: preflight.debug_port
694
+ });
695
+ ensurePipelineNotAborted(runtimeHooks.signal);
696
+ if (!pageCheck.ok) {
697
+ const loginRelated = new Set(["LOGIN_REQUIRED", "LOGIN_REQUIRED_AFTER_REDIRECT"]);
698
+ const connectivityRelated = new Set(["DEBUG_PORT_UNREACHABLE"]);
699
+ const guidance = buildChromeSetupGuidance({
700
+ debugPort: preflight.debug_port,
701
+ pageState: pageCheck.page_state
702
+ });
703
+ return buildFailedResponse(
704
+ connectivityRelated.has(pageCheck.state)
705
+ ? "BOSS_CHROME_NOT_CONNECTED"
706
+ : loginRelated.has(pageCheck.state)
707
+ ? "BOSS_LOGIN_REQUIRED"
708
+ : "BOSS_RECOMMEND_PAGE_NOT_READY",
709
+ loginRelated.has(pageCheck.state)
710
+ ? `开始执行搜索和筛选前,请先在端口 ${preflight.debug_port} 的 Chrome 完成 Boss 登录并停留在 recommend 页面。`
711
+ : connectivityRelated.has(pageCheck.state)
712
+ ? `开始执行搜索和筛选前,需要先连接到端口 ${preflight.debug_port} 的 Chrome 远程调试实例。`
713
+ : `开始执行搜索和筛选前,请先在端口 ${preflight.debug_port} 的 Chrome 停留在 Boss recommend 页面。`,
714
+ {
715
+ search_params: parsed.searchParams,
716
+ screen_params: parsed.screenParams,
717
+ required_user_action: "prepare_boss_recommend_page",
718
+ guidance,
719
+ diagnostics: {
720
+ debug_port: preflight.debug_port,
721
+ page_state: pageCheck.page_state
722
+ }
723
+ }
724
+ );
725
+ }
726
+
727
+ runtimeHooks.setStage("job_list", "页面就绪,开始读取岗位列表。");
728
+ runtimeHooks.heartbeat("job_list");
729
+ const jobListResult = await listJobs({
730
+ workspaceRoot,
731
+ port: preflight.debug_port,
732
+ runtime: runtimeHooks.adapterRuntime("job_list")
733
+ });
734
+ ensurePipelineNotAborted(runtimeHooks.signal);
735
+ if (isProcessAbortError(jobListResult.error)) {
736
+ throw new PipelineAbortError(jobListResult.error?.message || "岗位列表读取已取消。");
737
+ }
738
+ if (!jobListResult.ok) {
739
+ const jobListErrorCode = String(jobListResult.error?.code || "");
740
+ const jobListErrorMessage = String(jobListResult.error?.message || "");
741
+ const pageReadinessFailure = (
742
+ jobListErrorCode === "JOB_TRIGGER_NOT_FOUND"
743
+ || jobListErrorCode === "NO_RECOMMEND_IFRAME"
744
+ || jobListErrorCode === "LOGIN_REQUIRED"
745
+ || jobListErrorMessage.includes("JOB_TRIGGER_NOT_FOUND")
746
+ || jobListErrorMessage.includes("NO_RECOMMEND_IFRAME")
747
+ || jobListErrorMessage.includes("LOGIN_REQUIRED")
748
+ );
749
+ if (pageReadinessFailure) {
750
+ const recheck = await ensureRecommendPageReady(workspaceRoot, {
751
+ port: preflight.debug_port
752
+ });
753
+ const loginRelated = new Set(["LOGIN_REQUIRED", "LOGIN_REQUIRED_AFTER_REDIRECT"]);
754
+ const connectivityRelated = new Set(["DEBUG_PORT_UNREACHABLE"]);
755
+ const guidance = buildChromeSetupGuidance({
756
+ debugPort: preflight.debug_port,
757
+ pageState: recheck.page_state
758
+ });
759
+ if (!recheck.ok || loginRelated.has(recheck.state) || connectivityRelated.has(recheck.state)) {
760
+ return buildFailedResponse(
761
+ connectivityRelated.has(recheck.state)
762
+ ? "BOSS_CHROME_NOT_CONNECTED"
763
+ : loginRelated.has(recheck.state)
764
+ ? "BOSS_LOGIN_REQUIRED"
765
+ : "BOSS_RECOMMEND_PAGE_NOT_READY",
766
+ loginRelated.has(recheck.state)
767
+ ? `检测到当前 Boss 处于未登录状态,请先登录后再继续。登录页:https://www.zhipin.com/web/user/?ka=bticket`
768
+ : connectivityRelated.has(recheck.state)
769
+ ? `读取岗位列表前需要先连接到端口 ${preflight.debug_port} 的 Chrome 远程调试实例。`
770
+ : `读取岗位列表前,请先在端口 ${preflight.debug_port} 的 Chrome 停留在 Boss recommend 页面。`,
771
+ {
772
+ search_params: parsed.searchParams,
773
+ screen_params: parsed.screenParams,
774
+ required_user_action: "prepare_boss_recommend_page",
775
+ guidance,
776
+ diagnostics: {
777
+ debug_port: preflight.debug_port,
778
+ page_state: recheck.page_state,
779
+ stdout: jobListResult.stdout?.slice(-1000),
780
+ stderr: jobListResult.stderr?.slice(-1000),
781
+ result: jobListResult.structured || null
782
+ }
783
+ }
784
+ );
785
+ }
786
+ }
787
+ return buildFailedResponse(
788
+ jobListResult.error?.code || "RECOMMEND_JOB_LIST_FAILED",
789
+ jobListResult.error?.message || "读取推荐岗位列表失败,无法开始筛选。",
790
+ {
791
+ search_params: parsed.searchParams,
792
+ screen_params: parsed.screenParams,
793
+ diagnostics: {
794
+ debug_port: preflight.debug_port,
795
+ stdout: jobListResult.stdout?.slice(-1000),
796
+ stderr: jobListResult.stderr?.slice(-1000),
797
+ result: jobListResult.structured || null
798
+ }
799
+ }
800
+ );
801
+ }
802
+ const jobOptions = normalizeJobOptions(jobListResult.jobs);
803
+ if (jobOptions.length === 0) {
804
+ return buildFailedResponse(
805
+ "RECOMMEND_JOB_LIST_EMPTY",
806
+ "未识别到可选岗位,暂时无法开始筛选。",
807
+ {
808
+ search_params: parsed.searchParams,
809
+ screen_params: parsed.screenParams,
810
+ diagnostics: {
811
+ debug_port: preflight.debug_port,
812
+ result: jobListResult.structured || null
813
+ }
814
+ }
815
+ );
816
+ }
817
+
818
+ const selectedJobHint = normalizeText(confirmation?.job_value || parsed.job_selection_hint || "");
819
+ const selectedJobResolution = resolveSelectedJob(jobOptions, selectedJobHint);
820
+ const jobConfirmed = confirmation?.job_confirmed === true;
821
+ const selectedTabStatus = pageScopeToTabStatus(selectedPage);
822
+ if (!jobConfirmed || !selectedJobResolution.job) {
823
+ const reason = selectedJobResolution.ambiguous
824
+ ? `你提供的岗位“${selectedJobHint}”匹配到多个选项:${selectedJobResolution.candidates.join(" / ")}。请明确选择其中一个岗位。`
825
+ : selectedJobHint
826
+ ? `未在当前岗位列表中找到“${selectedJobHint}”,请从以下岗位中重新确认一个。`
827
+ : "已识别当前推荐页岗位列表,请先确认本次要执行的岗位;确认后会先点击该岗位,再开始 search 和 screen。";
828
+ const pendingQuestions = (parsed.pending_questions || []).filter((item) => item?.field !== "job");
829
+ pendingQuestions.push(buildJobPendingQuestion(jobOptions, selectedJobHint, reason));
830
+ const requiredConfirmations = dedupe([...buildRequiredConfirmations(parsed), "job"]);
831
+ return {
832
+ status: "NEED_CONFIRMATION",
833
+ required_confirmations: requiredConfirmations,
834
+ selected_page: selectedPage,
835
+ search_params: parsed.searchParams,
836
+ screen_params: {
837
+ ...parsed.screenParams,
838
+ target_count: parsed.proposed_target_count ?? parsed.screenParams.target_count,
839
+ post_action: parsed.proposed_post_action || parsed.screenParams.post_action,
840
+ max_greet_count: parsed.proposed_max_greet_count || parsed.screenParams.max_greet_count
841
+ },
842
+ pending_questions: pendingQuestions,
843
+ review: parsed.review,
844
+ job_options: jobOptions
845
+ };
846
+ }
847
+ const selectedJob = selectedJobResolution.job;
848
+ const selectedJobToken = selectedJob.value || selectedJob.title || selectedJob.label;
849
+ if (confirmation?.final_confirmed !== true) {
850
+ const pendingQuestions = (parsed.pending_questions || []).filter((item) => item?.field !== "final_review");
851
+ pendingQuestions.push(buildFinalReviewQuestion({
852
+ searchParams: parsed.searchParams,
853
+ screenParams: {
854
+ ...parsed.screenParams,
855
+ target_count: parsed.proposed_target_count ?? parsed.screenParams.target_count,
856
+ post_action: parsed.proposed_post_action || parsed.screenParams.post_action,
857
+ max_greet_count: parsed.proposed_max_greet_count || parsed.screenParams.max_greet_count
858
+ },
859
+ selectedJob,
860
+ selectedPage
861
+ }));
862
+ return {
863
+ status: "NEED_CONFIRMATION",
864
+ required_confirmations: dedupe([...buildRequiredConfirmations(parsed), "final_review"]),
865
+ selected_page: selectedPage,
866
+ search_params: parsed.searchParams,
867
+ screen_params: {
868
+ ...parsed.screenParams,
869
+ target_count: parsed.proposed_target_count ?? parsed.screenParams.target_count,
870
+ post_action: parsed.proposed_post_action || parsed.screenParams.post_action,
871
+ max_greet_count: parsed.proposed_max_greet_count || parsed.screenParams.max_greet_count
872
+ },
873
+ selected_job: selectedJob,
874
+ pending_questions: pendingQuestions,
875
+ review: parsed.review,
876
+ job_options: jobOptions
877
+ };
878
+ }
879
+
880
+ const resumeCompletionReason = normalizeText(resume?.previous_completion_reason || "").toLowerCase();
881
+ const isResumeRun = resume?.resume === true;
882
+ const resumeFromPausedBeforeScreen = isResumeRun && resumeCompletionReason === "paused_before_screen";
883
+ const skipSearchOnResume = isResumeRun && !resumeFromPausedBeforeScreen;
884
+ let effectiveSearchParams = { ...parsed.searchParams };
885
+ let searchSummary = null;
886
+ let shouldRunSearch = !skipSearchOnResume;
887
+ let screenAutoRecoveryCount = 0;
888
+ let lastAutoRecovery = null;
889
+ let activeTabStatus = null;
890
+ let currentResumeConfig = {
891
+ checkpoint_path: resume?.checkpoint_path || null,
892
+ pause_control_path: resume?.pause_control_path || null,
893
+ output_csv: resume?.output_csv || null,
894
+ resume: resume?.resume === true,
895
+ require_checkpoint: skipSearchOnResume
896
+ };
897
+
898
+ const ensureSelectedPageTab = async () => {
899
+ if (selectedPage === "recommend") {
900
+ activeTabStatus = selectedTabStatus;
901
+ return {
902
+ ok: true,
903
+ switched: false,
904
+ before_state: null,
905
+ after_state: null
906
+ };
907
+ }
908
+ const expectedStatus = selectedTabStatus;
909
+ let beforeState = null;
910
+ if (typeof readTabState === "function") {
911
+ beforeState = await readTabState(workspaceRoot, { port: preflight.debug_port });
912
+ if (beforeState?.ok && normalizeText(beforeState.active_status)) {
913
+ activeTabStatus = normalizeText(beforeState.active_status);
914
+ }
915
+ }
916
+ if (String(activeTabStatus || "") === String(expectedStatus)) {
917
+ return {
918
+ ok: true,
919
+ switched: false,
920
+ before_state: beforeState || null,
921
+ after_state: beforeState || null
922
+ };
923
+ }
924
+ if (typeof switchTab !== "function") {
925
+ return {
926
+ ok: false,
927
+ error: {
928
+ code: "RECOMMEND_TAB_SWITCH_ADAPTER_MISSING",
929
+ message: "缺少 recommend tab 切换适配器。"
930
+ },
931
+ before_state: beforeState || null,
932
+ after_state: null
933
+ };
934
+ }
935
+ const switchResult = await switchTab(workspaceRoot, {
936
+ port: preflight.debug_port,
937
+ target_status: expectedStatus
938
+ });
939
+ if (!switchResult?.ok) {
940
+ return {
941
+ ok: false,
942
+ error: {
943
+ code: switchResult?.state || "RECOMMEND_TAB_SWITCH_FAILED",
944
+ message: switchResult?.message || `切换到${PAGE_SCOPE_LABELS[selectedPage]} tab 失败。`
945
+ },
946
+ before_state: beforeState || null,
947
+ after_state: switchResult?.tab_state || null
948
+ };
949
+ }
950
+ activeTabStatus = normalizeText(switchResult.active_status || switchResult.tab_state?.active_status || expectedStatus);
951
+ return {
952
+ ok: true,
953
+ switched: true,
954
+ before_state: beforeState || null,
955
+ after_state: switchResult.tab_state || null
956
+ };
957
+ };
958
+
959
+ while (true) {
960
+ if (shouldRunSearch) {
961
+ ensurePipelineNotAborted(runtimeHooks.signal);
962
+ runtimeHooks.setStage(
963
+ "search",
964
+ screenAutoRecoveryCount > 0
965
+ ? `自动恢复第 ${screenAutoRecoveryCount} 次:重新执行 recommend search(强制 recent_not_view=${FORCED_RECENT_NOT_VIEW_ON_SCREEN_RECOVERY})。`
966
+ : "岗位已确认,开始执行 recommend search。"
967
+ );
968
+ runtimeHooks.heartbeat("search", lastAutoRecovery);
969
+ const searchResult = await searchCli({
970
+ workspaceRoot,
971
+ searchParams: effectiveSearchParams,
972
+ selectedJob: selectedJobToken,
973
+ pageScope: selectedPage,
974
+ runtime: runtimeHooks.adapterRuntime("search")
975
+ });
976
+ ensurePipelineNotAborted(runtimeHooks.signal);
977
+ if (isProcessAbortError(searchResult.error)) {
978
+ throw new PipelineAbortError(searchResult.error?.message || "推荐筛选已取消。");
979
+ }
980
+ if (!searchResult.ok) {
981
+ const searchErrorCode = String(searchResult.error?.code || "");
982
+ const searchErrorMessage = String(searchResult.error?.message || "");
983
+ const loginRelatedSearchFailure = (
984
+ searchErrorCode === "LOGIN_REQUIRED"
985
+ || searchErrorCode === "NO_RECOMMEND_IFRAME"
986
+ || searchErrorMessage.includes("LOGIN_REQUIRED")
987
+ || searchErrorMessage.includes("NO_RECOMMEND_IFRAME")
988
+ );
989
+ if (loginRelatedSearchFailure) {
990
+ const recheck = await ensureRecommendPageReady(workspaceRoot, {
991
+ port: preflight.debug_port
992
+ });
993
+ if (recheck.state === "LOGIN_REQUIRED" || recheck.state === "LOGIN_REQUIRED_AFTER_REDIRECT") {
994
+ const guidance = buildChromeSetupGuidance({
995
+ debugPort: preflight.debug_port,
996
+ pageState: recheck.page_state
997
+ });
998
+ return buildFailedResponse(
999
+ "BOSS_LOGIN_REQUIRED",
1000
+ "检测到当前 Boss 处于未登录状态,请先登录后再继续。登录页:https://www.zhipin.com/web/user/?ka=bticket",
1001
+ {
1002
+ search_params: effectiveSearchParams,
1003
+ screen_params: parsed.screenParams,
1004
+ selected_job: selectedJob,
1005
+ required_user_action: "prepare_boss_recommend_page",
1006
+ guidance,
1007
+ diagnostics: {
1008
+ debug_port: preflight.debug_port,
1009
+ page_state: recheck.page_state,
1010
+ stdout: searchResult.stdout?.slice(-1000),
1011
+ stderr: searchResult.stderr?.slice(-1000),
1012
+ result: searchResult.structured || null,
1013
+ auto_recovery: lastAutoRecovery
1014
+ }
1015
+ }
1016
+ );
1017
+ }
1018
+ }
1019
+ return buildFailedResponse(
1020
+ searchResult.error?.code || "RECOMMEND_SEARCH_FAILED",
1021
+ searchResult.error?.message || "推荐页筛选执行失败。",
1022
+ {
1023
+ search_params: effectiveSearchParams,
1024
+ screen_params: parsed.screenParams,
1025
+ selected_job: selectedJob,
1026
+ diagnostics: {
1027
+ debug_port: preflight.debug_port,
1028
+ stdout: searchResult.stdout?.slice(-1000),
1029
+ stderr: searchResult.stderr?.slice(-1000),
1030
+ result: searchResult.structured || null,
1031
+ auto_recovery: lastAutoRecovery
1032
+ }
1033
+ }
1034
+ );
1035
+ }
1036
+
1037
+ searchSummary = searchResult.summary || {};
1038
+ if (isPauseRequested(runtimeHooks)) {
1039
+ return buildPausedResponse("已在 screen 阶段开始前暂停 Recommend 流水线。", {
1040
+ selected_page: selectedPage,
1041
+ active_tab_status: activeTabStatus || null,
1042
+ search_params: effectiveSearchParams,
1043
+ screen_params: parsed.screenParams,
1044
+ selected_job: selectedJob,
1045
+ partial_result: {
1046
+ candidate_count: searchSummary.candidate_count ?? null,
1047
+ applied_filters: searchSummary.applied_filters || effectiveSearchParams,
1048
+ output_csv: currentResumeConfig.output_csv || null,
1049
+ completion_reason: "paused_before_screen"
1050
+ }
1051
+ });
1052
+ }
1053
+ const tabSwitchResult = await ensureSelectedPageTab();
1054
+ if (!tabSwitchResult.ok) {
1055
+ return buildFailedResponse(
1056
+ tabSwitchResult.error?.code || "RECOMMEND_TAB_SWITCH_FAILED",
1057
+ tabSwitchResult.error?.message || `切换到${PAGE_SCOPE_LABELS[selectedPage]} tab 失败。`,
1058
+ {
1059
+ selected_page: selectedPage,
1060
+ active_tab_status: activeTabStatus || null,
1061
+ search_params: effectiveSearchParams,
1062
+ screen_params: parsed.screenParams,
1063
+ selected_job: selectedJob,
1064
+ required_user_action: "retry_switch_recommend_tab",
1065
+ guidance: {
1066
+ expected_tab_status: selectedTabStatus,
1067
+ expected_page_scope: selectedPage,
1068
+ expected_page_label: PAGE_SCOPE_LABELS[selectedPage]
1069
+ },
1070
+ diagnostics: {
1071
+ debug_port: preflight.debug_port,
1072
+ tab_switch: tabSwitchResult
1073
+ }
1074
+ }
1075
+ );
1076
+ }
1077
+ ensurePipelineNotAborted(runtimeHooks.signal);
1078
+ runtimeHooks.setStage(
1079
+ "screen",
1080
+ selectedPage !== "recommend"
1081
+ ? `search 完成,已切换到${PAGE_SCOPE_LABELS[selectedPage]} tab,开始执行 recommend screen。`
1082
+ : "search 完成,开始执行 recommend screen。"
1083
+ );
1084
+ } else {
1085
+ const tabSwitchResult = await ensureSelectedPageTab();
1086
+ if (!tabSwitchResult.ok) {
1087
+ return buildFailedResponse(
1088
+ tabSwitchResult.error?.code || "RECOMMEND_TAB_SWITCH_FAILED",
1089
+ tabSwitchResult.error?.message || `切换到${PAGE_SCOPE_LABELS[selectedPage]} tab 失败。`,
1090
+ {
1091
+ selected_page: selectedPage,
1092
+ active_tab_status: activeTabStatus || null,
1093
+ search_params: effectiveSearchParams,
1094
+ screen_params: parsed.screenParams,
1095
+ selected_job: selectedJob,
1096
+ required_user_action: "retry_switch_recommend_tab",
1097
+ guidance: {
1098
+ expected_tab_status: selectedTabStatus,
1099
+ expected_page_scope: selectedPage,
1100
+ expected_page_label: PAGE_SCOPE_LABELS[selectedPage]
1101
+ },
1102
+ diagnostics: {
1103
+ debug_port: preflight.debug_port,
1104
+ tab_switch: tabSwitchResult
1105
+ }
1106
+ }
1107
+ );
1108
+ }
1109
+ ensurePipelineNotAborted(runtimeHooks.signal);
1110
+ runtimeHooks.setStage("screen", "检测到可续跑 checkpoint,跳过 search,直接恢复 recommend screen。");
1111
+ }
1112
+
1113
+ runtimeHooks.heartbeat("screen", lastAutoRecovery);
1114
+ const screenResult = await screenCli({
1115
+ workspaceRoot,
1116
+ screenParams: parsed.screenParams,
1117
+ pageScope: selectedPage,
1118
+ resume: currentResumeConfig,
1119
+ runtime: runtimeHooks.adapterRuntime("screen")
1120
+ });
1121
+ ensurePipelineNotAborted(runtimeHooks.signal);
1122
+ if (isProcessAbortError(screenResult.error)) {
1123
+ throw new PipelineAbortError(screenResult.error?.message || "推荐筛选已取消。");
1124
+ }
1125
+ if (screenResult.paused) {
1126
+ return buildPausedResponse("Recommend 流水线已暂停,可使用 resume 继续。", {
1127
+ selected_page: selectedPage,
1128
+ active_tab_status: activeTabStatus || null,
1129
+ search_params: effectiveSearchParams,
1130
+ screen_params: parsed.screenParams,
1131
+ selected_job: selectedJob,
1132
+ partial_result: screenResult.summary || screenResult.structured?.result || null
1133
+ });
1134
+ }
1135
+ if (!screenResult.ok) {
1136
+ const screenErrorCode = String(screenResult.error?.code || "");
1137
+ const partialScreenResult = screenResult.summary || screenResult.structured?.result || null;
1138
+ const resumeOutputCsv = normalizeText(partialScreenResult?.output_csv || currentResumeConfig.output_csv || "");
1139
+ const hasCheckpointForRecovery = Boolean(normalizeText(currentResumeConfig.checkpoint_path || ""));
1140
+ const screenPartialForRecovery = partialScreenResult
1141
+ ? {
1142
+ processed_count: partialScreenResult.processed_count ?? null,
1143
+ passed_count: partialScreenResult.passed_count ?? null,
1144
+ skipped_count: partialScreenResult.skipped_count ?? null,
1145
+ output_csv: partialScreenResult.output_csv || currentResumeConfig.output_csv || null,
1146
+ checkpoint_path: partialScreenResult.checkpoint_path || currentResumeConfig.checkpoint_path || null,
1147
+ completion_reason: partialScreenResult.completion_reason || null
1148
+ }
1149
+ : null;
1150
+ const isResumeCaptureRecovery = screenErrorCode === "RESUME_CAPTURE_FAILED_CONSECUTIVE_LIMIT";
1151
+ const isPageExhaustedRecovery = screenErrorCode === "TARGET_COUNT_NOT_REACHED_PAGE_EXHAUSTED";
1152
+ const isRecoverableScreenFailure = isResumeCaptureRecovery || isPageExhaustedRecovery;
1153
+ const canRecoverSafely = hasCheckpointForRecovery && Boolean(resumeOutputCsv);
1154
+ const hasRecoveryAttemptsRemaining = screenAutoRecoveryCount < MAX_SCREEN_AUTO_RECOVERY_ATTEMPTS;
1155
+
1156
+ if (isRecoverableScreenFailure && !canRecoverSafely) {
1157
+ return buildFailedResponse(
1158
+ "SCREEN_AUTO_RECOVERY_UNSAFE",
1159
+ "检测到 recommend 自动恢复触发,但缺少 checkpoint 或 output_csv,无法安全续跑。",
1160
+ {
1161
+ search_params: effectiveSearchParams,
1162
+ screen_params: parsed.screenParams,
1163
+ selected_job: selectedJob,
1164
+ partial_result: partialScreenResult,
1165
+ diagnostics: {
1166
+ debug_port: preflight.debug_port,
1167
+ stdout: screenResult.stdout?.slice(-1000),
1168
+ stderr: screenResult.stderr?.slice(-1000),
1169
+ result: screenResult.structured || null,
1170
+ auto_recovery: {
1171
+ trigger: screenErrorCode,
1172
+ attempt: screenAutoRecoveryCount,
1173
+ max_attempts: MAX_SCREEN_AUTO_RECOVERY_ATTEMPTS,
1174
+ original_recent_not_view: parsed.searchParams.recent_not_view,
1175
+ effective_recent_not_view: effectiveSearchParams.recent_not_view,
1176
+ partial_result: screenPartialForRecovery
1177
+ }
1178
+ }
1179
+ }
1180
+ );
1181
+ }
1182
+
1183
+ if (isRecoverableScreenFailure && !hasRecoveryAttemptsRemaining) {
1184
+ return buildFailedResponse(
1185
+ screenResult.error?.code || "RECOMMEND_SCREEN_FAILED",
1186
+ `${screenResult.error?.message || "推荐页筛选执行失败。"} 已达到自动恢复上限 ${MAX_SCREEN_AUTO_RECOVERY_ATTEMPTS} 次。`,
1187
+ {
1188
+ search_params: effectiveSearchParams,
1189
+ screen_params: parsed.screenParams,
1190
+ selected_job: selectedJob,
1191
+ partial_result: partialScreenResult,
1192
+ diagnostics: {
1193
+ debug_port: preflight.debug_port,
1194
+ stdout: screenResult.stdout?.slice(-1000),
1195
+ stderr: screenResult.stderr?.slice(-1000),
1196
+ result: screenResult.structured || null,
1197
+ auto_recovery: lastAutoRecovery
1198
+ }
1199
+ }
1200
+ );
1201
+ }
1202
+
1203
+ if (isRecoverableScreenFailure && canRecoverSafely && hasRecoveryAttemptsRemaining) {
1204
+ screenAutoRecoveryCount += 1;
1205
+ lastAutoRecovery = {
1206
+ trigger: screenErrorCode,
1207
+ attempt: screenAutoRecoveryCount,
1208
+ max_attempts: MAX_SCREEN_AUTO_RECOVERY_ATTEMPTS,
1209
+ original_recent_not_view: parsed.searchParams.recent_not_view,
1210
+ effective_recent_not_view: effectiveSearchParams.recent_not_view,
1211
+ partial_result: screenPartialForRecovery,
1212
+ page_exhaustion: screenResult.error?.page_exhaustion || null
1213
+ };
1214
+
1215
+ if (isPageExhaustedRecovery) {
1216
+ runtimeHooks.setStage(
1217
+ "screen_recovery",
1218
+ `推荐列表已到底但未达目标,开始自动补货(第 ${screenAutoRecoveryCount} 次):优先尝试页内刷新。`
1219
+ );
1220
+ runtimeHooks.heartbeat("screen_recovery", lastAutoRecovery);
1221
+
1222
+ const refreshResult = typeof refreshRecommendList === "function"
1223
+ ? await refreshRecommendList(workspaceRoot, {
1224
+ port: preflight.debug_port
1225
+ })
1226
+ : {
1227
+ ok: false,
1228
+ action: "in_page_refresh",
1229
+ state: "REFRESH_ADAPTER_MISSING",
1230
+ message: "缺少页内刷新适配器。"
1231
+ };
1232
+ ensurePipelineNotAborted(runtimeHooks.signal);
1233
+
1234
+ lastAutoRecovery = {
1235
+ ...lastAutoRecovery,
1236
+ refresh: refreshResult
1237
+ ? {
1238
+ ok: refreshResult.ok,
1239
+ state: refreshResult.state || null,
1240
+ message: refreshResult.message || null,
1241
+ before_state: refreshResult.before_state || null,
1242
+ after_state: refreshResult.after_state || null
1243
+ }
1244
+ : null
1245
+ };
1246
+
1247
+ if (refreshResult?.ok) {
1248
+ lastAutoRecovery = {
1249
+ ...lastAutoRecovery,
1250
+ action: "in_page_refresh"
1251
+ };
1252
+ currentResumeConfig = {
1253
+ checkpoint_path: currentResumeConfig.checkpoint_path || null,
1254
+ pause_control_path: currentResumeConfig.pause_control_path || null,
1255
+ output_csv: resumeOutputCsv || null,
1256
+ resume: true,
1257
+ require_checkpoint: true
1258
+ };
1259
+ shouldRunSearch = false;
1260
+ searchSummary = null;
1261
+ continue;
1262
+ }
1263
+
1264
+ runtimeHooks.setStage(
1265
+ "screen_recovery",
1266
+ `页内刷新不可用(${refreshResult?.state || "unknown"}),改为刷新 recommend 页面并重跑 search。`
1267
+ );
1268
+ runtimeHooks.heartbeat("screen_recovery", lastAutoRecovery);
1269
+ } else {
1270
+ const recoveryFailureText = selectedPage === "featured" ? "network 简历获取失败" : "截图失败";
1271
+ runtimeHooks.setStage(
1272
+ "screen_recovery",
1273
+ `screen 连续${recoveryFailureText},开始自动恢复(第 ${screenAutoRecoveryCount} 次):刷新 recommend 页面并重跑 search。`
1274
+ );
1275
+ runtimeHooks.heartbeat("screen_recovery", lastAutoRecovery);
1276
+ }
1277
+
1278
+ effectiveSearchParams = {
1279
+ ...effectiveSearchParams,
1280
+ recent_not_view: FORCED_RECENT_NOT_VIEW_ON_SCREEN_RECOVERY
1281
+ };
1282
+ lastAutoRecovery = {
1283
+ ...lastAutoRecovery,
1284
+ action: "reload_page_and_rerun_search",
1285
+ effective_recent_not_view: effectiveSearchParams.recent_not_view
1286
+ };
1287
+
1288
+ const reloadResult = typeof reloadRecommendPage === "function"
1289
+ ? await reloadRecommendPage(workspaceRoot, {
1290
+ port: preflight.debug_port
1291
+ })
1292
+ : null;
1293
+ ensurePipelineNotAborted(runtimeHooks.signal);
1294
+
1295
+ lastAutoRecovery = {
1296
+ ...lastAutoRecovery,
1297
+ reload: reloadResult
1298
+ ? {
1299
+ ok: reloadResult.ok,
1300
+ state: reloadResult.state || null,
1301
+ message: reloadResult.message || null,
1302
+ reloaded_url: reloadResult.reloaded_url || null
1303
+ }
1304
+ : null
1305
+ };
1306
+
1307
+ const recoveryPageCheck = await ensureRecommendPageReady(workspaceRoot, {
1308
+ port: preflight.debug_port
1309
+ });
1310
+ ensurePipelineNotAborted(runtimeHooks.signal);
1311
+ if (!recoveryPageCheck.ok) {
1312
+ const guidance = buildChromeSetupGuidance({
1313
+ debugPort: preflight.debug_port,
1314
+ pageState: recoveryPageCheck.page_state
1315
+ });
1316
+ return buildFailedResponse(
1317
+ recoveryPageCheck.state === "LOGIN_REQUIRED" || recoveryPageCheck.state === "LOGIN_REQUIRED_AFTER_REDIRECT"
1318
+ ? "BOSS_LOGIN_REQUIRED"
1319
+ : recoveryPageCheck.state === "DEBUG_PORT_UNREACHABLE"
1320
+ ? "BOSS_CHROME_NOT_CONNECTED"
1321
+ : "BOSS_RECOMMEND_PAGE_NOT_READY",
1322
+ "自动恢复时无法重新就绪 recommend 页面,请先处理页面状态后再继续。",
1323
+ {
1324
+ search_params: effectiveSearchParams,
1325
+ screen_params: parsed.screenParams,
1326
+ selected_job: selectedJob,
1327
+ partial_result: partialScreenResult,
1328
+ required_user_action: "prepare_boss_recommend_page",
1329
+ guidance,
1330
+ diagnostics: {
1331
+ debug_port: preflight.debug_port,
1332
+ page_state: recoveryPageCheck.page_state,
1333
+ stdout: screenResult.stdout?.slice(-1000),
1334
+ stderr: screenResult.stderr?.slice(-1000),
1335
+ result: screenResult.structured || null,
1336
+ auto_recovery: lastAutoRecovery
1337
+ }
1338
+ }
1339
+ );
1340
+ }
1341
+
1342
+ currentResumeConfig = {
1343
+ checkpoint_path: currentResumeConfig.checkpoint_path || null,
1344
+ pause_control_path: currentResumeConfig.pause_control_path || null,
1345
+ output_csv: resumeOutputCsv || null,
1346
+ resume: true,
1347
+ require_checkpoint: true
1348
+ };
1349
+ shouldRunSearch = true;
1350
+ searchSummary = null;
1351
+ continue;
1352
+ }
1353
+
1354
+ return buildFailedResponse(
1355
+ screenResult.error?.code || "RECOMMEND_SCREEN_FAILED",
1356
+ screenResult.error?.message || "推荐页筛选执行失败。",
1357
+ {
1358
+ search_params: effectiveSearchParams,
1359
+ screen_params: parsed.screenParams,
1360
+ selected_job: selectedJob,
1361
+ partial_result: partialScreenResult,
1362
+ diagnostics: {
1363
+ debug_port: preflight.debug_port,
1364
+ stdout: screenResult.stdout?.slice(-1000),
1365
+ stderr: screenResult.stderr?.slice(-1000),
1366
+ result: screenResult.structured || null,
1367
+ auto_recovery: lastAutoRecovery
1368
+ }
1369
+ }
1370
+ );
1371
+ }
1372
+
1373
+ runtimeHooks.setStage("finalize", "screen 完成,正在汇总结果。");
1374
+ runtimeHooks.heartbeat("finalize");
1375
+ const durationSec = Math.max(1, Math.round((Date.now() - startedAt) / 1000));
1376
+ const finalSearchSummary = searchSummary || {};
1377
+ const screenSummary = screenResult.summary || {};
1378
+ const resolvedActiveTabStatus = normalizeText(
1379
+ screenSummary.active_tab_status
1380
+ || finalSearchSummary.active_tab_status
1381
+ || activeTabStatus
1382
+ || selectedTabStatus
1383
+ ) || selectedTabStatus;
1384
+ const resolvedSelectedPage = normalizePageScope(
1385
+ screenSummary.selected_page
1386
+ || finalSearchSummary.selected_page
1387
+ || selectedPage
1388
+ || tabStatusToPageScope(resolvedActiveTabStatus)
1389
+ ) || selectedPage;
1390
+ const resolvedResumeSourceRaw = normalizeText(screenSummary.resume_source || "").toLowerCase();
1391
+ const resolvedResumeSource = resolvedResumeSourceRaw === "network"
1392
+ ? "network"
1393
+ : resolvedSelectedPage === "featured"
1394
+ ? "network"
1395
+ : "image_fallback";
1396
+ runtimeHooks.progress("finalize", {
1397
+ processed: screenSummary.processed_count ?? 0,
1398
+ passed: screenSummary.passed_count ?? 0,
1399
+ skipped: screenSummary.skipped_count ?? 0,
1400
+ greet_count: screenSummary.greet_count ?? 0
1401
+ });
1402
+
1403
+ return {
1404
+ status: "COMPLETED",
1405
+ search_params: effectiveSearchParams,
1406
+ screen_params: parsed.screenParams,
1407
+ result: {
1408
+ candidate_count: finalSearchSummary.candidate_count ?? null,
1409
+ applied_filters: finalSearchSummary.applied_filters || effectiveSearchParams,
1410
+ processed_count: screenSummary.processed_count ?? 0,
1411
+ passed_count: screenSummary.passed_count ?? 0,
1412
+ skipped_count: screenSummary.skipped_count ?? 0,
1413
+ duration_sec: durationSec,
1414
+ output_csv: screenSummary.output_csv || null,
1415
+ completion_reason: screenSummary.completion_reason || "screen_completed",
1416
+ page_state: finalSearchSummary.page_state || pageCheck.page_state,
1417
+ selected_job: finalSearchSummary.selected_job || selectedJob,
1418
+ selected_page: resolvedSelectedPage,
1419
+ active_tab_status: resolvedActiveTabStatus,
1420
+ resume_source: resolvedResumeSource,
1421
+ post_action: parsed.screenParams.post_action,
1422
+ max_greet_count: parsed.screenParams.max_greet_count,
1423
+ greet_count: screenSummary.greet_count ?? 0,
1424
+ greet_limit_fallback_count: screenSummary.greet_limit_fallback_count ?? 0,
1425
+ auto_recovery: lastAutoRecovery
1426
+ },
1427
+ message: parsed.screenParams.post_action === "none"
1428
+ ? "Recommend 流水线已完成。本次 post_action=none:符合条件的人选仅记录到 CSV,不执行收藏或打招呼。"
1429
+ : "Recommend 流水线已完成。post_action 在运行开始时已一次性确认;若选择打招呼并设置上限,超出上限后会自动改为收藏。"
1430
+ };
1431
+ }
1432
+ }