dsh-agent-enhancer 0.3.13 → 0.3.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.en.md +5 -5
  2. package/README.md +5 -5
  3. package/lib/client/browser-agent/overlay.d.ts.map +1 -1
  4. package/lib/client/browser-agent/tab.d.ts.map +1 -1
  5. package/lib/client/dsh/settings-features.d.ts +2 -0
  6. package/lib/client/dsh/settings-features.d.ts.map +1 -1
  7. package/lib/client/dsh/settings.d.ts.map +1 -1
  8. package/lib/client/locales.d.ts +35 -1
  9. package/lib/client/locales.d.ts.map +1 -1
  10. package/lib/client/remote.d.ts +4 -1
  11. package/lib/client/remote.d.ts.map +1 -1
  12. package/lib/client.js +212 -27
  13. package/lib/client.js.map +1 -1
  14. package/lib/config.d.ts +4 -0
  15. package/lib/config.d.ts.map +1 -1
  16. package/lib/host/browser-agent/capture.d.ts +55 -0
  17. package/lib/host/browser-agent/capture.d.ts.map +1 -0
  18. package/lib/host/browser-agent/diagnose.d.ts +38 -0
  19. package/lib/host/browser-agent/diagnose.d.ts.map +1 -0
  20. package/lib/host/browser-agent/driver.d.ts +35 -0
  21. package/lib/host/browser-agent/driver.d.ts.map +1 -1
  22. package/lib/host/browser-agent/human-gate.d.ts +8 -0
  23. package/lib/host/browser-agent/human-gate.d.ts.map +1 -1
  24. package/lib/host/browser-agent/install.d.ts +18 -0
  25. package/lib/host/browser-agent/install.d.ts.map +1 -1
  26. package/lib/host/browser-agent/playwright-driver.d.ts +49 -5
  27. package/lib/host/browser-agent/playwright-driver.d.ts.map +1 -1
  28. package/lib/host/browser-agent/playwright-snapshot.d.ts +16 -2
  29. package/lib/host/browser-agent/playwright-snapshot.d.ts.map +1 -1
  30. package/lib/host/browser-agent/protocol.d.ts +17 -0
  31. package/lib/host/browser-agent/protocol.d.ts.map +1 -1
  32. package/lib/host/browser-agent/session-state.d.ts +24 -9
  33. package/lib/host/browser-agent/session-state.d.ts.map +1 -1
  34. package/lib/host/browser-agent/tab-registry.d.ts +32 -0
  35. package/lib/host/browser-agent/tab-registry.d.ts.map +1 -0
  36. package/lib/host/browser-agent/tab-scope.d.ts +22 -0
  37. package/lib/host/browser-agent/tab-scope.d.ts.map +1 -0
  38. package/lib/host/browser-agent/tools.d.ts +8 -0
  39. package/lib/host/browser-agent/tools.d.ts.map +1 -1
  40. package/lib/host/index.d.ts +10 -1
  41. package/lib/host/index.d.ts.map +1 -1
  42. package/lib/host/rpc.d.ts +331 -0
  43. package/lib/host/rpc.d.ts.map +1 -1
  44. package/lib/index.js +960 -118
  45. package/lib/index.js.map +4 -4
  46. package/package.json +11 -12
