// 进程层:日志开关、启动横幅、崩溃重启循环、退出码。 // // 一次会话(session.mjs)只管一个浏览器进程;这里管「崩了就重来」以及「什么情况该放弃」。 // 重试等待递增:15s → 30s → 45s …,上限 120s,避免持续失败时疯狂刷 CDP 端口。 import { sleep } from './cdp.mjs'; import { cleanStaleSingleton } from './browser.mjs'; import { runSession, disposeActiveSession } from './session.mjs'; import { openLog } from './log.mjs'; import { noDisplayReason, platformName } from './platform.mjs'; const RETRY_BASE_MS = 15000; const RETRY_MAX_MS = 120000; /** * @param {object} o * @param {object} o.cfg * @param {string} o.binary * @param {string} o.scriptSrc * @param {object} o.stop * @param {Function} o.log / o.warn / o.error */ export async function runSupervisor(o) { const { cfg, stop } = o; const log = o.log, warn = o.warn, error = o.error; // 自检不写文件日志:避免每次 --check 都改仓库内容 if (!cfg.CHECK_ONLY) openLog(cfg.LOG_FILE, cfg.LOG_MAX_BYTES); log('=== 云学堂助手 · 无头运行器' + (cfg.CHECK_ONLY ? '(自检)' : '') + ' 启动 ==='); log('Node ' + process.version + ' ' + platformName + '/' + process.arch); log('配置 ' + (cfg.CONFIG_FILE || '(未找到 config/runner.config.mjs,使用内置默认值)')); log('浏览器 ' + o.binary); log('profile ' + cfg.PROFILE_DIR + '(cookie / localStorage 持久化,删掉即重置登录态与进度缓存)'); if (cfg.WANT_VISIBLE && !cfg.VISIBLE) { warn(noDisplayReason() + ',配置里的 headless: false 被忽略,强制无头运行。'); } if (!cfg.CHECK_ONLY) { log('日志 ' + cfg.LOG_FILE + '(' + (process.platform === 'win32' ? 'Ctrl+C 结束' : 'Ctrl+C 结束') + ')'); } let attempt = 0; let last = null; while (!stop.stopping) { attempt++; if (attempt > 1) log('--- 第 ' + attempt + ' 次尝试 ---'); try { last = await runSession({ ...o, cfg }); if (stop.stopping) break; if (cfg.CHECK_ONLY) break; // 正常结束:只有「脚本自己停了 / 无进展」且配了重启间隔才再来一轮 const restartable = !last.limitReached && cfg.RESTART_MINUTES > 0; if (!restartable) break; log('按 YUN_XUE_TANG_RESTART_MINUTES=' + cfg.RESTART_MINUTES + ' 等待后重新开始…'); const until = Date.now() + cfg.RESTART_MINUTES * 60000; while (!stop.stopping && Date.now() < until) await sleep(2000); if (stop.stopping) break; cleanStaleSingleton(cfg.PROFILE_DIR); } catch (e) { if (stop.stopping) break; // 会话抛错时内部的收尾代码已被跳过,这里补上:否则浏览器进程会残留、端口被占 await disposeActiveSession(); error('会话异常:' + (e && e.message ? e.message : e)); // 连登 5 次失败基本都是密码错 / 要验证码,重试没意义,直接用专门的退出码结束 if (e && e.message && /连续 \d+ 次登录失败/.test(e.message)) { return { exitCode: 3, last }; } const waitMs = Math.min(RETRY_BASE_MS * attempt, RETRY_MAX_MS); warn('浏览器/连接异常,' + Math.round(waitMs / 1000) + ' 秒后重试(第 ' + attempt + ' 次)'); await sleep(waitMs); } } log('=== 运行器退出 ==='); if (cfg.CHECK_ONLY) return { exitCode: last && last.ok ? 0 : 1, last }; // 0 = 正常收尾(达到上限 / 预算 / 无更多课程);1 = 无进展卡死 if (last && /没有任何进展/.test(last.finishReason || '')) return { exitCode: 1, last }; return { exitCode: 0, last }; }