@liang-hz/agent-in-chrome 0.55.2 → 0.56.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.
@@ -51,6 +51,7 @@ const RUNTIME_DIR = path.join(DATA_DIR, "agent-in-chrome");
51
51
  const HOST_SRC = path.join(ROOT, "native-host", "host.mjs");
52
52
  const FG_SWIFT_SRC = path.join(ROOT, "native-host", "mac-foreground", "aic-fg.swift");
53
53
  const SERVER_SRC = path.join(ROOT, "mcp", "server.mjs");
54
+ const BIN_SRC = path.join(ROOT, "bin", "agent-in-chrome.mjs");
54
55
  const HOST_PATH = path.join(RUNTIME_DIR, "host.mjs");
55
56
  const SERVER_PATH = path.join(RUNTIME_DIR, "server.mjs");
56
57
  const MCP_DIR = path.join(ROOT, "mcp");
@@ -75,7 +76,7 @@ function scanDeps(entryAbs, out = new Set()) {
75
76
  }
76
77
  return out;
77
78
  }
78
- const SERVER_DEPS = [...scanDeps(SERVER_SRC, scanDeps(HOST_SRC))].sort();
79
+ const SERVER_DEPS = [...scanDeps(SERVER_SRC, scanDeps(HOST_SRC, scanDeps(BIN_SRC)))].sort();
79
80
  const EXT_FILES = ["sw.js", "manifest.json"];
80
81
  const EXT_STABLE_DIR = path.join(DATA_DIR, "extension");
81
82
  const IS_GIT_CHECKOUT = fs.existsSync(path.join(ROOT, ".git"));
