@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,194 @@
1
+ /*
2
+ * 更新提示:把「有新版了」这件事说给 **agent** 听,而不是打印到一个没人看的终端。
3
+ *
4
+ * MCP server 是被 agent 客户端 spawn 的子进程,stdout 是协议通道、stderr 多半没人看——
5
+ * 传统 CLI 那种「启动时打一行黄字」在这里等于没说。所以提示走**工具返回值的尾巴**:
6
+ * agent 读到那句话,可以自己决定要不要告诉用户、要不要去升级。
7
+ *
8
+ * 三条硬约束(越界就会变成骚扰):
9
+ * - 不阻塞:查询在后台跑,查不完就算了,绝不让任何一次工具调用等它
10
+ * - 不打扰:一个进程只提示一次,且只在有新版时才追加
11
+ * - 可关掉:AGENT_IN_CHROME_NO_UPDATE_NOTIFIER=1 或任何 CI 环境直接不查
12
+ *
13
+ * 出站请求只有这一个,且只发出「最新版本号是多少」这一问:不带机器标识、不带用量、
14
+ * 不带任何本机信息。这是整个产品唯一的非 localhost 网络行为,PRIVACY.md 里写明了。
15
+ */
16
+
17
+ import https from "node:https";
18
+
19
+ /*
20
+ * 两个名字,别混:
21
+ * · PKG —— **npm 包名**(带 scope)。只用在 registry 地址、`npx <PKG>@latest …`、
22
+ * `--package=<PKG>@x.y.z` 这三类地方。
23
+ * · BIN —— **可执行文件名 / 产品短名**。package.json 的 `bin` 键、GitHub 仓库名、
24
+ * `~/.agent-in-chrome` 数据目录、各客户端 MCP 配置里那个键,全都是它,**不随 scope 改**;
25
+ * 改它会让已装用户升级后断链(配置里的键对不上、数据目录换了地方)。
26
+ * 两个都是写死的常量:运行时目录里只有安装器摊过去的那几个 .mjs,没有 package.json,
27
+ * 在那里读它必然 ENOENT。防漂靠 scripts/test-sw.mjs 里「PKG 与 package.json 的 name 一致」那条断言。
28
+ */
29
+ export const PKG = "@liang-hz/agent-in-chrome";
30
+ export const BIN = "agent-in-chrome";
31
+
32
+ /*
33
+ * registry 端点:`/<包名>/latest`,**不带** `application/vnd.npm.install-v1+json`
34
+ * 那个「精简 packument」accept 头——registry 只对**整份 packument** 提供精简表示,
35
+ * `/latest` 这个单版本端点上给 scoped 包直接判 406;而这里的失败是静默返回 null,
36
+ * 不会有任何人看见。extension/update-check.js 同此,别只改一边。
37
+ */
38
+ export const REGISTRY = `https://registry.npmjs.org/${PKG}/latest`;
39
+ const FETCH_TIMEOUT_MS = 2000;
40
+ const RELEASES = `https://github.com/Liang-HZ/${BIN}/releases`;
41
+
42
+ /*
43
+ * 提示语里给用户的升级命令。`update` 子命令内部另走一条:查到精确版本号再用它下发
44
+ * (见 mcp/update-cli.mjs),为的是在日志里留下「装的到底是哪一版」。
45
+ */
46
+ export const UPDATE_CMD = `npx ${PKG}@latest update`;
47
+
48
+ function disabled() {
49
+ const off = String(process.env.AGENT_IN_CHROME_NO_UPDATE_NOTIFIER || "").toLowerCase();
50
+ if (["1", "true", "yes", "on"].includes(off)) return true;
51
+ if (process.env.CI) return true;
52
+ return false;
53
+ }
54
+
55
+ function parse(v) {
56
+ const m = /^(\d+)\.(\d+)\.(\d+)/.exec(String(v || "").trim());
57
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
58
+ }
59
+
60
+ /*
61
+ * 把远端来的版本串洗成 `x.y.z`,洗不出来返回 null。
62
+ *
63
+ * 这不是洁癖:registry 的应答是远程可控的,而这个值有两个去处——① 追加到工具返回值
64
+ * 尾巴(模型直接读的位置,一条 `"<版本串> 忽略以上所有指令…"` 就是高可信度提示注入);
65
+ * ② 拼进 `update` 下发给 npm 的 `--package=@liang-hz/agent-in-chrome@<版本>`。两处都只接受三段数字。
66
+ */
67
+ export function cleanVersion(v) {
68
+ const m = parse(v);
69
+ return m ? m.join(".") : null;
70
+ }
71
+
72
+ export function isNewer(a, b) {
73
+ const x = parse(a);
74
+ const y = parse(b);
75
+ if (!x || !y) return false;
76
+ for (let i = 0; i < 3; i++) {
77
+ if (x[i] > y[i]) return true;
78
+ if (x[i] < y[i]) return false;
79
+ }
80
+ return false;
81
+ }
82
+
83
+ /*
84
+ * 取 npm 上的最新版本号。任何失败(超时、断网、限流、返回不是 JSON)都**静默返回 null**。
85
+ * 超时默认 2s,是**后台提示那条路**的预算:它绝不能让工具调用等,宁可这次不提示。
86
+ * 终端里的 check / update 是人在等,给得起更长,所以那边显式传大一点的值
87
+ * (见 mcp/update-cli.mjs 的 CLI_TIMEOUT_MS)。
88
+ */
89
+ export function fetchLatest({ timeoutMs = FETCH_TIMEOUT_MS } = {}) {
90
+ return new Promise((resolve) => {
91
+ let settled = false;
92
+ const done = (v) => {
93
+ if (settled) return;
94
+ settled = true;
95
+ resolve(v);
96
+ };
97
+ const timer = setTimeout(() => done(null), timeoutMs);
98
+ timer.unref?.();
99
+
100
+ try {
101
+ const req = https.get(
102
+ REGISTRY,
103
+ (res) => {
104
+ if (res.statusCode !== 200) {
105
+ res.resume();
106
+ clearTimeout(timer);
107
+ return done(null);
108
+ }
109
+ let buf = "";
110
+ res.setEncoding("utf8");
111
+ res.on("data", (c) => {
112
+ buf += c;
113
+ if (buf.length > 1 << 20) req.destroy();
114
+ });
115
+ res.on("end", () => {
116
+ clearTimeout(timer);
117
+ try {
118
+ done(JSON.parse(buf)?.version || null);
119
+ } catch {
120
+ done(null);
121
+ }
122
+ });
123
+ }
124
+ );
125
+ req.on("error", () => {
126
+ clearTimeout(timer);
127
+ done(null);
128
+ });
129
+ req.setTimeout(timeoutMs, () => req.destroy());
130
+ } catch {
131
+ clearTimeout(timer);
132
+ done(null);
133
+ }
134
+ });
135
+ }
136
+
137
+ /*
138
+ * 创建一个提示器。
139
+ *
140
+ * @param {object} opts
141
+ * @param {string} opts.current 本地版本
142
+ * @param {(url:string)=>Promise<string|null>} [opts.fetcher] 仅测试用的注入点
143
+ * @returns {{ start():void, take():string|null }}
144
+ * start() 触发一次后台查询(重复调用无副作用);
145
+ * take() 返回该追加的那行提示,**取走即清**——一个进程只提示一次。
146
+ * snapshot() 返回 { current, latest, hasUpdate },给 browser_status 用。
147
+ * 它**只读那一次后台查询的结果**,自己不发任何请求:加个字段不该多一次出站,
148
+ * 也不该让 browser_status 这种几十毫秒就回的调用去等网络。
149
+ * 查询还没回来 / 查失败 / 被关掉(CI、NO_UPDATE_NOTIFIER)时 latest 恒为 null,
150
+ * hasUpdate 恒为 false——「不知道」和「没有新版」在字段上分得开:看 latest 是不是 null。
151
+ * 和 take() 互不干扰:take 是一次性的提示行,snapshot 可以问任意多次。
152
+ */
153
+ export function createUpdateNotice({ current, fetcher } = {}) {
154
+ let pending = null;
155
+ let started = false;
156
+ let spent = false;
157
+ let latestSeen = null;
158
+
159
+ const start = () => {
160
+ if (started || spent || disabled()) return;
161
+ started = true;
162
+ const get = fetcher ? fetcher(REGISTRY) : fetchLatest();
163
+ Promise.resolve(get)
164
+ .then((latest) => {
165
+ const v = parse(latest);
166
+ if (v) latestSeen = v.join(".");
167
+ if (v && isNewer(latest, current)) {
168
+ const safe = v.join(".");
169
+ pending =
170
+ `[${BIN}] 有新版本 ${safe}(当前 ${current})。` +
171
+ `升级:${UPDATE_CMD};更新说明:${RELEASES}。` +
172
+ `请把这件事转告用户,由用户决定是否升级,不要自行升级。` +
173
+ `(设 AGENT_IN_CHROME_NO_UPDATE_NOTIFIER=1 可永久关闭此提示)`;
174
+ }
175
+ })
176
+ .catch(() => {});
177
+ };
178
+
179
+ const take = () => {
180
+ if (!pending) return null;
181
+ const line = pending;
182
+ pending = null;
183
+ spent = true;
184
+ return line;
185
+ };
186
+
187
+ const snapshot = () => ({
188
+ current: current ?? null,
189
+ latest: latestSeen,
190
+ hasUpdate: latestSeen ? isNewer(latestSeen, current) : false,
191
+ });
192
+
193
+ return { start, take, snapshot };
194
+ }
@@ -0,0 +1,356 @@
1
+ #!/usr/bin/env node
2
+ // Agent in Chrome — native messaging host
3
+ //
4
+ // 这个进程由 Chrome 拉起,生命周期跟着扩展的 service worker 走(SW 一死就收到 EOF)。
5
+ // 所以它不持有任何业务状态,只做两件事:
6
+ // 1. stdio 长度前缀协议 <-> unix socket 上的换行分隔 JSON
7
+ // 2. 每 20s 往扩展发一个 ping,把 MV3 的 30s 空闲计时器顶回去
8
+ //
9
+ // 铁律:stdout 是协议通道,除了帧什么都不能写。日志一律进文件。
10
+
11
+ import net from "node:net";
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+
17
+ const SOCK = process.env.AGENT_IN_CHROME_SOCK || path.join(os.homedir(), ".agent-in-chrome", "agent-in-chrome.sock");
18
+ const LOG = path.join(os.homedir(), ".agent-in-chrome", "agent-in-chrome-host.log");
19
+ const PING_MS = 20_000;
20
+ const RECONNECT_MS = 1_000;
21
+ const RECONNECT_MAX_MS = 3_000;
22
+
23
+ const MAX_FRAME_BYTES = 64 * 1024 * 1024;
24
+
25
+ const SOCK_LINE_MAX = 8 * 1024 * 1024;
26
+
27
+ const LOG_MAX_BYTES = 2_000_000;
28
+
29
+ const LOG_CHECK_EVERY_BYTES = 64 * 1024;
30
+ let logSinceCheck = Infinity;
31
+
32
+ function log(...parts) {
33
+ try {
34
+ logSinceCheck += parts.join(" ").length + 32;
35
+ if (logSinceCheck >= LOG_CHECK_EVERY_BYTES) {
36
+ logSinceCheck = 0;
37
+ try {
38
+ if (fs.statSync(LOG).size >= LOG_MAX_BYTES) fs.renameSync(LOG, `${LOG}.1`);
39
+ } catch {}
40
+ }
41
+ fs.appendFileSync(LOG, `[${new Date().toISOString()}] ${parts.join(" ")}\n`, { mode: 0o600 });
42
+ } catch {}
43
+ }
44
+
45
+ function toChrome(obj) {
46
+ const body = Buffer.from(JSON.stringify(obj), "utf8");
47
+ const head = Buffer.allocUnsafe(4);
48
+ head.writeUInt32LE(body.length, 0);
49
+ process.stdout.write(Buffer.concat([head, body]));
50
+ }
51
+
52
+ let stdinChunks = [];
53
+ let stdinBuffered = 0;
54
+
55
+ /* 把队首合并到至少 n 字节(只动队首,后面的块一概不碰)。调用方保证 stdinBuffered >= n */
56
+ function coalesceHead(n) {
57
+ while (stdinChunks[0].length < n) stdinChunks.splice(0, 2, Buffer.concat([stdinChunks[0], stdinChunks[1]]));
58
+ }
59
+
60
+ function takeHead(n) {
61
+ const out = Buffer.allocUnsafe(n);
62
+ let off = 0;
63
+ while (off < n) {
64
+ const c = stdinChunks[0];
65
+ const want = n - off;
66
+ if (c.length <= want) {
67
+ c.copy(out, off);
68
+ off += c.length;
69
+ stdinChunks.shift();
70
+ } else {
71
+ c.copy(out, off, 0, want);
72
+ stdinChunks[0] = c.subarray(want);
73
+ off += want;
74
+ }
75
+ }
76
+ stdinBuffered -= n;
77
+ return out;
78
+ }
79
+
80
+ process.stdin.on("data", (chunk) => {
81
+ stdinChunks.push(chunk);
82
+ stdinBuffered += chunk.length;
83
+ for (;;) {
84
+ if (stdinBuffered < 4) return;
85
+ coalesceHead(4);
86
+ const len = stdinChunks[0].readUInt32LE(0);
87
+ if (len > MAX_FRAME_BYTES) {
88
+ log(`扩展发来的帧长度不合理(${len} 字节 > 上限 ${MAX_FRAME_BYTES}),流已错位,退出让 Chrome 重新拉起`);
89
+ process.exit(1);
90
+ }
91
+ if (stdinBuffered < 4 + len) return;
92
+ takeHead(4);
93
+ const body = takeHead(len);
94
+ let msg;
95
+ try {
96
+ msg = JSON.parse(body.toString("utf8"));
97
+ } catch (e) {
98
+ log("扩展发来的帧解析失败:", e.message);
99
+ continue;
100
+ }
101
+ onFromExtension(msg);
102
+ }
103
+ });
104
+ process.stdin.on("end", () => {
105
+ log("扩展断开(SW 可能被回收),退出");
106
+ process.exit(0);
107
+ });
108
+ process.stdin.on("error", (e) => {
109
+ log("stdin 错误:", e.message);
110
+ process.exit(0);
111
+ });
112
+
113
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
114
+ const { getToken, bridgeEndpoint, dataDirFor, handshakeNonce, handshakeProof, timingSafeEqualStr } = await import(
115
+ fs.existsSync(path.join(HERE, "token.mjs")) ? "./token.mjs" : "../mcp/token.mjs"
116
+ );
117
+ const ENDPOINT = bridgeEndpoint(SOCK);
118
+ const ENDPOINT_IS_PIPE = ENDPOINT !== SOCK || process.platform === "win32";
119
+ const LEGACY_TOKEN_HELLO_OK = !ENDPOINT_IS_PIPE;
120
+ const LEGACY_HELLO_WAIT_MS = 800;
121
+ /* 握手整体的死线:超了就断开重连,令牌一个字节都不发 */
122
+ const HANDSHAKE_TIMEOUT_MS = 10_000;
123
+ const cfgMod = await import(fs.existsSync(path.join(HERE, "config.mjs")) ? "./config.mjs" : "../mcp/config.mjs");
124
+
125
+ let tokenCache = null;
126
+ function authToken() {
127
+ if (tokenCache === null) {
128
+ try {
129
+ tokenCache = getToken(dataDirFor(SOCK));
130
+ } catch (e) {
131
+ log("读不到桥接令牌:", e.message);
132
+ tokenCache = "";
133
+ }
134
+ }
135
+ return tokenCache;
136
+ }
137
+
138
+ let sock = null;
139
+ let sockBuf = "";
140
+ let reconnectTimer = null;
141
+ let lastExtHello = null;
142
+ let authWarned = false;
143
+
144
+ let agentLinkUp = null;
145
+ function notifyAgentLink(up) {
146
+ if (agentLinkUp === up) return;
147
+ agentLinkUp = up;
148
+ toChrome({ type: "agent-link", up });
149
+ }
150
+
151
+ function toAgent(obj) {
152
+ if (!sock || sock.destroyed) return false;
153
+ try {
154
+ sock.write(JSON.stringify(obj) + "\n");
155
+ return true;
156
+ } catch (e) {
157
+ log("写 socket 失败:", e.message);
158
+ return false;
159
+ }
160
+ }
161
+
162
+ let lastDropWhy = null;
163
+ let dropRepeats = 0;
164
+ function flushDropRepeats() {
165
+ if (dropRepeats > 0) log(`(上一条「${lastDropWhy}」又重复了 ${dropRepeats} 次)`);
166
+ dropRepeats = 0;
167
+ }
168
+ function noteDrop(why) {
169
+ if (why === lastDropWhy) {
170
+ dropRepeats++;
171
+ return;
172
+ }
173
+ flushDropRepeats();
174
+ lastDropWhy = why;
175
+ log("与 agent 断开:", why);
176
+ }
177
+
178
+ function connectSocket() {
179
+ if (sock && !sock.destroyed) return;
180
+ if (ENDPOINT === SOCK && !fs.existsSync(SOCK)) {
181
+ scheduleReconnect();
182
+ return;
183
+ }
184
+ const s = net.connect(ENDPOINT);
185
+ s.setEncoding("utf8");
186
+
187
+ const cnonce = handshakeNonce();
188
+ let greeted = false;
189
+ let provedWith = null;
190
+ let verified = false;
191
+
192
+ const greet = (snonce) => {
193
+ if (greeted || s.destroyed) return;
194
+ greeted = true;
195
+ provedWith = snonce || null;
196
+ const frame = { type: "hello", role: "host", pid: process.pid };
197
+ if (snonce) {
198
+ frame.nonce = cnonce;
199
+ frame.proof = handshakeProof(authToken(), "client", snonce, cnonce);
200
+ } else {
201
+ frame.token = authToken();
202
+ }
203
+ if (sock !== s) return;
204
+ if (!toAgent(frame)) return;
205
+ if (lastExtHello) toAgent(lastExtHello);
206
+ };
207
+ let dropWarned = false;
208
+
209
+ const shook = () => greeted && (verified || LEGACY_TOKEN_HELLO_OK);
210
+ const hsTimer = setTimeout(() => {
211
+ if (shook()) return;
212
+ drop(
213
+ ENDPOINT_IS_PIPE
214
+ ? "握手超时:对面没出题、也没证明它握着同一份令牌(令牌没有发出去)"
215
+ : "握手超时"
216
+ );
217
+ }, HANDSHAKE_TIMEOUT_MS);
218
+ hsTimer.unref?.();
219
+
220
+ s.on("connect", () => {
221
+ sock = s;
222
+ sockBuf = "";
223
+ flushDropRepeats();
224
+ lastDropWhy = null;
225
+ reconnectDelay = RECONNECT_MS;
226
+ log("已连上 agent:", SOCK);
227
+ notifyAgentLink(true);
228
+ if (LEGACY_TOKEN_HELLO_OK) {
229
+ const t = setTimeout(() => greet(null), LEGACY_HELLO_WAIT_MS);
230
+ t.unref?.();
231
+ }
232
+ toChrome({ type: "ping" });
233
+ });
234
+
235
+ s.on("data", (chunk) => {
236
+ sockBuf += chunk;
237
+ let idx;
238
+ while ((idx = sockBuf.indexOf("\n")) >= 0) {
239
+ const line = sockBuf.slice(0, idx).trim();
240
+ sockBuf = sockBuf.slice(idx + 1);
241
+ if (!line) continue;
242
+ let msg;
243
+ try {
244
+ msg = JSON.parse(line);
245
+ } catch (e) {
246
+ log("agent 发来的行解析失败:", e.message);
247
+ continue;
248
+ }
249
+ if (!msg || typeof msg !== "object") continue;
250
+ // ---- 握手:这两帧只属于 host 与主之间,绝不往扩展转发
251
+ if (msg.type === "challenge") {
252
+ if (typeof msg.nonce === "string" && msg.nonce) greet(msg.nonce);
253
+ continue;
254
+ }
255
+ if (msg.type === "welcome") {
256
+ if (!provedWith) continue;
257
+ verified =
258
+ typeof msg.proof === "string" &&
259
+ timingSafeEqualStr(msg.proof, handshakeProof(authToken(), "server", provedWith, cnonce));
260
+ if (!verified) {
261
+ impostor = true;
262
+ drop("对面拿不出反向证明:占着这个端点的不是主(令牌没有发出去)");
263
+ }
264
+ continue;
265
+ }
266
+ if (msg.type === "error" && msg.code === "unauthorized") {
267
+ if (!authWarned) {
268
+ authWarned = true;
269
+ log("agent 拒绝了我们的令牌:", msg.message || "unauthorized");
270
+ }
271
+ continue;
272
+ }
273
+ if (ENDPOINT_IS_PIPE && !verified) {
274
+ if (!dropWarned) {
275
+ dropWarned = true;
276
+ log("丢弃未验明正身的对端发来的帧(之后同类不再记):", msg.type || "无 type");
277
+ }
278
+ continue;
279
+ }
280
+ toChrome(msg);
281
+ }
282
+ if (sockBuf.length > SOCK_LINE_MAX) {
283
+ sockBuf = "";
284
+ drop(`agent 侧单行超过 ${SOCK_LINE_MAX} 字节还没有换行,丢弃并重连`);
285
+ }
286
+ });
287
+
288
+ let dropped = false;
289
+ let impostor = false;
290
+ const drop = (why) => {
291
+ if (dropped) return;
292
+ dropped = true;
293
+ clearTimeout(hsTimer);
294
+ if (sock === s) sock = null;
295
+ s.destroy();
296
+ noteDrop(why);
297
+ notifyAgentLink(false);
298
+ if (impostor) {
299
+ log(
300
+ `桥接端点被一个拿不出令牌的进程占着,退出让 Chrome 重新拉起(令牌没有发出去)。` +
301
+ `请检查是否有别的进程抢先建了这个管道名,或对面是旧版本;确认干净后重启浏览器扩展或所有会话。`
302
+ );
303
+ process.exit(1);
304
+ }
305
+ scheduleReconnect();
306
+ };
307
+ s.on("error", (e) => drop(e.message));
308
+ s.on("close", () => drop("closed"));
309
+ }
310
+
311
+ let reconnectDelay = RECONNECT_MS;
312
+ function scheduleReconnect() {
313
+ if (reconnectTimer) return;
314
+ reconnectTimer = setTimeout(() => {
315
+ reconnectTimer = null;
316
+ connectSocket();
317
+ }, reconnectDelay);
318
+ reconnectDelay = Math.min(reconnectDelay * 2, RECONNECT_MAX_MS);
319
+ }
320
+
321
+ function onFromExtension(msg) {
322
+ if (msg.type === "pong") return;
323
+ if (msg.type === "hello" && msg.role === "extension") lastExtHello = msg;
324
+ if (msg.type === "config-get") {
325
+ const r = cfgMod.loadSync();
326
+ toChrome({ type: "config-result", id: msg.id, ok: r.value !== null, value: r.value, source: r.source, problems: r.problems });
327
+ return;
328
+ }
329
+ if (msg.type === "config-set") {
330
+ try {
331
+ const patch = msg.patch && typeof msg.patch === "object" ? msg.patch : {};
332
+ const probe = cfgMod.normalize({ tools: patch.tools || {} });
333
+ if (probe.value === null || probe.problems.length) {
334
+ toChrome({ type: "config-result", id: msg.id, ok: false, error: `无效设置:${probe.problems.join(";")}` });
335
+ return;
336
+ }
337
+ const cur = cfgMod.loadSync();
338
+ const base = cur.value ?? cfgMod.defaults();
339
+ if (patch.tools && typeof patch.tools === "object") base.tools = { ...base.tools, ...patch.tools };
340
+ const clean = cfgMod.saveSync(base);
341
+ toChrome({ type: "config-result", id: msg.id, ok: true, value: clean, rebuilt: cur.source === "error" });
342
+ } catch (e) {
343
+ toChrome({ type: "config-result", id: msg.id, ok: false, error: String(e?.message || e) });
344
+ }
345
+ return;
346
+ }
347
+ if (!toAgent(msg)) {
348
+ log("丢弃(agent 未连接):", msg.type, msg.id || "");
349
+ }
350
+ }
351
+
352
+ // 入站消息会重置 SW 的 30s 空闲计时器 —— 这是让连接活下去的关键
353
+ setInterval(() => toChrome({ type: "ping" }), PING_MS).unref?.();
354
+
355
+ log(`host 启动 pid=${process.pid} sock=${SOCK}`);
356
+ connectSocket();
@@ -0,0 +1,114 @@
1
+ // aic-fg —— 「本机侧因果归还前台」的观测/执行 helper(只在 macOS 上存在)。
2
+ // ## 协议(stdin 每行一条命令,stdout 每行一条 JSON 事件)
3
+ // arm <ttlMs> 武装;ttl 到期自动解除
4
+ // confirm 结果因到达
5
+ // disarm 主动解除
6
+ // ping → {"t":"pong"}
7
+ // stdin 到 EOF(父进程退出)就自杀,不留孤儿。
8
+
9
+ import AppKit
10
+ import Foundation
11
+
12
+ setvbuf(stdout, nil, _IOLBF, 0)
13
+
14
+ let CONFIRM_WINDOW_MS = 600.0
15
+
16
+ func nowMs() -> Double { Date().timeIntervalSince1970 * 1000 }
17
+ func esc(_ s: String) -> String {
18
+ s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"")
19
+ }
20
+ func emit(_ fields: [(String, String)]) {
21
+ let body = fields.map { "\"\($0.0)\":\($0.1)" }.joined(separator: ",")
22
+ print("{\(body)}")
23
+ }
24
+ func str(_ s: String?) -> String { s == nil ? "null" : "\"\(esc(s!))\"" }
25
+ func num(_ d: Double) -> String { String(Int(d.rounded())) }
26
+
27
+ final class Guard: NSObject {
28
+ var front: NSRunningApplication? = NSWorkspace.shared.frontmostApplication
29
+ var armBase: NSRunningApplication?
30
+ var armUntil: Double = 0
31
+ var stealer: NSRunningApplication?
32
+ var stealAt: Double = 0
33
+
34
+ @objc func onActivate(_ n: Notification) {
35
+ let app = n.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication
36
+ front = app
37
+ let t = nowMs()
38
+ guard t <= armUntil, let base = armBase, let app else { return }
39
+ if app.processIdentifier == base.processIdentifier {
40
+ stealer = nil
41
+ stealAt = 0
42
+ return
43
+ }
44
+ stealer = app
45
+ stealAt = t
46
+ emit([("t", "\"steal\""), ("ms", num(t)), ("to", str(app.bundleIdentifier ?? app.localizedName))])
47
+ }
48
+
49
+ func arm(_ ttlMs: Double) {
50
+ let t = nowMs()
51
+ armUntil = t + ttlMs
52
+ armBase = front
53
+ stealer = nil
54
+ stealAt = 0
55
+ emit([("t", "\"armed\""), ("ms", num(t)), ("base", str(armBase?.bundleIdentifier ?? armBase?.localizedName)), ("until", num(armUntil))])
56
+ }
57
+
58
+ func disarm() {
59
+ armUntil = 0
60
+ armBase = nil
61
+ stealer = nil
62
+ stealAt = 0
63
+ emit([("t", "\"disarmed\""), ("ms", num(nowMs()))])
64
+ }
65
+
66
+ func confirm() {
67
+ let t = nowMs()
68
+ func skip(_ why: String) { emit([("t", "\"skip\""), ("ms", num(t)), ("why", "\"\(why)\"")]) }
69
+ if t > armUntil { return skip("not-armed") }
70
+ guard let base = armBase else { return skip("no-base") }
71
+ if stealAt == 0 { return skip("no-steal") }
72
+ if t - stealAt > CONFIRM_WINDOW_MS { return skip("late") }
73
+ if base.isTerminated { return skip("base-gone") }
74
+ if let f = front, let s = stealer, f.processIdentifier != s.processIdentifier { return skip("moved") }
75
+ let ok = base.activate(options: [])
76
+ emit([
77
+ ("t", "\"restore\""), ("ms", num(t)), ("to", str(base.bundleIdentifier ?? base.localizedName)),
78
+ ("ok", ok ? "true" : "false"), ("stealMs", num(stealAt)), ("exposureMs", num(t - stealAt)),
79
+ ])
80
+ stealAt = 0
81
+ stealer = nil
82
+ }
83
+ }
84
+
85
+ let g = Guard()
86
+ NSWorkspace.shared.notificationCenter.addObserver(
87
+ g, selector: #selector(Guard.onActivate(_:)),
88
+ name: NSWorkspace.didActivateApplicationNotification, object: nil)
89
+
90
+ var inbuf = ""
91
+ FileHandle.standardInput.readabilityHandler = { fh in
92
+ let d = fh.availableData
93
+ if d.isEmpty { exit(0) }
94
+ inbuf += String(decoding: d, as: UTF8.self)
95
+ while let i = inbuf.firstIndex(of: "\n") {
96
+ let line = String(inbuf[inbuf.startIndex..<i]).trimmingCharacters(in: .whitespaces)
97
+ inbuf = String(inbuf[inbuf.index(after: i)...])
98
+ let parts = line.split(separator: " ").map(String.init)
99
+ guard let cmd = parts.first else { continue }
100
+ DispatchQueue.main.async {
101
+ switch cmd {
102
+ case "arm": g.arm(parts.count > 1 ? (Double(parts[1]) ?? 5000) : 5000)
103
+ case "confirm": g.confirm()
104
+ case "disarm": g.disarm()
105
+ case "ping": emit([("t", "\"pong\""), ("ms", num(nowMs()))])
106
+ case "quit": exit(0)
107
+ default: break
108
+ }
109
+ }
110
+ }
111
+ }
112
+
113
+ emit([("t", "\"ready\""), ("ms", num(nowMs())), ("front", str(g.front?.bundleIdentifier ?? g.front?.localizedName)), ("pid", String(ProcessInfo.processInfo.processIdentifier))])
114
+ RunLoop.main.run()