@capyclaw/browser-suite 0.1.2 → 0.2.37
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/LICENSE +21 -0
- package/README.md +9 -5
- package/composition.lock.json +37 -25
- package/contract/browser-contract.json +484 -25
- package/cordis.patch.yml +3 -9
- package/dsh-suite.json +110 -82
- package/lib/index.mjs +1 -1
- package/node_modules/@capyclaw/asset-service/README.md +48 -0
- package/node_modules/@capyclaw/asset-service/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/asset-service/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/asset-service/lib/host.mjs +14 -0
- package/node_modules/@capyclaw/asset-service/package.json +59 -0
- package/node_modules/@capyclaw/asset-service/src/index.mjs +304 -0
- package/node_modules/@capyclaw/browser-skill-api/README.md +3 -0
- package/node_modules/@capyclaw/browser-skill-api/contract/browser-contract.json +1349 -0
- package/node_modules/@capyclaw/browser-skill-api/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/browser-skill-api/package.json +49 -0
- package/node_modules/@capyclaw/browser-skill-api/plugin.mjs +15 -0
- package/node_modules/@capyclaw/browser-skill-api/skills/browser-api/SKILL.md +85 -0
- package/node_modules/@capyclaw/browser-skill-api/skills/browser-api/references/tool-contract.md +692 -0
- package/node_modules/@capyclaw/browser-skill-browser/README.md +3 -0
- package/node_modules/@capyclaw/browser-skill-browser/contract/browser-contract.json +1349 -0
- package/node_modules/@capyclaw/browser-skill-browser/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/browser-skill-browser/package.json +49 -0
- package/node_modules/@capyclaw/browser-skill-browser/plugin.mjs +15 -0
- package/node_modules/@capyclaw/browser-skill-browser/skills/browser/SKILL.md +27 -0
- package/node_modules/@capyclaw/browser-skill-ops/README.md +3 -0
- package/node_modules/@capyclaw/browser-skill-ops/contract/browser-contract.json +1349 -0
- package/node_modules/@capyclaw/browser-skill-ops/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/browser-skill-ops/package.json +49 -0
- package/node_modules/@capyclaw/browser-skill-ops/plugin.mjs +15 -0
- package/node_modules/@capyclaw/browser-skill-ops/skills/browser-ops/SKILL.md +63 -0
- package/node_modules/@capyclaw/browser-workbench/README.md +89 -0
- package/node_modules/@capyclaw/browser-workbench/contract/browser-contract.json +1349 -0
- package/node_modules/@capyclaw/browser-workbench/demo/form.html +112 -0
- package/node_modules/@capyclaw/browser-workbench/lib/host.mjs +1 -0
- package/node_modules/@capyclaw/browser-workbench/package.json +71 -0
- package/node_modules/@capyclaw/browser-workbench/plugin.mjs +1 -0
- package/node_modules/@capyclaw/browser-workbench/server/constants.mjs +16 -0
- package/node_modules/@capyclaw/browser-workbench/server/contract-snapshots.mjs +81 -0
- package/node_modules/@capyclaw/browser-workbench/server/contract.mjs +24 -0
- package/node_modules/@capyclaw/browser-workbench/server/embedded-host.mjs +247 -0
- package/node_modules/@capyclaw/browser-workbench/server/engine.mjs +2466 -0
- package/node_modules/@capyclaw/browser-workbench/server/governor.mjs +189 -0
- package/node_modules/@capyclaw/browser-workbench/server/http-utils.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/human.mjs +628 -0
- package/node_modules/@capyclaw/browser-workbench/server/infra/http.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/infra/tuning.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/input.mjs +154 -0
- package/node_modules/@capyclaw/browser-workbench/server/login-vault.mjs +109 -0
- package/node_modules/@capyclaw/browser-workbench/server/mcp/handler.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/mcp/instructions.mjs +31 -0
- package/node_modules/@capyclaw/browser-workbench/server/orphans.mjs +163 -0
- package/node_modules/@capyclaw/browser-workbench/server/relay.mjs +198 -0
- package/node_modules/@capyclaw/browser-workbench/server/routes/api.mjs +233 -0
- package/node_modules/@capyclaw/browser-workbench/server/routes/assets.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/routes/mcp.mjs +17 -0
- package/node_modules/@capyclaw/browser-workbench/server/routes/workbench.mjs +33 -0
- package/node_modules/@capyclaw/browser-workbench/server/session-engines.mjs +223 -0
- package/node_modules/@capyclaw/browser-workbench/server/shared/SHARED_MANIFEST.json +70 -0
- package/node_modules/@capyclaw/browser-workbench/server/shared/asset-service.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/shared/editor-host.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/shared/kit/editor/lease.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/shared/kit/service/api.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/shared/kit/service/http.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/shared/kit/service/mcp-http.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/shared/kit/tools/validate.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/shared/kit/tuning.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/shared/kit/util/fs-lock.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/shared/service-host.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/shared/tool-host.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/shared/tuning.mjs +2 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/capabilities/contract.mjs +55 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/capabilities/evaluate.mjs +36 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/capabilities/index.mjs +26 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/capabilities/interaction.mjs +215 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/capabilities/navigation.mjs +35 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/capabilities/screenshot.mjs +50 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/capabilities/session.mjs +81 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/capabilities/snapshot.mjs +30 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/capabilities/tabs.mjs +35 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/index.mjs +12 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/kernel/define.mjs +5 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/kernel/output.mjs +30 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/kernel/ports.mjs +59 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools/kernel/registry.mjs +17 -0
- package/node_modules/@capyclaw/browser-workbench/server/tools.mjs +3 -0
- package/node_modules/@capyclaw/browser-workbench/server/workbench-framework.mjs +305 -0
- package/node_modules/@capyclaw/browser-workbench/ui/app.js +447 -0
- package/node_modules/@capyclaw/browser-workbench/ui/index.html +46 -0
- package/node_modules/@capyclaw/browser-workbench/ui/style.css +144 -0
- package/node_modules/@capyclaw/document-workbench/README.md +125 -0
- package/node_modules/@capyclaw/document-workbench/package.json +44 -0
- package/node_modules/@capyclaw/document-workbench/src/bridge/index.mjs +321 -0
- package/node_modules/@capyclaw/document-workbench/src/client/index.mjs +625 -0
- package/node_modules/@capyclaw/document-workbench/src/client/screenshot.mjs +98 -0
- package/node_modules/@capyclaw/document-workbench/src/index.mjs +9 -0
- package/node_modules/@capyclaw/document-workbench/src/model/audit.mjs +101 -0
- package/node_modules/@capyclaw/document-workbench/src/model/conformance.mjs +92 -0
- package/node_modules/@capyclaw/document-workbench/src/model/ids.mjs +56 -0
- package/node_modules/@capyclaw/document-workbench/src/model/index.mjs +18 -0
- package/node_modules/@capyclaw/document-workbench/src/model/locate.mjs +118 -0
- package/node_modules/@capyclaw/document-workbench/src/model/manifest.mjs +148 -0
- package/node_modules/@capyclaw/document-workbench/src/model/ops.mjs +160 -0
- package/node_modules/@capyclaw/document-workbench/src/model/validate.mjs +72 -0
- package/node_modules/@capyclaw/document-workbench/src/ops/index.mjs +93 -0
- package/node_modules/@capyclaw/document-workbench/src/session/context.mjs +103 -0
- package/node_modules/@capyclaw/document-workbench/src/session/index.mjs +394 -0
- package/node_modules/@capyclaw/document-workbench/src/session/lease.mjs +105 -0
- package/node_modules/@capyclaw/document-workbench/src/session/mode.mjs +80 -0
- package/node_modules/@capyclaw/document-workbench/src/session/sanitize.mjs +107 -0
- package/node_modules/@capyclaw/document-workbench/src/session/state.mjs +159 -0
- package/node_modules/@capyclaw/document-workbench/src/session/watch.mjs +63 -0
- package/node_modules/@capyclaw/document-workbench/src/store/file-backend.mjs +158 -0
- package/node_modules/@capyclaw/document-workbench/src/testing/index.mjs +75 -0
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +139 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/node_modules/@capyclaw/portal/README.md +70 -0
- package/node_modules/@capyclaw/portal/lib/index.mjs +387 -0
- package/node_modules/@capyclaw/portal/lib/ledger.mjs +194 -0
- package/node_modules/@capyclaw/portal/lib/portal-agent.ps1 +811 -0
- package/node_modules/@capyclaw/portal/lib/portal-darwin.mjs +183 -0
- package/node_modules/@capyclaw/portal/package.json +40 -0
- package/node_modules/@capyclaw/service-broker/README.md +104 -0
- package/node_modules/@capyclaw/service-broker/cordis.patch.yml +8 -0
- package/node_modules/@capyclaw/service-broker/dsh-suite.json +21 -0
- package/node_modules/@capyclaw/service-broker/lib/control.mjs +193 -0
- package/node_modules/@capyclaw/service-broker/lib/discovery.mjs +109 -0
- package/node_modules/@capyclaw/service-broker/lib/engine.mjs +1236 -0
- package/node_modules/@capyclaw/service-broker/lib/host.mjs +182 -0
- package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +249 -0
- package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +325 -0
- package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +28 -0
- package/node_modules/@capyclaw/service-broker/lib/spec.mjs +78 -0
- package/node_modules/@capyclaw/service-broker/package.json +65 -0
- package/node_modules/@capyclaw/service-broker/server.mjs +81 -0
- package/node_modules/@capyclaw/service-broker/service.schema.json +62 -0
- package/node_modules/@capyclaw/service-broker/services.json +3 -0
- package/node_modules/@capyclaw/service-host/README.md +86 -0
- package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
- package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
- package/node_modules/@capyclaw/service-host/package.json +60 -0
- package/node_modules/@capyclaw/service-host/src/index.mjs +571 -0
- package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
- package/node_modules/@capyclaw/tool-host/README.md +56 -0
- package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
- package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
- package/node_modules/@capyclaw/tool-host/lib/host.mjs +16 -0
- package/node_modules/@capyclaw/tool-host/package.json +59 -0
- package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
- package/node_modules/@capyclaw/tool-host/src/index.mjs +416 -0
- package/package.json +31 -14
- package/services.json +1 -21
|
@@ -0,0 +1,2466 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 浏览器引擎控制器:Playwright 持久化上下文 + ref 快照交互。
|
|
3
|
+
*
|
|
4
|
+
* 设计口径(借鉴 Playwright MCP / dsh-playwright-browser,能力自建):
|
|
5
|
+
* - 懒启动:第一次导航才拉起浏览器;探测链 playwright chromium 缓存
|
|
6
|
+
* → msedge → chrome,全失败给结构化错误与安装提示。
|
|
7
|
+
* - 基础默认有头(headless:false,standalone 调试看得见点击/打字);嵌入主区时
|
|
8
|
+
* relay 把形态默认改为无头(主区即实时镜像,零弹窗),登录态持久化
|
|
9
|
+
* (userDataDir 落 hostDir/profile,跨重启保留 cookie)。
|
|
10
|
+
* - snapshot + ref:快照是「可交互元素 + 结构节点」的缩进文本树,每个
|
|
11
|
+
* 元素带 ref=eN;动作引用 ref,不猜 CSS 选择器;ref 过期报
|
|
12
|
+
* STALE_SNAPSHOT,重新 browser_snapshot 即可。
|
|
13
|
+
* - 动作串行化:浏览器单线程语义,所有动作走互斥队列。
|
|
14
|
+
* - 安全默认:仅 http(s)、拒绝带凭据 URL、browser_evaluate 默认关闭
|
|
15
|
+
* (allowEvaluate 开启),页面内容视为不可信数据。
|
|
16
|
+
*
|
|
17
|
+
* 本模块只依赖 playwright 与 node 内置模块,可独立单测(纯函数)与注入测试。
|
|
18
|
+
*/
|
|
19
|
+
import fs from 'node:fs'
|
|
20
|
+
import path from 'node:path'
|
|
21
|
+
import { createRequire } from 'node:module'
|
|
22
|
+
import { createProcessOps, reapOrphanBrowsers, isProfileLockError } from './orphans.mjs'
|
|
23
|
+
import { mulberry32, randInt, resolveHumanProfile, bezierPath, moveDurationMs, moveDelays, typingPlan, scrollPlan, stealthInitScript, uaClientHints } from './human.mjs'
|
|
24
|
+
import { openInput, closeInput } from './input.mjs'
|
|
25
|
+
import { readVault, writeVault, vaultSummary } from './login-vault.mjs'
|
|
26
|
+
import { createGovernor } from './governor.mjs'
|
|
27
|
+
|
|
28
|
+
/* --------------------------------------------------------------------------
|
|
29
|
+
* 配置解析(纯函数,可单测)
|
|
30
|
+
* ------------------------------------------------------------------------ */
|
|
31
|
+
|
|
32
|
+
export const ENGINE_CONFIG_DEFAULTS = Object.freeze({
|
|
33
|
+
headless: false,
|
|
34
|
+
allowEvaluate: false,
|
|
35
|
+
channel: '',
|
|
36
|
+
executablePath: '',
|
|
37
|
+
navigationTimeoutMs: 30000,
|
|
38
|
+
actionTimeoutMs: 15000,
|
|
39
|
+
maxSnapshotChars: 40000,
|
|
40
|
+
viewportWidth: 1280,
|
|
41
|
+
viewportHeight: 800,
|
|
42
|
+
/* 实时画面(工作台 /api/live)的 JPEG 质量:帧要走 SSE,压太小看不清,压太大
|
|
43
|
+
又会被 loopback 带宽和前端解码拖慢;60 是 1280×800 下肉眼无损的实用点。 */
|
|
44
|
+
screencastQuality: 60,
|
|
45
|
+
/* 资源回收:空闲多久没人用就挂起浏览器(释放进程,保留 profile 与标签日志),
|
|
46
|
+
0 = 关闭空闲回收。下次该会话再有动作时懒重启并恢复标签页。 */
|
|
47
|
+
idleTimeoutMs: 1800000,
|
|
48
|
+
/* 同时最多跑几个浏览器进程(LRU 上限):超了就把最久未用的挂起。0 = 不限。 */
|
|
49
|
+
maxRunningEngines: 6,
|
|
50
|
+
/* 回收巡检周期:多久扫一次空闲/超限引擎。 */
|
|
51
|
+
reapIntervalMs: 30000,
|
|
52
|
+
/* 重启后是否恢复上次的标签页(落盘在 <hostDir>/tabs.json)。 */
|
|
53
|
+
restoreTabs: true,
|
|
54
|
+
/* 恢复上限:只恢复最近 N 个标签页(0 = 全部)。**不限制新开**,只给恢复这条启动
|
|
55
|
+
关键路径封顶:每页串行 goto 各等一次导航超时,N 大了会让回收后第一个工具调用卡
|
|
56
|
+
几分钟,内存也按 N 个渲染进程堆。落盘时同样按 N 裁剪,旧的超大 tabs.json 自愈。 */
|
|
57
|
+
maxRestoreTabs: 8,
|
|
58
|
+
/* 孤儿进程兜底:启动前清扫父进程已死的残留浏览器;撞 profile 锁时强清重试。 */
|
|
59
|
+
reapOrphans: true,
|
|
60
|
+
/* 启动兜底超时:单次 launchPersistentContext 超过它就判失败换下一候选,
|
|
61
|
+
防止驱动/杀毒/坏 profile 把启动挂死、进而卡死整条动作队列。0 = 不限。 */
|
|
62
|
+
launchTimeoutMs: 60000,
|
|
63
|
+
/* 关闭兜底超时:挂起/重置时 saveVault 与 ctx.close 各自的上限;超时后强杀
|
|
64
|
+
占用本 profile 的进程兜底,保证回收巡检/停服不会被一个卡死的浏览器拖住。0 = 不限。 */
|
|
65
|
+
shutdownTimeoutMs: 15000,
|
|
66
|
+
/* 截图保留上限:screenshots 目录只留最近 N 张 shot-*.png,旧的自动删。
|
|
67
|
+
截图是落盘产物,无上限会在长会话里无限吃磁盘。0 = 不清理。 */
|
|
68
|
+
maxScreenshotFiles: 200,
|
|
69
|
+
/* 礼貌调度器主机状态 TTL:闲置域名条目过期修剪,防 hosts 表无界增长。0 = 不修剪。 */
|
|
70
|
+
hostTtlMs: 600000,
|
|
71
|
+
/* 登录态保险箱:把 cookie 存到会话目录之外(sessions/login-vault),新会话/重启后注回去。
|
|
72
|
+
profile 本身不共享(Chrome 有进程级锁),只共享 cookie——这样「换个会话就掉登录」不再发生。 */
|
|
73
|
+
loginVault: true,
|
|
74
|
+
/* 拟人操作:鼠标走贝塞尔轨迹 + 最小急动度 + 微颤、按键带高斯抖动与词间停顿、
|
|
75
|
+
滚轮分多次动量衰减、点击按住几十毫秒。代价是每个动作多 20–60ms。
|
|
76
|
+
速度优先时设 DSH_BROWSER_HUMANIZE=false(动作回到 5–20ms)。 */
|
|
77
|
+
humanize: true,
|
|
78
|
+
/* 拟人档位:fast(默认,动作 ~25ms/字符)/ normal(~90ms,过行为风控)/ careful(~185ms)。
|
|
79
|
+
normal/careful 的鼠标轨迹按真实时间间隔逐点送达(fast 为速度批量同帧发)。 */
|
|
80
|
+
humanizeProfile: 'fast',
|
|
81
|
+
/* 点击按住时长下限(ms):0 = 用档位默认(fast 档 1–4ms 等于同帧按下松开)。
|
|
82
|
+
行为风控对「按下即松开」敏感时,设 60–120 模拟真人点击按住时长。 */
|
|
83
|
+
minClickHoldMs: 0,
|
|
84
|
+
/* 反自动化指纹补丁:navigator.webdriver、chrome.runtime、plugins、WebGL 厂商串等。 */
|
|
85
|
+
stealth: true,
|
|
86
|
+
/* 可选驱动:'patchright'(Playwright 的 stealth 分支,需要自行安装)。默认用 playwright。 */
|
|
87
|
+
stealthDriver: '',
|
|
88
|
+
/* 礼貌调度:每主机导航间隔+抖动、跨会话导航并发上限、429/风控指数退避、每引擎动作限速。
|
|
89
|
+
把「像攻击的突发流量形状」在引擎侧消掉,降低触发人机验证/被判爬虫的概率。
|
|
90
|
+
DSH_BROWSER_POLITE=false 关闭(回到无间隔直发)。 */
|
|
91
|
+
polite: true,
|
|
92
|
+
navGapMs: 900,
|
|
93
|
+
navGapJitterMs: 400,
|
|
94
|
+
maxConcurrentNav: 2,
|
|
95
|
+
actionRate: 8,
|
|
96
|
+
backoffBaseMs: 4000,
|
|
97
|
+
backoffMaxMs: 60000,
|
|
98
|
+
})
|
|
99
|
+
|
|
100
|
+
const ENV_FIELDS = [
|
|
101
|
+
['DSH_BROWSER_HEADLESS', 'headless', 'boolean'],
|
|
102
|
+
['DSH_BROWSER_ALLOW_EVALUATE', 'allowEvaluate', 'boolean'],
|
|
103
|
+
['DSH_BROWSER_CHANNEL', 'channel', 'string'],
|
|
104
|
+
['DSH_BROWSER_EXECUTABLE_PATH', 'executablePath', 'string'],
|
|
105
|
+
['DSH_BROWSER_NAV_TIMEOUT_MS', 'navigationTimeoutMs', 'number'],
|
|
106
|
+
['DSH_BROWSER_ACTION_TIMEOUT_MS', 'actionTimeoutMs', 'number'],
|
|
107
|
+
['DSH_BROWSER_MAX_SNAPSHOT_CHARS', 'maxSnapshotChars', 'number'],
|
|
108
|
+
['DSH_BROWSER_VIEWPORT_W', 'viewportWidth', 'number'],
|
|
109
|
+
['DSH_BROWSER_VIEWPORT_H', 'viewportHeight', 'number'],
|
|
110
|
+
['DSH_BROWSER_SCREENCAST_QUALITY', 'screencastQuality', 'number'],
|
|
111
|
+
['DSH_BROWSER_IDLE_TIMEOUT_MS', 'idleTimeoutMs', 'number'],
|
|
112
|
+
['DSH_BROWSER_MAX_ENGINES', 'maxRunningEngines', 'number'],
|
|
113
|
+
['DSH_BROWSER_REAP_INTERVAL_MS', 'reapIntervalMs', 'number'],
|
|
114
|
+
['DSH_BROWSER_RESTORE_TABS', 'restoreTabs', 'boolean'],
|
|
115
|
+
['DSH_BROWSER_MAX_RESTORE_TABS', 'maxRestoreTabs', 'number'],
|
|
116
|
+
['DSH_BROWSER_REAP_ORPHANS', 'reapOrphans', 'boolean'],
|
|
117
|
+
['DSH_BROWSER_LAUNCH_TIMEOUT_MS', 'launchTimeoutMs', 'number'],
|
|
118
|
+
['DSH_BROWSER_SHUTDOWN_TIMEOUT_MS', 'shutdownTimeoutMs', 'number'],
|
|
119
|
+
['DSH_BROWSER_MAX_SCREENSHOT_FILES', 'maxScreenshotFiles', 'number'],
|
|
120
|
+
['DSH_BROWSER_HOST_TTL_MS', 'hostTtlMs', 'number'],
|
|
121
|
+
['DSH_BROWSER_LOGIN_VAULT', 'loginVault', 'boolean'],
|
|
122
|
+
['DSH_BROWSER_HUMANIZE', 'humanize', 'boolean'],
|
|
123
|
+
['DSH_BROWSER_HUMANIZE_PROFILE', 'humanizeProfile', 'string'],
|
|
124
|
+
['DSH_BROWSER_MIN_CLICK_HOLD_MS', 'minClickHoldMs', 'number'],
|
|
125
|
+
['DSH_BROWSER_STEALTH', 'stealth', 'boolean'],
|
|
126
|
+
['DSH_BROWSER_STEALTH_DRIVER', 'stealthDriver', 'string'],
|
|
127
|
+
['DSH_BROWSER_POLITE', 'polite', 'boolean'],
|
|
128
|
+
['DSH_BROWSER_NAV_GAP_MS', 'navGapMs', 'number'],
|
|
129
|
+
['DSH_BROWSER_NAV_GAP_JITTER_MS', 'navGapJitterMs', 'number'],
|
|
130
|
+
['DSH_BROWSER_MAX_CONCURRENT_NAV', 'maxConcurrentNav', 'number'],
|
|
131
|
+
['DSH_BROWSER_ACTION_RATE', 'actionRate', 'number'],
|
|
132
|
+
['DSH_BROWSER_BACKOFF_BASE_MS', 'backoffBaseMs', 'number'],
|
|
133
|
+
['DSH_BROWSER_BACKOFF_MAX_MS', 'backoffMaxMs', 'number'],
|
|
134
|
+
]
|
|
135
|
+
|
|
136
|
+
/* 这几个数字字段允许 0(idleTimeoutMs=0 禁用空闲回收;maxRunningEngines=0 不限;
|
|
137
|
+
maxRestoreTabs=0 恢复全部;navGapMs=0 无间隔;maxConcurrentNav=0 不限并发;
|
|
138
|
+
actionRate=0 不限动作速率;launchTimeoutMs/shutdownTimeoutMs=0 不限时;
|
|
139
|
+
maxScreenshotFiles=0 不清理截图;hostTtlMs=0 不修剪主机表;minClickHoldMs=0 用档位默认按住时长)。
|
|
140
|
+
其余数字字段仍要求 >0(0 超时 / 0 视口 / 0 巡检周期无意义)。 */
|
|
141
|
+
const ZERO_OK_NUMBER_FIELDS = new Set(['idleTimeoutMs', 'maxRunningEngines', 'maxRestoreTabs', 'navGapMs', 'maxConcurrentNav', 'actionRate', 'launchTimeoutMs', 'shutdownTimeoutMs', 'maxScreenshotFiles', 'hostTtlMs', 'minClickHoldMs'])
|
|
142
|
+
|
|
143
|
+
/** 环境变量 + 显式覆盖 → 引擎配置(默认值兜底)。 */
|
|
144
|
+
export function resolveEngineConfig(env = process.env, overrides = {}) {
|
|
145
|
+
const cfg = { ...ENGINE_CONFIG_DEFAULTS }
|
|
146
|
+
for (const [key, field, type] of ENV_FIELDS) {
|
|
147
|
+
const raw = env[key]
|
|
148
|
+
if (raw === undefined || raw === '') continue
|
|
149
|
+
if (type === 'boolean') cfg[field] = /^(1|true|yes)$/i.test(String(raw))
|
|
150
|
+
else if (type === 'number') {
|
|
151
|
+
const num = Number(raw)
|
|
152
|
+
const ok = Number.isFinite(num) && (num > 0 || (num === 0 && ZERO_OK_NUMBER_FIELDS.has(field)))
|
|
153
|
+
if (ok) cfg[field] = Math.floor(num)
|
|
154
|
+
} else cfg[field] = String(raw)
|
|
155
|
+
}
|
|
156
|
+
for (const [field, value] of Object.entries(overrides || {})) {
|
|
157
|
+
if (value === undefined || value === null || value === '') continue
|
|
158
|
+
cfg[field] = value
|
|
159
|
+
}
|
|
160
|
+
return cfg
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* 有头/无头裁决(纯函数,可单测)。
|
|
165
|
+
* 嵌入式(有 serviceHost,挂主区)**强制无头**:用户契约「浏览器只在主区镜像、不弹外部
|
|
166
|
+
* 窗口」(2026-11-17 用户明确要求)。有头偏好(<hostDir>/engine.json headless:false)在
|
|
167
|
+
* 嵌入式不再生效 —— 否则下次重启就在主区外弹真 Chrome 窗,正是报障场景;登录/验证码走
|
|
168
|
+
* 主区实时镜像 + /api/input 回放,不需要真窗口。显式环境变量 DSH_BROWSER_HEADLESS 保留
|
|
169
|
+
* 作调试逃生口(两种形态都认)。
|
|
170
|
+
* standalone(无 serviceHost,开发/调试)保持旧优先级:偏好 > cordis 配置 > 默认有头。
|
|
171
|
+
*/
|
|
172
|
+
export function resolveHeadlessPolicy({ env = process.env, serviceHost = null, engineConfig = null, prefs = null } = {}) {
|
|
173
|
+
const raw = env.DSH_BROWSER_HEADLESS
|
|
174
|
+
if (raw !== undefined && raw !== '') return /^(1|true|yes)$/i.test(String(raw))
|
|
175
|
+
if (serviceHost) return true
|
|
176
|
+
if (prefs && typeof prefs.headless === 'boolean') return prefs.headless
|
|
177
|
+
if (engineConfig && typeof engineConfig.headless === 'boolean') return engineConfig.headless
|
|
178
|
+
return false
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/* --------------------------------------------------------------------------
|
|
182
|
+
* URL 安全校验(纯函数,可单测)
|
|
183
|
+
* ------------------------------------------------------------------------ */
|
|
184
|
+
|
|
185
|
+
function urlError(code, message, hint) {
|
|
186
|
+
return Object.assign(new Error(message), { code, hint })
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 仅 http(s)、拒绝内嵌凭据;其余协议一律拒绝(file:/javascript:/data: 等)。 */
|
|
190
|
+
export function assertSafeUrl(raw) {
|
|
191
|
+
let parsed
|
|
192
|
+
try {
|
|
193
|
+
parsed = new URL(String(raw))
|
|
194
|
+
} catch {
|
|
195
|
+
throw urlError('URL_INVALID', `不是合法 URL: ${String(raw).slice(0, 200)}`, '提供完整地址,如 https://example.com/path')
|
|
196
|
+
}
|
|
197
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
|
|
198
|
+
throw urlError('URL_SCHEME_DENIED',
|
|
199
|
+
`仅支持 http/https,收到 ${parsed.protocol}`,
|
|
200
|
+
'浏览器工具只访问网页;本地文件与其他协议被拒绝。')
|
|
201
|
+
}
|
|
202
|
+
if (parsed.username || parsed.password) {
|
|
203
|
+
throw urlError('URL_CREDENTIALS_DENIED',
|
|
204
|
+
'URL 内嵌了用户名/密码,已拒绝',
|
|
205
|
+
'凭据不要放进 URL;先打开登录页,再用 browser_fill 填表登录。')
|
|
206
|
+
}
|
|
207
|
+
return parsed.href
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/* --------------------------------------------------------------------------
|
|
211
|
+
* 页内快照脚本(在浏览器里执行;自包含,不引用外部标识符)
|
|
212
|
+
* ------------------------------------------------------------------------ */
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* 收集可交互元素 + 结构节点(标题/图片),返回扁平条目 + 缩进文本行。
|
|
216
|
+
* 只走主框架(iframe/shadow DOM 不入快照,README 如实标注)。
|
|
217
|
+
* opts.profile=true 时额外返回分阶段耗时(bench 用;引擎调用不带参,零开销)。
|
|
218
|
+
*/
|
|
219
|
+
export function pageSnapshotFunction(opts) {
|
|
220
|
+
const prof = !!(opts && opts.profile)
|
|
221
|
+
const t = prof ? { query: 0, style: 0, name: 0, path: 0, total: 0 } : null
|
|
222
|
+
const mark = () => (prof ? performance.now() : 0)
|
|
223
|
+
const tStart = mark()
|
|
224
|
+
const INTERACTIVE = 'a, button, input, select, textarea, summary, [role], [contenteditable="true"], [onclick], [tabindex]'
|
|
225
|
+
/* 真正的交互控件角色:heading/img/landmark 不算。observe 用它判断「应用是否已渲染」——
|
|
226
|
+
SPA 空壳常只有一个标题,把标题算成内容会错过几百毫秒后才注入的控件(实战 soak 实测)。 */
|
|
227
|
+
const CONTROL_ROLES = new Set(['button', 'link', 'textbox', 'searchbox', 'checkbox', 'radio', 'combobox', 'listbox', 'menuitem', 'menuitemcheckbox', 'menuitemradio', 'option', 'slider', 'spinbutton', 'switch', 'tab', 'treeitem'])
|
|
228
|
+
const skipHidden = (el, style) => el.getClientRects().length === 0
|
|
229
|
+
|| style.visibility === 'hidden' || style.display === 'none'
|
|
230
|
+
|| el.getAttribute('aria-hidden') === 'true'
|
|
231
|
+
|
|
232
|
+
function implicitRole(el) {
|
|
233
|
+
const tag = el.tagName.toLowerCase()
|
|
234
|
+
if (tag === 'a') return 'link'
|
|
235
|
+
if (tag === 'button' || tag === 'summary') return 'button'
|
|
236
|
+
if (tag === 'select') return 'combobox'
|
|
237
|
+
if (tag === 'textarea' || el.isContentEditable) return 'textbox'
|
|
238
|
+
if (tag === 'input') {
|
|
239
|
+
const type = (el.getAttribute('type') || 'text').toLowerCase()
|
|
240
|
+
if (type === 'checkbox') return 'checkbox'
|
|
241
|
+
if (type === 'radio') return 'radio'
|
|
242
|
+
if (type === 'submit' || type === 'button' || type === 'reset') return 'button'
|
|
243
|
+
return 'textbox'
|
|
244
|
+
}
|
|
245
|
+
if (/^h[1-6]$/.test(tag)) return 'heading'
|
|
246
|
+
if (tag === 'img') return 'img'
|
|
247
|
+
if (tag === 'form') return 'form'
|
|
248
|
+
return 'generic'
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function nameOf(el) {
|
|
252
|
+
const aria = el.getAttribute('aria-label') || el.getAttribute('title')
|
|
253
|
+
if (aria) return aria.trim()
|
|
254
|
+
if (el.id) {
|
|
255
|
+
const label = document.querySelector(`label[for="${CSS.escape(el.id)}"]`)
|
|
256
|
+
if (label && label.textContent.trim()) return label.textContent.trim().slice(0, 80)
|
|
257
|
+
}
|
|
258
|
+
const closest = el.closest('label')
|
|
259
|
+
if (closest && closest.textContent.trim()) return closest.textContent.trim().slice(0, 80)
|
|
260
|
+
const alt = el.getAttribute('alt')
|
|
261
|
+
if (alt) return alt.trim().slice(0, 80)
|
|
262
|
+
const placeholder = el.getAttribute('placeholder')
|
|
263
|
+
if (placeholder) return placeholder.trim().slice(0, 80)
|
|
264
|
+
/* textContent 比 innerText 快一个量级(innerText 会强制 layout 重算换行盒)。 */
|
|
265
|
+
const text = (el.textContent || '').trim()
|
|
266
|
+
if (text) return text.replace(/\s+/g, ' ').slice(0, 80)
|
|
267
|
+
if (el.tagName.toLowerCase() === 'select') {
|
|
268
|
+
const opt = el.selectedOptions && el.selectedOptions[0]
|
|
269
|
+
if (opt) return (opt.textContent || '').trim().slice(0, 80)
|
|
270
|
+
}
|
|
271
|
+
return ''
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function valueOf(el, role) {
|
|
275
|
+
const tag = el.tagName.toLowerCase()
|
|
276
|
+
if (tag === 'input') {
|
|
277
|
+
const type = (el.getAttribute('type') || 'text').toLowerCase()
|
|
278
|
+
if (type === 'password') return '••••'
|
|
279
|
+
if (type === 'checkbox' || type === 'radio') return el.checked ? '[checked]' : ''
|
|
280
|
+
const value = el.value
|
|
281
|
+
return value ? `"${String(value).slice(0, 60)}"` : ''
|
|
282
|
+
}
|
|
283
|
+
if (tag === 'select') {
|
|
284
|
+
const opt = el.selectedOptions && el.selectedOptions[0]
|
|
285
|
+
return opt ? `"${(opt.textContent || opt.value || '').trim().slice(0, 60)}"` : ''
|
|
286
|
+
}
|
|
287
|
+
if (role === 'textbox' && !el.isContentEditable) {
|
|
288
|
+
const value = el.value
|
|
289
|
+
return value ? `"${String(value).slice(0, 60)}"` : ''
|
|
290
|
+
}
|
|
291
|
+
return ''
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function cssPath(el) {
|
|
295
|
+
/* 只用「按构造即唯一」的短路径,绝不做全文档查询:
|
|
296
|
+
旧实现每向上走一层都 querySelectorAll 验一次唯一性,900 个元素的页面
|
|
297
|
+
光路径生成就吃掉 55ms(占快照开销 93%)。现在:
|
|
298
|
+
- id / data-* 仍走一次精确查询换短选择器(少见,代价可控);
|
|
299
|
+
- 其余一律 body 起的 nth-of-type 链(同级同标签序号),零文档查询。 */
|
|
300
|
+
if (el.id) {
|
|
301
|
+
try { if (document.getElementById(el.id) === el) return `#${CSS.escape(el.id)}` } catch { /* 非法 id */ }
|
|
302
|
+
}
|
|
303
|
+
for (const attr of ['data-testid', 'data-test', 'data-qa']) {
|
|
304
|
+
const val = el.getAttribute(attr)
|
|
305
|
+
if (!val) continue
|
|
306
|
+
try {
|
|
307
|
+
const byAttr = `[${attr}="${val.replace(/"/g, '\\"')}"]`
|
|
308
|
+
if (document.querySelectorAll(byAttr).length === 1) return byAttr
|
|
309
|
+
} catch { /* 非法属性值 */ }
|
|
310
|
+
}
|
|
311
|
+
const parts = []
|
|
312
|
+
let cur = el
|
|
313
|
+
while (cur && cur !== document.body && cur.parentElement) {
|
|
314
|
+
/* 祖先里有唯一 id 就用它收口:真实站点常见「容器有 id」,路径能短一大截。 */
|
|
315
|
+
if (cur !== el && cur.id) {
|
|
316
|
+
try { if (document.getElementById(cur.id) === cur) { parts.unshift(`#${CSS.escape(cur.id)}`); break } } catch { /* 非法 id */ }
|
|
317
|
+
}
|
|
318
|
+
/* 同标签序号用兄弟指针数(比遍历 live HTMLCollection 快一个量级);
|
|
319
|
+
只有存在同标签兄弟时才带 :nth-of-type,路径更短。 */
|
|
320
|
+
let index = 1
|
|
321
|
+
let prev = cur
|
|
322
|
+
while ((prev = prev.previousElementSibling)) {
|
|
323
|
+
if (prev.tagName === cur.tagName) index += 1
|
|
324
|
+
}
|
|
325
|
+
let hasAfter = false
|
|
326
|
+
let next = cur
|
|
327
|
+
while ((next = next.nextElementSibling)) {
|
|
328
|
+
if (next.tagName === cur.tagName) { hasAfter = true; break }
|
|
329
|
+
}
|
|
330
|
+
const tag = cur.tagName.toLowerCase()
|
|
331
|
+
parts.unshift(index > 1 || hasAfter ? `${tag}:nth-of-type(${index})` : tag)
|
|
332
|
+
cur = cur.parentElement
|
|
333
|
+
}
|
|
334
|
+
parts.unshift('body')
|
|
335
|
+
return parts.join(' > ')
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
const entries = []
|
|
339
|
+
const lines = []
|
|
340
|
+
let ref = 0
|
|
341
|
+
let controls = 0
|
|
342
|
+
const sQuery = mark()
|
|
343
|
+
const nodes = document.querySelectorAll(`${INTERACTIVE}, h1, h2, h3, h4, h5, h6, img`)
|
|
344
|
+
const bodyDepth = (() => { let d = 0; let n = document.body; while (n && n.parentElement) { d += 1; n = n.parentElement } return d })()
|
|
345
|
+
if (prof) t.query = mark() - sQuery
|
|
346
|
+
const stats = prof ? { visited: 0, hidden: 0 } : null
|
|
347
|
+
for (const el of nodes) {
|
|
348
|
+
if (stats) stats.visited += 1
|
|
349
|
+
let s = mark()
|
|
350
|
+
const style = window.getComputedStyle(el)
|
|
351
|
+
const skip = skipHidden(el, style)
|
|
352
|
+
if (prof) t.style += mark() - s
|
|
353
|
+
if (skip) { if (stats) stats.hidden += 1; continue }
|
|
354
|
+
const tag = el.tagName.toLowerCase()
|
|
355
|
+
if (tag === 'input' && (el.getAttribute('type') || '').toLowerCase() === 'hidden') continue
|
|
356
|
+
if (tag === 'img' && !el.getAttribute('alt')) continue
|
|
357
|
+
const role = el.getAttribute('role') || implicitRole(el)
|
|
358
|
+
if (role === 'generic' || role === 'presentation' || role === 'none') continue
|
|
359
|
+
if (CONTROL_ROLES.has(role)) controls += 1
|
|
360
|
+
ref += 1
|
|
361
|
+
s = mark()
|
|
362
|
+
const name = nameOf(el)
|
|
363
|
+
const value = valueOf(el, role)
|
|
364
|
+
if (prof) t.name += mark() - s
|
|
365
|
+
let node = el.parentElement
|
|
366
|
+
let depth = 0
|
|
367
|
+
while (node && node !== document.body) { depth += 1; node = node.parentElement }
|
|
368
|
+
s = mark()
|
|
369
|
+
const css = cssPath(el)
|
|
370
|
+
if (prof) t.path += mark() - s
|
|
371
|
+
const id = `e${ref}`
|
|
372
|
+
/* 只带定位必需字段:css 是最大头,tag/depth 引擎不用(缩进在 lines 里),去掉可显著减小回传体积。
|
|
373
|
+
name 里的控制字符会破坏回传分帧(\u0001/\u0002 是分隔符),统一压成空格。 */
|
|
374
|
+
entries.push({ ref: id, role, name: name.replace(/[\u0000-\u001f\u007f]/g, ' '), css })
|
|
375
|
+
const label = `${role}${name ? ` "${name}"` : ''}${value ? ` ${value}` : ''}`
|
|
376
|
+
lines.push(`${' '.repeat(Math.max(depth - bodyDepth + 1, 0))}- ${label} [ref=${id}]`)
|
|
377
|
+
}
|
|
378
|
+
if (prof) { t.total = mark() - tStart; t.stats = stats }
|
|
379
|
+
/* 回传形状很关键:对象数组要 28ms(heavy 页),同内容压成一个字符串只要 1.3ms。
|
|
380
|
+
entries 用 \u0001 分字段、\u0002 分条目;lines 直接并成一整段文本。 */
|
|
381
|
+
const entriesPacked = entries
|
|
382
|
+
.map((item) => `${item.ref}\u0001${item.role}\u0001${item.name}\u0001${item.css}`)
|
|
383
|
+
.join('\u0002')
|
|
384
|
+
return {
|
|
385
|
+
url: location.href,
|
|
386
|
+
title: document.title || '',
|
|
387
|
+
text: lines.join('\n'),
|
|
388
|
+
entriesPacked,
|
|
389
|
+
total: entries.length,
|
|
390
|
+
interactive: controls,
|
|
391
|
+
...(prof ? { timings: t } : {}),
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** 解析页内打回来的 entries 字符串;也兼容测试里直接给 entries 数组的假页面。 */
|
|
396
|
+
export function parseSnapshotEntries(raw) {
|
|
397
|
+
if (raw && typeof raw.entriesPacked === 'string') {
|
|
398
|
+
if (!raw.entriesPacked) return []
|
|
399
|
+
const out = []
|
|
400
|
+
for (const chunk of raw.entriesPacked.split('\u0002')) {
|
|
401
|
+
const [ref, role, name, css] = chunk.split('\u0001')
|
|
402
|
+
if (ref && css) out.push({ ref, role, name, css })
|
|
403
|
+
}
|
|
404
|
+
return out
|
|
405
|
+
}
|
|
406
|
+
return Array.isArray(raw && raw.entries) ? raw.entries : []
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/* --------------------------------------------------------------------------
|
|
410
|
+
* 引擎本体
|
|
411
|
+
* ------------------------------------------------------------------------ */
|
|
412
|
+
|
|
413
|
+
function engineError(code, message, hint) {
|
|
414
|
+
return Object.assign(new Error(message), { code, hint: hint || '' })
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Playwright 的导航超时:name=TimeoutError 或消息里带 'Timeout ... exceeded'。 */
|
|
418
|
+
function isNavigationTimeout(error) {
|
|
419
|
+
if (!error) return false
|
|
420
|
+
if (error.name === 'TimeoutError') return true
|
|
421
|
+
return /Timeout\s+\d+ms\s+exceeded/i.test(String(error.message || ''))
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/** 把裸 Playwright 网络错误翻译成人话 + 统一 NAV_FAILED 代码,模型/用户都不用猜 net::ERR_*。 */
|
|
425
|
+
function navFailure(error, url) {
|
|
426
|
+
const raw = String((error && error.message) || error || '')
|
|
427
|
+
const m = raw.match(/net::(ERR_[A-Z_]+)/)
|
|
428
|
+
const code = m ? m[1] : ''
|
|
429
|
+
const reason = ({
|
|
430
|
+
ERR_NAME_NOT_RESOLVED: '域名解析失败(网址拼错或域名不存在)',
|
|
431
|
+
ERR_CONNECTION_REFUSED: '连接被拒绝(目标端口没有服务)',
|
|
432
|
+
ERR_CONNECTION_TIMED_OUT: '连接超时(目标不可达或被防火墙丢弃)',
|
|
433
|
+
ERR_TIMED_OUT: '连接超时(目标不可达或被防火墙丢弃)',
|
|
434
|
+
ERR_ADDRESS_UNREACHABLE: '地址不可达',
|
|
435
|
+
ERR_INTERNET_DISCONNECTED: '网络已断开',
|
|
436
|
+
ERR_CONNECTION_RESET: '连接被重置',
|
|
437
|
+
ERR_SSL_PROTOCOL_ERROR: 'TLS/SSL 握手失败',
|
|
438
|
+
ERR_CERT_AUTHORITY_INVALID: '证书不受信任',
|
|
439
|
+
})[code] || (code ? `网络错误 ${code}` : '导航失败')
|
|
440
|
+
return engineError('NAV_FAILED', `无法打开 ${url}:${reason}`,
|
|
441
|
+
'检查网址与网络后重试;若目标确不可达,换一个可达地址,不要反复重试同一地址。')
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** 是否落在 Chromium 网络错误页(chrome-error://):此时再 evaluate 只会抛「context destroyed」。 */
|
|
445
|
+
function isChromeErrorPage(page) {
|
|
446
|
+
try { return /^chrome-error:/i.test(page.url() || '') } catch { return false }
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** 给任何 await 加个上限:渲染进程卡死时 page.evaluate 可能永远不返回。 */
|
|
450
|
+
function withTimeout(promise, ms, label) {
|
|
451
|
+
let timer
|
|
452
|
+
const timeout = new Promise((_, reject) => {
|
|
453
|
+
timer = setTimeout(() => {
|
|
454
|
+
reject(engineError('TIMEOUT', `${label}超过 ${ms}ms 未返回`,
|
|
455
|
+
'页面可能卡死;可先 browser_screenshot 确认,必要时 browser_close 重置(登录态保留)。'))
|
|
456
|
+
}, ms)
|
|
457
|
+
})
|
|
458
|
+
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer))
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/** 读引擎偏好(目前只有 headless):工作台切过一次就记住,重启后不用再点。 */
|
|
462
|
+
export function readEnginePrefs(hostDir) {
|
|
463
|
+
if (!hostDir) return {}
|
|
464
|
+
try {
|
|
465
|
+
const data = JSON.parse(fs.readFileSync(path.join(hostDir, 'engine.json'), 'utf8'))
|
|
466
|
+
return data && typeof data === 'object' ? data : {}
|
|
467
|
+
} catch { return {} }
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
const ACTION_LOG_LIMIT = 50
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* 驱动解析:默认 playwright;显式要 patchright(Playwright 的 stealth 分支,收敛
|
|
474
|
+
* Runtime.enable / Console.enable 这类 CDP 泄漏面)且本机装了就用它——两者 API 兼容。
|
|
475
|
+
*
|
|
476
|
+
* 为什么用 require 而不是 import():宿主(dsh)自带热重载钩子在 CJS 缓存里留下过半初始化的
|
|
477
|
+
* playwright-core(`require('./lib/coreBundle').inprocess` 为 undefined → 「reading 'playwright'」),
|
|
478
|
+
* 而 ESM 的模块表一旦缓存就无法再读盘。这里先用 createRequire 清掉 playwright 相关缓存再同步加载,
|
|
479
|
+
* 能绕开被污染的半成品;require 不可用时再退回原来的 import()。
|
|
480
|
+
*/
|
|
481
|
+
const engineRequire = createRequire(import.meta.url)
|
|
482
|
+
|
|
483
|
+
/** 只清 playwright / playwright-core 的 CJS 缓存:半初始化的 coreBundle 会让整个驱动变 undefined。 */
|
|
484
|
+
function purgePlaywrightCache() {
|
|
485
|
+
try {
|
|
486
|
+
for (const key of Object.keys(engineRequire.cache)) {
|
|
487
|
+
if (/[\\/]playwright(-core)?[\\/]/.test(key)) delete engineRequire.cache[key]
|
|
488
|
+
}
|
|
489
|
+
} catch { /* 清不掉就照常尝试,失败由调用方报错 */ }
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
async function loadPlaywright(cfg) {
|
|
493
|
+
purgePlaywrightCache()
|
|
494
|
+
if (String(cfg?.stealthDriver || '').toLowerCase() === 'patchright') {
|
|
495
|
+
try { return engineRequire('patchright') } catch { /* 没装:回落 playwright,不报错 */ }
|
|
496
|
+
}
|
|
497
|
+
try { return engineRequire('playwright') } catch { /* 打包形态拿不到 CJS 时退回 ESM */ }
|
|
498
|
+
return import('playwright')
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* @param {object} options
|
|
503
|
+
* @param {string} options.hostDir 宿主数据目录(profile/ 与 screenshots/ 落这里)
|
|
504
|
+
* @param {object} [options.config] resolveEngineConfig 的产物(默认再解析一次环境变量)
|
|
505
|
+
* @param {object} [options.playwright] 注入的 playwright 模块(测试用;缺省动态 import)
|
|
506
|
+
* @param {object} [options.processOps] 注入的进程操作面(孤儿清扫用;测试注入假枚举)
|
|
507
|
+
*/
|
|
508
|
+
/** 反自动化 UA 缓存:本会话目录 + 上层共享目录各存一份,尽量只付一次「探测 + 重启」的代价。
|
|
509
|
+
* 缓存里必须同时记下内核完整版本(CDP product,如 156.0.8078.4):
|
|
510
|
+
* Chrome 的 UA 字符串本来就做「版本削减」(报 major.0.0.0 是正常行为),完整版本只出现在
|
|
511
|
+
* UA-CH 里;历史版本曾把补丁值当真实 UA 存下来,还拿削减版当完整版,反而更假。 */
|
|
512
|
+
const UA_RE = /\) Chrome\/\d+\.\d+\.\d+\.\d+ Safari\//
|
|
513
|
+
const UA_BUILD_RE = /Chrome\/(\d+\.\d+\.\d+\.\d+)/
|
|
514
|
+
|
|
515
|
+
function uaBuildOf(ua) {
|
|
516
|
+
const m = UA_BUILD_RE.exec(String(ua || ''))
|
|
517
|
+
return m ? m[1] : ''
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
function uaMajorOf(ua) {
|
|
521
|
+
const build = uaBuildOf(ua)
|
|
522
|
+
return build ? build.split('.')[0] : ''
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function uaCacheFiles(hostDir) {
|
|
526
|
+
return [path.join(hostDir, 'ua.json'), path.join(hostDir, '..', 'ua-cache.json')]
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** 读回 { ua, build };没有可信缓存返回 null。 */
|
|
530
|
+
export function readUaCache(hostDir) {
|
|
531
|
+
for (const file of uaCacheFiles(hostDir)) {
|
|
532
|
+
try {
|
|
533
|
+
const data = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
534
|
+
if (!data || data.version !== 2) continue
|
|
535
|
+
const ua = data.ua
|
|
536
|
+
if (typeof ua !== 'string' || !UA_RE.test(ua)) continue
|
|
537
|
+
const build = String(data.build || '')
|
|
538
|
+
if (!/^\d+\.\d+\.\d+\.\d+$/.test(build)) continue
|
|
539
|
+
/* 大版本必须一致:串了值/换了内核的缓存不能拿去当 HTTP 头。 */
|
|
540
|
+
if (build.split('.')[0] !== uaMajorOf(ua)) continue
|
|
541
|
+
return { ua, build }
|
|
542
|
+
} catch { /* 没有缓存或坏文件:继续找下一个 */ }
|
|
543
|
+
}
|
|
544
|
+
return null
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
export function writeUaCache(hostDir, ua, build) {
|
|
548
|
+
const value = String(ua || '')
|
|
549
|
+
if (!UA_RE.test(value)) return
|
|
550
|
+
const full = String(build || uaBuildOf(value) || '')
|
|
551
|
+
if (!/^\d+\.\d+\.\d+\.\d+$/.test(full)) return
|
|
552
|
+
const payload = JSON.stringify({ version: 2, ua: value, build: full, at: new Date().toISOString() })
|
|
553
|
+
for (const file of uaCacheFiles(hostDir)) {
|
|
554
|
+
try { fs.writeFileSync(file, payload) } catch { /* 只影响下次启动的头 */ }
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/** 真实 UA → 可对外使用的 UA:只删 Headless 一词(保留前面的空格:正牌是 `) Chrome/156…`)。 */
|
|
559
|
+
function chromeUaFrom(raw) {
|
|
560
|
+
const ua = String(raw || '').replace(/Headless(?=Chrome)/, '')
|
|
561
|
+
return UA_RE.test(ua) ? ua : ''
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* 读浏览器真实 UA 与完整版本。
|
|
566
|
+
* 必须走 CDP 的 Browser.getVersion:页面里的 navigator.userAgent 会被我们自己的 stealth
|
|
567
|
+
* 补丁改写,用它探测等于照镜子(这正是假版本号被写进缓存的根因)。
|
|
568
|
+
* UA 字符串按 Chrome 的削减规则保留 `major.0.0.0`;完整版本从 product(`Chrome/156.0.8078.4`)取,
|
|
569
|
+
* 只用于 UA-CH 的高熵字段——两者都必须是内核对外的真实值。
|
|
570
|
+
*/
|
|
571
|
+
async function detectRealUserAgent(page) {
|
|
572
|
+
let session = null
|
|
573
|
+
try {
|
|
574
|
+
const ctx = page.context()
|
|
575
|
+
if (ctx && typeof ctx.newCDPSession === 'function') {
|
|
576
|
+
session = await ctx.newCDPSession(page)
|
|
577
|
+
const info = await session.send('Browser.getVersion')
|
|
578
|
+
const ua = chromeUaFrom(info && info.userAgent)
|
|
579
|
+
const build = uaBuildOf(String((info && info.product) || ''))
|
|
580
|
+
if (ua) return { ua, build: build || uaBuildOf(ua) }
|
|
581
|
+
}
|
|
582
|
+
} catch { /* CDP 不可用(接管的老驱动):回落页面 */ }
|
|
583
|
+
finally { try { if (session) await session.detach() } catch { /* 已断开 */ } }
|
|
584
|
+
try {
|
|
585
|
+
const ua = chromeUaFrom(await page.evaluate(() => navigator.userAgent))
|
|
586
|
+
return ua ? { ua, build: uaBuildOf(ua) } : null
|
|
587
|
+
} catch { return null }
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
/**
|
|
591
|
+
* 落地页是不是「登录页」:只在跨主机跳到 login./passport./sso./signin./auth. 这类主机时算。
|
|
592
|
+
* 同主机内的登录路径不算(用户本来就可能主动打开登录页)。
|
|
593
|
+
* 目的:登录态失效时直接把结论写进返回值,模型才有机会提示用户扫码,而不是反复重试同一个动作。
|
|
594
|
+
*/
|
|
595
|
+
export function loginRedirectNote(requested, landed) {
|
|
596
|
+
try {
|
|
597
|
+
const a = new URL(String(requested || ''))
|
|
598
|
+
const b = new URL(String(landed || ''))
|
|
599
|
+
if (a.host === b.host) return ''
|
|
600
|
+
if (!/^(login|passport|sso|signin|auth)\./i.test(b.host)) return ''
|
|
601
|
+
return `被重定向到登录页(${b.host}):当前登录态已失效,需要重新登录(可扫码)后再继续`
|
|
602
|
+
} catch { return '' }
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
/**
|
|
606
|
+
* 页内人机验证探针:只「识别」常见挑战容器,返回类型字符串;不做任何破解。
|
|
607
|
+
* 识别到的挑战交给工作台人工过一次,再由登录态保险箱持久化——这是合规且稳定的闭环。
|
|
608
|
+
*/
|
|
609
|
+
export function challengeProbe() {
|
|
610
|
+
const has = (s) => { try { return !!document.querySelector(s) } catch { return false } }
|
|
611
|
+
if (has('#nc_1_wrapper, #nc_1_n1z, .nc-container, #baxia-dialog-content')) return 'slider'
|
|
612
|
+
if (has('.geetest_panel, .geetest_widget, .geetest_holder')) return 'geetest'
|
|
613
|
+
if (has('#tcaptcha_transform, #tcaptcha_popup, .tcaptcha-popup')) return 'tcaptcha'
|
|
614
|
+
if (has('iframe[src*="captcha"], iframe[src*="punish"], iframe[src*="_____tmd_____"]')) return 'iframe-challenge'
|
|
615
|
+
return ''
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
/** 把探针结果翻译成给模型的提示:人工过一次 + 保险箱持久化,不自动破解。 */
|
|
619
|
+
export function challengeNote(kind) {
|
|
620
|
+
if (!kind) return ''
|
|
621
|
+
return `遇到人机验证(${kind}):请在浏览器工作台人工完成一次(滑块/点选/扫码),完成后继续;登录态会由保险箱持久化,不自动破解`
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* DSH Web 自身 401 鉴权页识别:受控浏览器与宿主浏览器登录态独立,
|
|
626
|
+
* 直接打开宿主 GUI 地址只会拿到一行纯文本(快照树为空)。认出它就给结论,
|
|
627
|
+
* 不让模型对着白屏重试、或试图「登录」宿主 GUI。只匹配固定文案,薄页才调用。
|
|
628
|
+
*/
|
|
629
|
+
export function dshAuthWallNote(text) {
|
|
630
|
+
if (!/dsh web authentication required/i.test(String(text || ''))) return ''
|
|
631
|
+
return '这是 DSH Web 自身的鉴权页(401):受控浏览器没有宿主浏览器的认证 cookie,不是目标网站故障。不要重试、不要试图登录宿主 GUI;请让用户在宿主浏览器打开 dsh web 打印的带 token 地址查看界面,受控浏览器继续用于互联网任务'
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
export async function createBrowserEngine({ hostDir, config, playwright, processOps } = {}) { if (!hostDir) throw new Error('createBrowserEngine: 缺少 hostDir')
|
|
635
|
+
/* 局部配置必须能覆盖默认值:传 {headless:true} 时 viewport 等未给的键要落到默认,
|
|
636
|
+
否则 launchPersistentContext 收到 viewport.width=undefined 直接起不来。 */
|
|
637
|
+
const cfg = config ? { ...ENGINE_CONFIG_DEFAULTS, ...config } : resolveEngineConfig()
|
|
638
|
+
const pw = playwright || await loadPlaywright(cfg)
|
|
639
|
+
const ops = processOps || createProcessOps()
|
|
640
|
+
/* 拟人档位(null = 机器节奏);RNG 每引擎一个,序列不可预测但同引擎内连续变化。 */
|
|
641
|
+
const human = cfg.humanize ? resolveHumanProfile(cfg.humanizeProfile) : null
|
|
642
|
+
const rng = mulberry32((Date.now() ^ (process.pid << 8)) >>> 0)
|
|
643
|
+
/* 礼貌调度器:主机间隔/并发/退避跨会话共享(模块级),动作限速每引擎一份。 */
|
|
644
|
+
const gov = createGovernor(cfg)
|
|
645
|
+
|
|
646
|
+
const profileDir = path.join(hostDir, 'profile')
|
|
647
|
+
const screenshotsDir = path.join(hostDir, 'screenshots')
|
|
648
|
+
const prefsFile = path.join(hostDir, 'engine.json')
|
|
649
|
+
const tabsFile = path.join(hostDir, 'tabs.json')
|
|
650
|
+
fs.mkdirSync(profileDir, { recursive: true })
|
|
651
|
+
fs.mkdirSync(screenshotsDir, { recursive: true })
|
|
652
|
+
|
|
653
|
+
/* ---- 运行态 ---- */
|
|
654
|
+
let context = null
|
|
655
|
+
let launching = null
|
|
656
|
+
let channelUsed = ''
|
|
657
|
+
let detectedUa = '' // 本次启动实际使用的 UA(真实内核版本,只去掉了 Headless 一词)
|
|
658
|
+
let detectedUaFull = '' // 内核完整版本(CDP product,如 156.0.8078.4):UA 字符串按 Chrome 规则削减成 major.0.0.0,完整值只用于 UA-CH
|
|
659
|
+
let activeTabId = null
|
|
660
|
+
let tabCounter = 0
|
|
661
|
+
const tabs = new Map() // id → page
|
|
662
|
+
const tabIds = new Map() // page → id
|
|
663
|
+
const refRegistries = new Map() // tabId → Map(ref → entry)
|
|
664
|
+
/* ref 全局单调编号(跨标签不重号):否则 T1 的 e3 会在 T2 里静默命中同编号的别的元素,
|
|
665
|
+
比报错更危险。重编号后跨标签 ref 在当前 registry 查不到 → 走 TAB_MISMATCH 明确提示。 */
|
|
666
|
+
let nextRefId = 1
|
|
667
|
+
const tabTitles = new Map() // tabId → 最近一次已知的 document.title(status 同步读,不能 await)
|
|
668
|
+
const snapshotChars = new Map() // tabId → 最后一次快照字符数
|
|
669
|
+
const mouseAt = new Map() // tabId → 最近一次鼠标坐标(拟人轨迹的起点)
|
|
670
|
+
const uaSessions = new Map() // page → CDP 会话(Emulation.setUserAgentOverride 需要会话存活)
|
|
671
|
+
const walls = new Map() // tabId → 鉴权墙提示(活动页停在 DSH Web 401 纯文本页时非空)
|
|
672
|
+
const counters = { actions: 0, errors: 0, snapshots: 0, inputs: 0, orphansKilled: 0 }
|
|
673
|
+
const actionLog = []
|
|
674
|
+
|
|
675
|
+
/* ---- 资源回收 / 标签恢复 ---- */
|
|
676
|
+
let lastActivity = Date.now() // 最近一次「有人在用」:工具动作 / 输入 / 看帧 / 截图
|
|
677
|
+
let restoring = false // 正在恢复标签页:抑制日志写回与重复恢复
|
|
678
|
+
let lastRestore = { restored: 0, skipped: 0 } // 最近一次恢复的实际页数 / 被上限裁掉的页数
|
|
679
|
+
let journalTimer = null // 标签日志防抖写盘计时器
|
|
680
|
+
|
|
681
|
+
/* ---- 登录态保险箱(cookie 跨会话复用)---- */
|
|
682
|
+
let vaultTimer = null // 保存节流计时器
|
|
683
|
+
let vaultInjected = 0 // 本次启动从保险箱注入了多少条 cookie
|
|
684
|
+
|
|
685
|
+
/* ---- 实时画面(CDP screencast)----
|
|
686
|
+
* 订阅者存在时才向当前活动页拉帧;没人看就停(screencast 开着会一直占带宽)。
|
|
687
|
+
* 帧不落盘、不进日志,纯前端观感通道。 */
|
|
688
|
+
const frameSubs = new Set()
|
|
689
|
+
let caster = null // { page, tabId, session }
|
|
690
|
+
let castTimer = null
|
|
691
|
+
let castBusy = false
|
|
692
|
+
|
|
693
|
+
/* ---- 动作互斥(浏览器单线程语义) ---- */
|
|
694
|
+
let chain = Promise.resolve()
|
|
695
|
+
function enqueue(task) {
|
|
696
|
+
const run = chain.then(task, task)
|
|
697
|
+
chain = run.then(() => {}, () => {})
|
|
698
|
+
return run
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
/* 控制面独立队列:标签 list/new/select/close 只动标签注册表与活动指针,不读写正在导航的
|
|
702
|
+
页面内容,因此不该排在一条可能挂 30s 的导航后面。页面内容类动作仍走主 chain 互斥。 */
|
|
703
|
+
let controlChain = Promise.resolve()
|
|
704
|
+
function enqueueControl(task) {
|
|
705
|
+
const run = controlChain.then(task, task)
|
|
706
|
+
controlChain = run.then(() => {}, () => {})
|
|
707
|
+
return run
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
function logAction(tool, detail, ms, ok, error) {
|
|
711
|
+
actionLog.unshift({ tool, detail, ms: Math.round(ms), ok, error: error ? String(error.message || error).slice(0, 160) : '', at: new Date().toISOString() })
|
|
712
|
+
if (actionLog.length > ACTION_LOG_LIMIT) actionLog.length = ACTION_LOG_LIMIT
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
async function track(tool, detail, task) {
|
|
716
|
+
/* 连发压速:单动作不等待,只有 1 秒内动作数超上限才插等待(防「像攻击」的高频形状)。 */
|
|
717
|
+
await gov.paceAction()
|
|
718
|
+
const started = Date.now()
|
|
719
|
+
counters.actions += 1
|
|
720
|
+
touch()
|
|
721
|
+
try {
|
|
722
|
+
const out = await task()
|
|
723
|
+
logAction(tool, detail, Date.now() - started, true)
|
|
724
|
+
scheduleJournal()
|
|
725
|
+
scheduleVault()
|
|
726
|
+
return out
|
|
727
|
+
} catch (error) {
|
|
728
|
+
counters.errors += 1
|
|
729
|
+
logAction(tool, detail, Date.now() - started, false, error)
|
|
730
|
+
throw error
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
/* ---- 标签页日志(落盘 + 重启恢复)----
|
|
735
|
+
* Playwright 持久上下文只保登录态(profile),不保标签页:重启后 ctx.pages()
|
|
736
|
+
* 通常只剩一个 about:blank。这里把「开了哪些页 + 哪个是活动页」记到 tabs.json,
|
|
737
|
+
* 下次懒启动时 best-effort 恢复,于是「重开会话还能看到上次的页面」。
|
|
738
|
+
* 只记 http(s) 地址;恢复尽力而为(死链/慢站跳过,绝不阻塞启动)。 */
|
|
739
|
+
|
|
740
|
+
function touch() { lastActivity = Date.now() }
|
|
741
|
+
|
|
742
|
+
/**
|
|
743
|
+
* 按 maxRestoreTabs 裁剪「待恢复」列表:留最近 N 个,活动页即使排得更早也保一个位。
|
|
744
|
+
* 裁掉的只是恢复候选,不影响当前活着的标签页(新开标签页数不设限)。
|
|
745
|
+
*/
|
|
746
|
+
function limitRestoreList(list, activeUrl) {
|
|
747
|
+
const limit = Number.isFinite(cfg.maxRestoreTabs) ? cfg.maxRestoreTabs : 0
|
|
748
|
+
if (!limit || list.length <= limit) return { tabs: list, dropped: 0 }
|
|
749
|
+
const kept = list.slice(-limit)
|
|
750
|
+
if (activeUrl && !kept.some((t) => t.url === activeUrl)) {
|
|
751
|
+
const active = list.filter((t) => t.url === activeUrl).pop()
|
|
752
|
+
/* 活动页顶掉这批里最旧的一位,长度仍是 limit。 */
|
|
753
|
+
if (active) kept[0] = active
|
|
754
|
+
}
|
|
755
|
+
return { tabs: kept, dropped: list.length - kept.length }
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
function journalSnapshot() {
|
|
759
|
+
const list = []
|
|
760
|
+
let activeUrl = ''
|
|
761
|
+
for (const [id, page] of tabs) {
|
|
762
|
+
let url = ''
|
|
763
|
+
try { url = page.url() || '' } catch { continue }
|
|
764
|
+
if (!/^https?:\/\//i.test(url)) continue // about:blank / chrome:// 等不记
|
|
765
|
+
list.push({ id, url })
|
|
766
|
+
if (id === activeTabId) activeUrl = url
|
|
767
|
+
}
|
|
768
|
+
/* 落盘就裁一次:日志不随标签页数量无限膨胀,恢复成本从源头有界。
|
|
769
|
+
把裁掉几页一起记进日志,下次恢复才能如实报告「还有几页没恢复」。 */
|
|
770
|
+
const { tabs: kept, dropped } = limitRestoreList(list, activeUrl)
|
|
771
|
+
return { tabs: kept, dropped, activeUrl, at: new Date().toISOString() }
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
function writeJournal() {
|
|
775
|
+
try {
|
|
776
|
+
const snap = journalSnapshot()
|
|
777
|
+
/* 没有可恢复的页就删掉旧日志,避免下次恢复出一堆空页。 */
|
|
778
|
+
if (!snap.tabs.length) { fs.rmSync(tabsFile, { force: true }); return }
|
|
779
|
+
fs.writeFileSync(tabsFile, JSON.stringify(snap, null, 2))
|
|
780
|
+
} catch { /* 宿主目录只读等:本次运行不受影响 */ }
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
/** 防抖写盘:一串连续动作(点击/填写)只在落定后写一次。 */
|
|
784
|
+
function scheduleJournal() {
|
|
785
|
+
if (restoring) return
|
|
786
|
+
if (journalTimer) clearTimeout(journalTimer)
|
|
787
|
+
journalTimer = setTimeout(() => { journalTimer = null; writeJournal() }, 800)
|
|
788
|
+
journalTimer.unref?.()
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/** 把当前上下文的 cookie 合进共享保险箱:登录过的站点在这里沉淀,供其它会话/下次启动注入。 */
|
|
792
|
+
async function saveVault() {
|
|
793
|
+
if (!cfg.loginVault || !context || typeof context.cookies !== 'function') return 0
|
|
794
|
+
try {
|
|
795
|
+
const cookies = await context.cookies()
|
|
796
|
+
return writeVault(hostDir, cookies)
|
|
797
|
+
} catch { return 0 }
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
/** 节流保存:动作密集时不要每步都跨进程取一次 cookie(5 秒最多一次)。 */
|
|
801
|
+
function scheduleVault() {
|
|
802
|
+
if (!cfg.loginVault || vaultTimer) return
|
|
803
|
+
vaultTimer = setTimeout(() => { vaultTimer = null; saveVault() }, 5000)
|
|
804
|
+
vaultTimer.unref?.()
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
function readJournal() {
|
|
808
|
+
try {
|
|
809
|
+
const data = JSON.parse(fs.readFileSync(tabsFile, 'utf8'))
|
|
810
|
+
if (!data || !Array.isArray(data.tabs)) return null
|
|
811
|
+
const all = data.tabs
|
|
812
|
+
.map((t) => (t && typeof t.url === 'string' ? { url: t.url } : null))
|
|
813
|
+
.filter((t) => t && /^https?:\/\//i.test(t.url))
|
|
814
|
+
if (!all.length) return null
|
|
815
|
+
const activeUrl = typeof data.activeUrl === 'string' ? data.activeUrl : ''
|
|
816
|
+
/* 旧版本或外部写坏的超大日志也按上限收:恢复只在最近 N 个上跑。 */
|
|
817
|
+
const { tabs: kept, dropped } = limitRestoreList(all, activeUrl)
|
|
818
|
+
const trimmedBefore = Number(data.dropped) > 0 ? Number(data.dropped) : 0
|
|
819
|
+
return { urls: kept.map((t) => t.url), activeUrl, skipped: trimmedBefore + dropped }
|
|
820
|
+
} catch { return null }
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/** 懒启动后恢复上次标签页(best-effort)。只在「全新空白上下文 + 有日志」时跑。 */
|
|
824
|
+
async function restoreJournal(ctx) {
|
|
825
|
+
if (!cfg.restoreTabs || restoring) return
|
|
826
|
+
lastRestore = { restored: 0, skipped: 0 }
|
|
827
|
+
const journal = readJournal()
|
|
828
|
+
if (!journal) return
|
|
829
|
+
/* 上下文已有非空白页(极少数 channel 会带页)就不覆盖用户现状。 */
|
|
830
|
+
const existing = ctx.pages()
|
|
831
|
+
const meaningful = existing.filter((p) => { try { return /^https?:\/\//i.test(p.url() || '') } catch { return false } })
|
|
832
|
+
if (meaningful.length) return
|
|
833
|
+
restoring = true
|
|
834
|
+
const created = [] // { id, url }
|
|
835
|
+
const restoreOne = async (url, reusePage) => {
|
|
836
|
+
let page = null
|
|
837
|
+
/* 恢复也走礼貌调度:重启瞬间对同一主机并发 N 个 goto 是典型突发形状,
|
|
838
|
+
这里受全局并发上限 + 每主机间隔约束,错峰加载。 */
|
|
839
|
+
const slot = await gov.acquireNav(url)
|
|
840
|
+
try {
|
|
841
|
+
/* 复用第一个空白页,其余新开。 */
|
|
842
|
+
page = reusePage || await ctx.newPage()
|
|
843
|
+
const id = registerPage(page)
|
|
844
|
+
await applyUaHints(page) /* 恢复页的第一个请求就要带对齐后的 UA-CH 头 */
|
|
845
|
+
const resp = await page.goto(url, { timeout: cfg.navigationTimeoutMs, waitUntil: 'domcontentloaded' })
|
|
846
|
+
gov.reportNav(slot, { status: resp && typeof resp.status === 'function' ? resp.status() : 0 })
|
|
847
|
+
created.push({ id, url })
|
|
848
|
+
} catch {
|
|
849
|
+
/* 死链/超时:跳过这一页。新开的页失败就关掉,避免留下空白孤儿页;复用页保留。
|
|
850
|
+
关页也加超时:渲染进程卡死时 close 可能永不返回,别把启动恢复挂住。 */
|
|
851
|
+
if (!reusePage && page) { try { await withTimeout(page.close(), 5000, '恢复失败页清理') } catch { /* 已关/卡死 */ } }
|
|
852
|
+
} finally {
|
|
853
|
+
gov.releaseNav(slot)
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
try {
|
|
857
|
+
/* 并发恢复但受调度器约束(并发上限+主机间隔):总耗时可控,又不对单主机突发。 */
|
|
858
|
+
await Promise.all(journal.urls.map((url, i) => restoreOne(url, i === 0 ? (existing[0] || null) : null)))
|
|
859
|
+
if (created.length) {
|
|
860
|
+
const match = created.find((c) => c.url === journal.activeUrl)
|
|
861
|
+
activeTabId = (match || created[0]).id
|
|
862
|
+
}
|
|
863
|
+
lastRestore = { restored: created.length, skipped: journal.skipped || 0 }
|
|
864
|
+
} finally {
|
|
865
|
+
restoring = false
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
/* ---- 懒启动与探测链 ---- */
|
|
870
|
+
function registerPage(page) {
|
|
871
|
+
if (tabIds.has(page)) return tabIds.get(page)
|
|
872
|
+
tabCounter += 1
|
|
873
|
+
const id = `T${tabCounter}`
|
|
874
|
+
tabs.set(id, page)
|
|
875
|
+
tabIds.set(page, id)
|
|
876
|
+
refRegistries.set(id, new Map())
|
|
877
|
+
tabTitles.set(id, '')
|
|
878
|
+
/* 标题缓存:domcontentloaded 时异步补一次(SPA 后续改标题由 takeSnapshot 再补)。 */
|
|
879
|
+
page.on('domcontentloaded', () => {
|
|
880
|
+
void page.title().then((t) => { if (tabs.has(id)) tabTitles.set(id, t || '') }).catch(() => {})
|
|
881
|
+
})
|
|
882
|
+
page.on('close', () => {
|
|
883
|
+
tabs.delete(id)
|
|
884
|
+
tabIds.delete(page)
|
|
885
|
+
refRegistries.delete(id)
|
|
886
|
+
tabTitles.delete(id)
|
|
887
|
+
snapshotChars.delete(id)
|
|
888
|
+
mouseAt.delete(id)
|
|
889
|
+
walls.delete(id)
|
|
890
|
+
closeInput(page)
|
|
891
|
+
const uaSession = uaSessions.get(page)
|
|
892
|
+
if (uaSession) { uaSessions.delete(page); try { void uaSession.detach().catch(() => {}) } catch { /* 已断 */ } }
|
|
893
|
+
if (activeTabId === id) {
|
|
894
|
+
const rest = [...tabs.keys()]
|
|
895
|
+
activeTabId = rest.length ? rest[rest.length - 1] : null
|
|
896
|
+
}
|
|
897
|
+
})
|
|
898
|
+
return id
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/**
|
|
902
|
+
* 网络侧 UA-CH 对齐:launch 的 userAgent 选项只改 UA 字符串,Sec-CH-UA 请求头仍由
|
|
903
|
+
* 浏览器内核自己生成(bundled Chromium 只报 Chromium,不报 Google Chrome),
|
|
904
|
+
* 与页内补丁的品牌清单对不上——口径不一致本身就是检测点。
|
|
905
|
+
* 用 CDP Emulation.setUserAgentOverride 的 userAgentMetadata 把请求头也换成同一份
|
|
906
|
+
* 清单(uaClientHints 单一真源)。会话必须存活,override 才持续生效,故按 page 缓存。
|
|
907
|
+
* 必须在任何 goto 之前调用;失败静默降级(老驱动/无 CDP 时不影响可用性)。
|
|
908
|
+
*/
|
|
909
|
+
async function applyUaHints(page) {
|
|
910
|
+
if (!cfg.stealth || !detectedUa) return
|
|
911
|
+
const hints = uaClientHints(detectedUa, detectedUaFull, process.platform === 'win32' ? 'Win32' : process.platform === 'darwin' ? 'MacIntel' : 'Linux x86_64')
|
|
912
|
+
if (!hints.brands.length) return
|
|
913
|
+
try {
|
|
914
|
+
let session = uaSessions.get(page)
|
|
915
|
+
if (!session) {
|
|
916
|
+
session = await page.context().newCDPSession(page)
|
|
917
|
+
uaSessions.set(page, session)
|
|
918
|
+
}
|
|
919
|
+
await session.send('Emulation.setUserAgentOverride', {
|
|
920
|
+
userAgent: detectedUa,
|
|
921
|
+
userAgentMetadata: {
|
|
922
|
+
brands: hints.brands,
|
|
923
|
+
fullVersionList: hints.fullVersionList,
|
|
924
|
+
platform: hints.platform,
|
|
925
|
+
platformVersion: hints.platformVersion,
|
|
926
|
+
architecture: hints.architecture,
|
|
927
|
+
bitness: hints.bitness,
|
|
928
|
+
model: hints.model,
|
|
929
|
+
mobile: hints.mobile,
|
|
930
|
+
wow64: hints.wow64,
|
|
931
|
+
formFactors: hints.formFactors,
|
|
932
|
+
},
|
|
933
|
+
})
|
|
934
|
+
} catch { /* 降级:请求头保持内核原样 */ }
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
/* 启动/关闭的兜底超时包装:0 = 不限(保留旧行为)。超时抛 code=TIMEOUT 的结构化错误,
|
|
938
|
+
由调用方决定重试/强清/换候选——绝不让一个卡死的驱动把整条动作队列挂住。 */
|
|
939
|
+
const launchAttempt = (promise) => {
|
|
940
|
+
if (!(cfg.launchTimeoutMs > 0)) return promise
|
|
941
|
+
let timedOut = false
|
|
942
|
+
const guarded = withTimeout(promise, cfg.launchTimeoutMs, '浏览器启动')
|
|
943
|
+
.catch((error) => { timedOut = !!(error && error.code === 'TIMEOUT'); throw error })
|
|
944
|
+
/* 超时后原启动若姗姗来迟地成功,把迟到的上下文关掉:否则留下一个占着 profile
|
|
945
|
+
的幽灵浏览器,下次启动撞锁。只在确认超时后才关,避免误关正常启动的上下文。 */
|
|
946
|
+
promise.then((late) => {
|
|
947
|
+
if (timedOut && late && typeof late.close === 'function') { try { void late.close().catch(() => {}) } catch { /* 已关 */ } }
|
|
948
|
+
}, () => {})
|
|
949
|
+
return guarded
|
|
950
|
+
}
|
|
951
|
+
const closeAttempt = (ctx) => (cfg.shutdownTimeoutMs > 0 ? withTimeout(ctx.close(), cfg.shutdownTimeoutMs, '浏览器关闭') : ctx.close())
|
|
952
|
+
|
|
953
|
+
async function launch() {
|
|
954
|
+
if (context) return context
|
|
955
|
+
if (launching) return launching
|
|
956
|
+
launching = (async () => {
|
|
957
|
+
/* 孤儿清扫不放在启动主路径上:Windows 枚举一次进程要 ~800ms(PowerShell + CIM),
|
|
958
|
+
而真孤儿只会在「profile 被占」时挡路——那种情况下面的撞锁分支会强制清扫并重试。
|
|
959
|
+
常规清扫只在服务启动时做一次(relay.prepare,且不阻塞就绪)。 */
|
|
960
|
+
const attempts = []
|
|
961
|
+
/* stealth:优先用上次探测到的正牌 UA 起(连 HTTP 头一起干净);首启无缓存则起后再探测并重启一次。
|
|
962
|
+
UA 字符串按 Chrome 削减规则是 major.0.0.0,完整版本另外记(只给 UA-CH 的高熵字段)。 */
|
|
963
|
+
const cachedUa = cfg.stealth ? readUaCache(hostDir) : null
|
|
964
|
+
let uaHint = cachedUa ? cachedUa.ua : ''
|
|
965
|
+
let uaFullHint = cachedUa ? cachedUa.build : ''
|
|
966
|
+
const candidates = []
|
|
967
|
+
if (cfg.executablePath) candidates.push({ label: `executablePath(${cfg.executablePath})`, options: { executablePath: cfg.executablePath } })
|
|
968
|
+
if (cfg.channel) candidates.push({ label: `channel:${cfg.channel}`, options: { channel: cfg.channel } })
|
|
969
|
+
/* 实测(bench/probe-stealth-modes.mjs):Playwright 默认的 headless 走 chromium_headless_shell,
|
|
970
|
+
淘宝 baxia 会直接判定异常并下发 punish 框;`channel: 'chromium'` 是完整浏览器的新无头模式,
|
|
971
|
+
同一台机器上 punish 从 4 个降到 0。所以反检测模式下优先完整浏览器。 */
|
|
972
|
+
if (cfg.stealth) candidates.push({ label: 'channel:chromium', options: { channel: 'chromium' } })
|
|
973
|
+
candidates.push({ label: 'chromium', options: {} })
|
|
974
|
+
if (process.platform === 'win32') {
|
|
975
|
+
candidates.push({ label: 'channel:msedge', options: { channel: 'msedge' } })
|
|
976
|
+
candidates.push({ label: 'channel:chrome', options: { channel: 'chrome' } })
|
|
977
|
+
} else {
|
|
978
|
+
candidates.push({ label: 'channel:chrome', options: { channel: 'chrome' } })
|
|
979
|
+
candidates.push({ label: 'channel:msedge', options: { channel: 'msedge' } })
|
|
980
|
+
}
|
|
981
|
+
const seen = new Set()
|
|
982
|
+
for (const candidate of candidates) {
|
|
983
|
+
const key = candidate.label
|
|
984
|
+
if (seen.has(key)) continue
|
|
985
|
+
seen.add(key)
|
|
986
|
+
/* 每个候选最多试两次:首次撞 profile 锁(ProcessSingleton)时强制清扫
|
|
987
|
+
占用该 profile 的进程(无论父进程死活——profile 每会话独占,撞锁即冲突),
|
|
988
|
+
然后原样重试一次。其余错误直接记入明细换下一个候选。 */
|
|
989
|
+
/* 每个候选最多重起一次(换 UA)。计数放在 pass 循环外:放里面会被 pass 递增重置,
|
|
990
|
+
变成「每轮都重起」,启动时间翻几倍。 */
|
|
991
|
+
let relaunched = false
|
|
992
|
+
for (let pass = 0; pass < 2; pass += 1) {
|
|
993
|
+
const launchUa = uaHint
|
|
994
|
+
try {
|
|
995
|
+
const ctx = await launchAttempt(pw.chromium.launchPersistentContext(profileDir, {
|
|
996
|
+
headless: cfg.headless,
|
|
997
|
+
viewport: { width: cfg.viewportWidth, height: cfg.viewportHeight },
|
|
998
|
+
/* 反自动化:去掉 --enable-automation(它会让 navigator.webdriver 为 true、
|
|
999
|
+
并在窗口上挂「正在受到自动测试软件控制」条),关掉 Blink 的自动化特征,
|
|
1000
|
+
并把 UA 换成与 JS 侧一致的正牌 Chrome(HeadlessChrome 是最显眼的标记)。 */
|
|
1001
|
+
...(cfg.stealth ? {
|
|
1002
|
+
ignoreDefaultArgs: ['--enable-automation'],
|
|
1003
|
+
/* 口径一致:Accept-Language / 时区 / 屏幕尺寸都要和 JS 侧补丁报的对上。
|
|
1004
|
+
locale 决定 Accept-Language 头与 navigator.language;timezoneId 用宿主时区
|
|
1005
|
+
(和 Intl 报的一致);screen 给一个常见桌面分辨率(无头默认屏幕=视口,很假)。
|
|
1006
|
+
window-size = 视口 + 一点窗口边框,让 outerHeight > innerHeight 像真窗口。 */
|
|
1007
|
+
locale: 'zh-CN',
|
|
1008
|
+
timezoneId: (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || 'Asia/Shanghai' } catch { return 'Asia/Shanghai' } })(),
|
|
1009
|
+
screen: { width: 1920, height: 1080 },
|
|
1010
|
+
args: ['--disable-blink-features=AutomationControlled', `--window-size=${cfg.viewportWidth},${cfg.viewportHeight + 100}`],
|
|
1011
|
+
...(uaHint ? { userAgent: uaHint } : {}),
|
|
1012
|
+
} : {}),
|
|
1013
|
+
...candidate.options,
|
|
1014
|
+
}))
|
|
1015
|
+
context = ctx
|
|
1016
|
+
channelUsed = candidate.label
|
|
1017
|
+
/* 真实内核 UA 对齐:缓存里的版本必须与本次启动的内核一致。
|
|
1018
|
+
首启无缓存、缓存是假的、或换了 channel 都会不一致——那就带真实 UA 重起一次,
|
|
1019
|
+
让 HTTP 头与 JS 侧报同一个版本(每个候选只重起一次,避免冷启动死循环)。 */
|
|
1020
|
+
if (cfg.stealth) {
|
|
1021
|
+
const probe = ctx.pages()[0] || (typeof ctx.newPage === 'function' ? await ctx.newPage() : null)
|
|
1022
|
+
/* UA 探测也在启动关键路径上:CDP/evaluate 卡死时 8s 封顶,降级为「无真实 UA」。 */
|
|
1023
|
+
let real = null
|
|
1024
|
+
if (probe) { try { real = await withTimeout(detectRealUserAgent(probe), 8000, '真实 UA 探测') } catch { real = null } }
|
|
1025
|
+
if (real) {
|
|
1026
|
+
detectedUa = real.ua
|
|
1027
|
+
detectedUaFull = real.build
|
|
1028
|
+
uaHint = real.ua
|
|
1029
|
+
uaFullHint = real.build
|
|
1030
|
+
writeUaCache(hostDir, real.ua, real.build)
|
|
1031
|
+
} else if (uaHint) {
|
|
1032
|
+
detectedUa = uaHint
|
|
1033
|
+
}
|
|
1034
|
+
/* 判据是「本次实际用出去的 UA」:拿它和真实值比,才不会每轮都判成不一致。 */
|
|
1035
|
+
if (!relaunched && real && launchUa !== real.ua) {
|
|
1036
|
+
relaunched = true
|
|
1037
|
+
context = null
|
|
1038
|
+
try { await closeAttempt(ctx) } catch { /* 已关/超时:下面重起会撞锁再强清 */ }
|
|
1039
|
+
continue /* 同一候选带真实 UA 重起一次 */
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
/* 指纹补丁必须在任何导航之前注入:addInitScript 对之后创建的文档生效。 */
|
|
1043
|
+
if (cfg.stealth && typeof ctx.addInitScript === 'function') {
|
|
1044
|
+
try {
|
|
1045
|
+
await ctx.addInitScript({
|
|
1046
|
+
content: stealthInitScript({
|
|
1047
|
+
platform: process.platform === 'win32' ? 'Win32' : process.platform === 'darwin' ? 'MacIntel' : 'Linux x86_64',
|
|
1048
|
+
languages: ['zh-CN', 'zh', 'en-US', 'en'],
|
|
1049
|
+
ua: uaHint || undefined,
|
|
1050
|
+
uaFull: uaFullHint || undefined,
|
|
1051
|
+
screen: { width: 1920, height: 1080 },
|
|
1052
|
+
}),
|
|
1053
|
+
})
|
|
1054
|
+
} catch { /* 老驱动不支持:stealth 降级,不影响可用性 */ }
|
|
1055
|
+
}
|
|
1056
|
+
/* 先把保险箱里的 cookie 注回去,再注册页面与恢复标签:
|
|
1057
|
+
恢复出来的页面一加载就是已登录状态,不会先闪一下登录页。
|
|
1058
|
+
注入失败(cookie 全过期/坏数据)不影响启动。 */
|
|
1059
|
+
if (cfg.loginVault && typeof ctx.addCookies === 'function') {
|
|
1060
|
+
try {
|
|
1061
|
+
const cookies = readVault(hostDir)
|
|
1062
|
+
vaultInjected = cookies.length
|
|
1063
|
+
if (cookies.length) await ctx.addCookies(cookies)
|
|
1064
|
+
} catch { vaultInjected = 0 }
|
|
1065
|
+
}
|
|
1066
|
+
for (const page of ctx.pages()) { registerPage(page); await applyUaHints(page) }
|
|
1067
|
+
ctx.on('page', (page) => { registerPage(page); activeTabId = tabIds.get(page); void applyUaHints(page) })
|
|
1068
|
+
if (!activeTabId && tabs.size) activeTabId = [...tabs.keys()][0]
|
|
1069
|
+
await restoreJournal(ctx)
|
|
1070
|
+
return ctx
|
|
1071
|
+
} catch (error) {
|
|
1072
|
+
const msg = String(error && error.message || error)
|
|
1073
|
+
/* 撞 profile 锁或启动超时:都可能有一个占着 profile 的进程在挡路
|
|
1074
|
+
(超时往往是半启动的浏览器卡住了)。强清占用者后重试本候选一次。 */
|
|
1075
|
+
const timedOut = !!(error && error.code === 'TIMEOUT')
|
|
1076
|
+
if (pass === 0 && cfg.reapOrphans && (isProfileLockError(msg) || timedOut)) {
|
|
1077
|
+
try {
|
|
1078
|
+
const swept = await reapOrphanBrowsers({ profileDirs: [profileDir], processOps: ops, force: true })
|
|
1079
|
+
counters.orphansKilled += swept.killed.length
|
|
1080
|
+
if (swept.killed.length) continue // 清掉了占用者 → 重试本候选
|
|
1081
|
+
} catch { /* 清扫失败 → 按原错误记录 */ }
|
|
1082
|
+
}
|
|
1083
|
+
attempts.push(`${candidate.label}: ${msg.split('\n')[0].slice(0, 200)}`)
|
|
1084
|
+
break
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
throw engineError('ENGINE_LAUNCH_FAILED',
|
|
1089
|
+
`浏览器启动失败(已尝试 ${attempts.length} 种方式)`,
|
|
1090
|
+
`安装 Playwright Chromium(npx playwright install chromium)或系统 Chrome/Edge 后重试。尝试明细:${attempts.join(';')}`)
|
|
1091
|
+
})()
|
|
1092
|
+
try {
|
|
1093
|
+
return await launching
|
|
1094
|
+
} finally {
|
|
1095
|
+
launching = null
|
|
1096
|
+
}
|
|
1097
|
+
}
|
|
1098
|
+
|
|
1099
|
+
async function ensureTab(tabId) {
|
|
1100
|
+
touch()
|
|
1101
|
+
await launch()
|
|
1102
|
+
let id = tabId || activeTabId
|
|
1103
|
+
if (id && !tabs.has(id)) {
|
|
1104
|
+
throw engineError('TAB_UNKNOWN', `标签页 ${id} 不存在`, '用 browser_tabs(action=list) 查看现有标签页。')
|
|
1105
|
+
}
|
|
1106
|
+
if (!id) {
|
|
1107
|
+
const page = await context.newPage()
|
|
1108
|
+
id = registerPage(page)
|
|
1109
|
+
await applyUaHints(page)
|
|
1110
|
+
activeTabId = id
|
|
1111
|
+
}
|
|
1112
|
+
if (!activeTabId) activeTabId = id
|
|
1113
|
+
return { id, page: tabs.get(id) }
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
/* ---- 快照 ---- */
|
|
1117
|
+
/**
|
|
1118
|
+
* 动作后落定:Playwright 的 click/press 只等到导航「提交」,不等新文档 DOM 就绪,
|
|
1119
|
+
* 立刻 evaluate 会拍到空页(真实站点上很常见)。这里补一次 domcontentloaded 等待,然后:
|
|
1120
|
+
* - 动作没改 DOM(空点击/聚焦/滚动)→ 只让出一个宏任务(~1ms);
|
|
1121
|
+
* - 动作改了 DOM → 再补一帧(~16ms),保证框架的渲染已经提交。
|
|
1122
|
+
* 实测 rAF 在无头浏览器里就是整整 16.5ms,无差别等待等于每次动作白扔一帧。
|
|
1123
|
+
*/
|
|
1124
|
+
async function settle(page) {
|
|
1125
|
+
try {
|
|
1126
|
+
await page.waitForLoadState('domcontentloaded', { timeout: 5000 })
|
|
1127
|
+
} catch { /* 未发生导航 / 站点慢:继续拍当前状态 */ }
|
|
1128
|
+
try {
|
|
1129
|
+
await withTimeout(page.evaluate(() => new Promise((done) => {
|
|
1130
|
+
let mutated = false
|
|
1131
|
+
let finished = false
|
|
1132
|
+
let timer = null
|
|
1133
|
+
const finish = () => {
|
|
1134
|
+
if (finished) return
|
|
1135
|
+
finished = true
|
|
1136
|
+
try { observer.disconnect() } catch { /* 页面已销毁 */ }
|
|
1137
|
+
if (timer) clearTimeout(timer)
|
|
1138
|
+
done()
|
|
1139
|
+
}
|
|
1140
|
+
const observer = new MutationObserver(() => { mutated = true })
|
|
1141
|
+
try {
|
|
1142
|
+
observer.observe(document.documentElement, { childList: true, subtree: true, attributes: true, characterData: true })
|
|
1143
|
+
} catch { done(); return }
|
|
1144
|
+
timer = setTimeout(finish, 200)
|
|
1145
|
+
setTimeout(() => {
|
|
1146
|
+
if (!mutated) { finish(); return }
|
|
1147
|
+
requestAnimationFrame(finish)
|
|
1148
|
+
}, 0)
|
|
1149
|
+
})), 800, '等待渲染')
|
|
1150
|
+
} catch { /* 页面已关闭 / 上下文被导航销毁:按当前状态继续 */ }
|
|
1151
|
+
}
|
|
1152
|
+
|
|
1153
|
+
/** 让位一帧 + 一次宏任务:比固定 sleep 快 4 倍,仍能给渲染/事件回调留出机会。 */
|
|
1154
|
+
async function nextFrame(page) {
|
|
1155
|
+
try {
|
|
1156
|
+
await withTimeout(page.evaluate(() => new Promise((done) => {
|
|
1157
|
+
requestAnimationFrame(() => setTimeout(done, 0))
|
|
1158
|
+
})), 800, '等待渲染')
|
|
1159
|
+
} catch { /* 页面已关闭 / 上下文被导航销毁:按当前状态继续 */ }
|
|
1160
|
+
}
|
|
1161
|
+
|
|
1162
|
+
/* ---- 拟人输入(humanize 关闭时全部退化为最省时的等价动作)---- */
|
|
1163
|
+
|
|
1164
|
+
/**
|
|
1165
|
+
* 亚帧停顿直接跳过:无头里 waitForTimeout(1) 实测代价 ~30ms(等于整整一帧),
|
|
1166
|
+
* 而 1–3ms 的「微停顿」在页面上完全看不出来——拟人细节要付钱,但不能付成两帧。
|
|
1167
|
+
*/
|
|
1168
|
+
function sleepMs(page, ms) {
|
|
1169
|
+
if (!(ms >= 4)) return Promise.resolve()
|
|
1170
|
+
return page.waitForTimeout(ms)
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
async function humanPause(page, range) {
|
|
1174
|
+
await sleepMs(page, randInt(rng, range[0], range[1]))
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
/**
|
|
1178
|
+
* 真实鼠标点击:先沿贝塞尔轨迹移动(最小急动度 + 微颤),再按下 → 按住 → 松开。
|
|
1179
|
+
* fast 档轨迹点一次并发送达(CDP 队列保序):4 个点从 48.7ms 降到 4.3ms;
|
|
1180
|
+
* normal/careful 档按最小急动度时间规整逐点送达——事件间隔与真人一致,
|
|
1181
|
+
* 避免「N 个 mousemove 时间戳全相同」这种显著机器特征。
|
|
1182
|
+
* verify(可选):按下前用同一相对落点复验一次。反应停顿 + 轨迹移动这段时间里
|
|
1183
|
+
* 页面可能因懒加载/动画/平滑滚动移位——复验发现移位就改点新坐标,目标被遮挡
|
|
1184
|
+
* 或消失就返回 ok:false 交回 Playwright 的 locator.click 处理。
|
|
1185
|
+
*/
|
|
1186
|
+
async function pointerClick(page, tabId, x, y, verify) {
|
|
1187
|
+
const input = await openInput(page)
|
|
1188
|
+
const from = mouseAt.get(tabId) || {
|
|
1189
|
+
x: Math.max(1, x - randInt(rng, 90, 300)),
|
|
1190
|
+
y: Math.max(1, y - randInt(rng, 40, 200)),
|
|
1191
|
+
}
|
|
1192
|
+
if (human) await humanPause(page, human.reactionMs)
|
|
1193
|
+
const path = human ? bezierPath(from, { x, y }, rng, human) : [{ x, y }]
|
|
1194
|
+
if (human && human.pacedMoves && path.length > 1) {
|
|
1195
|
+
const total = moveDurationMs(Math.hypot(x - from.x, y - from.y), rng, human)
|
|
1196
|
+
const delays = moveDelays(path, total)
|
|
1197
|
+
for (let i = 0; i < path.length; i += 1) {
|
|
1198
|
+
if (delays[i] > 0) await sleepMs(page, delays[i])
|
|
1199
|
+
await input.move([path[i]])
|
|
1200
|
+
}
|
|
1201
|
+
} else {
|
|
1202
|
+
await input.move(path)
|
|
1203
|
+
}
|
|
1204
|
+
if (verify) {
|
|
1205
|
+
const fresh = await verify()
|
|
1206
|
+
if (!fresh || fresh.hittable === false) {
|
|
1207
|
+
mouseAt.set(tabId, { x, y })
|
|
1208
|
+
return { ok: false }
|
|
1209
|
+
}
|
|
1210
|
+
if (Number.isFinite(fresh.x) && Number.isFinite(fresh.y)) { x = fresh.x; y = fresh.y }
|
|
1211
|
+
}
|
|
1212
|
+
mouseAt.set(tabId, { x, y })
|
|
1213
|
+
/* 到达后、按下前的短暂停留(normal/careful):人眼确认落点再按。 */
|
|
1214
|
+
if (human && human.pacedMoves) await humanPause(page, human.dwellMs)
|
|
1215
|
+
/* fast 档按住时长只有 1–4ms,等于一次帧内按下松开;normal/careful 保留真实停顿。
|
|
1216
|
+
minClickHoldMs 给风控敏感站点一个「按住时长下限」的固定参数。 */
|
|
1217
|
+
const hold = Math.max(human ? randInt(rng, human.holdMs[0], human.holdMs[1]) : 0, Number(cfg.minClickHoldMs) || 0)
|
|
1218
|
+
await input.click(x, y, hold)
|
|
1219
|
+
return { ok: true, x, y }
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
/** 敲一个字符:走真实 keydown/keypress/input/keyup(换行用 Enter)。 */
|
|
1223
|
+
async function typeChar(page, ch) {
|
|
1224
|
+
const input = await openInput(page)
|
|
1225
|
+
if (ch === '\n' || ch === '\r') { await input.press('Enter'); return }
|
|
1226
|
+
await input.type(ch)
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
/**
|
|
1230
|
+
* 逐字符拟人输入:高斯抖动间隔 + 词间停顿 + 偶发邻键手误与退格。
|
|
1231
|
+
* 超过档位阈值的长文本走 insertText(真人填长文也是粘贴,逐字敲反而失真又慢)。
|
|
1232
|
+
*/
|
|
1233
|
+
async function typeText(page, text) {
|
|
1234
|
+
const value = String(text ?? '')
|
|
1235
|
+
const input = await openInput(page)
|
|
1236
|
+
if (!human) {
|
|
1237
|
+
await input.type(value)
|
|
1238
|
+
return { chars: value.length, pasted: false, degraded: true }
|
|
1239
|
+
}
|
|
1240
|
+
if (value.length > human.pasteOverChars) {
|
|
1241
|
+
await input.insertText(value)
|
|
1242
|
+
return { chars: value.length, pasted: true }
|
|
1243
|
+
}
|
|
1244
|
+
/* 连打的字符攒成一个 keyboard.type 批量发:事件之间的间隔本来就是 0,
|
|
1245
|
+
分 N 次发只是多付 N 次 CDP 往返(实测每次 ~2ms),时序特征完全一样。 */
|
|
1246
|
+
let burst = ''
|
|
1247
|
+
const flush = async () => {
|
|
1248
|
+
if (!burst) return
|
|
1249
|
+
const chunk = burst
|
|
1250
|
+
burst = ''
|
|
1251
|
+
await input.type(chunk)
|
|
1252
|
+
}
|
|
1253
|
+
for (const ev of typingPlan(value, rng, human)) {
|
|
1254
|
+
/* 亚帧间隔不等待:见 sleepMs 的注释(waitForTimeout(1) 也要一整帧)。 */
|
|
1255
|
+
if (ev.type === 'wait') { await flush(); await sleepMs(page, ev.ms); continue }
|
|
1256
|
+
if (ev.type === 'key') {
|
|
1257
|
+
if (ev.delayMs > 0) { await flush(); await sleepMs(page, ev.delayMs) }
|
|
1258
|
+
burst += ev.key
|
|
1259
|
+
continue
|
|
1260
|
+
}
|
|
1261
|
+
if (ev.type === 'typo') {
|
|
1262
|
+
await flush()
|
|
1263
|
+
await sleepMs(page, ev.delayMs)
|
|
1264
|
+
await typeChar(page, ev.key)
|
|
1265
|
+
await sleepMs(page, ev.fixMs)
|
|
1266
|
+
await input.press('Backspace')
|
|
1267
|
+
}
|
|
1268
|
+
}
|
|
1269
|
+
await flush()
|
|
1270
|
+
return { chars: value.length, pasted: false }
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/**
|
|
1274
|
+
* 点一个目标:坐标点击优先(比 locator.click 少掉稳定帧等待与 actionability 轮询),
|
|
1275
|
+
* 量框与命中校验合成一次页内调用,验不过才回落 Playwright 的 locator.click
|
|
1276
|
+
* (它会自己滚动、等可点、等不被遮挡)。
|
|
1277
|
+
*/
|
|
1278
|
+
async function clickTarget(page, tabId, target) {
|
|
1279
|
+
/* 没有真实鼠标(老驱动/假页面)就交回 Playwright 的 locator.click。 */
|
|
1280
|
+
if (typeof page.mouse?.click !== 'function') {
|
|
1281
|
+
const { locator, entry: plain } = await locatorForTarget(page, tabId, target)
|
|
1282
|
+
await locator.click({ timeout: cfg.actionTimeoutMs })
|
|
1283
|
+
return plain
|
|
1284
|
+
}
|
|
1285
|
+
/* 随机落点按比例给出:人不会每次都精准命中正中心。 */
|
|
1286
|
+
const aim = { fx: 0.3 + rng() * 0.4, fy: 0.3 + rng() * 0.4 }
|
|
1287
|
+
/* ref 路径省一次 locator.count():唯一性校验和取点合成同一个页内调用。 */
|
|
1288
|
+
if (target.ref) {
|
|
1289
|
+
const entry = resolveRef(tabId, target.ref)
|
|
1290
|
+
const spot = await probeCssPoint(page, entry.css, aim)
|
|
1291
|
+
if (spot && spot.matches === 1) {
|
|
1292
|
+
if (spot.sized && spot.inViewport && spot.hittable) {
|
|
1293
|
+
/* 按下前复验:移位就改点新坐标;被遮挡/消失则走下面的 locator 回落。 */
|
|
1294
|
+
const res = await pointerClick(page, tabId, spot.x, spot.y, async () => {
|
|
1295
|
+
const s = await probeCssPoint(page, entry.css, aim)
|
|
1296
|
+
return s && s.matches === 1 && s.sized ? s : null
|
|
1297
|
+
})
|
|
1298
|
+
if (res.ok) return entry
|
|
1299
|
+
}
|
|
1300
|
+
} else if (spot && spot.matches !== 1) {
|
|
1301
|
+
throw engineError('STALE_SNAPSHOT',
|
|
1302
|
+
`ref=${target.ref}(${entry.role}${entry.name ? ` "${entry.name}"` : ''})定位到 ${spot.matches} 个元素`,
|
|
1303
|
+
'快照已过期;重新 browser_snapshot 后用新 ref。')
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
const { locator, entry } = await locatorForTarget(page, tabId, target)
|
|
1307
|
+
const probe = await probeClickPoint(locator, aim)
|
|
1308
|
+
if (!probe) {
|
|
1309
|
+
await locator.click({ timeout: cfg.actionTimeoutMs })
|
|
1310
|
+
return entry
|
|
1311
|
+
}
|
|
1312
|
+
let spot = probe
|
|
1313
|
+
/* 元素不在视口里才滚动(scrollIntoViewIfNeeded 本身要 ~35ms),滚完重新取点。 */
|
|
1314
|
+
if (!spot.inViewport) {
|
|
1315
|
+
try { await locator.scrollIntoViewIfNeeded({ timeout: cfg.actionTimeoutMs }) } catch { /* 元素不可滚动 */ }
|
|
1316
|
+
spot = await probeClickPoint(locator, aim)
|
|
1317
|
+
/* 平滑滚动/懒加载可能还在移位:等到连续两次取点一致再按(有界,最多 3 轮)。 */
|
|
1318
|
+
for (let i = 0; i < 3 && spot; i += 1) {
|
|
1319
|
+
await sleepMs(page, 80)
|
|
1320
|
+
const again = await probeClickPoint(locator, aim)
|
|
1321
|
+
if (!again) break
|
|
1322
|
+
const stable = Math.abs(again.x - spot.x) <= 0.5 && Math.abs(again.y - spot.y) <= 0.5
|
|
1323
|
+
spot = again
|
|
1324
|
+
if (stable) break
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
if (!spot || !spot.inViewport || !spot.hittable) {
|
|
1328
|
+
await locator.click({ timeout: cfg.actionTimeoutMs })
|
|
1329
|
+
return entry
|
|
1330
|
+
}
|
|
1331
|
+
const res = await pointerClick(page, tabId, spot.x, spot.y, () => probeClickPoint(locator, aim))
|
|
1332
|
+
if (!res.ok) await locator.click({ timeout: cfg.actionTimeoutMs })
|
|
1333
|
+
return entry
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
/** 按 CSS 取点(ref 的 css 路径用):一次页内调用同时给出唯一性、落点、视口、命中。 */
|
|
1337
|
+
async function probeCssPoint(page, css, aim) {
|
|
1338
|
+
try {
|
|
1339
|
+
return await page.evaluate(([sel, f]) => {
|
|
1340
|
+
let nodes
|
|
1341
|
+
try { nodes = document.querySelectorAll(sel) } catch { return { matches: -1 } }
|
|
1342
|
+
if (nodes.length !== 1) return { matches: nodes.length }
|
|
1343
|
+
const el = nodes[0]
|
|
1344
|
+
const rect = el.getBoundingClientRect()
|
|
1345
|
+
if (!(rect.width >= 2 && rect.height >= 2)) return { matches: 1, sized: false }
|
|
1346
|
+
/* 落点取整:实测 Blink 在命中判定与事件派发前就把 CDP 小数坐标取整(clientX/Y 恒整数),
|
|
1347
|
+
小数不带来精度,反而让页内校验与实际命中不一致。
|
|
1348
|
+
在「可见交集」里取点:元素部分出视口时点可见部分即可,不必回落滚动等待(实测移动目标提速)。 */
|
|
1349
|
+
const vw = window.innerWidth || 0
|
|
1350
|
+
const vh = window.innerHeight || 0
|
|
1351
|
+
const ix = Math.max(rect.x, 0)
|
|
1352
|
+
const iy = Math.max(rect.y, 0)
|
|
1353
|
+
const iw = Math.max(0, Math.min(rect.x + rect.width, vw) - ix)
|
|
1354
|
+
const ih = Math.max(0, Math.min(rect.y + rect.height, vh) - iy)
|
|
1355
|
+
const x = Math.round(ix + iw * f.fx)
|
|
1356
|
+
const y = Math.round(iy + ih * f.fy)
|
|
1357
|
+
const inViewport = iw >= 2 && ih >= 2
|
|
1358
|
+
const hit = document.elementFromPoint(x, y)
|
|
1359
|
+
const hittable = !!hit && (el === hit || el.contains(hit) || hit.contains(el))
|
|
1360
|
+
return { matches: 1, sized: true, x, y, inViewport, hittable }
|
|
1361
|
+
}, [css, aim], { timeout: cfg.actionTimeoutMs })
|
|
1362
|
+
} catch {
|
|
1363
|
+
return null
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
/** 一次页内调用同时拿到落点、是否在视口、是否命中:省掉一次 CDP 往返(~5ms)。 */
|
|
1368
|
+
async function probeClickPoint(locator, aim) {
|
|
1369
|
+
try {
|
|
1370
|
+
return await locator.evaluate((el, f) => {
|
|
1371
|
+
if (!el.isConnected) return null
|
|
1372
|
+
const rect = el.getBoundingClientRect()
|
|
1373
|
+
if (!(rect.width >= 2 && rect.height >= 2)) return null
|
|
1374
|
+
/* 落点取整 + 可见交集取点:与 probeCssPoint 同一套实测结论
|
|
1375
|
+
(Blink 派发前取整小数坐标;部分可见元素点可见部分,不回落滚动等待)。 */
|
|
1376
|
+
const vw = window.innerWidth || 0
|
|
1377
|
+
const vh = window.innerHeight || 0
|
|
1378
|
+
const ix = Math.max(rect.x, 0)
|
|
1379
|
+
const iy = Math.max(rect.y, 0)
|
|
1380
|
+
const iw = Math.max(0, Math.min(rect.x + rect.width, vw) - ix)
|
|
1381
|
+
const ih = Math.max(0, Math.min(rect.y + rect.height, vh) - iy)
|
|
1382
|
+
const x = Math.round(ix + iw * f.fx)
|
|
1383
|
+
const y = Math.round(iy + ih * f.fy)
|
|
1384
|
+
const inViewport = iw >= 2 && ih >= 2
|
|
1385
|
+
const hit = document.elementFromPoint(x, y)
|
|
1386
|
+
const hittable = !!hit && (el === hit || el.contains(hit) || hit.contains(el))
|
|
1387
|
+
return { x, y, inViewport, hittable }
|
|
1388
|
+
}, aim, { timeout: cfg.actionTimeoutMs })
|
|
1389
|
+
} catch {
|
|
1390
|
+
return null
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
/** 填表:拟人档位下先清空、聚焦、再逐字符敲;否则一次 fill 到位。 */
|
|
1395
|
+
async function fillTarget(page, tabId, target, text, submit) {
|
|
1396
|
+
const { locator, entry } = await locatorForTarget(page, tabId, target)
|
|
1397
|
+
const value = String(text ?? '')
|
|
1398
|
+
let typed = null
|
|
1399
|
+
/* 拟人输入需要真实 keyboard;老驱动/假页面没有就退回一次 fill(typeText 内部会降级)。 */
|
|
1400
|
+
const input = human ? await openInput(page) : null
|
|
1401
|
+
if (human && input.hasKeyboard && value.length <= human.pasteOverChars) {
|
|
1402
|
+
await locator.focus({ timeout: cfg.actionTimeoutMs })
|
|
1403
|
+
/* 先全选再打字覆盖:省掉 locator.fill('') 的 actionability 检查(实测 ~30ms)。 */
|
|
1404
|
+
await input.press(process.platform === 'darwin' ? 'Meta+a' : 'Control+a')
|
|
1405
|
+
typed = await typeText(page, value)
|
|
1406
|
+
} else {
|
|
1407
|
+
await locator.fill(value, { timeout: cfg.actionTimeoutMs })
|
|
1408
|
+
}
|
|
1409
|
+
if (submit) await locator.press('Enter', { timeout: cfg.actionTimeoutMs })
|
|
1410
|
+
return { entry, typed }
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
/**
|
|
1414
|
+
* 滚动:拟人档位下拆成多次滚轮 tick(动量衰减),否则一次滚轮。
|
|
1415
|
+
* tick 走输入通道并发送达,页面上仍然是 N 次 wheel 事件,只是不再逐帧等回执。
|
|
1416
|
+
*/
|
|
1417
|
+
async function scrollByAmount(page, delta) {
|
|
1418
|
+
const input = await openInput(page)
|
|
1419
|
+
/* 没有真实滚轮(老驱动/假页面)就用页面内滚动,语义等价。 */
|
|
1420
|
+
if (input.kind === 'page' && typeof page.mouse?.wheel !== 'function') {
|
|
1421
|
+
await page.evaluate((dy) => window.scrollBy(0, dy), delta)
|
|
1422
|
+
return 1
|
|
1423
|
+
}
|
|
1424
|
+
if (human) await humanPause(page, human.reactionMs)
|
|
1425
|
+
const plan = human ? scrollPlan(delta, rng, human) : [{ dy: delta }]
|
|
1426
|
+
/* 滚轮落点给个轻微偏移:真人滚轮时指针不会钉在视口正中。 */
|
|
1427
|
+
const x = Math.round(cfg.viewportWidth / 2 + (rng() - 0.5) * 120)
|
|
1428
|
+
const y = Math.round(cfg.viewportHeight / 2 + (rng() - 0.5) * 120)
|
|
1429
|
+
await input.wheel(plan.map((step) => ({ x, y, dy: step.dy })))
|
|
1430
|
+
return plan.length
|
|
1431
|
+
}
|
|
1432
|
+
|
|
1433
|
+
async function takeSnapshot(page, tabId) {
|
|
1434
|
+
const raw = await withTimeout(page.evaluate(pageSnapshotFunction), 8000, '页面快照')
|
|
1435
|
+
counters.snapshots += 1
|
|
1436
|
+
const registry = new Map()
|
|
1437
|
+
/* 页内快照按 e1..eN 编号;这里重映射成全局唯一 id,并同步改写文本里的 [ref=…]。 */
|
|
1438
|
+
const remap = new Map()
|
|
1439
|
+
for (const entry of parseSnapshotEntries(raw)) {
|
|
1440
|
+
const id = `e${nextRefId++}`
|
|
1441
|
+
remap.set(entry.ref, id)
|
|
1442
|
+
registry.set(id, { ...entry, ref: id })
|
|
1443
|
+
}
|
|
1444
|
+
refRegistries.set(tabId, registry)
|
|
1445
|
+
if (typeof raw.title === 'string') tabTitles.set(tabId, raw.title)
|
|
1446
|
+
const full = (typeof raw.text === 'string' ? raw.text : (raw.lines || []).join('\n'))
|
|
1447
|
+
.replace(/\[ref=(e\d+)\]/g, (m, old) => (remap.has(old) ? `[ref=${remap.get(old)}]` : m))
|
|
1448
|
+
let text = full
|
|
1449
|
+
let truncated = false
|
|
1450
|
+
if (text.length > cfg.maxSnapshotChars) {
|
|
1451
|
+
truncated = true
|
|
1452
|
+
text = text.slice(0, cfg.maxSnapshotChars) + `\n…(已截断:完整快照 ${full.length} 字符;已列出的 ref 仍可使用)`
|
|
1453
|
+
}
|
|
1454
|
+
snapshotChars.set(tabId, text.length)
|
|
1455
|
+
return {
|
|
1456
|
+
url: raw.url,
|
|
1457
|
+
title: raw.title,
|
|
1458
|
+
elements: raw.total,
|
|
1459
|
+
/* 交互控件数(不含 heading/img):observe 判断「应用渲染完没有」用它。
|
|
1460
|
+
假页面/旧快照没有这个字段时回落 total,行为与原来一致。 */
|
|
1461
|
+
interactive: typeof raw.interactive === 'number' ? raw.interactive : raw.total,
|
|
1462
|
+
truncated,
|
|
1463
|
+
text,
|
|
1464
|
+
}
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
/* ---- 观察:空白快照多半是「还没画完」 ---- */
|
|
1468
|
+
async function waitForQuiet(page, budgetMs) {
|
|
1469
|
+
try {
|
|
1470
|
+
await page.waitForLoadState('networkidle', { timeout: budgetMs })
|
|
1471
|
+
} catch { /* 有长轮询的站点永远不 idle:按预算到点就走 */ }
|
|
1472
|
+
await nextFrame(page)
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
/** 等 DOM 真的变一次(SPA 注入内容的信号),最多 budget 就到点。 */
|
|
1476
|
+
async function waitForDomChange(page, budgetMs) {
|
|
1477
|
+
try {
|
|
1478
|
+
await withTimeout(page.evaluate((budget) => new Promise((done) => {
|
|
1479
|
+
let settled = false
|
|
1480
|
+
let timer = null
|
|
1481
|
+
const finish = () => {
|
|
1482
|
+
if (settled) return
|
|
1483
|
+
settled = true
|
|
1484
|
+
try { observer.disconnect() } catch { /* 页面已销毁 */ }
|
|
1485
|
+
if (timer) clearTimeout(timer)
|
|
1486
|
+
requestAnimationFrame(() => setTimeout(done, 0))
|
|
1487
|
+
}
|
|
1488
|
+
const observer = new MutationObserver(finish)
|
|
1489
|
+
timer = setTimeout(finish, budget)
|
|
1490
|
+
try {
|
|
1491
|
+
observer.observe(document.documentElement, { childList: true, subtree: true })
|
|
1492
|
+
} catch { finish() }
|
|
1493
|
+
}), budgetMs), budgetMs + 800, '等待页面渲染')
|
|
1494
|
+
} catch { /* 页面已关闭 / 导航中:按当前状态继续 */ }
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
/**
|
|
1498
|
+
* 等页面「动起来」:网络静默与 DOM 变更赛跑,谁先到就继续。
|
|
1499
|
+
* 纯静默页(无请求、等 JS 定时器渲内容)不必死等 networkidle 的 500ms 静默窗口。
|
|
1500
|
+
*/
|
|
1501
|
+
async function waitForRender(page, budgetMs) {
|
|
1502
|
+
const quiet = waitForQuiet(page, budgetMs).catch(() => {})
|
|
1503
|
+
const change = waitForDomChange(page, budgetMs).catch(() => {})
|
|
1504
|
+
await Promise.race([quiet, change])
|
|
1505
|
+
}
|
|
1506
|
+
|
|
1507
|
+
/**
|
|
1508
|
+
* 拍快照的兜底:SPA 首屏常见「domcontentloaded 已到、组件还没挂载」,
|
|
1509
|
+
* 这时拍出来是一张接近空白的树,模型只能干等再拍一次(盲等就是这么来的)。
|
|
1510
|
+
* 只在树非常薄时多给一个短窗口,正常页面零额外成本。
|
|
1511
|
+
*/
|
|
1512
|
+
async function observe(page, tabId) {
|
|
1513
|
+
const snapshot = await takeSnapshot(page, tabId)
|
|
1514
|
+
/* 门控用「交互控件数」而不是条目总数:标题/图片不算内容已渲染。
|
|
1515
|
+
SPA 空壳常只有一个 heading(实测 250ms 后才注入按钮),按总数早退会错过它们。 */
|
|
1516
|
+
const controls = typeof snapshot.interactive === 'number' ? snapshot.interactive : snapshot.elements
|
|
1517
|
+
if (controls >= 3) { walls.delete(tabId); return snapshot }
|
|
1518
|
+
/* 控件很少的页面可能本来就薄(内容页/文章/鉴权墙):读一段 body 文本再决定。
|
|
1519
|
+
DSH Web 401 鉴权页是纯文本、快照树为空,只有 body 文本能认出它;
|
|
1520
|
+
控件 ≥3 的正常页在上面已直接返回,零额外成本。 */
|
|
1521
|
+
let readyState = 'complete'
|
|
1522
|
+
let bodyText = ''
|
|
1523
|
+
try {
|
|
1524
|
+
const probe = await withTimeout(page.evaluate(() => ({
|
|
1525
|
+
ready: document.readyState,
|
|
1526
|
+
text: ((document.body && document.body.innerText) || '').slice(0, 400),
|
|
1527
|
+
})), 2000, '读取页面状态')
|
|
1528
|
+
if (probe && typeof probe.ready === 'string') readyState = probe.ready
|
|
1529
|
+
if (probe && typeof probe.text === 'string') bodyText = probe.text
|
|
1530
|
+
} catch { /* 页面已关闭或卡死 */ }
|
|
1531
|
+
const wall = dshAuthWallNote(bodyText)
|
|
1532
|
+
if (wall) walls.set(tabId, wall)
|
|
1533
|
+
/* 有真实控件,或正文足够长(内容页/鉴权墙)→ 认为已渲染;
|
|
1534
|
+
只有标题的空壳应用不算,给一个短窗口等控件注入。 */
|
|
1535
|
+
if (readyState === 'complete' && (controls > 0 || bodyText.trim().length >= 200)) {
|
|
1536
|
+
if (wall) snapshot.authWall = wall
|
|
1537
|
+
else walls.delete(tabId)
|
|
1538
|
+
return snapshot
|
|
1539
|
+
}
|
|
1540
|
+
await waitForRender(page, controls === 0 ? 1500 : 800)
|
|
1541
|
+
const second = await takeSnapshot(page, tabId)
|
|
1542
|
+
const out = second.elements >= snapshot.elements ? second : snapshot
|
|
1543
|
+
if (out.elements > 2) walls.delete(tabId)
|
|
1544
|
+
else if (wall) { walls.set(tabId, wall); out.authWall = wall }
|
|
1545
|
+
return out
|
|
1546
|
+
}
|
|
1547
|
+
|
|
1548
|
+
/* ---- 批量动作 ---- */
|
|
1549
|
+
/**
|
|
1550
|
+
* 下拉选择:先读一遍 option 再精确选中。
|
|
1551
|
+
* 直接用 selectOption({value}) 选不中时 Playwright 会一直等到 actionTimeout(15 s)才报错,
|
|
1552
|
+
* 值/文本两种写法各试一次就是 30 s——这里先把候选读出来,匹配不上立刻给可用选项。
|
|
1553
|
+
*/
|
|
1554
|
+
async function chooseOption(page, tabId, ref, value) {
|
|
1555
|
+
const { locator, entry } = await locatorFor(page, tabId, ref)
|
|
1556
|
+
const wanted = String(value ?? '')
|
|
1557
|
+
const options = await locator.evaluate((el) => (el.tagName === 'SELECT'
|
|
1558
|
+
? Array.from(el.options).map((o) => ({ value: o.value, label: (o.textContent || '').trim() }))
|
|
1559
|
+
: []))
|
|
1560
|
+
if (!options.length) {
|
|
1561
|
+
throw engineError('ARG_INVALID', `ref=${ref}(${entry.role})不是 <select>`, '下拉选择只对 select 元素有效。')
|
|
1562
|
+
}
|
|
1563
|
+
const matched = options.find((o) => o.value === wanted)
|
|
1564
|
+
|| options.find((o) => o.label === wanted)
|
|
1565
|
+
|| options.find((o) => o.label.includes(wanted))
|
|
1566
|
+
if (!matched) {
|
|
1567
|
+
throw engineError('ARG_INVALID',
|
|
1568
|
+
`下拉里没有选项「${wanted}」`,
|
|
1569
|
+
`可用选项:${options.map((o) => o.label || o.value).slice(0, 12).join(' / ')}`)
|
|
1570
|
+
}
|
|
1571
|
+
await locator.selectOption(matched.value, { timeout: cfg.actionTimeoutMs })
|
|
1572
|
+
return { applied: matched.label || matched.value, entry }
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
/**
|
|
1576
|
+
* 单步执行:只做动作、不拍快照。
|
|
1577
|
+
* 批量的意义就在于「一次往返做多件事」,中途拍快照会把 ref 重新编号,
|
|
1578
|
+
* 反而让同一批后面那些 ref 失效。
|
|
1579
|
+
*/
|
|
1580
|
+
async function runStep(page, tabId, op, step) {
|
|
1581
|
+
switch (op) {
|
|
1582
|
+
case 'click': {
|
|
1583
|
+
await clickTarget(page, tabId, { ref: step.ref, selector: step.selector, text: step.text })
|
|
1584
|
+
return
|
|
1585
|
+
}
|
|
1586
|
+
case 'fill': {
|
|
1587
|
+
await fillTarget(page, tabId, { ref: step.ref, selector: step.selector }, step.text, !!step.submit)
|
|
1588
|
+
return
|
|
1589
|
+
}
|
|
1590
|
+
case 'press': {
|
|
1591
|
+
if (step.ref || step.selector) {
|
|
1592
|
+
const { locator } = await locatorForTarget(page, tabId, { ref: step.ref, selector: step.selector })
|
|
1593
|
+
await locator.press(String(step.key || 'Enter'), { timeout: cfg.actionTimeoutMs })
|
|
1594
|
+
} else {
|
|
1595
|
+
await page.keyboard.press(String(step.key || 'Enter'))
|
|
1596
|
+
}
|
|
1597
|
+
return
|
|
1598
|
+
}
|
|
1599
|
+
case 'select': {
|
|
1600
|
+
await chooseOption(page, tabId, step.ref, step.value)
|
|
1601
|
+
return
|
|
1602
|
+
}
|
|
1603
|
+
case 'drag': {
|
|
1604
|
+
await dragBetween(page, tabId, step)
|
|
1605
|
+
return
|
|
1606
|
+
}
|
|
1607
|
+
case 'scroll': {
|
|
1608
|
+
const delta = step.direction === 'up' ? -Number(step.amount || 600) : Number(step.amount || 600)
|
|
1609
|
+
await scrollByAmount(page, delta)
|
|
1610
|
+
return
|
|
1611
|
+
}
|
|
1612
|
+
case 'wait': {
|
|
1613
|
+
if (step.selector) {
|
|
1614
|
+
await page.waitForSelector(String(step.selector), { timeout: Math.min(Number(step.ms) || cfg.actionTimeoutMs, cfg.actionTimeoutMs) })
|
|
1615
|
+
} else {
|
|
1616
|
+
await page.waitForTimeout(Math.min(Number(step.ms) || 300, 30000))
|
|
1617
|
+
}
|
|
1618
|
+
return
|
|
1619
|
+
}
|
|
1620
|
+
default:
|
|
1621
|
+
throw engineError('ARG_INVALID', `不支持的 op: ${op || '(空)'}`, '可用:click / fill / press / select / drag / scroll / wait')
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
/* ---- ref 解析 ---- */
|
|
1626
|
+
function resolveRef(tabId, ref) {
|
|
1627
|
+
const registry = refRegistries.get(tabId)
|
|
1628
|
+
const entry = registry && registry.get(String(ref))
|
|
1629
|
+
if (!entry) {
|
|
1630
|
+
/* ref 可能属于别的标签页(用户/并发动作切走了活动标签):别误报「快照过期」,
|
|
1631
|
+
直接指出它在哪、该怎么切回去,模型才不会对着空白页反复重拍快照。 */
|
|
1632
|
+
for (const [owner, reg] of refRegistries) {
|
|
1633
|
+
if (owner !== tabId && reg && reg.has(String(ref))) {
|
|
1634
|
+
throw engineError('TAB_MISMATCH',
|
|
1635
|
+
`ref=${ref} 属于标签页 ${owner},但当前活动标签是 ${tabId || '(无)'}`,
|
|
1636
|
+
`先 browser_tabs(action=select, tab=${owner}) 切回去,或给本次动作带 tab=${owner} 参数。`)
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
throw engineError('STALE_SNAPSHOT',
|
|
1640
|
+
`ref=${ref} 不在当前标签页最近的快照里`,
|
|
1641
|
+
'页面可能已变化或引用了别的标签页;先 browser_snapshot 重新观察,再用新 ref。')
|
|
1642
|
+
}
|
|
1643
|
+
return entry
|
|
1644
|
+
}
|
|
1645
|
+
|
|
1646
|
+
async function locatorFor(page, tabId, ref) {
|
|
1647
|
+
const entry = resolveRef(tabId, ref)
|
|
1648
|
+
const locator = page.locator(entry.css)
|
|
1649
|
+
const count = await locator.count()
|
|
1650
|
+
if (count !== 1) {
|
|
1651
|
+
throw engineError('STALE_SNAPSHOT',
|
|
1652
|
+
`ref=${ref}(${entry.role}${entry.name ? ` "${entry.name}"` : ''})定位到 ${count} 个元素`,
|
|
1653
|
+
'快照已过期;重新 browser_snapshot 后用新 ref。')
|
|
1654
|
+
}
|
|
1655
|
+
return { locator, entry }
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
/**
|
|
1659
|
+
* 目标定位:优先 ref;快照里没有的(无 role 的 div 按钮、滑块手柄)用 selector 或文本兜底。
|
|
1660
|
+
* 文本兜底按「按钮 → 链接 → 精确文本 → 含该文本」的顺序找第一个可见元素。
|
|
1661
|
+
*/
|
|
1662
|
+
async function locatorForTarget(page, tabId, { ref, selector, text } = {}) {
|
|
1663
|
+
if (ref) return locatorFor(page, tabId, ref)
|
|
1664
|
+
if (selector) {
|
|
1665
|
+
const locator = page.locator(String(selector))
|
|
1666
|
+
const count = await locator.count()
|
|
1667
|
+
if (!count) {
|
|
1668
|
+
throw engineError('TARGET_NOT_FOUND', `选择器没有匹配到元素:${selector}`, '检查 CSS 选择器,或先用 browser_snapshot 看页面结构。')
|
|
1669
|
+
}
|
|
1670
|
+
return { locator: locator.first(), entry: { role: '元素', name: String(selector) } }
|
|
1671
|
+
}
|
|
1672
|
+
if (text) {
|
|
1673
|
+
const wanted = String(text).trim()
|
|
1674
|
+
const candidates = [
|
|
1675
|
+
page.getByRole('button', { name: wanted, exact: true }),
|
|
1676
|
+
page.getByRole('link', { name: wanted, exact: true }),
|
|
1677
|
+
page.getByText(wanted, { exact: true }),
|
|
1678
|
+
page.getByText(wanted),
|
|
1679
|
+
]
|
|
1680
|
+
for (const candidate of candidates) {
|
|
1681
|
+
const count = await candidate.count()
|
|
1682
|
+
for (let i = 0; i < count; i += 1) {
|
|
1683
|
+
const one = candidate.nth(i)
|
|
1684
|
+
if (await one.isVisible().catch(() => false)) {
|
|
1685
|
+
return { locator: one, entry: { role: 'text', name: wanted } }
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
throw engineError('TARGET_NOT_FOUND', `页面上没找到可见的「${wanted}」`,
|
|
1690
|
+
'确认文案是否一致(可先 browser_snapshot 看),或改用 selector 精确定位。')
|
|
1691
|
+
}
|
|
1692
|
+
throw engineError('ARG_INVALID', '缺少目标:ref / selector / text 至少给一个',
|
|
1693
|
+
'ref 来自快照;快照里没有的元素用 selector 或 text。')
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
/* ---- 拖拽(滑块验证、拖放排序) ---- */
|
|
1697
|
+
async function dragBetween(page, tabId, target) {
|
|
1698
|
+
const from = await locatorForTarget(page, tabId, target)
|
|
1699
|
+
const box = await from.locator.boundingBox()
|
|
1700
|
+
if (!box) {
|
|
1701
|
+
throw engineError('TARGET_NOT_FOUND', '起点元素不可见,无法拖拽', '先 browser_scroll 把它滚到视口内,或截图确认。')
|
|
1702
|
+
}
|
|
1703
|
+
const sx = box.x + box.width / 2
|
|
1704
|
+
const sy = box.y + box.height / 2
|
|
1705
|
+
let tx = sx + Number(target.dx || 0)
|
|
1706
|
+
let ty = sy + Number(target.dy || 0)
|
|
1707
|
+
if (target.toRef || target.toSelector || target.toText) {
|
|
1708
|
+
const to = await locatorForTarget(page, tabId, { ref: target.toRef, selector: target.toSelector, text: target.toText })
|
|
1709
|
+
const toBox = await to.locator.boundingBox()
|
|
1710
|
+
if (!toBox) throw engineError('TARGET_NOT_FOUND', '终点元素不可见,无法拖拽', '改用 dx/dy 相对位移,或先滚动到位。')
|
|
1711
|
+
tx = toBox.x + toBox.width / 2
|
|
1712
|
+
ty = toBox.y + toBox.height / 2
|
|
1713
|
+
}
|
|
1714
|
+
if (Math.round(tx) === Math.round(sx) && Math.round(ty) === Math.round(sy)) {
|
|
1715
|
+
throw engineError('ARG_INVALID', '拖拽需要一个去处:给 toRef/toSelector/toText,或 dx/dy',
|
|
1716
|
+
'滑块通常给 dx(如 300),拖放排序用 toRef。')
|
|
1717
|
+
}
|
|
1718
|
+
const moveSteps = Math.max(1, Math.min(Number(target.steps) || 24, 80))
|
|
1719
|
+
const start = { x: sx, y: sy }
|
|
1720
|
+
if (human) {
|
|
1721
|
+
const fromPoint = mouseAt.get(tabId) || {
|
|
1722
|
+
x: Math.max(1, sx - randInt(rng, 120, 320)),
|
|
1723
|
+
y: Math.max(1, sy - randInt(rng, 60, 220)),
|
|
1724
|
+
}
|
|
1725
|
+
await humanPause(page, human.reactionMs)
|
|
1726
|
+
const approach = bezierPath(fromPoint, start, rng, human)
|
|
1727
|
+
if (human.pacedMoves && approach.length > 1) {
|
|
1728
|
+
const delays = moveDelays(approach, moveDurationMs(Math.hypot(start.x - fromPoint.x, start.y - fromPoint.y), rng, human))
|
|
1729
|
+
for (let i = 0; i < approach.length; i += 1) {
|
|
1730
|
+
if (delays[i] > 0) await sleepMs(page, delays[i])
|
|
1731
|
+
await page.mouse.move(approach[i].x, approach[i].y)
|
|
1732
|
+
}
|
|
1733
|
+
} else {
|
|
1734
|
+
for (const point of approach) await page.mouse.move(point.x, point.y)
|
|
1735
|
+
}
|
|
1736
|
+
} else {
|
|
1737
|
+
await page.mouse.move(sx, sy)
|
|
1738
|
+
}
|
|
1739
|
+
mouseAt.set(tabId, start)
|
|
1740
|
+
await page.mouse.down()
|
|
1741
|
+
try {
|
|
1742
|
+
if (human) {
|
|
1743
|
+
/* 真人拖滑块几乎都会过冲一点再回拉修正:这正是滑块风控最看重的轨迹特征。 */
|
|
1744
|
+
const distance = Math.hypot(tx - sx, ty - sy)
|
|
1745
|
+
const overshoot = Math.round((rng() - 0.5) * 2 * Math.min(8, Math.max(2, distance * 0.04)))
|
|
1746
|
+
const path = bezierPath(start, { x: tx + overshoot, y: ty }, rng, { ...human, moveSteps: [18, 34] })
|
|
1747
|
+
for (const point of path) {
|
|
1748
|
+
await page.mouse.move(point.x, point.y)
|
|
1749
|
+
await page.waitForTimeout(randInt(rng, 4, 18))
|
|
1750
|
+
}
|
|
1751
|
+
if (overshoot) {
|
|
1752
|
+
await page.waitForTimeout(randInt(rng, 60, 160))
|
|
1753
|
+
await page.mouse.move(tx, ty, { steps: 2 })
|
|
1754
|
+
}
|
|
1755
|
+
await page.waitForTimeout(randInt(rng, 80, 220))
|
|
1756
|
+
} else {
|
|
1757
|
+
await page.mouse.move(tx, ty, { steps: moveSteps })
|
|
1758
|
+
await page.waitForTimeout(60)
|
|
1759
|
+
}
|
|
1760
|
+
} finally {
|
|
1761
|
+
await page.mouse.up()
|
|
1762
|
+
}
|
|
1763
|
+
return {
|
|
1764
|
+
from: from.entry.name || from.entry.role,
|
|
1765
|
+
to: `${Math.round(tx)},${Math.round(ty)}`,
|
|
1766
|
+
distance: Math.round(Math.hypot(tx - sx, ty - sy)),
|
|
1767
|
+
}
|
|
1768
|
+
}
|
|
1769
|
+
|
|
1770
|
+
/* ---- 实时画面:CDP screencast ----
|
|
1771
|
+
* 侧栏里的「浏览器」不是把 OS 窗口搬进来(做不到),而是把当前活动页的帧推过去:
|
|
1772
|
+
* Page.startScreencast → JPEG 帧 → SSE;鼠标/键盘再从侧栏回放成真实输入。
|
|
1773
|
+
* 帧只在有人订阅时拉,没人看立刻停,避免后台白烧 CPU。 */
|
|
1774
|
+
|
|
1775
|
+
function broadcastFrame(frame) {
|
|
1776
|
+
for (const sub of [...frameSubs]) {
|
|
1777
|
+
try {
|
|
1778
|
+
sub(frame)
|
|
1779
|
+
} catch { /* 单个订阅者写失败(客户端已断开)不影响其他人 */ }
|
|
1780
|
+
}
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1783
|
+
async function stopCast() {
|
|
1784
|
+
const current = caster
|
|
1785
|
+
if (!current) return
|
|
1786
|
+
caster = null
|
|
1787
|
+
try { current.session.removeAllListeners?.('Page.screencastFrame') } catch { /* 已 detach */ }
|
|
1788
|
+
try { await current.session.send('Page.stopScreencast') } catch { /* 页面已关闭 */ }
|
|
1789
|
+
try { await current.session.detach() } catch { /* 已断开 */ }
|
|
1790
|
+
}
|
|
1791
|
+
|
|
1792
|
+
async function attachCast() {
|
|
1793
|
+
if (castBusy) return
|
|
1794
|
+
castBusy = true
|
|
1795
|
+
try {
|
|
1796
|
+
if (!frameSubs.size) { await stopCast(); return }
|
|
1797
|
+
if (!context) { await stopCast(); return }
|
|
1798
|
+
const page = activeTabId ? tabs.get(activeTabId) : null
|
|
1799
|
+
if (!page) { await stopCast(); return }
|
|
1800
|
+
if (caster && caster.page === page) return
|
|
1801
|
+
await stopCast()
|
|
1802
|
+
const session = await context.newCDPSession(page)
|
|
1803
|
+
const tabId = activeTabId
|
|
1804
|
+
caster = { page, tabId, session }
|
|
1805
|
+
session.on('Page.screencastFrame', (event) => {
|
|
1806
|
+
if (!caster || caster.session !== session || !frameSubs.size) return
|
|
1807
|
+
/* 先 ack 再广播:ack 是「可以给下一帧了」的背压阀,晚 ack 会直接掉帧率。 */
|
|
1808
|
+
session.send('Page.screencastFrameAck', { sessionId: event.sessionId }).catch(() => {})
|
|
1809
|
+
broadcastFrame({
|
|
1810
|
+
tab: tabId,
|
|
1811
|
+
data: event.data,
|
|
1812
|
+
width: Number(event.metadata?.deviceWidth) || cfg.viewportWidth,
|
|
1813
|
+
height: Number(event.metadata?.deviceHeight) || cfg.viewportHeight,
|
|
1814
|
+
})
|
|
1815
|
+
})
|
|
1816
|
+
page.once('close', () => {
|
|
1817
|
+
if (caster && caster.session === session) stopCast().catch(() => {})
|
|
1818
|
+
})
|
|
1819
|
+
await session.send('Page.startScreencast', {
|
|
1820
|
+
format: 'jpeg',
|
|
1821
|
+
quality: Math.max(10, Math.min(Number(cfg.screencastQuality) || 60, 95)),
|
|
1822
|
+
maxWidth: cfg.viewportWidth,
|
|
1823
|
+
maxHeight: cfg.viewportHeight,
|
|
1824
|
+
everyNthFrame: 1,
|
|
1825
|
+
})
|
|
1826
|
+
} catch {
|
|
1827
|
+
/* 页面正在导航 / 已关闭 / context 刚被 close:下一轮再挂,不报错 */
|
|
1828
|
+
caster = null
|
|
1829
|
+
} finally {
|
|
1830
|
+
castBusy = false
|
|
1831
|
+
}
|
|
1832
|
+
}
|
|
1833
|
+
|
|
1834
|
+
/**
|
|
1835
|
+
* 订阅当前活动页的实时帧。返回取消订阅函数。
|
|
1836
|
+
* 切标签页(activeTabId 变化)由轮询自动跟随,不需要订阅方处理。
|
|
1837
|
+
*/
|
|
1838
|
+
function watchFrames(callback) {
|
|
1839
|
+
if (typeof callback !== 'function') throw engineError('ARG_INVALID', 'watchFrames 需要回调')
|
|
1840
|
+
touch()
|
|
1841
|
+
frameSubs.add(callback)
|
|
1842
|
+
if (castTimer === null) {
|
|
1843
|
+
castTimer = setInterval(() => { attachCast().catch(() => {}) }, 500)
|
|
1844
|
+
castTimer.unref?.()
|
|
1845
|
+
}
|
|
1846
|
+
attachCast().catch(() => {})
|
|
1847
|
+
let active = true
|
|
1848
|
+
return () => {
|
|
1849
|
+
if (!active) return
|
|
1850
|
+
active = false
|
|
1851
|
+
frameSubs.delete(callback)
|
|
1852
|
+
if (frameSubs.size === 0) {
|
|
1853
|
+
if (castTimer !== null) { clearInterval(castTimer); castTimer = null }
|
|
1854
|
+
stopCast().catch(() => {})
|
|
1855
|
+
}
|
|
1856
|
+
}
|
|
1857
|
+
}
|
|
1858
|
+
|
|
1859
|
+
/* ---- 远端输入回放 ----
|
|
1860
|
+
* 走独立的串行队列:真实输入必须保序(down→move→up),但不能和工具动作队列
|
|
1861
|
+
* 抢锁——AI 的 click 可能正在等 15s 超时,用户这时也该能点。
|
|
1862
|
+
* 鼠标移动是高频事件,队列积压时直接丢帧(丢 move 不丢 down/up)。 */
|
|
1863
|
+
|
|
1864
|
+
let inputChain = Promise.resolve()
|
|
1865
|
+
let inputPending = 0
|
|
1866
|
+
|
|
1867
|
+
function enqueueInput(task) {
|
|
1868
|
+
const run = inputChain.then(task, task)
|
|
1869
|
+
inputChain = run.then(() => {}, () => {})
|
|
1870
|
+
inputPending += 1
|
|
1871
|
+
return run.finally(() => { inputPending -= 1 })
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
const MOUSE_BUTTONS = new Set(['left', 'right', 'middle'])
|
|
1875
|
+
|
|
1876
|
+
function clampNumber(value, min, max, fallback = 0) {
|
|
1877
|
+
const num = Number(value)
|
|
1878
|
+
if (!Number.isFinite(num)) return fallback
|
|
1879
|
+
return Math.min(max, Math.max(min, num))
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
function mouseButton(value) {
|
|
1883
|
+
const name = String(value || 'left')
|
|
1884
|
+
return MOUSE_BUTTONS.has(name) ? name : 'left'
|
|
1885
|
+
}
|
|
1886
|
+
|
|
1887
|
+
async function applyPointer(page, event) {
|
|
1888
|
+
const x = clampNumber(event.x, 0, cfg.viewportWidth)
|
|
1889
|
+
const y = clampNumber(event.y, 0, cfg.viewportHeight)
|
|
1890
|
+
const button = mouseButton(event.button)
|
|
1891
|
+
const kind = String(event.kind || '')
|
|
1892
|
+
/* clickCount 必须给:CDP 的 mousePressed/Released 带 clickCount>=1 时
|
|
1893
|
+
Chromium 才会合成 click 事件;给 0 只有 mousedown/mouseup,按钮不触发。 */
|
|
1894
|
+
const clickCount = Math.round(clampNumber(event.clickCount, 1, 3, 1))
|
|
1895
|
+
if (kind === 'move') { await page.mouse.move(x, y); return }
|
|
1896
|
+
if (kind === 'down') { await page.mouse.move(x, y); await page.mouse.down({ button, clickCount }); return }
|
|
1897
|
+
if (kind === 'up') { await page.mouse.move(x, y); await page.mouse.up({ button, clickCount }); return }
|
|
1898
|
+
if (kind === 'click') {
|
|
1899
|
+
await page.mouse.click(x, y, { button, clickCount })
|
|
1900
|
+
return
|
|
1901
|
+
}
|
|
1902
|
+
if (kind === 'wheel') {
|
|
1903
|
+
await page.mouse.move(x, y)
|
|
1904
|
+
await page.mouse.wheel(clampNumber(event.deltaX, -4000, 4000), clampNumber(event.deltaY, -4000, 4000))
|
|
1905
|
+
return
|
|
1906
|
+
}
|
|
1907
|
+
throw engineError('ARG_INVALID', `pointer 不支持 ${kind}`, '可用:move / down / up / click / wheel')
|
|
1908
|
+
}
|
|
1909
|
+
|
|
1910
|
+
/** 可打印 ASCII 走真实按键(页面能收到 keydown/keypress),其余(中文、emoji)走 insertText。 */
|
|
1911
|
+
async function applyText(page, text) {
|
|
1912
|
+
const value = String(text ?? '')
|
|
1913
|
+
if (!value) return
|
|
1914
|
+
if (/^[\x20-\x7e]+$/.test(value)) await page.keyboard.type(value)
|
|
1915
|
+
else await page.keyboard.insertText(value)
|
|
1916
|
+
}
|
|
1917
|
+
|
|
1918
|
+
async function applyKey(page, event) {
|
|
1919
|
+
const kind = String(event.kind || '')
|
|
1920
|
+
if (kind === 'text') { await applyText(page, event.text); return }
|
|
1921
|
+
const key = String(event.key || '')
|
|
1922
|
+
if (!key) throw engineError('ARG_INVALID', 'key 不能为空', '传 Enter / Tab / Backspace / ArrowLeft / a 这类键名。')
|
|
1923
|
+
if (kind === 'down') { await page.keyboard.down(key); return }
|
|
1924
|
+
if (kind === 'up') { await page.keyboard.up(key); return }
|
|
1925
|
+
if (kind === 'press') { await page.keyboard.press(key); return }
|
|
1926
|
+
throw engineError('ARG_INVALID', `key 不支持 ${kind}`, '可用:press / down / up / text')
|
|
1927
|
+
}
|
|
1928
|
+
|
|
1929
|
+
/** 关掉浏览器并释放帧订阅状态。persist=true 先把标签页落盘(供下次恢复);
|
|
1930
|
+
* 显式重置(browser_close)传 false 并清掉日志。切无头/空闲挂起/停服都走 persist。 */
|
|
1931
|
+
async function shutdown({ persist = true } = {}) {
|
|
1932
|
+
await stopCast()
|
|
1933
|
+
/* 无论是否落盘,都先掐掉防抖计时器:避免关闭后残留计时器再写一次日志。 */
|
|
1934
|
+
if (journalTimer) { clearTimeout(journalTimer); journalTimer = null }
|
|
1935
|
+
if (vaultTimer) { clearTimeout(vaultTimer); vaultTimer = null }
|
|
1936
|
+
if (!context) {
|
|
1937
|
+
if (!persist) { try { fs.rmSync(tabsFile, { force: true }) } catch { /* 忽略 */ } }
|
|
1938
|
+
return false
|
|
1939
|
+
}
|
|
1940
|
+
if (persist) {
|
|
1941
|
+
/* 关之前同步落盘最后一次状态(防抖计时器可能还没触发)。 */
|
|
1942
|
+
writeJournal()
|
|
1943
|
+
/* 登录态先存再关:每次正常挂起都刷新一遍保险箱。
|
|
1944
|
+
渲染进程卡死时 cookies() 可能永不返回——加超时上限,超时放弃本次保存,
|
|
1945
|
+
绝不把回收巡检/停服挂在一个卡死的浏览器上。 */
|
|
1946
|
+
try {
|
|
1947
|
+
await (cfg.shutdownTimeoutMs > 0 ? withTimeout(saveVault(), cfg.shutdownTimeoutMs, '登录态保存') : saveVault())
|
|
1948
|
+
} catch { /* 超时/失败不阻塞回收 */ }
|
|
1949
|
+
}
|
|
1950
|
+
const ctx = context
|
|
1951
|
+
context = null
|
|
1952
|
+
activeTabId = null
|
|
1953
|
+
walls.clear()
|
|
1954
|
+
let closeTimedOut = false
|
|
1955
|
+
try {
|
|
1956
|
+
await closeAttempt(ctx)
|
|
1957
|
+
} catch (error) {
|
|
1958
|
+
closeTimedOut = !!(error && error.code === 'TIMEOUT')
|
|
1959
|
+
}
|
|
1960
|
+
if (closeTimedOut && cfg.reapOrphans) {
|
|
1961
|
+
/* 卡死的浏览器不肯退:强杀占用本 profile 的进程兜底,释放内存/句柄,
|
|
1962
|
+
也避免下次启动撞锁。best-effort,杀不掉也不阻塞回收流程。 */
|
|
1963
|
+
try {
|
|
1964
|
+
const swept = await reapOrphanBrowsers({ profileDirs: [profileDir], processOps: ops, force: true })
|
|
1965
|
+
counters.orphansKilled += swept.killed.length
|
|
1966
|
+
} catch { /* 忽略 */ }
|
|
1967
|
+
}
|
|
1968
|
+
/* 每标签状态兜底清空:正常关闭时 page close 事件会清,但超时强杀时事件可能不来,
|
|
1969
|
+
不清就会按累计开过的标签数泄漏(mouseAt/refRegistries/输入会话等)。 */
|
|
1970
|
+
for (const page of tabs.values()) { try { closeInput(page) } catch { /* 已关 */ } }
|
|
1971
|
+
for (const session of uaSessions.values()) { try { void session.detach().catch(() => {}) } catch { /* 已断 */ } }
|
|
1972
|
+
uaSessions.clear()
|
|
1973
|
+
tabs.clear()
|
|
1974
|
+
tabIds.clear()
|
|
1975
|
+
refRegistries.clear()
|
|
1976
|
+
tabTitles.clear()
|
|
1977
|
+
snapshotChars.clear()
|
|
1978
|
+
mouseAt.clear()
|
|
1979
|
+
if (!persist) { try { fs.rmSync(tabsFile, { force: true }) } catch { /* 忽略 */ } }
|
|
1980
|
+
return true
|
|
1981
|
+
}
|
|
1982
|
+
|
|
1983
|
+
/** 截图保留策略:只留最近 maxScreenshotFiles 张 shot-*.png,更旧的删掉。
|
|
1984
|
+
* best-effort:读目录/删文件失败不影响截图本身。每次落盘后调用,防长会话磁盘无界增长。 */
|
|
1985
|
+
function pruneScreenshots() {
|
|
1986
|
+
const limit = Number.isFinite(cfg.maxScreenshotFiles) ? cfg.maxScreenshotFiles : 0
|
|
1987
|
+
if (limit <= 0) return
|
|
1988
|
+
try {
|
|
1989
|
+
const entries = fs.readdirSync(screenshotsDir)
|
|
1990
|
+
.filter((name) => /^shot-.*\.png$/i.test(name))
|
|
1991
|
+
.map((name) => {
|
|
1992
|
+
const full = path.join(screenshotsDir, name)
|
|
1993
|
+
try { return { full, mtime: fs.statSync(full).mtimeMs } } catch { return null }
|
|
1994
|
+
})
|
|
1995
|
+
.filter(Boolean)
|
|
1996
|
+
if (entries.length <= limit) return
|
|
1997
|
+
entries.sort((a, b) => a.mtime - b.mtime)
|
|
1998
|
+
for (const e of entries.slice(0, entries.length - limit)) {
|
|
1999
|
+
try { fs.rmSync(e.full, { force: true }) } catch { /* 占用/已删 */ }
|
|
2000
|
+
}
|
|
2001
|
+
} catch { /* 忽略 */ }
|
|
2002
|
+
}
|
|
2003
|
+
|
|
2004
|
+
/* ---- 公开 API ---- */
|
|
2005
|
+
const engine = {
|
|
2006
|
+
config: cfg,
|
|
2007
|
+
profileDir,
|
|
2008
|
+
screenshotsDir,
|
|
2009
|
+
|
|
2010
|
+
/** 结构化状态(health/metrics/工具共用;不触发浏览器启动)。 */
|
|
2011
|
+
status() {
|
|
2012
|
+
const tabList = [...tabs.entries()].map(([id, page]) => {
|
|
2013
|
+
let url = ''
|
|
2014
|
+
try { url = page.url() || '' } catch { /* 已关闭 */ }
|
|
2015
|
+
return { id, url, title: tabTitles.get(id) || '', active: id === activeTabId }
|
|
2016
|
+
})
|
|
2017
|
+
return {
|
|
2018
|
+
running: !!context,
|
|
2019
|
+
launching: !!launching,
|
|
2020
|
+
headless: cfg.headless,
|
|
2021
|
+
channel: channelUsed,
|
|
2022
|
+
tabs: tabList,
|
|
2023
|
+
activeTab: activeTabId,
|
|
2024
|
+
/* 活动页若停在 DSH Web 自身 401 鉴权页:工作台据此盖解释层,别让人对着白屏猜。 */
|
|
2025
|
+
authWall: walls.get(activeTabId) || '',
|
|
2026
|
+
viewport: { width: cfg.viewportWidth, height: cfg.viewportHeight },
|
|
2027
|
+
counters: { ...counters },
|
|
2028
|
+
watching: frameSubs.size,
|
|
2029
|
+
evaluateEnabled: !!cfg.allowEvaluate,
|
|
2030
|
+
lastActivity,
|
|
2031
|
+
/* 是否留有可恢复的标签日志(工作台据此在重开时自动恢复一次)。 */
|
|
2032
|
+
restorable: !!cfg.restoreTabs && fs.existsSync(tabsFile),
|
|
2033
|
+
/* 恢复上限(0=全部)与最近一次恢复结果:被裁掉的页不静默消失,工作台可提示。 */
|
|
2034
|
+
restoreLimit: Number.isFinite(cfg.maxRestoreTabs) ? cfg.maxRestoreTabs : 0,
|
|
2035
|
+
lastRestore: { ...lastRestore },
|
|
2036
|
+
/* 拟人/反检测现状:工作台与健康检查据此如实展示「现在像不像真人在操作」。 */
|
|
2037
|
+
humanize: human ? human.name : 'off',
|
|
2038
|
+
stealth: !!cfg.stealth,
|
|
2039
|
+
driver: String(cfg.stealthDriver || 'playwright') || 'playwright',
|
|
2040
|
+
/* 实际发出去的 UA(真实内核版本,只去掉 Headless 一词):排查登录/风控先看这个。
|
|
2041
|
+
UA 字符串里的版本号按 Chrome 规则削减成 major.0.0.0,完整版本在 uaFull。 */
|
|
2042
|
+
ua: detectedUa || '',
|
|
2043
|
+
uaFull: detectedUaFull || '',
|
|
2044
|
+
/* 登录态保险箱:共享 cookie 的条数、上次保存时间、本次启动注入了几条。 */
|
|
2045
|
+
loginVault: cfg.loginVault
|
|
2046
|
+
? { ...(vaultSummary(hostDir) || { cookies: 0, savedAt: '' }), injected: vaultInjected }
|
|
2047
|
+
: null,
|
|
2048
|
+
/* 礼貌调度现状:间隔/并发/退避/限速的计数与正在退避的主机,排查「为什么慢/被限」先看这个。 */
|
|
2049
|
+
governor: gov.stats(),
|
|
2050
|
+
}
|
|
2051
|
+
},
|
|
2052
|
+
|
|
2053
|
+
actionLog() {
|
|
2054
|
+
return actionLog.slice()
|
|
2055
|
+
},
|
|
2056
|
+
|
|
2057
|
+
/* ---- 侧栏实时画面与远端输入(工作台 /api/live、/api/input 用) ---- */
|
|
2058
|
+
|
|
2059
|
+
/** 订阅活动页实时帧;返回取消订阅函数。没订阅者时不会拉帧。 */
|
|
2060
|
+
watchFrames,
|
|
2061
|
+
|
|
2062
|
+
/**
|
|
2063
|
+
* 回放一次真实输入(鼠标/滚轮/键盘)。
|
|
2064
|
+
* pointer: { kind: move|down|up|click|wheel, x, y, button?, deltaX?, deltaY?, clickCount? }
|
|
2065
|
+
* key: { kind: press|down|up|text, key?, text? }
|
|
2066
|
+
*/
|
|
2067
|
+
async input(event = {}) {
|
|
2068
|
+
const type = String(event?.type || '')
|
|
2069
|
+
/* 鼠标移动是高频事件:队列积压时丢 move,绝不丢 down/up。 */
|
|
2070
|
+
if (type === 'pointer' && String(event.kind) === 'move' && inputPending > 4) return { dropped: true }
|
|
2071
|
+
return enqueueInput(async () => {
|
|
2072
|
+
if (!context) {
|
|
2073
|
+
throw engineError('ENGINE_NOT_RUNNING', '浏览器未启动',
|
|
2074
|
+
'在侧栏地址栏打开一个网址,或让 AI 调用 browser_navigate 拉起浏览器。')
|
|
2075
|
+
}
|
|
2076
|
+
const { page } = await ensureTab()
|
|
2077
|
+
if (type === 'pointer') await applyPointer(page, event)
|
|
2078
|
+
else if (type === 'key') await applyKey(page, event)
|
|
2079
|
+
else throw engineError('ARG_INVALID', `input 不支持 ${type}`, '可用:pointer / key')
|
|
2080
|
+
counters.inputs += 1
|
|
2081
|
+
return { ok: true }
|
|
2082
|
+
})
|
|
2083
|
+
},
|
|
2084
|
+
|
|
2085
|
+
/**
|
|
2086
|
+
* 切换有头/无头。运行中的浏览器会被关掉(登录态持久化在 profile 里),
|
|
2087
|
+
* 下一次动作按新模式重启——这样侧栏里能做到「完全不弹窗」。
|
|
2088
|
+
*/
|
|
2089
|
+
async setHeadless(value) {
|
|
2090
|
+
const want = !!value
|
|
2091
|
+
const changed = cfg.headless !== want
|
|
2092
|
+
cfg.headless = want
|
|
2093
|
+
/* 记住这次选择:下次 relay 重启(比如 DSH 重启)仍按这个模式。 */
|
|
2094
|
+
try {
|
|
2095
|
+
fs.writeFileSync(prefsFile, JSON.stringify({ ...readEnginePrefs(hostDir), headless: want }, null, 2))
|
|
2096
|
+
} catch { /* 宿主目录只读时忽略:本次运行仍然生效 */ }
|
|
2097
|
+
let restarted = false
|
|
2098
|
+
if (changed && context) {
|
|
2099
|
+
await enqueue(async () => { restarted = await shutdown() })
|
|
2100
|
+
}
|
|
2101
|
+
return { headless: want, restarted, changed }
|
|
2102
|
+
},
|
|
2103
|
+
|
|
2104
|
+
async navigate({ url, tab } = {}) {
|
|
2105
|
+
const safe = assertSafeUrl(url)
|
|
2106
|
+
return enqueue(() => track('browser_navigate', safe.slice(0, 120), async () => {
|
|
2107
|
+
const { id, page } = await ensureTab(tab)
|
|
2108
|
+
activeTabId = id
|
|
2109
|
+
walls.delete(id) /* 新导航作废上一堵墙的结论;observe 按落地页重新识别 */
|
|
2110
|
+
/* 礼貌调度:同主机间隔+抖动、跨会话并发上限、429/风控退避都在 withNavigation 里。
|
|
2111
|
+
classify 把「状态码 / 人机验证 / 登录墙」回报给调度器决定是否退避。 */
|
|
2112
|
+
const result = await gov.withNavigation(safe, async () => {
|
|
2113
|
+
/* 超时不等于失败:常见于慢站/被拦的探测域名,此时页面往往已经有可交互内容。
|
|
2114
|
+
软失败:拍一张当前快照一并返回,让模型能继续动作,而不是拿一个空错误重来。 */
|
|
2115
|
+
let timedOut = false
|
|
2116
|
+
let status = 0
|
|
2117
|
+
try {
|
|
2118
|
+
const resp = await page.goto(safe, { timeout: cfg.navigationTimeoutMs, waitUntil: 'domcontentloaded' })
|
|
2119
|
+
if (resp && typeof resp.status === 'function') status = resp.status()
|
|
2120
|
+
} catch (error) {
|
|
2121
|
+
if (page.isClosed()) throw engineError('TAB_CLOSED', `标签页在导航期间被关闭:${safe}`, '用 browser_tabs(action=list) 查看现有标签页后重试。')
|
|
2122
|
+
if (!isNavigationTimeout(error)) throw navFailure(error, safe)
|
|
2123
|
+
timedOut = true
|
|
2124
|
+
await settle(page)
|
|
2125
|
+
}
|
|
2126
|
+
/* 落在 chrome-error:// 错误页:再 observe 只会抛「context destroyed」的裸错。
|
|
2127
|
+
直接给清晰的 NAV_FAILED,快速失败,不留一个坏标签让模型对着空快照猜。 */
|
|
2128
|
+
if (isChromeErrorPage(page)) {
|
|
2129
|
+
throw engineError('NAV_FAILED', `无法打开 ${safe}:浏览器落在网络错误页(目标不可达或被拦截)`,
|
|
2130
|
+
'检查网址与网络后重试;若目标确不可达,换一个可达地址,不要反复重试同一地址。')
|
|
2131
|
+
}
|
|
2132
|
+
let snapshot
|
|
2133
|
+
try {
|
|
2134
|
+
snapshot = await observe(page, id)
|
|
2135
|
+
} catch (error) {
|
|
2136
|
+
if (page.isClosed()) throw engineError('TAB_CLOSED', `标签页在导航期间被关闭:${safe}`, '用 browser_tabs(action=list) 查看现有标签页后重试。')
|
|
2137
|
+
if (isChromeErrorPage(page)) throw engineError('NAV_FAILED', `无法打开 ${safe}:浏览器落在网络错误页(目标不可达或被拦截)`, '检查网址与网络后重试。')
|
|
2138
|
+
throw error
|
|
2139
|
+
}
|
|
2140
|
+
const landed = (() => { try { return page.url() || '' } catch { return safe } })()
|
|
2141
|
+
/* 落到 DSH Web 自身 401 鉴权页 = 受控浏览器没有宿主登录态:直接给结论,
|
|
2142
|
+
不让模型对着空快照重试、或试图「登录」宿主 GUI。 */
|
|
2143
|
+
const wallNote = snapshot.authWall || ''
|
|
2144
|
+
/* 被重定向到登录页 = 登录态失效(或本来没登录)。别让模型自己猜:
|
|
2145
|
+
直接标出来,它才知道该提示用户扫码,而不是反复重试同一个动作。 */
|
|
2146
|
+
const loginNote = wallNote ? '' : loginRedirectNote(safe, landed)
|
|
2147
|
+
let kind = ''
|
|
2148
|
+
let note = wallNote || loginNote
|
|
2149
|
+
if (!note) {
|
|
2150
|
+
/* 识别人机验证容器(只识别、不破解):提示人工过一次,保险箱随后持久化。 */
|
|
2151
|
+
try { kind = await withTimeout(page.evaluate(challengeProbe), 1500, '识别人机验证') } catch { /* 页面已关闭/卡死 */ }
|
|
2152
|
+
if (typeof kind !== 'string') kind = ''
|
|
2153
|
+
note = challengeNote(kind)
|
|
2154
|
+
}
|
|
2155
|
+
return {
|
|
2156
|
+
tab: id,
|
|
2157
|
+
url: landed,
|
|
2158
|
+
title: snapshot.title,
|
|
2159
|
+
snapshot,
|
|
2160
|
+
timedOut,
|
|
2161
|
+
timeoutMs: cfg.navigationTimeoutMs,
|
|
2162
|
+
...(note ? { note } : {}),
|
|
2163
|
+
...(wallNote ? { authWall: true } : {}),
|
|
2164
|
+
__risk: { status, challenge: kind !== '', login: loginNote !== '' },
|
|
2165
|
+
}
|
|
2166
|
+
}, (out) => out.__risk)
|
|
2167
|
+
delete result.__risk /* 风险信号只给调度器,不暴露给工具调用方 */
|
|
2168
|
+
return result
|
|
2169
|
+
}))
|
|
2170
|
+
},
|
|
2171
|
+
|
|
2172
|
+
async snapshot({ tab } = {}) {
|
|
2173
|
+
return enqueue(() => track('browser_snapshot', tab ? `tab=${tab}` : 'active', async () => {
|
|
2174
|
+
const { id, page } = await ensureTab(tab)
|
|
2175
|
+
const snapshot = await observe(page, id)
|
|
2176
|
+
return { tab: id, ...snapshot, ...(snapshot.authWall ? { note: snapshot.authWall } : {}) }
|
|
2177
|
+
}))
|
|
2178
|
+
},
|
|
2179
|
+
|
|
2180
|
+
async click({ ref, selector, text, tab } = {}) {
|
|
2181
|
+
const detail = ref ? `ref=${ref}` : selector ? `sel=${String(selector).slice(0, 60)}` : `text=${String(text || '').slice(0, 40)}`
|
|
2182
|
+
return enqueue(() => track('browser_click', detail, async () => {
|
|
2183
|
+
const { id, page } = await ensureTab(tab)
|
|
2184
|
+
const entry = await clickTarget(page, id, { ref, selector, text })
|
|
2185
|
+
await settle(page)
|
|
2186
|
+
const snapshot = await observe(page, id)
|
|
2187
|
+
return { clicked: `${entry.role}${entry.name ? ` "${entry.name}"` : ''}`, tab: id, snapshot }
|
|
2188
|
+
}))
|
|
2189
|
+
},
|
|
2190
|
+
|
|
2191
|
+
/** 拖拽:滑块验证、拖放排序。起点/终点都支持 ref / selector / text,也支持 dx/dy 相对位移。 */
|
|
2192
|
+
async drag({ ref, selector, text, toRef, toSelector, toText, dx, dy, steps, tab } = {}) {
|
|
2193
|
+
const detail = ref ? `ref=${ref}` : selector ? `sel=${String(selector).slice(0, 50)}` : `text=${String(text || '').slice(0, 30)}`
|
|
2194
|
+
return enqueue(() => track('browser_drag', detail, async () => {
|
|
2195
|
+
const { id, page } = await ensureTab(tab)
|
|
2196
|
+
const moved = await dragBetween(page, id, { ref, selector, text, toRef, toSelector, toText, dx, dy, steps })
|
|
2197
|
+
await settle(page)
|
|
2198
|
+
const snapshot = await observe(page, id)
|
|
2199
|
+
return { tab: id, moved, snapshot }
|
|
2200
|
+
}))
|
|
2201
|
+
},
|
|
2202
|
+
|
|
2203
|
+
async fill({ ref, text, submit = false, tab } = {}) {
|
|
2204
|
+
return enqueue(() => track('browser_fill', `ref=${ref}`, async () => {
|
|
2205
|
+
const { id, page } = await ensureTab(tab)
|
|
2206
|
+
const { entry, typed } = await fillTarget(page, id, { ref }, text, !!submit)
|
|
2207
|
+
if (submit) await settle(page)
|
|
2208
|
+
const snapshot = await observe(page, id)
|
|
2209
|
+
return {
|
|
2210
|
+
filled: `${entry.role}${entry.name ? ` "${entry.name}"` : ''}`,
|
|
2211
|
+
submit: !!submit,
|
|
2212
|
+
typed: typed ? { chars: typed.chars, pasted: typed.pasted } : null,
|
|
2213
|
+
tab: id,
|
|
2214
|
+
snapshot,
|
|
2215
|
+
}
|
|
2216
|
+
}))
|
|
2217
|
+
},
|
|
2218
|
+
|
|
2219
|
+
async press({ key, ref, tab } = {}) {
|
|
2220
|
+
return enqueue(() => track('browser_press', `${ref ? `ref=${ref} ` : ''}${key}`, async () => {
|
|
2221
|
+
const { id, page } = await ensureTab(tab)
|
|
2222
|
+
if (ref) {
|
|
2223
|
+
const { locator } = await locatorFor(page, id, ref)
|
|
2224
|
+
await locator.press(String(key), { timeout: cfg.actionTimeoutMs })
|
|
2225
|
+
} else {
|
|
2226
|
+
await page.keyboard.press(String(key))
|
|
2227
|
+
}
|
|
2228
|
+
await settle(page)
|
|
2229
|
+
const snapshot = await observe(page, id)
|
|
2230
|
+
return { key, tab: id, snapshot }
|
|
2231
|
+
}))
|
|
2232
|
+
},
|
|
2233
|
+
|
|
2234
|
+
async select({ ref, value, tab } = {}) {
|
|
2235
|
+
return enqueue(() => track('browser_select', `ref=${ref}`, async () => {
|
|
2236
|
+
const { id, page } = await ensureTab(tab)
|
|
2237
|
+
const { applied, entry } = await chooseOption(page, id, ref, value)
|
|
2238
|
+
await settle(page)
|
|
2239
|
+
const snapshot = await observe(page, id)
|
|
2240
|
+
return { selected: `${entry.name || entry.role} → ${applied}`, tab: id, snapshot }
|
|
2241
|
+
}))
|
|
2242
|
+
},
|
|
2243
|
+
|
|
2244
|
+
/** 文件上传:把本机文件塞进 <input type=file>(Playwright setInputFiles)。
|
|
2245
|
+
* files 为本机绝对路径数组;空数组=清空已选。闭环里由 materializeArtifact 物化出路径后调用,
|
|
2246
|
+
* browser 套件本身不知道 work-store / 信封的存在(解耦总原则)。 */
|
|
2247
|
+
async upload({ ref, selector, files, tab } = {}) {
|
|
2248
|
+
const list = Array.isArray(files) ? files.map((f) => String(f)) : (files ? [String(files)] : [])
|
|
2249
|
+
for (const f of list) {
|
|
2250
|
+
if (!path.isAbsolute(f)) throw engineError('ARG_INVALID', `文件路径须为绝对路径:${f}`, '先用 materializeArtifact 物化出本机绝对路径。')
|
|
2251
|
+
if (!fs.existsSync(f)) throw engineError('ARG_INVALID', `文件不存在:${f}`, '确认路径正确且文件已生成。')
|
|
2252
|
+
}
|
|
2253
|
+
const detail = ref ? `ref=${ref}` : `sel=${String(selector || '').slice(0, 50)}`
|
|
2254
|
+
return enqueue(() => track('browser_upload', `${detail} ${list.length} 文件`, async () => {
|
|
2255
|
+
const { id, page } = await ensureTab(tab)
|
|
2256
|
+
const { locator, entry } = await locatorForTarget(page, id, { ref, selector })
|
|
2257
|
+
await locator.setInputFiles(list, { timeout: cfg.actionTimeoutMs })
|
|
2258
|
+
await settle(page)
|
|
2259
|
+
const snapshot = await observe(page, id)
|
|
2260
|
+
return { uploaded: list.map((f) => path.basename(f)), count: list.length, target: `${entry.role}${entry.name ? ` "${entry.name}"` : ''}`, tab: id, snapshot }
|
|
2261
|
+
}))
|
|
2262
|
+
},
|
|
2263
|
+
|
|
2264
|
+
async scroll({ direction = 'down', amount = 600, tab } = {}) {
|
|
2265
|
+
return enqueue(() => track('browser_scroll', `${direction} ${amount}px`, async () => {
|
|
2266
|
+
const { id, page } = await ensureTab(tab)
|
|
2267
|
+
const delta = direction === 'up' ? -Number(amount) : Number(amount)
|
|
2268
|
+
const ticks = await scrollByAmount(page, delta)
|
|
2269
|
+
const snapshot = await observe(page, id)
|
|
2270
|
+
return { scrolled: `${direction} ${Math.abs(delta)}px`, ticks, tab: id, snapshot }
|
|
2271
|
+
}))
|
|
2272
|
+
},
|
|
2273
|
+
|
|
2274
|
+
/**
|
|
2275
|
+
* 批量动作:一条消息里按顺序做完多个不跳转的动作,只回一份最终快照。
|
|
2276
|
+
* 每一步本来都要一次模型往返(约 2 s 固定开销),打包后只算一次。
|
|
2277
|
+
*/
|
|
2278
|
+
async act({ steps = [], tab, stopOnError = true } = {}) {
|
|
2279
|
+
const list = Array.isArray(steps) ? steps.slice(0, 10) : []
|
|
2280
|
+
if (!list.length) {
|
|
2281
|
+
throw engineError('ARG_INVALID', 'steps 不能为空', '传 [{op:"fill",ref:"e2",text:"..."}] 这样的数组。')
|
|
2282
|
+
}
|
|
2283
|
+
return enqueue(() => track('browser_act', `${list.length} 步`, async () => {
|
|
2284
|
+
const { id, page } = await ensureTab(tab)
|
|
2285
|
+
const results = []
|
|
2286
|
+
let failed = -1
|
|
2287
|
+
for (const [index, step] of list.entries()) {
|
|
2288
|
+
const op = String(step?.op || '')
|
|
2289
|
+
try {
|
|
2290
|
+
await runStep(page, id, op, step)
|
|
2291
|
+
results.push({ index, op, ok: true })
|
|
2292
|
+
} catch (error) {
|
|
2293
|
+
failed = index
|
|
2294
|
+
results.push({
|
|
2295
|
+
index,
|
|
2296
|
+
op,
|
|
2297
|
+
ok: false,
|
|
2298
|
+
error: `${error?.code ? `[${error.code}] ` : ''}${error?.message || error}${error?.hint ? `|${error.hint}` : ''}`,
|
|
2299
|
+
})
|
|
2300
|
+
if (stopOnError) break
|
|
2301
|
+
}
|
|
2302
|
+
}
|
|
2303
|
+
await settle(page)
|
|
2304
|
+
const snapshot = await observe(page, id)
|
|
2305
|
+
return { tab: id, results, failed, snapshot }
|
|
2306
|
+
}))
|
|
2307
|
+
},
|
|
2308
|
+
|
|
2309
|
+
async wait({ ms, selector, tab } = {}) {
|
|
2310
|
+
return enqueue(() => track('browser_wait', ms ? `${ms}ms` : selector ? selector.slice(0, 80) : 'load', async () => {
|
|
2311
|
+
const { id, page } = await ensureTab(tab)
|
|
2312
|
+
if (selector) {
|
|
2313
|
+
await page.waitForSelector(String(selector), { timeout: Math.min(Number(ms) || cfg.actionTimeoutMs, cfg.actionTimeoutMs) })
|
|
2314
|
+
} else if (ms) {
|
|
2315
|
+
await page.waitForTimeout(Math.min(Number(ms), 30000))
|
|
2316
|
+
} else {
|
|
2317
|
+
await page.waitForLoadState('load', { timeout: cfg.navigationTimeoutMs })
|
|
2318
|
+
}
|
|
2319
|
+
/* 等完必拍快照:否则模型还要再调一次 browser_snapshot,白跑一轮往返。 */
|
|
2320
|
+
const snapshot = await observe(page, id)
|
|
2321
|
+
return { waited: true, tab: id, snapshot }
|
|
2322
|
+
}))
|
|
2323
|
+
},
|
|
2324
|
+
|
|
2325
|
+
async history({ action = 'back', tab } = {}) {
|
|
2326
|
+
return enqueue(() => track('browser_history', action, async () => {
|
|
2327
|
+
const { id, page } = await ensureTab(tab)
|
|
2328
|
+
walls.delete(id) /* 后退/前进/重载都是新文档:作废上一堵墙的结论 */
|
|
2329
|
+
const current = (() => { try { return page.url() || '' } catch { return '' } })()
|
|
2330
|
+
return gov.withNavigation(current, async () => {
|
|
2331
|
+
let resp = null
|
|
2332
|
+
if (action === 'back') resp = await page.goBack({ timeout: cfg.navigationTimeoutMs })
|
|
2333
|
+
else if (action === 'forward') resp = await page.goForward({ timeout: cfg.navigationTimeoutMs })
|
|
2334
|
+
else if (action === 'reload') resp = await page.reload({ timeout: cfg.navigationTimeoutMs })
|
|
2335
|
+
else throw engineError('ARG_INVALID', `history 不支持 ${action}`, '可用:back / forward / reload')
|
|
2336
|
+
const snapshot = await observe(page, id)
|
|
2337
|
+
return { action, url: page.url(), tab: id, snapshot, ...(snapshot.authWall ? { note: snapshot.authWall, authWall: true } : {}), __risk: { status: resp && typeof resp.status === 'function' ? resp.status() : 0 } }
|
|
2338
|
+
}, (out) => { const r = out.__risk; delete out.__risk; return r })
|
|
2339
|
+
}))
|
|
2340
|
+
},
|
|
2341
|
+
|
|
2342
|
+
async tabsAction({ action = 'list', url, tab } = {}) {
|
|
2343
|
+
return enqueueControl(() => track('browser_tabs', action, async () => {
|
|
2344
|
+
if (action === 'list') {
|
|
2345
|
+
return { tabs: engine.status().tabs, activeTab: activeTabId }
|
|
2346
|
+
}
|
|
2347
|
+
if (action === 'new') {
|
|
2348
|
+
await launch()
|
|
2349
|
+
const page = await context.newPage()
|
|
2350
|
+
const id = registerPage(page)
|
|
2351
|
+
await applyUaHints(page)
|
|
2352
|
+
activeTabId = id
|
|
2353
|
+
if (url) {
|
|
2354
|
+
const safe = assertSafeUrl(url)
|
|
2355
|
+
await gov.withNavigation(safe, async () => {
|
|
2356
|
+
let resp
|
|
2357
|
+
try {
|
|
2358
|
+
resp = await page.goto(safe, { timeout: cfg.navigationTimeoutMs, waitUntil: 'domcontentloaded' })
|
|
2359
|
+
} catch (error) {
|
|
2360
|
+
if (page.isClosed()) throw engineError('TAB_CLOSED', `标签页在导航期间被关闭:${safe}`, '用 browser_tabs(action=list) 查看现有标签页后重试。')
|
|
2361
|
+
if (!isNavigationTimeout(error)) throw navFailure(error, safe)
|
|
2362
|
+
}
|
|
2363
|
+
if (isChromeErrorPage(page)) throw engineError('NAV_FAILED', `无法打开 ${safe}:浏览器落在网络错误页(目标不可达或被拦截)`, '检查网址与网络后重试。')
|
|
2364
|
+
return { __risk: { status: resp && typeof resp.status === 'function' ? resp.status() : 0 } }
|
|
2365
|
+
}, (out) => out.__risk)
|
|
2366
|
+
}
|
|
2367
|
+
const snapshot = await observe(page, id).catch(() => null)
|
|
2368
|
+
return { tab: id, url: page.url(), snapshot, ...(snapshot && snapshot.authWall ? { note: snapshot.authWall, authWall: true } : {}) }
|
|
2369
|
+
}
|
|
2370
|
+
if (action === 'select') {
|
|
2371
|
+
if (!tab || !tabs.has(tab)) throw engineError('TAB_UNKNOWN', `标签页 ${tab || '(空)'} 不存在`, '先 browser_tabs(action=list)。')
|
|
2372
|
+
activeTabId = tab
|
|
2373
|
+
/* 目标页可能正在主队列里导航:observe best-effort,失败不阻断切换本身。 */
|
|
2374
|
+
const snapshot = await observe(tabs.get(tab), tab).catch(() => null)
|
|
2375
|
+
return { tab, snapshot, ...(snapshot && snapshot.authWall ? { note: snapshot.authWall, authWall: true } : {}) }
|
|
2376
|
+
}
|
|
2377
|
+
if (action === 'close') {
|
|
2378
|
+
if (!tab || !tabs.has(tab)) throw engineError('TAB_UNKNOWN', `标签页 ${tab || '(空)'} 不存在`, '先 browser_tabs(action=list)。')
|
|
2379
|
+
await tabs.get(tab).close()
|
|
2380
|
+
return { closed: tab, tabs: engine.status().tabs }
|
|
2381
|
+
}
|
|
2382
|
+
throw engineError('ARG_INVALID', `tabs 不支持 ${action}`, '可用:list / new / select / close')
|
|
2383
|
+
}))
|
|
2384
|
+
},
|
|
2385
|
+
|
|
2386
|
+
/** 截图:落盘 + 带回 PNG base64(工具面直接把图给模型,不用再 read_image)。 */
|
|
2387
|
+
async screenshot({ fullPage = false, tab } = {}) {
|
|
2388
|
+
return enqueue(() => track('browser_screenshot', fullPage ? 'fullPage' : 'viewport', async () => {
|
|
2389
|
+
const { page } = await ensureTab(tab)
|
|
2390
|
+
const buffer = await page.screenshot({ fullPage: !!fullPage })
|
|
2391
|
+
const file = path.join(screenshotsDir, `shot-${Date.now()}-${Math.floor(Math.random() * 1e4)}.png`)
|
|
2392
|
+
fs.writeFileSync(file, buffer)
|
|
2393
|
+
pruneScreenshots()
|
|
2394
|
+
return {
|
|
2395
|
+
path: file,
|
|
2396
|
+
bytes: buffer.length,
|
|
2397
|
+
mimeType: 'image/png',
|
|
2398
|
+
data: buffer.toString('base64'),
|
|
2399
|
+
tab: activeTabId,
|
|
2400
|
+
}
|
|
2401
|
+
}))
|
|
2402
|
+
},
|
|
2403
|
+
|
|
2404
|
+
/** 实时画面(工作台 /api/screenshot 用:不落盘,直接返回 PNG Buffer)。 */
|
|
2405
|
+
async screenshotBuffer({ tab } = {}) {
|
|
2406
|
+
const { page } = await ensureTab(tab)
|
|
2407
|
+
return page.screenshot({ fullPage: false })
|
|
2408
|
+
},
|
|
2409
|
+
|
|
2410
|
+
/** 任意 JS 执行:默认关闭,如实返回 NOT_IMPLEMENTED(不伪造结果)。 */
|
|
2411
|
+
async evaluate({ script, tab } = {}) {
|
|
2412
|
+
if (!cfg.allowEvaluate) {
|
|
2413
|
+
throw engineError('NOT_IMPLEMENTED',
|
|
2414
|
+
'browser_evaluate 默认关闭(安全默认:页面脚本面不向模型开放)',
|
|
2415
|
+
'确有需要时在 cordis 配置 allowEvaluate: true 或环境变量 DSH_BROWSER_ALLOW_EVALUATE=true,重启服务后生效。')
|
|
2416
|
+
}
|
|
2417
|
+
return enqueue(() => track('browser_evaluate', String(script).slice(0, 80), async () => {
|
|
2418
|
+
const { id, page } = await ensureTab(tab)
|
|
2419
|
+
const out = await page.evaluate(String(script))
|
|
2420
|
+
return { tab: id, result: out === undefined ? null : out }
|
|
2421
|
+
}))
|
|
2422
|
+
},
|
|
2423
|
+
|
|
2424
|
+
async close() {
|
|
2425
|
+
return enqueue(() => track('browser_close', '', async () => {
|
|
2426
|
+
/* 显式重置:不留标签日志,下次 navigate 是干净浏览器(登录态仍在 profile)。 */
|
|
2427
|
+
return { closed: await shutdown({ persist: false }) }
|
|
2428
|
+
}))
|
|
2429
|
+
},
|
|
2430
|
+
|
|
2431
|
+
/** 生命周期挂起:释放浏览器进程但保留 profile + 标签日志,下次动作懒重启并恢复。
|
|
2432
|
+
* 空闲回收 / LRU 超限 / 停服走这里(区别于 browser_close 的显式重置)。
|
|
2433
|
+
* ifIdleMs:空闲回收专用——巡检读到的是陈旧 lastActivity,suspend 又要排动作队列,
|
|
2434
|
+
* 排队期间可能来了新动作/有人开始看帧。入队后真正挂起前二次复检,避免把正在用的
|
|
2435
|
+
* 浏览器挂起。LRU/停服不传 ifIdleMs(强制挂起)。 */
|
|
2436
|
+
async suspend({ ifIdleMs } = {}) {
|
|
2437
|
+
return enqueue(async () => {
|
|
2438
|
+
if (Number(ifIdleMs) > 0) {
|
|
2439
|
+
if (frameSubs.size > 0) return { suspended: false, skipped: 'watching' }
|
|
2440
|
+
if (lastActivity && Date.now() - lastActivity <= Number(ifIdleMs)) return { suspended: false, skipped: 'active' }
|
|
2441
|
+
}
|
|
2442
|
+
const suspended = await shutdown({ persist: true })
|
|
2443
|
+
return { suspended }
|
|
2444
|
+
})
|
|
2445
|
+
},
|
|
2446
|
+
|
|
2447
|
+
/** 恢复上次浏览器:懒启动(含标签页恢复),不附带新导航。工作台重开时调用,
|
|
2448
|
+
* 于是「点开上次的会话还能看到上次的页面」。无标签日志时只是拉起空浏览器。 */
|
|
2449
|
+
async resume() {
|
|
2450
|
+
return enqueue(async () => {
|
|
2451
|
+
const wasRunning = !!context
|
|
2452
|
+
await launch()
|
|
2453
|
+
touch()
|
|
2454
|
+
return {
|
|
2455
|
+
resumed: true,
|
|
2456
|
+
tabs: engine.status().tabs,
|
|
2457
|
+
activeTab: activeTabId,
|
|
2458
|
+
/* 只有这一趟真的拉起了新浏览器才有「恢复」可报;已在运行时如实返回 0/0。 */
|
|
2459
|
+
restore: wasRunning ? { restored: 0, skipped: 0 } : { ...lastRestore },
|
|
2460
|
+
}
|
|
2461
|
+
})
|
|
2462
|
+
},
|
|
2463
|
+
}
|
|
2464
|
+
|
|
2465
|
+
return engine
|
|
2466
|
+
}
|