@@ -83,6 +84,9 @@ const REINSTALL_CMD = IS_GIT_CHECKOUT ? "node scripts/install.mjs" : `npx ${PKG_
83
84
  const WIN = process.platform === "win32";
84
85
  const LAUNCHER = path.join(RUNTIME_DIR, WIN ? "native-host-launcher.bat" : "native-host-launcher.sh");
85
86
  const MCP_LAUNCHER = path.join(RUNTIME_DIR, WIN ? "mcp-launcher.bat" : "mcp-launcher.sh");
87
+ const LOCAL_BIN_DIR = path.join(HOME, ".local", "bin");
88
+ const MANAGED_CLI_PATH = path.join(LOCAL_BIN_DIR, "agent-in-chrome");
89
+ const MANAGED_CLI_MARKER = "# agent-in-chrome-managed-cli";
86
90
  const WIN_HOST_MANIFEST = path.join(RUNTIME_DIR, `${HOST_NAME}.json`);
87
91
 
88
92
  const RUNTIME_KEEP_DIRS = new Set(["cli-profile"]);
@@ -286,6 +290,13 @@ function checkStrayBrowsers() {
286
290
  * 映射都指向被替换掉的那个 inode,不会读到半截新文件;
287
291
  * 也从不「原地截断重写」一个可能正被读取或执行的文件。
288
292
  * 同目录是硬要求:跨设备的 rename 会 EXDEV,而 os.tmpdir() 在很多机器上是另一个卷。
293
+ *
294
+ * Windows 上 rename 盖不到一个正被别的进程打开着的目标(NTFS 没有「替换已打开
295
+ * 文件」的 POSIX 语义,rename 报 EPERM)。这时走「让位舞步」:旧文件先改名让位——
296
+ * 它自己的打开句柄跟着旧名字走,内容一个字节不动;新文件立刻顶上原名;旧名字
297
+ * 尽力而为地删(被握着时是 delete-pending,握着它的进程一退出系统才真删)。
298
+ * 代价是两次 rename 之间有几微秒的 ENOENT 窗口,只在「目标正被握着」这一种
299
+ * 情形付出;常规升级(没人握着)仍然走上面的单次 rename,一个窗口都没有。
289
300
  */
290
301
  function replaceAtomically(from, to, mode = 0o644) {
291
302
  fs.mkdirSync(path.dirname(to), { recursive: true });
@@ -294,12 +305,38 @@ function replaceAtomically(from, to, mode = 0o644) {
294
305
  if (!WIN) fs.chmodSync(tmp, mode);
295
306
  try {
296
307
  fs.renameSync(tmp, to);
308
+ return;
297
309
  } catch (e) {
310
+ if (!WIN || !["EPERM", "EACCES", "EBUSY"].includes(e.code)) {
311
+ try {
312
+ fs.unlinkSync(tmp);
313
+ } catch {}
314
+ throw e;
315
+ }
316
+ }
317
+ const stale = `${to}.stale-${process.pid}`;
318
+ try {
319
+ fs.renameSync(to, stale);
320
+ } catch (e2) {
321
+ try {
322
+ fs.unlinkSync(tmp);
323
+ } catch {}
324
+ throw e2;
325
+ }
326
+ try {
327
+ fs.renameSync(tmp, to);
328
+ } catch (e3) {
329
+ try {
330
+ fs.renameSync(stale, to);
331
+ } catch {}
298
332
  try {
299
333
  fs.unlinkSync(tmp);
300
334
  } catch {}
301
- throw e;
335
+ throw e3;
302
336
  }
337
+ try {
338
+ fs.unlinkSync(stale);
339
+ } catch {}
303
340
  }
304
341
 
305
342
  function runtimeManifest() {
@@ -317,6 +354,7 @@ function sweepRuntime(keep) {
317
354
  const owned = (rel, name) =>
318
355
  name.endsWith(".mjs") ||
319
356
  /\.incoming-\d+$/.test(name) ||
357
+ /\.stale-\d+$/.test(name) ||
320
358
  rel.split(path.sep)[0] === "extension";
321
359
  const walk = (dir, rel) => {
322
360
  let ents;
@@ -357,6 +395,27 @@ function syncRuntime() {
357
395
  return sweepRuntime(new Set(manifest.map(([rel]) => rel)));
358
396
  }
359
397
 
398
+ export function runtimeDrift(manifest = runtimeManifest(), runtimeDir = RUNTIME_DIR) {
399
+ const out = [];
400
+ for (const [rel, src] of manifest) {
401
+ let srcBuf;
402
+ try {
403
+ srcBuf = fs.readFileSync(src);
404
+ } catch {
405
+ continue;
406
+ }
407
+ let dstBuf;
408
+ try {
409
+ dstBuf = fs.readFileSync(path.join(runtimeDir, rel));
410
+ } catch {
411
+ out.push({ rel, why: "missing" });
412
+ continue;
413
+ }
414
+ if (!srcBuf.equals(dstBuf)) out.push({ rel, why: "differ" });
415
+ }
416
+ return out;
417
+ }
418
+
360
419
  // Chrome 和 agent 桌面端都是 GUI 应用,PATH 里没有 nvm / homebrew 的 node——
361
420
  // `#!/usr/bin/env node` 在它们手里必然 ENOENT。所以到处都必须写绝对路径。
362
421
  // 用跑安装脚本的这个 node(process.execPath 是绝对路径),不依赖调用方的 PATH。
@@ -825,6 +884,59 @@ function doCrx() {
825
884
  ok(`清单: ${CRX_JSON} (v${extVersion()})`);
826
885
  }
827
886
 
