@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,443 @@
|
|
|
1
|
+
// 零依赖 CDP 客户端。CLI/headless 模式的传输层底座。
|
|
2
|
+
//
|
|
3
|
+
// 桌面模式里这一层是 Chrome 自己:扩展调它的调试器 API,浏览器内部
|
|
4
|
+
// 就把命令递给了目标标签页。CLI 模式没有扩展,我们自己连浏览器的 WebSocket 端点,
|
|
5
|
+
// 把同样的命令发出去——所以上层(sw.js 那 7000 行)可以完全不动。
|
|
6
|
+
//
|
|
7
|
+
// 只用 flatten 模式(attachToTarget({flatten:true})):所有 target 的消息都走
|
|
8
|
+
// **同一条** WebSocket,靠 sessionId 分流。老式的嵌套 Target.sendMessageToTarget
|
|
9
|
+
// 已经废弃,而且每个 target 一条连接在 OOPIF 多的页面上会开出十几条。
|
|
10
|
+
|
|
11
|
+
import crypto from "node:crypto";
|
|
12
|
+
|
|
13
|
+
const DEFAULT_TIMEOUT_MS = 30_000;
|
|
14
|
+
|
|
15
|
+
/*
|
|
16
|
+
* 从 CDP 的 targetId 推出一个稳定的整数 tabId(31 位正整数,恒 >= 1)。
|
|
17
|
+
* targetId 在标签页的整个生命周期里不变,所以由它推导出来的 tabId 天然跨进程一致
|
|
18
|
+
* ——不能按进程自增:会话归属是跨进程持久化的,编号重排就会指到别的标签页上。
|
|
19
|
+
*/
|
|
20
|
+
export function tabIdForTarget(targetId) {
|
|
21
|
+
const h = crypto.createHash("sha1").update(String(targetId)).digest();
|
|
22
|
+
return (h.readUInt32BE(0) & 0x7fffffff) || 1;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class CdpError extends Error {
|
|
26
|
+
constructor(msg, { method, params, sessionId } = {}) {
|
|
27
|
+
super(msg);
|
|
28
|
+
this.name = "CdpError";
|
|
29
|
+
this.method = method;
|
|
30
|
+
this.params = params;
|
|
31
|
+
this.sessionId = sessionId;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/*
|
|
36
|
+
* 传输层。CDP 有两条物理通道,帧格式(JSON-RPC)完全一样,只有「怎么送出去」不同:
|
|
37
|
+
*
|
|
38
|
+
* · WebSocket —— `--remote-debugging-port` 开出来的 `ws://127.0.0.1:<port>`。
|
|
39
|
+
* **任何本机进程都连得上**,Chrome 不认令牌,端口号还写在 DevToolsActivePort 里。
|
|
40
|
+
* 换来的是浏览器能被**别的进程收养**(KEEP 热复用、换主接管全靠它)。
|
|
41
|
+
* · 管道 —— `--remote-debugging-pipe`,走子进程的 fd 3(我们写)/ fd 4(我们读),
|
|
42
|
+
* 帧之间用 `\0` 分隔。**天然只有父进程用得上**,Chrome 不监听任何 TCP 端口、
|
|
43
|
+
* 也不写 DevToolsActivePort。代价是浏览器绑在本进程上:关掉 fd3/fd4 它自己退出。
|
|
44
|
+
*
|
|
45
|
+
* 选哪条在 browser-launch.mjs 里定(见那边的 USE_PIPE)。这里只管把两种通道
|
|
46
|
+
* 抹平成同一个接口,上面 CdpClient 的逻辑一行都不用分叉。
|
|
47
|
+
* 两个实现都提供 open({onMessage,onClose}) / write(frame) / close() 三个方法。
|
|
48
|
+
*/
|
|
49
|
+
class WsTransport {
|
|
50
|
+
constructor(wsUrl) {
|
|
51
|
+
this.wsUrl = wsUrl;
|
|
52
|
+
}
|
|
53
|
+
open({ onMessage, onClose }) {
|
|
54
|
+
if (typeof WebSocket === "undefined") {
|
|
55
|
+
return Promise.reject(
|
|
56
|
+
new CdpError(
|
|
57
|
+
`这条 CDP 通道要 Node 的全局 WebSocket,${process.version} 没有(Node 22+ 才有;` +
|
|
58
|
+
`本机装的 Node 太老)。两条出路:升级到 Node 22+,或去掉 AGENT_IN_CHROME_KEEP=1 / ` +
|
|
59
|
+
`AGENT_IN_CHROME_CDP_TRANSPORT=port —— 默认的管道通道在老 Node 上照常能跑,` +
|
|
60
|
+
`代价只是每次会话都要冷启一次浏览器。`
|
|
61
|
+
)
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
return new Promise((resolve, reject) => {
|
|
65
|
+
const ws = new WebSocket(this.wsUrl);
|
|
66
|
+
ws.onopen = () => {
|
|
67
|
+
this.ws = ws;
|
|
68
|
+
resolve();
|
|
69
|
+
};
|
|
70
|
+
ws.onerror = () => reject(new CdpError(`连不上浏览器的 CDP 端点:${this.wsUrl}`));
|
|
71
|
+
ws.onclose = () => onClose();
|
|
72
|
+
ws.onmessage = (ev) => onMessage(ev.data);
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
write(frame) {
|
|
76
|
+
this.ws.send(JSON.stringify(frame));
|
|
77
|
+
}
|
|
78
|
+
close() {
|
|
79
|
+
try {
|
|
80
|
+
this.ws?.close();
|
|
81
|
+
} catch {}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
class PipeTransport {
|
|
86
|
+
/* @param read fd4 的可读流(Chrome → 我们) @param write fd3 的可写流(我们 → Chrome) */
|
|
87
|
+
constructor(read, write) {
|
|
88
|
+
this.read = read;
|
|
89
|
+
this.write_ = write;
|
|
90
|
+
}
|
|
91
|
+
open({ onMessage, onClose }) {
|
|
92
|
+
let parts = [];
|
|
93
|
+
let partsLen = 0;
|
|
94
|
+
this.read.on("data", (chunk) => {
|
|
95
|
+
let start = 0;
|
|
96
|
+
let i;
|
|
97
|
+
while ((i = chunk.indexOf(0, start)) >= 0) {
|
|
98
|
+
const piece = chunk.subarray(start, i);
|
|
99
|
+
let raw;
|
|
100
|
+
if (parts.length) {
|
|
101
|
+
parts.push(piece);
|
|
102
|
+
raw = Buffer.concat(parts, partsLen + piece.length).toString("utf8");
|
|
103
|
+
parts = [];
|
|
104
|
+
partsLen = 0;
|
|
105
|
+
} else {
|
|
106
|
+
raw = piece.toString("utf8");
|
|
107
|
+
}
|
|
108
|
+
start = i + 1;
|
|
109
|
+
if (raw) onMessage(raw);
|
|
110
|
+
}
|
|
111
|
+
if (start < chunk.length) {
|
|
112
|
+
const tail = chunk.subarray(start);
|
|
113
|
+
parts.push(tail);
|
|
114
|
+
partsLen += tail.length;
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
const done = () => onClose();
|
|
118
|
+
this.read.on("close", done);
|
|
119
|
+
this.read.on("end", done);
|
|
120
|
+
this.write_.on("close", done);
|
|
121
|
+
this.write_.on("error", done);
|
|
122
|
+
return Promise.resolve();
|
|
123
|
+
}
|
|
124
|
+
write(frame) {
|
|
125
|
+
this.write_.write(JSON.stringify(frame) + "\0");
|
|
126
|
+
}
|
|
127
|
+
close() {
|
|
128
|
+
try {
|
|
129
|
+
this.read?.destroy();
|
|
130
|
+
} catch {}
|
|
131
|
+
try {
|
|
132
|
+
this.write_?.destroy();
|
|
133
|
+
} catch {}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export class CdpClient {
|
|
138
|
+
#tx = null;
|
|
139
|
+
#nextId = 1;
|
|
140
|
+
#pending = new Map();
|
|
141
|
+
#listeners = new Set();
|
|
142
|
+
#closed = false;
|
|
143
|
+
#closeReason = null;
|
|
144
|
+
#closeHandlers = new Set();
|
|
145
|
+
#closeNotified = false;
|
|
146
|
+
|
|
147
|
+
/*
|
|
148
|
+
* @param target `ws://…` 字符串,或 `{pipe:{read,write}}`(子进程的 fd4/fd3)
|
|
149
|
+
*/
|
|
150
|
+
constructor(target, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
|
|
151
|
+
if (typeof target === "string") {
|
|
152
|
+
this.wsUrl = target;
|
|
153
|
+
this.#tx = new WsTransport(target);
|
|
154
|
+
this.kind = "ws";
|
|
155
|
+
} else if (target?.pipe?.read && target?.pipe?.write) {
|
|
156
|
+
this.wsUrl = null;
|
|
157
|
+
this.#tx = new PipeTransport(target.pipe.read, target.pipe.write);
|
|
158
|
+
this.kind = "pipe";
|
|
159
|
+
} else {
|
|
160
|
+
throw new CdpError("CdpClient 要一个 ws:// 地址或 {pipe:{read,write}}");
|
|
161
|
+
}
|
|
162
|
+
this.timeoutMs = timeoutMs;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async connect() {
|
|
166
|
+
await this.#tx.open({
|
|
167
|
+
onMessage: (data) => this.#onMessage(data),
|
|
168
|
+
onClose: () => this.#settleAllPending(),
|
|
169
|
+
});
|
|
170
|
+
return this;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
#settleAllPending() {
|
|
174
|
+
if (this.#closed && !this.#pending.size) return;
|
|
175
|
+
this.#closed = true;
|
|
176
|
+
const why = this.#closeReason || "浏览器的 CDP 连接断开了(浏览器可能退出了)";
|
|
177
|
+
for (const [, p] of this.#pending) {
|
|
178
|
+
clearTimeout(p.timer);
|
|
179
|
+
p.reject(new CdpError(why, { method: p.method }));
|
|
180
|
+
}
|
|
181
|
+
this.#pending.clear();
|
|
182
|
+
if (!this.#closeNotified) {
|
|
183
|
+
this.#closeNotified = true;
|
|
184
|
+
for (const fn of [...this.#closeHandlers]) {
|
|
185
|
+
try {
|
|
186
|
+
fn(why);
|
|
187
|
+
} catch {}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/* 连接断掉时叫一声(只叫一次)。返回退订函数。 */
|
|
193
|
+
onClose(fn) {
|
|
194
|
+
this.#closeHandlers.add(fn);
|
|
195
|
+
if (this.#closeNotified) {
|
|
196
|
+
try {
|
|
197
|
+
fn(this.#closeReason);
|
|
198
|
+
} catch {}
|
|
199
|
+
}
|
|
200
|
+
return () => this.#closeHandlers.delete(fn);
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
get closed() {
|
|
204
|
+
return this.#closed;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
#onMessage(data) {
|
|
208
|
+
let msg;
|
|
209
|
+
try {
|
|
210
|
+
msg = JSON.parse(data);
|
|
211
|
+
} catch {
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
if (msg.id !== undefined && this.#pending.has(msg.id)) {
|
|
215
|
+
const p = this.#pending.get(msg.id);
|
|
216
|
+
this.#pending.delete(msg.id);
|
|
217
|
+
clearTimeout(p.timer);
|
|
218
|
+
if (msg.error) {
|
|
219
|
+
p.reject(
|
|
220
|
+
new CdpError(`${p.method}: ${msg.error.message}${msg.error.data ? ` (${msg.error.data})` : ""}`, {
|
|
221
|
+
method: p.method,
|
|
222
|
+
sessionId: p.sessionId,
|
|
223
|
+
})
|
|
224
|
+
);
|
|
225
|
+
} else {
|
|
226
|
+
p.resolve(msg.result);
|
|
227
|
+
}
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
if (msg.method) {
|
|
231
|
+
for (const fn of this.#listeners) {
|
|
232
|
+
try {
|
|
233
|
+
fn(msg.method, msg.params, msg.sessionId);
|
|
234
|
+
} catch {
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/* 收 CDP 事件。返回退订函数。 */
|
|
241
|
+
onEvent(fn) {
|
|
242
|
+
this.#listeners.add(fn);
|
|
243
|
+
return () => this.#listeners.delete(fn);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/*
|
|
247
|
+
* 发一条 CDP 命令,resolve 出 result;带 sessionId 就发给那个 target 的会话。
|
|
248
|
+
* 连接已关闭直接 reject;超时(默认 30s)也 reject,两种都是 CdpError。
|
|
249
|
+
*/
|
|
250
|
+
send(method, params = {}, sessionId = undefined, { timeoutMs = this.timeoutMs } = {}) {
|
|
251
|
+
if (this.#closed || !this.#tx)
|
|
252
|
+
return Promise.reject(
|
|
253
|
+
new CdpError(
|
|
254
|
+
"CDP 连接已关闭:浏览器退出了(用户关掉、崩了,或者别人 cli-browser.mjs --stop 收了它)。" +
|
|
255
|
+
"server 会在下一次工具调用时自己重新拉起一个(约 1~2s),直接重试即可;" +
|
|
256
|
+
"旧浏览器里的标签页跟着没了,用 browser_new_tab 重新开。",
|
|
257
|
+
{ method }
|
|
258
|
+
)
|
|
259
|
+
);
|
|
260
|
+
const id = this.#nextId++;
|
|
261
|
+
const frame = { id, method, params };
|
|
262
|
+
if (sessionId) frame.sessionId = sessionId;
|
|
263
|
+
return new Promise((resolve, reject) => {
|
|
264
|
+
const timer = setTimeout(() => {
|
|
265
|
+
this.#pending.delete(id);
|
|
266
|
+
reject(
|
|
267
|
+
new CdpError(
|
|
268
|
+
`${method} ${timeoutMs}ms 没有回执。` +
|
|
269
|
+
"如果是鼠标类命令或截图,先确认这个标签页开了 Emulation.setFocusEmulationEnabled——" +
|
|
270
|
+
"后台标签页不产合成帧时,Chrome 内部会等到 5s 硬超时。",
|
|
271
|
+
{ method, params, sessionId }
|
|
272
|
+
)
|
|
273
|
+
);
|
|
274
|
+
}, timeoutMs);
|
|
275
|
+
timer.unref?.();
|
|
276
|
+
this.#pending.set(id, { resolve, reject, timer, method, sessionId });
|
|
277
|
+
try {
|
|
278
|
+
this.#tx.write(frame);
|
|
279
|
+
} catch (e) {
|
|
280
|
+
clearTimeout(timer);
|
|
281
|
+
this.#pending.delete(id);
|
|
282
|
+
reject(new CdpError(`${method} 发不出去:${e.message}`, { method }));
|
|
283
|
+
}
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
close(reason) {
|
|
288
|
+
this.#closeReason = reason;
|
|
289
|
+
try {
|
|
290
|
+
this.#tx?.close();
|
|
291
|
+
} catch {}
|
|
292
|
+
this.#settleAllPending();
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/*
|
|
297
|
+
* 连上浏览器,并把 target 表维护起来:CDP 认 32 位十六进制 targetId,
|
|
298
|
+
* chrome.tabs.* 那套 API 认整数 tabId,这一层在两者之间翻译,
|
|
299
|
+
* 并把 target 的增删改抛成 created / destroyed / changed 三种事件(见 on())。
|
|
300
|
+
*/
|
|
301
|
+
export class Browser {
|
|
302
|
+
targets = new Map();
|
|
303
|
+
#byTab = new Map();
|
|
304
|
+
activeTargetId = null;
|
|
305
|
+
#handlers = { created: new Set(), destroyed: new Set(), changed: new Set() };
|
|
306
|
+
|
|
307
|
+
constructor(client) {
|
|
308
|
+
this.client = client;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/* @param target `ws://…` 或 `{pipe:{read,write}}`,见 CdpClient 的构造函数 */
|
|
312
|
+
static async connect(target, opts) {
|
|
313
|
+
const client = await new CdpClient(target, opts).connect();
|
|
314
|
+
const br = new Browser(client);
|
|
315
|
+
await br.#init();
|
|
316
|
+
return br;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
async #init() {
|
|
320
|
+
this.client.onEvent((method, params, sessionId) => this.#onEvent(method, params, sessionId));
|
|
321
|
+
await this.client.send("Target.setAutoAttach", {
|
|
322
|
+
autoAttach: true,
|
|
323
|
+
waitForDebuggerOnStart: false,
|
|
324
|
+
flatten: true,
|
|
325
|
+
filter: [{ type: "page", exclude: false }],
|
|
326
|
+
});
|
|
327
|
+
await this.client.send("Target.setDiscoverTargets", { discover: true });
|
|
328
|
+
const { targetInfos } = await this.client.send("Target.getTargets");
|
|
329
|
+
for (const info of targetInfos) this.#upsert(info);
|
|
330
|
+
const firstPage = [...this.targets.values()].find((t) => t.type === "page");
|
|
331
|
+
this.activeTargetId = firstPage?.targetId || null;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
#upsert(info, sessionId, { onlyUpdate = false } = {}) {
|
|
335
|
+
if (info.type !== "page" && info.type !== "iframe") return null;
|
|
336
|
+
let rec = this.targets.get(info.targetId);
|
|
337
|
+
if (!rec && onlyUpdate) return null;
|
|
338
|
+
const fresh = !rec;
|
|
339
|
+
if (!rec) {
|
|
340
|
+
rec = {
|
|
341
|
+
targetId: info.targetId,
|
|
342
|
+
type: info.type,
|
|
343
|
+
url: info.url,
|
|
344
|
+
title: info.title,
|
|
345
|
+
sessionId: sessionId || null,
|
|
346
|
+
tabId: info.type === "page" ? tabIdForTarget(info.targetId) : null,
|
|
347
|
+
openerId: info.openerId || null,
|
|
348
|
+
windowId: 1,
|
|
349
|
+
};
|
|
350
|
+
this.targets.set(info.targetId, rec);
|
|
351
|
+
if (rec.tabId) this.#byTab.set(rec.tabId, info.targetId);
|
|
352
|
+
} else {
|
|
353
|
+
rec.url = info.url ?? rec.url;
|
|
354
|
+
rec.title = info.title ?? rec.title;
|
|
355
|
+
if (sessionId) rec.sessionId = sessionId;
|
|
356
|
+
}
|
|
357
|
+
rec.__fresh = fresh;
|
|
358
|
+
return rec;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
#onEvent(method, params, sessionId) {
|
|
362
|
+
if (method === "Target.attachedToTarget") {
|
|
363
|
+
this.client.send("Runtime.runIfWaitingForDebugger", {}, params.sessionId).catch(() => {});
|
|
364
|
+
const rec = this.#upsert(params.targetInfo, params.sessionId);
|
|
365
|
+
if (rec && rec.__fresh) for (const fn of this.#handlers.created) fn(rec);
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
if (method === "Target.detachedFromTarget") {
|
|
369
|
+
for (const [id, rec] of this.targets) {
|
|
370
|
+
if (rec.sessionId !== params.sessionId) continue;
|
|
371
|
+
if (rec.type === "iframe") this.targets.delete(id);
|
|
372
|
+
else rec.sessionId = null;
|
|
373
|
+
}
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
const discovery = (info) => this.#upsert(info, undefined, { onlyUpdate: info?.type === "iframe" });
|
|
377
|
+
if (method === "Target.targetCreated") {
|
|
378
|
+
discovery(params.targetInfo);
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
if (method === "Target.targetInfoChanged") {
|
|
382
|
+
const rec = discovery(params.targetInfo);
|
|
383
|
+
if (rec) for (const fn of this.#handlers.changed) fn(rec);
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (method === "Target.targetDestroyed") {
|
|
387
|
+
const rec = this.targets.get(params.targetId);
|
|
388
|
+
if (rec) {
|
|
389
|
+
this.targets.delete(params.targetId);
|
|
390
|
+
if (rec.tabId) this.#byTab.delete(rec.tabId);
|
|
391
|
+
if (this.activeTargetId === rec.targetId) this.activeTargetId = null;
|
|
392
|
+
for (const fn of this.#handlers.destroyed) fn(rec);
|
|
393
|
+
}
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
on(kind, fn) {
|
|
399
|
+
this.#handlers[kind].add(fn);
|
|
400
|
+
return () => this.#handlers[kind].delete(fn);
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/*
|
|
404
|
+
* tabId -> 记录,找不到给 null(不抛)。热路径专用,走 #byTab 索引,O(1)。
|
|
405
|
+
*/
|
|
406
|
+
tryByTabId(tabId) {
|
|
407
|
+
const targetId = this.#byTab.get(Number(tabId));
|
|
408
|
+
return (targetId ? this.targets.get(targetId) : null) || null;
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
/* tabId -> 记录。找不到就抛,错误文案照产品口径写清楚下一步。 */
|
|
412
|
+
byTabId(tabId) {
|
|
413
|
+
const targetId = this.#byTab.get(Number(tabId));
|
|
414
|
+
const rec = targetId ? this.targets.get(targetId) : null;
|
|
415
|
+
if (!rec)
|
|
416
|
+
throw new CdpError(
|
|
417
|
+
`标签页 ${tabId} 不在了(可能已被关闭)。用 browser_tabs_list 看现在有哪些,或 browser_new_tab 重新开一张。`
|
|
418
|
+
);
|
|
419
|
+
return rec;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/* 现存的标签页记录(只有 type === "page",不含 OOPIF) */
|
|
423
|
+
pages() {
|
|
424
|
+
return [...this.targets.values()].filter((t) => t.type === "page");
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
/* 保证这个 target 已经 attach,返回 sessionId */
|
|
428
|
+
async session(rec) {
|
|
429
|
+
if (rec.sessionId) return rec.sessionId;
|
|
430
|
+
const { sessionId } = await this.client.send("Target.attachToTarget", {
|
|
431
|
+
targetId: rec.targetId,
|
|
432
|
+
flatten: true,
|
|
433
|
+
});
|
|
434
|
+
rec.sessionId = sessionId;
|
|
435
|
+
return sessionId;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/* 往某个标签页发 CDP 命令 */
|
|
439
|
+
async send(rec, method, params, opts) {
|
|
440
|
+
const sessionId = await this.session(rec);
|
|
441
|
+
return this.client.send(method, params, sessionId, opts);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// 提示文案里那条「你去敲这个」的命令怎么拼——**一处真源**,谁要给用户一条命令都从这里取。
|
|
2
|
+
//
|
|
3
|
+
// 同一个工具有两种敲法,取决于用户是怎么装的:
|
|
4
|
+
// · 仓库检出:`node scripts/borrow-login.mjs …`,直接跑树里那个文件
|
|
5
|
+
// · npm / npx 装的:走 bin 的子命令 `npx @liang-hz/agent-in-chrome borrow-login …`
|
|
6
|
+
//
|
|
7
|
+
// 装出来的运行时是**扁平布局**(`~/.agent-in-chrome/agent-in-chrome/server.mjs`、
|
|
8
|
+
// `<runtime>/cdp/…`),里面没有 `scripts/` 这个目录;npm 包里虽然有 `scripts/`,但它
|
|
9
|
+
// 躺在 npx 缓存或全局 prefix 底下,路径是一串没人抄得动的 hash。这两种情况下写死
|
|
10
|
+
// `node scripts/x.mjs` 的提示,用户照着敲得到的只有一句 Cannot find module。
|
|
11
|
+
|
|
12
|
+
import fs from "node:fs";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
import { fileURLToPath } from "node:url";
|
|
15
|
+
|
|
16
|
+
// npm 上的包名。bin 名不带 scope,包名带——提示里出现的是包名(`npx <包名> <子命令>`)。
|
|
17
|
+
export const PKG = "@liang-hz/agent-in-chrome";
|
|
18
|
+
|
|
19
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
20
|
+
// 这棵树的根:仓库根 / npm 包根 / 扁平运行时目录,三种形态都是本模块的上一层。
|
|
21
|
+
const ROOT = path.join(HERE, "..");
|
|
22
|
+
|
|
23
|
+
/*
|
|
24
|
+
* 判据是「用户 cd 得进去、敲得着 scripts/ 那个目录吗」,两条否决:
|
|
25
|
+
*
|
|
26
|
+
* · 这棵树里根本没有 `scripts/<name>.mjs` —— 装出来的扁平运行时就是这样
|
|
27
|
+
* (`<runtime>/server.mjs`、`<runtime>/cdp/…`,本模块摊在 `<runtime>/cli-invocation.mjs`)。
|
|
28
|
+
* · 这棵树在 `node_modules/` 底下 —— npm -g、npx 缓存、项目依赖三种装法全长这样。
|
|
29
|
+
* 文件确实在盘上,但那条路径是包管理器的内部布局(npx 那份还是一串 hash),
|
|
30
|
+
* 不是能写进文档让人照敲的东西。
|
|
31
|
+
*
|
|
32
|
+
* 两条都不成立才给「直接跑脚本」的敲法:仓库检出(含剥过注释的公开树)就落在这一档。
|
|
33
|
+
*/
|
|
34
|
+
function reachableScript(name) {
|
|
35
|
+
try {
|
|
36
|
+
if (/(^|[\\/])node_modules([\\/]|$)/.test(ROOT)) return false;
|
|
37
|
+
return fs.existsSync(path.join(ROOT, "scripts", `${name}.mjs`));
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const inCheckout = () => reachableScript("borrow-login");
|
|
44
|
+
|
|
45
|
+
/*
|
|
46
|
+
* 一条用户真能敲的命令。
|
|
47
|
+
*
|
|
48
|
+
* @param {string} name scripts/ 下的脚本名,不带扩展名(也就是 bin 的子命令名,两者同名)
|
|
49
|
+
* @param {string} [args] 跟在后面的参数,原样拼上
|
|
50
|
+
*/
|
|
51
|
+
export function scriptCmd(name, args = "") {
|
|
52
|
+
const base = reachableScript(name) ? `node scripts/${name}.mjs` : `npx ${PKG} ${name}`;
|
|
53
|
+
return args ? `${base} ${args}` : base;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// 自检那一条同理:仓库里是 `node scripts/install.mjs --check`,npm 装的是 `check` 子命令。
|
|
57
|
+
export function checkCmd() {
|
|
58
|
+
return inCheckout() ? "node scripts/install.mjs --check" : `npx ${PKG} check`;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// 「重装一遍」那一条。npm 那边带 `@latest`:让用户去拉新的那一份,而不是重跑手上这份。
|
|
62
|
+
export function reinstallCmd() {
|
|
63
|
+
return inCheckout() ? "node scripts/install.mjs" : `npx ${PKG}@latest install`;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// 这棵树里的 `scripts/` 用户敲不敲得着(测试和调用方要复用同一条判据时用它)。
|
|
67
|
+
export const isCheckout = inCheckout;
|
package/mcp/config.mjs
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// Agent in Chrome — 配置真源:~/.agent-in-chrome/config.json。三个读者(扩展 sw.js、
|
|
2
|
+
// MCP server 本进程、安装器 / CLI)互相读不到对方的内存,权威因此放在一个三方都能直接读、
|
|
3
|
+
// 且不依赖谁在线的文件里;内存里的都是缓存,文件说了算。两条铁律:
|
|
4
|
+
// 1. **坏配置一律失败关闭**——保住上一份好的,绝不回落成默认值:默认值比用户的设置
|
|
5
|
+
// 宽松,静默回落等于替他把关掉的工具打开。2. **写必须原子**——临时文件 + rename。
|
|
6
|
+
|
|
7
|
+
import fs from "node:fs";
|
|
8
|
+
import path from "node:path";
|
|
9
|
+
import { defaultDataDir } from "./token.mjs";
|
|
10
|
+
|
|
11
|
+
export const CONFIG_DIR = defaultDataDir();
|
|
12
|
+
export const CONFIG_FILE = path.join(CONFIG_DIR, "config.json");
|
|
13
|
+
|
|
14
|
+
/* 工具档位。名字是对外契约(配置文件里写的就是这个词),别改。 */
|
|
15
|
+
export const PROFILES = ["observe", "full"];
|
|
16
|
+
/*
|
|
17
|
+
* 旧档位名到现档位的迁移表。迁移方向必须是**放宽**:standard → full(更宽松的一侧),
|
|
18
|
+
* 绝不映射到 observe——静默削减用户已有的能力比多给一点危险更糟。
|
|
19
|
+
* readonly → observe 是同能力换名(外加 revealSecrets 提档)。
|
|
20
|
+
*/
|
|
21
|
+
export const LEGACY_PROFILES = { readonly: "observe", standard: "full" };
|
|
22
|
+
|
|
23
|
+
/*
|
|
24
|
+
* 缺省 = 现在的行为。这一条很重要:老用户升上来时没有配置文件,
|
|
25
|
+
* 读到的必须和他升级前用的一模一样,不能因为「有了配置系统」就换了默认行为。
|
|
26
|
+
*/
|
|
27
|
+
export const DEFAULTS = Object.freeze({
|
|
28
|
+
version: 1,
|
|
29
|
+
tools: Object.freeze({
|
|
30
|
+
profile: "full",
|
|
31
|
+
disable: Object.freeze([]),
|
|
32
|
+
enable: Object.freeze([]),
|
|
33
|
+
}),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
const clone = (o) => JSON.parse(JSON.stringify(o));
|
|
37
|
+
|
|
38
|
+
/*
|
|
39
|
+
* 校验 + 补默认值。返回 { value, problems }。
|
|
40
|
+
*
|
|
41
|
+
* problems 非空不代表 value 不能用——不认识的字段会被指出来但跳过,
|
|
42
|
+
* 这样老版本 server 碰上新版本写的配置不会整个罢工。真正致命的(比如
|
|
43
|
+
* 顶层不是对象)会让 value 为 null,交给调用方决定失败关闭。
|
|
44
|
+
*/
|
|
45
|
+
export function normalize(raw) {
|
|
46
|
+
const problems = [];
|
|
47
|
+
const notes = [];
|
|
48
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
49
|
+
return { value: null, problems: ["顶层不是一个 JSON 对象"], notes };
|
|
50
|
+
}
|
|
51
|
+
const out = clone(DEFAULTS);
|
|
52
|
+
|
|
53
|
+
if (raw.version !== undefined) {
|
|
54
|
+
if (!Number.isInteger(raw.version) || raw.version < 1) problems.push(`version 得是 >=1 的整数,收到 ${JSON.stringify(raw.version)}`);
|
|
55
|
+
else out.version = raw.version;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const t = raw.tools;
|
|
59
|
+
if (t !== undefined) {
|
|
60
|
+
if (t === null || typeof t !== "object" || Array.isArray(t)) {
|
|
61
|
+
problems.push("tools 得是对象");
|
|
62
|
+
} else {
|
|
63
|
+
if (t.profile !== undefined) {
|
|
64
|
+
if (PROFILES.includes(t.profile)) {
|
|
65
|
+
out.tools.profile = t.profile;
|
|
66
|
+
} else if (t.profile in LEGACY_PROFILES) {
|
|
67
|
+
out.tools.profile = LEGACY_PROFILES[t.profile];
|
|
68
|
+
notes.push(
|
|
69
|
+
`tools.profile 的 ${JSON.stringify(t.profile)} 是旧档位名,已按 ${JSON.stringify(LEGACY_PROFILES[t.profile])} 生效(0.40 起档位只剩 observe/full)`
|
|
70
|
+
);
|
|
71
|
+
} else {
|
|
72
|
+
return { value: null, problems: [`tools.profile 只能是 ${PROFILES.join(" / ")},收到 ${JSON.stringify(t.profile)}`], notes };
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
for (const key of ["disable", "enable"]) {
|
|
76
|
+
if (t[key] === undefined) continue;
|
|
77
|
+
if (!Array.isArray(t[key])) {
|
|
78
|
+
problems.push(`tools.${key} 得是字符串数组`);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
const bad = t[key].filter((x) => typeof x !== "string" || !x);
|
|
82
|
+
if (bad.length) problems.push(`tools.${key} 里有非字符串项:${JSON.stringify(bad)}`);
|
|
83
|
+
out.tools[key] = [...new Set(t[key].filter((x) => typeof x === "string" && x))];
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
for (const k of Object.keys(raw)) if (!["version", "tools"].includes(k)) problems.push(`不认识的字段 ${k}(已忽略)`);
|
|
89
|
+
|
|
90
|
+
return { value: out, problems, notes };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function defaults() {
|
|
94
|
+
return clone(DEFAULTS);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/*
|
|
98
|
+
* 同步读一次。
|
|
99
|
+
*
|
|
100
|
+
* 返回 { value, problems, source }:
|
|
101
|
+
* source = "default"(文件不存在)/ "file"(读到了)/ "error"(存在但读不了)
|
|
102
|
+
* source === "error" 时 value 为 null —— 调用方必须失败关闭(保住上一份好的),
|
|
103
|
+
* 不能把它当成 "default"。
|
|
104
|
+
*/
|
|
105
|
+
export function loadSync(file = CONFIG_FILE) {
|
|
106
|
+
let text;
|
|
107
|
+
try {
|
|
108
|
+
text = fs.readFileSync(file, "utf8");
|
|
109
|
+
} catch (e) {
|
|
110
|
+
if (e.code === "ENOENT") return { value: defaults(), problems: [], notes: [], source: "default" };
|
|
111
|
+
return { value: null, problems: [`读不了 ${file}:${e.message}`], notes: [], source: "error" };
|
|
112
|
+
}
|
|
113
|
+
let raw;
|
|
114
|
+
try {
|
|
115
|
+
raw = JSON.parse(text);
|
|
116
|
+
} catch (e) {
|
|
117
|
+
return { value: null, problems: [`${file} 不是合法 JSON:${e.message}`], notes: [], source: "error" };
|
|
118
|
+
}
|
|
119
|
+
const { value, problems, notes } = normalize(raw);
|
|
120
|
+
if (value === null) return { value: null, problems, notes, source: "error" };
|
|
121
|
+
return { value, problems, notes, source: "file" };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/*
|
|
125
|
+
* 原子写:同目录临时文件 + rename。
|
|
126
|
+
*
|
|
127
|
+
* 必须同目录——跨文件系统 rename 会退化成拷贝,就不原子了。
|
|
128
|
+
* 只有本进程/扩展改设置时才调它;读者从不写。
|
|
129
|
+
*/
|
|
130
|
+
export function saveSync(value, file = CONFIG_FILE) {
|
|
131
|
+
const { value: clean, problems } = normalize(value);
|
|
132
|
+
if (clean === null) throw new Error(`拒绝写入无效配置:${problems.join(";")}`);
|
|
133
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
134
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now().toString(36)}`;
|
|
135
|
+
fs.writeFileSync(tmp, JSON.stringify(clean, null, 2) + "\n", { mode: 0o600 });
|
|
136
|
+
try {
|
|
137
|
+
fs.renameSync(tmp, file);
|
|
138
|
+
} catch (e) {
|
|
139
|
+
try {
|
|
140
|
+
fs.unlinkSync(tmp);
|
|
141
|
+
} catch {}
|
|
142
|
+
throw e;
|
|
143
|
+
}
|
|
144
|
+
return clean;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/*
|
|
148
|
+
* 盯着配置文件,变了就回调。返回 stop()。
|
|
149
|
+
*
|
|
150
|
+
* 盯的是**目录**不是文件:
|
|
151
|
+
* · 原子写是 rename,被 watch 的那个 inode 根本没被改过,watch 文件收不到事件;
|
|
152
|
+
* · 文件一开始不存在时 watch 文件直接抛 ENOENT,而「第一次创建配置」正是要监听的时刻;
|
|
153
|
+
* · 编辑器保存多半也是 rename-replace,同理。
|
|
154
|
+
*
|
|
155
|
+
* 防抖:一次保存常常连着来好几个事件(rename 前后、元数据),不合并的话
|
|
156
|
+
* 一次改动会发好几条 listChanged,客户端跟着重拉好几次工具表。
|
|
157
|
+
*/
|
|
158
|
+
export function watch(onChange, { file = CONFIG_FILE, debounceMs = 80 } = {}) {
|
|
159
|
+
const dir = path.dirname(file);
|
|
160
|
+
const base = path.basename(file);
|
|
161
|
+
try {
|
|
162
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
163
|
+
} catch {}
|
|
164
|
+
|
|
165
|
+
let timer = null;
|
|
166
|
+
let stopped = false;
|
|
167
|
+
let w;
|
|
168
|
+
try {
|
|
169
|
+
w = fs.watch(dir, { persistent: false }, (_type, name) => {
|
|
170
|
+
if (name && name !== base) return;
|
|
171
|
+
if (timer) clearTimeout(timer);
|
|
172
|
+
timer = setTimeout(() => {
|
|
173
|
+
timer = null;
|
|
174
|
+
if (!stopped) onChange(loadSync(file));
|
|
175
|
+
}, debounceMs);
|
|
176
|
+
});
|
|
177
|
+
} catch (e) {
|
|
178
|
+
return { ok: false, error: e, stop() {} };
|
|
179
|
+
}
|
|
180
|
+
w.unref?.();
|
|
181
|
+
return {
|
|
182
|
+
ok: true,
|
|
183
|
+
stop() {
|
|
184
|
+
stopped = true;
|
|
185
|
+
if (timer) clearTimeout(timer);
|
|
186
|
+
try {
|
|
187
|
+
w.close();
|
|
188
|
+
} catch {}
|
|
189
|
+
},
|
|
190
|
+
};
|
|
191
|
+
}
|