@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.
Files changed (112) hide show
  1. package/.ext-id.txt +4 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/PRIVACY.md +86 -0
  5. package/README.en.md +419 -0
  6. package/README.md +406 -0
  7. package/bin/agent-in-chrome.mjs +97 -0
  8. package/commands/agent-in-chrome.md +18 -0
  9. package/commands/install-agent-in-chrome.md +22 -0
  10. package/docs/AGENTS.md +94 -0
  11. package/docs/CLI.md +297 -0
  12. package/docs/client-compat.json +23 -0
  13. package/extension/about-toc.js +25 -0
  14. package/extension/about.html +240 -0
  15. package/extension/about.js +44 -0
  16. package/extension/agent-window.html +100 -0
  17. package/extension/icons/icon-128.png +0 -0
  18. package/extension/icons/icon-16.png +0 -0
  19. package/extension/icons/icon-24.png +0 -0
  20. package/extension/icons/icon-32.png +0 -0
  21. package/extension/icons/icon-48.png +0 -0
  22. package/extension/icons/icon-64.png +0 -0
  23. package/extension/icons/icon-attention-128.png +0 -0
  24. package/extension/icons/icon-attention-16.png +0 -0
  25. package/extension/icons/icon-attention-24.png +0 -0
  26. package/extension/icons/icon-attention-32.png +0 -0
  27. package/extension/icons/icon-attention-48.png +0 -0
  28. package/extension/icons/icon-attention-64.png +0 -0
  29. package/extension/icons/icon-attention.svg +18 -0
  30. package/extension/icons/icon-failed-128.png +0 -0
  31. package/extension/icons/icon-failed-16.png +0 -0
  32. package/extension/icons/icon-failed-24.png +0 -0
  33. package/extension/icons/icon-failed-32.png +0 -0
  34. package/extension/icons/icon-failed-48.png +0 -0
  35. package/extension/icons/icon-failed-64.png +0 -0
  36. package/extension/icons/icon-failed.svg +18 -0
  37. package/extension/icons/icon-idle-128.png +0 -0
  38. package/extension/icons/icon-idle-16.png +0 -0
  39. package/extension/icons/icon-idle-24.png +0 -0
  40. package/extension/icons/icon-idle-32.png +0 -0
  41. package/extension/icons/icon-idle-48.png +0 -0
  42. package/extension/icons/icon-idle-64.png +0 -0
  43. package/extension/icons/icon-idle.svg +18 -0
  44. package/extension/icons/icon-mark.svg +10 -0
  45. package/extension/icons/icon-running-128.png +0 -0
  46. package/extension/icons/icon-running-16.png +0 -0
  47. package/extension/icons/icon-running-24.png +0 -0
  48. package/extension/icons/icon-running-32.png +0 -0
  49. package/extension/icons/icon-running-48.png +0 -0
  50. package/extension/icons/icon-running-64.png +0 -0
  51. package/extension/icons/icon-running.svg +18 -0
  52. package/extension/icons/icon.svg +18 -0
  53. package/extension/manifest.json +44 -0
  54. package/extension/popup-ui.js +38 -0
  55. package/extension/popup.html +350 -0
  56. package/extension/popup.js +741 -0
  57. package/extension/sw.js +11127 -0
  58. package/extension/update-check.js +66 -0
  59. package/extension/welcome.html +110 -0
  60. package/extension/welcome.js +18 -0
  61. package/mcp/agent-identity.mjs +1007 -0
  62. package/mcp/cdp/bridge.mjs +239 -0
  63. package/mcp/cdp/browser-launch.mjs +1127 -0
  64. package/mcp/cdp/chrome-shim.mjs +1124 -0
  65. package/mcp/cdp/client.mjs +443 -0
  66. package/mcp/cli-invocation.mjs +67 -0
  67. package/mcp/config.mjs +191 -0
  68. package/mcp/foreground-guard.mjs +295 -0
  69. package/mcp/proc-win.mjs +112 -0
  70. package/mcp/secret-shape.mjs +155 -0
  71. package/mcp/server.mjs +3437 -0
  72. package/mcp/session-id.mjs +281 -0
  73. package/mcp/token.mjs +260 -0
  74. package/mcp/tool-tiers.mjs +84 -0
  75. package/mcp/trace.mjs +528 -0
  76. package/mcp/update-cli.mjs +163 -0
  77. package/mcp/update-notice.mjs +194 -0
  78. package/native-host/host.mjs +356 -0
  79. package/native-host/mac-foreground/aic-fg.swift +114 -0
  80. package/native-host/mac-foreground/build.mjs +43 -0
  81. package/package.json +46 -0
  82. package/scripts/agents.mjs +921 -0
  83. package/scripts/borrow-login.mjs +935 -0
  84. package/scripts/cli-browser.mjs +148 -0
  85. package/scripts/e2e-sweep.mjs +192 -0
  86. package/scripts/e2e.mjs +3911 -0
  87. package/scripts/fixture-server.mjs +1419 -0
  88. package/scripts/guard-publish.mjs +175 -0
  89. package/scripts/install.mjs +1383 -0
  90. package/scripts/launcher-provenance.mjs +74 -0
  91. package/scripts/pack-crx.mjs +82 -0
  92. package/scripts/pick.mjs +114 -0
  93. package/scripts/test-agents.mjs +968 -0
  94. package/scripts/test-borrow.mjs +289 -0
  95. package/scripts/test-config.mjs +618 -0
  96. package/scripts/test-e2e-sweep.mjs +251 -0
  97. package/scripts/test-foreground-guard.mjs +383 -0
  98. package/scripts/test-identity.mjs +1141 -0
  99. package/scripts/test-install-skill.mjs +378 -0
  100. package/scripts/test-protocol.mjs +712 -0
  101. package/scripts/test-security.mjs +1360 -0
  102. package/scripts/test-sw.mjs +14526 -0
  103. package/scripts/test-update.mjs +301 -0
  104. package/skills/agent-in-chrome/SKILL.md +60 -0
  105. package/skills/agent-in-chrome/references/actions-and-waits.md +136 -0
  106. package/skills/agent-in-chrome/references/amap-dir-dropdown.md +66 -0
  107. package/skills/agent-in-chrome/references/geetest-click-captcha.md +55 -0
  108. package/skills/agent-in-chrome/references/network-debugging.md +20 -0
  109. package/skills/agent-in-chrome/references/reading-pages.md +30 -0
  110. package/skills/agent-in-chrome/references/recovery.md +25 -0
  111. package/skills/agent-in-chrome/references/tabs-and-sessions.md +34 -0
  112. package/skills/install-agent-in-chrome/SKILL.md +252 -0
