@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,935 @@
1
+ #!/usr/bin/env node
2
+ // 把指定域的登录态从**用户自己那个 Chrome**借给**隔离实例**,一条命令走完。
3
+ //
4
+ // 两种装法各有各的敲法,两条都是一等入口:
5
+ // git 检出: node scripts/borrow-login.mjs --domains github.com
6
+ // npm / npx: npx @liang-hz/agent-in-chrome borrow-login --domains github.com
7
+ // (npm 装出来的运行时是扁平布局,没有 `scripts/` 这个目录可敲;bin 的子命令在包内
8
+ // 解析路径,`scripts/` 与 `mcp/` 的相对位置在包里和在仓库里是一样的。)
9
+ //
10
+ // … --domains github.com,news.ycombinator.com
11
+ // … --domains github.com --profile /path/to/profile
12
+ // … --status
13
+ // … --release # 还掉最近借的那一批
14
+ // … --release --all # 还掉账本上全部
15
+ // … --release --domains github.com
16
+ //
17
+ // 边界与承诺(动手前先读这几条):
18
+ // · 只搬 cookie。把 token 放在 localStorage / IndexedDB 的站点(Firebase Auth、MSAL、
19
+ // Supabase 这类)搬不动,症状是「导入成功但仍然未登录」。
20
+ // · 会话 cookie(没有 expires)只活在隔离实例这一次运行里,这是 Web 规范的语义;
21
+ // `--pin-session <小时数>` 才把它改写成持久 cookie,那等于替站点延长凭据寿命,默认关着。
22
+ // · 账本 `<profile>/aic-borrowed-cookies.json`(0600)只记 name/domain/path + 借用时刻,
23
+ // **不含任何 cookie 值**;`--release` 只碰账本上记过账的那些,别的一律不动。
24
+ // · 落盘的 cookie 明文文件用完即删(正常路径、异常路径、进程退出三处),`--keep-file` 才留。
25
+
26
+ import { spawn } from "node:child_process";
27
+ import fs from "node:fs";
28
+ import os from "node:os";
29
+ import path from "node:path";
30
+ import { fileURLToPath, pathToFileURL } from "node:url";
31
+ import { scriptCmd, checkCmd, reinstallCmd } from "../mcp/cli-invocation.mjs";
32
+
33
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
34
+
35
+ // 报告和提示里回指自己 / 回指 cli-browser 的那两条命令,按用户的装法拼出真能敲的形态。
36
+ const SELF = scriptCmd("borrow-login");
37
+ const CLI_BROWSER = scriptCmd("cli-browser");
38
+
39
+ export const LEDGER_BASENAME = "aic-borrowed-cookies.json";
40
+
41
+ export const LEDGER_MAX_BATCHES = 50;
42
+ export const LEDGER_MAX_ENTRIES = 500;
43
+
44
+ export const STORAGE_CAVEAT =
45
+ "只搬 cookie **覆盖不了**把 token 放 localStorage / IndexedDB 的站点" +
46
+ "(Firebase Auth、MSAL、Supabase 这类),那种站点的症状是「导入成功但仍然未登录」。";
47
+
48
+ /*
49
+ * 域名规范化:去掉前导点、转小写,顺带容忍「整条 URL 粘进来」和端口。
50
+ * IDN 会转成 punycode(Chrome 的 cookie 库里存的就是 punycode)。
51
+ *
52
+ * @returns 规范化后的域名;不像域名就返回 null(由调用方点名报出来)
53
+ */
54
+ export function normalizeDomain(raw) {
55
+ let s = String(raw ?? "").trim();
56
+ if (!s) return null;
57
+ s = s.replace(/^[a-z][a-z0-9+.-]*:\/\//i, "");
58
+ s = s.split(/[/?#]/)[0];
59
+ s = s.replace(/^\.+/, "").replace(/\.+$/, "");
60
+ if (!s) return null;
61
+ let host;
62
+ try {
63
+ host = new URL(`http://${s}`).hostname;
64
+ } catch {
65
+ return null;
66
+ }
67
+ if (!host || host.startsWith("[")) return null;
68
+ if (!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/.test(host)) return null;
69
+ return host;
70
+ }
71
+
72
+ export function normalizeDomains(list) {
73
+ const domains = [];
74
+ const invalid = [];
75
+ for (const raw of list || []) {
76
+ const d = normalizeDomain(raw);
77
+ if (!d) invalid.push(String(raw));
78
+ else if (!domains.includes(d)) domains.push(d);
79
+ }
80
+ return { domains, invalid };
81
+ }
82
+
83
+ export class UsageError extends Error {}
84
+
85
+ /*
86
+ * 参数解析。三种模式互斥:借(默认)、`--status`、`--release`。
87
+ *
88
+ * 报错要说清下一步做什么——这些文字是使用者(和 agent)的唯一线索。
89
+ */
90
+ export function parseArgs(argv) {
91
+ const out = {
92
+ mode: "borrow",
93
+ domainsRaw: [],
94
+ profile: null,
95
+ fromProfile: null,
96
+ keepFile: false,
97
+ all: false,
98
+ wipe: false,
99
+ pinSessionHours: null,
100
+ headed: false,
101
+ help: false,
102
+ };
103
+ const take = (i, flag) => {
104
+ const v = argv[i + 1];
105
+ if (v === undefined || v.startsWith("--")) throw new UsageError(`${flag} 后面要跟一个值,什么都没做。`);
106
+ return v;
107
+ };
108
+ for (let i = 0; i < argv.length; i++) {
109
+ let a = argv[i];
110
+ let inlineVal = null;
111
+ const eq = a.indexOf("=");
112
+ if (a.startsWith("--") && eq > 2) {
113
+ inlineVal = a.slice(eq + 1);
114
+ a = a.slice(0, eq);
115
+ }
116
+ switch (a) {
117
+ case "-h":
118
+ case "--help":
119
+ out.help = true;
120
+ break;
121
+ case "--status":
122
+ out.mode = "status";
123
+ break;
124
+ case "--release":
125
+ out.mode = "release";
126
+ break;
127
+ case "--all":
128
+ out.all = true;
129
+ break;
130
+ case "--wipe":
131
+ out.wipe = true;
132
+ break;
133
+ case "--keep-file":
134
+ out.keepFile = true;
135
+ break;
136
+ case "--headed":
137
+ out.headed = true;
138
+ break;
139
+ case "--domains":
140
+ out.domainsRaw.push(...String(inlineVal ?? take(i++, "--domains")).split(","));
141
+ break;
142
+ case "--profile":
143
+ out.profile = String(inlineVal ?? take(i++, "--profile"));
144
+ break;
145
+ case "--from-profile":
146
+ out.fromProfile = String(inlineVal ?? take(i++, "--from-profile"));
147
+ break;
148
+ case "--pin-session": {
149
+ const v = String(inlineVal ?? take(i++, "--pin-session"));
150
+ const h = Number(v);
151
+ if (!Number.isFinite(h) || h <= 0)
152
+ throw new UsageError(`--pin-session 要一个正数(小时),收到 ${JSON.stringify(v)},什么都没做。`);
153
+ out.pinSessionHours = h;
154
+ break;
155
+ }
156
+ default:
157
+ throw new UsageError(`不认识的参数 ${a}。跑 --help 看用法,什么都没做。`);
158
+ }
159
+ }
160
+ if (out.help) return out;
161
+
162
+ if (out.mode === "status" && out.domainsRaw.length)
163
+ throw new UsageError("--status 只是查看,不接受 --domains,什么都没做。");
164
+ if (out.fromProfile && out.mode !== "borrow")
165
+ throw new UsageError("--from-profile 只在借用时有意义(它说的是「从哪儿借」),什么都没做。");
166
+ if (out.fromProfile && out.profile && path.resolve(out.fromProfile) === path.resolve(out.profile))
167
+ throw new UsageError("--from-profile 和 --profile 是同一个目录,那就是自己借给自己,什么都没做。");
168
+ if (out.mode !== "release" && out.all)
169
+ throw new UsageError("--all 只跟 --release 一起用(表示还掉账本上全部),什么都没做。");
170
+ if (out.wipe && !(out.mode === "release" && out.all))
171
+ throw new UsageError(
172
+ "--wipe 只能和 --release --all 一起用。它走的是 Storage.clearCookies," +
173
+ "会把这个隔离 profile 里**你自己手动登录的站点**也一起清掉,所以必须显式说全,什么都没做。"
174
+ );
175
+ if (out.mode === "borrow" && !out.domainsRaw.length)
176
+ throw new UsageError(
177
+ "要借哪些域的登录态?给 --domains,比如 --domains github.com,news.ycombinator.com。" +
178
+ "(查看现状用 --status,归还用 --release。)什么都没做。"
179
+ );
180
+ const { domains, invalid } = normalizeDomains(out.domainsRaw);
181
+ if (invalid.length)
182
+ throw new UsageError(`这些不像域名:${invalid.join("、")}。域名形如 github.com(前导点、大小写、端口、整条 URL 都会自动处理)。什么都没做。`);
183
+ out.domains = domains;
184
+ return out;
185
+ }
186
+
187
+ export const cookieKey = (c) => JSON.stringify([c?.name ?? "", c?.domain ?? "", c?.path ?? ""]);
188
+
189
+ export const isSessionCookie = (c) => c?.session === true || c?.expires === undefined || Number(c?.expires) === -1;
190
+
191
+ export const ledgerRowIsSession = (c) => c?.session === true;
192
+
193
+ /*
194
+ * 把会话 cookie 改写成持久 cookie(`--pin-session <小时>`)。
195
+ *
196
+ * **默认不做。** 它把凭据的寿命延长到了站点本来不打算给的长度——站点把它发成会话
197
+ * cookie,意思就是「关掉浏览器就该失效」。所以这是个显式开关,而且报告里会点名说
198
+ * 改了哪几条。
199
+ */
200
+ export function pinSessionCookies(cookies, hours, nowMs = Date.now()) {
201
+ if (!(hours > 0)) return { cookies, pinned: [] };
202
+ const expires = Math.floor(nowMs / 1000) + Math.round(hours * 3600);
203
+ const pinned = [];
204
+ const out = (cookies || []).map((c) => {
205
+ if (!isSessionCookie(c)) return c;
206
+ pinned.push({ name: c.name, domain: c.domain, path: c.path });
207
+ const { session: _drop, ...rest } = c;
208
+ return { ...rest, expires };
209
+ });
210
+ return { cookies: out, pinned };
211
+ }
212
+
213
+ /*
214
+ * 导入之后的逐字比对。
215
+ *
216
+ * `cookies_import` 自己那道读回校验只按 **name+domain+path+分区** 认「在不在」,
217
+ * **不看 value**。而对 cookie 来说值错一个字节 = 静默地没登录上——正是这个项目最忌
218
+ * 讳的那种「报告成功、实际没做成」。所以这里再比一次值和 httpOnly。
219
+ *
220
+ * @param sent 送过去的那批(导出文件里的原样)
221
+ * @param got 隔离实例里读回来的那批
222
+ */
223
+ export function diffImported(sent, got) {
224
+ const byKey = new Map((got || []).map((c) => [cookieKey(c), c]));
225
+ const matched = [];
226
+ const missing = [];
227
+ const mismatched = [];
228
+ for (const c of sent || []) {
229
+ const g = byKey.get(cookieKey(c));
230
+ if (!g) {
231
+ missing.push({ name: c.name, domain: c.domain, path: c.path, why: whyDropped(c) });
232
+ continue;
233
+ }
234
+ const bad = [];
235
+ if (String(g.value ?? "") !== String(c.value ?? "")) bad.push("value");
236
+ if (!!g.httpOnly !== !!c.httpOnly) bad.push("httpOnly");
237
+ if (!!g.secure !== !!c.secure) bad.push("secure");
238
+ if (bad.length) mismatched.push({ name: c.name, domain: c.domain, path: c.path, fields: bad });
239
+ else matched.push({ name: c.name, domain: c.domain, path: c.path, session: isSessionCookie(g) });
240
+ }
241
+ return { matched, missing, mismatched };
242
+ }
243
+
244
+ // 给一条没种上的 cookie 算一句解释:SameSite=None 缺 secure / 已经过期 /
245
+ // 同一注册域 cookie 条数超上限。判据自己算,浏览器不给理由。
246
+ export function whyDropped(c) {
247
+ if (c?.sameSite === "None" && !c?.secure) return "SameSite=None 但没有 secure,浏览器直接丢弃";
248
+ if (c?.expires !== undefined && Number(c.expires) !== -1 && Number(c.expires) * 1000 < Date.now())
249
+ return "expires 已经过期";
250
+ return "没落地,最可能是同一个注册域 cookie 数超了上限(Chrome 到 180 条就淘汰到 150 条,丢最老的)";
251
+ }
252
+
253
+ export const emptyLedger = () => ({ version: 1, batches: [] });
254
+
255
+ /*
256
+ * 账本清理。三层,缺一层都会让它只增不减:
257
+ *
258
+ * ① `liveKeys` 给了就按存在性清:账本上那条 cookie 浏览器里已经没了(会话 cookie
259
+ * 随重启消失、站点自己覆盖掉、用户手动清过),条目就该销。这和 sw.js 的
260
+ * `pruneLedgers()` 是同一条规矩——判据只用**记过的账**核对**当下的事实**,
261
+ * 不用会过期的猜测。**浏览器连不上时不许猜**:liveKeys 传 null,这一层跳过。
262
+ * ② 空批次销掉。
263
+ * ③ 硬上限兜底。丢最老的,并且**把丢掉的报出来**——它们从此没法用 --release
264
+ * 自动还了,这件事不能静默。
265
+ */
266
+ export function pruneLedger(ledger, liveKeys, { maxBatches = LEDGER_MAX_BATCHES, maxEntries = LEDGER_MAX_ENTRIES } = {}) {
267
+ const src = ledger && Array.isArray(ledger.batches) ? ledger : emptyLedger();
268
+ const droppedEntries = [];
269
+ let batches = src.batches.map((b) => {
270
+ if (!liveKeys) return b;
271
+ const keep = [];
272
+ for (const c of b.cookies || []) {
273
+ if (liveKeys.has(cookieKey(c))) keep.push(c);
274
+ else droppedEntries.push({ ...c, batchId: b.id });
275
+ }
276
+ return { ...b, cookies: keep };
277
+ });
278
+ const emptied = batches.filter((b) => !(b.cookies || []).length).map((b) => b.id);
279
+ batches = batches.filter((b) => (b.cookies || []).length);
280
+
281
+ batches.sort((a, b) => (a.atMs || 0) - (b.atMs || 0));
282
+ const capped = [];
283
+ while (batches.length > maxBatches) capped.push(batches.shift());
284
+ const total = () => batches.reduce((n, b) => n + (b.cookies || []).length, 0);
285
+ while (total() > maxEntries && batches.length > 1) capped.push(batches.shift());
286
+
287
+ return { ledger: { version: 1, batches }, droppedEntries, emptiedBatches: emptied, cappedBatches: capped };
288
+ }
289
+
290
+ /* `--release` 要还哪几批:默认最近一批,`--all` 全部,给了 `--domains` 就按域挑 */
291
+ export function selectBatches(ledger, { all = false, domains = [] } = {}) {
292
+ const batches = [...((ledger && ledger.batches) || [])].sort((a, b) => (a.atMs || 0) - (b.atMs || 0));
293
+ if (all) return { picked: batches, rest: [] };
294
+ if (domains && domains.length) {
295
+ const want = new Set(domains);
296
+ const picked = [];
297
+ const rest = [];
298
+ for (const b of batches) {
299
+ const hit = (b.cookies || []).filter((c) => domainMatches(c.domain, want));
300
+ const miss = (b.cookies || []).filter((c) => !domainMatches(c.domain, want));
301
+ if (hit.length) picked.push({ ...b, cookies: hit });
302
+ if (miss.length) rest.push({ ...b, cookies: miss });
303
+ }
304
+ return { picked, rest };
305
+ }
306
+ const last = batches[batches.length - 1];
307
+ return { picked: last ? [last] : [], rest: last ? batches.slice(0, -1) : [] };
308
+ }
309
+
310
+ export function domainMatches(cookieDomain, wantSet) {
311
+ const d = String(cookieDomain || "").replace(/^\./, "").toLowerCase();
312
+ for (const w of wantSet) if (d === w || d.endsWith("." + w)) return true;
313
+ return false;
314
+ }
315
+
316
+ export function formatBorrowReport({ domains, sent, diff, importReported, pinned, profileDir, browser, ledgerNote, source = "你的 Chrome" }) {
317
+ const L = [];
318
+ const sessionCount = (diff.matched || []).filter((c) => c.session).length;
319
+ const persistCount = (diff.matched || []).length - sessionCount;
320
+ L.push(`从${source} 导出 ${domains.join("、")} 的 ${sent.length} 条 cookie → ${profileDir}`);
321
+ L.push(
322
+ `种上并逐字校验通过:${diff.matched.length} 条` +
323
+ `(工具自己报的是 ${importReported?.imported ?? "?"}/${importReported?.requested ?? "?"};` +
324
+ `这里的数字是把值和 httpOnly 也读回来比过的,不是照抄它)`
325
+ );
326
+ if (diff.mismatched.length) {
327
+ L.push(`⚠️ 值对不上:${diff.mismatched.length} 条 —— 这是严重问题,别拿它当能用的登录态:`);
328
+ for (const c of diff.mismatched) L.push(` · ${c.name} @ ${c.domain}${c.path}:${c.fields.join(" / ")} 和源头不一致`);
329
+ }
330
+ if (diff.missing.length) {
331
+ L.push(`没种上:${diff.missing.length} 条`);
332
+ for (const c of diff.missing) L.push(` · ${c.name} @ ${c.domain}${c.path} —— ${c.why}`);
333
+ }
334
+ L.push("");
335
+ L.push(`有效期(只算真的种上了的那 ${diff.matched.length} 条):${sessionCount} 条是**会话 cookie**,${persistCount} 条是持久 cookie。`);
336
+ if (pinned?.length)
337
+ L.push(` 本次按 --pin-session 把 ${pinned.length} 条会话 cookie 改写成了持久 cookie —— 这等于替站点延长了凭据寿命,心里有数。`);
338
+ if (sessionCount)
339
+ L.push(
340
+ ` 会话 cookie 只活在这个浏览器进程的内存里,隔离实例一重启就没了,要重借。` +
341
+ `(想让它们活过重启:--pin-session <小时数>,默认关着,因为那等于替站点延长了凭据寿命。)`
342
+ );
343
+ if (persistCount)
344
+ L.push(
345
+ ` 持久 cookie 会写进 <profile>/Default/Cookies,能活过重启 —— **前提是浏览器优雅退出**。` +
346
+ `收隔离实例请用 ${CLI_BROWSER} --stop(它走 Browser.close);整组 SIGTERM 会把刷盘打断。`
347
+ );
348
+ L.push("");
349
+ L.push(STORAGE_CAVEAT);
350
+ if (ledgerNote) L.push(ledgerNote);
351
+ if (browser)
352
+ L.push(
353
+ `\n隔离实例还开着:pid=${browser.pid} ${browser.version || ""}(特意留着,会话 cookie 在它内存里)。` +
354
+ `\n 用它:AGENT_IN_CHROME_LAUNCH=1 AGENT_IN_CHROME_PROFILE=${profileDir} 起 MCP server,会自动认领这个浏览器` +
355
+ `\n 还回去:${SELF} --release --profile ${profileDir}` +
356
+ `\n 收掉它:AGENT_IN_CHROME_PROFILE=${profileDir} ${CLI_BROWSER} --stop`
357
+ );
358
+ return L;
359
+ }
360
+
361
+ // 帮助文本里的示例命令**跟着用户的装法拼**(见 mcp/cli-invocation.mjs):git 检出
362
+ // 给 `node scripts/borrow-login.mjs …`,npm / npx 装的给 `npx …borrow-login …`。
363
+ const HELP = `把指定域的登录态从你自己那个 Chrome 借给隔离实例。
364
+
365
+ ${SELF} --domains github.com,news.ycombinator.com
366
+ ${SELF} --domains github.com --profile /path/to/profile
367
+ ${SELF} --status
368
+ ${SELF} --release 还掉最近借的那一批
369
+ ${SELF} --release --all 还掉账本上全部
370
+ ${SELF} --release --domains github.com
371
+ ${SELF} --release --all --wipe 清空隔离 profile 的全部 cookie(含你自己登的,慎用)
372
+
373
+ 参数
374
+ --domains a.com,b.com 要借(或要还)的域,含子域。前导点/大小写/端口/整条 URL 都会自动处理
375
+ --profile <目录> 隔离实例的 profile,默认 $AGENT_IN_CHROME_PROFILE 或
376
+ ~/.agent-in-chrome/agent-in-chrome/cli-profile
377
+ --from-profile <目录> 从**另一个隔离 profile**借,而不是从你自己那个 Chrome 借。
378
+ 用途:把一个长期登录着的隔离 profile 借给一次性的任务 profile
379
+ --keep-file 留下落盘的 cookie 文件(排查用)。默认用完即删——那份文件是
380
+ 可直接冒用的完整会话凭据,留在磁盘上就是一处新的攻击面
381
+ --pin-session <小时> 把会话 cookie 改写成持久 cookie,让它活过隔离实例重启。
382
+ **默认关**:这等于替站点延长了凭据寿命
383
+ --headed 隔离实例开有头窗口(默认 headless)
384
+ -h, --help 这份说明
385
+
386
+ 前提:你的 Chrome 开着、Agent in Chrome 扩展已启用(${checkCmd()})。
387
+ `;
388
+
389
+ const ok = (s) => console.log(` \x1b[32m✓\x1b[0m ${s}`);
390
+ const warn = (s) => console.log(` \x1b[33m!\x1b[0m ${s}`);
391
+ const step = (s) => console.log(`\n\x1b[1m${s}\x1b[0m`);
392
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
393
+
394
+ function bridgeServerCmd() {
395
+ const override = process.env.AGENT_IN_CHROME_BORROW_SERVER;
396
+ if (override) return override.endsWith(".mjs") ? [process.execPath, [override]] : [override, []];
397
+ const installed = path.join(os.homedir(), ".agent-in-chrome", "agent-in-chrome", "mcp-launcher.sh");
398
+ if (fs.existsSync(installed)) return [installed, []];
399
+ return [process.execPath, [path.join(ROOT, "mcp", "server.mjs")]];
400
+ }
401
+
402
+ function mcpClient(cmd, args, env, label) {
403
+ const p = spawn(cmd, args, { stdio: ["pipe", "pipe", "pipe"], env });
404
+ let errText = "";
405
+ p.stderr.setEncoding("utf8");
406
+ p.stderr.on("data", (c) => {
407
+ errText += c;
408
+ if (errText.length > 20000) errText = errText.slice(-20000);
409
+ });
410
+ let buf = "";
411
+ const waiting = new Map();
412
+ let n = 0;
413
+ p.stdout.setEncoding("utf8");
414
+ p.stdout.on("data", (c) => {
415
+ buf += c;
416
+ let i;
417
+ while ((i = buf.indexOf("\n")) >= 0) {
418
+ const line = buf.slice(0, i).trim();
419
+ buf = buf.slice(i + 1);
420
+ if (!line) continue;
421
+ try {
422
+ const m = JSON.parse(line);
423
+ const f = waiting.get(m.id);
424
+ if (f) {
425
+ waiting.delete(m.id);
426
+ f(m);
427
+ }
428
+ } catch {}
429
+ }
430
+ });
431
+ const rpc = (method, params) =>
432
+ new Promise((res, rej) => {
433
+ const id = ++n;
434
+ const t = setTimeout(() => rej(new Error(`${label}:${method} 超时(90s)`)), 90_000);
435
+ waiting.set(id, (m) => {
436
+ clearTimeout(t);
437
+ res(m);
438
+ });
439
+ p.stdin.write(JSON.stringify({ jsonrpc: "2.0", id, method, params }) + "\n");
440
+ });
441
+ return {
442
+ proc: p,
443
+ label,
444
+ get stderr() {
445
+ return errText;
446
+ },
447
+ async init() {
448
+ const r = await rpc("initialize", {
449
+ protocolVersion: "2025-06-18",
450
+ capabilities: {},
451
+ clientInfo: { name: "borrow-login", version: "0" },
452
+ });
453
+ p.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) + "\n");
454
+ return r.result?.serverInfo || {};
455
+ },
456
+ async tools() {
457
+ const r = await rpc("tools/list", {});
458
+ return (r.result?.tools || []).map((t) => t.name);
459
+ },
460
+ async call(name, params = {}) {
461
+ const r = await rpc("tools/call", { name, arguments: params });
462
+ const text = r.result?.content?.[0]?.text ?? "";
463
+ if (r.result?.isError) throw new Error(text);
464
+ try {
465
+ return JSON.parse(text);
466
+ } catch {
467
+ return text;
468
+ }
469
+ },
470
+ kill() {
471
+ try {
472
+ p.kill();
473
+ } catch {}
474
+ },
475
+ };
476
+ }
477
+
478
+ const scratchFiles = new Set();
479
+ let keepScratch = false;
480
+ function dropScratch() {
481
+ if (keepScratch) return;
482
+ for (const f of scratchFiles) {
483
+ try {
484
+ fs.rmSync(f, { force: true });
485
+ } catch {}
486
+ }
487
+ scratchFiles.clear();
488
+ }
489
+ process.on("exit", dropScratch);
490
+
491
+ function ledgerPath(profileDir) {
492
+ return path.join(profileDir, LEDGER_BASENAME);
493
+ }
494
+ function readLedger(profileDir) {
495
+ try {
496
+ const j = JSON.parse(fs.readFileSync(ledgerPath(profileDir), "utf8"));
497
+ return j && Array.isArray(j.batches) ? j : emptyLedger();
498
+ } catch {
499
+ return emptyLedger();
500
+ }
501
+ }
502
+ function writeLedger(profileDir, ledger) {
503
+ const abs = ledgerPath(profileDir);
504
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
505
+ const tmp = `${abs}.tmp-${process.pid}`;
506
+ const fd = fs.openSync(tmp, "w", 0o600);
507
+ try {
508
+ fs.writeFileSync(fd, JSON.stringify(ledger, null, 2) + "\n");
509
+ } finally {
510
+ fs.closeSync(fd);
511
+ }
512
+ fs.renameSync(tmp, abs);
513
+ }
514
+
515
+ async function liveCookieKeys(cli, tabId) {
516
+ const r = await cli.call("browser_cdp", {
517
+ method: "Storage.getCookies",
518
+ params: {},
519
+ maxChars: 4_000_000,
520
+ tabId,
521
+ });
522
+ if (r?.truncated)
523
+ throw new Error(
524
+ `隔离实例的 cookie 列表被截断了(${r.chars} 字符),没法可靠核对账本,什么都没改。` +
525
+ "这说明这个 profile 里 cookie 极多;可以先 --release --all 清一遍再借。"
526
+ );
527
+ const cookies = r?.result?.cookies || [];
528
+ return { keys: new Set(cookies.map(cookieKey)), count: cookies.length };
529
+ }
530
+
531
+ async function openIsolated(launch, { headless, label }) {
532
+ const info = await launch.ensureBrowser({ headless });
533
+ const cli = mcpClient(process.execPath, [path.join(ROOT, "mcp", "server.mjs")], {
534
+ ...process.env,
535
+ AGENT_IN_CHROME_LAUNCH: "1",
536
+ AGENT_IN_CHROME_KEEP: "1",
537
+ AGENT_IN_CHROME_PROFILE: launch.PROFILE_DIR,
538
+ AGENT_IN_CHROME_HEADLESS: headless ? "1" : "0",
539
+ AGENT_IN_CHROME_SESSION_ID: `borrow-login-cdp-${process.pid}`,
540
+ }, "隔离实例");
541
+ const server = await cli.init();
542
+ const names = await cli.tools();
543
+ for (const need of ["browser_cookies_import", "browser_cdp", "browser_new_tab"])
544
+ if (!names.includes(need)) {
545
+ cli.kill();
546
+ throw new Error(
547
+ `隔离实例这一侧的 ${need} 没有注册(server ${server.version || "?"})。` +
548
+ "多半是工具档位被切到了「观察」档——搬运登录态属于凭据面,需要「完全」档。"
549
+ );
550
+ }
551
+ let tab;
552
+ try {
553
+ tab = await cli.call("browser_new_tab", { label });
554
+ } catch (e) {
555
+ cli.kill();
556
+ throw new Error(`隔离实例开不出标签页:${e.message}\nserver stderr:\n${cli.stderr.slice(-1200)}`);
557
+ }
558
+ return { info, cli, tabId: tab.tabId };
559
+ }
560
+
561
+ async function closeIso(iso) {
562
+ if (!iso) return;
563
+ try {
564
+ await iso.cli.call("browser_close_all", {});
565
+ } catch {}
566
+ iso.cli.kill();
567
+ }
568
+
569
+ async function exportFrom(domains, outFile, fromProfile) {
570
+ const cdpSource = !!fromProfile;
571
+ const [cmd, args] = cdpSource ? [process.execPath, [path.join(ROOT, "mcp", "server.mjs")]] : bridgeServerCmd();
572
+ step(`① 从${cdpSource ? `隔离 profile ${fromProfile}` : "你自己那个 Chrome"} 导出(${domains.join("、")})`);
573
+ console.log(` 用的 server:${cmd}${args.length ? " " + args.join(" ") : ""}`);
574
+ const env = { ...process.env, AGENT_IN_CHROME_SESSION_ID: `borrow-login-src-${process.pid}` };
575
+ if (cdpSource) {
576
+ env.AGENT_IN_CHROME_LAUNCH = "1";
577
+ env.AGENT_IN_CHROME_KEEP = "1";
578
+ env.AGENT_IN_CHROME_PROFILE = path.resolve(fromProfile);
579
+ env.AGENT_IN_CHROME_HEADLESS = env.AGENT_IN_CHROME_HEADLESS ?? "1";
580
+ } else {
581
+ delete env.AGENT_IN_CHROME_LAUNCH;
582
+ delete env.AGENT_IN_CHROME_PROFILE;
583
+ delete env.AGENT_IN_CHROME_KEEP;
584
+ }
585
+ const cli = mcpClient(cmd, args, env, cdpSource ? "源隔离实例" : "真 Chrome");
586
+ try {
587
+ const server = await cli.init();
588
+ const names = await cli.tools();
589
+ if (!names.includes("browser_cookies_export"))
590
+ throw new Error(
591
+ `browser_cookies_export 没有注册(server ${server.version || "?"})。` +
592
+ "多半是工具档位被切到了「观察」档——导出 cookie 属于凭据面,需要在扩展设置里切到「完全」档。"
593
+ );
594
+
595
+ let status = null;
596
+ let lastErr = "";
597
+ const deadline = Date.now() + 45_000;
598
+ process.stdout.write(cdpSource ? " 等源隔离实例就绪" : " 等 Chrome 扩展接入");
599
+ while (Date.now() < deadline) {
600
+ try {
601
+ status = await cli.call("browser_status");
602
+ break;
603
+ } catch (e) {
604
+ lastErr = String(e.message || e);
605
+ process.stdout.write(".");
606
+ await sleep(1500);
607
+ }
608
+ }
609
+ console.log("");
610
+ if (!status) {
611
+ if (cdpSource) throw new Error(`源隔离实例起不来(最后一次报的是:${lastErr})\n\nserver stderr 末尾:\n${cli.stderr.slice(-1200)}`);
612
+ throw bridgeDownError(lastErr, cli.stderr);
613
+ }
614
+ ok(cdpSource ? `源隔离实例就绪(工具层 ${status.version})` : `扩展已接入(扩展 ${status.version})`);
615
+
616
+ const tab = await cli.call("browser_new_tab", { label: "借登录态" });
617
+ try {
618
+ const res = await cli.call("browser_cookies_export", { domains, outFile, tabId: tab.tabId });
619
+ if (!res?.file) throw new Error(`导出没有落盘(返回:${JSON.stringify(res).slice(0, 300)})`);
620
+ scratchFiles.add(res.file);
621
+ ok(`导出 ${res.count} 条(${Object.keys(res.domains || {}).join("、") || "无"})→ ${res.file}(0600)`);
622
+ return res;
623
+ } catch (e) {
624
+ throw new Error(
625
+ `导出被拒了。扩展那边原样说:\n\n${e.message}\n\n` +
626
+ "如果这是按域授权闸:去点扩展图标,在弹窗里给这些域授权,然后把这条命令重跑一遍。"
627
+ );
628
+ } finally {
629
+ try {
630
+ await cli.call("browser_close_all", {});
631
+ } catch {}
632
+ }
633
+ } finally {
634
+ cli.kill();
635
+ }
636
+ }
637
+
638
+ function bridgeDownError(lastErr, stderr) {
639
+ const tail = (stderr || "").trim().split("\n").slice(-6).join("\n");
640
+ let hint =
641
+ "排查顺序:\n" +
642
+ " 1. Chrome 在跑吗,chrome://extensions 里 Agent in Chrome 是否已启用\n" +
643
+ " 2. 点扩展图标看弹窗里的断开原因,点一下「重新连接」\n" +
644
+ ` 3. ${checkCmd()}`;
645
+ if (/桥接认证|认证失败|handshake/i.test(stderr || ""))
646
+ hint =
647
+ "stderr 里是**桥接认证失败**:这条 socket 已经被另一个版本的 server 当主占着,\n" +
648
+ "两边的握手协议对不上(0.48 把它换成了质询-应答,0.47 的主认不出)。\n" +
649
+ ` · 把运行时同步到当前版本:${reinstallCmd()},然后重启所有 agent 会话\n` +
650
+ " · 或者用和主同版本的 server:AGENT_IN_CHROME_BORROW_SERVER=<那份 server.mjs 或 launcher>";
651
+ return new Error(`连不上你的 Chrome(最后一次报的是:${lastErr})。\n\n${hint}\n\nserver stderr 末尾:\n${tail}`);
652
+ }
653
+
654
+ async function main(argv) {
655
+ let args;
656
+ try {
657
+ args = parseArgs(argv);
658
+ } catch (e) {
659
+ if (e instanceof UsageError) {
660
+ console.error(`\n${e.message}\n`);
661
+ return 2;
662
+ }
663
+ throw e;
664
+ }
665
+ if (args.help) {
666
+ console.log(HELP);
667
+ return 0;
668
+ }
669
+ keepScratch = args.keepFile;
670
+
671
+ if (args.profile) process.env.AGENT_IN_CHROME_PROFILE = path.resolve(args.profile);
672
+ process.env.AGENT_IN_CHROME_KEEP = "1";
673
+ const launch = await import("../mcp/cdp/browser-launch.mjs");
674
+ const PROFILE = launch.PROFILE_DIR;
675
+ const headless = !args.headed;
676
+
677
+ if (args.mode === "status") return await doStatus(launch, PROFILE);
678
+ if (args.mode === "release") return await doRelease(launch, PROFILE, args, headless);
679
+ return await doBorrow(launch, PROFILE, args, headless);
680
+ }
681
+
682
+ async function doStatus(launch, PROFILE) {
683
+ console.log(`\n\x1b[1m隔离实例\x1b[0m ${PROFILE}`);
684
+ const st = launch.browserStatus();
685
+ if (st.running) console.log(` 在跑:pid=${st.pid} ${st.version || ""} ${st.endpoint?.wsUrl || ""}`);
686
+ else console.log(` 没在跑${st.stale ? "(账上有条陈旧记录,进程已经不在了)" : ""}`);
687
+
688
+ let ledger = readLedger(PROFILE);
689
+ const before = ledger.batches.reduce((n, b) => n + (b.cookies || []).length, 0);
690
+ console.log(`\n\x1b[1m借用账本\x1b[0m ${ledgerPath(PROFILE)}`);
691
+ if (!before) {
692
+ console.log(" 空的——现在没借着任何东西。");
693
+ return 0;
694
+ }
695
+
696
+ if (st.running) {
697
+ let iso = null;
698
+ try {
699
+ iso = await openIsolated(launch, { headless: true, label: "查借用账本" });
700
+ const live = await liveCookieKeys(iso.cli, iso.tabId);
701
+ const pruned = pruneLedger(ledger, live.keys);
702
+ if (pruned.droppedEntries.length || pruned.emptiedBatches.length) writeLedger(PROFILE, pruned.ledger);
703
+ ledger = pruned.ledger;
704
+ if (pruned.droppedEntries.length)
705
+ console.log(` (核对后清掉 ${pruned.droppedEntries.length} 条已经不在浏览器里的旧账)`);
706
+ } catch (e) {
707
+ warn(`没核对成账本:${e.message}`);
708
+ } finally {
709
+ await closeIso(iso);
710
+ if (iso && !iso.info.adopted) {
711
+ const r = await launch.stopBrowserGracefully();
712
+ warn(`查看时浏览器已不在,冷启动了一个又收掉了(${r.how},stopped=${r.stopped})`);
713
+ } else {
714
+ try {
715
+ launch.markAdoptable();
716
+ } catch {}
717
+ }
718
+ }
719
+ } else {
720
+ warn("隔离实例没在跑,账本没跟浏览器核对过——里面的会话 cookie 其实早就随进程没了。");
721
+ }
722
+
723
+ for (const b of ledger.batches.sort((a, b2) => (a.atMs || 0) - (b2.atMs || 0))) {
724
+ const s = (b.cookies || []).filter(ledgerRowIsSession).length;
725
+ console.log(
726
+ ` · ${new Date(b.atMs).toLocaleString()} ${(b.domains || []).join("、")} ` +
727
+ `${(b.cookies || []).length} 条(会话 ${s} / 持久 ${(b.cookies || []).length - s})${b.pinnedHours ? ` 已 pin ${b.pinnedHours}h` : ""}`
728
+ );
729
+ }
730
+ console.log(`\n还回去:${SELF} --release --all --profile ${PROFILE}`);
731
+ return 0;
732
+ }
733
+
734
+ async function doBorrow(launch, PROFILE, args, headless) {
735
+ const cookieOut = path.join(
736
+ process.env.AGENT_IN_CHROME_COOKIE_DIR || path.join(os.homedir(), ".agent-in-chrome", "cookies"),
737
+ `borrow-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}.json`
738
+ );
739
+ const exported = await exportFrom(args.domains, cookieOut, args.fromProfile);
740
+ if (!exported.count)
741
+ throw new Error(
742
+ `这几个域一条 cookie 都没有:${args.domains.join("、")}。三种可能:\n` +
743
+ " · 你在那个 Chrome 里本来就没登录这些站\n" +
744
+ " · 域名写错了(cookie 常挂在 .example.com 上,写 example.com 就行;但 www 前缀有时是另一条)\n" +
745
+ " · 那个站的登录态根本不在 cookie 里(见结尾那条边界)\n" +
746
+ "什么都没往隔离实例里写。"
747
+ );
748
+
749
+ let sent = JSON.parse(fs.readFileSync(exported.file, "utf8")).cookies || [];
750
+ let pinned = [];
751
+ if (args.pinSessionHours) {
752
+ const r = pinSessionCookies(sent, args.pinSessionHours);
753
+ sent = r.cookies;
754
+ pinned = r.pinned;
755
+ const fd = fs.openSync(exported.file, "w", 0o600);
756
+ try {
757
+ fs.writeFileSync(fd, JSON.stringify({ cookies: sent }, null, 2));
758
+ } finally {
759
+ fs.closeSync(fd);
760
+ }
761
+ ok(`--pin-session ${args.pinSessionHours}h:把 ${pinned.length} 条会话 cookie 改写成持久 cookie`);
762
+ }
763
+
764
+ step(`② 起隔离实例并导入 → ${PROFILE}`);
765
+ const iso = await openIsolated(launch, { headless, label: "借登录态" });
766
+ let succeeded = false;
767
+ const coldStarted = !iso.info.adopted;
768
+ process.on("exit", () => {
769
+ if (succeeded || iso.info.adopted) {
770
+ try {
771
+ launch.markAdoptable();
772
+ } catch {}
773
+ }
774
+ });
775
+ try {
776
+ console.log(` 浏览器 pid=${iso.info.pid}(${iso.info.adopted ? "复用" : "新起"})${iso.info.version || ""}`);
777
+ const importReported = await iso.cli.call("browser_cookies_import", { inFile: exported.file, tabId: iso.tabId });
778
+
779
+ const verifyFile = `${exported.file}.verify`;
780
+ scratchFiles.add(verifyFile);
781
+ await iso.cli.call("browser_cookies_export", { domains: args.domains, outFile: verifyFile, tabId: iso.tabId });
782
+ const got = JSON.parse(fs.readFileSync(verifyFile, "utf8")).cookies || [];
783
+ const diff = diffImported(sent, got);
784
+
785
+ const ledgerNote = appendBatch(PROFILE, {
786
+ domains: args.domains,
787
+ cookies: diff.matched.map((c) => ({ name: c.name, domain: c.domain, path: c.path, session: c.session })),
788
+ pinnedHours: args.pinSessionHours || null,
789
+ liveKeys: (await liveCookieKeys(iso.cli, iso.tabId)).keys,
790
+ });
791
+
792
+ succeeded = diff.matched.length > 0 && diff.mismatched.length === 0;
793
+ step("③ 结果");
794
+ for (const line of formatBorrowReport({
795
+ domains: args.domains,
796
+ sent,
797
+ diff,
798
+ importReported,
799
+ pinned,
800
+ profileDir: PROFILE,
801
+ browser: { pid: iso.info.pid, version: iso.info.version },
802
+ ledgerNote,
803
+ source: args.fromProfile ? `隔离 profile ${path.resolve(args.fromProfile)}` : "你的 Chrome",
804
+ }))
805
+ console.log(line);
806
+
807
+ if (args.keepFile) warn(`\n--keep-file:留下了 ${exported.file} 和 ${verifyFile} —— 里面是可直接冒用的完整会话凭据,用完自己删。`);
808
+ return diff.mismatched.length ? 1 : 0;
809
+ } finally {
810
+ await closeIso(iso);
811
+ if (!succeeded && coldStarted) {
812
+ const r = await launch.stopBrowserGracefully();
813
+ warn(`借用没成功,本次起的隔离实例已收掉(${r.how},stopped=${r.stopped})`);
814
+ }
815
+ dropScratch();
816
+ }
817
+ }
818
+
819
+ function appendBatch(PROFILE, { domains, cookies, pinnedHours, liveKeys }) {
820
+ const ledger = readLedger(PROFILE);
821
+ ledger.batches.push({
822
+ id: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`,
823
+ atMs: Date.now(),
824
+ at: new Date().toISOString(),
825
+ domains,
826
+ pinnedHours,
827
+ cookies,
828
+ });
829
+ const pruned = pruneLedger(ledger, liveKeys);
830
+ writeLedger(PROFILE, pruned.ledger);
831
+ const notes = [];
832
+ if (pruned.droppedEntries.length)
833
+ notes.push(`账本顺带清掉 ${pruned.droppedEntries.length} 条已经不在浏览器里的旧账(会话 cookie 随重启消失是最常见的原因)。`);
834
+ if (pruned.cappedBatches.length)
835
+ notes.push(
836
+ `⚠️ 账本超出上限(${LEDGER_MAX_BATCHES} 批 / ${LEDGER_MAX_ENTRIES} 条),丢掉了最老的 ${pruned.cappedBatches.length} 批:` +
837
+ pruned.cappedBatches.map((b) => `${new Date(b.atMs).toLocaleString()} ${(b.domains || []).join("、")}`).join(";") +
838
+ "。这些从此没法用 --release 自动还了,要清只能 --release --all --wipe。"
839
+ );
840
+ return notes.length ? "\n" + notes.join("\n") : null;
841
+ }
842
+
843
+ async function doRelease(launch, PROFILE, args, headless) {
844
+ const ledger = readLedger(PROFILE);
845
+ const total = ledger.batches.reduce((n, b) => n + (b.cookies || []).length, 0);
846
+ if (!total && !args.wipe) {
847
+ console.log(`\n账本是空的,没有借来的东西要还:${ledgerPath(PROFILE)}`);
848
+ return 0;
849
+ }
850
+ const { picked, rest } = selectBatches(ledger, { all: args.all, domains: args.domains });
851
+ const targets = [];
852
+ const seen = new Set();
853
+ for (const b of picked)
854
+ for (const c of b.cookies || []) {
855
+ if (seen.has(cookieKey(c))) continue;
856
+ seen.add(cookieKey(c));
857
+ targets.push(c);
858
+ }
859
+ if (!targets.length && !args.wipe) {
860
+ console.log(`\n账本上没有匹配的条目${args.domains?.length ? `(--domains ${args.domains.join("、")})` : ""},什么都没做。`);
861
+ return 0;
862
+ }
863
+
864
+ const wasRunning = launch.browserStatus().running;
865
+ step(`归还 ${args.wipe ? "(--wipe:清空全部 cookie)" : `${targets.length} 条`} → ${PROFILE}`);
866
+ if (!wasRunning) console.log(" 隔离实例没在跑,先起一个:持久 cookie 在磁盘上,不起浏览器删不掉。");
867
+ const iso = await openIsolated(launch, { headless, label: "还登录态" });
868
+ try {
869
+ if (args.wipe) {
870
+ warn("--wipe:走 Storage.clearCookies,这个 profile 里**你自己手动登录的站点也会被清掉**。");
871
+ await iso.cli.call("browser_cdp", { method: "Storage.clearCookies", params: {}, tabId: iso.tabId });
872
+ } else {
873
+ for (const c of targets)
874
+ await iso.cli.call("browser_cdp", {
875
+ method: "Network.deleteCookies",
876
+ params: { name: c.name, domain: c.domain, path: c.path },
877
+ tabId: iso.tabId,
878
+ });
879
+ }
880
+
881
+ const live = await liveCookieKeys(iso.cli, iso.tabId);
882
+ const stillThere = targets.filter((c) => live.keys.has(cookieKey(c)));
883
+ const gone = targets.filter((c) => !live.keys.has(cookieKey(c)));
884
+ ok(`确认删掉 ${gone.length} 条(读回校验过,不是照抄返回值)`);
885
+ if (stillThere.length) {
886
+ warn(`还有 ${stillThere.length} 条没删掉,账本上给它们留着,下次 --release 还会再试:`);
887
+ for (const c of stillThere) console.log(` · ${c.name} @ ${c.domain}${c.path}`);
888
+ }
889
+
890
+ const keptKeys = new Set(stillThere.map(cookieKey));
891
+ const remaining = {
892
+ version: 1,
893
+ batches: [...rest, ...picked.map((b) => ({ ...b, cookies: (b.cookies || []).filter((c) => keptKeys.has(cookieKey(c))) }))],
894
+ };
895
+ const pruned = pruneLedger(remaining, args.wipe ? new Set() : live.keys);
896
+ writeLedger(PROFILE, pruned.ledger);
897
+ const left = pruned.ledger.batches.reduce((n, b) => n + (b.cookies || []).length, 0);
898
+ console.log(`\n账本上还剩 ${left} 条借来的 cookie。`);
899
+ return stillThere.length ? 1 : 0;
900
+ } finally {
901
+ await closeIso(iso);
902
+ if (!wasRunning) {
903
+ const r = await launch.stopBrowserGracefully();
904
+ console.log(` 为归还起的隔离实例已收掉(${r.how},stopped=${r.stopped})${r.fallbackReason ? ` —— ${r.fallbackReason}` : ""}`);
905
+ } else {
906
+ try {
907
+ launch.markAdoptable();
908
+ } catch {}
909
+ }
910
+ }
911
+ }
912
+
913
+ /*
914
+ * 命令行入口。两个调用方共用它,收尾(删落盘的 cookie 明文)也就只有这一处:
915
+ * · `node scripts/borrow-login.mjs …`——git 检出直接跑这个文件
916
+ * · `npx @liang-hz/agent-in-chrome borrow-login …`——bin 的子命令 import 进来调它
917
+ *
918
+ * @param {string[]} argv 旗标,不含 node 和脚本名
919
+ * @returns 退出码
920
+ */
921
+ export async function runBorrowLogin(argv) {
922
+ try {
923
+ return (await main(argv)) || 0;
924
+ } catch (e) {
925
+ console.error(`\n\x1b[31m✗\x1b[0m ${e?.message || e}\n`);
926
+ return 1;
927
+ } finally {
928
+ dropScratch();
929
+ }
930
+ }
931
+
932
+ const isMain = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
933
+ if (isMain) {
934
+ process.exitCode = await runBorrowLogin(process.argv.slice(2));
935
+ }