@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.
package/extension/sw.js CHANGED
@@ -9,7 +9,7 @@
9
9
  // 所有 browser_* 工具的实现都在这个文件里(工具表见 TOOLS)。
10
10
 
11
11
  const HOST_NAME = "org.liangai.agent_in_chrome";
12
- const VERSION = "0.55.2";
12
+ const VERSION = "0.56.0";
13
13
  /* 这个 service worker 实例是什么时候起来的(= 磁盘上的代码是什么时候读进来的),见 hello */
14
14
  const SW_BOOTED_AT = Date.now();
15
15
  /* agent 开的标签页统一收进这一组,跟用户自己的标签页视觉隔离 */
@@ -493,6 +493,46 @@ function cookieDomainKey(d) {
493
493
  */
494
494
  const cookieGrantCovers = (g, d) => d === g || d.endsWith("." + g);
495
495
 
496
+ const PUBLIC_MULTI_SUFFIXES = new Set([
497
+ "github.io",
498
+ "gitlab.io",
499
+ "pages.dev",
500
+ "workers.dev",
501
+ "netlify.app",
502
+ "vercel.app",
503
+ "herokuapp.com",
504
+ "appspot.com",
505
+ "cloudfront.net",
506
+ "onrender.com",
507
+ ]);
508
+
509
+ function isPublicSuffixLike(domainKey) {
510
+ const d = cookieDomainKey(domainKey);
511
+ if (!d) return true;
512
+ const labels = d.split(".").filter(Boolean);
513
+ if (labels.length < 2) return true;
514
+ if (
515
+ labels.length === 2 &&
516
+ labels[1].length === 2 &&
517
+ /^(com|net|org|gov|edu|ac|co|mil|ne|or|go|gr|ad)$/.test(labels[0])
518
+ ) {
519
+ return true;
520
+ }
521
+ return PUBLIC_MULTI_SUFFIXES.has(d);
522
+ }
523
+
524
+ function cookieSentToHost(cookie, targetHost) {
525
+ const h = cookieDomainKey(targetHost);
526
+ if (!h) return false;
527
+ const rawDomain = String(cookie?.domain || "");
528
+ const d = cookieDomainKey(rawDomain);
529
+ if (!d) return false;
530
+ if (cookie?.hostOnly === true) return d === h;
531
+ if (d === h || d.endsWith("." + h)) return true;
532
+ if (rawDomain.startsWith(".") && !isPublicSuffixLike(d) && h.endsWith("." + d)) return true;
533
+ return false;
534
+ }
535
+
496
536
  /*
497
537
  * 敏感域:只给一次性授权,永不进长期名单。
498
538
  *
@@ -644,7 +684,7 @@ async function cookieLoanGate(cookies, sid) {
644
684
  tooMany
645
685
  ? `凭据借出被拒:这次要导出 ${missing.length} 个域的登录态明文,一次申请不了这么多(上限 ${ASK_PER_CALL_MAX} 个)。` +
646
686
  `一次点击授权掉整个浏览器的登录态,正是这道闸首先要防的事,所以没有「全部允许」这个选项。` +
647
- `涉及的域列在下面,挑出你这次任务真正需要的那几个,用 domains 参数点名再重来:` +
687
+ `涉及的域列在下面,挑出你这次任务真正需要的那几个(或直接传入实际访问的具体子域名,如 app.example.com——祖先域 SSO cookie 会自动随同匹配),用 domains 参数点名再重来:` +
648
688
  `${shown.join("、")}${more}。`
649
689
  : `凭据借出被拒:${shown.join("、")}${more} 不在用户的授权名单里,一条 cookie 都没有导出。` +
650
690
  `cookie 明文等价于可直接冒用的完整登录态,所以默认拒绝,授权只能由用户本人点。` +
@@ -2495,6 +2535,8 @@ chrome.tabs.onCreated.addListener(async (tab) => {
2495
2535
  });
2496
2536
 
2497
2537
  const BODY_MAX = 200_000;
2538
+ const HARD_DETAIL_BODY = 5_000_000;
2539
+ const HARD_FETCH_MAX = 10_000_000;
2498
2540
  const AUTO_BODY_TYPES = new Set(["XHR", "Fetch", "EventSource", "WebSocket"]);
2499
2541
  const RAW_HEADERS_WAIT_MS = 250;
2500
2542
 
@@ -2557,6 +2599,64 @@ function bodyRedactNote(hits) {
2557
2599
  return `报文体里 ${hits.length} 处凭据已打码(${names})。确需原文传 revealSecrets:true——那份别外发。`;
2558
2600
  }
2559
2601
 
2602
+ function redactText(str) {
2603
+ if (typeof str !== "string" || !str) return String(str || "");
2604
+ let out = str;
2605
+ out = out.replace(/((?:Proxy-)?Authorization\s*:\s*)([^\r\n]+)/gi, (_, pre, v) => `${pre}<已打码 ${v.length} 字符>`);
2606
+ out = out.replace(/((?:Set-)?Cookie\s*:\s*)([^\r\n]+)/gi, (_, pre, v) => `${pre}<已打码 ${v.length} 字符>`);
2607
+ out = out.replace(
2608
+ /\b(Bearer|Basic)\s+([A-Za-z0-9\-._~+/=]{4,})/gi,
2609
+ (_, scheme, tok) => `${scheme} <已打码 ${tok.length} 字符>`
2610
+ );
2611
+ out = redactBody(out, false).text;
2612
+ return out;
2613
+ }
2614
+
2615
+ const SECRET_QUERY_KEY =
2616
+ /^(?:token|access_token|refresh_token|id_token|auth|secret|api[-_]?key|password|session|sid|ticket|sig|signature|code)$/i;
2617
+
2618
+ function redactUrlQuery(rawUrl) {
2619
+ const s = String(rawUrl || "");
2620
+ try {
2621
+ const u = new URL(s);
2622
+ for (const [k, v] of [...u.searchParams.entries()]) {
2623
+ if (SECRET_HEADER.test(k) || SECRET_QUERY_KEY.test(k) || redactText(v) !== v) {
2624
+ u.searchParams.set(k, "[REDACTED]");
2625
+ }
2626
+ }
2627
+ const out = (u.origin + u.pathname + u.search + u.hash).replace(/%5BREDACTED%5D/g, "[REDACTED]");
2628
+ return out.length > 120 ? out.slice(0, 120) + "…" : out;
2629
+ } catch {
2630
+ const out = redactText(s);
2631
+ return out.length > 120 ? out.slice(0, 120) + "…" : out;
2632
+ }
2633
+ }
2634
+
2635
+ function matchWaitUrl(rawUrl, needle) {
2636
+ const raw = String(rawUrl || "");
2637
+ const n = String(needle || "");
2638
+ if (!n) return { matched: true, inQueryOnly: null };
2639
+ if (/[?&=#]/.test(n)) return { matched: raw.includes(n), inQueryOnly: null };
2640
+ let base;
2641
+ let queryDecoded = "";
2642
+ try {
2643
+ const u = new URL(raw);
2644
+ base = u.origin + u.pathname;
2645
+ try {
2646
+ queryDecoded = decodeURIComponent(u.search || "");
2647
+ } catch {
2648
+ queryDecoded = u.search || "";
2649
+ }
2650
+ } catch {
2651
+ const idx = raw.search(/[?#]/);
2652
+ base = idx >= 0 ? raw.slice(0, idx) : raw;
2653
+ queryDecoded = idx >= 0 ? raw.slice(idx) : "";
2654
+ }
2655
+ if (base.includes(n)) return { matched: true, inQueryOnly: null };
2656
+ const inQuery = raw.includes(n) || queryDecoded.includes(n);
2657
+ return { matched: false, inQueryOnly: inQuery ? base : null };
2658
+ }
2659
+
2560
2660
  const WS_FRAME_MAX = 200;
2561
2661
  const WS_PAYLOAD_MAX = 20_000;
2562
2662
 
@@ -2978,26 +3078,44 @@ async function wakeTab(tabId) {
2978
3078
  * 探针(inPage)走的都是单帧默认注入——不一起防住,卡点只是往后挪了一步。
2979
3079
  */
2980
3080
  async function injectStaged(opts) {
2981
- const idle = chrome.scripting.executeScript(opts);
2982
- const PENDING = {};
2983
- let timer;
2984
- const first = await Promise.race([
2985
- idle,
2986
- new Promise((r) => {
2987
- timer = setTimeout(() => r(PENDING), IDLE_INJECT_MS);
2988
- }),
2989
- ]).finally(() => clearTimeout(timer));
2990
- if (first !== PENDING) return { res: first, degraded: false };
2991
- Promise.resolve(idle).catch(() => {});
2992
- await wakeTab(opts.target?.tabId);
2993
- const res = await deadline(
2994
- chrome.scripting.executeScript({ ...opts, injectImmediately: true }),
2995
- IMMEDIATE_INJECT_MS,
2996
- `页面注入 ${IDLE_INJECT_MS + IMMEDIATE_INJECT_MS}ms 没有回执(等帧就绪、立即注入两条路都试过了):` +
2997
- `这张标签页的注入路卡死了,重试大概率还是它。用 browser_new_tab 开一张新的、地址照旧,在新页上重来;` +
2998
- `这张页也没全废——browser_eval 走 CDP,仍然读得到东西。`
2999
- );
3000
- return { res, degraded: true };
3081
+ const tabId = opts.target?.tabId;
3082
+ let wakePending = null;
3083
+ const pulseWake = () => {
3084
+ if (tabId == null) return Promise.resolve();
3085
+ if (!wakePending) {
3086
+ wakePending = wakeTab(tabId)
3087
+ .catch(() => {})
3088
+ .finally(() => {
3089
+ wakePending = null;
3090
+ });
3091
+ }
3092
+ return wakePending;
3093
+ };
3094
+ const heartbeat = tabId == null ? null : setInterval(() => void pulseWake(), EVAL_WAKE_MS);
3095
+ try {
3096
+ const idle = chrome.scripting.executeScript(opts);
3097
+ const PENDING = {};
3098
+ let timer;
3099
+ const first = await Promise.race([
3100
+ idle,
3101
+ new Promise((r) => {
3102
+ timer = setTimeout(() => r(PENDING), IDLE_INJECT_MS);
3103
+ }),
3104
+ ]).finally(() => clearTimeout(timer));
3105
+ if (first !== PENDING) return { res: first, degraded: false };
3106
+ Promise.resolve(idle).catch(() => {});
3107
+ await pulseWake();
3108
+ const res = await deadline(
3109
+ chrome.scripting.executeScript({ ...opts, injectImmediately: true }),
3110
+ IMMEDIATE_INJECT_MS,
3111
+ `页面注入 ${IDLE_INJECT_MS + IMMEDIATE_INJECT_MS}ms 没有回执(等帧就绪、立即注入两条路都试过了):` +
3112
+ `这张标签页的注入路卡死了,重试大概率还是它。用 browser_new_tab 开一张新的、地址照旧,在新页上重来;` +
3113
+ `这张页也没全废——browser_eval 走 CDP,仍然读得到东西。`
3114
+ );
3115
+ return { res, degraded: true };
3116
+ } finally {
3117
+ if (heartbeat !== null) clearInterval(heartbeat);
3118
+ }
3001
3119
  }
3002
3120
 
3003
3121
  /*
@@ -3162,7 +3280,7 @@ function cursorAgent(op, A) {
3162
3280
  A = {
3163
3281
  x: Math.round((window.innerWidth || 0) / 2),
3164
3282
  y: Math.round((window.innerHeight || 0) * 0.4),
3165
- travelMs: 1,
3283
+ travelMs: 0,
3166
3284
  kind: "move",
3167
3285
  idle: true,
3168
3286
  };
@@ -3288,7 +3406,8 @@ function cursorAgent(op, A) {
3288
3406
 
3289
3407
  const kind = String((A && A.kind) || "move");
3290
3408
  const label = A && A.label ? String(A.label).slice(0, 40) : "";
3291
- const travel = Math.max(0, Math.min(600, Number(A && A.travelMs) || 120));
3409
+ const travel =
3410
+ A && A.travelMs != null ? Math.max(0, Math.min(600, Number(A.travelMs) || 0)) : 0;
3292
3411
 
3293
3412
  w.className = "w";
3294
3413
  void w.offsetWidth;
@@ -3947,10 +4066,21 @@ function pageAgent(op, arg) {
3947
4066
  let b = box(el);
3948
4067
  let scrolled = false;
3949
4068
  const offscreen = (r) => r.x + r.w <= 0 || r.y + r.h <= 0 || r.x >= vw || r.y >= vh;
4069
+ const SLIVER_MIN_PX = 6;
4070
+ const sliver = (r) => {
4071
+ if (r.x < 0 && r.x + r.w > 0 && r.x + r.w < SLIVER_MIN_PX) return true;
4072
+ if (r.x < vw && r.x + r.w > vw && vw - r.x < SLIVER_MIN_PX) return true;
4073
+ if (r.y < 0 && r.y + r.h > 0 && r.y + r.h < SLIVER_MIN_PX) return true;
4074
+ if (r.y < vh && r.y + r.h > vh && vh - r.y < SLIVER_MIN_PX) return true;
4075
+ return false;
4076
+ };
3950
4077
  if (el.scrollIntoView) {
3951
4078
  if (offscreen(b)) {
3952
4079
  scrolled = scrollIn(el, "center");
3953
4080
  b = box(el);
4081
+ } else if (sliver(b)) {
4082
+ scrolled = scrollIn(el, "center") || scrolled;
4083
+ b = box(el);
3954
4084
  } else {
3955
4085
  const c0 = clipperOf(el);
3956
4086
  if (c0 && c0.canScroll) {
@@ -4030,6 +4160,7 @@ function pageAgent(op, arg) {
4030
4160
  return {
4031
4161
  code: "occluded",
4032
4162
  msg: blocker ? `被 ${desc(blocker)} 挡住` : sawAny ? "命中的是别的元素" : "该位置命中不到任何元素(可能整块区域被裁掉了)",
4163
+ blockerClass: blocker ? String((blocker.getAttribute && blocker.getAttribute("class")) || blocker.className || "") : "",
4033
4164
  scrolled,
4034
4165
  };
4035
4166
  };
@@ -4150,6 +4281,31 @@ function pageAgent(op, arg) {
4150
4281
  w.fn = null;
4151
4282
  };
4152
4283
 
4284
+ const snapState = (target) => {
4285
+ try {
4286
+ if (!target) return null;
4287
+ return {
4288
+ expanded: target.getAttribute?.("aria-expanded") ?? null,
4289
+ state: target.getAttribute?.("data-state") ?? null,
4290
+ selected: target.getAttribute?.("aria-selected") ?? null,
4291
+ checked: target.getAttribute?.("aria-checked") ?? null,
4292
+ pressed: target.getAttribute?.("aria-pressed") ?? null,
4293
+ open: typeof target.hasAttribute === "function" ? target.hasAttribute("open") : false,
4294
+ };
4295
+ } catch {
4296
+ return null;
4297
+ }
4298
+ };
4299
+ const countPopups = () => {
4300
+ try {
4301
+ return document.querySelectorAll(
4302
+ '[role="listbox"],[role="menu"],[role="dialog"],[data-radix-popper-content-wrapper],[data-state="open"]'
4303
+ ).length;
4304
+ } catch {
4305
+ return 0;
4306
+ }
4307
+ };
4308
+
4153
4309
  if (A.arm) {
4154
4310
  detach();
4155
4311
  w.armed = true;
@@ -4157,6 +4313,8 @@ function pageAgent(op, arg) {
4157
4313
  w.elsewhere = [];
4158
4314
  const el = (W.__aicRefs || [])[Number(A.idx) - 1] || null;
4159
4315
  if (!el) return { ok: false };
4316
+ w.beforeState = snapState(el);
4317
+ w.beforePopups = countPopups();
4160
4318
  const fn = (e) => {
4161
4319
  if (!w.armed || w.onTarget.length >= 8) return;
4162
4320
  w.onTarget.push(e && e.type);
@@ -4172,8 +4330,25 @@ function pageAgent(op, arg) {
4172
4330
  }
4173
4331
 
4174
4332
  w.armed = false;
4333
+ let stateChanged = false;
4334
+ if (w.beforeState && w.el) {
4335
+ const afterState = snapState(w.el);
4336
+ if (afterState) {
4337
+ for (const k of ["expanded", "state", "selected", "checked", "pressed", "open"]) {
4338
+ if (afterState[k] !== w.beforeState[k]) {
4339
+ stateChanged = true;
4340
+ break;
4341
+ }
4342
+ }
4343
+ }
4344
+ }
4345
+ if (!stateChanged && typeof w.beforePopups === "number" && countPopups() > w.beforePopups) {
4346
+ stateChanged = true;
4347
+ }
4348
+ w.beforeState = null;
4349
+ w.beforePopups = 0;
4175
4350
  detach();
4176
- const out = { ok: true, onTarget: w.onTarget.slice(), elsewhere: w.elsewhere.slice(), url: location.href };
4351
+ const out = { ok: true, onTarget: w.onTarget.slice(), elsewhere: w.elsewhere.slice(), url: location.href, stateChanged };
4177
4352
  w.onTarget = [];
4178
4353
  w.elsewhere = [];
4179
4354
  return out;
@@ -4205,7 +4380,7 @@ function pageAgent(op, arg) {
4205
4380
  const res = actionable(el, !!A.force);
4206
4381
  const rb = box(el);
4207
4382
  const nowBox = [Math.round(rb.x), Math.round(rb.y), Math.round(rb.w), Math.round(rb.h)];
4208
- if (!res.ok) return { error: failMsg(A.ref, el, res), code: res.code, box: nowBox };
4383
+ if (!res.ok) return { error: failMsg(A.ref, el, res), code: res.code, blockerClass: res.blockerClass || "", box: nowBox };
4209
4384
 
4210
4385
  const chain = frameChain(res.x, res.y, !A.force);
4211
4386
  if (chain.blocked) {
@@ -4548,7 +4723,7 @@ function pageAgent(op, arg) {
4548
4723
  const wantText = Number(A.maxText);
4549
4724
  const maxText = Math.max(0, Number.isFinite(wantText) ? wantText : 20000);
4550
4725
  const wantTextOff = isTopFrame ? Number(A.textOffset) : 0;
4551
- const textOffset = Math.max(0, Number.isFinite(wantTextOff) ? wantTextOff : 0);
4726
+ const rawTextOff = Number.isFinite(wantTextOff) ? Math.trunc(wantTextOff) : 0;
4552
4727
  const textRoot = containerSel ? containerEl : document.body;
4553
4728
  let raw = "";
4554
4729
  try {
@@ -4561,6 +4736,7 @@ function pageAgent(op, arg) {
4561
4736
  if (t.length >= 2) raw = raw.split(t).join(`(可编辑的凭据字段,${t.length} 字符,值已隐去)`);
4562
4737
  }
4563
4738
  } catch {}
4739
+ const textOffset = rawTextOff < 0 ? Math.max(0, raw.length + rawTextOff) : Math.max(0, rawTextOff);
4564
4740
  return {
4565
4741
  ...base,
4566
4742
  scroll: {
@@ -4577,7 +4753,7 @@ function pageAgent(op, arg) {
4577
4753
  ...(containerInvalid ? { containerInvalid: true } : {}),
4578
4754
  text: raw.slice(textOffset, textOffset + maxText),
4579
4755
  textTotal: raw.length,
4580
- ...(textOffset ? { textOffset } : {}),
4756
+ ...(textOffset || rawTextOff < 0 ? { textOffset } : {}),
4581
4757
  textTruncated: raw.length > textOffset + maxText,
4582
4758
  };
4583
4759
  }
@@ -5094,6 +5270,12 @@ async function cdpClearHit(tabId, mark, { sessionId = null } = {}) {
5094
5270
  }).catch(() => {});
5095
5271
  }
5096
5272
 
5273
+ function isTransientLoaderText(str) {
5274
+ return /\b(?:el-loading-mask|el-loading-spinner|ant-spin|ant-spin-spinning|loading-mask|loading-spinner)\b|aria-busy=["']?true/i.test(
5275
+ String(str || "")
5276
+ );
5277
+ }
5278
+
5097
5279
  async function cdpResolveNode(tabId, handle, { force = false, label = null } = {}) {
5098
5280
  const h = typeof handle === "number" ? { backendNodeId: handle, targetId: null } : handle;
5099
5281
  const backendNodeId = h.backendNodeId;
@@ -5153,6 +5335,7 @@ async function cdpResolveNode(tabId, handle, { force = false, label = null } = {
5153
5335
  );
5154
5336
  }
5155
5337
  if (!force) {
5338
+ await new Promise((s) => setTimeout(s, SETTLE_GAP_MS));
5156
5339
  const again = await cdpCenter(tabId, backendNodeId, { sessionId });
5157
5340
  if (again && (Math.abs(again.x - c.x) > 2 || Math.abs(again.y - c.y) > 2)) {
5158
5341
  await new Promise((s) => setTimeout(s, SETTLE_GAP_MS));
@@ -5172,7 +5355,13 @@ async function cdpResolveNode(tabId, handle, { force = false, label = null } = {
5172
5355
  }
5173
5356
 
5174
5357
  const hitCtx = { sessionId };
5175
- const hit = force ? { ok: true } : await cdpHitCheck(tabId, backendNodeId, c.x, c.y, hitCtx, { sessionId });
5358
+ let hit = force ? { ok: true } : await cdpHitCheck(tabId, backendNodeId, c.x, c.y, hitCtx, { sessionId });
5359
+ if (!force && !hit.ok && hit.kind !== "nohit" && isTransientLoaderText(hit.blocker)) {
5360
+ for (let lr = 0; lr < 2 && !hit.ok && hit.kind !== "nohit" && isTransientLoaderText(hit.blocker); lr++) {
5361
+ await new Promise((s) => setTimeout(s, 250));
5362
+ hit = await cdpHitCheck(tabId, backendNodeId, c.x, c.y, hitCtx, { sessionId });
5363
+ }
5364
+ }
5176
5365
  if (!hit.ok && hit.kind === "nohit") {
5177
5366
  if (!vp) vp = await cdpViewport(tabId, { sessionId });
5178
5367
  const outside = vp && (c.x < 0 || c.y < 0 || c.x >= vp.w || c.y >= vp.h);
@@ -5196,7 +5385,13 @@ async function cdpResolveNode(tabId, handle, { force = false, label = null } = {
5196
5385
  }
5197
5386
  if (!force && ownerBackendNodeId != null) {
5198
5387
  const oc = await cdpCenter(tabId, ownerBackendNodeId);
5199
- const ohit = oc ? await cdpHitCheck(tabId, ownerBackendNodeId, oc.x, oc.y) : null;
5388
+ let ohit = oc ? await cdpHitCheck(tabId, ownerBackendNodeId, oc.x, oc.y) : null;
5389
+ if (oc && ohit && !ohit.ok && ohit.kind !== "nohit" && isTransientLoaderText(ohit.blocker)) {
5390
+ for (let lr = 0; lr < 2 && ohit && !ohit.ok && ohit.kind !== "nohit" && isTransientLoaderText(ohit.blocker); lr++) {
5391
+ await new Promise((s) => setTimeout(s, 250));
5392
+ ohit = await cdpHitCheck(tabId, ownerBackendNodeId, oc.x, oc.y);
5393
+ }
5394
+ }
5200
5395
  if (oc && ohit && !ohit.ok && ohit.kind !== "nohit") {
5201
5396
  throw new Error(
5202
5397
  `不可操作(occluded):${shown} <${tag}> ${name} 本身在那个跨进程 iframe 里没被挡,` +
@@ -5716,6 +5911,7 @@ async function resolveRef(tabId, ref, { force = false, label = null } = {}) {
5716
5911
  let r = null;
5717
5912
  let moveFrom = null;
5718
5913
  let moveTo = null;
5914
+ let loaderRetries = 0;
5719
5915
  for (let attempt = 0; ; attempt++) {
5720
5916
  try {
5721
5917
  r = await inFrame(tabId, p.frameId, pageAgent, ["resolve", { ref: shown, idx: p.idx, force: !!force }]);
@@ -5728,6 +5924,11 @@ async function resolveRef(tabId, ref, { force = false, label = null } = {}) {
5728
5924
  if (!r) {
5729
5925
  throw new Error(`${shown} 所在的帧没有返回结果,可能刚刚导航或被移除。重新 browser_read_page。`);
5730
5926
  }
5927
+ if (!force && r.code === "occluded" && loaderRetries < 2 && (isTransientLoaderText(r.error) || isTransientLoaderText(r.blockerClass))) {
5928
+ loaderRetries++;
5929
+ await new Promise((s) => setTimeout(s, 250));
5930
+ continue;
5931
+ }
5731
5932
  if (force || !r.box) break;
5732
5933
 
5733
5934
  await new Promise((s) => setTimeout(s, SETTLE_GAP_MS));
@@ -5786,7 +5987,11 @@ async function resolveRef(tabId, ref, { force = false, label = null } = {}) {
5786
5987
  );
5787
5988
  }
5788
5989
  if (!force && viaParent) {
5789
- const blocker = await crossFrameHitCheck(tabId, p.frameId, p.idx, x, y, chainOf(geoUsed, p.frameId));
5990
+ let blocker = await crossFrameHitCheck(tabId, p.frameId, p.idx, x, y, chainOf(geoUsed, p.frameId));
5991
+ for (let lr = 0; lr < 2 && blocker && isTransientLoaderText(blocker); lr++) {
5992
+ await new Promise((s) => setTimeout(s, 250));
5993
+ blocker = await crossFrameHitCheck(tabId, p.frameId, p.idx, x, y, chainOf(geoUsed, p.frameId));
5994
+ }
5790
5995
  if (blocker) {
5791
5996
  throw new Error(
5792
5997
  `不可操作(occluded):${shown} <${r.tag}> ${r.name} 在跨源 iframe(${r.frameUrl || "地址未知"})里,` +
@@ -6032,7 +6237,16 @@ async function requireTarget(sid, tabId) {
6032
6237
  if (owner === sid) return id;
6033
6238
  if (owner !== undefined)
6034
6239
  throw new Error(`标签页 ${id} 归另一个 agent 会话(${owner})管,别去抢。用 browser_new_tab 开自己的。`);
6240
+ const liveTab = await chrome.tabs.get(id).catch(() => null);
6035
6241
  const held = heldTabs(sid);
6242
+ if (liveTab) {
6243
+ throw new Error(
6244
+ `标签页 ${id} 不在本会话持有的标签页里(它是用户当前开着的标签页,${liveTab.url || ""}),什么都没做。` +
6245
+ `默认请用 browser_new_tab({url: ${JSON.stringify(liveTab.url || "")}}) 开副本;` +
6246
+ `仅在用户明确要求操作这张现有页时调 browser_tab_use({tabId: ${id}, takeover: true}) 接管。` +
6247
+ (held.length ? `\n本会话现在持有 ${held.length} 个:\n${listTabs(held)}` : "")
6248
+ );
6249
+ }
6036
6250
  throw new Error(
6037
6251
  `标签页 ${id} 不在本会话持有的标签页里(可能已经关掉或放开了),什么都没做。` +
6038
6252
  (held.length
@@ -6858,6 +7072,12 @@ async function clickVerified(tabId, frameId, idx, x, y, opts = {}) {
6858
7072
  }
6859
7073
  const leftClick = (opts.button || "left") === "left";
6860
7074
  if (hitTarget && leftClick && !onTarget.includes("click")) {
7075
+ if (seen.stateChanged === true) {
7076
+ return markEventsSeen({
7077
+ verified: "hit",
7078
+ verifyNote: "目标响应了 pointerdown 并切换了交互/浮层状态(未产生 click,常见于 Radix 等组件)。",
7079
+ });
7080
+ }
6861
7081
  throw new Error(
6862
7082
  `按下落在了目标上,但浏览器没有合成 click 事件——按下和抬起之间目标动了,页面不会把它当成一次点击。` +
6863
7083
  `页面**没有**按你的意图被操作。等它停稳再点(browser_wait_for 的 js 参数),` +
@@ -6986,6 +7206,13 @@ function markFileInputInPage(ref, selector, token) {
6986
7206
  fired[token] = { change: false, input: false };
6987
7207
  const onChange = () => {
6988
7208
  fired[token].change = true;
7209
+ try {
7210
+ fired[token].filesAtChange = [...el.files].map((f) => ({
7211
+ name: f.name,
7212
+ size: f.size,
7213
+ type: f.type || "",
7214
+ }));
7215
+ } catch {}
6989
7216
  };
6990
7217
  const onInput = () => {
6991
7218
  fired[token].input = true;
@@ -7034,11 +7261,28 @@ function readFileInputInPage(token) {
7034
7261
  };
7035
7262
  el = walk(document);
7036
7263
  }
7037
- if (!el)
7264
+ if (!el) {
7265
+ const caught = fired.filesAtChange;
7266
+ if (caught) {
7267
+ try {
7268
+ delete regs[token];
7269
+ } catch {}
7270
+ try {
7271
+ delete firedAll[token];
7272
+ } catch {}
7273
+ return {
7274
+ files: caught,
7275
+ count: caught.length,
7276
+ changeFired: nativeChange,
7277
+ inputFired: nativeInput,
7278
+ elementReplaced: true,
7279
+ };
7280
+ }
7038
7281
  return {
7039
7282
  error:
7040
7283
  "上传目标在设置过程中从页面上消失了(页面可能重新渲染或导航过)。重新 browser_read_page 后再试一次。",
7041
7284
  };
7285
+ }
7042
7286
 
7043
7287
  const files = [];
7044
7288
  try {
@@ -7888,6 +8132,76 @@ async function scanDialogsDiff(tabId, url) {
7888
8132
 
7889
8133
  // ------------------------------------------------------------------- 工具集
7890
8134
 
8135
+ function couldBeUninvokedFunction(expr) {
8136
+ let s = String(expr || "").trim();
8137
+ for (;;) {
8138
+ const before = s;
8139
+ s = s.replace(/^\s*(?:\/\/[^\n]*\n?|\/\*[\s\S]*?\*\/\s*)+/, "").trim();
8140
+ if (s.startsWith("(") && s.endsWith(")")) {
8141
+ let depth = 0;
8142
+ let inStr = null;
8143
+ let esc = false;
8144
+ let wrapsAll = true;
8145
+ for (let i = 0; i < s.length; i++) {
8146
+ const ch = s[i];
8147
+ if (esc) {
8148
+ esc = false;
8149
+ continue;
8150
+ }
8151
+ if (inStr) {
8152
+ if (ch === "\\") esc = true;
8153
+ else if (ch === inStr) inStr = null;
8154
+ continue;
8155
+ }
8156
+ if (ch === "'" || ch === '"' || ch === "`") {
8157
+ inStr = ch;
8158
+ continue;
8159
+ }
8160
+ if (ch === "(") depth++;
8161
+ else if (ch === ")") {
8162
+ depth--;
8163
+ if (depth === 0 && i < s.length - 1) {
8164
+ wrapsAll = false;
8165
+ break;
8166
+ }
8167
+ }
8168
+ }
8169
+ if (wrapsAll && depth === 0) s = s.slice(1, -1).trim();
8170
+ }
8171
+ if (s === before) break;
8172
+ }
8173
+ const noAsync = s.replace(/^async\s+/, "");
8174
+ if (noAsync.startsWith("(")) {
8175
+ let depth = 0;
8176
+ let inStr = null;
8177
+ let esc = false;
8178
+ let closeIdx = -1;
8179
+ for (let i = 0; i < noAsync.length; i++) {
8180
+ const ch = noAsync[i];
8181
+ if (esc) { esc = false; continue; }
8182
+ if (inStr) {
8183
+ if (ch === "\\") esc = true;
8184
+ else if (ch === inStr) inStr = null;
8185
+ continue;
8186
+ }
8187
+ if (ch === "'" || ch === '"' || ch === "`") { inStr = ch; continue; }
8188
+ if (ch === "(") depth++;
8189
+ else if (ch === ")") {
8190
+ depth--;
8191
+ if (depth === 0) { closeIdx = i; break; }
8192
+ }
8193
+ }
8194
+ if (closeIdx > 0) {
8195
+ const rest = noAsync.slice(closeIdx + 1).trim();
8196
+ return rest.startsWith("=>");
8197
+ }
8198
+ }
8199
+ if (/^(?:async\s+)?[A-Za-z_$][\w$]*\s*=>/.test(s)) return true;
8200
+ if (/^(?:async\s+)?function\b/.test(s)) return true;
8201
+ if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/.test(s)) return true;
8202
+ return false;
8203
+ }
8204
+
7891
8205
  const TOOLS = {
7892
8206
  // 报本会话现在持有哪些标签页、连接状态,以及别的会话手上占着哪些页。
7893
8207
  async status(_args, sid) {
@@ -7960,19 +8274,35 @@ const TOOLS = {
7960
8274
  const s = sess(sid);
7961
8275
  const mine = new Set(heldTabs(sid).map((t) => t.tabId));
7962
8276
  const list = tabs
7963
- .map((t) => ({
7964
- tabId: t.id,
7965
- windowId: t.windowId,
7966
- title: t.title || "",
7967
- url: t.url || "",
7968
- active: !!t.active,
7969
- // 本会话持有的(可能不止一个)
7970
- isTarget: mine.has(t.id),
7971
- // 用户自己拖进本会话标签组的 = 明确授权,可以直接 tab_use
7972
- inMyGroup: s.groupId != null && t.groupId === s.groupId,
7973
- // 已经归别的会话管的标签页,别去抢
7974
- ownedByOther: tabOwner.has(t.id) && tabOwner.get(t.id) !== sid,
7975
- }))
8277
+ .map((t) => {
8278
+ const isMe = mine.has(t.id);
8279
+ const isInMyGroup = s.groupId != null && t.groupId === s.groupId;
8280
+ const isOther = tabOwner.has(t.id) && tabOwner.get(t.id) !== sid;
8281
+ return {
8282
+ tabId: t.id,
8283
+ windowId: t.windowId,
8284
+ title: t.title || "",
8285
+ url: t.url || "",
8286
+ active: !!t.active,
8287
+ // 本会话持有的(可能不止一个)
8288
+ isTarget: isMe,
8289
+ ownedByMe: isMe,
8290
+ usableDirectly: isMe,
8291
+ // 用户自己拖进本会话标签组的 = 明确授权,可以直接 tab_use
8292
+ inMyGroup: isInMyGroup,
8293
+ // 已经归别的会话管的标签页,别去抢
8294
+ ownedByOther: isOther,
8295
+ ...(isMe
8296
+ ? {}
8297
+ : {
8298
+ claimHint: isOther
8299
+ ? "归另一个会话持有,不要操作"
8300
+ : isInMyGroup
8301
+ ? "已在你的标签组中,需先 browser_tab_use({tabId}) 接管"
8302
+ : "用户自己的标签页:默认请用 browser_new_tab({url}) 开副本;仅在用户明确要求操作这张页时调 browser_tab_use({tabId, takeover: true})",
8303
+ }),
8304
+ };
8305
+ })
7976
8306
  .filter(
7977
8307
  (t) =>
7978
8308
  !needle ||
@@ -8272,6 +8602,7 @@ const TOOLS = {
8272
8602
  closedCount: 0,
8273
8603
  releasedCount: 0,
8274
8604
  blocked: "mixed-tasks",
8605
+ warning: "本次未关闭任何标签页(closedCount=0):存在多任务标签页,请带上 label 或使用 browser_close_tab 逐页关闭",
8275
8606
  tasks: [...byTask.entries()].map(([k, v]) => ({
8276
8607
  label: k,
8277
8608
  tabCount: v.length,
@@ -8359,12 +8690,9 @@ const TOOLS = {
8359
8690
  let cookies = Array.isArray(res?.cookies) ? res.cookies : [];
8360
8691
  // 归一化和「一条授权覆不覆盖某个域」都用闸那边的同一份实现——两处口径必须一致
8361
8692
  // (cookieDomainKey / cookieGrantCovers 的头注释各自说过一遍),手抄一份迟早分叉
8362
- const want = Array.isArray(domains) ? domains.map(cookieDomainKey) : null;
8693
+ const want = Array.isArray(domains) ? domains.map(cookieDomainKey).filter(Boolean) : null;
8363
8694
  if (want && want.length) {
8364
- cookies = cookies.filter((c) => {
8365
- const d = cookieDomainKey(c.domain);
8366
- return want.some((w) => cookieGrantCovers(w, d));
8367
- });
8695
+ cookies = cookies.filter((c) => want.some((w) => cookieSentToHost(c, w)));
8368
8696
  }
8369
8697
  const domainCount = {};
8370
8698
  for (const c of cookies) domainCount[c.domain] = (domainCount[c.domain] || 0) + 1;
@@ -8594,7 +8922,7 @@ const TOOLS = {
8594
8922
  const wantTx = Number(maxText);
8595
8923
  const maxTx = Math.max(0, Number.isFinite(wantTx) ? wantTx : 20000);
8596
8924
  const wantTxOff = Number(textOffset);
8597
- const txOff = Math.max(0, Number.isFinite(wantTxOff) ? wantTxOff : 0);
8925
+ const txOff = Number.isFinite(wantTxOff) ? Math.trunc(wantTxOff) : 0;
8598
8926
  const containerSel = typeof container === "string" && container.trim() ? container.trim() : "";
8599
8927
  const nonce = frameNonce();
8600
8928
  const res = await inAllFrames(tabId, pageAgent, [
@@ -8722,7 +9050,8 @@ const TOOLS = {
8722
9050
  }
8723
9051
  text += seg;
8724
9052
  }
8725
- const topLeft = Math.max(0, topTotal - txOff - topText.length);
9053
+ const effOff = Number(top.textOffset) || 0;
9054
+ const topLeft = Math.max(0, topTotal - effOff - topText.length);
8726
9055
  const textTruncated = maxTx ? topLeft > 0 || txDropped.length > 0 : false;
8727
9056
  const textTotal = topTotal;
8728
9057
  const textHint = !maxTx
@@ -8731,8 +9060,8 @@ const TOOLS = {
8731
9060
  : ""
8732
9061
  : textTruncated
8733
9062
  ? (topLeft > 0
8734
- ? `顶层正文共 ${topTotal} 字符,这次给了从 ${txOff} 起的 ${topText.length} 个,还剩 ${topLeft} 个:` +
8735
- `续读把 textOffset 设成 ${txOff + topText.length}(textOffset 只作用于顶层帧)。`
9063
+ ? `顶层正文共 ${topTotal} 字符,这次给了从 ${effOff} 起的 ${topText.length} 个,还剩 ${topLeft} 个:` +
9064
+ `续读把 textOffset 设成 ${effOff + topText.length}(textOffset 只作用于顶层帧)。`
8736
9065
  : `顶层正文已经给全了(${topTotal} 字符)。`) +
8737
9066
  (txDropped.length
8738
9067
  ? `iframe ${txDropped.join("、")} 的正文这次一个字都没给(额度不够)——它不随 textOffset 续读,` +
@@ -8818,7 +9147,7 @@ const TOOLS = {
8818
9147
  frames: frameInfo.length ? frameInfo : undefined,
8819
9148
  text,
8820
9149
  textTotal,
8821
- ...(txOff ? { textOffset: txOff } : {}),
9150
+ ...(effOff || txOff < 0 ? { textOffset: effOff } : {}),
8822
9151
  textTruncated,
8823
9152
  ...(textHint ? { textHint } : {}),
8824
9153
  // 这些同级字段的内容整个是**网页自己写的**:正文、标题、元素的可访问名/标签、
@@ -8852,7 +9181,7 @@ const TOOLS = {
8852
9181
  // 按文字找元素:给几个候选 ref,而不是把整页倾倒出来。搜索走 CDP 的 DOM.performSearch
8853
9182
  // (文本 / CSS 选择器 / XPath 都认,**穿 iframe、穿 shadow DOM、没有元素数上限**),
8854
9183
  // 只对命中的那几个再去算坐标和可访问名。返回 ref_b<backendNodeId>,句柄和节点同生命周期。
8855
- async find({ query, role, limit = 8, maxCandidates = 60, container, settleMs, tabId: wantTab } = {}, sid) {
9184
+ async find({ query, role, limit = 8, maxCandidates = 60, minMatches = 0, container, settleMs, tabId: wantTab } = {}, sid) {
8856
9185
  const q = String(query ?? "").trim();
8857
9186
  const wantRole = String(role ?? "").trim();
8858
9187
  if (!q && !wantRole) throw new Error("需要 query(要找的文字)或 role(如 button / link / textbox)之一。");
@@ -9068,6 +9397,12 @@ const TOOLS = {
9068
9397
  kept.sort((a, b) => a._tier - b._tier || b._s - a._s);
9069
9398
  const lim = Math.max(1, Math.min(50, Number(limit) || 8));
9070
9399
  const out = kept.slice(0, lim).map(({ _s, _tier, _byRole, _bn, ...rest }) => rest);
9400
+ const minNeed = Math.max(0, Math.floor(Number(minMatches) || 0));
9401
+ if (minNeed > 0 && out.length < minNeed) {
9402
+ throw new Error(
9403
+ `未找到匹配元素(期望至少 ${minNeed} 个,实际 ${out.length} 个):query=${JSON.stringify(q || null)} role=${JSON.stringify(wantRole || null)}`
9404
+ );
9405
+ }
9071
9406
  const roleFellBack = !!wantRole && kept.length > 0 && kept[0]._tier > 0;
9072
9407
  const tab = await chrome.tabs.get(tabId).catch(() => null);
9073
9408
 
@@ -9145,6 +9480,17 @@ const TOOLS = {
9145
9480
  sid
9146
9481
  ) {
9147
9482
  const tabId = await withTarget(sid, wantTab);
9483
+ try {
9484
+ const tab = await chrome.tabs.get(tabId);
9485
+ const win = await chrome.windows.get(tab.windowId);
9486
+ if (win.state === "minimized") {
9487
+ throw new Error(
9488
+ "Chrome 窗口是最小化的:最小化的窗口不产帧,截图会一直挂到超时。先把窗口恢复(点任务栏图标即可,不必切过去)再试。"
9489
+ );
9490
+ }
9491
+ } catch (e) {
9492
+ if (/最小化的窗口/.test(String(e?.message || e))) throw e;
9493
+ }
9148
9494
  const given = [region ? "region" : null, ref ? "ref" : null, selector ? "selector" : null, fullPage ? "fullPage" : null].filter(Boolean);
9149
9495
  if (given.length > 1) {
9150
9496
  throw new Error(`region / ref / selector / fullPage 只能给一个,收到了 ${given.join(" 和 ")},什么都没截。`);
@@ -9293,7 +9639,7 @@ const TOOLS = {
9293
9639
  * activeDialog 兜住——工具描述里写明了这一点。
9294
9640
  */
9295
9641
  async click(
9296
- { ref, selector, x, y, button = "left", clickCount = 1, modifiers, force = false, tabId: wantTab } = {},
9642
+ { ref, selector, x, y, button = "left", clickCount = 1, modifiers, force = false, settleMs, tabId: wantTab } = {},
9297
9643
  sid
9298
9644
  ) {
9299
9645
  const tabId = await withTarget(sid, wantTab);
@@ -9321,11 +9667,33 @@ const TOOLS = {
9321
9667
  if (!cleaned && hitCtx?.mark)
9322
9668
  await cdpClearHit(tabId, hitCtx.mark, { sessionId: hitCtx.sessionId || null }).catch(() => {});
9323
9669
  }
9670
+ const wantSettle = Math.min(DOM_SETTLE_MAX_MS, Math.max(0, Number(settleMs) || 0));
9671
+ let settle = null;
9672
+ let settleNote = null;
9673
+ if (wantSettle > 0) {
9674
+ try {
9675
+ settle = await settleDom(tabId, wantSettle);
9676
+ } catch (e) {
9677
+ settleNote = `沉降等待已降级(可能触发了导航或上下文销毁):${String(e?.message || e)}`;
9678
+ }
9679
+ }
9324
9680
  const dlg = await scanDialogsDiff(tabId);
9325
9681
  return {
9326
9682
  clicked: what,
9327
9683
  at: [cx, cy],
9328
9684
  ...info,
9685
+ ...(settle
9686
+ ? {
9687
+ settleMs: wantSettle,
9688
+ waitedMs: settle.waitedMs,
9689
+ ...(settle.settled
9690
+ ? {}
9691
+ : {
9692
+ settleWarning: `等到预算见底 DOM 还在变${settle.noisyFrames?.length ? `(${settle.noisyFrames.join("、")})` : ""}。`,
9693
+ }),
9694
+ }
9695
+ : {}),
9696
+ ...(settleNote ? { settleNote } : {}),
9329
9697
  ...(dlg?.active
9330
9698
  ? {
9331
9699
  ...(dlg.appeared ? { dialogAppeared: true } : {}),
@@ -9797,6 +10165,29 @@ const TOOLS = {
9797
10165
  } else if (r.type === "undefined") {
9798
10166
  out.hint = "表达式返回 undefined。要取值记得让最后一条语句是表达式(别用 const x = …,直接写 x)。";
9799
10167
  } else if (r.type === "function" || (r.type === "object" && value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0)) {
10168
+ let isFn = r.type === "function";
10169
+ if (!isFn && couldBeUninvokedFunction(expression)) {
10170
+ let probeObjId = null;
10171
+ try {
10172
+ const r2 = await cdp(tabId, "Runtime.evaluate", {
10173
+ expression: String(expression),
10174
+ returnByValue: false,
10175
+ awaitPromise: false,
10176
+ userGesture: false,
10177
+ });
10178
+ probeObjId = r2?.result?.objectId || null;
10179
+ if (r2?.result?.type === "function") isFn = true;
10180
+ } catch {
10181
+ } finally {
10182
+ if (probeObjId) cdp(tabId, "Runtime.releaseObject", { objectId: probeObjId }).catch(() => {});
10183
+ }
10184
+ }
10185
+ if (isFn) {
10186
+ throw new Error(
10187
+ "expression 求值结果是一个未被调用的函数对象(如 `() => ...`)。" +
10188
+ "请改成立即执行表达式 `(() => { ... })()`,或直接写求值表达式,不要只传函数定义。"
10189
+ );
10190
+ }
9800
10191
  out.hint =
9801
10192
  "返回值序列化后是空对象 {}。DOM 节点、NodeList 项、Map/Set、函数这类宿主对象都会变成 {}。" +
9802
10193
  "改成返回可 JSON 化的数据,例如 el.textContent、[...nodes].map(n => n.id)。";
@@ -10092,12 +10483,258 @@ const TOOLS = {
10092
10483
  };
10093
10484
  },
10094
10485
 
10486
+ // 在当前已登录标签页上下文中发起同源 HTTP 请求(自动携带 HttpOnly Cookie)
10487
+ async fetch_http(
10488
+ {
10489
+ url,
10490
+ method = "GET",
10491
+ query,
10492
+ headers,
10493
+ json,
10494
+ body,
10495
+ maxBody,
10496
+ timeoutMs = 30000,
10497
+ redirect = "follow",
10498
+ revealSecrets = false,
10499
+ _forOutFile = false,
10500
+ tabId: wantTab,
10501
+ } = {},
10502
+ sid
10503
+ ) {
10504
+ if (!url || typeof url !== "string" || !url.trim()) {
10505
+ throw new Error("需要 url(同源绝对地址或以 / 开头的相对路径)");
10506
+ }
10507
+ if (json !== undefined && body !== undefined) {
10508
+ throw new Error("json 和 body 不能同时传,二选一");
10509
+ }
10510
+ const m = String(method || "GET").toUpperCase().trim();
10511
+ if (!["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"].includes(m)) {
10512
+ throw new Error(`不支持的 HTTP method: ${method}`);
10513
+ }
10514
+ const redirMode = redirect === "error" ? "error" : redirect === "follow" || redirect === undefined ? "follow" : null;
10515
+ if (!redirMode) throw new Error(`redirect 只支持 "follow" 或 "error",收到 ${JSON.stringify(redirect)}`);
10516
+
10517
+ assertNavigable(url);
10518
+ const tabId = await withTarget(sid, wantTab);
10519
+ const tab = await chrome.tabs.get(tabId).catch(() => null);
10520
+ const tabUrl = tab?.url || "";
10521
+ assertNavigable(tabUrl);
10522
+ let tabParsed;
10523
+ try {
10524
+ tabParsed = new URL(tabUrl);
10525
+ } catch {
10526
+ throw new Error(`当前标签页地址不是有效页面: ${tabUrl}`);
10527
+ }
10528
+ if (tabParsed.protocol !== "http:" && tabParsed.protocol !== "https:") {
10529
+ throw new Error(`browser_fetch 仅支持在 http/https 页面上下文执行,当前页面是 ${tabParsed.protocol}`);
10530
+ }
10531
+
10532
+ const cleanRaw = String(url).replace(/[\t\n\r\0]/g, "").trim();
10533
+ let resolvedUrl;
10534
+ try {
10535
+ resolvedUrl = new URL(cleanRaw, tabParsed.href);
10536
+ } catch {
10537
+ throw new Error(`无效的请求 URL: ${url}`);
10538
+ }
10539
+ assertNavigable(resolvedUrl.href);
10540
+ if (resolvedUrl.origin !== tabParsed.origin) {
10541
+ throw new Error(
10542
+ `browser_fetch 仅支持同源请求(当前页面 ${tabParsed.origin},目标 ${resolvedUrl.origin})。` +
10543
+ "跨站请先用 browser_new_tab 打开目标站点再发起请求。"
10544
+ );
10545
+ }
10546
+
10547
+ if (query && typeof query === "object" && !Array.isArray(query)) {
10548
+ for (const [k, v] of Object.entries(query)) {
10549
+ if (v === null || v === undefined) continue;
10550
+ resolvedUrl.searchParams.set(k, String(v));
10551
+ }
10552
+ }
10553
+
10554
+ const reqHeaders = {};
10555
+ if (headers && typeof headers === "object" && !Array.isArray(headers)) {
10556
+ for (const [k, v] of Object.entries(headers)) {
10557
+ if (v !== undefined && v !== null) reqHeaders[String(k)] = String(v);
10558
+ }
10559
+ }
10560
+ let reqBody;
10561
+ if (json !== undefined) {
10562
+ reqBody = JSON.stringify(json);
10563
+ if (!Object.keys(reqHeaders).some((k) => k.toLowerCase() === "content-type")) {
10564
+ reqHeaders["Content-Type"] = "application/json";
10565
+ }
10566
+ } else if (body !== undefined) {
10567
+ reqBody = String(body);
10568
+ }
10569
+
10570
+ const forOutFile = _forOutFile === true;
10571
+ const reveal = revealSecrets === true;
10572
+ const capLimit = forOutFile ? HARD_FETCH_MAX : 500_000;
10573
+ const rawMax = Number(maxBody);
10574
+ const wantMax =
10575
+ Number.isFinite(rawMax) && rawMax > 0 ? Math.min(capLimit, Math.floor(rawMax)) : forOutFile ? HARD_FETCH_MAX : 50_000;
10576
+ const budget = Math.max(1000, Number(timeoutMs) > 0 ? Number(timeoutMs) : 30_000);
10577
+
10578
+ const t0 = Date.now();
10579
+ const hostObj = await cdp(tabId, "Runtime.evaluate", {
10580
+ expression: "globalThis",
10581
+ returnByValue: false,
10582
+ });
10583
+ const objectId = hostObj?.result?.objectId;
10584
+ if (!objectId) throw new Error("页面执行上下文不可用(可能正在导航)");
10585
+
10586
+ let timer = null;
10587
+ const beat = setInterval(() => {
10588
+ wakeTab(tabId).catch(() => {});
10589
+ }, EVAL_WAKE_MS);
10590
+ const TIMEOUT_MARK = "__aic_fetch_timeout__";
10591
+ let res;
10592
+ try {
10593
+ res = await Promise.race([
10594
+ cdp(tabId, "Runtime.callFunctionOn", {
10595
+ objectId,
10596
+ functionDeclaration: `async function(req) {
10597
+ const ctrl = typeof AbortController === "function" ? new AbortController() : null;
10598
+ const t = ctrl ? setTimeout(() => ctrl.abort(), req.timeoutMs) : null;
10599
+ try {
10600
+ const init = {
10601
+ method: req.method,
10602
+ headers: req.headers,
10603
+ credentials: "same-origin",
10604
+ redirect: req.redirect,
10605
+ ...(ctrl ? { signal: ctrl.signal } : {}),
10606
+ ...(req.body !== undefined && req.method !== "GET" && req.method !== "HEAD" ? { body: req.body } : {}),
10607
+ };
10608
+ const r = await fetch(req.url, init);
10609
+ if (r.url) {
10610
+ const finalOrigin = new URL(r.url, location.href).origin;
10611
+ if (finalOrigin !== location.origin) {
10612
+ return { crossOriginRedirect: true, finalOrigin, finalUrl: r.url, status: r.status };
10613
+ }
10614
+ }
10615
+ const txt = await r.text();
10616
+ const rh = {};
10617
+ try {
10618
+ r.headers.forEach((val, key) => { rh[key] = val; });
10619
+ } catch {}
10620
+ const bodyTruncated = txt.length > req.maxChars;
10621
+ return {
10622
+ ok: r.ok,
10623
+ status: r.status,
10624
+ statusText: r.statusText,
10625
+ url: r.url || req.url,
10626
+ contentType: r.headers.get("content-type") || "",
10627
+ sizeChars: txt.length,
10628
+ bodyTruncated,
10629
+ text: bodyTruncated ? txt.slice(0, req.maxChars) : txt,
10630
+ responseHeaders: rh,
10631
+ };
10632
+ } finally {
10633
+ if (t !== null) clearTimeout(t);
10634
+ }
10635
+ }`,
10636
+ arguments: [
10637
+ {
10638
+ value: {
10639
+ url: resolvedUrl.href,
10640
+ method: m,
10641
+ headers: reqHeaders,
10642
+ body: reqBody,
10643
+ redirect: redirMode,
10644
+ maxChars: wantMax,
10645
+ timeoutMs: budget,
10646
+ },
10647
+ },
10648
+ ],
10649
+ returnByValue: true,
10650
+ awaitPromise: true,
10651
+ userGesture: true,
10652
+ }),
10653
+ new Promise((_, rej) => {
10654
+ timer = setTimeout(() => rej(new Error(TIMEOUT_MARK)), budget + 2000);
10655
+ }),
10656
+ ]);
10657
+ } catch (e) {
10658
+ const msg = String(e?.message || e);
10659
+ if (msg === TIMEOUT_MARK) {
10660
+ throw new Error(`browser_fetch 请求超时(>${budget}ms):${redactUrlQuery(resolvedUrl.href)}`);
10661
+ }
10662
+ throw e;
10663
+ } finally {
10664
+ clearTimeout(timer);
10665
+ clearInterval(beat);
10666
+ cdp(tabId, "Runtime.releaseObject", { objectId }).catch(() => {});
10667
+ }
10668
+
10669
+ if (res?.exceptionDetails) {
10670
+ const d = res.exceptionDetails;
10671
+ const errText = d.exception?.description || d.text || "fetch 请求失败";
10672
+ if (redirMode === "error" && /redirect|abort|Failed to fetch|NetworkError/i.test(errText)) {
10673
+ throw new Error(`browser_fetch 请求被中止(可能触发了重定向且 redirect:"error"):${errText}`);
10674
+ }
10675
+ throw new Error(`browser_fetch 请求失败:${errText}`);
10676
+ }
10677
+ const v = res?.result?.value;
10678
+ if (!v || typeof v !== "object") {
10679
+ throw new Error("browser_fetch 未拿到有效响应(页面可能刚刚导航)");
10680
+ }
10681
+ let vOrigin = tabParsed.origin;
10682
+ if (v.url) {
10683
+ try {
10684
+ vOrigin = new URL(v.url, tabParsed.href).origin;
10685
+ } catch {}
10686
+ }
10687
+ if (v.crossOriginRedirect || vOrigin !== tabParsed.origin) {
10688
+ throw new Error(
10689
+ `browser_fetch 请求发生了跨源重定向(${tabParsed.origin} → ${v.finalOrigin || vOrigin}):` +
10690
+ "已丢弃响应体并中止,以防跨源数据外泄。跨站请先用 browser_new_tab 打开目标站点。"
10691
+ );
10692
+ }
10693
+
10694
+ const responseHeaders = redactHeaders(v.responseHeaders, reveal);
10695
+ let rawText = String(v.text ?? "");
10696
+ let bodyHits = [];
10697
+ if (!forOutFile) {
10698
+ const red = redactBody(rawText, reveal);
10699
+ rawText = red.text;
10700
+ bodyHits = red.hits;
10701
+ }
10702
+ let parsedJson;
10703
+ if (!v.bodyTruncated && (/json/i.test(v.contentType || "") || /^\s*[\[{]/.test(rawText))) {
10704
+ try {
10705
+ parsedJson = JSON.parse(rawText);
10706
+ } catch {}
10707
+ }
10708
+ const payloadField = parsedJson !== undefined ? { data: parsedJson } : { body: rawText };
10709
+ const bodyNote = !forOutFile ? bodyRedactNote(bodyHits) : null;
10710
+ return {
10711
+ ok: !!v.ok,
10712
+ status: v.status,
10713
+ statusText: v.statusText || "",
10714
+ url: v.url || resolvedUrl.href,
10715
+ contentType: v.contentType || "",
10716
+ durMs: Date.now() - t0,
10717
+ sizeChars: v.sizeChars ?? rawText.length,
10718
+ bodyTruncated: !!v.bodyTruncated,
10719
+ responseHeaders,
10720
+ ...payloadField,
10721
+ ...(bodyNote ? { bodyRedactNote: bodyNote } : {}),
10722
+ ...(!reveal && !forOutFile ? { headersNote: "凭据类响应头已打码;确需原文传 revealSecrets:true" } : {}),
10723
+ _fromPage: ["url", "responseHeaders", parsedJson !== undefined ? "data" : "body"],
10724
+ };
10725
+ },
10726
+
10095
10727
  /* 点进某一条:请求头、请求体、响应头、响应体、耗时 —— DevTools 里点开那一栏 */
10096
10728
  async request_detail(
10097
- { requestId, includeBody = true, maxBody = 20000, headers = true, revealSecrets = false, tabId: wantTab } = {},
10729
+ { requestId, includeBody = true, maxBody, headers = true, revealSecrets = false, _forOutFile = false, tabId: wantTab } = {},
10098
10730
  sid
10099
10731
  ) {
10100
10732
  revealSecrets = revealSecrets === true;
10733
+ const forOutFile = _forOutFile === true;
10734
+ const cap = forOutFile ? HARD_DETAIL_BODY : 500_000;
10735
+ const rawMb = Number(maxBody);
10736
+ const wantMaxBody =
10737
+ Number.isFinite(rawMb) && rawMb > 0 ? Math.min(cap, Math.floor(rawMb)) : forOutFile ? HARD_DETAIL_BODY : 20000;
10101
10738
  const tabId = await withTarget(sid, wantTab);
10102
10739
  if (!requestId) throw new Error("需要 requestId(来自 browser_network)");
10103
10740
  const r = findReq(tabId, String(requestId));
@@ -10157,19 +10794,39 @@ const TOOLS = {
10157
10794
  const bodyHits = [];
10158
10795
  if (r.postData) {
10159
10796
  const red = redactBody(r.postData, revealSecrets);
10160
- out.requestBody = red.text.slice(0, Number(maxBody));
10797
+ out.requestBody = red.text.slice(0, wantMaxBody);
10161
10798
  bodyHits.push(...red.hits);
10162
- out.requestBodyTruncated = red.text.length > Number(maxBody) || !!r.postDataTruncated;
10799
+ out.requestBodyTruncated = red.text.length > wantMaxBody || !!r.postDataTruncated;
10163
10800
  } else if (r.hasPostData) {
10164
10801
  out.requestBody = `(有请求体,但取不回来:${r.postDataErr || "原因未知"}。多半是它已经被 CDP 缓冲淘汰了)`;
10165
10802
  }
10166
10803
  if (includeBody) {
10167
- if (r.body !== undefined) {
10168
- const red = redactBody(r.body, revealSecrets);
10169
- out.responseBody = red.text.slice(0, Number(maxBody));
10170
- bodyHits.push(...red.hits);
10171
- out.responseBodyTruncated = r.bodyTruncated || red.text.length > Number(maxBody);
10804
+ let fullRespBody = r.body;
10805
+ let fullRespTruncated = !!r.bodyTruncated;
10806
+ let fullRespNote = null;
10807
+ if (r.body !== undefined && r.bodyTruncated && wantMaxBody > BODY_MAX && !r.failed) {
10808
+ try {
10809
+ const got = await cdp(tabId, "Network.getResponseBody", { requestId: r.id });
10810
+ if (got && typeof got.body === "string") {
10811
+ fullRespBody = got.body;
10812
+ fullRespTruncated = fullRespBody.length > wantMaxBody;
10813
+ }
10814
+ } catch {
10815
+ fullRespNote = `超过 ${BODY_MAX} 字符的部分已从浏览器缓冲淘汰,可改用 browser_fetch 重发请求并配 outFile 落盘`;
10816
+ }
10817
+ }
10818
+ if (fullRespBody !== undefined) {
10819
+ if (forOutFile) {
10820
+ out.responseBody = fullRespBody.slice(0, wantMaxBody);
10821
+ out.responseBodyTruncated = fullRespTruncated || fullRespBody.length > wantMaxBody;
10822
+ } else {
10823
+ const red = redactBody(fullRespBody, revealSecrets);
10824
+ out.responseBody = red.text.slice(0, wantMaxBody);
10825
+ bodyHits.push(...red.hits);
10826
+ out.responseBodyTruncated = fullRespTruncated || red.text.length > wantMaxBody;
10827
+ }
10172
10828
  out.responseBodyBase64 = r.bodyBase64 || undefined;
10829
+ if (fullRespNote) out.responseBodyNote = fullRespNote;
10173
10830
  } else if (r.bodyErr) {
10174
10831
  out.responseBodyError = r.bodyErr;
10175
10832
  if (r.bodyEvicted) out.responseBodyNote = "这条的响应体先前为了给新请求腾内存被丢掉过,刚才重取也没取回来(CDP 缓冲区多半已淘汰)";
@@ -10378,7 +11035,11 @@ const TOOLS = {
10378
11035
  const CHUNK_MS = 3000;
10379
11036
  const probe = (sel, txt) => {
10380
11037
  const r = {};
10381
- if (sel) r.selector = !!document.querySelector(sel);
11038
+ if (sel) {
11039
+ const el = document.querySelector(sel);
11040
+ r.selector = !!el;
11041
+ if (el) r.matchedText = String(el.innerText || el.textContent || el.value || "").trim().slice(0, 200);
11042
+ }
10382
11043
  if (txt) r.text = ((document.body && document.body.innerText) || "").includes(txt);
10383
11044
  r.url = location.href;
10384
11045
  return r;
@@ -10409,15 +11070,31 @@ const TOOLS = {
10409
11070
  const TXT = ${JSON.stringify(textContains || null)};
10410
11071
  const URLC = ${JSON.stringify(urlContains || null)};
10411
11072
  const POLL = ${poll}, BUDGET = ${budgetMs}, T0 = Date.now();
11073
+ const matchUrl = (rawUrl, needle) => {
11074
+ const raw = String(rawUrl || "");
11075
+ const n = String(needle || "");
11076
+ if (!n) return true;
11077
+ if (/[?&=#]/.test(n)) return raw.includes(n);
11078
+ let base;
11079
+ try {
11080
+ const u = new URL(raw);
11081
+ base = u.origin + u.pathname;
11082
+ } catch {
11083
+ const idx = raw.search(/[?#]/);
11084
+ base = idx >= 0 ? raw.slice(0, idx) : raw;
11085
+ }
11086
+ return base.includes(n);
11087
+ };
10412
11088
  // 返回值要能被 returnByValue 序列化:js 返回 DOM 节点/循环引用时,
10413
11089
  // 整个结果不能因此炸掉——那样连「等到没等到」都报不出来
10414
11090
  const safe = (v) => { try { JSON.parse(JSON.stringify(v)); return v; } catch (e) { return String(v).slice(0, 300); } };
10415
11091
  let evals = 0, sawValue = false, everSucceeded = false, lastValue, lastError = null;
10416
11092
  for (;;) {
10417
11093
  let ok = true;
10418
- if (SEL && !document.querySelector(SEL)) ok = false;
11094
+ const selEl = SEL ? document.querySelector(SEL) : null;
11095
+ if (SEL && !selEl) ok = false;
10419
11096
  if (TXT && !((document.body && document.body.innerText) || "").includes(TXT)) ok = false;
10420
- if (URLC && !location.href.includes(URLC)) ok = false;
11097
+ if (URLC && !matchUrl(location.href, URLC)) ok = false;
10421
11098
  ${
10422
11099
  js
10423
11100
  ? `/* __AIC_WAIT_JS__ */ evals++;
@@ -10430,8 +11107,12 @@ const TOOLS = {
10430
11107
  : ""
10431
11108
  }
10432
11109
  const done = ok || Date.now() - T0 >= BUDGET;
10433
- if (done) return { matched: ok, url: location.href, evals, sawValue, everSucceeded, lastError,
10434
- jsValue: lastValue === undefined ? null : safe(lastValue) };
11110
+ if (done) {
11111
+ const matchedText = ok && selEl ? String(selEl.innerText || selEl.textContent || selEl.value || "").trim().slice(0, 200) : undefined;
11112
+ return { matched: ok, url: location.href, evals, sawValue, everSucceeded, lastError,
11113
+ ...(matchedText !== undefined ? { matchedText } : {}),
11114
+ jsValue: lastValue === undefined ? null : safe(lastValue) };
11115
+ }
10435
11116
  await new Promise((r) => setTimeout(r, POLL));
10436
11117
  }
10437
11118
  })()`;
@@ -10481,11 +11162,16 @@ const TOOLS = {
10481
11162
  if (v.everSucceeded) everSucceeded = true;
10482
11163
  if (v.lastError) lastError = v.lastError;
10483
11164
  if (v.matched) {
11165
+ const fromPage = [];
11166
+ if (js) fromPage.push("jsValue");
11167
+ if (selector && v.matchedText !== undefined) fromPage.push("matchedText");
10484
11168
  return {
10485
11169
  matched: true,
10486
11170
  url: v.url,
10487
11171
  waitedMs: Date.now() - started,
10488
- ...(js ? { jsValue: v.jsValue, evals, _fromPage: ["jsValue"] } : {}),
11172
+ ...(js ? { jsValue: v.jsValue, evals } : {}),
11173
+ ...(selector && v.matchedText !== undefined ? { matchedText: v.matchedText } : {}),
11174
+ ...(fromPage.length ? { _fromPage: fromPage } : {}),
10489
11175
  };
10490
11176
  }
10491
11177
  continue;
@@ -10495,7 +11181,7 @@ const TOOLS = {
10495
11181
  lastUrl = r.url;
10496
11182
  const okSel = selector ? r.selector : true;
10497
11183
  const okTxt = textContains ? r.text : true;
10498
- const okUrl = urlContains ? String(r.url).includes(urlContains) : true;
11184
+ const okUrl = urlContains ? matchWaitUrl(r.url, urlContains).matched : true;
10499
11185
  let okJs = true;
10500
11186
  if (js) {
10501
11187
  evals++;
@@ -10520,11 +11206,16 @@ const TOOLS = {
10520
11206
  }
10521
11207
  }
10522
11208
  if (okSel && okTxt && okUrl && okJs) {
11209
+ const fromPage = [];
11210
+ if (js) fromPage.push("jsValue");
11211
+ if (selector && r.matchedText !== undefined) fromPage.push("matchedText");
10523
11212
  return {
10524
11213
  matched: true,
10525
11214
  url: r.url,
10526
11215
  waitedMs: Date.now() - started,
10527
- ...(js ? { jsValue: lastValue, evals, _fromPage: ["jsValue"] } : {}),
11216
+ ...(js ? { jsValue: lastValue, evals } : {}),
11217
+ ...(selector && r.matchedText !== undefined ? { matchedText: r.matchedText } : {}),
11218
+ ...(fromPage.length ? { _fromPage: fromPage } : {}),
10528
11219
  };
10529
11220
  }
10530
11221
  await new Promise((r2) => setTimeout(r2, poll));
@@ -10533,7 +11224,13 @@ const TOOLS = {
10533
11224
  clearInterval(beat);
10534
11225
  }
10535
11226
  let msg = `等待超时(${timeoutMs}ms): ${JSON.stringify({ selector, urlContains, textContains, js })}`;
10536
- if (urlContains && lastUrl) msg += `\n当前 URL:${lastUrl}`;
11227
+ if (urlContains && lastUrl) {
11228
+ msg += `\n当前 URL:${redactUrlQuery(lastUrl)}`;
11229
+ const uDiag = matchWaitUrl(lastUrl, urlContains);
11230
+ if (uDiag.inQueryOnly) {
11231
+ msg += `\n(目标串 ${JSON.stringify(urlContains)} 仅出现在当前地址 ${uDiag.inQueryOnly} 的查询参数中——多半停在登录/OAuth 回调页,尚未进入目标站)`;
11232
+ }
11233
+ }
10537
11234
  if (js) {
10538
11235
  msg += `\njs 求值了 ${evals} 次。`;
10539
11236
  if (sawValue) msg += `最后一次返回:${brief(lastValue)}(需要它是真值才算满足)。`;
@@ -10544,6 +11241,23 @@ const TOOLS = {
10544
11241
  `再确认条件是否真的会成立。`;
10545
11242
  }
10546
11243
  }
11244
+ const netErrors = (networkRing.get(tabId) || [])
11245
+ .filter((r) => r.ts >= started && matchType(r, "api") && (r.failed || r.status >= 400))
11246
+ .slice(-5)
11247
+ .map((r) => `${r.method || "GET"} ${redactUrlQuery(r.url)} → ${r.failed ? "failed:" + r.failed : r.status}`);
11248
+ if (netErrors.length) {
11249
+ msg += `\n等待期间接口异常(最近 ${netErrors.length} 条):\n ${netErrors.join("\n ")}`;
11250
+ }
11251
+ const conErrors = (consoleRing.get(tabId) || [])
11252
+ .filter((c) => c.ts >= started && (c.level === "error" || c.level === "assert"))
11253
+ .slice(-3)
11254
+ .map((c) => {
11255
+ const clean = redactText(redactBody(String(c.text || ""), false).text);
11256
+ return clean.length > 120 ? clean.slice(0, 120) + "…" : clean;
11257
+ });
11258
+ if (conErrors.length) {
11259
+ msg += `\n等待期间控制台报错(最近 ${conErrors.length} 条):\n ${conErrors.join("\n ")}`;
11260
+ }
10547
11261
  msg += activityNote(await pageActivityProbe(tabId));
10548
11262
  throw new Error(msg);
10549
11263
  },
@@ -10776,6 +11490,7 @@ const TOOLS = {
10776
11490
  },
10777
11491
  changeFired: back.changeFired,
10778
11492
  changeDispatchedManually: back.changeDispatchedManually || undefined,
11493
+ elementReplaced: back.elementReplaced || undefined,
10779
11494
  hint: back.changeFired
10780
11495
  ? undefined
10781
11496
  : "页面没有收到 change 事件,说明它可能并不监听这个输入框。检查上传是否真的开始了。",
@@ -10950,7 +11665,7 @@ async function applyViewport(tabId, vp, warnings) {
10950
11665
  : `按 ${got.innerWidth} 这个宽度去算坐标和断点,别按你给的那个。`)
10951
11666
  );
10952
11667
  }
10953
- if (got.dpr !== dsf) warnings.push(`devicePixelRatio 实际是 ${got.dpr},不是你给的 ${dsf}。`);
11668
+ if (Math.abs(Number(got.dpr) - Number(dsf)) > 0.001) warnings.push(`devicePixelRatio 实际是 ${got.dpr},不是你给的 ${dsf}。`);
10954
11669
  return out;
10955
11670
  }
10956
11671
 
@@ -10983,7 +11698,10 @@ async function applyGeolocation(tabId, geo, applied, warnings) {
10983
11698
  const grantErr = origin ? await grantPermissionsFor(tabId, origin, ["geolocation"]).catch((e) => e) : null;
10984
11699
  const state = await permissionState(tabId, "geolocation");
10985
11700
  out.permission = state || "unknown";
10986
- if (state === "granted") return out;
11701
+ if (state === "granted") {
11702
+ await ensureInteractive(tabId).catch(() => {});
11703
+ return out;
11704
+ }
10987
11705
  if (!state || state === "error") {
10988
11706
  if (!grantErr) {
10989
11707
  warnings.push("定位权限已授予,但页面侧问不出 permissions 状态(这一页可能不是普通 http(s) 页面)——用之前先在页面里试一次 getCurrentPosition。");