@@ -0,0 +1,148 @@
1
+ #!/usr/bin/env node
2
+ // CLI/headless 模式的浏览器:起 / 收 / 查 / 自检。
3
+ //
4
+ // 两种装法各有各的敲法:git 检出跑 `node scripts/cli-browser.mjs …`;npm / npx 装出来的
5
+ // 运行时是扁平布局、没有 `scripts/` 目录,走 bin 的子命令
6
+ // `npx @liang-hz/agent-in-chrome cli-browser …`(旗标一模一样)。
7
+ //
8
+ // (无旗标) 起(已在跑就复用)并自检一遍
9
+ // --headed 有头,想亲眼看它在干什么时用
10
+ // --status 查
11
+ // --stop 收
12
+ //
13
+ // 平时不用手动跑:MCP server 带 AGENT_IN_CHROME_LAUNCH=1 起来时会自己保证浏览器在。
14
+ // 这个脚本的用处是 ① 先把浏览器烘热,省掉每个会话的冷启动 ② 排查连不上
15
+ // ③ 跑 e2e——浏览器要在几轮测试之间一直活着。
16
+ //
17
+ // 起 / 收 / 查都只作用于 `AGENT_IN_CHROME_PROFILE` 指的那一个 profile(默认
18
+ // ~/.agent-in-chrome/agent-in-chrome/cli-profile):记录是按 profile 分开放的,所以 --stop
19
+ // 收不到、也绝不会误收别的会话给别的 profile 起的浏览器。
20
+
21
+ import http from "node:http";
22
+
23
+ process.env.AGENT_IN_CHROME_KEEP ??= "1";
24
+
25
+ const {
26
+ ensureBrowser,
27
+ stopBrowserGracefully,
28
+ markAdoptable,
29
+ browserStatus,
30
+ findBrowser,
31
+ HEADLESS,
32
+ PROFILE_DIR,
33
+ USE_PIPE,
34
+ } = await import("../mcp/cdp/browser-launch.mjs");
35
+ const { Browser } = await import("../mcp/cdp/client.mjs");
36
+
37
+ const argv = process.argv.slice(2);
38
+ const has = (f) => argv.includes(f);
39
+
40
+ if (has("--status")) {
41
+ const st = browserStatus();
42
+ console.log(JSON.stringify(st, null, 2));
43
+ process.exit(st.running ? 0 : 1);
44
+ }
45
+
46
+ if (has("--stop")) {
47
+ const r = await stopBrowserGracefully();
48
+ const how =
49
+ r.how === "graceful"
50
+ ? "优雅退出"
51
+ : r.how === "signal"
52
+ ? r.expected
53
+ ? "信号收掉(管道传输本来就只能这样收)"
54
+ : "信号收掉(没走成优雅退出)"
55
+ : "";
56
+ console.log(`${r.stopped ? `已收掉(${how})` : r.how === "none" ? "没有在跑的浏览器" : `没收掉(${how})`}:${PROFILE_DIR}`);
57
+ if (r.fallbackReason) console.log(` ${r.expected ? "为什么不走优雅退出" : "优雅退出这条路没走通"}:${r.fallbackReason}`);
58
+ if (!r.stopped && r.how !== "none") {
59
+ console.log(` pid=${r.pid} 还活着,SIGTERM/SIGKILL 都没收掉它。它占着 ${PROFILE_DIR},`);
60
+ console.log(" 在它退出之前这个 profile 起不了新浏览器——手动确认那个进程是什么再收。");
61
+ process.exit(1);
62
+ }
63
+ process.exit(0);
64
+ }
65
+
66
+ const headless = has("--headed") ? false : HEADLESS;
67
+
68
+ const { bin, kind, stable } = findBrowser();
69
+ console.log(`浏览器 ${kind}${stable ? "" : "(不是正式版,指纹会差一截)"}\n ${bin}`);
70
+
71
+ const info = await ensureBrowser({ headless });
72
+ console.log(`进程 pid=${info.pid}(${info.adopted ? "复用" : "新起"})headless=${info.headless}`);
73
+ console.log(`版本 ${info.version}`);
74
+ console.log(`端点 ${info.wsUrl || `管道(fd3/fd4,pid=${info.pid} 一退它就退)`}`);
75
+ console.log(`profile ${info.profileDir}`);
76
+ if (USE_PIPE)
77
+ console.log(
78
+ "注意 这次是管道传输(AGENT_IN_CHROME_CDP_TRANSPORT=pipe 压过了默认值):\n" +
79
+ " 浏览器绑在本进程上,脚本一退它就退——烘热不会留下任何东西,e2e 也接不上。"
80
+ );
81
+
82
+ const br = await Browser.connect(info.pipe ? { pipe: info.pipe } : info.wsUrl);
83
+ const t0 = Date.now();
84
+ const { targetId } = await br.client.send("Target.createTarget", { url: "about:blank" });
85
+ for (let i = 0; i < 40 && !br.targets.get(targetId)?.sessionId; i++)
86
+ await new Promise((r) => setTimeout(r, 50));
87
+ const rec = br.targets.get(targetId);
88
+ if (!rec) {
89
+ console.log("\n❌ 新开的标签页没出现在 target 表里(autoAttach 没生效?)");
90
+ process.exit(1);
91
+ }
92
+
93
+ const srv = http.createServer((_q, s) => {
94
+ s.writeHead(200, { "content-type": "text/html; charset=utf-8" });
95
+ s.end("<title>aic-selfcheck</title><h1 id=h>hello</h1>");
96
+ });
97
+ await new Promise((r) => srv.listen(0, "127.0.0.1", r));
98
+ const html = `http://127.0.0.1:${srv.address().port}/`;
99
+ await br.send(rec, "Page.enable");
100
+ await br.send(rec, "Page.navigate", { url: html });
101
+ let title = "";
102
+ for (let i = 0; i < 60; i++) {
103
+ const r = await br.send(rec, "Runtime.evaluate", {
104
+ expression: "document.title + '|' + (document.getElementById('h')?.textContent || '')",
105
+ returnByValue: true,
106
+ });
107
+ title = r.result?.value || "";
108
+ if (title.startsWith("aic-selfcheck|hello")) break;
109
+ await new Promise((r) => setTimeout(r, 50));
110
+ }
111
+ const fp = (
112
+ await br.send(rec, "Runtime.evaluate", {
113
+ expression: `(async () => JSON.stringify({
114
+ ua: navigator.userAgent,
115
+ webdriver: navigator.webdriver,
116
+ brands: navigator.userAgentData?.brands,
117
+ fullVersionList: (await navigator.userAgentData?.getHighEntropyValues(["fullVersionList"]))?.fullVersionList,
118
+ languages: navigator.languages,
119
+ }))()`,
120
+ awaitPromise: true,
121
+ returnByValue: true,
122
+ })
123
+ ).result?.value;
124
+ await br.client.send("Target.closeTarget", { targetId });
125
+ br.client.close();
126
+ srv.close();
127
+
128
+ const o = JSON.parse(fp);
129
+ console.log("\n站点看到的指纹:");
130
+ console.log(` UA ${o.ua}`);
131
+ console.log(` webdriver ${o.webdriver}${o.webdriver ? " ← 必须是 false,见 browser-launch.mjs 里那条 flag" : ""}`);
132
+ console.log(` brands ${JSON.stringify(o.brands)}`);
133
+ console.log(` 版本清单 ${JSON.stringify(o.fullVersionList)}`);
134
+ console.log(` languages ${JSON.stringify(o.languages)}`);
135
+ if (String(o.ua).includes("Headless"))
136
+ console.log(
137
+ " ↑ UA 里带 Headless —— 真实站点看得见。正常路径上它在**起进程时**就被抹掉了" +
138
+ "(browser-launch.mjs 的 --user-agent),这里还带着说明那道没生效:多半是取有头 UA 的" +
139
+ " `--version` 那次调用失败了。走 MCP 时 shim 会在 attach 时补一层兜底。"
140
+ );
141
+
142
+ if (title.startsWith("aic-selfcheck|hello")) {
143
+ markAdoptable();
144
+ console.log(`\n✅ 自检通过(${((Date.now() - t0) / 1000).toFixed(1)}s):开标签页 → 导航 → 读到了页面里的真实内容`);
145
+ process.exit(0);
146
+ }
147
+ console.log(`\n❌ 自检失败:页面里读回来的是 ${JSON.stringify(title)}`);
148
+ process.exit(1);
@@ -0,0 +1,192 @@
1
+ import { spawn } from "node:child_process";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import fs from "node:fs";
5
+ import { pathToFileURL } from "node:url";
6
+
7
+ export const E2E_PREFIX = "e2e-";
8
+
9
+ export function ownerPidOf(sid) {
10
+ const m = /-(\d+)-[0-9a-z]+$/.exec(String(sid || ""));
11
+ if (!m) return null;
12
+ const pid = Number(m[1]);
13
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
14
+ }
15
+
16
+ export function liveRegisteredSessions(registry, isAlive) {
17
+ const out = new Set();
18
+ for (const row of Array.isArray(registry) ? registry : []) {
19
+ if (!Number.isInteger(row?.pid) || !isAlive(row.pid)) continue;
20
+ for (const sid of Array.isArray(row.sessions) ? row.sessions : []) out.add(sid);
21
+ }
22
+ return out;
23
+ }
24
+
25
+ export function pickStraySessions({ otherSessions, registry = [], isAlive }) {
26
+ const protectedSids = liveRegisteredSessions(registry, isAlive);
27
+ const out = [];
28
+ for (const o of Array.isArray(otherSessions) ? otherSessions : []) {
29
+ const sid = o?.session;
30
+ if (typeof sid !== "string" || !sid.startsWith(E2E_PREFIX)) continue;
31
+ const tabIds = Array.isArray(o.tabIds) ? o.tabIds : [];
32
+ if (!tabIds.length) continue;
33
+ if (protectedSids.has(sid)) continue;
34
+ const pid = ownerPidOf(sid);
35
+ if (pid !== null && isAlive(pid)) continue;
36
+ out.push({
37
+ session: sid,
38
+ tabIds,
39
+ why: pid === null ? "旧版裸名会话,主人无从追溯" : `主人进程 ${pid} 已退出`,
40
+ });
41
+ }
42
+ return out;
43
+ }
44
+
45
+ function registryPath() {
46
+ const base = process.env.AGENT_IN_CHROME_SOCK
47
+ ? path.dirname(path.resolve(process.env.AGENT_IN_CHROME_SOCK))
48
+ : path.join(os.homedir(), ".agent-in-chrome");
49
+ return path.join(base, "e2e-runs.json");
50
+ }
51
+
52
+ function readRegistryFile() {
53
+ try {
54
+ const v = JSON.parse(fs.readFileSync(registryPath(), "utf8"));
55
+ return Array.isArray(v) ? v : [];
56
+ } catch {
57
+ return [];
58
+ }
59
+ }
60
+
61
+ function pidAlive(pid) {
62
+ try {
63
+ process.kill(pid, 0);
64
+ return true;
65
+ } catch (e) {
66
+ return e && e.code === "EPERM";
67
+ }
68
+ }
69
+
70
+ function sweepClient(sessionId) {
71
+ const launcher =
72
+ process.env.AGENT_IN_CHROME_E2E_LAUNCHER ||
73
+ path.join(os.homedir(), ".agent-in-chrome", "agent-in-chrome", "mcp-launcher.sh");
74
+ const p = spawn(launcher, [], {
75
+ stdio: ["pipe", "pipe", "pipe"],
76
+ env: { ...process.env, AGENT_IN_CHROME_SESSION_ID: sessionId },
77
+ });
78
+ let buf = "";
79
+ const waiters = new Map();
80
+ let n = 0;
81
+ p.stdout.setEncoding("utf8");
82
+ p.stdout.on("data", (c) => {
83
+ buf += c;
84
+ let i;
85
+ while ((i = buf.indexOf("\n")) >= 0) {
86
+ const line = buf.slice(0, i).trim();
87
+ buf = buf.slice(i + 1);
88
+ if (!line) continue;
89
+ try {
90
+ const m = JSON.parse(line);
91
+ const f = waiters.get(m.id);
92
+ if (f) { waiters.delete(m.id); f(m); }
93
+ } catch {}
94
+ }
95
+ });
96
+ let errTail = "";
97
+ p.stderr.setEncoding("utf8");
98
+ p.stderr.on("data", (c) => { errTail = (errTail + c).slice(-4000); });
99
+ const rpc = (method, params) =>
100
+ new Promise((res, rej) => {
101
+ const id = ++n;
102
+ const t = setTimeout(() => rej(new Error(`${method} 超时`)), 30000);
103
+ waiters.set(id, (m) => { clearTimeout(t); res(m); });
104
+ p.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
105
+ });
106
+ return {
107
+ get errTail() { return errTail; },
108
+ async init() {
109
+ await rpc("initialize", {
110
+ protocolVersion: "2025-06-18",
111
+ capabilities: {},
112
+ clientInfo: { name: "e2e-sweep", version: "0" },
113
+ });
114
+ p.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n");
115
+ },
116
+ async call(tool, args = {}) {
117
+ const r = await rpc("tools/call", { name: tool, arguments: args });
118
+ const text = r.result?.content?.[0]?.text ?? "";
119
+ if (r.result?.isError) throw new Error(text);
120
+ try { return JSON.parse(text); } catch { return text; }
121
+ },
122
+ kill() { try { p.kill(); } catch {} },
123
+ };
124
+ }
125
+
126
+ export async function runSweep({ dryRun = false, log = console.log, makeClient = sweepClient, registry = null, isAlive = pidAlive } = {}) {
127
+ const probe = makeClient(`sweep-${process.pid}-${Date.now().toString(36)}`);
128
+ let stray = [];
129
+ try {
130
+ await probe.init();
131
+ const st = await probe.call("browser_status");
132
+ stray = pickStraySessions({
133
+ otherSessions: st?.otherSessions,
134
+ registry: registry ?? readRegistryFile(),
135
+ isAlive,
136
+ });
137
+ } finally {
138
+ probe.kill();
139
+ }
140
+
141
+ if (!stray.length) {
142
+ log("没有游离的 e2e 会话——干净。");
143
+ return { stray: [], closed: 0 };
144
+ }
145
+
146
+ log(`发现 ${stray.length} 个游离的 e2e 会话:`);
147
+ for (const s of stray) log(` · ${s.session}(${s.why})占着 ${s.tabIds.length} 个标签页`);
148
+ if (dryRun) {
149
+ log("\n--dry-run:一个都没收。去掉这个参数才真的关。");
150
+ return { stray, closed: 0 };
151
+ }
152
+
153
+ let closed = 0;
154
+ let released = 0;
155
+ for (const s of stray) {
156
+ const c = makeClient(s.session);
157
+ try {
158
+ await c.init();
159
+ const r = await c.call("browser_close_all", { scope: "session" });
160
+ const n = r?.closedCount || 0;
161
+ const rel = r?.releasedCount || 0;
162
+ closed += n;
163
+ released += rel;
164
+ log(` \x1b[32m✓\x1b[0m ${s.session}:收掉 ${n} 个标签页${rel ? `,另有 ${rel} 张只解了组没关(见下)` : ""}`);
165
+ } catch (e) {
166
+ log(` \x1b[33m·\x1b[0m ${s.session}:这次没收成(${String(e.message).slice(0, 120)})——下次再跑还会看见它`);
167
+ } finally {
168
+ c.kill();
169
+ }
170
+ }
171
+ log(`\n共收掉 ${closed} 个标签页。用户自己的页一张没动。`);
172
+ if (released) {
173
+ log(
174
+ `另有 ${released} 张页只解了组、没有关:close_all 只关「确实是 agent 自己开的」那些,` +
175
+ `而这几张在扩展账本上只有归属、没有「我开的」这一笔(e2e 被强杀时刚建出来、还没落盘就会这样)。` +
176
+ `它们此后不再属于任何会话,本命令也就再看不见它们——请自己确认一下要不要关掉。`
177
+ );
178
+ }
179
+ return { stray, closed, released };
180
+ }
181
+
182
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
183
+ const dryRun = process.argv.includes("--dry-run") || process.argv.includes("-n");
184
+ try {
185
+ await runSweep({ dryRun });
186
+ process.exit(0);
187
+ } catch (e) {
188
+ console.error(`清扫没跑成:${e.message}`);
189
+ console.error("桥接没连上多半是 Chrome 没开、或扩展被停用。先 `node scripts/install.mjs --check`。");
190
+ process.exit(1);
191
+ }
192
+ }