package/lib/index.js CHANGED
@@ -68,6 +68,8 @@ var DEFAULT_SETTINGS = {
68
68
  runAlertsLevel: "unfocused",
69
69
  browserAgentEnabled: false,
70
70
  browserAgentBrowser: "auto",
71
+ browserAgentDebugTools: false,
72
+ browserAgentIdleClose: true,
71
73
  webChatBridgeEnabled: true,
72
74
  instructionsSkillsEnabled: true,
73
75
  mcpConnectorsEnabled: true,
@@ -113,6 +115,8 @@ function resolveSettings(value) {
113
115
  runAlertsLevel: resolveRunAlertsLevel(value?.runAlertsLevel),
114
116
  browserAgentEnabled: value?.browserAgentEnabled ?? false,
115
117
  browserAgentBrowser: resolveBrowserAgentBrowser(value?.browserAgentBrowser),
118
+ browserAgentDebugTools: value?.browserAgentDebugTools === true,
119
+ browserAgentIdleClose: value?.browserAgentIdleClose !== false,
116
120
  webChatBridgeEnabled: value?.webChatBridgeEnabled ?? true,
117
121
  instructionsSkillsEnabled: value?.instructionsSkillsEnabled ?? true,
118
122
  mcpConnectorsEnabled: value?.mcpConnectorsEnabled ?? true,
@@ -358,6 +362,7 @@ var BrowserHumanGate = class {
358
362
  const request = {
359
363
  id,
360
364
  sessionId: input.sessionId,
365
+ kind: input.kind ?? "human",
361
366
  prompt: input.prompt,
362
367
  detail: input.detail,
363
368
  ...input.url === void 0 ? {} : { url: input.url }
@@ -605,7 +610,6 @@ function stopAgentBrowserProcesses(profileDir) {
605
610
 
606
611
  // src/host/browser-agent/playwright-driver.ts
607
612
  import { existsSync as existsSync2, mkdirSync } from "node:fs";
608
- import { chromium, webkit } from "playwright-core";
609
613
 
610
614
  // src/host/browser-agent/proximity.ts
611
615
  function attachHrefByProximity(nodes, anchors) {
@@ -675,7 +679,7 @@ function attachHrefByProximity(nodes, anchors) {
675
679
  }
676
680
 
677
681
  // src/host/browser-agent/playwright-snapshot.ts
678
- var PLAYWRIGHT_DRIVER_VERSION = "pw-0.1.0";
682
+ var PLAYWRIGHT_DRIVER_VERSION = "pw-0.2.0";
679
683
  var PLAYWRIGHT_REF_ATTR = "data-dsh-ba-ref";
680
684
  var MAX_NODES = 80;
681
685
  var HARVEST_PAGE_SNAPSHOT_SOURCE = `"use strict";
@@ -851,7 +855,32 @@ for (var ri = 0; ri < records.length; ri++) {
851
855
  preferred.setAttribute(attr, String(rec.ref));
852
856
  }
853
857
  `;
854
- async function capturePlaywrightSnapshot(page) {
858
+ function selectSnapshotRows(rows, max) {
859
+ const budget = Math.max(0, Math.trunc(max));
860
+ if (budget === 0) return [];
861
+ const links = rows.filter((row) => row.priority <= 0);
862
+ const controls = rows.filter((row) => row.priority === 1);
863
+ const anchors = rows.filter((row) => row.priority > 1);
864
+ const controlSlots = Math.min(controls.length, Math.max(1, Math.floor(budget / 2)));
865
+ const linkSlots = Math.min(links.length, budget - controlSlots);
866
+ let remaining = budget - controlSlots - linkSlots;
867
+ const anchorSlots = Math.min(anchors.length, remaining);
868
+ remaining -= anchorSlots;
869
+ const picked = /* @__PURE__ */ new Set([
870
+ ...controls.slice(0, controlSlots),
871
+ ...links.slice(0, linkSlots),
872
+ ...anchors.slice(0, anchorSlots)
873
+ ]);
874
+ if (remaining > 0) {
875
+ for (const row of [...links.slice(linkSlots), ...controls.slice(controlSlots)]) {
876
+ if (remaining === 0) break;
877
+ picked.add(row);
878
+ remaining -= 1;
879
+ }
880
+ }
881
+ return rows.filter((row) => picked.has(row));
882
+ }
883
+ async function capturePlaywrightSnapshot(page, options = {}) {
855
884
  const harvest = await page.evaluate(`(() => { ${HARVEST_PAGE_SNAPSHOT_SOURCE} })()`);
856
885
  const proximityNodes = harvest.interactive.map((item) => ({
857
886
  href: item.href,
@@ -880,7 +909,10 @@ async function capturePlaywrightSnapshot(page) {
880
909
  x: typeof node.x === "number" ? node.x : 0,
881
910
  y: typeof node.y === "number" ? node.y : 0,
882
911
  sensitive: item?.sensitive === true,
883
- priority: node.priority ?? (href ? 0 : 1)
912
+ // Rank by element kind, not by whether proximity bound an href: a button
913
+ // sitting near a link would otherwise be treated as a link and lose the
914
+ // node budget to real anchors.
915
+ priority: (item?.tag ?? "a") === "a" ? 0 : 1
884
916
  };
885
917
  });
886
918
  const knownHrefs = new Set(rows.map((r) => r.href).filter((h) => h !== ""));
@@ -895,15 +927,17 @@ async function capturePlaywrightSnapshot(page) {
895
927
  x: anchor.x + anchor.w / 2,
896
928
  y: anchor.y + anchor.h / 2,
897
929
  sensitive: false,
898
- priority: 0
930
+ // 2, not 0: a synthetic anchor (harvested from geometry, not an element)
931
+ // must never push a real button/input out of the node budget.
932
+ priority: 2
899
933
  });
900
934
  }
901
- rows.sort((a, b) => a.priority - b.priority);
902
- const limited = rows.slice(0, MAX_NODES);
935
+ const limited = selectSnapshotRows(rows, MAX_NODES);
903
936
  const nodes = [];
904
937
  const refs = /* @__PURE__ */ new Map();
938
+ const refBase = Number.isFinite(options.startRef) ? Math.max(1, Math.trunc(options.startRef)) : 1;
905
939
  for (const row of limited) {
906
- const ref = nodes.length + 1;
940
+ const ref = refBase + nodes.length;
907
941
  nodes.push({
908
942
  ref,
909
943
  role: row.role,
@@ -939,10 +973,14 @@ async function capturePlaywrightSnapshot(page) {
939
973
  title: await page.title().catch(() => ""),
940
974
  nodes,
941
975
  textPreview: harvest.textPreview,
942
- tabId: 1,
943
976
  source: harvest.anchors.length > 0 || proximityHits > 0 ? "playwright+anchors" : "playwright",
944
977
  extensionVersion: PLAYWRIGHT_DRIVER_VERSION,
945
978
  anchorCount: harvest.anchors.length,
979
+ harvest: {
980
+ interactive: harvest.interactive.length,
981
+ controls: rows.filter((row) => row.priority === 1).length,
982
+ anchors: proximityAnchors.length
983
+ },
946
984
  ...withHref === 0 ? {
947
985
  note: `No http(s) href on interactive refs yet (anchors_in_dom=${harvest.anchors.length}). browser_wait then browser_snapshot again.`
948
986
  } : proximityHits > 0 ? { note: `Bound ${proximityHits} ref(s) to nearby document hrefs (anchors_in_dom=${harvest.anchors.length}).` } : { note: `anchors_in_dom=${harvest.anchors.length}` }
@@ -950,6 +988,60 @@ async function capturePlaywrightSnapshot(page) {
950
988
  return { body, refs };
951
989
  }
952
990
 
991
+ // src/host/browser-agent/capture.ts
992
+ var SECRET_PARAM = /^(access_?token|id_?token|auth|authorization|code|key|password|secret|session|sessionid|sig|signature|token)$/i;
993
+ var URL_IN_TEXT = /https?:\/\/[^\s"'<>]+/g;
994
+ function redactUrl(raw) {
995
+ const withoutUserInfo = raw.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, "$1");
996
+ const withoutFragment = withoutUserInfo.replace(/#.*$/, "");
997
+ const masked = withoutFragment.replace(
998
+ /([?&])([^=&#]+)=([^&#]*)/g,
999
+ (match, separator, key) => SECRET_PARAM.test(decodeURIComponent(key)) ? `${separator}${key}=***` : match
1000
+ );
1001
+ return masked.length > 300 ? `${masked.slice(0, 300)}\u2026` : masked;
1002
+ }
1003
+ function redactText(text3) {
1004
+ return text3.replace(URL_IN_TEXT, (match) => {
1005
+ const trailing = match.match(/[),.;]+$/)?.[0] ?? "";
1006
+ const core = trailing === "" ? match : match.slice(0, -trailing.length);
1007
+ return `${redactUrl(core)}${trailing}`;
1008
+ });
1009
+ }
1010
+ var CaptureBuffer = class {
1011
+ constructor(max = 300) {
1012
+ this.max = max;
1013
+ }
1014
+ max;
1015
+ entries = [];
1016
+ dropped = 0;
1017
+ get size() {
1018
+ return this.entries.length;
1019
+ }
1020
+ push(entry) {
1021
+ this.entries.push(entry);
1022
+ while (this.entries.length > this.max) {
1023
+ this.entries.shift();
1024
+ this.dropped += 1;
1025
+ }
1026
+ }
1027
+ /** Newest `limit` entries of the requested kind, optionally clearing them. */
1028
+ read(kind, options = {}) {
1029
+ const limit = Math.min(Math.max(Math.trunc(options.limit ?? 40), 1), 200);
1030
+ const matched = this.entries.filter((entry) => kind === "all" || entry.kind === (kind === "network" ? "request" : "console"));
1031
+ const selected = matched.slice(-limit);
1032
+ if (options.clear === true) {
1033
+ const keep = this.entries.filter((entry) => !selected.includes(entry));
1034
+ this.entries.length = 0;
1035
+ this.entries.push(...keep);
1036
+ }
1037
+ return { entries: selected, dropped: this.dropped };
1038
+ }
1039
+ clear() {
1040
+ this.entries.length = 0;
1041
+ this.dropped = 0;
1042
+ }
1043
+ };
1044
+
953
1045
  // src/host/browser-agent/auto-nav.ts
954
1046
  function pathKey(raw) {
955
1047
  try {
@@ -1006,7 +1098,70 @@ function pickAutoNavigateHref(links, beforeUrl, preferredName = "") {
1006
1098
  return best;
1007
1099
  }
1008
1100
 
1101
+ // src/host/browser-agent/tab-registry.ts
1102
+ var EMPTY_REFS = /* @__PURE__ */ new Map();
1103
+ var TabRegistry = class {
1104
+ idByPage = /* @__PURE__ */ new WeakMap();
1105
+ pageById = /* @__PURE__ */ new Map();
1106
+ refsById = /* @__PURE__ */ new Map();
1107
+ nextId = 1;
1108
+ /** Stable id for a page, assigned on first sight. */
1109
+ idOf(page) {
1110
+ const known = this.idByPage.get(page);
1111
+ if (known !== void 0) return known;
1112
+ const id = this.nextId;
1113
+ this.nextId += 1;
1114
+ this.idByPage.set(page, id);
1115
+ this.pageById.set(id, page);
1116
+ this.refsById.set(id, /* @__PURE__ */ new Map());
1117
+ return id;
1118
+ }
1119
+ /** Forget a closed page. Its id is retired, never handed to another page. */
1120
+ release(page) {
1121
+ const id = this.idByPage.get(page);
1122
+ if (id === void 0) return;
1123
+ this.idByPage.delete(page);
1124
+ this.pageById.delete(id);
1125
+ this.refsById.delete(id);
1126
+ }
1127
+ page(tabId) {
1128
+ return this.pageById.get(tabId);
1129
+ }
1130
+ refsOf(tabId) {
1131
+ return this.refsById.get(tabId) ?? EMPTY_REFS;
1132
+ }
1133
+ ref(tabId, ref) {
1134
+ return this.refsById.get(tabId)?.get(ref);
1135
+ }
1136
+ setRefs(tabId, refs) {
1137
+ this.refsById.set(tabId, new Map(refs));
1138
+ }
1139
+ clearRefs(tabId) {
1140
+ this.refsById.set(tabId, /* @__PURE__ */ new Map());
1141
+ }
1142
+ /** Which other tab still holds this ref — used to explain a cross-tab mistake. */
1143
+ tabHolding(ref, exceptTabId) {
1144
+ for (const [tabId, refs] of this.refsById) {
1145
+ if (tabId !== exceptTabId && refs.has(ref)) return tabId;
1146
+ }
1147
+ return void 0;
1148
+ }
1149
+ /** Actionable message for a ref that is not in the active tab. */
1150
+ unknownRefMessage(ref, activeTabId) {
1151
+ const other = this.tabHolding(ref, activeTabId);
1152
+ if (other !== void 0) {
1153
+ return `Ref ${ref} belongs to tab ${other}; tab ${activeTabId} is active. Switch back with browser_follow_tab (tabId ${other}) or call browser_snapshot for refs in this tab.`;
1154
+ }
1155
+ return `Unknown ref ${ref}; call browser_snapshot first`;
1156
+ }
1157
+ };
1158
+
1009
1159
  // src/host/browser-agent/playwright-driver.ts
1160
+ var playwrightModule = null;
1161
+ async function loadPlaywright() {
1162
+ playwrightModule ??= await import("playwright-core");
1163
+ return playwrightModule;
1164
+ }
1010
1165
  var PlaywrightDriver = class {
1011
1166
  kind = "playwright";
1012
1167
  profileDirOption;
@@ -1018,7 +1173,18 @@ var PlaywrightDriver = class {
1018
1173
  lastError = null;
1019
1174
  channel = null;
1020
1175
  launchedProfileDir = null;
1021
- lastRefs = /* @__PURE__ */ new Map();
1176
+ tabs = new TabRegistry();
1177
+ trackedPages = /* @__PURE__ */ new WeakSet();
1178
+ /** Monotonic per-driver ref counter, so refs never collide across tabs. */
1179
+ nextRef = 1;
1180
+ /** Null until the debug tools ask for capture; stays on for the driver lifetime. */
1181
+ capture = null;
1182
+ captureStartedPages = /* @__PURE__ */ new WeakSet();
1183
+ requestStart = /* @__PURE__ */ new WeakMap();
1184
+ /** Last applied emulation per tab, echoed in snapshot so the agent can see it. */
1185
+ emulationByTab = /* @__PURE__ */ new Map();
1186
+ /** Last agent/UI use per page; a page's clock starts when it is first seen. */
1187
+ lastUse = /* @__PURE__ */ new WeakMap();
1022
1188
  constructor(options) {
1023
1189
  this.profileDirOption = options.profileDir;
1024
1190
  this.preferenceOption = options.preference ?? "auto";
@@ -1038,9 +1204,56 @@ var PlaywrightDriver = class {
1038
1204
  }
1039
1205
  return this.currentProfileDir();
1040
1206
  }
1041
- /** Latest snapshot refs — used by the click/type path. */
1042
- refOf(ref) {
1043
- return this.lastRefs.get(ref);
1207
+ /**
1208
+ * Stable id for a page, and the place its refs live. Ids survive other tabs
1209
+ * opening/closing and are never reused; refs stay with the tab that captured
1210
+ * them, so switching tabs no longer invalidates the snapshot you came from.
1211
+ */
1212
+ tabIdFor(page) {
1213
+ const tabId = this.tabs.idOf(page);
1214
+ if (!this.lastUse.has(page)) this.lastUse.set(page, Date.now());
1215
+ if (!this.trackedPages.has(page)) {
1216
+ this.trackedPages.add(page);
1217
+ page.on("close", () => {
1218
+ this.tabs.release(page);
1219
+ this.emulationByTab.delete(tabId);
1220
+ this.trackedPages.delete(page);
1221
+ });
1222
+ }
1223
+ return tabId;
1224
+ }
1225
+ clearRefs(page) {
1226
+ this.tabs.clearRefs(this.tabIdFor(page));
1227
+ }
1228
+ /** Any real use of a page resets its idle clock; sidebar listing does not. */
1229
+ touch(page) {
1230
+ this.lastUse.set(page, Date.now());
1231
+ }
1232
+ async sweepIdleTabs(input) {
1233
+ const context = this.context;
1234
+ if (context === null) return [];
1235
+ const keep = new Set(input.keep ?? []);
1236
+ const pages = context.pages();
1237
+ const closed = [];
1238
+ const now = Date.now();
1239
+ for (const page of pages) {
1240
+ if (pages.length - closed.length <= 1) break;
1241
+ if (page === this.page || page.isClosed()) continue;
1242
+ const tabId = this.tabIdFor(page);
1243
+ if (keep.has(tabId)) continue;
1244
+ const last = this.lastUse.get(page) ?? now;
1245
+ if (now - last < input.idleMs) continue;
1246
+ await page.close().catch(() => void 0);
1247
+ if (page.isClosed()) closed.push(tabId);
1248
+ }
1249
+ return closed;
1250
+ }
1251
+ /** Page still attached to this context and not closed. */
1252
+ isLivePage(page) {
1253
+ if (page === null || typeof page !== "object") return false;
1254
+ const candidate = page;
1255
+ if (typeof candidate.isClosed !== "function" || candidate.isClosed()) return false;
1256
+ return this.context?.pages().includes(candidate) === true;
1044
1257
  }
1045
1258
  status() {
1046
1259
  const ready = this.context !== null && this.page !== null && !this.page.isClosed();
@@ -1093,7 +1306,7 @@ var PlaywrightDriver = class {
1093
1306
  this.context = null;
1094
1307
  this.page = null;
1095
1308
  this.launchedProfileDir = null;
1096
- this.lastRefs.clear();
1309
+ this.capture = null;
1097
1310
  });
1098
1311
  return;
1099
1312
  } catch (error) {
@@ -1122,6 +1335,7 @@ var PlaywrightDriver = class {
1122
1335
  }
1123
1336
  }
1124
1337
  let webkitExe;
1338
+ const { webkit } = await loadPlaywright();
1125
1339
  try {
1126
1340
  webkitExe = webkit.executablePath();
1127
1341
  } catch (error) {
@@ -1149,6 +1363,7 @@ var PlaywrightDriver = class {
1149
1363
  this.lastError = `${kind} is not installed or not found on PATH`;
1150
1364
  return null;
1151
1365
  }
1366
+ const { chromium } = await loadPlaywright();
1152
1367
  return chromium.launchPersistentContext(profileDir, {
1153
1368
  executablePath: resolved.executable,
1154
1369
  headless: this.headless,
@@ -1176,6 +1391,7 @@ var PlaywrightDriver = class {
1176
1391
  if (this.page === null || this.page.isClosed()) {
1177
1392
  throw new Error("Playwright page is not available");
1178
1393
  }
1394
+ this.touch(this.page);
1179
1395
  return this.page;
1180
1396
  }
1181
1397
  async pageStatus() {
@@ -1184,7 +1400,7 @@ var PlaywrightDriver = class {
1184
1400
  connected: true,
1185
1401
  url: page.url(),
1186
1402
  title: await page.title().catch(() => ""),
1187
- tabId: tabIdOf(page.context(), page),
1403
+ tabId: this.tabIdFor(page),
1188
1404
  bound: true
1189
1405
  };
1190
1406
  }
@@ -1199,18 +1415,22 @@ var PlaywrightDriver = class {
1199
1415
  }
1200
1416
  await page.goto(url, { waitUntil: "domcontentloaded" });
1201
1417
  await settlePage(page);
1202
- this.lastRefs.clear();
1418
+ this.touch(page);
1419
+ this.clearRefs(page);
1203
1420
  return {
1204
1421
  url: page.url(),
1205
1422
  title: await page.title().catch(() => ""),
1206
- tabId: tabIdOf(page.context(), page)
1423
+ tabId: this.tabIdFor(page)
1207
1424
  };
1208
1425
  }
1209
1426
  async snapshot() {
1210
1427
  const page = await this.requirePage();
1211
- const { body, refs } = await capturePlaywrightSnapshot(page);
1212
- this.lastRefs = new Map(refs);
1213
- return { ...body, tabId: tabIdOf(page.context(), page) };
1428
+ const tabId = this.tabIdFor(page);
1429
+ const { body, refs } = await capturePlaywrightSnapshot(page, { startRef: this.nextRef });
1430
+ this.nextRef += body.nodes.length;
1431
+ this.tabs.setRefs(tabId, refs);
1432
+ const emulation = this.emulationByTab.get(tabId);
1433
+ return { ...body, ...emulation === void 0 ? {} : { emulation }, tabId };
1214
1434
  }
1215
1435
  async extract(input = {}) {
1216
1436
  const page = await this.requirePage();
@@ -1223,14 +1443,15 @@ var PlaywrightDriver = class {
1223
1443
  text: clipped.slice(0, maxChars),
1224
1444
  truncated: clipped.length > maxChars,
1225
1445
  ...input.focus === void 0 || input.focus.trim() === "" ? {} : { focus: input.focus.trim() },
1226
- tabId: tabIdOf(page.context(), page)
1446
+ tabId: this.tabIdFor(page)
1227
1447
  };
1228
1448
  }
1229
1449
  async click(ref) {
1230
1450
  const page = await this.requirePage();
1231
- const record2 = this.lastRefs.get(ref);
1451
+ const tabId = this.tabIdFor(page);
1452
+ const record2 = this.tabs.ref(tabId, ref);
1232
1453
  if (record2 === void 0) {
1233
- throw new Error(`Unknown ref ${ref}; call browser_snapshot first`);
1454
+ throw new Error(this.tabs.unknownRefMessage(ref, tabId));
1234
1455
  }
1235
1456
  const beforeUrl = page.url();
1236
1457
  const href = /^https?:\/\//i.test(record2.href) ? record2.href : "";
@@ -1246,14 +1467,14 @@ var PlaywrightDriver = class {
1246
1467
  if (href !== "" && pathsDiffer(beforeUrl, href)) {
1247
1468
  await page.goto(href, { waitUntil: "domcontentloaded" });
1248
1469
  await settlePage(page);
1249
- this.lastRefs.clear();
1470
+ this.clearRefs(page);
1250
1471
  const after = page.url();
1251
1472
  return {
1252
1473
  url: after,
1253
1474
  title: await page.title().catch(() => ""),
1254
1475
  changed: pathsDiffer(beforeUrl, after),
1255
1476
  href,
1256
- tabId: tabIdOf(page.context(), page),
1477
+ tabId: this.tabIdFor(page),
1257
1478
  warning: "Opened this ref's href after snapshot bound a nearby document link."
1258
1479
  };
1259
1480
  }
@@ -1265,14 +1486,14 @@ var PlaywrightDriver = class {
1265
1486
  const adopted = await adoptPopup(popup, beforeUrl);
1266
1487
  if (adopted) {
1267
1488
  this.page = popup;
1268
- this.lastRefs.clear();
1489
+ this.clearRefs(page);
1269
1490
  await settlePage(popup);
1270
1491
  return {
1271
1492
  url: popup.url(),
1272
1493
  title: await popup.title().catch(() => ""),
1273
1494
  changed: true,
1274
1495
  ...href !== "" ? { href } : {},
1275
- tabId: tabIdOf(context, popup),
1496
+ tabId: this.tabIdFor(popup),
1276
1497
  warning: "Click opened a new tab; rebound the browser-agent session to it."
1277
1498
  };
1278
1499
  }
@@ -1296,7 +1517,7 @@ var PlaywrightDriver = class {
1296
1517
  changed = pathsDiffer(beforeUrl, afterUrl);
1297
1518
  followedHref = changed;
1298
1519
  }
1299
- this.lastRefs.clear();
1520
+ this.clearRefs(page);
1300
1521
  let pageLinks = [];
1301
1522
  if (!changed && href === "") {
1302
1523
  pageLinks = await listHttpAnchors(page);
@@ -1305,7 +1526,7 @@ var PlaywrightDriver = class {
1305
1526
  url: afterUrl,
1306
1527
  title: await page.title().catch(() => ""),
1307
1528
  changed,
1308
- tabId: tabIdOf(page.context(), page),
1529
+ tabId: this.tabIdFor(page),
1309
1530
  ...href !== "" ? { href } : {},
1310
1531
  ...pageLinks.length > 0 ? { pageLinks: pageLinks.slice(0, 8) } : {},
1311
1532
  ...followedHref ? { warning: "Click missed; opened this ref's own href via navigation." } : !changed ? {
@@ -1317,14 +1538,14 @@ var PlaywrightDriver = class {
1317
1538
  if (href !== "" && pathsDiffer(beforeUrl, href)) {
1318
1539
  await page.goto(href, { waitUntil: "domcontentloaded" });
1319
1540
  await settlePage(page);
1320
- this.lastRefs.clear();
1541
+ this.clearRefs(page);
1321
1542
  const after = page.url();
1322
1543
  return {
1323
1544
  url: after,
1324
1545
  title: await page.title().catch(() => ""),
1325
1546
  changed: pathsDiffer(beforeUrl, after),
1326
1547
  href,
1327
- tabId: tabIdOf(page.context(), page),
1548
+ tabId: this.tabIdFor(page),
1328
1549
  warning: "Ref stamp missing; opened this ref's href directly."
1329
1550
  };
1330
1551
  }
@@ -1334,12 +1555,12 @@ var PlaywrightDriver = class {
1334
1555
  await settlePage(page);
1335
1556
  const afterUrl = page.url();
1336
1557
  const changed = pathsDiffer(beforeUrl, afterUrl);
1337
- this.lastRefs.clear();
1558
+ this.clearRefs(page);
1338
1559
  return {
1339
1560
  url: afterUrl,
1340
1561
  title: await page.title().catch(() => ""),
1341
1562
  changed,
1342
- tabId: tabIdOf(page.context(), page),
1563
+ tabId: this.tabIdFor(page),
1343
1564
  ...href !== "" ? { href } : {},
1344
1565
  ...!changed ? {
1345
1566
  warning: "Pathname unchanged after coordinate click. browser_snapshot again or browser_navigate by href."
@@ -1348,8 +1569,9 @@ var PlaywrightDriver = class {
1348
1569
  }
1349
1570
  async type(ref, text3) {
1350
1571
  const page = await this.requirePage();
1351
- if (this.lastRefs.get(ref) === void 0) {
1352
- throw new Error(`Unknown ref ${ref}; call browser_snapshot first`);
1572
+ const tabId = this.tabIdFor(page);
1573
+ if (this.tabs.ref(tabId, ref) === void 0) {
1574
+ throw new Error(this.tabs.unknownRefMessage(ref, tabId));
1353
1575
  }
1354
1576
  const locator = page.locator(`[${PLAYWRIGHT_REF_ATTR}="${ref}"]`).first();
1355
1577
  const count = await locator.count().catch(() => 0);
@@ -1364,12 +1586,12 @@ var PlaywrightDriver = class {
1364
1586
  await locator.pressSequentially(text3, { delay: 10 });
1365
1587
  }
1366
1588
  await settlePage(page);
1367
- this.lastRefs.clear();
1589
+ this.clearRefs(page);
1368
1590
  return {
1369
1591
  url: page.url(),
1370
1592
  title: await page.title().catch(() => ""),
1371
1593
  changed: false,
1372
- tabId: tabIdOf(page.context(), page)
1594
+ tabId: this.tabIdFor(page)
1373
1595
  };
1374
1596
  }
1375
1597
  async scroll(dy) {
@@ -1380,7 +1602,7 @@ var PlaywrightDriver = class {
1380
1602
  url: page.url(),
1381
1603
  title: await page.title().catch(() => ""),
1382
1604
  changed: false,
1383
- tabId: tabIdOf(page.context(), page)
1605
+ tabId: this.tabIdFor(page)
1384
1606
  };
1385
1607
  }
1386
1608
  async wait(input = {}) {
@@ -1401,7 +1623,7 @@ var PlaywrightDriver = class {
1401
1623
  url: page.url(),
1402
1624
  title: await page.title().catch(() => ""),
1403
1625
  matched,
1404
- tabId: tabIdOf(page.context(), page)
1626
+ tabId: this.tabIdFor(page)
1405
1627
  };
1406
1628
  }
1407
1629
  async screenshot() {
@@ -1410,7 +1632,7 @@ var PlaywrightDriver = class {
1410
1632
  return {
1411
1633
  mime: "image/png",
1412
1634
  base64: buf.toString("base64"),
1413
- tabId: tabIdOf(page.context(), page)
1635
+ tabId: this.tabIdFor(page)
1414
1636
  };
1415
1637
  }
1416
1638
  async listTabs() {
@@ -1419,25 +1641,151 @@ var PlaywrightDriver = class {
1419
1641
  return { tabs: [], boundTabId: null };
1420
1642
  }
1421
1643
  return {
1422
- tabs: await Promise.all(pages.map(async (p, index) => ({
1423
- tabId: index + 1,
1644
+ tabs: await Promise.all(pages.map(async (p) => ({
1645
+ tabId: this.tabIdFor(p),
1424
1646
  title: await p.title().catch(() => ""),
1425
1647
  url: p.url(),
1426
1648
  active: p === this.page,
1427
- // Session bind is layered in install.listTabs; driver marks the live page.
1428
- bound: p === this.page
1649
+ // Session bind and read-only scope are layered in install.listTabs.
1650
+ bound: p === this.page,
1651
+ readOnly: false
1429
1652
  }))),
1430
- boundTabId: this.page ? pages.indexOf(this.page) + 1 : null
1653
+ boundTabId: this.page === null ? null : this.tabIdFor(this.page)
1431
1654
  };
1432
1655
  }
1656
+ startCapture() {
1657
+ if (this.capture !== null) return;
1658
+ const context = this.context;
1659
+ if (context === null) return;
1660
+ this.capture = new CaptureBuffer(300);
1661
+ for (const page of context.pages()) this.attachCapture(page);
1662
+ context.on("page", (page) => this.attachCapture(page));
1663
+ }
1664
+ attachCapture(page) {
1665
+ const buffer = this.capture;
1666
+ if (buffer === null || this.captureStartedPages.has(page)) return;
1667
+ this.captureStartedPages.add(page);
1668
+ const tabId = this.tabIdFor(page);
1669
+ const stamp = () => Date.now();
1670
+ page.on("console", (message) => {
1671
+ try {
1672
+ buffer.push({
1673
+ kind: "console",
1674
+ at: stamp(),
1675
+ tabId,
1676
+ level: message.type(),
1677
+ // Console text can embed a request URL, so it gets the same masking as
1678
+ // the network layer; otherwise a failed fetch leaks its query string.
1679
+ text: clipText(redactText(message.text()), 500),
1680
+ ...message.location().url === "" ? {} : { location: redactText(`${message.location().url}:${message.location().lineNumber}`) }
1681
+ });
1682
+ } catch {
1683
+ }
1684
+ });
1685
+ page.on("pageerror", (error) => {
1686
+ buffer.push({
1687
+ kind: "console",
1688
+ at: stamp(),
1689
+ tabId,
1690
+ level: "pageerror",
1691
+ text: clipText(redactText(error instanceof Error ? error.message : String(error)), 500)
1692
+ });
1693
+ });
1694
+ page.on("request", (request) => {
1695
+ this.requestStart.set(request, performance.now());
1696
+ });
1697
+ page.on("response", (response) => {
1698
+ const request = response.request();
1699
+ const started = this.requestStart.get(request);
1700
+ buffer.push({
1701
+ kind: "request",
1702
+ at: stamp(),
1703
+ tabId,
1704
+ method: request.method(),
1705
+ url: redactUrl(response.url()),
1706
+ resourceType: request.resourceType(),
1707
+ status: response.status(),
1708
+ ...started === void 0 ? {} : { durationMs: Math.round(performance.now() - started) }
1709
+ });
1710
+ });
1711
+ page.on("requestfailed", (request) => {
1712
+ const started = this.requestStart.get(request);
1713
+ buffer.push({
1714
+ kind: "request",
1715
+ at: stamp(),
1716
+ tabId,
1717
+ method: request.method(),
1718
+ url: redactUrl(request.url()),
1719
+ resourceType: request.resourceType(),
1720
+ ...started === void 0 ? {} : { durationMs: Math.round(performance.now() - started) },
1721
+ failure: clipText(request.failure()?.errorText ?? "request failed", 160)
1722
+ });
1723
+ });
1724
+ }
1725
+ readCapture(input) {
1726
+ if (this.capture === null) return { entries: [], dropped: 0 };
1727
+ return this.capture.read(input.kind, {
1728
+ ...input.limit === void 0 ? {} : { limit: input.limit },
1729
+ ...input.clear === void 0 ? {} : { clear: input.clear }
1730
+ });
1731
+ }
1732
+ async emulate(input) {
1733
+ const page = await this.requirePage();
1734
+ const applied = [];
1735
+ const media = {};
1736
+ if (input.colorScheme !== void 0) {
1737
+ media.colorScheme = input.colorScheme === "reset" ? null : input.colorScheme;
1738
+ applied.push(`colorScheme=${input.colorScheme}`);
1739
+ }
1740
+ if (input.reducedMotion !== void 0) {
1741
+ media.reducedMotion = input.reducedMotion === "reset" ? null : input.reducedMotion;
1742
+ applied.push(`reducedMotion=${input.reducedMotion}`);
1743
+ }
1744
+ if (Object.keys(media).length > 0) await page.emulateMedia(media);
1745
+ if (input.viewport !== void 0) {
1746
+ const width = Math.min(Math.max(Math.trunc(input.viewport.width), 320), 3840);
1747
+ const height = Math.min(Math.max(Math.trunc(input.viewport.height), 240), 2160);
1748
+ await page.setViewportSize({ width, height });
1749
+ applied.push(`viewport=${width}x${height}`);
1750
+ }
1751
+ const tabId = this.tabIdFor(page);
1752
+ this.rememberEmulation(tabId, input);
1753
+ return {
1754
+ url: page.url(),
1755
+ title: await page.title().catch(() => ""),
1756
+ applied,
1757
+ tabId: this.tabIdFor(page)
1758
+ };
1759
+ }
1760
+ /** Record what is now emulated on this tab, so snapshot can echo it. */
1761
+ rememberEmulation(tabId, input) {
1762
+ const next = { ...this.emulationByTab.get(tabId) ?? {} };
1763
+ if (input.colorScheme !== void 0) {
1764
+ if (input.colorScheme === "reset") delete next.colorScheme;
1765
+ else next.colorScheme = input.colorScheme;
1766
+ }
1767
+ if (input.reducedMotion !== void 0) {
1768
+ if (input.reducedMotion === "reset") delete next.reducedMotion;
1769
+ else next.reducedMotion = input.reducedMotion;
1770
+ }
1771
+ if (input.viewport !== void 0) {
1772
+ next.viewport = {
1773
+ width: Math.min(Math.max(Math.trunc(input.viewport.width), 320), 3840),
1774
+ height: Math.min(Math.max(Math.trunc(input.viewport.height), 240), 2160)
1775
+ };
1776
+ }
1777
+ if (Object.keys(next).length === 0) this.emulationByTab.delete(tabId);
1778
+ else this.emulationByTab.set(tabId, next);
1779
+ }
1433
1780
  async followTab(tabId, _activate = false) {
1434
1781
  await this.ensureReady();
1435
- const pages = this.context?.pages() ?? [];
1436
- const page = pages[tabId - 1];
1437
- if (page === void 0) throw new Error(`No Playwright page for tabId ${tabId}`);
1438
- this.page = page;
1439
- this.lastRefs.clear();
1440
- return { tabId, url: page.url(), title: await page.title().catch(() => "") };
1782
+ const candidate = this.tabs.page(tabId);
1783
+ if (!this.isLivePage(candidate)) {
1784
+ throw new Error(`No running browser tab for tabId ${tabId} (it may have been closed); call browser_list_tabs for current ids`);
1785
+ }
1786
+ this.page = candidate;
1787
+ this.touch(candidate);
1788
+ return { tabId, url: candidate.url(), title: await candidate.title().catch(() => "") };
1441
1789
  }
1442
1790
  async bind(tabId, _sessionId) {
1443
1791
  return this.followTab(tabId, true);
@@ -1449,7 +1797,7 @@ var PlaywrightDriver = class {
1449
1797
  this.page = null;
1450
1798
  this.channel = null;
1451
1799
  this.launchedProfileDir = null;
1452
- this.lastRefs.clear();
1800
+ this.capture = null;
1453
1801
  if (ctx !== null) {
1454
1802
  await ctx.close().catch(() => void 0);
1455
1803
  }
@@ -1463,6 +1811,10 @@ function sleep(ms) {
1463
1811
  setTimeout(resolve17, ms);
1464
1812
  });
1465
1813
  }
1814
+ function clipText(text3, max) {
1815
+ const flat = text3.replace(/\s+/g, " ").trim();
1816
+ return flat.length > max ? `${flat.slice(0, max)}\u2026` : flat;
1817
+ }
1466
1818
  async function settlePage(page, quietMs = 800) {
1467
1819
  await page.waitForLoadState("domcontentloaded").catch(() => void 0);
1468
1820
  await Promise.race([
@@ -1482,11 +1834,6 @@ async function adoptPopup(popup, beforeUrl) {
1482
1834
  const url = popup.isClosed() ? "" : popup.url();
1483
1835
  return /^https?:\/\//i.test(url) && pathsDiffer(beforeUrl, url);
1484
1836
  }
1485
- function tabIdOf(context, page) {
1486
- const pages = context.pages();
1487
- const index = pages.indexOf(page);
1488
- return index >= 0 ? index + 1 : 1;
1489
- }
1490
1837
  async function listHttpAnchors(page) {
1491
1838
  return page.evaluate(`(() => {
1492
1839
  var out = [];
@@ -1559,22 +1906,43 @@ function registerBrowserAgentPrompt(ctx) {
1559
1906
 
1560
1907
  // src/host/browser-agent/session-state.ts
1561
1908
  var MAX_AUDIT = 40;
1909
+ function emptyMemory() {
1910
+ return { refs: /* @__PURE__ */ new Set(), hrefs: /* @__PURE__ */ new Map(), names: /* @__PURE__ */ new Map(), dead: /* @__PURE__ */ new Set() };
1911
+ }
1562
1912
  var BrowserSessionState = class {
1563
1913
  tabBySession = /* @__PURE__ */ new Map();
1564
1914
  sessionByTab = /* @__PURE__ */ new Map();
1565
1915
  needsHumanBySession = /* @__PURE__ */ new Map();
1566
- /** Refs from the latest successful browser_snapshot for this session. */
1567
- lastRefsBySession = /* @__PURE__ */ new Map();
1568
- /** Optional href per ref from the latest snapshot (follow only that ref's href after a dead click). */
1569
- lastHrefBySession = /* @__PURE__ */ new Map();
1570
- /** Optional accessible name per ref from the latest snapshot (name-matched auto-nav). */
1571
- lastNameBySession = /* @__PURE__ */ new Map();
1572
- /** Refs that already failed a click with no navigation — block re-click until a fresh snapshot. */
1573
- deadClickRefsBySession = /* @__PURE__ */ new Map();
1916
+ /**
1917
+ * Snapshot memory lives with the tab, not the session: refs captured in a tab
1918
+ * stay valid when the session switches away and back (refs are unique per
1919
+ * driver, so there is no cross-tab aliasing).
1920
+ */
1921
+ memoryByTab = /* @__PURE__ */ new Map();
1922
+ /** Snapshots taken before a tab is bound (rare, first call) land here. */
1923
+ memoryUnbound = /* @__PURE__ */ new Map();
1574
1924
  /** Last http(s) page URL for approval origin when pageStatus is blank/about:blank. */
1575
1925
  lastHttpUrlBySession = /* @__PURE__ */ new Map();
1576
1926
  conflict = null;
1577
1927
  audit = [];
1928
+ /** Memory for this session's current tab, creating it on first use. */
1929
+ memoryOf(sessionId) {
1930
+ const tabId = this.tabBySession.get(sessionId);
1931
+ if (tabId === void 0) {
1932
+ let memory2 = this.memoryUnbound.get(sessionId);
1933
+ if (memory2 === void 0) {
1934
+ memory2 = emptyMemory();
1935
+ this.memoryUnbound.set(sessionId, memory2);
1936
+ }
1937
+ return memory2;
1938
+ }
1939
+ let memory = this.memoryByTab.get(tabId);
1940
+ if (memory === void 0) {
1941
+ memory = emptyMemory();
1942
+ this.memoryByTab.set(tabId, memory);
1943
+ }
1944
+ return memory;
1945
+ }
1578
1946
  bind(sessionId, tabId) {
1579
1947
  const prev = this.tabBySession.get(sessionId);
1580
1948
  if (prev !== void 0 && prev !== tabId) this.sessionByTab.delete(prev);
@@ -1590,15 +1958,49 @@ var BrowserSessionState = class {
1590
1958
  sessionOf(tabId) {
1591
1959
  return this.sessionByTab.get(tabId);
1592
1960
  }
1961
+ /** Tab ids that some session is bound to; idle-close must never take these. */
1962
+ boundTabIds() {
1963
+ return [...this.sessionByTab.keys()];
1964
+ }
1965
+ /**
1966
+ * The tab went away (closed by idle sweep or by the user): drop the binding and
1967
+ * the refs captured there, so the next tool call re-snapshots instead of
1968
+ * resolving refs that no longer exist.
1969
+ */
1970
+ unbindTab(tabId) {
1971
+ const sessionId = this.sessionByTab.get(tabId);
1972
+ this.sessionByTab.delete(tabId);
1973
+ this.memoryByTab.delete(tabId);
1974
+ if (sessionId === void 0) return void 0;
1975
+ if (this.tabBySession.get(sessionId) === tabId) this.tabBySession.delete(sessionId);
1976
+ this.memoryUnbound.delete(sessionId);
1977
+ if (this.conflict?.sessionId === sessionId) this.conflict = null;
1978
+ return sessionId;
1979
+ }
1980
+ /** Which tab still holds this ref (refs are driver-unique), if any. */
1981
+ tabHoldingRef(ref, exceptTabId) {
1982
+ for (const [tabId, memory] of this.memoryByTab) {
1983
+ if (tabId === exceptTabId) continue;
1984
+ if (memory.refs.has(ref)) return tabId;
1985
+ }
1986
+ return void 0;
1987
+ }
1988
+ /** Drop snapshot memory for tabs that no longer exist. */
1989
+ retainTabs(tabIds) {
1990
+ const alive = new Set(tabIds);
1991
+ for (const tabId of [...this.memoryByTab.keys()]) {
1992
+ if (!alive.has(tabId)) this.memoryByTab.delete(tabId);
1993
+ }
1994
+ }
1593
1995
  clearSession(sessionId) {
1594
1996
  const tabId = this.tabBySession.get(sessionId);
1595
1997
  this.tabBySession.delete(sessionId);
1596
- if (tabId !== void 0) this.sessionByTab.delete(tabId);
1998
+ if (tabId !== void 0) {
1999
+ this.sessionByTab.delete(tabId);
2000
+ this.memoryByTab.delete(tabId);
2001
+ }
2002
+ this.memoryUnbound.delete(sessionId);
1597
2003
  this.needsHumanBySession.delete(sessionId);
1598
- this.lastRefsBySession.delete(sessionId);
1599
- this.lastHrefBySession.delete(sessionId);
1600
- this.lastNameBySession.delete(sessionId);
1601
- this.deadClickRefsBySession.delete(sessionId);
1602
2004
  this.lastHttpUrlBySession.delete(sessionId);
1603
2005
  if (this.conflict?.sessionId === sessionId) this.conflict = null;
1604
2006
  for (let i = this.audit.length - 1; i >= 0; i -= 1) {
@@ -1606,36 +2008,36 @@ var BrowserSessionState = class {
1606
2008
  }
1607
2009
  }
1608
2010
  setLastRefs(sessionId, refs) {
1609
- this.lastRefsBySession.set(sessionId, new Set(refs.filter((ref) => Number.isFinite(ref))));
1610
- this.deadClickRefsBySession.delete(sessionId);
2011
+ const memory = this.memoryOf(sessionId);
2012
+ memory.refs = new Set(refs.filter((ref) => Number.isFinite(ref)));
2013
+ memory.dead = /* @__PURE__ */ new Set();
1611
2014
  }
1612
2015
  setLastHrefs(sessionId, hrefs) {
1613
- this.lastHrefBySession.set(sessionId, hrefs);
2016
+ this.memoryOf(sessionId).hrefs = new Map(hrefs);
1614
2017
  }
1615
2018
  setLastNames(sessionId, names) {
1616
- this.lastNameBySession.set(sessionId, names);
2019
+ this.memoryOf(sessionId).names = new Map(names);
1617
2020
  }
1618
2021
  clearLastRefs(sessionId) {
1619
- this.lastRefsBySession.delete(sessionId);
1620
- this.lastHrefBySession.delete(sessionId);
1621
- this.lastNameBySession.delete(sessionId);
2022
+ const memory = this.memoryOf(sessionId);
2023
+ memory.refs = /* @__PURE__ */ new Set();
2024
+ memory.hrefs = /* @__PURE__ */ new Map();
2025
+ memory.names = /* @__PURE__ */ new Map();
1622
2026
  }
1623
2027
  markDeadClickRef(sessionId, ref) {
1624
- const set = this.deadClickRefsBySession.get(sessionId) ?? /* @__PURE__ */ new Set();
1625
- set.add(ref);
1626
- this.deadClickRefsBySession.set(sessionId, set);
2028
+ this.memoryOf(sessionId).dead.add(ref);
1627
2029
  }
1628
2030
  isDeadClickRef(sessionId, ref) {
1629
- return this.deadClickRefsBySession.get(sessionId)?.has(ref) === true;
2031
+ return this.memoryOf(sessionId).dead.has(ref);
1630
2032
  }
1631
2033
  hasRef(sessionId, ref) {
1632
- return this.lastRefsBySession.get(sessionId)?.has(ref) === true;
2034
+ return this.memoryOf(sessionId).refs.has(ref);
1633
2035
  }
1634
2036
  hrefOfRef(sessionId, ref) {
1635
- return this.lastHrefBySession.get(sessionId)?.get(ref);
2037
+ return this.memoryOf(sessionId).hrefs.get(ref);
1636
2038
  }
1637
2039
  nameOfRef(sessionId, ref) {
1638
- return this.lastNameBySession.get(sessionId)?.get(ref);
2040
+ return this.memoryOf(sessionId).names.get(ref);
1639
2041
  }
1640
2042
  rememberHttpUrl(sessionId, url) {
1641
2043
  if (!/^https?:\/\//i.test(url)) return;
@@ -1645,7 +2047,7 @@ var BrowserSessionState = class {
1645
2047
  return this.lastHttpUrlBySession.get(sessionId);
1646
2048
  }
1647
2049
  lastRefList(sessionId) {
1648
- return [...this.lastRefsBySession.get(sessionId) ?? []];
2050
+ return [...this.memoryOf(sessionId).refs];
1649
2051
  }
1650
2052
  setConflict(conflict) {
1651
2053
  this.conflict = conflict;
@@ -1656,18 +2058,18 @@ var BrowserSessionState = class {
1656
2058
  currentConflict() {
1657
2059
  return this.conflict;
1658
2060
  }
1659
- setNeedsHuman(sessionId, detail) {
1660
- this.needsHumanBySession.set(sessionId, detail);
2061
+ setNeedsHuman(sessionId, detail, kind = "human") {
2062
+ this.needsHumanBySession.set(sessionId, { detail, kind });
1661
2063
  }
1662
2064
  clearNeedsHuman(sessionId) {
1663
2065
  this.needsHumanBySession.delete(sessionId);
1664
2066
  }
1665
2067
  needsHuman(sessionId) {
1666
- return this.needsHumanBySession.get(sessionId);
2068
+ return this.needsHumanBySession.get(sessionId)?.detail;
1667
2069
  }
1668
2070
  anyNeedsHuman() {
1669
- for (const [sessionId, detail] of this.needsHumanBySession) {
1670
- return { sessionId, detail };
2071
+ for (const [sessionId, value] of this.needsHumanBySession) {
2072
+ return { sessionId, detail: value.detail, kind: value.kind };
1671
2073
  }
1672
2074
  return null;
1673
2075
  }
@@ -1680,6 +2082,101 @@ var BrowserSessionState = class {
1680
2082
  }
1681
2083
  };
1682
2084
 
2085
+ // src/host/browser-agent/tab-scope.ts
2086
+ var TabScopeStore = class {
2087
+ readOnlyTabs = /* @__PURE__ */ new Set();
2088
+ setReadOnly(tabId, readOnly) {
2089
+ if (readOnly) {
2090
+ this.readOnlyTabs.add(tabId);
2091
+ return;
2092
+ }
2093
+ this.readOnlyTabs.delete(tabId);
2094
+ }
2095
+ isReadOnly(tabId) {
2096
+ return tabId !== void 0 && this.readOnlyTabs.has(tabId);
2097
+ }
2098
+ /** Drop scopes for tabs that no longer exist. */
2099
+ retain(tabIds) {
2100
+ const alive = new Set(tabIds);
2101
+ for (const tabId of [...this.readOnlyTabs]) {
2102
+ if (!alive.has(tabId)) this.readOnlyTabs.delete(tabId);
2103
+ }
2104
+ }
2105
+ clear() {
2106
+ this.readOnlyTabs.clear();
2107
+ }
2108
+ /** Model-facing refusal, shared so every mutating tool says the same thing. */
2109
+ refusal(tabId) {
2110
+ return `tab_read_only: tab ${tabId} is read-only (set by the user). Nothing was changed. Reading tools still work: browser_snapshot, browser_extract, browser_scroll, browser_wait. Ask the user to unlock the tab in the sidebar tab list, or open a new tab with browser_navigate({ newTab: true }).`;
2111
+ }
2112
+ };
2113
+
2114
+ // src/host/browser-agent/diagnose.ts
2115
+ var PROFILE_LOCK = /ProcessSingleton|SingletonLock|already in use|profile.*(?:lock|use)|EBUSY|EACCES|EPERM/i;
2116
+ var AVAILABILITY = { chrome: "chrome", edge: "edge", safari: "safari" };
2117
+ function usableBrowsers(input) {
2118
+ const { availability, platform } = input;
2119
+ const order = input.preference === "auto" ? platform === "win32" ? ["edge", "chrome"] : platform === "darwin" ? ["safari", "chrome"] : ["chrome"] : [AVAILABILITY[input.preference]];
2120
+ return order.filter((name2) => availability[name2] === true);
2121
+ }
2122
+ function diagnose(input) {
2123
+ return { ...classify(input), browsers: input.availability };
2124
+ }
2125
+ function classify(input) {
2126
+ const detail = typeof input.lastError === "string" && input.lastError.trim() !== "" ? input.lastError.trim() : void 0;
2127
+ if (!input.enabled) {
2128
+ return {
2129
+ code: "disabled",
2130
+ nextStep: "Browser agent is off. Ask the user to enable \u8BBE\u7F6E \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u529F\u80FD \u2192 \u6D4F\u89C8\u5668 Agent, then retry."
2131
+ };
2132
+ }
2133
+ if (input.ready) {
2134
+ return {
2135
+ code: "ok",
2136
+ nextStep: "Ready: page tools act on the bound tab listed above."
2137
+ };
2138
+ }
2139
+ const usable = usableBrowsers(input);
2140
+ if (detail !== void 0 && /WEBKIT_MISSING/i.test(detail)) {
2141
+ return {
2142
+ code: "webkit_missing",
2143
+ detail,
2144
+ nextStep: "The WebKit engine for the Safari option is not installed. Either run `npx playwright install webkit` and retry, or switch the browser setting to Chrome/Edge, which needs no extra download."
2145
+ };
2146
+ }
2147
+ if (input.preference === "safari" && !input.availability.safari) {
2148
+ return {
2149
+ code: "browser_missing",
2150
+ detail,
2151
+ nextStep: "Safari is not present on this machine, and the Safari option drives the WebKit engine. Switch the browser setting to Chrome, or on macOS install Safari first."
2152
+ };
2153
+ }
2154
+ if (usable.length === 0 && detail === void 0) {
2155
+ return {
2156
+ code: "browser_missing",
2157
+ nextStep: `No usable browser found for preference "${input.preference}" on ${input.platform}. Install Chrome (or Edge on Windows) or change the browser setting, then retry.`
2158
+ };
2159
+ }
2160
+ if (detail !== void 0 && PROFILE_LOCK.test(detail)) {
2161
+ return {
2162
+ code: "profile_locked",
2163
+ detail,
2164
+ nextStep: "The dedicated profile is still held by another process \u2014 usually a leftover agent browser window or a second Desktop instance. Close it (or quit the other instance), then retry; no settings change needed."
2165
+ };
2166
+ }
2167
+ if (detail !== void 0) {
2168
+ return {
2169
+ code: "launch_failed",
2170
+ detail,
2171
+ nextStep: "Launch failed. Check the browser choice in Settings \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u529F\u80FD \u2192 \u6D4F\u89C8\u5668 Agent, and retry once. If it keeps failing, the detail above names the missing piece."
2172
+ };
2173
+ }
2174
+ return {
2175
+ code: "idle",
2176
+ nextStep: "Nothing launched yet. Call browser_navigate (or Alt+click a chat link) to launch the dedicated browser; do not ask the user to start it manually."
2177
+ };
2178
+ }
2179
+
1683
2180
  // src/host/browser-agent/tools.ts
1684
2181
  import { defineTool } from "@deepseek-ai/dsh-tools";
1685
2182
  var HUMAN_WAIT_TIMEOUT_MS = 15 * 6e4;
@@ -1714,9 +2211,21 @@ function formatSnapshot(body, extra) {
1714
2211
  typeof body.source === "string" ? `snapshot_source: ${body.source}` : null,
1715
2212
  typeof body.extensionVersion === "string" ? `extension: ${body.extensionVersion}` : null,
1716
2213
  typeof body.anchorCount === "number" ? `anchors_in_dom: ${body.anchorCount}` : null,
2214
+ body.harvest === void 0 ? null : `harvest: interactive=${body.harvest.interactive} controls=${body.harvest.controls} anchors=${body.harvest.anchors}`,
2215
+ body.emulation === void 0 ? null : `emulation: ${[
2216
+ body.emulation.colorScheme === void 0 ? null : `colorScheme=${body.emulation.colorScheme}`,
2217
+ body.emulation.reducedMotion === void 0 ? null : `reducedMotion=${body.emulation.reducedMotion}`,
2218
+ body.emulation.viewport === void 0 ? null : `viewport=${body.emulation.viewport.width}x${body.emulation.viewport.height}`
2219
+ ].filter((part) => part !== null).join(" ")}`,
1717
2220
  typeof body.note === "string" && body.note.trim() !== "" ? `note: ${body.note.trim()}` : null,
1718
2221
  ...extra ?? [],
1719
- "interactive (prefer refs that include href=\u2026 ; never invent URLs; re-snapshot after navigation):",
2222
+ (() => {
2223
+ const links = body.nodes.filter((node) => node.tag === "a").length;
2224
+ const controls = body.nodes.length - links;
2225
+ const shown = body.nodes.length;
2226
+ const tally = controls > 0 ? `${links} link / ${controls} control` : `${links} link`;
2227
+ return controls > 0 ? `interactive (${shown} shown: ${tally} \u2014 controls are at the end; prefer refs that include href=\u2026 ; never invent URLs; re-snapshot after navigation):` : `interactive (${shown} shown: ${tally}; prefer refs that include href=\u2026 ; never invent URLs; re-snapshot after navigation):`;
2228
+ })(),
1720
2229
  ...body.nodes.slice(0, 80).map((node) => `- [${node.ref}] ${node.role}${node.tag !== void 0 ? `/${node.tag}` : ""}${node.sensitive === true ? " [sensitive]" : ""}${typeof node.href === "string" && node.href !== "" ? ` href=${JSON.stringify(node.href)}` : ""} ${JSON.stringify(node.name)}`),
1721
2230
  "text_preview (short \u2014 use browser_extract for long/below-fold content):",
1722
2231
  body.textPreview.slice(0, 2e3)
@@ -1780,6 +2289,14 @@ function driverOf(options) {
1780
2289
  const value = options.driver;
1781
2290
  return typeof value === "function" ? value() : value;
1782
2291
  }
2292
+ function pickEnum(value, allowed, field) {
2293
+ if (value === void 0 || value === null || value === "") return void 0;
2294
+ const text3 = String(value).trim().toLowerCase();
2295
+ if (!allowed.includes(text3)) {
2296
+ throw new Error(`${field} must be one of: ${allowed.join(" | ")}`);
2297
+ }
2298
+ return text3;
2299
+ }
1783
2300
  function registerBrowserTools(ctx, options) {
1784
2301
  const disposers = [];
1785
2302
  const guardEnabled = () => {
@@ -1810,6 +2327,25 @@ function registerBrowserTools(ctx, options) {
1810
2327
  }
1811
2328
  await driverOf(options).ensureReady(startUrl);
1812
2329
  };
2330
+ const requireDebugTools = (tool) => {
2331
+ if (options.debugTools?.() === true) return;
2332
+ throw new Error(
2333
+ `${tool}: debug tools are off. Nothing ran. Ask the user to enable \u8BBE\u7F6E \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u529F\u80FD \u2192 \u6D4F\u89C8\u5668 Agent \u2192 \u8C03\u8BD5\u5DE5\u5177, then retry.`
2334
+ );
2335
+ };
2336
+ const requireWritableTab = (sessionId, tool) => {
2337
+ const scope = options.tabScope;
2338
+ if (scope === void 0) return;
2339
+ const tabId = options.sessions.tabOf(sessionId);
2340
+ if (tabId === void 0 || !scope.isReadOnly(tabId)) return;
2341
+ options.sessions.record({
2342
+ sessionId,
2343
+ tool,
2344
+ summary: `Blocked: tab ${tabId} is read-only`,
2345
+ outcome: "denied"
2346
+ });
2347
+ throw new Error(scope.refusal(tabId));
2348
+ };
1813
2349
  const requireMutation = async (exec, tool, summary, url) => {
1814
2350
  const sessionId = sessionIdOf(exec);
1815
2351
  let effectiveUrl = typeof url === "string" && /^https?:\/\//i.test(url) ? url : void 0;
@@ -1856,13 +2392,14 @@ function registerBrowserTools(ctx, options) {
1856
2392
  }
1857
2393
  };
1858
2394
  const pauseForHuman = async (input) => {
1859
- options.sessions.setNeedsHuman(input.sessionId, input.detail);
2395
+ options.sessions.setNeedsHuman(input.sessionId, input.detail, input.kind ?? "human");
1860
2396
  await focusBoundTab(input.sessionId, input.tabId);
1861
2397
  try {
1862
2398
  return await options.human.waitForHuman({
1863
2399
  sessionId: input.sessionId,
1864
2400
  prompt: input.prompt,
1865
2401
  detail: input.detail,
2402
+ ...input.kind === void 0 ? {} : { kind: input.kind },
1866
2403
  ...input.url === void 0 ? {} : { url: input.url },
1867
2404
  signal: input.signal
1868
2405
  });
@@ -1889,6 +2426,13 @@ function registerBrowserTools(ctx, options) {
1889
2426
  };
1890
2427
  const requireFreshRef = (sessionId, ref, tool) => {
1891
2428
  if (options.sessions.hasRef(sessionId, ref)) return;
2429
+ const active = options.sessions.tabOf(sessionId);
2430
+ const owner = options.sessions.tabHoldingRef(ref, active);
2431
+ if (owner !== void 0) {
2432
+ throw new Error(
2433
+ `${tool}: ref ${ref} belongs to tab ${owner}, but tab ${active ?? "none"} is active. Switch back with browser_follow_tab (tabId ${owner}) \u2014 that tab's refs are still valid \u2014 or call browser_snapshot to get refs for the current tab.`
2434
+ );
2435
+ }
1892
2436
  const known = options.sessions.lastRefList(sessionId);
1893
2437
  if (known.length === 0) {
1894
2438
  throw new Error(
@@ -1976,30 +2520,29 @@ function registerBrowserTools(ctx, options) {
1976
2520
  };
1977
2521
  disposers.push(ctx.tools.register(textTool(
1978
2522
  "browser_status",
1979
- "Check the Desktop dedicated-browser bridge (Mac: Safari/Chrome; Windows: Chrome/Edge): connection, bound tab URL/title/tabId. Use this for any real-browser / webpage / on-page task. Auto-launches the dedicated browser when disconnected \u2014 do not ask the user to launch manually first.",
2523
+ "Check the Desktop dedicated browser (Mac: Safari/Chrome; Windows: Chrome/Edge): whether it is usable, the bound tab URL/title/tabId, and \u2014 when something is wrong \u2014 the concrete next step. Use this for any real-browser / webpage / on-page task. Auto-launches the dedicated browser when disconnected \u2014 do not ask the user to launch manually first.",
1980
2524
  {},
1981
2525
  async (_args, exec) => {
1982
2526
  guardEnabled();
1983
2527
  const sessionId = sessionIdOf(exec);
2528
+ const diag = options.diagnosis?.();
2529
+ const diagLines = diag === void 0 ? [] : [
2530
+ `diagnosis: ${diag.code}`,
2531
+ `next: ${diag.nextStep}`,
2532
+ diag.detail === void 0 ? null : `detail: ${diag.detail}`
2533
+ ].filter((line) => line !== null);
1984
2534
  const st = driverOf(options).status();
1985
- if (!st.listening) {
1986
- return [
1987
- `driver: ${st.kind}`,
1988
- "bridge: not listening",
1989
- st.port !== void 0 ? `port: ${st.port}` : null,
1990
- `error: ${st.lastError ?? "not started"}`
1991
- ].filter((line) => line !== null).join("\n");
1992
- }
1993
- if (!st.ready) {
2535
+ if (!st.listening || !st.ready) {
1994
2536
  try {
1995
2537
  await ensureConnected();
1996
2538
  } catch (error) {
1997
2539
  return [
1998
2540
  `driver: ${st.kind}`,
1999
- st.endpoint !== void 0 ? `bridge: listening on ${st.endpoint}` : "bridge: listening",
2000
- "extension: disconnected",
2541
+ `browser: ${st.listening ? "listening, not ready" : "not started"}`,
2542
+ st.endpoint !== void 0 ? `endpoint: ${st.endpoint}` : null,
2543
+ ...diagLines,
2001
2544
  formatBridgeError(error)
2002
- ].join("\n");
2545
+ ].filter((line) => line !== null).join("\n");
2003
2546
  }
2004
2547
  }
2005
2548
  try {
@@ -2008,8 +2551,8 @@ function registerBrowserTools(ctx, options) {
2008
2551
  await rememberTab(sessionId, tab.tabId);
2009
2552
  return [
2010
2553
  `driver: ${driverOf(options).kind}`,
2011
- "bridge: ok",
2012
- "extension: connected",
2554
+ "browser: ready",
2555
+ ...diagLines,
2013
2556
  `url: ${tab.url}`,
2014
2557
  `title: ${tab.title}`,
2015
2558
  `tabId: ${tab.tabId}`,
@@ -2020,9 +2563,12 @@ function registerBrowserTools(ctx, options) {
2020
2563
  ].filter((line) => line !== null).join("\n");
2021
2564
  } catch (error) {
2022
2565
  noteHuman(sessionId, {}, error);
2023
- return `driver: ${driverOf(options).kind}
2024
- bridge: listening
2025
- extension: connected but status failed: ${formatBridgeError(error)}`;
2566
+ return [
2567
+ `driver: ${driverOf(options).kind}`,
2568
+ "browser: ready, status call failed",
2569
+ ...diagLines,
2570
+ formatBridgeError(error)
2571
+ ].join("\n");
2026
2572
  }
2027
2573
  }
2028
2574
  )));
@@ -2087,6 +2633,8 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
2087
2633
  sessionId,
2088
2634
  prompt,
2089
2635
  detail: prompt.slice(0, 240),
2636
+ // A generic "do this in the browser" request must not wear the login card.
2637
+ kind: "ask",
2090
2638
  ...url === void 0 ? {} : { url },
2091
2639
  ...tabId === void 0 ? {} : { tabId },
2092
2640
  signal: exec.signal
@@ -2132,6 +2680,7 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
2132
2680
  if (url === "") throw new Error("url is required");
2133
2681
  await ensureConnected(url);
2134
2682
  await ensureSessionTab(sessionId);
2683
+ if (!newTab) requireWritableTab(sessionId, "browser_navigate");
2135
2684
  await requireMutation(
2136
2685
  exec,
2137
2686
  "browser_navigate",
@@ -2187,6 +2736,7 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
2187
2736
  if (!Number.isFinite(ref)) throw new Error("ref must be a number");
2188
2737
  await ensureConnected();
2189
2738
  await ensureSessionTab(sessionId);
2739
+ requireWritableTab(sessionId, "browser_click");
2190
2740
  let url;
2191
2741
  try {
2192
2742
  url = (await driverOf(options).pageStatus()).url;
@@ -2307,6 +2857,7 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
2307
2857
  if (!Number.isFinite(ref)) throw new Error("ref must be a number");
2308
2858
  await ensureConnected();
2309
2859
  await ensureSessionTab(sessionId);
2860
+ requireWritableTab(sessionId, "browser_type");
2310
2861
  let url;
2311
2862
  try {
2312
2863
  url = (await driverOf(options).pageStatus()).url;
@@ -2546,6 +3097,138 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
2546
3097
  ].filter((line) => line !== null).join("\n");
2547
3098
  }
2548
3099
  )));
3100
+ disposers.push(ctx.tools.register(textTool(
3101
+ "browser_network",
3102
+ "Read buffered network activity for the bound tab (method, url, status, duration, failures). Read-only; no approval. Headers, cookies and bodies are never recorded; secret-looking query values are masked. Requires the Debug tools switch in Settings \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u6D4F\u89C8\u5668 Agent. Capture starts automatically when that switch is on, so navigate first, then read.",
3103
+ {
3104
+ limit: {
3105
+ type: "number",
3106
+ description: "Newest N entries (default 40, max 200)."
3107
+ },
3108
+ clear: {
3109
+ type: "boolean",
3110
+ description: "Drop the returned entries from the buffer."
3111
+ }
3112
+ },
3113
+ async (args, exec) => {
3114
+ guardEnabled();
3115
+ requireDebugTools("browser_network");
3116
+ const sessionId = sessionIdOf(exec);
3117
+ await ensureConnected();
3118
+ await ensureSessionTab(sessionId);
3119
+ const limit = Number(args.limit);
3120
+ const driver = driverOf(options);
3121
+ driver.startCapture();
3122
+ const { entries, dropped } = driver.readCapture({
3123
+ kind: "network",
3124
+ ...Number.isFinite(limit) ? { limit } : {},
3125
+ ...args.clear === true ? { clear: true } : {}
3126
+ });
3127
+ const rows = entries.filter((entry) => entry.kind === "request");
3128
+ if (rows.length === 0) {
3129
+ return "no network activity buffered yet. Navigate or wait for the page to load, then call browser_network again.";
3130
+ }
3131
+ return [
3132
+ `network entries: ${rows.length}${dropped > 0 ? ` (${dropped} older dropped)` : ""}`,
3133
+ ...rows.map((entry) => {
3134
+ const status = entry.kind !== "request" ? "" : entry.status === void 0 ? entry.failure ?? "failed" : String(entry.status);
3135
+ const ms = entry.kind === "request" && entry.durationMs !== void 0 ? ` ${entry.durationMs}ms` : "";
3136
+ const method = entry.kind === "request" ? entry.method : "GET";
3137
+ return `- [${entry.tabId}] ${status} ${method} ${entry.kind === "request" ? entry.url : ""}${ms}`;
3138
+ })
3139
+ ].join("\n");
3140
+ }
3141
+ )));
3142
+ disposers.push(ctx.tools.register(textTool(
3143
+ "browser_console",
3144
+ "Read buffered console messages and uncaught page errors for the bound tab. Read-only; no approval. Requires the Debug tools switch in Settings \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u6D4F\u89C8\u5668 Agent.",
3145
+ {
3146
+ limit: {
3147
+ type: "number",
3148
+ description: "Newest N entries (default 40, max 200)."
3149
+ },
3150
+ clear: {
3151
+ type: "boolean",
3152
+ description: "Drop the returned entries from the buffer."
3153
+ }
3154
+ },
3155
+ async (args, exec) => {
3156
+ guardEnabled();
3157
+ requireDebugTools("browser_console");
3158
+ const sessionId = sessionIdOf(exec);
3159
+ await ensureConnected();
3160
+ await ensureSessionTab(sessionId);
3161
+ const limit = Number(args.limit);
3162
+ const driver = driverOf(options);
3163
+ driver.startCapture();
3164
+ const { entries } = driver.readCapture({
3165
+ kind: "console",
3166
+ ...Number.isFinite(limit) ? { limit } : {},
3167
+ ...args.clear === true ? { clear: true } : {}
3168
+ });
3169
+ if (entries.length === 0) {
3170
+ return "no console output buffered yet. Reload or interact with the page, then call browser_console again.";
3171
+ }
3172
+ return [
3173
+ `console entries: ${entries.length}`,
3174
+ ...entries.map((entry) => {
3175
+ if (entry.kind !== "console") return "";
3176
+ const where = entry.location === void 0 ? "" : ` (${entry.location})`;
3177
+ return `- [${entry.tabId}] ${entry.level}: ${entry.text}${where}`;
3178
+ })
3179
+ ].filter((line) => line !== "").join("\n");
3180
+ }
3181
+ )));
3182
+ disposers.push(ctx.tools.register(textTool(
3183
+ "browser_emulate",
3184
+ "Change how the bound page renders for testing: color scheme, reduced motion, viewport size. Read-only on page data; no approval. Requires the Debug tools switch in Settings \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u6D4F\u89C8\u5668 Agent. Call browser_snapshot afterwards to see the effect.",
3185
+ {
3186
+ colorScheme: {
3187
+ type: "string",
3188
+ description: "light | dark | no-preference | reset"
3189
+ },
3190
+ reducedMotion: {
3191
+ type: "string",
3192
+ description: "reduce | no-preference | reset"
3193
+ },
3194
+ width: {
3195
+ type: "number",
3196
+ description: "Viewport width in CSS px (320\u20133840)."
3197
+ },
3198
+ height: {
3199
+ type: "number",
3200
+ description: "Viewport height in CSS px (240\u20132160)."
3201
+ }
3202
+ },
3203
+ async (args, exec) => {
3204
+ guardEnabled();
3205
+ requireDebugTools("browser_emulate");
3206
+ const sessionId = sessionIdOf(exec);
3207
+ const colorScheme = pickEnum(args.colorScheme, ["light", "dark", "no-preference", "reset"], "colorScheme");
3208
+ const reducedMotion = pickEnum(args.reducedMotion, ["reduce", "no-preference", "reset"], "reducedMotion");
3209
+ const width = Number(args.width);
3210
+ const height = Number(args.height);
3211
+ const hasViewport = Number.isFinite(width) && Number.isFinite(height);
3212
+ if (colorScheme === void 0 && reducedMotion === void 0 && !hasViewport) {
3213
+ throw new Error("browser_emulate: pass colorScheme, reducedMotion, or width+height");
3214
+ }
3215
+ await ensureConnected();
3216
+ await ensureSessionTab(sessionId);
3217
+ const result = await runBridge(() => driverOf(options).emulate({
3218
+ ...colorScheme === void 0 ? {} : { colorScheme },
3219
+ ...reducedMotion === void 0 ? {} : { reducedMotion },
3220
+ ...hasViewport ? { viewport: { width, height } } : {}
3221
+ }));
3222
+ await rememberTab(sessionId, result.tabId);
3223
+ return [
3224
+ `emulated: ${result.applied.join(", ")}`,
3225
+ `url: ${result.url}`,
3226
+ `title: ${result.title}`,
3227
+ result.tabId !== void 0 ? `tabId: ${result.tabId}` : null,
3228
+ "Action: browser_snapshot now echoes the emulation line, so you can confirm the mode the page is in."
3229
+ ].filter((line) => line !== null).join("\n");
3230
+ }
3231
+ )));
2549
3232
  disposers.push(ctx.tools.register(textTool(
2550
3233
  "browser_list_tabs",
2551
3234
  "List open browser tabs (id, title, url, active, bound). Read-only; no approval. Use with browser_follow_tab to bind this session to another tab.",
@@ -2626,10 +3309,34 @@ title: ${result.title}`;
2626
3309
  }
2627
3310
 
2628
3311
  // src/host/browser-agent/install.ts
3312
+ var IDLE_TICK_MS = 6e4;
3313
+ var IDLE_CLOSE_MS = 10 * 6e4;
2629
3314
  function installBrowserAgent(ctx, options) {
2630
3315
  const approval = new BrowserApprovalGate();
2631
3316
  const human = new BrowserHumanGate();
2632
3317
  const sessions = new BrowserSessionState();
3318
+ const tabScope = new TabScopeStore();
3319
+ let availabilityCache = null;
3320
+ const browserAvailability = () => {
3321
+ if (availabilityCache !== null) return availabilityCache;
3322
+ availabilityCache = {
3323
+ chrome: resolveBrowserExecutable("chrome") !== null,
3324
+ edge: resolveBrowserExecutable("edge") !== null,
3325
+ safari: resolveBrowserExecutable("safari") !== null
3326
+ };
3327
+ return availabilityCache;
3328
+ };
3329
+ const diagnoseNow = () => {
3330
+ const status = activeDriver?.status();
3331
+ return diagnose({
3332
+ enabled: options.enabled(),
3333
+ ready: status?.ready === true,
3334
+ preference: options.browserPreference(),
3335
+ platform: process.platform,
3336
+ lastError: status?.lastError ?? null,
3337
+ availability: browserAvailability()
3338
+ });
3339
+ };
2633
3340
  let unregisterTools = null;
2634
3341
  let unregisterPrompt = null;
2635
3342
  let active = false;
@@ -2667,6 +3374,7 @@ function installBrowserAgent(ctx, options) {
2667
3374
  const previousPreference = mountedPreference;
2668
3375
  activeDriver = null;
2669
3376
  mountedPreference = null;
3377
+ tabScope.clear();
2670
3378
  const pw = playwrightDriver;
2671
3379
  playwrightDriver = null;
2672
3380
  if (pw !== null) {
@@ -2724,6 +3432,9 @@ function installBrowserAgent(ctx, options) {
2724
3432
  approval,
2725
3433
  human,
2726
3434
  sessions,
3435
+ tabScope,
3436
+ debugTools: () => options.debugTools?.() === true,
3437
+ diagnosis: diagnoseNow,
2727
3438
  // Gate on settings only — `active` flips false during driver align and
2728
3439
  // must not make browser_* look "disabled" mid-turn.
2729
3440
  enabled: () => options.enabled(),
@@ -2738,6 +3449,7 @@ function installBrowserAgent(ctx, options) {
2738
3449
  try {
2739
3450
  if (preferenceMatchesRunning(preference)) {
2740
3451
  await requireDriver().ensureReady(startUrl);
3452
+ primeCapture();
2741
3453
  active = true;
2742
3454
  return { ok: true };
2743
3455
  }
@@ -2758,6 +3470,7 @@ function installBrowserAgent(ctx, options) {
2758
3470
  ensureToolsRegistered();
2759
3471
  active = true;
2760
3472
  await activeDriver.ensureReady(startUrl);
3473
+ primeCapture();
2761
3474
  mountedPreference = preference;
2762
3475
  return { ok: true };
2763
3476
  } catch (error) {
@@ -2768,12 +3481,20 @@ function installBrowserAgent(ctx, options) {
2768
3481
  return { ok: false, error: error instanceof Error ? error.message : String(error) };
2769
3482
  }
2770
3483
  };
3484
+ const primeCapture = () => {
3485
+ if (options.debugTools?.() !== true) return;
3486
+ try {
3487
+ requireDriver().startCapture();
3488
+ } catch {
3489
+ }
3490
+ };
2771
3491
  const mount = () => {
2772
3492
  const preference = options.browserPreference();
2773
3493
  createDriver(preference);
2774
3494
  ensureToolsRegistered();
2775
3495
  };
2776
3496
  const refresh = () => {
3497
+ availabilityCache = null;
2777
3498
  const want = options.enabled();
2778
3499
  if (!want) {
2779
3500
  if (!active && playwrightDriver === null && unregisterTools === null && !switchPending) {
@@ -2797,6 +3518,35 @@ function installBrowserAgent(ctx, options) {
2797
3518
  active = true;
2798
3519
  };
2799
3520
  refresh();
3521
+ const sweepIdleTabs = async () => {
3522
+ if (!options.enabled() || options.idleClose?.() !== true) return;
3523
+ const driver = activeDriver;
3524
+ if (driver === null || driver.status().ready !== true) return;
3525
+ try {
3526
+ const closed = await driver.sweepIdleTabs({
3527
+ idleMs: IDLE_CLOSE_MS,
3528
+ keep: sessions.boundTabIds()
3529
+ });
3530
+ for (const tabId of closed) {
3531
+ const sessionId = sessions.unbindTab(tabId);
3532
+ tabScope.setReadOnly(tabId, false);
3533
+ sessions.record({
3534
+ sessionId: sessionId ?? "host",
3535
+ tool: "browser_idle_close",
3536
+ summary: `Closed idle tab ${tabId}`,
3537
+ outcome: "ok"
3538
+ });
3539
+ }
3540
+ } catch (error) {
3541
+ ctx.logger.warn(
3542
+ `agent-enhancer: idle tab sweep failed: ${error instanceof Error ? error.message : String(error)}`
3543
+ );
3544
+ }
3545
+ };
3546
+ const idleTimer = setInterval(() => {
3547
+ void sweepIdleTabs();
3548
+ }, IDLE_TICK_MS);
3549
+ idleTimer.unref?.();
2800
3550
  return {
2801
3551
  approval,
2802
3552
  human,
@@ -2804,6 +3554,9 @@ function installBrowserAgent(ctx, options) {
2804
3554
  driverStatus() {
2805
3555
  return activeDriver?.status() ?? null;
2806
3556
  },
3557
+ diagnose() {
3558
+ return diagnoseNow();
3559
+ },
2807
3560
  activeProfileDir() {
2808
3561
  if (mountedPreference !== null) {
2809
3562
  return browserAgentProfileDirFor(options.profileRoot, mountedPreference);
@@ -2823,10 +3576,13 @@ function installBrowserAgent(ctx, options) {
2823
3576
  }
2824
3577
  try {
2825
3578
  const body = await activeDriver.listTabs();
3579
+ tabScope.retain(body.tabs.map((tab) => tab.tabId));
3580
+ sessions.retainTabs(body.tabs.map((tab) => tab.tabId));
2826
3581
  return {
2827
3582
  tabs: body.tabs.map((tab) => ({
2828
3583
  ...tab,
2829
- bound: sessions.sessionOf(tab.tabId) !== void 0
3584
+ bound: sessions.sessionOf(tab.tabId) !== void 0,
3585
+ readOnly: tabScope.isReadOnly(tab.tabId)
2830
3586
  })),
2831
3587
  boundTabId: body.boundTabId
2832
3588
  };
@@ -2834,6 +3590,17 @@ function installBrowserAgent(ctx, options) {
2834
3590
  return { tabs: [], boundTabId: null };
2835
3591
  }
2836
3592
  },
3593
+ setTabReadOnly(input) {
3594
+ if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
3595
+ tabScope.setReadOnly(input.tabId, input.readOnly);
3596
+ sessions.record({
3597
+ sessionId: "sidebar",
3598
+ tool: "browser_tab_read_only",
3599
+ summary: `${input.readOnly ? "Read-only" : "Writable"} tab ${input.tabId}`,
3600
+ outcome: "ok"
3601
+ });
3602
+ return { ok: true };
3603
+ },
2837
3604
  async selectTab(input) {
2838
3605
  if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
2839
3606
  await switchGate.catch(() => void 0);
@@ -2977,6 +3744,7 @@ function installBrowserAgent(ctx, options) {
2977
3744
  },
2978
3745
  async dispose() {
2979
3746
  active = false;
3747
+ clearInterval(idleTimer);
2980
3748
  approval.clearAll();
2981
3749
  human.clearAll();
2982
3750
  await switchGate.catch(() => void 0);
@@ -12819,7 +13587,7 @@ function installAutoSessionRoute(ctx, options) {
12819
13587
  const settings = options.settings();
12820
13588
  const map = autoRouteMapOf(settings);
12821
13589
  const note = (agent === void 0 ? void 0 : notes.get(agent)) ?? loggedTurn(asAgent(agent));
12822
- const classify = settings.autoClassifierEnabled ? createClassifier({ prepareCall: innerPrepare }, map.classifier) : void 0;
13590
+ const classify2 = settings.autoClassifierEnabled ? createClassifier({ prepareCall: innerPrepare }, map.classifier) : void 0;
12823
13591
  let mapped;
12824
13592
  try {
12825
13593
  mapped = await resolveAutoRoute({
@@ -12828,7 +13596,7 @@ function installAutoSessionRoute(ctx, options) {
12828
13596
  toolHeavy: note?.toolHeavy ?? false,
12829
13597
  map,
12830
13598
  classifierEnabled: settings.autoClassifierEnabled,
12831
- classify,
13599
+ classify: classify2,
12832
13600
  isAvailable: (provider, model) => provider !== "" && model !== "" && !isAutoModel({ provider, model }),
12833
13601
  signal,
12834
13602
  fallback: fallbackRoute(ctx, asAgent(agent))
@@ -13220,7 +13988,7 @@ var AuxiliaryModels = class {
13220
13988
  async resolveAutoRouteFor(session, override, text3, feature, toolHeavy) {
13221
13989
  const settings = this.enhancerSettings();
13222
13990
  const map = autoRouteMapOf(settings);
13223
- const classify = settings.autoClassifierEnabled ? createClassifier(this.ctx.llm, map.classifier) : void 0;
13991
+ const classify2 = settings.autoClassifierEnabled ? createClassifier(this.ctx.llm, map.classifier) : void 0;
13224
13992
  let mapped;
13225
13993
  try {
13226
13994
  mapped = await resolveAutoRoute({
@@ -13229,7 +13997,7 @@ var AuxiliaryModels = class {
13229
13997
  toolHeavy,
13230
13998
  map,
13231
13999
  classifierEnabled: settings.autoClassifierEnabled,
13232
- classify,
14000
+ classify: classify2,
13233
14001
  isAvailable: (provider, model) => this.modelExists(provider, model),
13234
14002
  fallback: this.fallbackFromSession(session, override)
13235
14003
  });
@@ -14940,7 +15708,9 @@ var browserAgentTabConflictSchema = z4.strictObject({
14940
15708
  });
14941
15709
  var browserAgentNeedsHumanSchema = z4.strictObject({
14942
15710
  sessionId: z4.string().min(1),
14943
- detail: z4.string().min(1)
15711
+ detail: z4.string().min(1),
15712
+ /** `human` = login/captcha on the page; `ask` = any other browser-side request. */
15713
+ kind: z4.enum(["human", "ask"])
14944
15714
  });
14945
15715
  var browserAgentAuditEntrySchema = z4.strictObject({
14946
15716
  at: z4.number(),
@@ -14957,7 +15727,21 @@ var browserAgentTabEntrySchema = z4.strictObject({
14957
15727
  /** True when this is the driver's currently focused page. */
14958
15728
  active: z4.boolean(),
14959
15729
  /** True when any chat session is bound to this tab. */
14960
- bound: z4.boolean()
15730
+ bound: z4.boolean(),
15731
+ /** User marked the tab read-only: mutating tools fail fast there. */
15732
+ readOnly: z4.boolean()
15733
+ });
15734
+ var browserAgentAvailabilitySchema = z4.strictObject({
15735
+ chrome: z4.boolean(),
15736
+ edge: z4.boolean(),
15737
+ safari: z4.boolean()
15738
+ });
15739
+ var browserAgentDiagnosisSchema = z4.strictObject({
15740
+ code: z4.enum(["disabled", "idle", "ok", "webkit_missing", "browser_missing", "profile_locked", "launch_failed"]),
15741
+ /** English, model-facing: what to do next. */
15742
+ nextStep: z4.string(),
15743
+ detail: z4.string().optional(),
15744
+ browsers: browserAgentAvailabilitySchema
14961
15745
  });
14962
15746
  var browserAgentSnapshotSchema = z4.strictObject({
14963
15747
  enabled: z4.boolean(),
@@ -14976,6 +15760,8 @@ var browserAgentSnapshotSchema = z4.strictObject({
14976
15760
  lastError: z4.string().nullable()
14977
15761
  }),
14978
15762
  pending: browserAgentPendingSchema.nullable(),
15763
+ /** Why the browser is (not) usable and the concrete next step. */
15764
+ diagnosis: browserAgentDiagnosisSchema,
14979
15765
  tabConflict: browserAgentTabConflictSchema.nullable(),
14980
15766
  needsHuman: browserAgentNeedsHumanSchema.nullable(),
14981
15767
  boundTabId: z4.number().int().nullable(),
@@ -15128,6 +15914,23 @@ var browserAgentSelectTabResultCodec = codec(
15128
15914
  "dsh-agent-enhancer#BrowserAgentSelectTabResult",
15129
15915
  browserAgentSelectTabResultSchema
15130
15916
  );
15917
+ var browserAgentSetTabReadOnlyRequestSchema = z4.strictObject({
15918
+ tabId: z4.number().int().positive(),
15919
+ readOnly: z4.boolean()
15920
+ });
15921
+ var browserAgentSetTabReadOnlyRequestCodec = codec(
15922
+ "dsh-agent-enhancer#BrowserAgentSetTabReadOnlyRequest",
15923
+ browserAgentSetTabReadOnlyRequestSchema
15924
+ );
15925
+ var browserAgentSetTabReadOnlyResultSchema = z4.strictObject({
15926
+ ok: z4.boolean(),
15927
+ error: z4.string().optional(),
15928
+ snapshot: browserAgentSnapshotSchema
15929
+ });
15930
+ var browserAgentSetTabReadOnlyResultCodec = codec(
15931
+ "dsh-agent-enhancer#BrowserAgentSetTabReadOnlyResult",
15932
+ browserAgentSetTabReadOnlyResultSchema
15933
+ );
15131
15934
  var instructionScopeSchema = z4.enum(["global", "shared", "project"]);
15132
15935
  var instructionFileEntrySchema = z4.strictObject({
15133
15936
  id: z4.string().min(1),
@@ -15866,6 +16669,18 @@ var remoteInfo = createTypertRemoteInfo({
15866
16669
  }],
15867
16670
  result: browserAgentSelectTabResultCodec
15868
16671
  },
16672
+ "agentEnhancer/browserAgentSetTabReadOnly": {
16673
+ service: "agentEnhancer",
16674
+ implementation: "browserAgentSetTabReadOnly",
16675
+ invocation: { kind: "direct" },
16676
+ parameters: [{
16677
+ name: "request",
16678
+ source: "json",
16679
+ codec: browserAgentSetTabReadOnlyRequestCodec,
16680
+ strictCodec: browserAgentSetTabReadOnlyRequestCodec
16681
+ }],
16682
+ result: browserAgentSetTabReadOnlyResultCodec
16683
+ },
15869
16684
  "agentEnhancer/listInstructionsSkills": {
15870
16685
  service: "agentEnhancer",
15871
16686
  implementation: "listInstructionsSkills",
@@ -16541,6 +17356,10 @@ var Config = z5.object({
16541
17356
  /** High-risk; default off. */
16542
17357
  browserAgentEnabled: z5.boolean().default(false).volatile(),
16543
17358
  browserAgentBrowser: z5.string().default("auto").volatile(),
17359
+ /** Debug tools (network / console / emulate); default off, gated per tool. */
17360
+ browserAgentDebugTools: z5.boolean().default(false).volatile(),
17361
+ /** Close idle agent tabs after ~10 min; default on, never the bound/active tab. */
17362
+ browserAgentIdleClose: z5.boolean().default(true).volatile(),
16544
17363
  /** Default off; embeds official web chat + import to work. */
16545
17364
  webChatBridgeEnabled: z5.boolean().default(true).volatile(),
16546
17365
  instructionsSkillsEnabled: z5.boolean().default(true).volatile(),
@@ -16632,10 +17451,12 @@ var AgentEnhancerService = class extends TypertRemoteService {
16632
17451
  const waiting = this.browserAgent?.human.current() ?? null;
16633
17452
  const needsHuman = waiting !== null ? {
16634
17453
  sessionId: waiting.sessionId,
16635
- detail: waiting.prompt.trim() !== "" ? waiting.prompt : waiting.detail
17454
+ detail: waiting.prompt.trim() !== "" ? waiting.prompt : waiting.detail,
17455
+ kind: waiting.kind
16636
17456
  } : this.browserAgent?.sessions.anyNeedsHuman() ?? null;
16637
17457
  const overlayBound = pending !== null ? this.browserAgent?.sessions.tabOf(pending.sessionId) ?? null : conflict !== null ? conflict.boundTabId : needsHuman !== null ? this.browserAgent?.sessions.tabOf(needsHuman.sessionId) ?? null : null;
16638
17458
  const connected = driverStatus?.ready === true;
17459
+ const diag = this.browserAgent?.diagnose();
16639
17460
  const listed = connected ? await this.browserAgent?.listTabs() : void 0;
16640
17461
  const tabs = listed?.tabs ?? [];
16641
17462
  const boundTabId = overlayBound ?? listed?.boundTabId ?? null;
@@ -16662,6 +17483,11 @@ var AgentEnhancerService = class extends TypertRemoteService {
16662
17483
  ...pending.url === void 0 ? {} : { url: pending.url },
16663
17484
  ...pending.origin === void 0 ? {} : { origin: pending.origin }
16664
17485
  },
17486
+ diagnosis: diag ?? {
17487
+ code: settings.enabled ? "idle" : "disabled",
17488
+ nextStep: settings.enabled ? "Nothing launched yet. Call browser_navigate (or Alt+click a chat link) to launch the dedicated browser." : "Browser agent is off. Enable it in \u8BBE\u7F6E \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u529F\u80FD.",
17489
+ browsers: { chrome: false, edge: false, safari: false }
17490
+ },
16665
17491
  tabConflict: conflict,
16666
17492
  needsHuman,
16667
17493
  boundTabId,
@@ -17364,6 +18190,18 @@ var AgentEnhancerService = class extends TypertRemoteService {
17364
18190
  snapshot: await this.browserSnapshotNow()
17365
18191
  };
17366
18192
  }
18193
+ async browserAgentSetTabReadOnly(request) {
18194
+ this.assertOwner();
18195
+ const result = this.browserAgent?.setTabReadOnly({
18196
+ tabId: request.tabId,
18197
+ readOnly: request.readOnly
18198
+ });
18199
+ return {
18200
+ ok: result?.ok === true,
18201
+ ...result?.error === void 0 ? {} : { error: result.error },
18202
+ snapshot: await this.browserSnapshotNow()
18203
+ };
18204
+ }
17367
18205
  };
17368
18206
  function resolveCheckpointRoot(dshHome2) {
17369
18207
  const base = join30(dshHome2, "profiles", "desktop", "plugin-data");
@@ -17447,6 +18285,8 @@ function readSettings(config) {
17447
18285
  runAlertsLevel: resolveRunAlertsLevel(config.runAlertsLevel.get()),
17448
18286
  browserAgentEnabled: config.browserAgentEnabled.get(),
17449
18287
  browserAgentBrowser: hostBrowserPreference(config.browserAgentBrowser.get()),
18288
+ browserAgentDebugTools: config.browserAgentDebugTools.get(),
18289
+ browserAgentIdleClose: config.browserAgentIdleClose.get(),
17450
18290
  webChatBridgeEnabled: config.webChatBridgeEnabled.get(),
17451
18291
  instructionsSkillsEnabled: config.instructionsSkillsEnabled.get(),
17452
18292
  mcpConnectorsEnabled: config.mcpConnectorsEnabled.get(),
@@ -17533,6 +18373,8 @@ function apply(ctx, config) {
17533
18373
  const browserAgent = installBrowserAgent(ctx, {
17534
18374
  enabled: () => browserAgentLive.enabled,
17535
18375
  browserPreference: () => browserAgentLive.browser,
18376
+ debugTools: () => settings().browserAgentDebugTools,
18377
+ idleClose: () => settings().browserAgentIdleClose,
17536
18378
  profileRoot: pluginDataPackageRoot,
17537
18379
  softPause: softPauseGate,
17538
18380
  softPauseEnabled: () => settings().softPauseEnabled,