@liang-hz/agent-in-chrome 0.55.0
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/.ext-id.txt +4 -0
- package/LICENSE +202 -0
- package/NOTICE +5 -0
- package/PRIVACY.md +86 -0
- package/README.en.md +419 -0
- package/README.md +406 -0
- package/bin/agent-in-chrome.mjs +97 -0
- package/commands/agent-in-chrome.md +18 -0
- package/commands/install-agent-in-chrome.md +22 -0
- package/docs/AGENTS.md +94 -0
- package/docs/CLI.md +297 -0
- package/docs/client-compat.json +23 -0
- package/extension/about-toc.js +25 -0
- package/extension/about.html +240 -0
- package/extension/about.js +44 -0
- package/extension/agent-window.html +100 -0
- package/extension/icons/icon-128.png +0 -0
- package/extension/icons/icon-16.png +0 -0
- package/extension/icons/icon-24.png +0 -0
- package/extension/icons/icon-32.png +0 -0
- package/extension/icons/icon-48.png +0 -0
- package/extension/icons/icon-64.png +0 -0
- package/extension/icons/icon-attention-128.png +0 -0
- package/extension/icons/icon-attention-16.png +0 -0
- package/extension/icons/icon-attention-24.png +0 -0
- package/extension/icons/icon-attention-32.png +0 -0
- package/extension/icons/icon-attention-48.png +0 -0
- package/extension/icons/icon-attention-64.png +0 -0
- package/extension/icons/icon-attention.svg +18 -0
- package/extension/icons/icon-failed-128.png +0 -0
- package/extension/icons/icon-failed-16.png +0 -0
- package/extension/icons/icon-failed-24.png +0 -0
- package/extension/icons/icon-failed-32.png +0 -0
- package/extension/icons/icon-failed-48.png +0 -0
- package/extension/icons/icon-failed-64.png +0 -0
- package/extension/icons/icon-failed.svg +18 -0
- package/extension/icons/icon-idle-128.png +0 -0
- package/extension/icons/icon-idle-16.png +0 -0
- package/extension/icons/icon-idle-24.png +0 -0
- package/extension/icons/icon-idle-32.png +0 -0
- package/extension/icons/icon-idle-48.png +0 -0
- package/extension/icons/icon-idle-64.png +0 -0
- package/extension/icons/icon-idle.svg +18 -0
- package/extension/icons/icon-mark.svg +10 -0
- package/extension/icons/icon-running-128.png +0 -0
- package/extension/icons/icon-running-16.png +0 -0
- package/extension/icons/icon-running-24.png +0 -0
- package/extension/icons/icon-running-32.png +0 -0
- package/extension/icons/icon-running-48.png +0 -0
- package/extension/icons/icon-running-64.png +0 -0
- package/extension/icons/icon-running.svg +18 -0
- package/extension/icons/icon.svg +18 -0
- package/extension/manifest.json +44 -0
- package/extension/popup-ui.js +38 -0
- package/extension/popup.html +350 -0
- package/extension/popup.js +741 -0
- package/extension/sw.js +11127 -0
- package/extension/update-check.js +66 -0
- package/extension/welcome.html +110 -0
- package/extension/welcome.js +18 -0
- package/mcp/agent-identity.mjs +1007 -0
- package/mcp/cdp/bridge.mjs +239 -0
- package/mcp/cdp/browser-launch.mjs +1127 -0
- package/mcp/cdp/chrome-shim.mjs +1124 -0
- package/mcp/cdp/client.mjs +443 -0
- package/mcp/cli-invocation.mjs +67 -0
- package/mcp/config.mjs +191 -0
- package/mcp/foreground-guard.mjs +295 -0
- package/mcp/proc-win.mjs +112 -0
- package/mcp/secret-shape.mjs +155 -0
- package/mcp/server.mjs +3437 -0
- package/mcp/session-id.mjs +281 -0
- package/mcp/token.mjs +260 -0
- package/mcp/tool-tiers.mjs +84 -0
- package/mcp/trace.mjs +528 -0
- package/mcp/update-cli.mjs +163 -0
- package/mcp/update-notice.mjs +194 -0
- package/native-host/host.mjs +356 -0
- package/native-host/mac-foreground/aic-fg.swift +114 -0
- package/native-host/mac-foreground/build.mjs +43 -0
- package/package.json +46 -0
- package/scripts/agents.mjs +921 -0
- package/scripts/borrow-login.mjs +935 -0
- package/scripts/cli-browser.mjs +148 -0
- package/scripts/e2e-sweep.mjs +192 -0
- package/scripts/e2e.mjs +3911 -0
- package/scripts/fixture-server.mjs +1419 -0
- package/scripts/guard-publish.mjs +175 -0
- package/scripts/install.mjs +1383 -0
- package/scripts/launcher-provenance.mjs +74 -0
- package/scripts/pack-crx.mjs +82 -0
- package/scripts/pick.mjs +114 -0
- package/scripts/test-agents.mjs +968 -0
- package/scripts/test-borrow.mjs +289 -0
- package/scripts/test-config.mjs +618 -0
- package/scripts/test-e2e-sweep.mjs +251 -0
- package/scripts/test-foreground-guard.mjs +383 -0
- package/scripts/test-identity.mjs +1141 -0
- package/scripts/test-install-skill.mjs +378 -0
- package/scripts/test-protocol.mjs +712 -0
- package/scripts/test-security.mjs +1360 -0
- package/scripts/test-sw.mjs +14526 -0
- package/scripts/test-update.mjs +301 -0
- package/skills/agent-in-chrome/SKILL.md +60 -0
- package/skills/agent-in-chrome/references/actions-and-waits.md +136 -0
- package/skills/agent-in-chrome/references/amap-dir-dropdown.md +66 -0
- package/skills/agent-in-chrome/references/geetest-click-captcha.md +55 -0
- package/skills/agent-in-chrome/references/network-debugging.md +20 -0
- package/skills/agent-in-chrome/references/reading-pages.md +30 -0
- package/skills/agent-in-chrome/references/recovery.md +25 -0
- package/skills/agent-in-chrome/references/tabs-and-sessions.md +34 -0
- package/skills/install-agent-in-chrome/SKILL.md +252 -0
|
@@ -0,0 +1,1127 @@
|
|
|
1
|
+
// Agent in Chrome — CLI / headless 模式:自己起一个浏览器,用直连 CDP 驱动。
|
|
2
|
+
//
|
|
3
|
+
// 桌面模式(用户自己开的 Chrome + 装好的扩展)完全不经过这个文件。
|
|
4
|
+
// CLI / headless 模式面向的是没有桌面前提的场合:终端里的 agent、cron、CI、远程机器。
|
|
5
|
+
//
|
|
6
|
+
// 本模块管的是浏览器的一生:找二进制(findBrowser)、拼命令行(browserArgs)、
|
|
7
|
+
// 冷启动或认领已在跑的实例(ensureBrowser)、收孤儿(sweepOrphans)、
|
|
8
|
+
// 收场(stopBrowser / stopBrowserGracefully)。用的是**用户机器上那个正式版 Chrome**,
|
|
9
|
+
// 不是 Chrome for Testing——指纹差别站点看得见。
|
|
10
|
+
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import os from "node:os";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
import { spawn, execFileSync } from "node:child_process";
|
|
15
|
+
import { scriptCmd } from "../cli-invocation.mjs";
|
|
16
|
+
|
|
17
|
+
// 提示里那条「去收掉占用者」的命令,按用户的装法拼(git 检出敲脚本,npm 装的敲子命令)。
|
|
18
|
+
const CLI_BROWSER = scriptCmd("cli-browser");
|
|
19
|
+
|
|
20
|
+
const HOME = os.homedir();
|
|
21
|
+
|
|
22
|
+
export const RUNTIME_DIR = path.join(HOME, ".agent-in-chrome", "agent-in-chrome");
|
|
23
|
+
/*
|
|
24
|
+
* CLI 模式专用 profile,可用 AGENT_IN_CHROME_PROFILE 指到别处,恒为绝对路径。
|
|
25
|
+
* **不能是用户日常那个 profile**:新版 Chrome 会直接拒绝对默认 profile 开
|
|
26
|
+
* `--remote-debugging-port`。代价是这个 profile 第一次跑没有任何登录态,需要的站点得
|
|
27
|
+
* 在里面登一次(登完就持久留着)。
|
|
28
|
+
*/
|
|
29
|
+
export const PROFILE_DIR = path.resolve(process.env.AGENT_IN_CHROME_PROFILE || path.join(RUNTIME_DIR, "cli-profile"));
|
|
30
|
+
const PID_BASENAME = "aic-cli-browser.json";
|
|
31
|
+
const PID_FILE = path.join(PROFILE_DIR, PID_BASENAME);
|
|
32
|
+
const LEGACY_PID_FILE = path.join(RUNTIME_DIR, "cli-browser.json");
|
|
33
|
+
const LOG_FILE = path.join(HOME, ".agent-in-chrome", "agent-in-chrome-cli.log");
|
|
34
|
+
const BROWSER_LOG = path.join(PROFILE_DIR, "aic-cli-browser.log");
|
|
35
|
+
|
|
36
|
+
export const LAUNCH_MODE = ["1", "true", "yes", "on"].includes(
|
|
37
|
+
String(process.env.AGENT_IN_CHROME_LAUNCH || "").toLowerCase()
|
|
38
|
+
);
|
|
39
|
+
export const HEADLESS = !["0", "false", "no", "off"].includes(
|
|
40
|
+
String(process.env.AGENT_IN_CHROME_HEADLESS ?? "1").toLowerCase()
|
|
41
|
+
);
|
|
42
|
+
/* 退出时不收浏览器,留给下一次调用热启动(AGENT_IN_CHROME_KEEP=1) */
|
|
43
|
+
export const KEEP_BROWSER = ["1", "true", "yes", "on"].includes(
|
|
44
|
+
String(process.env.AGENT_IN_CHROME_KEEP || "").toLowerCase()
|
|
45
|
+
);
|
|
46
|
+
|
|
47
|
+
/*
|
|
48
|
+
* CDP 走管道还是走 TCP 端口。**默认管道。**
|
|
49
|
+
*
|
|
50
|
+
* · 管道(`--remote-debugging-pipe`,走子进程的 fd 3/4):不开任何 TCP 端口、
|
|
51
|
+
* 也不写 DevToolsActivePort,只有父进程用得上;代价是浏览器绑在本进程上,
|
|
52
|
+
* 活不过它,也没法被别的进程收养。
|
|
53
|
+
* · 端口(`--remote-debugging-port`):可被收养(KEEP 热复用、主退出后从会话接管
|
|
54
|
+
* 都靠它),代价是那个端口**没有任何访问控制**——本机任何进程连上就能全权驱动。
|
|
55
|
+
*
|
|
56
|
+
* 所以开关挂在 KEEP 上(它的含义本就是「这个浏览器要活过本进程」):默认走管道,
|
|
57
|
+
* `AGENT_IN_CHROME_KEEP=1` 走端口。显式压过:`AGENT_IN_CHROME_CDP_TRANSPORT=pipe|port`。
|
|
58
|
+
*/
|
|
59
|
+
const TRANSPORT_ENV = String(process.env.AGENT_IN_CHROME_CDP_TRANSPORT || "").toLowerCase();
|
|
60
|
+
export const USE_PIPE = TRANSPORT_ENV === "pipe" ? true : TRANSPORT_ENV === "port" ? false : !KEEP_BROWSER;
|
|
61
|
+
|
|
62
|
+
/* sweepOrphans 先 SIGTERM 等这么久,还赖着再 SIGKILL 等那么久;两段之和就是它的预算 */
|
|
63
|
+
const SWEEP_TERM_MS = 2_000;
|
|
64
|
+
const SWEEP_KILL_MS = 500;
|
|
65
|
+
const SWEEP_BUDGET_MS = SWEEP_TERM_MS + SWEEP_KILL_MS;
|
|
66
|
+
/* 管道传输拿端点的上限(在 fd3 上问一句 Browser.getVersion) */
|
|
67
|
+
const PIPE_ENDPOINT_MS = 20_000;
|
|
68
|
+
/* 端口传输拿端点的上限(等 DevToolsActivePort 出现并验明正身) */
|
|
69
|
+
const PORT_ENDPOINT_MS = 30_000;
|
|
70
|
+
|
|
71
|
+
/* 「保证有一个浏览器可用」最长可能花多久 —— 各段预算之和,不是拍出来的数 */
|
|
72
|
+
export const STARTUP_BUDGET_MS = SWEEP_BUDGET_MS + (USE_PIPE ? PIPE_ENDPOINT_MS : PORT_ENDPOINT_MS);
|
|
73
|
+
|
|
74
|
+
/*
|
|
75
|
+
* 调用方等桥接就绪的宽限。留一半余量:预算是各段**理论上限**之和,真实路径还要
|
|
76
|
+
* 加上进程 spawn、ps 快照、磁盘这些没法计入预算的开销。
|
|
77
|
+
* 上限由 MCP 的 60s 调用超时兜着——超过它再等也没意义,桥接那边会先一步被杀掉。
|
|
78
|
+
*/
|
|
79
|
+
export const BRIDGE_GRACE_MS = Math.min(Math.round(STARTUP_BUDGET_MS * 1.5), 50_000);
|
|
80
|
+
|
|
81
|
+
const LOG_MAX_BYTES = 2_000_000;
|
|
82
|
+
|
|
83
|
+
/* 每次落盘先看一眼要不要轮转:超过 maxBytes 就把当前这份挪成 `.1`(只留一代)。所有日志共用这一条 */
|
|
84
|
+
export function rotateIfBig(file, maxBytes = LOG_MAX_BYTES) {
|
|
85
|
+
try {
|
|
86
|
+
if (fs.statSync(file).size < maxBytes) return false;
|
|
87
|
+
fs.renameSync(file, `${file}.1`);
|
|
88
|
+
return true;
|
|
89
|
+
} catch {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const LOG_CHECK_EVERY_BYTES = 64 * 1024;
|
|
95
|
+
let logSinceCheck = Infinity;
|
|
96
|
+
|
|
97
|
+
/*
|
|
98
|
+
* 写一行日志:stderr 一份,`~/.agent-in-chrome/agent-in-chrome-cli.log` 一份(会轮转)。
|
|
99
|
+
* **绝不能写 stdout**——那是 MCP 的 JSON-RPC 协议通道,往上写一个字节就把协议流毁了。
|
|
100
|
+
*/
|
|
101
|
+
export function log(...parts) {
|
|
102
|
+
const line = `[${new Date().toISOString()}] ${parts.join(" ")}`;
|
|
103
|
+
try {
|
|
104
|
+
process.stderr.write(line + "\n");
|
|
105
|
+
} catch {}
|
|
106
|
+
try {
|
|
107
|
+
logSinceCheck += line.length + 1;
|
|
108
|
+
if (logSinceCheck >= LOG_CHECK_EVERY_BYTES) {
|
|
109
|
+
logSinceCheck = 0;
|
|
110
|
+
fs.mkdirSync(path.dirname(LOG_FILE), { recursive: true });
|
|
111
|
+
rotateIfBig(LOG_FILE);
|
|
112
|
+
}
|
|
113
|
+
fs.appendFileSync(LOG_FILE, line + "\n");
|
|
114
|
+
} catch {
|
|
115
|
+
try {
|
|
116
|
+
fs.mkdirSync(path.dirname(LOG_FILE), { recursive: true });
|
|
117
|
+
fs.appendFileSync(LOG_FILE, line + "\n");
|
|
118
|
+
} catch {}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function firstExisting(cands) {
|
|
123
|
+
for (const c of cands) if (c && fs.existsSync(c)) return c;
|
|
124
|
+
return null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/*
|
|
128
|
+
* 找浏览器。优先级就是「越像用户日常那台越好」:
|
|
129
|
+
* 正式版 Chrome → Beta/Canary → Chromium / Chrome for Testing(指纹会差,最后才用)。
|
|
130
|
+
*/
|
|
131
|
+
export function findBrowser() {
|
|
132
|
+
const explicit = process.env.AGENT_IN_CHROME_BIN;
|
|
133
|
+
if (explicit) {
|
|
134
|
+
if (!fs.existsSync(explicit)) throw new Error(`AGENT_IN_CHROME_BIN 指的文件不存在:${explicit}`);
|
|
135
|
+
return { bin: explicit, kind: "指定", stable: true };
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const mac = process.platform === "darwin";
|
|
139
|
+
const stableCands = mac
|
|
140
|
+
? [
|
|
141
|
+
["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "正式版 Chrome"],
|
|
142
|
+
[path.join(HOME, "Applications/Google Chrome.app/Contents/MacOS/Google Chrome"), "正式版 Chrome"],
|
|
143
|
+
["/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta", "Chrome Beta"],
|
|
144
|
+
["/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary", "Chrome Canary"],
|
|
145
|
+
]
|
|
146
|
+
: [
|
|
147
|
+
["/usr/bin/google-chrome", "正式版 Chrome"],
|
|
148
|
+
["/usr/bin/google-chrome-stable", "正式版 Chrome"],
|
|
149
|
+
["/opt/google/chrome/chrome", "正式版 Chrome"],
|
|
150
|
+
];
|
|
151
|
+
for (const [bin, kind] of stableCands) if (fs.existsSync(bin)) return { bin, kind, stable: true };
|
|
152
|
+
|
|
153
|
+
const fallback = mac
|
|
154
|
+
? [
|
|
155
|
+
["/Applications/Chromium.app/Contents/MacOS/Chromium", "Chromium"],
|
|
156
|
+
[
|
|
157
|
+
"/Applications/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
|
|
158
|
+
"Chrome for Testing",
|
|
159
|
+
],
|
|
160
|
+
]
|
|
161
|
+
: [
|
|
162
|
+
["/usr/bin/chromium", "Chromium"],
|
|
163
|
+
["/usr/bin/chromium-browser", "Chromium"],
|
|
164
|
+
];
|
|
165
|
+
for (const [bin, kind] of fallback) if (fs.existsSync(bin)) return { bin, kind, stable: false };
|
|
166
|
+
|
|
167
|
+
throw new Error(
|
|
168
|
+
"找不到浏览器。CLI/headless 模式要用本机的 Chrome(指纹就该是它本来的样子):\n" +
|
|
169
|
+
(mac
|
|
170
|
+
? " macOS:装 Google Chrome 到 /Applications 即可\n"
|
|
171
|
+
: " Linux:apt install google-chrome-stable,或用 AGENT_IN_CHROME_BIN 指路径\n") +
|
|
172
|
+
"也可以用 AGENT_IN_CHROME_BIN 指定任意 Chromium 系二进制。"
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const versionCache = new Map();
|
|
177
|
+
function browserMajorVersion(bin) {
|
|
178
|
+
let key = bin;
|
|
179
|
+
try {
|
|
180
|
+
key = `${bin}@${fs.statSync(bin).mtimeMs}`;
|
|
181
|
+
} catch {}
|
|
182
|
+
if (versionCache.has(key)) return versionCache.get(key);
|
|
183
|
+
let major = "";
|
|
184
|
+
try {
|
|
185
|
+
const out = execFileSync(bin, ["--version"], { encoding: "utf8" });
|
|
186
|
+
major = (out.match(/(\d+)\.\d+\.\d+\.\d+/) || [])[1] || "";
|
|
187
|
+
} catch {}
|
|
188
|
+
versionCache.set(key, major);
|
|
189
|
+
return major;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function headedUserAgent(bin) {
|
|
193
|
+
const major = browserMajorVersion(bin);
|
|
194
|
+
if (!major) return null;
|
|
195
|
+
const plat =
|
|
196
|
+
process.platform === "darwin"
|
|
197
|
+
? "Macintosh; Intel Mac OS X 10_15_7"
|
|
198
|
+
: process.platform === "win32"
|
|
199
|
+
? "Windows NT 10.0; Win64; x64"
|
|
200
|
+
: "X11; Linux x86_64";
|
|
201
|
+
return `Mozilla/5.0 (${plat}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${major}.0.0.0 Safari/537.36`;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/*
|
|
205
|
+
* 自启浏览器的认领标记,写在浏览器进程自己的命令行上(不依赖任何文件)。
|
|
206
|
+
* 值是**起它的那个进程的 pid**,扫孤儿靠它认「这个浏览器是不是我们起的、还有没有人要」。
|
|
207
|
+
*/
|
|
208
|
+
export const OWNER_FLAG = "--aic-owner";
|
|
209
|
+
|
|
210
|
+
/*
|
|
211
|
+
* 从浏览器进程的命令行里读出它的 `--user-data-dir`,读不到给 null。
|
|
212
|
+
*
|
|
213
|
+
* 值一直取到下一个 ` --` 开头的旗标为止:路径里带空格(macOS 的
|
|
214
|
+
* `Application Support` 之流)不能把它截成半截。我们自己 spawn 的命令行里
|
|
215
|
+
* user-data-dir 后面永远还有别的旗标(--remote-debugging-port 紧跟其后),
|
|
216
|
+
* 所以这个边界总是存在。
|
|
217
|
+
*/
|
|
218
|
+
export function profileDirFrom(cmd) {
|
|
219
|
+
const m = /--user-data-dir=(.+?)(?=\s--|$)/.exec(String(cmd || ""));
|
|
220
|
+
return m ? m[1] : null;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/*
|
|
224
|
+
* 从进程列表里挑出「我们起的、而且**没人要了**」的浏览器,返回它们的 pid。
|
|
225
|
+
*
|
|
226
|
+
* 纯函数。判据严格到偏执,失败方向是**宁可漏杀,也绝不误杀用户自己的 Chrome**:
|
|
227
|
+
* 必须带我们的标记(OWNER_FLAG,且前面是空白)、标记值是纯数字 pid、命令行里确实是
|
|
228
|
+
* 浏览器、主人已经不在了;主人不在之后还要再问 profile 里的账——账上 adoptable=true
|
|
229
|
+
* 或 managerPid 还活着,都表示「有人还要它」,不碰。
|
|
230
|
+
*
|
|
231
|
+
* @param procs [{pid, cmd}]
|
|
232
|
+
* @param isAlive (pid) => boolean —— 判断主人 / 现任管理者是否还在
|
|
233
|
+
* @param opts.readRecord (profileDir) => 该 profile 的浏览器记录,不给就回到只看主人的老判据
|
|
234
|
+
* @param opts.excludeProfile 这个 profile 的浏览器一律不碰
|
|
235
|
+
*/
|
|
236
|
+
export function orphansFrom(procs, isAlive, { readRecord = null, excludeProfile = null } = {}) {
|
|
237
|
+
const re = new RegExp(`(?:^|\\s)${OWNER_FLAG.replace(/[-]/g, "\\-")}=(\\d+)(?:\\s|$)`);
|
|
238
|
+
const out = [];
|
|
239
|
+
for (const p of procs || []) {
|
|
240
|
+
const cmd = String(p?.cmd || "");
|
|
241
|
+
if (!/chrome|chromium/i.test(cmd)) continue;
|
|
242
|
+
const m = re.exec(cmd);
|
|
243
|
+
if (!m) continue;
|
|
244
|
+
const owner = Number(m[1]);
|
|
245
|
+
if (!Number.isInteger(owner) || owner <= 0) continue;
|
|
246
|
+
if (isAlive(owner)) continue;
|
|
247
|
+
const profile = profileDirFrom(cmd);
|
|
248
|
+
if (excludeProfile && profile === excludeProfile) continue;
|
|
249
|
+
if (readRecord && profile) {
|
|
250
|
+
const rec = readRecord(profile);
|
|
251
|
+
if (rec && Number(rec.pid) === Number(p.pid)) {
|
|
252
|
+
if (rec.adoptable === true) continue;
|
|
253
|
+
if (rec.managerPid && isAlive(Number(rec.managerPid))) continue;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
out.push(Number(p.pid));
|
|
257
|
+
}
|
|
258
|
+
return out;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/* 本机进程快照,只取 pid + 完整命令行 */
|
|
262
|
+
export function psSnapshot() {
|
|
263
|
+
try {
|
|
264
|
+
const out = execFileSync("/bin/ps", ["-eo", "pid=,command="], { encoding: "utf8", maxBuffer: 8 << 20 });
|
|
265
|
+
return out
|
|
266
|
+
.split("\n")
|
|
267
|
+
.map((l) => {
|
|
268
|
+
const m = /^\s*(\d+)\s+(.*)$/.exec(l);
|
|
269
|
+
return m ? { pid: Number(m[1]), cmd: m[2] } : null;
|
|
270
|
+
})
|
|
271
|
+
.filter(Boolean);
|
|
272
|
+
} catch {
|
|
273
|
+
return [];
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
export const pidAlive = (pid) => {
|
|
278
|
+
try {
|
|
279
|
+
process.kill(pid, 0);
|
|
280
|
+
return true;
|
|
281
|
+
} catch (e) {
|
|
282
|
+
return e.code === "EPERM";
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
|
|
286
|
+
function pidIsZombie(pid) {
|
|
287
|
+
if (process.platform === "win32") return false;
|
|
288
|
+
try {
|
|
289
|
+
const st = execFileSync("/bin/ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8", timeout: 2000 });
|
|
290
|
+
return /^\s*Z/.test(String(st));
|
|
291
|
+
} catch {
|
|
292
|
+
return false;
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/* 给 orphansFrom 的账本读取器:<profile>/aic-cli-browser.json,读不到就是没账 */
|
|
297
|
+
export function readProfileRecord(profileDir) {
|
|
298
|
+
return readJson(path.join(profileDir, PID_BASENAME));
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function sleepSync(ms) {
|
|
302
|
+
if (!(ms > 0)) return;
|
|
303
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/*
|
|
307
|
+
* 盯着这批 pid 直到它们消失或超时,返回**还活着**的那些。
|
|
308
|
+
*
|
|
309
|
+
* 单独抽出来是为了能被注入着测:真进程的死亡时机不由我们说了算,
|
|
310
|
+
* 拿真进程去测「等待逻辑对不对」只会测出一个偶发的测试。
|
|
311
|
+
*/
|
|
312
|
+
export function waitGone(pids, { isAlive = pidAlive, totalMs = 2000, stepMs = 50, sleep = sleepSync, now = Date.now } = {}) {
|
|
313
|
+
let left = pids.filter(isAlive);
|
|
314
|
+
const deadline = now() + totalMs;
|
|
315
|
+
while (left.length) {
|
|
316
|
+
const remain = deadline - now();
|
|
317
|
+
if (remain <= 0) break;
|
|
318
|
+
sleep(Math.min(stepMs, remain));
|
|
319
|
+
left = left.filter(isAlive);
|
|
320
|
+
}
|
|
321
|
+
return left;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/*
|
|
325
|
+
* 收掉本机上「我们起的、没人要了」的浏览器(同步版)。
|
|
326
|
+
* 先 SIGTERM 整组、等,还赖着再 SIGKILL、再等,**验完再报**:
|
|
327
|
+
* 返回 {gone, stubborn}——确认没了的进 gone,杀不掉的进 stubborn,绝不谎报成功。
|
|
328
|
+
* 没有孤儿时一次都不等。
|
|
329
|
+
*
|
|
330
|
+
* @param excludeProfile 这个 profile 的浏览器不碰(调用方自己正要认领它)
|
|
331
|
+
*/
|
|
332
|
+
export function sweepOrphans({
|
|
333
|
+
excludeProfile = null,
|
|
334
|
+
isAlive = pidAlive,
|
|
335
|
+
kill = (pid, sig) => process.kill(pid, sig),
|
|
336
|
+
sleep = sleepSync,
|
|
337
|
+
procs = null,
|
|
338
|
+
termGraceMs = SWEEP_TERM_MS,
|
|
339
|
+
killGraceMs = SWEEP_KILL_MS,
|
|
340
|
+
} = {}) {
|
|
341
|
+
const plan = sweepPlan({ excludeProfile, kill, procs });
|
|
342
|
+
if (!plan) return { gone: [], stubborn: [] };
|
|
343
|
+
const { targets, signal, signalled } = plan;
|
|
344
|
+
let left = signalled.length ? waitGone(signalled, { isAlive, totalMs: termGraceMs, sleep }) : [];
|
|
345
|
+
if (left.length) {
|
|
346
|
+
for (const pid of left) signal(pid, "SIGKILL");
|
|
347
|
+
left = waitGone(left, { isAlive, totalMs: killGraceMs, sleep });
|
|
348
|
+
}
|
|
349
|
+
return sweepFinish(targets, signalled, left, isAlive);
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/*
|
|
353
|
+
* sweepOrphans 的异步版,参数与返回值完全相同。
|
|
354
|
+
* **走得到 await 的调用方必须用这个**:同步那版用 Atomics.wait 把整条线程停住,
|
|
355
|
+
* 最长 2.5s,那段时间事件循环完全冻结,MCP 的请求一律无人应答。
|
|
356
|
+
* 同步版也不能删——`process.on("exit")` 里的兜底只跑得动同步代码。
|
|
357
|
+
*/
|
|
358
|
+
export async function sweepOrphansAsync({
|
|
359
|
+
excludeProfile = null,
|
|
360
|
+
isAlive = pidAlive,
|
|
361
|
+
kill = (pid, sig) => process.kill(pid, sig),
|
|
362
|
+
sleep = (ms) => new Promise((r) => setTimeout(r, ms)),
|
|
363
|
+
procs = null,
|
|
364
|
+
termGraceMs = SWEEP_TERM_MS,
|
|
365
|
+
killGraceMs = SWEEP_KILL_MS,
|
|
366
|
+
} = {}) {
|
|
367
|
+
const plan = sweepPlan({ excludeProfile, kill, procs });
|
|
368
|
+
if (!plan) return { gone: [], stubborn: [] };
|
|
369
|
+
const { targets, signal, signalled } = plan;
|
|
370
|
+
let left = signalled.length ? await waitGoneAsync(signalled, { isAlive, totalMs: termGraceMs, sleep }) : [];
|
|
371
|
+
if (left.length) {
|
|
372
|
+
for (const pid of left) signal(pid, "SIGKILL");
|
|
373
|
+
left = await waitGoneAsync(left, { isAlive, totalMs: killGraceMs, sleep });
|
|
374
|
+
}
|
|
375
|
+
return sweepFinish(targets, signalled, left, isAlive);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function canGroupKill(pid, procs) {
|
|
379
|
+
const cmd = (procs || []).find((p) => Number(p?.pid) === Number(pid))?.cmd;
|
|
380
|
+
const profile = cmd ? profileDirFrom(String(cmd)) : null;
|
|
381
|
+
if (!profile) return true;
|
|
382
|
+
const rec = readProfileRecord(profile);
|
|
383
|
+
return !rec || rec.transport !== "pipe";
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function sweepPlan({ excludeProfile, kill, procs }) {
|
|
387
|
+
const snap = procs || psSnapshot();
|
|
388
|
+
const targets = orphansFrom(snap, pidAlive, { readRecord: readProfileRecord, excludeProfile });
|
|
389
|
+
if (!targets.length) return null;
|
|
390
|
+
const signal = (pid, sig) => {
|
|
391
|
+
if (canGroupKill(pid, snap)) {
|
|
392
|
+
try {
|
|
393
|
+
kill(-pid, sig);
|
|
394
|
+
return true;
|
|
395
|
+
} catch {}
|
|
396
|
+
}
|
|
397
|
+
try {
|
|
398
|
+
kill(pid, sig);
|
|
399
|
+
return true;
|
|
400
|
+
} catch {
|
|
401
|
+
return false;
|
|
402
|
+
}
|
|
403
|
+
};
|
|
404
|
+
const signalled = targets.filter((pid) => signal(pid, "SIGTERM"));
|
|
405
|
+
return { targets, signal, signalled };
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
function sweepFinish(targets, signalled, left, isAlive) {
|
|
409
|
+
const stubborn = new Set(left);
|
|
410
|
+
for (const pid of targets) if (!signalled.includes(pid) && isAlive(pid)) stubborn.add(pid);
|
|
411
|
+
const gone = targets.filter((pid) => !stubborn.has(pid));
|
|
412
|
+
|
|
413
|
+
if (gone.length) log(`收掉 ${gone.length} 个孤儿浏览器: ${gone.join(", ")}`);
|
|
414
|
+
if (stubborn.size) log(`有 ${stubborn.size} 个孤儿浏览器杀不掉(SIGKILL 之后仍在): ${[...stubborn].join(", ")}`);
|
|
415
|
+
return { gone, stubborn: [...stubborn] };
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/* waitGone 的异步版:等法一样,只是把线程还给事件循环 */
|
|
419
|
+
export async function waitGoneAsync(pids, { isAlive = pidAlive, totalMs = 2000, stepMs = 50, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), now = Date.now } = {}) {
|
|
420
|
+
let left = pids.filter(isAlive);
|
|
421
|
+
const deadline = now() + totalMs;
|
|
422
|
+
while (left.length) {
|
|
423
|
+
const remain = deadline - now();
|
|
424
|
+
if (remain <= 0) break;
|
|
425
|
+
await sleep(Math.min(stepMs, remain));
|
|
426
|
+
left = left.filter(isAlive);
|
|
427
|
+
}
|
|
428
|
+
return left;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/*
|
|
432
|
+
* 拼浏览器命令行。固定带上本 profile 的 `--user-data-dir`、认领标记(OWNER_FLAG)、
|
|
433
|
+
* 以及一串把「自动化痕迹」抹平的开关(navigator.webdriver、UA / UA-CH 等)。
|
|
434
|
+
* pipe=true 走 `--remote-debugging-pipe`,否则 `--remote-debugging-port=<port>`(0 = 内核分配)。
|
|
435
|
+
*/
|
|
436
|
+
export function browserArgs({ headless = HEADLESS, port = 0, bin = null, pipe = USE_PIPE } = {}) {
|
|
437
|
+
const args = [
|
|
438
|
+
`--user-data-dir=${PROFILE_DIR}`,
|
|
439
|
+
pipe ? "--remote-debugging-pipe" : `--remote-debugging-port=${port}`,
|
|
440
|
+
"--no-first-run",
|
|
441
|
+
"--no-default-browser-check",
|
|
442
|
+
"--disable-search-engine-choice-screen",
|
|
443
|
+
"--hide-crash-restore-bubble",
|
|
444
|
+
"--use-mock-keychain",
|
|
445
|
+
"--password-store=basic",
|
|
446
|
+
`--window-size=${process.env.AGENT_IN_CHROME_WINDOW || "1280,800"}`,
|
|
447
|
+
"--disable-blink-features=AutomationControlled",
|
|
448
|
+
"--disable-component-update",
|
|
449
|
+
"--disable-features=OptimizationHints",
|
|
450
|
+
"--disable-gpu-shader-disk-cache",
|
|
451
|
+
`--disk-cache-size=${Number(process.env.AGENT_IN_CHROME_DISK_CACHE || 134_217_728)}`,
|
|
452
|
+
`${OWNER_FLAG}=${process.pid}`,
|
|
453
|
+
];
|
|
454
|
+
if (process.platform === "linux") args.push("--disable-dev-shm-usage");
|
|
455
|
+
if (headless) {
|
|
456
|
+
args.unshift("--headless=new");
|
|
457
|
+
const ua = bin ? headedUserAgent(bin) : null;
|
|
458
|
+
if (ua) args.push(`--user-agent=${ua}`);
|
|
459
|
+
}
|
|
460
|
+
if (process.env.AGENT_IN_CHROME_ARGS) args.push(...process.env.AGENT_IN_CHROME_ARGS.split(" ").filter(Boolean));
|
|
461
|
+
args.push("about:blank");
|
|
462
|
+
return args;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
const ACTIVE_PORT_FILE = () => path.join(PROFILE_DIR, "DevToolsActivePort");
|
|
466
|
+
|
|
467
|
+
/*
|
|
468
|
+
* 读 DevToolsActivePort:第一行是端口,第二行是 browser 端点的路径。
|
|
469
|
+
*
|
|
470
|
+
* 第二行长这样:`/devtools/browser/0b6916d7-bd5a-4f78-94b1-e14fb8e377a6`。
|
|
471
|
+
* 那个 GUID 是**每次启动新生成的、一个浏览器实例一个**,它是本文件里最值钱的一样
|
|
472
|
+
* 东西——见 verifyEndpoint。
|
|
473
|
+
*/
|
|
474
|
+
function readEndpoint() {
|
|
475
|
+
try {
|
|
476
|
+
const [port, wsPath] = fs.readFileSync(ACTIVE_PORT_FILE(), "utf8").split("\n");
|
|
477
|
+
if (!port || !wsPath) return null;
|
|
478
|
+
return {
|
|
479
|
+
port: Number(port.trim()),
|
|
480
|
+
wsPath: wsPath.trim(),
|
|
481
|
+
wsUrl: `ws://127.0.0.1:${port.trim()}${wsPath.trim()}`,
|
|
482
|
+
};
|
|
483
|
+
} catch {
|
|
484
|
+
return null;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/*
|
|
489
|
+
* 让端口本人确认:你就是**这个 profile** 的端口文件记的那个浏览器。
|
|
490
|
+
* 核对用 Chrome 自己给的东西——`/json/version` 回的 `webSocketDebuggerUrl` 里带着
|
|
491
|
+
* 那个一实例一个的 GUID,和端口文件第二行逐字相同才认。对不上就抛。
|
|
492
|
+
* 只探活是不够的:端口号会被复用,旧端口文件 + 别人的浏览器一样 200 照回。
|
|
493
|
+
*/
|
|
494
|
+
async function verifyEndpoint(ep) {
|
|
495
|
+
const r = await fetch(`http://127.0.0.1:${ep.port}/json/version`, { signal: AbortSignal.timeout(2000) });
|
|
496
|
+
if (!r.ok) throw new Error(`调试端口 ${ep.port} 回了 HTTP ${r.status}`);
|
|
497
|
+
const info = await r.json();
|
|
498
|
+
const got = (() => {
|
|
499
|
+
try {
|
|
500
|
+
return new URL(info.webSocketDebuggerUrl).pathname;
|
|
501
|
+
} catch {
|
|
502
|
+
return null;
|
|
503
|
+
}
|
|
504
|
+
})();
|
|
505
|
+
if (got !== ep.wsPath)
|
|
506
|
+
throw new Error(
|
|
507
|
+
`调试端口 ${ep.port} 上是**另一个**浏览器:它自报 ${got},而本 profile 的端口文件记的是 ` +
|
|
508
|
+
`${ep.wsPath}。端口号被复用了、端口文件是旧的——不是我们要找的那个浏览器。`
|
|
509
|
+
);
|
|
510
|
+
return { ...ep, version: info.Browser };
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
async function waitForEndpoint(timeoutMs = PORT_ENDPOINT_MS) {
|
|
514
|
+
const t0 = Date.now();
|
|
515
|
+
let last = null;
|
|
516
|
+
while (Date.now() - t0 < timeoutMs) {
|
|
517
|
+
const ep = readEndpoint();
|
|
518
|
+
if (ep) {
|
|
519
|
+
try {
|
|
520
|
+
return await verifyEndpoint(ep);
|
|
521
|
+
} catch (e) {
|
|
522
|
+
last = e;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
526
|
+
}
|
|
527
|
+
throw new Error(
|
|
528
|
+
`${timeoutMs}ms 内没等到浏览器的调试端点(${ACTIVE_PORT_FILE()})。` +
|
|
529
|
+
`看浏览器日志 ${BROWSER_LOG}${last ? `;最后一次探测报的是 ${last.message}` : ""}`
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function readJson(file) {
|
|
534
|
+
try {
|
|
535
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
536
|
+
} catch {
|
|
537
|
+
return null;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function locatePid() {
|
|
542
|
+
const rec = readJson(PID_FILE);
|
|
543
|
+
if (rec?.pid) return [PID_FILE, rec];
|
|
544
|
+
const legacy = readJson(LEGACY_PID_FILE);
|
|
545
|
+
if (legacy?.pid && legacy.profileDir === PROFILE_DIR) return [LEGACY_PID_FILE, legacy];
|
|
546
|
+
return [PID_FILE, null];
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
function readPid() {
|
|
550
|
+
return locatePid()[1];
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function writePid(rec) {
|
|
554
|
+
fs.mkdirSync(path.dirname(PID_FILE), { recursive: true });
|
|
555
|
+
const tmp = `${PID_FILE}.tmp-${process.pid}-${Date.now().toString(36)}`;
|
|
556
|
+
fs.writeFileSync(tmp, JSON.stringify(rec, null, 2) + "\n");
|
|
557
|
+
try {
|
|
558
|
+
fs.renameSync(tmp, PID_FILE);
|
|
559
|
+
} catch (e) {
|
|
560
|
+
try {
|
|
561
|
+
fs.unlinkSync(tmp);
|
|
562
|
+
} catch {}
|
|
563
|
+
throw e;
|
|
564
|
+
}
|
|
565
|
+
dropLegacyIfOurs();
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/*
|
|
569
|
+
* 在账上记一笔「这个浏览器是特意留下等认领的」。
|
|
570
|
+
*
|
|
571
|
+
* 谁来调:所有**故意不收浏览器就走人**的路——bridge.close 的 KEEP / peersLeft>0
|
|
572
|
+
* 两种,以及 cli-browser.mjs 烘热完退出时。少了这一笔,留下的浏览器在 sweepOrphans
|
|
573
|
+
* 眼里就是「主人死了又没人要」的孤儿,下一个进程启动时就把它收了——KEEP 省下的
|
|
574
|
+
* 冷启动、接管要保住的标签页,全在那一下没的。
|
|
575
|
+
*
|
|
576
|
+
* 必须同步:主调用方在 process.on("exit") 里,事件循环已经不转了。
|
|
577
|
+
*/
|
|
578
|
+
export function markAdoptable() {
|
|
579
|
+
const rec = aliveBrowser();
|
|
580
|
+
if (!rec) return false;
|
|
581
|
+
writePid({ ...rec, adoptable: true });
|
|
582
|
+
return true;
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
function dropLegacyIfOurs() {
|
|
586
|
+
if (readJson(LEGACY_PID_FILE)?.profileDir !== PROFILE_DIR) return;
|
|
587
|
+
try {
|
|
588
|
+
fs.unlinkSync(LEGACY_PID_FILE);
|
|
589
|
+
} catch {}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
function clearPid() {
|
|
593
|
+
try {
|
|
594
|
+
fs.unlinkSync(PID_FILE);
|
|
595
|
+
} catch {}
|
|
596
|
+
dropLegacyIfOurs();
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/*
|
|
600
|
+
* 这个 pid 此刻是不是一个正跑着**本 profile** 的浏览器。
|
|
601
|
+
*
|
|
602
|
+
* 两道都必要:pid 会被系统复用(`kill(pid,0)` 只说明「有个进程」,不说明是哪个),
|
|
603
|
+
* 而认 `--user-data-dir=<本 profile>` 才说明是「跑我们这个 profile 的」。
|
|
604
|
+
* 这是所有「要不要把信号发给它」的最后一道闸——别的 profile 的浏览器命令行里写的是
|
|
605
|
+
* 别的目录,过不了这一道,所以一份写错/别人的记录也带不动我们去杀它。
|
|
606
|
+
*/
|
|
607
|
+
function pidRunsThisProfile(pid, procs = null) {
|
|
608
|
+
if (!pid) return false;
|
|
609
|
+
try {
|
|
610
|
+
process.kill(pid, 0);
|
|
611
|
+
} catch {
|
|
612
|
+
return false;
|
|
613
|
+
}
|
|
614
|
+
if (procs) {
|
|
615
|
+
const hit = procs.find((x) => x.pid === Number(pid));
|
|
616
|
+
return !!hit && hit.cmd.includes(`--user-data-dir=${PROFILE_DIR}`);
|
|
617
|
+
}
|
|
618
|
+
try {
|
|
619
|
+
const cmd = execFileSync("/bin/ps", ["-p", String(pid), "-o", "command="], { encoding: "utf8" });
|
|
620
|
+
return cmd.includes(`--user-data-dir=${PROFILE_DIR}`);
|
|
621
|
+
} catch {
|
|
622
|
+
return false;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/*
|
|
627
|
+
* **我们给这个 profile 起的**那个浏览器还活着吗;活着就返回它的记录(pid 已核对过)。
|
|
628
|
+
*
|
|
629
|
+
* 用在收浏览器和报状态上,认领不走这条(认领只问 profile 目录,见 adoptRunning)。
|
|
630
|
+
* 「是我们起的」这半个问题只有我们自己的记录答得出来——Chrome 不记谁把它拉起来的,
|
|
631
|
+
* 所以这里仍要读记录;但**记录说的 pid 不算数**,得过下面那两道核对。
|
|
632
|
+
*/
|
|
633
|
+
export function aliveBrowser() {
|
|
634
|
+
const rec = readPid();
|
|
635
|
+
if (!rec?.pid) return null;
|
|
636
|
+
if (rec.profileDir !== PROFILE_DIR) return null;
|
|
637
|
+
|
|
638
|
+
const owner = profileOwnerPid();
|
|
639
|
+
const pid = owner && pidRunsThisProfile(owner) ? owner : pidRunsThisProfile(rec.pid) ? rec.pid : null;
|
|
640
|
+
if (!pid) return null;
|
|
641
|
+
return { ...rec, pid };
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/*
|
|
645
|
+
* 谁正占着这个 profile(返回它的 pid,没人占返回 null)。
|
|
646
|
+
* **Chrome 自己按 profile 记的,不是我们记的**:读 `<profile>/SingletonLock` 这个
|
|
647
|
+
* 指向「主机名-pid」的符号链接。Chrome 一个 `--user-data-dir` 只准一个实例,
|
|
648
|
+
* 第二个起来会输掉 ProcessSingleton 当场自杀。
|
|
649
|
+
* 这里只探活,**不核对是不是我们起的**——它要回答的是「被谁占着」,答案得包括
|
|
650
|
+
* 用户自己开的那种。拿它当发信号的目标时,核对由调用方补。
|
|
651
|
+
*/
|
|
652
|
+
function profileOwnerPid() {
|
|
653
|
+
let target = null;
|
|
654
|
+
try {
|
|
655
|
+
target = fs.readlinkSync(path.join(PROFILE_DIR, "SingletonLock"));
|
|
656
|
+
} catch {
|
|
657
|
+
return null;
|
|
658
|
+
}
|
|
659
|
+
const m = /-(\d+)$/.exec(String(target));
|
|
660
|
+
if (!m) return null;
|
|
661
|
+
const pid = Number(m[1]);
|
|
662
|
+
try {
|
|
663
|
+
process.kill(pid, 0);
|
|
664
|
+
} catch {
|
|
665
|
+
return null;
|
|
666
|
+
}
|
|
667
|
+
return pid;
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/*
|
|
671
|
+
* 认领一个已经在**这个 profile** 上跑着的浏览器。没有就返回 null(该冷启动了)。
|
|
672
|
+
*
|
|
673
|
+
* 输入全部来自 `<PROFILE_DIR>`:端点读 `DevToolsActivePort`、占用者 pid 读
|
|
674
|
+
* `SingletonLock`(两样都是 Chrome 自己按 profile 写的),再由 verifyEndpoint 让端口
|
|
675
|
+
* 本人用 GUID 确认身份。**于是「认领到别的 profile 的浏览器」从结构上不成立**。
|
|
676
|
+
*/
|
|
677
|
+
async function adoptRunning({ headless, procs = null }) {
|
|
678
|
+
const owner = profileOwnerPid();
|
|
679
|
+
const ep0 = readEndpoint();
|
|
680
|
+
if (!owner && !ep0) return null;
|
|
681
|
+
|
|
682
|
+
let why = null;
|
|
683
|
+
const ep = ep0 ? await verifyEndpoint(ep0).catch((e) => ((why = e), null)) : null;
|
|
684
|
+
|
|
685
|
+
if (!ep) {
|
|
686
|
+
if (!owner) return null;
|
|
687
|
+
if (spawnInProgress()) return null;
|
|
688
|
+
throw new Error(
|
|
689
|
+
`这个 profile 已经被另一个浏览器实例占着(pid=${owner}),但拿不到它的调试端点:${PROFILE_DIR}\n` +
|
|
690
|
+
(why
|
|
691
|
+
? `端点这边报的是:${why.message}\n`
|
|
692
|
+
: `没有 ${ACTIVE_PORT_FILE()}——它大概是没开 --remote-debugging-port 起来的。\n`) +
|
|
693
|
+
"Chrome 一个 profile 只准一个实例同时跑(换 --profile-directory 也绕不过去),\n" +
|
|
694
|
+
"所以现在既认领不了它、也不能另起一个。两条路:\n" +
|
|
695
|
+
" ① 给这个实例换一份自己的 profile:AGENT_IN_CHROME_PROFILE=<另一个目录>\n" +
|
|
696
|
+
` ② 先收掉占用者:${CLI_BROWSER} --stop(带上同一个 AGENT_IN_CHROME_PROFILE)。\n` +
|
|
697
|
+
` 它要是说「没有在跑的浏览器」,说明 pid=${owner} 不是我们起的(比如你自己开的\n` +
|
|
698
|
+
" Chrome 指到了同一个目录),得你自己去收。\n" +
|
|
699
|
+
"(多个 MCP 会话共用一个浏览器不需要这么做——它们靠 socket 主从共用同一个实例。)"
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
const rec = readPid();
|
|
704
|
+
const pid = owner || (rec?.pid && pidRunsThisProfile(rec.pid, procs) ? rec.pid : null);
|
|
705
|
+
const meta = rec && rec.pid === pid ? rec : null;
|
|
706
|
+
const { adopted: _drop, ...persist } = {
|
|
707
|
+
...(meta || {}),
|
|
708
|
+
kind: meta?.kind || "在跑的浏览器",
|
|
709
|
+
headless: meta?.headless ?? headless,
|
|
710
|
+
pid,
|
|
711
|
+
profileDir: PROFILE_DIR,
|
|
712
|
+
managerPid: process.pid,
|
|
713
|
+
adoptable: KEEP_BROWSER,
|
|
714
|
+
...ep,
|
|
715
|
+
};
|
|
716
|
+
writePid(persist);
|
|
717
|
+
log(`复用已在跑的浏览器 pid=${pid} ${ep.version}`);
|
|
718
|
+
return { ...persist, adopted: true };
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
const SPAWN_LOCK_DIR = () => path.join(PROFILE_DIR, "aic-cli-spawn.lock");
|
|
722
|
+
const SPAWN_LOCK_STALE_MS = 60_000;
|
|
723
|
+
const SPAWN_WAIT_MS = Number(process.env.AGENT_IN_CHROME_SPAWN_WAIT_MS || 45_000);
|
|
724
|
+
|
|
725
|
+
function acquireSpawnLock() {
|
|
726
|
+
const dir = SPAWN_LOCK_DIR();
|
|
727
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
728
|
+
try {
|
|
729
|
+
fs.mkdirSync(dir);
|
|
730
|
+
fs.writeFileSync(path.join(dir, "pid"), String(process.pid));
|
|
731
|
+
return true;
|
|
732
|
+
} catch (e) {
|
|
733
|
+
if (e.code !== "EEXIST") throw e;
|
|
734
|
+
let holder = null;
|
|
735
|
+
try {
|
|
736
|
+
holder = Number(fs.readFileSync(path.join(dir, "pid"), "utf8").trim()) || null;
|
|
737
|
+
} catch {}
|
|
738
|
+
const holderAlive = (() => {
|
|
739
|
+
if (!holder) return false;
|
|
740
|
+
try {
|
|
741
|
+
process.kill(holder, 0);
|
|
742
|
+
return true;
|
|
743
|
+
} catch {
|
|
744
|
+
return false;
|
|
745
|
+
}
|
|
746
|
+
})();
|
|
747
|
+
let ageMs = 0;
|
|
748
|
+
try {
|
|
749
|
+
ageMs = Date.now() - fs.statSync(dir).mtimeMs;
|
|
750
|
+
} catch {
|
|
751
|
+
continue;
|
|
752
|
+
}
|
|
753
|
+
const stale = (holder && !holderAlive) || ageMs > SPAWN_LOCK_STALE_MS;
|
|
754
|
+
if (!stale) return false;
|
|
755
|
+
try {
|
|
756
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
757
|
+
} catch {}
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
return false;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
function releaseSpawnLock() {
|
|
764
|
+
try {
|
|
765
|
+
fs.rmSync(SPAWN_LOCK_DIR(), { recursive: true, force: true });
|
|
766
|
+
} catch {}
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
function spawnInProgress() {
|
|
770
|
+
const dir = SPAWN_LOCK_DIR();
|
|
771
|
+
let holder = null;
|
|
772
|
+
try {
|
|
773
|
+
holder = Number(fs.readFileSync(path.join(dir, "pid"), "utf8").trim()) || null;
|
|
774
|
+
} catch {}
|
|
775
|
+
if (holder) {
|
|
776
|
+
try {
|
|
777
|
+
process.kill(holder, 0);
|
|
778
|
+
} catch {
|
|
779
|
+
return false;
|
|
780
|
+
}
|
|
781
|
+
} else if (!fs.existsSync(dir)) {
|
|
782
|
+
return false;
|
|
783
|
+
}
|
|
784
|
+
try {
|
|
785
|
+
return Date.now() - fs.statSync(dir).mtimeMs <= SPAWN_LOCK_STALE_MS;
|
|
786
|
+
} catch {
|
|
787
|
+
return false;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/*
|
|
792
|
+
* 保证有一个浏览器在跑,返回它的记录(pid / profileDir / transport / 端点或管道流)。
|
|
793
|
+
* 已经在跑就复用(热启动,同时保住登录态和已打开的页面),不重开;冷启动约 1~2s。
|
|
794
|
+
* 顺序是:收孤儿 → 认领已在跑的 → 抢冷启动锁 → 起新的。
|
|
795
|
+
* 管道传输下没有可认领的东西(浏览器只有父进程用得上),直接冷启动。
|
|
796
|
+
*/
|
|
797
|
+
export async function ensureBrowser({ headless = HEADLESS } = {}) {
|
|
798
|
+
fs.mkdirSync(PROFILE_DIR, { recursive: true });
|
|
799
|
+
const procs0 = psSnapshot();
|
|
800
|
+
await sweepOrphansAsync({ excludeProfile: PROFILE_DIR, procs: procs0 });
|
|
801
|
+
if (USE_PIPE) {
|
|
802
|
+
if (!acquireSpawnLock()) {
|
|
803
|
+
throw new Error(
|
|
804
|
+
`这个 profile 上另一个进程正在起浏览器,而管道模式下它的浏览器只有它自己用得了。\n` +
|
|
805
|
+
`同一个 profile 不能同时跑两个实例(Chrome 的 ProcessSingleton 不允许)。两条路:\n` +
|
|
806
|
+
` ① 给这个实例换一个 profile:AGENT_IN_CHROME_PROFILE=…\n` +
|
|
807
|
+
` ② 确实要多个进程共用一个浏览器:AGENT_IN_CHROME_KEEP=1(改走可被收养的端口模式,\n` +
|
|
808
|
+
` 代价是那个端口没有访问控制,见 docs/CLI.md)`
|
|
809
|
+
);
|
|
810
|
+
}
|
|
811
|
+
try {
|
|
812
|
+
const holder = profileOwnerPid();
|
|
813
|
+
if (holder && pidRunsThisProfile(holder))
|
|
814
|
+
throw new Error(
|
|
815
|
+
`这个 profile 已经被另一个浏览器实例占着(pid=${holder}):${PROFILE_DIR}\n` +
|
|
816
|
+
`而当前是管道传输,它的 CDP 只有起它的那个进程用得上——认领不了,也不能另起一个\n` +
|
|
817
|
+
`(Chrome 一个 user-data-dir 只准一个实例,换 --profile-directory 也绕不过去)。三条路:\n` +
|
|
818
|
+
` ① 先收掉占用者:${CLI_BROWSER} --stop(带上同一个 AGENT_IN_CHROME_PROFILE)\n` +
|
|
819
|
+
` ② 给这个实例换一份自己的 profile:AGENT_IN_CHROME_PROFILE=<另一个目录>\n` +
|
|
820
|
+
` ③ 确实要多个进程共用一个浏览器:AGENT_IN_CHROME_KEEP=1(改走可被收养的端口模式,\n` +
|
|
821
|
+
` 代价是那个端口没有访问控制,见 docs/CLI.md)`
|
|
822
|
+
);
|
|
823
|
+
return await coldStart({ headless });
|
|
824
|
+
} finally {
|
|
825
|
+
releaseSpawnLock();
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
const t0 = Date.now();
|
|
829
|
+
for (;;) {
|
|
830
|
+
const existing = await adoptRunning({ headless, procs: Date.now() - t0 < 500 ? procs0 : null });
|
|
831
|
+
if (existing) return existing;
|
|
832
|
+
|
|
833
|
+
if (acquireSpawnLock()) {
|
|
834
|
+
try {
|
|
835
|
+
const again = await adoptRunning({ headless });
|
|
836
|
+
if (again) return again;
|
|
837
|
+
return await coldStart({ headless });
|
|
838
|
+
} finally {
|
|
839
|
+
releaseSpawnLock();
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
if (Date.now() - t0 > SPAWN_WAIT_MS)
|
|
844
|
+
throw new Error(
|
|
845
|
+
`等了 ${Math.round((Date.now() - t0) / 1000)}s,另一个进程还在给这个 profile 起浏览器没起完` +
|
|
846
|
+
`(锁:${SPAWN_LOCK_DIR()})。它多半卡住了。两条路:\n` +
|
|
847
|
+
` ① 看它的日志:${BROWSER_LOG}\n` +
|
|
848
|
+
` ② 确认那个进程已经不在了的话,删掉锁目录再来一次。`
|
|
849
|
+
);
|
|
850
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
/*
|
|
855
|
+
* 冷启动前把 profile 里的 variations(field trial)种子清掉,返回删掉的文件名。
|
|
856
|
+
* 只动 profile 根目录下 Variations / VariationsSeedV2 / VariationsSafeSeedV2 三个文件,
|
|
857
|
+
* Default/(cookie、登录态、存储)一概不碰。种子只在启动时应用一次,所以每次冷启动
|
|
858
|
+
* 前删掉即可;删掉后浏览器就是「全新安装还没拉到种子」的形态,站点可见的指纹不变。
|
|
859
|
+
*/
|
|
860
|
+
export function scrubVariationsSeed(profileDir) {
|
|
861
|
+
const removed = [];
|
|
862
|
+
for (const f of ["Variations", "VariationsSeedV2", "VariationsSafeSeedV2"]) {
|
|
863
|
+
try {
|
|
864
|
+
fs.unlinkSync(path.join(profileDir, f));
|
|
865
|
+
removed.push(f);
|
|
866
|
+
} catch {}
|
|
867
|
+
}
|
|
868
|
+
if (removed.length) log(`清掉 variations 种子(field trial 会拖慢 CDP,见 scrubVariationsSeed 注释): ${removed.join(", ")}`);
|
|
869
|
+
return removed;
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/*
|
|
873
|
+
* 管道模式的「起来了没」。
|
|
874
|
+
*
|
|
875
|
+
* 端口模式靠 `<profile>/DevToolsActivePort` 出现来判断;管道模式没有那个文件,
|
|
876
|
+
* 所以判据换成**它答不答得上话**——在 fd3 上问一句 `Browser.getVersion`。
|
|
877
|
+
* 这比等文件更实在:文件只说明端口开了,回答说明 CDP 真的能用了。
|
|
878
|
+
*
|
|
879
|
+
* 返回的形状和 `waitForEndpoint()` 对齐(`version` 那几样),另外把两条流交出去,
|
|
880
|
+
* 好让上层直接拿去建 CdpClient——管道**不能重连**,握手用的就得是同一对 fd。
|
|
881
|
+
*/
|
|
882
|
+
async function pipeEndpoint(child, { timeoutMs = PIPE_ENDPOINT_MS } = {}) {
|
|
883
|
+
const wr = child.stdio[3];
|
|
884
|
+
const rd = child.stdio[4];
|
|
885
|
+
if (!wr?.writable || !rd?.readable)
|
|
886
|
+
throw new Error("--remote-debugging-pipe 起来了但拿不到 fd3/fd4——spawn 的 stdio 配置不对(代码问题,不是环境问题)");
|
|
887
|
+
|
|
888
|
+
const version = await new Promise((resolve, reject) => {
|
|
889
|
+
let buf = Buffer.alloc(0);
|
|
890
|
+
const onData = (chunk) => {
|
|
891
|
+
buf = Buffer.concat([buf, chunk]);
|
|
892
|
+
let i;
|
|
893
|
+
while ((i = buf.indexOf(0)) >= 0) {
|
|
894
|
+
const raw = buf.subarray(0, i).toString("utf8");
|
|
895
|
+
buf = buf.subarray(i + 1);
|
|
896
|
+
if (!raw) continue;
|
|
897
|
+
try {
|
|
898
|
+
const m = JSON.parse(raw);
|
|
899
|
+
if (m.id === 1) {
|
|
900
|
+
cleanup();
|
|
901
|
+
return m.error ? reject(new Error(`Browser.getVersion 报错:${m.error.message}`)) : resolve(m.result || {});
|
|
902
|
+
}
|
|
903
|
+
} catch {}
|
|
904
|
+
}
|
|
905
|
+
};
|
|
906
|
+
const onExit = () => {
|
|
907
|
+
cleanup();
|
|
908
|
+
reject(new Error(`浏览器在握手前就退出了,看 ${BROWSER_LOG}`));
|
|
909
|
+
};
|
|
910
|
+
const timer = setTimeout(() => {
|
|
911
|
+
cleanup();
|
|
912
|
+
reject(new Error(`等了 ${timeoutMs}ms,管道上的 Browser.getVersion 没有回音。看 ${BROWSER_LOG}`));
|
|
913
|
+
}, timeoutMs);
|
|
914
|
+
function cleanup() {
|
|
915
|
+
clearTimeout(timer);
|
|
916
|
+
rd.off("data", onData);
|
|
917
|
+
child.off("exit", onExit);
|
|
918
|
+
}
|
|
919
|
+
rd.on("data", onData);
|
|
920
|
+
child.on("exit", onExit);
|
|
921
|
+
wr.write(JSON.stringify({ id: 1, method: "Browser.getVersion", params: {} }) + "\0");
|
|
922
|
+
});
|
|
923
|
+
|
|
924
|
+
return {
|
|
925
|
+
port: null,
|
|
926
|
+
wsUrl: null,
|
|
927
|
+
browserGuid: null,
|
|
928
|
+
version: version.product || "",
|
|
929
|
+
transport: "pipe",
|
|
930
|
+
pipe: { read: rd, write: wr },
|
|
931
|
+
};
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
async function coldStart({ headless }) {
|
|
935
|
+
const { bin, kind, stable } = findBrowser();
|
|
936
|
+
try {
|
|
937
|
+
fs.unlinkSync(ACTIVE_PORT_FILE());
|
|
938
|
+
} catch {}
|
|
939
|
+
scrubVariationsSeed(PROFILE_DIR);
|
|
940
|
+
|
|
941
|
+
fs.mkdirSync(path.dirname(BROWSER_LOG), { recursive: true });
|
|
942
|
+
rotateIfBig(BROWSER_LOG);
|
|
943
|
+
const out = fs.openSync(BROWSER_LOG, "a");
|
|
944
|
+
const child = USE_PIPE
|
|
945
|
+
? spawn(bin, browserArgs({ headless, bin }), { stdio: ["ignore", out, out, "pipe", "pipe"] })
|
|
946
|
+
: spawn(bin, browserArgs({ headless, bin }), { stdio: ["ignore", out, out], detached: true });
|
|
947
|
+
if (!USE_PIPE) child.unref();
|
|
948
|
+
try {
|
|
949
|
+
fs.closeSync(out);
|
|
950
|
+
} catch {}
|
|
951
|
+
|
|
952
|
+
const ep = USE_PIPE ? await pipeEndpoint(child) : await waitForEndpoint();
|
|
953
|
+
if (!pidRunsThisProfile(child.pid)) {
|
|
954
|
+
log(`冷启动的孩子 pid=${child.pid} 已不在(输掉了 ProcessSingleton),转认领真正的占用者`);
|
|
955
|
+
const winner = await adoptRunning({ headless });
|
|
956
|
+
if (winner) return winner;
|
|
957
|
+
throw new Error(
|
|
958
|
+
`起的浏览器 pid=${child.pid} 没活下来,而这个 profile 的调试端点却在——` +
|
|
959
|
+
`多半是另一个进程抢先占了 ${PROFILE_DIR} 又立刻退了。重试一次,还不行看 ${BROWSER_LOG}。`
|
|
960
|
+
);
|
|
961
|
+
}
|
|
962
|
+
const rec = {
|
|
963
|
+
pid: child.pid,
|
|
964
|
+
bin,
|
|
965
|
+
kind,
|
|
966
|
+
stable,
|
|
967
|
+
profileDir: PROFILE_DIR,
|
|
968
|
+
headless,
|
|
969
|
+
startedAt: new Date().toISOString(),
|
|
970
|
+
managerPid: process.pid,
|
|
971
|
+
adoptable: KEEP_BROWSER,
|
|
972
|
+
...ep,
|
|
973
|
+
};
|
|
974
|
+
writePid(rec);
|
|
975
|
+
log(`起浏览器 ${kind} pid=${child.pid} headless=${headless} ${ep.version} port=${ep.port}`);
|
|
976
|
+
if (!stable)
|
|
977
|
+
log(
|
|
978
|
+
`注意:用的是 ${kind},不是正式版 Chrome —— 指纹和真实用户有可见差距` +
|
|
979
|
+
"(版本、userAgentData.brands)。要紧的话装个 Chrome 或用 AGENT_IN_CHROME_BIN 指过去。"
|
|
980
|
+
);
|
|
981
|
+
return { ...rec, adopted: false };
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
/*
|
|
985
|
+
* 「这个浏览器归别人管着,我不该收」——是的话返回那个管理者的 pid,否则 null。
|
|
986
|
+
*
|
|
987
|
+
* 单独抽成纯函数是为了能被注入着测:真进程的生死不由测试说了算,拿真浏览器去测
|
|
988
|
+
* 「该不该收」只会测出一个偶发的测试(同 waitGone 抽出来的理由)。
|
|
989
|
+
*/
|
|
990
|
+
export function stopBlockedByManager(rec, { force = false, self = process.pid, isAlive = pidAlive } = {}) {
|
|
991
|
+
if (force) return null;
|
|
992
|
+
const mgr = Number(rec?.managerPid);
|
|
993
|
+
if (!Number.isInteger(mgr) || mgr <= 0) return null;
|
|
994
|
+
if (mgr === self) return null;
|
|
995
|
+
return isAlive(mgr) ? mgr : null;
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
/*
|
|
999
|
+
* 收掉我们给**这个 profile** 起的浏览器(同步、发信号),返回是否真的收了一个。
|
|
1000
|
+
* 只认本 profile 的记录,别的会话给别的 profile 起的浏览器绝不碰;
|
|
1001
|
+
* **别人正管着的也不收**(记录里的 managerPid 还活着),`force` 才越过这道。
|
|
1002
|
+
* 端口传输整组打(渲染进程一起走),管道传输只打主进程——那条路的浏览器不是组长。
|
|
1003
|
+
*/
|
|
1004
|
+
export function stopBrowser({ force = false } = {}) {
|
|
1005
|
+
const rec = aliveBrowser();
|
|
1006
|
+
if (!rec) {
|
|
1007
|
+
clearPid();
|
|
1008
|
+
return false;
|
|
1009
|
+
}
|
|
1010
|
+
const mgr = stopBlockedByManager(rec, { force });
|
|
1011
|
+
if (mgr !== null) {
|
|
1012
|
+
log(`不收浏览器 pid=${rec.pid}:它归 pid=${mgr} 管,那个进程还活着`);
|
|
1013
|
+
return false;
|
|
1014
|
+
}
|
|
1015
|
+
const groupKill = rec.transport !== "pipe";
|
|
1016
|
+
try {
|
|
1017
|
+
if (groupKill) process.kill(-rec.pid, "SIGTERM");
|
|
1018
|
+
else process.kill(rec.pid, "SIGTERM");
|
|
1019
|
+
} catch {
|
|
1020
|
+
try {
|
|
1021
|
+
process.kill(rec.pid, "SIGTERM");
|
|
1022
|
+
} catch {}
|
|
1023
|
+
}
|
|
1024
|
+
clearPid();
|
|
1025
|
+
log(`收掉浏览器 pid=${rec.pid}`);
|
|
1026
|
+
return true;
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
/*
|
|
1030
|
+
* 优雅地收掉本 profile 的浏览器:先请它自己退(CDP `Browser.close`),
|
|
1031
|
+
* 不成再退回上面那个同步的信号版。走这条路刚落地的持久 cookie 才刷得下去。
|
|
1032
|
+
*
|
|
1033
|
+
* 判据是**进程真的没了**,不是命令发出去了:`Browser.close` 的回执不保证回得来
|
|
1034
|
+
*(浏览器开始退出时连接先断),所以 stopped 一律由「pid 真的消失了」断。
|
|
1035
|
+
* 连接前必须 verifyEndpoint,否则可能悄悄关掉别人的浏览器。
|
|
1036
|
+
*
|
|
1037
|
+
* @returns {{stopped:boolean, how:"graceful"|"signal"|"none", pid:number|null,
|
|
1038
|
+
* fallbackReason:string|null, expected?:boolean}}
|
|
1039
|
+
* expected=true 表示「这次本来就走不成优雅退出」(管道传输没有端点),不是出了错。
|
|
1040
|
+
*/
|
|
1041
|
+
export async function stopBrowserGracefully({ timeoutMs = 10_000, force = true } = {}) {
|
|
1042
|
+
const rec = aliveBrowser();
|
|
1043
|
+
if (!rec) {
|
|
1044
|
+
clearPid();
|
|
1045
|
+
return { stopped: false, how: "none", pid: null, fallbackReason: null, expected: false };
|
|
1046
|
+
}
|
|
1047
|
+
const pid = rec.pid;
|
|
1048
|
+
let fallbackReason = null;
|
|
1049
|
+
|
|
1050
|
+
let expected = false;
|
|
1051
|
+
const ep0 = readEndpoint();
|
|
1052
|
+
if (rec.transport === "pipe" || !ep0?.wsUrl) {
|
|
1053
|
+
expected = rec.transport === "pipe" || rec.transport === undefined;
|
|
1054
|
+
fallbackReason = expected
|
|
1055
|
+
? `这个浏览器是管道传输起的(绑在起它的进程上,不开调试端口),没有别的进程连得上的端点,` +
|
|
1056
|
+
`只能用信号收——不是出了错。要让 --stop 走 CDP Browser.close(刚落地的持久 cookie 才刷得下去),` +
|
|
1057
|
+
`用 AGENT_IN_CHROME_KEEP=1 起(改走端口模式,见 docs/CLI.md)。`
|
|
1058
|
+
: `记录说它是 ${rec.transport} 传输,却读不到 ${ACTIVE_PORT_FILE()}——端口文件多半被删了或 profile 被搬过。` +
|
|
1059
|
+
`只能退回信号收,刚落地的持久 cookie 可能没刷下去。`;
|
|
1060
|
+
} else {
|
|
1061
|
+
try {
|
|
1062
|
+
const ep = await verifyEndpoint(ep0);
|
|
1063
|
+
const { CdpClient } = await import("./client.mjs");
|
|
1064
|
+
const client = await new CdpClient(ep.wsUrl, { timeoutMs: Math.min(timeoutMs, 5_000) }).connect();
|
|
1065
|
+
try {
|
|
1066
|
+
await client.send("Browser.close").catch(() => {});
|
|
1067
|
+
} finally {
|
|
1068
|
+
try {
|
|
1069
|
+
client.close();
|
|
1070
|
+
} catch {}
|
|
1071
|
+
}
|
|
1072
|
+
if (!(await waitPidGoneAsync(pid, timeoutMs))) {
|
|
1073
|
+
clearPid();
|
|
1074
|
+
log(`优雅收掉浏览器 pid=${pid}(Browser.close)`);
|
|
1075
|
+
return { stopped: true, how: "graceful", pid, fallbackReason: null, expected: false };
|
|
1076
|
+
}
|
|
1077
|
+
fallbackReason = `发了 Browser.close,但 ${timeoutMs}ms 后 pid=${pid} 还活着`;
|
|
1078
|
+
} catch (e) {
|
|
1079
|
+
fallbackReason = String(e?.message || e);
|
|
1080
|
+
}
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
stopBrowser({ force });
|
|
1084
|
+
let stillAlive = await waitPidGoneAsync(pid, SWEEP_TERM_MS + SWEEP_KILL_MS);
|
|
1085
|
+
if (stillAlive) {
|
|
1086
|
+
log(`pid=${pid} 没理 SIGTERM,升级到 SIGKILL`);
|
|
1087
|
+
try {
|
|
1088
|
+
if (rec.transport !== "pipe") process.kill(-pid, "SIGKILL");
|
|
1089
|
+
else process.kill(pid, "SIGKILL");
|
|
1090
|
+
} catch {
|
|
1091
|
+
try {
|
|
1092
|
+
process.kill(pid, "SIGKILL");
|
|
1093
|
+
} catch {}
|
|
1094
|
+
}
|
|
1095
|
+
stillAlive = await waitPidGoneAsync(pid, SWEEP_KILL_MS + 1_000);
|
|
1096
|
+
}
|
|
1097
|
+
return { stopped: !stillAlive, how: "signal", pid, fallbackReason, expected };
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
async function waitPidGoneAsync(pid, totalMs, stepMs = 50) {
|
|
1101
|
+
const deadline = Date.now() + totalMs;
|
|
1102
|
+
let ticks = 0;
|
|
1103
|
+
while (pidAlive(pid)) {
|
|
1104
|
+
if (++ticks % 10 === 0 && pidIsZombie(pid)) return false;
|
|
1105
|
+
if (Date.now() >= deadline) return pidIsZombie(pid) ? false : true;
|
|
1106
|
+
await new Promise((r) => setTimeout(r, stepMs));
|
|
1107
|
+
}
|
|
1108
|
+
return false;
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
/*
|
|
1112
|
+
* 本 profile 的浏览器现状,给 --status 和诊断用:running / pid / 端点 / 记录文件位置,
|
|
1113
|
+
* 外加 stale(有记录但人已经不在)和 foreignRecord(记录记的是别的 profile)两个提示位。
|
|
1114
|
+
*/
|
|
1115
|
+
export function browserStatus() {
|
|
1116
|
+
const [pidFile, rec] = locatePid();
|
|
1117
|
+
const alive = aliveBrowser();
|
|
1118
|
+
return {
|
|
1119
|
+
running: !!alive,
|
|
1120
|
+
...(rec || {}),
|
|
1121
|
+
endpoint: readEndpoint(),
|
|
1122
|
+
pidFile,
|
|
1123
|
+
profileDir: PROFILE_DIR,
|
|
1124
|
+
stale: !!rec && !alive,
|
|
1125
|
+
...(rec && rec.profileDir !== PROFILE_DIR ? { foreignRecord: rec.profileDir } : {}),
|
|
1126
|
+
};
|
|
1127
|
+
}
|