@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.
@@ -12,6 +12,20 @@ import { winProc } from "./proc-win.mjs";
12
12
 
13
13
  const STALE_MS = 7 * 24 * 60 * 60 * 1000;
14
14
 
15
+ let wseq = 0;
16
+ export function writeJsonAtomic(file, obj, fs = fsMod) {
17
+ const tmp = `${file}.${process.pid}.${++wseq}.tmp`;
18
+ try {
19
+ fs.writeFileSync(tmp, JSON.stringify(obj), { mode: 0o600 });
20
+ fs.renameSync(tmp, file);
21
+ } catch (e) {
22
+ try {
23
+ fs.unlinkSync(tmp);
24
+ } catch {}
25
+ throw e;
26
+ }
27
+ }
28
+
15
29
  export const pidAlive = (pid) => {
16
30
  if (!Number.isInteger(pid) || pid <= 0) return false;
17
31
  try {
@@ -118,7 +132,7 @@ export function makeInheritor({
118
132
  if (!best) return false;
119
133
  const got = best.name.slice("session-".length, -".json".length);
120
134
  try {
121
- fs.writeFileSync(path.join(dir, best.name), JSON.stringify({ pid, at: now(), id: fingerprint }), { mode: 0o600 });
135
+ writeJsonAtomic(path.join(dir, best.name), { pid, at: now(), id: fingerprint }, fs);
122
136
  } catch {
123
137
  return false;
124
138
  }
@@ -144,7 +158,8 @@ export function makeClaimer({ dir = defaultDataDir(), fs = fsMod, isAlive = pidA
144
158
  for (let slot = 1; slot <= maxSlots; slot++) {
145
159
  const slotKey = slot === 1 ? key : `${key}-${slot}`;
146
160
  const file = path.join(dir, `session-${slotKey}.json`);
147
- const payload = JSON.stringify(fingerprint ? { pid, at: Date.now(), id: fingerprint } : { pid, at: Date.now() });
161
+ const payloadObj = fingerprint ? { pid, at: Date.now(), id: fingerprint } : { pid, at: Date.now() };
162
+ const payload = JSON.stringify(payloadObj);
148
163
  try {
149
164
  fs.writeFileSync(file, payload, { flag: "wx", mode: 0o600 });
150
165
  return slotKey;
@@ -157,7 +172,7 @@ export function makeClaimer({ dir = defaultDataDir(), fs = fsMod, isAlive = pidA
157
172
  } catch {}
158
173
  if (cur && cur.pid !== pid && isAlive(cur.pid)) continue;
159
174
  try {
160
- fs.writeFileSync(file, payload, { mode: 0o600 });
175
+ writeJsonAtomic(file, payloadObj, fs);
161
176
  return slotKey;
162
177
  } catch {
163
178
  return false;
@@ -184,6 +199,13 @@ export function pruneClaims({ dir = defaultDataDir(), fs = fsMod, isAlive = pidA
184
199
  fs.unlinkSync(f);
185
200
  removed++;
186
201
  } catch {
202
+ try {
203
+ const st = fs.statSync(f);
204
+ if (now() - Number(st?.mtimeMs || 0) >= Math.min(STALE_MS, 5 * 60_000)) {
205
+ fs.unlinkSync(f);
206
+ removed++;
207
+ }
208
+ } catch {}
187
209
  }
188
210
  }
189
211
  return removed;
@@ -44,6 +44,7 @@ export const TOOL_TIER = {
44
44
  browser_tab_use: "full",
45
45
  browser_close_tab: "full",
46
46
  browser_eval: "full",
47
+ browser_fetch: "full",
47
48
  browser_cdp: "full",
48
49
  browser_cookies_export: "full",
49
50
  browser_cookies_import: "full",
package/mcp/trace.mjs CHANGED
@@ -238,6 +238,7 @@ export function resolveTraceFile(dir, want) {
238
238
  }
239
239
 
240
240
  export function createTrace({ sessionId, dir = defaultTraceDir(), enabled = true, version = "" } = {}) {
241
+ const resolveSid = () => (typeof sessionId === "function" ? sessionId() : sessionId) || "default";
241
242
  const steps = [];
242
243
  const failedNums = [];
243
244
  let total = 0;
@@ -251,11 +252,12 @@ export function createTrace({ sessionId, dir = defaultTraceDir(), enabled = true
251
252
  if (fileTried || !enabled) return;
252
253
  fileTried = true;
253
254
  try {
255
+ const sid = resolveSid();
254
256
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
255
- file = path.join(dir, fileNameFor(sessionId));
257
+ file = path.join(dir, fileNameFor(sid));
256
258
  fs.writeFileSync(
257
259
  file,
258
- JSON.stringify({ _meta: { session: sessionId, pid: process.pid, startedAt: new Date().toISOString(), version } }) + "\n",
260
+ JSON.stringify({ _meta: { session: sid, pid: process.pid, startedAt: new Date().toISOString(), version } }) + "\n",
259
261
  { mode: 0o600 }
260
262
  );
261
263
  bytes = fs.statSync(file).size;
@@ -271,9 +273,10 @@ export function createTrace({ sessionId, dir = defaultTraceDir(), enabled = true
271
273
  try {
272
274
  const line = JSON.stringify(obj) + "\n";
273
275
  if (bytes + line.length > MAX_FILE_BYTES) {
276
+ const sid = resolveSid();
274
277
  const head =
275
278
  JSON.stringify({
276
- _meta: { session: sessionId, pid: process.pid, compactedAt: new Date().toISOString(), version, dropped },
279
+ _meta: { session: sid, pid: process.pid, compactedAt: new Date().toISOString(), version, dropped },
277
280
  }) + "\n";
278
281
  const body = steps.map((s) => JSON.stringify(s) + "\n").join("");
279
282
  fs.writeFileSync(file, head + body, { mode: 0o600 });
@@ -353,7 +356,7 @@ export function createTrace({ sessionId, dir = defaultTraceDir(), enabled = true
353
356
 
354
357
  function meta() {
355
358
  const m = {
356
- session: sessionId,
359
+ session: resolveSid(),
357
360
  totalSteps: total,
358
361
  kept: steps.length,
359
362
  failedSteps: [...failedNums],
@@ -138,6 +138,9 @@ function authToken() {
138
138
  let sock = null;
139
139
  let sockBuf = "";
140
140
  let reconnectTimer = null;
141
+ let outboundReady = false;
142
+ let outboundQueue = [];
143
+ const OUTBOUND_QUEUE_MAX = 64;
141
144
  let lastExtHello = null;
142
145
  let authWarned = false;
143
146
 
@@ -159,6 +162,12 @@ function toAgent(obj) {
159
162
  }
160
163
  }
161
164
 
165
+ function flushOutbound() {
166
+ while (outboundReady && outboundQueue.length && sock && !sock.destroyed) {
167
+ if (!toAgent(outboundQueue.shift())) break;
168
+ }
169
+ }
170
+
162
171
  let lastDropWhy = null;
163
172
  let dropRepeats = 0;
164
173
  function flushDropRepeats() {
@@ -203,6 +212,10 @@ function connectSocket() {
203
212
  if (sock !== s) return;
204
213
  if (!toAgent(frame)) return;
205
214
  if (lastExtHello) toAgent(lastExtHello);
215
+ if (LEGACY_TOKEN_HELLO_OK) {
216
+ outboundReady = true;
217
+ flushOutbound();
218
+ }
206
219
  };
207
220
  let dropWarned = false;
208
221
 
@@ -220,6 +233,7 @@ function connectSocket() {
220
233
  s.on("connect", () => {
221
234
  sock = s;
222
235
  sockBuf = "";
236
+ outboundReady = false;
223
237
  flushDropRepeats();
224
238
  lastDropWhy = null;
225
239
  reconnectDelay = RECONNECT_MS;
@@ -261,6 +275,8 @@ function connectSocket() {
261
275
  impostor = true;
262
276
  drop("对面拿不出反向证明:占着这个端点的不是主(令牌没有发出去)");
263
277
  }
278
+ outboundReady = true;
279
+ flushOutbound();
264
280
  continue;
265
281
  }
266
282
  if (msg.type === "error" && msg.code === "unauthorized") {
@@ -292,6 +308,7 @@ function connectSocket() {
292
308
  dropped = true;
293
309
  clearTimeout(hsTimer);
294
310
  if (sock === s) sock = null;
311
+ outboundReady = false;
295
312
  s.destroy();
296
313
  noteDrop(why);
297
314
  notifyAgentLink(false);
@@ -344,6 +361,17 @@ function onFromExtension(msg) {
344
361
  }
345
362
  return;
346
363
  }
364
+ if (sock && !sock.destroyed && !outboundReady) {
365
+ if (outboundQueue.length >= OUTBOUND_QUEUE_MAX) {
366
+ const stale = outboundQueue.shift();
367
+ log(
368
+ `握手未完成,出站积压超过 ${OUTBOUND_QUEUE_MAX} 条,丢弃最早的一帧:`,
369
+ stale.type || "无 type"
370
+ );
371
+ }
372
+ outboundQueue.push(msg);
373
+ return;
374
+ }
347
375
  if (!toAgent(msg)) {
348
376
  log("丢弃(agent 未连接):", msg.type, msg.id || "");
349
377
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@liang-hz/agent-in-chrome",
3
- "version": "0.55.2",
3
+ "version": "0.56.0",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "engines": {
@@ -29,6 +29,7 @@ import os from "node:os";
29
29
  import path from "node:path";
30
30
  import { fileURLToPath, pathToFileURL } from "node:url";
31
31
  import { scriptCmd, checkCmd, reinstallCmd } from "../mcp/cli-invocation.mjs";
32
+ import { launcherNeedsShell, cmdq } from "./launcher-spawn.mjs";
32
33
 
33
34
  const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
34
35
 
@@ -296,8 +297,8 @@ export function selectBatches(ledger, { all = false, domains = [] } = {}) {
296
297
  const picked = [];
297
298
  const rest = [];
298
299
  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));
300
+ const hit = (b.cookies || []).filter((c) => domainMatches(c, want));
301
+ const miss = (b.cookies || []).filter((c) => !domainMatches(c, want));
301
302
  if (hit.length) picked.push({ ...b, cookies: hit });
302
303
  if (miss.length) rest.push({ ...b, cookies: miss });
303
304
  }
@@ -307,9 +308,51 @@ export function selectBatches(ledger, { all = false, domains = [] } = {}) {
307
308
  return { picked: last ? [last] : [], rest: last ? batches.slice(0, -1) : [] };
308
309
  }
309
310
 
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;
311
+ const BORROW_PUBLIC_MULTI_SUFFIXES = new Set([
312
+ "github.io",
313
+ "gitlab.io",
314
+ "pages.dev",
315
+ "workers.dev",
316
+ "netlify.app",
317
+ "vercel.app",
318
+ "herokuapp.com",
319
+ "appspot.com",
320
+ "cloudfront.net",
321
+ "onrender.com",
322
+ ]);
323
+
324
+ function isPublicSuffixLike(domainKey) {
325
+ const labels = String(domainKey || "").replace(/^\./, "").toLowerCase().split(".").filter(Boolean);
326
+ if (labels.length < 2) return true;
327
+ if (
328
+ labels.length === 2 &&
329
+ labels[1].length === 2 &&
330
+ /^(com|net|org|gov|edu|ac|co|mil|ne|or|go|gr|ad)$/.test(labels[0])
331
+ ) {
332
+ return true;
333
+ }
334
+ return BORROW_PUBLIC_MULTI_SUFFIXES.has(labels.join("."));
335
+ }
336
+
337
+ export function domainMatches(cookieOrDomain, wantSet) {
338
+ const rawDomain =
339
+ typeof cookieOrDomain === "object" && cookieOrDomain !== null
340
+ ? String(cookieOrDomain.domain || "")
341
+ : String(cookieOrDomain || "");
342
+ const hostOnly =
343
+ typeof cookieOrDomain === "object" && cookieOrDomain !== null ? cookieOrDomain.hostOnly === true : false;
344
+ const d = rawDomain.replace(/^\./, "").toLowerCase();
345
+ if (!d) return false;
346
+ for (const w of wantSet) {
347
+ const h = String(w || "").replace(/^\./, "").toLowerCase();
348
+ if (!h) continue;
349
+ if (hostOnly) {
350
+ if (d === h) return true;
351
+ continue;
352
+ }
353
+ if (d === h || d.endsWith("." + h)) return true;
354
+ if (rawDomain.startsWith(".") && !isPublicSuffixLike(d) && h.endsWith("." + d)) return true;
355
+ }
313
356
  return false;
314
357
  }
315
358
 
@@ -394,13 +437,16 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
394
437
  function bridgeServerCmd() {
395
438
  const override = process.env.AGENT_IN_CHROME_BORROW_SERVER;
396
439
  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");
440
+ const installed = path.join(os.homedir(), ".agent-in-chrome", "agent-in-chrome", process.platform === "win32" ? "mcp-launcher.bat" : "mcp-launcher.sh");
398
441
  if (fs.existsSync(installed)) return [installed, []];
399
442
  return [process.execPath, [path.join(ROOT, "mcp", "server.mjs")]];
400
443
  }
401
444
 
402
445
  function mcpClient(cmd, args, env, label) {
403
- const p = spawn(cmd, args, { stdio: ["pipe", "pipe", "pipe"], env });
446
+ const p =
447
+ launcherNeedsShell(cmd)
448
+ ? spawn(cmdq(cmd), { stdio: ["pipe", "pipe", "pipe"], env, shell: true, windowsHide: true })
449
+ : spawn(cmd, args, { stdio: ["pipe", "pipe", "pipe"], env });
404
450
  let errText = "";
405
451
  p.stderr.setEncoding("utf8");
406
452
  p.stderr.on("data", (c) => {
@@ -1,8 +1,8 @@
1
- import { spawn } from "node:child_process";
2
1
  import os from "node:os";
3
2
  import path from "node:path";
4
3
  import fs from "node:fs";
5
4
  import { pathToFileURL } from "node:url";
5
+ import { defaultMcpLauncher, spawnMcpLauncher } from "./launcher-spawn.mjs";
6
6
 
7
7
  export const E2E_PREFIX = "e2e-";
8
8
 
@@ -69,9 +69,8 @@ function pidAlive(pid) {
69
69
 
70
70
  function sweepClient(sessionId) {
71
71
  const launcher =
72
- process.env.AGENT_IN_CHROME_E2E_LAUNCHER ||
73
- path.join(os.homedir(), ".agent-in-chrome", "agent-in-chrome", "mcp-launcher.sh");
74
- const p = spawn(launcher, [], {
72
+ process.env.AGENT_IN_CHROME_E2E_LAUNCHER || defaultMcpLauncher();
73
+ const p = spawnMcpLauncher(launcher, {
75
74
  stdio: ["pipe", "pipe", "pipe"],
76
75
  env: { ...process.env, AGENT_IN_CHROME_SESSION_ID: sessionId },
77
76
  });