@liang-hz/agent-in-chrome 0.55.5 → 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.5";
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
 
@@ -4060,6 +4160,7 @@ function pageAgent(op, arg) {
4060
4160
  return {
4061
4161
  code: "occluded",
4062
4162
  msg: blocker ? `被 ${desc(blocker)} 挡住` : sawAny ? "命中的是别的元素" : "该位置命中不到任何元素(可能整块区域被裁掉了)",
4163
+ blockerClass: blocker ? String((blocker.getAttribute && blocker.getAttribute("class")) || blocker.className || "") : "",
4063
4164
  scrolled,
4064
4165
  };
4065
4166
  };
@@ -4180,6 +4281,31 @@ function pageAgent(op, arg) {
4180
4281
  w.fn = null;
4181
4282
  };
4182
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
+
4183
4309
  if (A.arm) {
4184
4310
  detach();
4185
4311
  w.armed = true;
@@ -4187,6 +4313,8 @@ function pageAgent(op, arg) {
4187
4313
  w.elsewhere = [];
4188
4314
  const el = (W.__aicRefs || [])[Number(A.idx) - 1] || null;
4189
4315
  if (!el) return { ok: false };
4316
+ w.beforeState = snapState(el);
4317
+ w.beforePopups = countPopups();
4190
4318
  const fn = (e) => {
4191
4319
  if (!w.armed || w.onTarget.length >= 8) return;
4192
4320
  w.onTarget.push(e && e.type);
@@ -4202,8 +4330,25 @@ function pageAgent(op, arg) {
4202
4330
  }
4203
4331
 
4204
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;
4205
4350
  detach();
4206
- 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 };
4207
4352
  w.onTarget = [];
4208
4353
  w.elsewhere = [];
4209
4354
  return out;
@@ -4235,7 +4380,7 @@ function pageAgent(op, arg) {
4235
4380
  const res = actionable(el, !!A.force);
4236
4381
  const rb = box(el);
4237
4382
  const nowBox = [Math.round(rb.x), Math.round(rb.y), Math.round(rb.w), Math.round(rb.h)];
4238
- 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 };
4239
4384
 
4240
4385
  const chain = frameChain(res.x, res.y, !A.force);
4241
4386
  if (chain.blocked) {
@@ -4578,7 +4723,7 @@ function pageAgent(op, arg) {
4578
4723
  const wantText = Number(A.maxText);
4579
4724
  const maxText = Math.max(0, Number.isFinite(wantText) ? wantText : 20000);
4580
4725
  const wantTextOff = isTopFrame ? Number(A.textOffset) : 0;
4581
- const textOffset = Math.max(0, Number.isFinite(wantTextOff) ? wantTextOff : 0);
4726
+ const rawTextOff = Number.isFinite(wantTextOff) ? Math.trunc(wantTextOff) : 0;
4582
4727
  const textRoot = containerSel ? containerEl : document.body;
4583
4728
  let raw = "";
4584
4729
  try {
@@ -4591,6 +4736,7 @@ function pageAgent(op, arg) {
4591
4736
  if (t.length >= 2) raw = raw.split(t).join(`(可编辑的凭据字段,${t.length} 字符,值已隐去)`);
4592
4737
  }
4593
4738
  } catch {}
4739
+ const textOffset = rawTextOff < 0 ? Math.max(0, raw.length + rawTextOff) : Math.max(0, rawTextOff);
4594
4740
  return {
4595
4741
  ...base,
4596
4742
  scroll: {
@@ -4607,7 +4753,7 @@ function pageAgent(op, arg) {
4607
4753
  ...(containerInvalid ? { containerInvalid: true } : {}),
4608
4754
  text: raw.slice(textOffset, textOffset + maxText),
4609
4755
  textTotal: raw.length,
4610
- ...(textOffset ? { textOffset } : {}),
4756
+ ...(textOffset || rawTextOff < 0 ? { textOffset } : {}),
4611
4757
  textTruncated: raw.length > textOffset + maxText,
4612
4758
  };
4613
4759
  }
@@ -5124,6 +5270,12 @@ async function cdpClearHit(tabId, mark, { sessionId = null } = {}) {
5124
5270
  }).catch(() => {});
5125
5271
  }
5126
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
+
5127
5279
  async function cdpResolveNode(tabId, handle, { force = false, label = null } = {}) {
5128
5280
  const h = typeof handle === "number" ? { backendNodeId: handle, targetId: null } : handle;
5129
5281
  const backendNodeId = h.backendNodeId;
@@ -5183,6 +5335,7 @@ async function cdpResolveNode(tabId, handle, { force = false, label = null } = {
5183
5335
  );
5184
5336
  }
5185
5337
  if (!force) {
5338
+ await new Promise((s) => setTimeout(s, SETTLE_GAP_MS));
5186
5339
  const again = await cdpCenter(tabId, backendNodeId, { sessionId });
5187
5340
  if (again && (Math.abs(again.x - c.x) > 2 || Math.abs(again.y - c.y) > 2)) {
5188
5341
  await new Promise((s) => setTimeout(s, SETTLE_GAP_MS));
@@ -5202,7 +5355,13 @@ async function cdpResolveNode(tabId, handle, { force = false, label = null } = {
5202
5355
  }
5203
5356
 
5204
5357
  const hitCtx = { sessionId };
5205
- 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
+ }
5206
5365
  if (!hit.ok && hit.kind === "nohit") {
5207
5366
  if (!vp) vp = await cdpViewport(tabId, { sessionId });
5208
5367
  const outside = vp && (c.x < 0 || c.y < 0 || c.x >= vp.w || c.y >= vp.h);
@@ -5226,7 +5385,13 @@ async function cdpResolveNode(tabId, handle, { force = false, label = null } = {
5226
5385
  }
5227
5386
  if (!force && ownerBackendNodeId != null) {
5228
5387
  const oc = await cdpCenter(tabId, ownerBackendNodeId);
5229
- 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
+ }
5230
5395
  if (oc && ohit && !ohit.ok && ohit.kind !== "nohit") {
5231
5396
  throw new Error(
5232
5397
  `不可操作(occluded):${shown} <${tag}> ${name} 本身在那个跨进程 iframe 里没被挡,` +
@@ -5746,6 +5911,7 @@ async function resolveRef(tabId, ref, { force = false, label = null } = {}) {
5746
5911
  let r = null;
5747
5912
  let moveFrom = null;
5748
5913
  let moveTo = null;
5914
+ let loaderRetries = 0;
5749
5915
  for (let attempt = 0; ; attempt++) {
5750
5916
  try {
5751
5917
  r = await inFrame(tabId, p.frameId, pageAgent, ["resolve", { ref: shown, idx: p.idx, force: !!force }]);
@@ -5758,6 +5924,11 @@ async function resolveRef(tabId, ref, { force = false, label = null } = {}) {
5758
5924
  if (!r) {
5759
5925
  throw new Error(`${shown} 所在的帧没有返回结果,可能刚刚导航或被移除。重新 browser_read_page。`);
5760
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
+ }
5761
5932
  if (force || !r.box) break;
5762
5933
 
5763
5934
  await new Promise((s) => setTimeout(s, SETTLE_GAP_MS));
@@ -5816,7 +5987,11 @@ async function resolveRef(tabId, ref, { force = false, label = null } = {}) {
5816
5987
  );
5817
5988
  }
5818
5989
  if (!force && viaParent) {
5819
- 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
+ }
5820
5995
  if (blocker) {
5821
5996
  throw new Error(
5822
5997
  `不可操作(occluded):${shown} <${r.tag}> ${r.name} 在跨源 iframe(${r.frameUrl || "地址未知"})里,` +
@@ -6062,7 +6237,16 @@ async function requireTarget(sid, tabId) {
6062
6237
  if (owner === sid) return id;
6063
6238
  if (owner !== undefined)
6064
6239
  throw new Error(`标签页 ${id} 归另一个 agent 会话(${owner})管,别去抢。用 browser_new_tab 开自己的。`);
6240
+ const liveTab = await chrome.tabs.get(id).catch(() => null);
6065
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
+ }
6066
6250
  throw new Error(
6067
6251
  `标签页 ${id} 不在本会话持有的标签页里(可能已经关掉或放开了),什么都没做。` +
6068
6252
  (held.length
@@ -6888,6 +7072,12 @@ async function clickVerified(tabId, frameId, idx, x, y, opts = {}) {
6888
7072
  }
6889
7073
  const leftClick = (opts.button || "left") === "left";
6890
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
+ }
6891
7081
  throw new Error(
6892
7082
  `按下落在了目标上,但浏览器没有合成 click 事件——按下和抬起之间目标动了,页面不会把它当成一次点击。` +
6893
7083
  `页面**没有**按你的意图被操作。等它停稳再点(browser_wait_for 的 js 参数),` +
@@ -7942,6 +8132,76 @@ async function scanDialogsDiff(tabId, url) {
7942
8132
 
7943
8133
  // ------------------------------------------------------------------- 工具集
7944
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
+
7945
8205
  const TOOLS = {
7946
8206
  // 报本会话现在持有哪些标签页、连接状态,以及别的会话手上占着哪些页。
7947
8207
  async status(_args, sid) {
@@ -8014,19 +8274,35 @@ const TOOLS = {
8014
8274
  const s = sess(sid);
8015
8275
  const mine = new Set(heldTabs(sid).map((t) => t.tabId));
8016
8276
  const list = tabs
8017
- .map((t) => ({
8018
- tabId: t.id,
8019
- windowId: t.windowId,
8020
- title: t.title || "",
8021
- url: t.url || "",
8022
- active: !!t.active,
8023
- // 本会话持有的(可能不止一个)
8024
- isTarget: mine.has(t.id),
8025
- // 用户自己拖进本会话标签组的 = 明确授权,可以直接 tab_use
8026
- inMyGroup: s.groupId != null && t.groupId === s.groupId,
8027
- // 已经归别的会话管的标签页,别去抢
8028
- ownedByOther: tabOwner.has(t.id) && tabOwner.get(t.id) !== sid,
8029
- }))
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
+ })
8030
8306
  .filter(
8031
8307
  (t) =>
8032
8308
  !needle ||
@@ -8326,6 +8602,7 @@ const TOOLS = {
8326
8602
  closedCount: 0,
8327
8603
  releasedCount: 0,
8328
8604
  blocked: "mixed-tasks",
8605
+ warning: "本次未关闭任何标签页(closedCount=0):存在多任务标签页,请带上 label 或使用 browser_close_tab 逐页关闭",
8329
8606
  tasks: [...byTask.entries()].map(([k, v]) => ({
8330
8607
  label: k,
8331
8608
  tabCount: v.length,
@@ -8413,12 +8690,9 @@ const TOOLS = {
8413
8690
  let cookies = Array.isArray(res?.cookies) ? res.cookies : [];
8414
8691
  // 归一化和「一条授权覆不覆盖某个域」都用闸那边的同一份实现——两处口径必须一致
8415
8692
  // (cookieDomainKey / cookieGrantCovers 的头注释各自说过一遍),手抄一份迟早分叉
8416
- const want = Array.isArray(domains) ? domains.map(cookieDomainKey) : null;
8693
+ const want = Array.isArray(domains) ? domains.map(cookieDomainKey).filter(Boolean) : null;
8417
8694
  if (want && want.length) {
8418
- cookies = cookies.filter((c) => {
8419
- const d = cookieDomainKey(c.domain);
8420
- return want.some((w) => cookieGrantCovers(w, d));
8421
- });
8695
+ cookies = cookies.filter((c) => want.some((w) => cookieSentToHost(c, w)));
8422
8696
  }
8423
8697
  const domainCount = {};
8424
8698
  for (const c of cookies) domainCount[c.domain] = (domainCount[c.domain] || 0) + 1;
@@ -8648,7 +8922,7 @@ const TOOLS = {
8648
8922
  const wantTx = Number(maxText);
8649
8923
  const maxTx = Math.max(0, Number.isFinite(wantTx) ? wantTx : 20000);
8650
8924
  const wantTxOff = Number(textOffset);
8651
- const txOff = Math.max(0, Number.isFinite(wantTxOff) ? wantTxOff : 0);
8925
+ const txOff = Number.isFinite(wantTxOff) ? Math.trunc(wantTxOff) : 0;
8652
8926
  const containerSel = typeof container === "string" && container.trim() ? container.trim() : "";
8653
8927
  const nonce = frameNonce();
8654
8928
  const res = await inAllFrames(tabId, pageAgent, [
@@ -8776,7 +9050,8 @@ const TOOLS = {
8776
9050
  }
8777
9051
  text += seg;
8778
9052
  }
8779
- 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);
8780
9055
  const textTruncated = maxTx ? topLeft > 0 || txDropped.length > 0 : false;
8781
9056
  const textTotal = topTotal;
8782
9057
  const textHint = !maxTx
@@ -8785,8 +9060,8 @@ const TOOLS = {
8785
9060
  : ""
8786
9061
  : textTruncated
8787
9062
  ? (topLeft > 0
8788
- ? `顶层正文共 ${topTotal} 字符,这次给了从 ${txOff} 起的 ${topText.length} 个,还剩 ${topLeft} 个:` +
8789
- `续读把 textOffset 设成 ${txOff + topText.length}(textOffset 只作用于顶层帧)。`
9063
+ ? `顶层正文共 ${topTotal} 字符,这次给了从 ${effOff} 起的 ${topText.length} 个,还剩 ${topLeft} 个:` +
9064
+ `续读把 textOffset 设成 ${effOff + topText.length}(textOffset 只作用于顶层帧)。`
8790
9065
  : `顶层正文已经给全了(${topTotal} 字符)。`) +
8791
9066
  (txDropped.length
8792
9067
  ? `iframe ${txDropped.join("、")} 的正文这次一个字都没给(额度不够)——它不随 textOffset 续读,` +
@@ -8872,7 +9147,7 @@ const TOOLS = {
8872
9147
  frames: frameInfo.length ? frameInfo : undefined,
8873
9148
  text,
8874
9149
  textTotal,
8875
- ...(txOff ? { textOffset: txOff } : {}),
9150
+ ...(effOff || txOff < 0 ? { textOffset: effOff } : {}),
8876
9151
  textTruncated,
8877
9152
  ...(textHint ? { textHint } : {}),
8878
9153
  // 这些同级字段的内容整个是**网页自己写的**:正文、标题、元素的可访问名/标签、
@@ -8906,7 +9181,7 @@ const TOOLS = {
8906
9181
  // 按文字找元素:给几个候选 ref,而不是把整页倾倒出来。搜索走 CDP 的 DOM.performSearch
8907
9182
  // (文本 / CSS 选择器 / XPath 都认,**穿 iframe、穿 shadow DOM、没有元素数上限**),
8908
9183
  // 只对命中的那几个再去算坐标和可访问名。返回 ref_b<backendNodeId>,句柄和节点同生命周期。
8909
- 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) {
8910
9185
  const q = String(query ?? "").trim();
8911
9186
  const wantRole = String(role ?? "").trim();
8912
9187
  if (!q && !wantRole) throw new Error("需要 query(要找的文字)或 role(如 button / link / textbox)之一。");
@@ -9122,6 +9397,12 @@ const TOOLS = {
9122
9397
  kept.sort((a, b) => a._tier - b._tier || b._s - a._s);
9123
9398
  const lim = Math.max(1, Math.min(50, Number(limit) || 8));
9124
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
+ }
9125
9406
  const roleFellBack = !!wantRole && kept.length > 0 && kept[0]._tier > 0;
9126
9407
  const tab = await chrome.tabs.get(tabId).catch(() => null);
9127
9408
 
@@ -9358,7 +9639,7 @@ const TOOLS = {
9358
9639
  * activeDialog 兜住——工具描述里写明了这一点。
9359
9640
  */
9360
9641
  async click(
9361
- { 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 } = {},
9362
9643
  sid
9363
9644
  ) {
9364
9645
  const tabId = await withTarget(sid, wantTab);
@@ -9386,11 +9667,33 @@ const TOOLS = {
9386
9667
  if (!cleaned && hitCtx?.mark)
9387
9668
  await cdpClearHit(tabId, hitCtx.mark, { sessionId: hitCtx.sessionId || null }).catch(() => {});
9388
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
+ }
9389
9680
  const dlg = await scanDialogsDiff(tabId);
9390
9681
  return {
9391
9682
  clicked: what,
9392
9683
  at: [cx, cy],
9393
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 } : {}),
9394
9697
  ...(dlg?.active
9395
9698
  ? {
9396
9699
  ...(dlg.appeared ? { dialogAppeared: true } : {}),
@@ -9862,6 +10165,29 @@ const TOOLS = {
9862
10165
  } else if (r.type === "undefined") {
9863
10166
  out.hint = "表达式返回 undefined。要取值记得让最后一条语句是表达式(别用 const x = …,直接写 x)。";
9864
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
+ }
9865
10191
  out.hint =
9866
10192
  "返回值序列化后是空对象 {}。DOM 节点、NodeList 项、Map/Set、函数这类宿主对象都会变成 {}。" +
9867
10193
  "改成返回可 JSON 化的数据,例如 el.textContent、[...nodes].map(n => n.id)。";
@@ -10157,12 +10483,258 @@ const TOOLS = {
10157
10483
  };
10158
10484
  },
10159
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
+
10160
10727
  /* 点进某一条:请求头、请求体、响应头、响应体、耗时 —— DevTools 里点开那一栏 */
10161
10728
  async request_detail(
10162
- { requestId, includeBody = true, maxBody = 20000, headers = true, revealSecrets = false, tabId: wantTab } = {},
10729
+ { requestId, includeBody = true, maxBody, headers = true, revealSecrets = false, _forOutFile = false, tabId: wantTab } = {},
10163
10730
  sid
10164
10731
  ) {
10165
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;
10166
10738
  const tabId = await withTarget(sid, wantTab);
10167
10739
  if (!requestId) throw new Error("需要 requestId(来自 browser_network)");
10168
10740
  const r = findReq(tabId, String(requestId));
@@ -10222,19 +10794,39 @@ const TOOLS = {
10222
10794
  const bodyHits = [];
10223
10795
  if (r.postData) {
10224
10796
  const red = redactBody(r.postData, revealSecrets);
10225
- out.requestBody = red.text.slice(0, Number(maxBody));
10797
+ out.requestBody = red.text.slice(0, wantMaxBody);
10226
10798
  bodyHits.push(...red.hits);
10227
- out.requestBodyTruncated = red.text.length > Number(maxBody) || !!r.postDataTruncated;
10799
+ out.requestBodyTruncated = red.text.length > wantMaxBody || !!r.postDataTruncated;
10228
10800
  } else if (r.hasPostData) {
10229
10801
  out.requestBody = `(有请求体,但取不回来:${r.postDataErr || "原因未知"}。多半是它已经被 CDP 缓冲淘汰了)`;
10230
10802
  }
10231
10803
  if (includeBody) {
10232
- if (r.body !== undefined) {
10233
- const red = redactBody(r.body, revealSecrets);
10234
- out.responseBody = red.text.slice(0, Number(maxBody));
10235
- bodyHits.push(...red.hits);
10236
- 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
+ }
10237
10828
  out.responseBodyBase64 = r.bodyBase64 || undefined;
10829
+ if (fullRespNote) out.responseBodyNote = fullRespNote;
10238
10830
  } else if (r.bodyErr) {
10239
10831
  out.responseBodyError = r.bodyErr;
10240
10832
  if (r.bodyEvicted) out.responseBodyNote = "这条的响应体先前为了给新请求腾内存被丢掉过,刚才重取也没取回来(CDP 缓冲区多半已淘汰)";
@@ -10443,7 +11035,11 @@ const TOOLS = {
10443
11035
  const CHUNK_MS = 3000;
10444
11036
  const probe = (sel, txt) => {
10445
11037
  const r = {};
10446
- 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
+ }
10447
11043
  if (txt) r.text = ((document.body && document.body.innerText) || "").includes(txt);
10448
11044
  r.url = location.href;
10449
11045
  return r;
@@ -10474,15 +11070,31 @@ const TOOLS = {
10474
11070
  const TXT = ${JSON.stringify(textContains || null)};
10475
11071
  const URLC = ${JSON.stringify(urlContains || null)};
10476
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
+ };
10477
11088
  // 返回值要能被 returnByValue 序列化:js 返回 DOM 节点/循环引用时,
10478
11089
  // 整个结果不能因此炸掉——那样连「等到没等到」都报不出来
10479
11090
  const safe = (v) => { try { JSON.parse(JSON.stringify(v)); return v; } catch (e) { return String(v).slice(0, 300); } };
10480
11091
  let evals = 0, sawValue = false, everSucceeded = false, lastValue, lastError = null;
10481
11092
  for (;;) {
10482
11093
  let ok = true;
10483
- if (SEL && !document.querySelector(SEL)) ok = false;
11094
+ const selEl = SEL ? document.querySelector(SEL) : null;
11095
+ if (SEL && !selEl) ok = false;
10484
11096
  if (TXT && !((document.body && document.body.innerText) || "").includes(TXT)) ok = false;
10485
- if (URLC && !location.href.includes(URLC)) ok = false;
11097
+ if (URLC && !matchUrl(location.href, URLC)) ok = false;
10486
11098
  ${
10487
11099
  js
10488
11100
  ? `/* __AIC_WAIT_JS__ */ evals++;
@@ -10495,8 +11107,12 @@ const TOOLS = {
10495
11107
  : ""
10496
11108
  }
10497
11109
  const done = ok || Date.now() - T0 >= BUDGET;
10498
- if (done) return { matched: ok, url: location.href, evals, sawValue, everSucceeded, lastError,
10499
- 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
+ }
10500
11116
  await new Promise((r) => setTimeout(r, POLL));
10501
11117
  }
10502
11118
  })()`;
@@ -10546,11 +11162,16 @@ const TOOLS = {
10546
11162
  if (v.everSucceeded) everSucceeded = true;
10547
11163
  if (v.lastError) lastError = v.lastError;
10548
11164
  if (v.matched) {
11165
+ const fromPage = [];
11166
+ if (js) fromPage.push("jsValue");
11167
+ if (selector && v.matchedText !== undefined) fromPage.push("matchedText");
10549
11168
  return {
10550
11169
  matched: true,
10551
11170
  url: v.url,
10552
11171
  waitedMs: Date.now() - started,
10553
- ...(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 } : {}),
10554
11175
  };
10555
11176
  }
10556
11177
  continue;
@@ -10560,7 +11181,7 @@ const TOOLS = {
10560
11181
  lastUrl = r.url;
10561
11182
  const okSel = selector ? r.selector : true;
10562
11183
  const okTxt = textContains ? r.text : true;
10563
- const okUrl = urlContains ? String(r.url).includes(urlContains) : true;
11184
+ const okUrl = urlContains ? matchWaitUrl(r.url, urlContains).matched : true;
10564
11185
  let okJs = true;
10565
11186
  if (js) {
10566
11187
  evals++;
@@ -10585,11 +11206,16 @@ const TOOLS = {
10585
11206
  }
10586
11207
  }
10587
11208
  if (okSel && okTxt && okUrl && okJs) {
11209
+ const fromPage = [];
11210
+ if (js) fromPage.push("jsValue");
11211
+ if (selector && r.matchedText !== undefined) fromPage.push("matchedText");
10588
11212
  return {
10589
11213
  matched: true,
10590
11214
  url: r.url,
10591
11215
  waitedMs: Date.now() - started,
10592
- ...(js ? { jsValue: lastValue, evals, _fromPage: ["jsValue"] } : {}),
11216
+ ...(js ? { jsValue: lastValue, evals } : {}),
11217
+ ...(selector && r.matchedText !== undefined ? { matchedText: r.matchedText } : {}),
11218
+ ...(fromPage.length ? { _fromPage: fromPage } : {}),
10593
11219
  };
10594
11220
  }
10595
11221
  await new Promise((r2) => setTimeout(r2, poll));
@@ -10598,7 +11224,13 @@ const TOOLS = {
10598
11224
  clearInterval(beat);
10599
11225
  }
10600
11226
  let msg = `等待超时(${timeoutMs}ms): ${JSON.stringify({ selector, urlContains, textContains, js })}`;
10601
- 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
+ }
10602
11234
  if (js) {
10603
11235
  msg += `\njs 求值了 ${evals} 次。`;
10604
11236
  if (sawValue) msg += `最后一次返回:${brief(lastValue)}(需要它是真值才算满足)。`;
@@ -10609,6 +11241,23 @@ const TOOLS = {
10609
11241
  `再确认条件是否真的会成立。`;
10610
11242
  }
10611
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
+ }
10612
11261
  msg += activityNote(await pageActivityProbe(tabId));
10613
11262
  throw new Error(msg);
10614
11263
  },
@@ -11049,7 +11698,10 @@ async function applyGeolocation(tabId, geo, applied, warnings) {
11049
11698
  const grantErr = origin ? await grantPermissionsFor(tabId, origin, ["geolocation"]).catch((e) => e) : null;
11050
11699
  const state = await permissionState(tabId, "geolocation");
11051
11700
  out.permission = state || "unknown";
11052
- if (state === "granted") return out;
11701
+ if (state === "granted") {
11702
+ await ensureInteractive(tabId).catch(() => {});
11703
+ return out;
11704
+ }
11053
11705
  if (!state || state === "error") {
11054
11706
  if (!grantErr) {
11055
11707
  warnings.push("定位权限已授予,但页面侧问不出 permissions 状态(这一页可能不是普通 http(s) 页面)——用之前先在页面里试一次 getCurrentPosition。");