887
+ function doManagedCli() {
888
+ if (WIN) return;
889
+ if (MODE === "uninstall") {
890
+ try {
891
+ const st = fs.lstatSync(MANAGED_CLI_PATH);
892
+ if (st.isFile() && fs.readFileSync(MANAGED_CLI_PATH, "utf8").includes(MANAGED_CLI_MARKER)) {
893
+ fs.unlinkSync(MANAGED_CLI_PATH);
894
+ ok(`已移除 CLI 入口 ${MANAGED_CLI_PATH}`);
895
+ }
896
+ } catch {}
897
+ return;
898
+ }
899
+ if (!IS_GIT_CHECKOUT) return;
900
+ if (MODE === "check") {
901
+ try {
902
+ const st = fs.lstatSync(MANAGED_CLI_PATH);
903
+ if (st.isFile() && fs.readFileSync(MANAGED_CLI_PATH, "utf8").includes(MANAGED_CLI_MARKER)) {
904
+ if (!(st.mode & 0o111)) bad(`CLI 入口没有可执行位: ${MANAGED_CLI_PATH}`);
905
+ else ok(`CLI 入口: ${MANAGED_CLI_PATH}`);
906
+ }
907
+ } catch {}
908
+ return;
909
+ }
910
+ if (!fs.existsSync(LOCAL_BIN_DIR)) return;
911
+ let existing = null;
912
+ try {
913
+ existing = fs.lstatSync(MANAGED_CLI_PATH);
914
+ } catch {}
915
+ if (existing) {
916
+ if (!existing.isFile()) {
917
+ skip(`CLI 入口 ${MANAGED_CLI_PATH} 已存在(非本安装器托管,跳过)`);
918
+ return;
919
+ }
920
+ try {
921
+ if (!fs.readFileSync(MANAGED_CLI_PATH, "utf8").includes(MANAGED_CLI_MARKER)) {
922
+ skip(`CLI 入口 ${MANAGED_CLI_PATH} 已存在(非本安装器托管,跳过)`);
923
+ return;
924
+ }
925
+ } catch {
926
+ skip(`CLI 入口 ${MANAGED_CLI_PATH} 不可读,跳过`);
927
+ return;
928
+ }
929
+ }
930
+ const binEntry = path.join(ROOT, "bin", "agent-in-chrome.mjs");
931
+ const body = `#!/bin/sh
932
+ ${MANAGED_CLI_MARKER}
933
+ exec ${shq(RUNTIME.command)} ${shq(binEntry)} "$@"
934
+ `;
935
+ fs.writeFileSync(MANAGED_CLI_PATH, body);
936
+ fs.chmodSync(MANAGED_CLI_PATH, 0o755);
937
+ ok(`CLI 入口: ${MANAGED_CLI_PATH}`);
938
+ }
939
+
828
940
  function doMcp() {
829
941
  if (MODE === "install") {
830
942
  writeLauncher(
@@ -833,13 +945,25 @@ function doMcp() {
833
945
  "agent 桌面端不一定把 env 传给 MCP 进程;node 路径和环境都固化在这个 wrapper 里,跟调用方无关。"
834
946
  );
835
947
  ok(`启动器: ${MCP_LAUNCHER}`);
948
+ doManagedCli();
836
949
  } else if (MODE === "check") {
837
950
  if (!fs.existsSync(MCP_LAUNCHER)) bad("MCP 启动器不存在,请重新安装");
838
951
  else if (!WIN && !(fs.statSync(MCP_LAUNCHER).mode & 0o111)) bad("MCP 启动器没有可执行位");
839
952
  else ok(`启动器: ${MCP_LAUNCHER}`);
953
+ doManagedCli();
840
954
  const missing = SERVER_DEPS.filter((d) => !fs.existsSync(path.join(RUNTIME_DIR, d)));
841
- if (missing.length) bad(`运行时缺少 server.mjs 依赖的模块:${missing.join(", ")},跑 ${REINSTALL_CMD} 重装`);
842
- else ok(`server 依赖模块齐全(${SERVER_DEPS.join(", ")})`);
955
+ if (missing.length) {
956
+ bad(`运行时缺少 server.mjs 依赖的模块:${missing.join(", ")},跑 ${REINSTALL_CMD} 重装`);
957
+ } else {
958
+ ok(`server 依赖模块齐全(${SERVER_DEPS.join(", ")})`);
959
+ const drift = runtimeDrift(runtimeManifest().filter(([rel]) => !String(rel).startsWith("extension")));
960
+ if (drift.length)
961
+ bad(
962
+ `运行时与源码不一致:${drift
963
+ .map((d) => `${d.rel}(${d.why === "missing" ? "缺" : "内容不同"})`)
964
+ .join("、")},跑 ${REINSTALL_CMD} 同步`
965
+ );
966
+ }
843
967
  smokeTestRuntime();
844
968
  checkStrayBrowsers();
845
969
  const extMissing = EXT_FILES.filter((f) => !fs.existsSync(path.join(RUNTIME_DIR, "extension", f)));
@@ -1001,6 +1125,8 @@ function doLeftovers() {
1001
1125
  step(`删除日志 ${path.basename(f)}`, () => (fs.unlinkSync(f), ok(`日志已删除 ${f}`)));
1002
1126
  }
1003
1127
 
1128
+ doManagedCli();
1129
+
1004
1130
  const cookies = countFiles(COOKIE_DIR);
1005
1131
  if (cookies && insideDataDir(COOKIE_DIR))
1006
1132
  removeAndReport(`导出的 cookie(${cookies} 个文件,完整会话凭据的明文,不能留在盘上)`, COOKIE_DIR);
@@ -0,0 +1,22 @@
1
+ import { spawn } from "node:child_process";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+
5
+ export const defaultMcpLauncher = () =>
6
+ path.join(
7
+ os.homedir(),
8
+ ".agent-in-chrome",
9
+ "agent-in-chrome",
10
+ process.platform === "win32" ? "mcp-launcher.bat" : "mcp-launcher.sh",
11
+ );
12
+
13
+ export const launcherNeedsShell = (file) => process.platform === "win32" && /\.(cmd|bat)$/i.test(String(file));
14
+
15
+ export const cmdq = (s) => (/[\s&|<>^"()]/.test(String(s)) ? `"${String(s).replace(/"/g, `""`)}"` : String(s));
16
+
17
+ export function spawnMcpLauncher(file, opts = {}) {
18
+ if (launcherNeedsShell(file)) {
19
+ return spawn(cmdq(file), { ...opts, shell: true, windowsHide: true });
20
+ }
21
+ return spawn(file, [], opts);
22
+ }
@@ -12,6 +12,7 @@ import path from "node:path";
12
12
  import crypto from "node:crypto";
13
13
  import { execFileSync } from "node:child_process";
14
14
  import { fileURLToPath } from "node:url";
15
+ import { zipDir } from "./release/zip.mjs";
15
16
 
16
17
  const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
17
18
  const EXT_DIR = path.join(ROOT, "extension");
@@ -42,7 +43,7 @@ const version = JSON.parse(fs.readFileSync(path.join(EXT_DIR, "manifest.json"),
42
43
 
43
44
  const zipPath = path.join(OUT_DIR, "extension.zip");
44
45
  fs.rmSync(zipPath, { force: true });
45
- execFileSync("/usr/bin/zip", ["-r", "-X", "-q", zipPath, "."], { cwd: EXT_DIR });
46
+ zipDir(zipPath, { cwd: EXT_DIR });
46
47
  const zip = fs.readFileSync(zipPath);
47
48
 
48
49
  const pubDer = crypto.createPublicKey(fs.readFileSync(KEY)).export({ type: "spki", format: "der" });
@@ -12,6 +12,17 @@ import * as install from "./install.mjs";
12
12
  import { pickMulti } from "./pick.mjs";
13
13
 
14
14
  const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
15
+
16
+ const TEST_REG_ROOT = `HKCU\\Software\\aic-reg-test-${process.pid}`;
17
+ if (process.platform === "win32") {
18
+ if (process.env.AGENT_IN_CHROME_REG_ROOT) throw new Error("AGENT_IN_CHROME_REG_ROOT 已被外部设置,测试的隔离前提不成立");
19
+ process.env.AGENT_IN_CHROME_REG_ROOT = TEST_REG_ROOT;
20
+ process.on("exit", () => {
21
+ try {
22
+ execFileSync("reg", ["delete", TEST_REG_ROOT, "/f"], { stdio: "pipe" });
23
+ } catch {}
24
+ });
25
+ }
15
26
  const SERVER_PATH = path.join(ROOT, "mcp", "server.mjs");
16
27
 
17
28
  {
@@ -570,7 +581,7 @@ console.log("\n\x1b[1m--check 的 socket 权限体检:按 defaultSockName 的
570
581
  );
571
582
  check("三条 sock 都枚举到了", found.length === 3, JSON.stringify(found));
572
583
  check("同目录的非 sock 文件不进来", !found.some((n) => n === "token" || n.endsWith(".log")), JSON.stringify(found));
573
- check("桌面那条的标签仍然是「桌面」", listSocks(dir).find(([, p]) => p.endsWith("/agent-in-chrome.sock"))?.[0] === "桌面");
584
+ check("桌面那条的标签仍然是「桌面」", listSocks(dir).find(([, p]) => path.basename(p) === "agent-in-chrome.sock")?.[0] === "桌面");
574
585
  check("目录不存在时返回空数组,不抛", JSON.stringify(listSocks(path.join(dir, "没有这个目录"))) === "[]");
575
586
  fs.rmSync(dir, { recursive: true, force: true });
576
587
  }
@@ -752,9 +763,10 @@ process.stdin.on("data", () => {
752
763
  check("旧 inode 的内容一个字没被动过(不是原地截断重写)", held.held === SENTINEL, JSON.stringify(held.held.slice(0, 80)));
753
764
  check("新文件是另一个 inode", newIno !== oldIno, `${newIno} vs ${oldIno}`);
754
765
  check("新文件的内容就是仓库里的源码", fs.readFileSync(serverRt, "utf8") === srcText);
766
+ const enoentOk = held.enoent === 0 || (process.platform === "win32" && held.enoent <= 4);
755
767
  check(
756
768
  `替换过程没有缺失窗口(${held.samples} 次 stat 全部命中)`,
757
- held.enoent === 0 && held.samples > 20,
769
+ enoentOk && held.samples > (process.platform === "win32" ? 5 : 20),
758
770
  `ENOENT ${held.enoent} 次 / 共 ${held.samples} 次`
759
771
  );
760
772
  check(
@@ -762,7 +774,11 @@ process.stdin.on("data", () => {
762
774
  held.inos.includes(oldIno) && held.inos.includes(newIno),
763
775
  `采到 ${JSON.stringify(held.inos)},旧 ${oldIno} 新 ${newIno}`
764
776
  );
765
- check("替换用的临时文件没留下", fs.readdirSync(RT).filter((f) => f.includes(".incoming-")).length === 0, fs.readdirSync(RT).join(","));
777
+ check(
778
+ "替换用的临时文件没留下",
779
+ fs.readdirSync(RT).filter((f) => f.includes(".incoming-") || f.includes(".stale-")).length === 0,
780
+ fs.readdirSync(RT).join(",")
781
+ );
766
782
 
767
783
  const stale = [
768
784
  ["zombie.mjs", path.join(RT, "zombie.mjs")],
@@ -874,31 +890,43 @@ console.log("\n\x1b[1mWindows 的 GUI 条目形状:cmd /c\x1b[0m");
874
890
 
875
891
  console.log("\n\x1b[1mclaude mcp add:子进程继承调用方的 HOME\x1b[0m");
876
892
  {
877
- const binDir = fs.mkdtempSync(path.join(os.tmpdir(), "aic-fakeclaude-"));
878
- const fake = path.join(binDir, "claude");
879
- fs.writeFileSync(fake, `#!/bin/sh\nprintf '%s\\n' "$HOME" "$@" >> "$HOME/claude-cli.log"\n`);
880
- fs.chmodSync(fake, 0o755);
881
- const home = makeHome([]);
882
- const realPath = process.env.PATH;
883
- process.env.PATH = `${binDir}${path.delimiter}${realPath}`;
884
- try {
885
- await quiet(() => runAgents("install", { ...opts(home), agents: ["claude-code"] }));
886
- } finally {
887
- process.env.PATH = realPath;
893
+ if (process.platform === "win32") {
894
+ console.log(" · 裸二进制那条路 Windows 上走不到(shabang 脚本没法被 CreateProcess 执行),等价路径在下一块");
895
+ } else {
896
+ const binDir = fs.mkdtempSync(path.join(os.tmpdir(), "aic-fakeclaude-"));
897
+ const fake = path.join(binDir, "claude");
898
+ fs.writeFileSync(fake, `#!/bin/sh\nprintf '%s\\n' "$HOME" "$@" >> "$HOME/claude-cli.log"\n`);
899
+ fs.chmodSync(fake, 0o755);
900
+ const home = makeHome([]);
901
+ const realPath = process.env.PATH;
902
+ process.env.PATH = `${binDir}${path.delimiter}${realPath}`;
903
+ try {
904
+ await quiet(() => runAgents("install", { ...opts(home), agents: ["claude-code"] }));
905
+ } finally {
906
+ process.env.PATH = realPath;
907
+ }
908
+ const log = readOr(path.join(home, "claude-cli.log")) || "";
909
+ check("claude 子进程看到的 HOME 是我们给的那个假 home", log.split("\n")[0] === home, JSON.stringify(log.slice(0, 200)));
910
+ check("真的把 mcp add 发出去了", log.includes("mcp") && log.includes("add") && log.includes(SERVER_PATH), JSON.stringify(log.slice(0, 300)));
911
+ check("真实 HOME 下没有被写出日志(没走穿)", !fs.existsSync(path.join(REAL_HOME, "claude-cli.log")));
912
+ fs.rmSync(binDir, { recursive: true, force: true });
888
913
  }
889
- const log = readOr(path.join(home, "claude-cli.log")) || "";
890
- check("claude 子进程看到的 HOME 是我们给的那个假 home", log.split("\n")[0] === home, JSON.stringify(log.slice(0, 200)));
891
- check("真的把 mcp add 发出去了", log.includes("mcp") && log.includes("add") && log.includes(SERVER_PATH), JSON.stringify(log.slice(0, 300)));
892
- check("真实 HOME 下没有被写出日志(没走穿)", !fs.existsSync(path.join(REAL_HOME, "claude-cli.log")));
893
- fs.rmSync(binDir, { recursive: true, force: true });
894
914
  }
895
915
 
896
916
  {
917
+ const onRealWin = process.platform === "win32";
897
918
  const binDir = fs.mkdtempSync(path.join(os.tmpdir(), "aic-fakecmd-"));
898
919
  const spaced = path.join(binDir, "bin dir (x86)");
899
920
  fs.mkdirSync(spaced, { recursive: true });
900
921
  const fake = path.join(spaced, "claude.cmd");
901
- fs.writeFileSync(fake, `#!/bin/sh\nprintf '%s\\n' "$HOME" "$@" >> "$HOME/claude-cli.log"\n`);
922
+ if (onRealWin) {
923
+ fs.writeFileSync(
924
+ fake,
925
+ `@echo off\r\n>>"%HOME%\\claude-cli.log" echo %HOME%\r\n>>"%HOME%\\claude-cli.log" echo %*\r\n`
926
+ );
927
+ } else {
928
+ fs.writeFileSync(fake, `#!/bin/sh\nprintf '%s\\n' "$HOME" "$@" >> "$HOME/claude-cli.log"\n`);
929
+ }
902
930
  fs.chmodSync(fake, 0o755);
903
931
  const home = makeHome([]);
904
932
  const srvDir = path.join(binDir, "srv dir");
@@ -916,10 +944,15 @@ console.log("\n\x1b[1mclaude mcp add:子进程继承调用方的 HOME\x1b[0m")
916
944
  } finally {
917
945
  process.env.PATH = realPath;
918
946
  }
919
- const lines = (readOr(path.join(home, "claude-cli.log")) || "").split("\n");
947
+ const lines = (readOr(path.join(home, "claude-cli.log")) || "").replace(/\r\n/g, "\n").split("\n").filter((l) => l !== "");
948
+ const withoutQuotes = lines.map((l) => l.replace(/"/g, ""));
920
949
  check("win32 的 .cmd shim 这条路真的跑起来了(不是退回直接编辑)", /claude mcp add 完成/.test(said), said.slice(-300));
921
950
  check(".cmd 子进程看到的也是我们给的 HOME", lines[0] === home, JSON.stringify(lines.slice(0, 3)));
922
- check("带空格和括号的路径原样到达(引号是自己加的)", lines.includes(serverPath), JSON.stringify(lines));
951
+ check(
952
+ "带空格和括号的路径原样到达(引号是自己加的)",
953
+ lines.includes(serverPath) || withoutQuotes.some((l) => l.includes(serverPath)),
954
+ JSON.stringify(lines)
955
+ );
923
956
  check("stderr 上没有 DEP0190 弃用警告(整条命令拼成字符串走的)", !/DEP0190/.test(said), said.slice(-200));
924
957
  fs.rmSync(binDir, { recursive: true, force: true });
925
958
  }
@@ -991,6 +1024,40 @@ console.log("\n\x1b[1mWorkBuddy AI:与国内版互不串写\x1b[0m");
991
1024
  check("卸载没碰国内版那条", cnAfter.mcpServers?.["agent-in-chrome"]?.command === launcher, JSON.stringify(cnAfter));
992
1025
  }
993
1026
 
1027
+ if (process.platform !== "win32") {
1028
+ console.log("\n\x1b[1mP1-5: ~/.local/bin/agent-in-chrome 包装器安装与卸载\x1b[0m");
1029
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-cli-wrap-"));
1030
+ SANDBOX_HOMES.push(home);
1031
+ fakeBrowserDir(home);
1032
+ const localBin = path.join(home, ".local", "bin");
1033
+ fs.mkdirSync(localBin, { recursive: true });
1034
+ const wrapPath = path.join(localBin, "agent-in-chrome");
1035
+
1036
+ const r1 = runInstaller(["--yes", "--no-agents"], home);
1037
+ check("P1-5: ~/.local/bin 存在时自动写入受管包装器", r1.status === 0 && fs.existsSync(wrapPath), r1.out.slice(-240));
1038
+ const content = fs.existsSync(wrapPath) ? fs.readFileSync(wrapPath, "utf8") : "";
1039
+ check("P1-5: 包装器含受管标记与可执行权限", content.includes("# agent-in-chrome-managed-cli") && ((fs.statSync(wrapPath).mode & 0o111) !== 0), content);
1040
+
1041
+ const chk = runInstaller(["--check"], home);
1042
+ check("P1-5: --check 检出受管 CLI 入口就绪", chk.out.includes(`CLI 入口: ${wrapPath}`), chk.out.slice(0, 400));
1043
+
1044
+ fs.chmodSync(wrapPath, 0o644);
1045
+ const chkNoExec = runInstaller(["--check"], home);
1046
+ check("P1-5: --check 检出缺少可执行位", chkNoExec.out.includes("CLI 入口没有可执行位"), chkNoExec.out.slice(0, 400));
1047
+ fs.chmodSync(wrapPath, 0o755);
1048
+
1049
+ const un = runInstaller(["--uninstall"], home);
1050
+ check("P1-5: --uninstall 只清带受管标记的包装器", un.status === 0 && !fs.existsSync(wrapPath), un.out.slice(-240));
1051
+
1052
+ fs.writeFileSync(wrapPath, "#!/bin/sh\necho custom\n");
1053
+ runInstaller(["--yes", "--no-agents"], home);
1054
+ check("P1-5: 已存在用户自定义文件时不覆盖", fs.readFileSync(wrapPath, "utf8").includes("echo custom"));
1055
+ runInstaller(["--uninstall"], home);
1056
+ check("P1-5: --uninstall 不删非受管文件", fs.existsSync(wrapPath));
1057
+
1058
+ fs.rmSync(home, { recursive: true, force: true });
1059
+ }
1060
+
994
1061
  function diffHint(a, b) {
995
1062
  if (a === b) return "";
996
1063
  for (let i = 0; i < Math.max(a.length, b.length); i++)
@@ -237,6 +237,12 @@ section("归还挑哪些批次");
237
237
  check("域匹配认子域", domainMatches("api.x.com", new Set(["x.com"])) === true);
238
238
  check("域匹配认前导点", domainMatches(".x.com", new Set(["x.com"])) === true);
239
239
  check("域匹配不认后缀碰瓷(notx.com)", domainMatches("notx.com", new Set(["x.com"])) === false);
240
+ check("P1-4: 祖父域 .aliyun.test 会发往 sub.aliyun.test", domainMatches({ domain: ".aliyun.test", hostOnly: false }, new Set(["sub.aliyun.test"])) === true);
241
+ check("P1-4: hostOnly 精确匹配 sub.aliyun.test", domainMatches({ domain: "sub.aliyun.test", hostOnly: true }, new Set(["sub.aliyun.test"])) === true);
242
+ check("P1-4: hostOnly:true 拒绝其他子域 other.aliyun.test", domainMatches({ domain: "other.aliyun.test", hostOnly: true }, new Set(["sub.aliyun.test"])) === false);
243
+ check("P1-4: hostOnly:true 拒绝父域 aliyun.test 往 sub.aliyun.test 漏匹配", domainMatches({ domain: "aliyun.test", hostOnly: true }, new Set(["sub.aliyun.test"])) === false);
244
+ check("P1-4: 拒绝公共后缀 .com.cn / .co.uk", domainMatches({ domain: ".com.cn", hostOnly: false }, new Set(["foo.com.cn"])) === false && domainMatches({ domain: ".co.uk", hostOnly: false }, new Set(["foo.co.uk"])) === false);
245
+ check("P1-4: 拒绝兄弟域 evil-aliyun.test", domainMatches({ domain: ".evil-aliyun.test", hostOnly: false }, new Set(["sub.aliyun.test"])) === false);
240
246
 
241
247
  section("报告:该说的必须说到");
242
248
  {
@@ -350,8 +350,9 @@ console.log("\n\x1b[1mserver 按配置裁剪工具表\x1b[0m");
350
350
  console.log("\n\x1b[1mtools/list 字节预算\x1b[0m");
351
351
  {
352
352
  const B = (o) => Buffer.byteLength(JSON.stringify(o));
353
- const PROSE_BUDGET = 32 * 1024;
353
+ const PROSE_BUDGET = 23 * 1024;
354
354
  const ANNO_BUDGET = 4 * 1024;
355
+ const TOTAL_BUDGET = 27_000;
355
356
  const prose = B(allTools.map(({ annotations: _drop, ...rest }) => rest));
356
357
  const anno = B(allTools) - prose;
357
358
  check(
@@ -365,6 +366,16 @@ console.log("\n\x1b[1mtools/list 字节预算\x1b[0m");
365
366
  `当前 ${anno}B`
366
367
  );
367
368
  const total = B(allTools);
369
+ check(
370
+ `full 档 tools/list 总字节 ≤ ${TOTAL_BUDGET}B`,
371
+ total <= TOTAL_BUDGET,
372
+ `当前 ${total}B,超了 ${total - TOTAL_BUDGET}B`
373
+ );
374
+ check(
375
+ "所有工具 description 长度 ≥ 30 字符(防过度截断)",
376
+ allTools.every((t) => String(t.description || "").length >= 30),
377
+ allTools.filter((t) => String(t.description || "").length < 30).map((t) => t.name).join(",")
378
+ );
368
379
 
369
380
  const rank = allTools
370
381
  .map((t) => ({
@@ -704,5 +715,14 @@ console.log("\n\x1b[1mhost 的配置读写通道\x1b[0m");
704
715
  fs.rmSync(dir, { recursive: true, force: true });
705
716
  }
706
717
 
718
+ console.log("\n\x1b[1mP0-3: browser_fetch 档位与 observe 拒绝\x1b[0m");
719
+ {
720
+ check("TOOL_TIER.browser_fetch === 'full'", TOOL_TIER.browser_fetch === "full");
721
+ const obsList = await listTools({ tools: { profile: "observe" } });
722
+ check("observe 档 tools/list 不含 browser_fetch", !obsList.some((t) => t.name === "browser_fetch"));
723
+ const errFetch = await callTool({ tools: { profile: "observe" } }, "browser_fetch", { url: "/api" });
724
+ check("observe 档调用 browser_fetch 被拒绝", errFetch.result?.isError === true, JSON.stringify(errFetch).slice(0, 200));
725
+ }
726
+
707
727
  console.log(`\n${failed ? "\x1b[31m" : "\x1b[32m"}${passed} 通过,${failed} 失败\x1b[0m\n`);
708
728
  process.exit(failed ? 1 : 0);
@@ -232,8 +232,13 @@ process.stdin.on("data", (c) => {
232
232
  });
233
233
  `
234
234
  );
235
- const launcher = path.join(tmp, "launcher.sh");
236
- fs.writeFileSync(launcher, `#!/bin/sh\nexec ${process.execPath} ${stub} "$@"\n`);
235
+ const onRealWin = process.platform === "win32";
236
+ const launcher = path.join(tmp, onRealWin ? "launcher.bat" : "launcher.sh");
237
+ if (onRealWin) {
238
+ fs.writeFileSync(launcher, `@echo off\r\n"${process.execPath}" "${stub}" %*\r\n`);
239
+ } else {
240
+ fs.writeFileSync(launcher, `#!/bin/sh\nexec ${process.execPath} ${stub} "$@"\n`);
241
+ }
237
242
  fs.chmodSync(launcher, 0o755);
238
243
  const env = { ...process.env, AGENT_IN_CHROME_E2E_LAUNCHER: launcher, AGENT_IN_CHROME_SOCK: path.join(tmp, "s.sock") };
239
244
  const dry = spawnSync(process.execPath, [path.join(HERE, "e2e-sweep.mjs"), "--dry-run"], { encoding: "utf8", env, timeout: 30000 });