dsh-agent-enhancer 0.3.13 → 0.3.15
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/README.en.md +5 -5
- package/README.md +5 -5
- package/lib/client/browser-agent/overlay.d.ts.map +1 -1
- package/lib/client/browser-agent/tab.d.ts.map +1 -1
- package/lib/client/dsh/settings-features.d.ts +3 -1
- package/lib/client/dsh/settings-features.d.ts.map +1 -1
- package/lib/client/dsh/settings.d.ts.map +1 -1
- package/lib/client/locales.d.ts +43 -1
- package/lib/client/locales.d.ts.map +1 -1
- package/lib/client/remote.d.ts +4 -1
- package/lib/client/remote.d.ts.map +1 -1
- package/lib/client.js +228 -27
- package/lib/client.js.map +1 -1
- package/lib/config.d.ts +14 -0
- package/lib/config.d.ts.map +1 -1
- package/lib/host/browser-agent/capture.d.ts +59 -0
- package/lib/host/browser-agent/capture.d.ts.map +1 -0
- package/lib/host/browser-agent/diagnose.d.ts +38 -0
- package/lib/host/browser-agent/diagnose.d.ts.map +1 -0
- package/lib/host/browser-agent/driver.d.ts +40 -0
- package/lib/host/browser-agent/driver.d.ts.map +1 -1
- package/lib/host/browser-agent/human-gate.d.ts +8 -0
- package/lib/host/browser-agent/human-gate.d.ts.map +1 -1
- package/lib/host/browser-agent/install.d.ts +19 -1
- package/lib/host/browser-agent/install.d.ts.map +1 -1
- package/lib/host/browser-agent/playwright-driver.d.ts +56 -5
- package/lib/host/browser-agent/playwright-driver.d.ts.map +1 -1
- package/lib/host/browser-agent/playwright-snapshot.d.ts +20 -2
- package/lib/host/browser-agent/playwright-snapshot.d.ts.map +1 -1
- package/lib/host/browser-agent/protocol.d.ts +17 -0
- package/lib/host/browser-agent/protocol.d.ts.map +1 -1
- package/lib/host/browser-agent/session-state.d.ts +24 -9
- package/lib/host/browser-agent/session-state.d.ts.map +1 -1
- package/lib/host/browser-agent/tab-registry.d.ts +32 -0
- package/lib/host/browser-agent/tab-registry.d.ts.map +1 -0
- package/lib/host/browser-agent/tab-scope.d.ts +22 -0
- package/lib/host/browser-agent/tab-scope.d.ts.map +1 -0
- package/lib/host/browser-agent/tools.d.ts +8 -0
- package/lib/host/browser-agent/tools.d.ts.map +1 -1
- package/lib/host/index.d.ts +10 -1
- package/lib/host/index.d.ts.map +1 -1
- package/lib/host/rpc.d.ts +331 -0
- package/lib/host/rpc.d.ts.map +1 -1
- package/lib/index.js +1030 -118
- package/lib/index.js.map +4 -4
- package/package.json +69 -70
package/lib/index.js
CHANGED
|
@@ -20,6 +20,28 @@ function resolveRunAlertsLevel(value) {
|
|
|
20
20
|
return "unfocused";
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
|
+
var BROWSER_AGENT_IDLE_CLOSE = ["10m", "30m", "60m", "never"];
|
|
24
|
+
function resolveBrowserAgentIdleClose(value) {
|
|
25
|
+
if (value === false) return "never";
|
|
26
|
+
if (value === true) return "10m";
|
|
27
|
+
return BROWSER_AGENT_IDLE_CLOSE.includes(value) ? value : "10m";
|
|
28
|
+
}
|
|
29
|
+
function browserAgentIdleCloseMs(value) {
|
|
30
|
+
switch (value) {
|
|
31
|
+
case "10m":
|
|
32
|
+
return 10 * 6e4;
|
|
33
|
+
case "30m":
|
|
34
|
+
return 30 * 6e4;
|
|
35
|
+
case "60m":
|
|
36
|
+
return 60 * 6e4;
|
|
37
|
+
case "never":
|
|
38
|
+
return null;
|
|
39
|
+
default: {
|
|
40
|
+
const _exhaustive = value;
|
|
41
|
+
return _exhaustive;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
23
45
|
function resolveBrowserAgentBrowser(value) {
|
|
24
46
|
switch (value) {
|
|
25
47
|
case "auto":
|
|
@@ -68,6 +90,8 @@ var DEFAULT_SETTINGS = {
|
|
|
68
90
|
runAlertsLevel: "unfocused",
|
|
69
91
|
browserAgentEnabled: false,
|
|
70
92
|
browserAgentBrowser: "auto",
|
|
93
|
+
browserAgentDebugTools: false,
|
|
94
|
+
browserAgentIdleClose: "10m",
|
|
71
95
|
webChatBridgeEnabled: true,
|
|
72
96
|
instructionsSkillsEnabled: true,
|
|
73
97
|
mcpConnectorsEnabled: true,
|
|
@@ -113,6 +137,8 @@ function resolveSettings(value) {
|
|
|
113
137
|
runAlertsLevel: resolveRunAlertsLevel(value?.runAlertsLevel),
|
|
114
138
|
browserAgentEnabled: value?.browserAgentEnabled ?? false,
|
|
115
139
|
browserAgentBrowser: resolveBrowserAgentBrowser(value?.browserAgentBrowser),
|
|
140
|
+
browserAgentDebugTools: value?.browserAgentDebugTools === true,
|
|
141
|
+
browserAgentIdleClose: resolveBrowserAgentIdleClose(value?.browserAgentIdleClose),
|
|
116
142
|
webChatBridgeEnabled: value?.webChatBridgeEnabled ?? true,
|
|
117
143
|
instructionsSkillsEnabled: value?.instructionsSkillsEnabled ?? true,
|
|
118
144
|
mcpConnectorsEnabled: value?.mcpConnectorsEnabled ?? true,
|
|
@@ -358,6 +384,7 @@ var BrowserHumanGate = class {
|
|
|
358
384
|
const request = {
|
|
359
385
|
id,
|
|
360
386
|
sessionId: input.sessionId,
|
|
387
|
+
kind: input.kind ?? "human",
|
|
361
388
|
prompt: input.prompt,
|
|
362
389
|
detail: input.detail,
|
|
363
390
|
...input.url === void 0 ? {} : { url: input.url }
|
|
@@ -605,7 +632,6 @@ function stopAgentBrowserProcesses(profileDir) {
|
|
|
605
632
|
|
|
606
633
|
// src/host/browser-agent/playwright-driver.ts
|
|
607
634
|
import { existsSync as existsSync2, mkdirSync } from "node:fs";
|
|
608
|
-
import { chromium, webkit } from "playwright-core";
|
|
609
635
|
|
|
610
636
|
// src/host/browser-agent/proximity.ts
|
|
611
637
|
function attachHrefByProximity(nodes, anchors) {
|
|
@@ -675,7 +701,7 @@ function attachHrefByProximity(nodes, anchors) {
|
|
|
675
701
|
}
|
|
676
702
|
|
|
677
703
|
// src/host/browser-agent/playwright-snapshot.ts
|
|
678
|
-
var PLAYWRIGHT_DRIVER_VERSION = "pw-0.
|
|
704
|
+
var PLAYWRIGHT_DRIVER_VERSION = "pw-0.2.0";
|
|
679
705
|
var PLAYWRIGHT_REF_ATTR = "data-dsh-ba-ref";
|
|
680
706
|
var MAX_NODES = 80;
|
|
681
707
|
var HARVEST_PAGE_SNAPSHOT_SOURCE = `"use strict";
|
|
@@ -851,7 +877,33 @@ for (var ri = 0; ri < records.length; ri++) {
|
|
|
851
877
|
preferred.setAttribute(attr, String(rec.ref));
|
|
852
878
|
}
|
|
853
879
|
`;
|
|
854
|
-
|
|
880
|
+
function selectSnapshotRows(rows, max) {
|
|
881
|
+
const budget = Math.max(0, Math.trunc(max));
|
|
882
|
+
if (budget === 0) return [];
|
|
883
|
+
const links = rows.filter((row) => row.priority <= 0);
|
|
884
|
+
const controls = rows.filter((row) => row.priority === 1);
|
|
885
|
+
const anchors = rows.filter((row) => row.priority > 1);
|
|
886
|
+
const controlSlots = Math.min(controls.length, Math.max(1, Math.floor(budget / 2)));
|
|
887
|
+
const linkSlots = Math.min(links.length, budget - controlSlots);
|
|
888
|
+
let remaining = budget - controlSlots - linkSlots;
|
|
889
|
+
const anchorSlots = Math.min(anchors.length, remaining);
|
|
890
|
+
remaining -= anchorSlots;
|
|
891
|
+
const picked = /* @__PURE__ */ new Set([
|
|
892
|
+
...controls.slice(0, controlSlots),
|
|
893
|
+
...links.slice(0, linkSlots),
|
|
894
|
+
...anchors.slice(0, anchorSlots)
|
|
895
|
+
]);
|
|
896
|
+
if (remaining > 0) {
|
|
897
|
+
for (const row of [...links.slice(linkSlots), ...controls.slice(controlSlots)]) {
|
|
898
|
+
if (remaining === 0) break;
|
|
899
|
+
picked.add(row);
|
|
900
|
+
remaining -= 1;
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
const groupOf = (row) => row.priority === 1 ? 0 : row.priority <= 0 ? 1 : 2;
|
|
904
|
+
return rows.filter((row) => picked.has(row)).sort((a, b) => groupOf(a) - groupOf(b));
|
|
905
|
+
}
|
|
906
|
+
async function capturePlaywrightSnapshot(page, options = {}) {
|
|
855
907
|
const harvest = await page.evaluate(`(() => { ${HARVEST_PAGE_SNAPSHOT_SOURCE} })()`);
|
|
856
908
|
const proximityNodes = harvest.interactive.map((item) => ({
|
|
857
909
|
href: item.href,
|
|
@@ -880,7 +932,10 @@ async function capturePlaywrightSnapshot(page) {
|
|
|
880
932
|
x: typeof node.x === "number" ? node.x : 0,
|
|
881
933
|
y: typeof node.y === "number" ? node.y : 0,
|
|
882
934
|
sensitive: item?.sensitive === true,
|
|
883
|
-
|
|
935
|
+
// Rank by element kind, not by whether proximity bound an href: a button
|
|
936
|
+
// sitting near a link would otherwise be treated as a link and lose the
|
|
937
|
+
// node budget to real anchors.
|
|
938
|
+
priority: (item?.tag ?? "a") === "a" ? 0 : 1
|
|
884
939
|
};
|
|
885
940
|
});
|
|
886
941
|
const knownHrefs = new Set(rows.map((r) => r.href).filter((h) => h !== ""));
|
|
@@ -895,15 +950,17 @@ async function capturePlaywrightSnapshot(page) {
|
|
|
895
950
|
x: anchor.x + anchor.w / 2,
|
|
896
951
|
y: anchor.y + anchor.h / 2,
|
|
897
952
|
sensitive: false,
|
|
898
|
-
|
|
953
|
+
// 2, not 0: a synthetic anchor (harvested from geometry, not an element)
|
|
954
|
+
// must never push a real button/input out of the node budget.
|
|
955
|
+
priority: 2
|
|
899
956
|
});
|
|
900
957
|
}
|
|
901
|
-
|
|
902
|
-
const limited = rows.slice(0, MAX_NODES);
|
|
958
|
+
const limited = selectSnapshotRows(rows, MAX_NODES);
|
|
903
959
|
const nodes = [];
|
|
904
960
|
const refs = /* @__PURE__ */ new Map();
|
|
961
|
+
const refBase = Number.isFinite(options.startRef) ? Math.max(1, Math.trunc(options.startRef)) : 1;
|
|
905
962
|
for (const row of limited) {
|
|
906
|
-
const ref = nodes.length
|
|
963
|
+
const ref = refBase + nodes.length;
|
|
907
964
|
nodes.push({
|
|
908
965
|
ref,
|
|
909
966
|
role: row.role,
|
|
@@ -939,10 +996,14 @@ async function capturePlaywrightSnapshot(page) {
|
|
|
939
996
|
title: await page.title().catch(() => ""),
|
|
940
997
|
nodes,
|
|
941
998
|
textPreview: harvest.textPreview,
|
|
942
|
-
tabId: 1,
|
|
943
999
|
source: harvest.anchors.length > 0 || proximityHits > 0 ? "playwright+anchors" : "playwright",
|
|
944
1000
|
extensionVersion: PLAYWRIGHT_DRIVER_VERSION,
|
|
945
1001
|
anchorCount: harvest.anchors.length,
|
|
1002
|
+
harvest: {
|
|
1003
|
+
interactive: harvest.interactive.length,
|
|
1004
|
+
controls: rows.filter((row) => row.priority === 1).length,
|
|
1005
|
+
anchors: proximityAnchors.length
|
|
1006
|
+
},
|
|
946
1007
|
...withHref === 0 ? {
|
|
947
1008
|
note: `No http(s) href on interactive refs yet (anchors_in_dom=${harvest.anchors.length}). browser_wait then browser_snapshot again.`
|
|
948
1009
|
} : 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 +1011,62 @@ async function capturePlaywrightSnapshot(page) {
|
|
|
950
1011
|
return { body, refs };
|
|
951
1012
|
}
|
|
952
1013
|
|
|
1014
|
+
// src/host/browser-agent/capture.ts
|
|
1015
|
+
var SECRET_PARAM = /^(access_?token|id_?token|auth|authorization|code|key|password|secret|session|sessionid|sig|signature|token)$/i;
|
|
1016
|
+
var URL_IN_TEXT = /https?:\/\/[^\s"'<>]+/g;
|
|
1017
|
+
function redactUrl(raw) {
|
|
1018
|
+
const withoutUserInfo = raw.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i, "$1");
|
|
1019
|
+
const withoutFragment = withoutUserInfo.replace(/#.*$/, "");
|
|
1020
|
+
const masked = withoutFragment.replace(
|
|
1021
|
+
/([?&])([^=&#]+)=([^&#]*)/g,
|
|
1022
|
+
(match, separator, key) => SECRET_PARAM.test(decodeURIComponent(key)) ? `${separator}${key}=***` : match
|
|
1023
|
+
);
|
|
1024
|
+
return masked.length > 300 ? `${masked.slice(0, 300)}\u2026` : masked;
|
|
1025
|
+
}
|
|
1026
|
+
function redactText(text3) {
|
|
1027
|
+
return text3.replace(URL_IN_TEXT, (match) => {
|
|
1028
|
+
const trailing = match.match(/[),.;]+$/)?.[0] ?? "";
|
|
1029
|
+
const core = trailing === "" ? match : match.slice(0, -trailing.length);
|
|
1030
|
+
return `${redactUrl(core)}${trailing}`;
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
var CaptureBuffer = class {
|
|
1034
|
+
constructor(max = 300) {
|
|
1035
|
+
this.max = max;
|
|
1036
|
+
}
|
|
1037
|
+
max;
|
|
1038
|
+
entries = [];
|
|
1039
|
+
dropped = 0;
|
|
1040
|
+
get size() {
|
|
1041
|
+
return this.entries.length;
|
|
1042
|
+
}
|
|
1043
|
+
push(entry) {
|
|
1044
|
+
this.entries.push(entry);
|
|
1045
|
+
while (this.entries.length > this.max) {
|
|
1046
|
+
this.entries.shift();
|
|
1047
|
+
this.dropped += 1;
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
/** Newest `limit` entries of the requested kind, optionally clearing them. */
|
|
1051
|
+
read(kind, options = {}) {
|
|
1052
|
+
const limit = Math.min(Math.max(Math.trunc(options.limit ?? 40), 1), 200);
|
|
1053
|
+
const ofKind = this.entries.filter((entry) => kind === "all" || entry.kind === (kind === "network" ? "request" : "console"));
|
|
1054
|
+
const matched = options.tabId === void 0 ? ofKind : ofKind.filter((entry) => entry.tabId === options.tabId);
|
|
1055
|
+
const skipped = ofKind.length - matched.length;
|
|
1056
|
+
const selected = matched.slice(-limit);
|
|
1057
|
+
if (options.clear === true) {
|
|
1058
|
+
const keep = this.entries.filter((entry) => !selected.includes(entry));
|
|
1059
|
+
this.entries.length = 0;
|
|
1060
|
+
this.entries.push(...keep);
|
|
1061
|
+
}
|
|
1062
|
+
return { entries: selected, dropped: this.dropped, skipped };
|
|
1063
|
+
}
|
|
1064
|
+
clear() {
|
|
1065
|
+
this.entries.length = 0;
|
|
1066
|
+
this.dropped = 0;
|
|
1067
|
+
}
|
|
1068
|
+
};
|
|
1069
|
+
|
|
953
1070
|
// src/host/browser-agent/auto-nav.ts
|
|
954
1071
|
function pathKey(raw) {
|
|
955
1072
|
try {
|
|
@@ -1006,7 +1123,70 @@ function pickAutoNavigateHref(links, beforeUrl, preferredName = "") {
|
|
|
1006
1123
|
return best;
|
|
1007
1124
|
}
|
|
1008
1125
|
|
|
1126
|
+
// src/host/browser-agent/tab-registry.ts
|
|
1127
|
+
var EMPTY_REFS = /* @__PURE__ */ new Map();
|
|
1128
|
+
var TabRegistry = class {
|
|
1129
|
+
idByPage = /* @__PURE__ */ new WeakMap();
|
|
1130
|
+
pageById = /* @__PURE__ */ new Map();
|
|
1131
|
+
refsById = /* @__PURE__ */ new Map();
|
|
1132
|
+
nextId = 1;
|
|
1133
|
+
/** Stable id for a page, assigned on first sight. */
|
|
1134
|
+
idOf(page) {
|
|
1135
|
+
const known = this.idByPage.get(page);
|
|
1136
|
+
if (known !== void 0) return known;
|
|
1137
|
+
const id = this.nextId;
|
|
1138
|
+
this.nextId += 1;
|
|
1139
|
+
this.idByPage.set(page, id);
|
|
1140
|
+
this.pageById.set(id, page);
|
|
1141
|
+
this.refsById.set(id, /* @__PURE__ */ new Map());
|
|
1142
|
+
return id;
|
|
1143
|
+
}
|
|
1144
|
+
/** Forget a closed page. Its id is retired, never handed to another page. */
|
|
1145
|
+
release(page) {
|
|
1146
|
+
const id = this.idByPage.get(page);
|
|
1147
|
+
if (id === void 0) return;
|
|
1148
|
+
this.idByPage.delete(page);
|
|
1149
|
+
this.pageById.delete(id);
|
|
1150
|
+
this.refsById.delete(id);
|
|
1151
|
+
}
|
|
1152
|
+
page(tabId) {
|
|
1153
|
+
return this.pageById.get(tabId);
|
|
1154
|
+
}
|
|
1155
|
+
refsOf(tabId) {
|
|
1156
|
+
return this.refsById.get(tabId) ?? EMPTY_REFS;
|
|
1157
|
+
}
|
|
1158
|
+
ref(tabId, ref) {
|
|
1159
|
+
return this.refsById.get(tabId)?.get(ref);
|
|
1160
|
+
}
|
|
1161
|
+
setRefs(tabId, refs) {
|
|
1162
|
+
this.refsById.set(tabId, new Map(refs));
|
|
1163
|
+
}
|
|
1164
|
+
clearRefs(tabId) {
|
|
1165
|
+
this.refsById.set(tabId, /* @__PURE__ */ new Map());
|
|
1166
|
+
}
|
|
1167
|
+
/** Which other tab still holds this ref — used to explain a cross-tab mistake. */
|
|
1168
|
+
tabHolding(ref, exceptTabId) {
|
|
1169
|
+
for (const [tabId, refs] of this.refsById) {
|
|
1170
|
+
if (tabId !== exceptTabId && refs.has(ref)) return tabId;
|
|
1171
|
+
}
|
|
1172
|
+
return void 0;
|
|
1173
|
+
}
|
|
1174
|
+
/** Actionable message for a ref that is not in the active tab. */
|
|
1175
|
+
unknownRefMessage(ref, activeTabId) {
|
|
1176
|
+
const other = this.tabHolding(ref, activeTabId);
|
|
1177
|
+
if (other !== void 0) {
|
|
1178
|
+
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.`;
|
|
1179
|
+
}
|
|
1180
|
+
return `Unknown ref ${ref}; call browser_snapshot first`;
|
|
1181
|
+
}
|
|
1182
|
+
};
|
|
1183
|
+
|
|
1009
1184
|
// src/host/browser-agent/playwright-driver.ts
|
|
1185
|
+
var playwrightModule = null;
|
|
1186
|
+
async function loadPlaywright() {
|
|
1187
|
+
playwrightModule ??= await import("playwright-core");
|
|
1188
|
+
return playwrightModule;
|
|
1189
|
+
}
|
|
1010
1190
|
var PlaywrightDriver = class {
|
|
1011
1191
|
kind = "playwright";
|
|
1012
1192
|
profileDirOption;
|
|
@@ -1018,7 +1198,18 @@ var PlaywrightDriver = class {
|
|
|
1018
1198
|
lastError = null;
|
|
1019
1199
|
channel = null;
|
|
1020
1200
|
launchedProfileDir = null;
|
|
1021
|
-
|
|
1201
|
+
tabs = new TabRegistry();
|
|
1202
|
+
trackedPages = /* @__PURE__ */ new WeakSet();
|
|
1203
|
+
/** Monotonic per-driver ref counter, so refs never collide across tabs. */
|
|
1204
|
+
nextRef = 1;
|
|
1205
|
+
/** Null until the debug tools ask for capture; stays on for the driver lifetime. */
|
|
1206
|
+
capture = null;
|
|
1207
|
+
captureStartedPages = /* @__PURE__ */ new WeakSet();
|
|
1208
|
+
requestStart = /* @__PURE__ */ new WeakMap();
|
|
1209
|
+
/** Last applied emulation per tab, echoed in snapshot so the agent can see it. */
|
|
1210
|
+
emulationByTab = /* @__PURE__ */ new Map();
|
|
1211
|
+
/** Last agent/UI use per page; a page's clock starts when it is first seen. */
|
|
1212
|
+
lastUse = /* @__PURE__ */ new WeakMap();
|
|
1022
1213
|
constructor(options) {
|
|
1023
1214
|
this.profileDirOption = options.profileDir;
|
|
1024
1215
|
this.preferenceOption = options.preference ?? "auto";
|
|
@@ -1038,9 +1229,56 @@ var PlaywrightDriver = class {
|
|
|
1038
1229
|
}
|
|
1039
1230
|
return this.currentProfileDir();
|
|
1040
1231
|
}
|
|
1041
|
-
/**
|
|
1042
|
-
|
|
1043
|
-
|
|
1232
|
+
/**
|
|
1233
|
+
* Stable id for a page, and the place its refs live. Ids survive other tabs
|
|
1234
|
+
* opening/closing and are never reused; refs stay with the tab that captured
|
|
1235
|
+
* them, so switching tabs no longer invalidates the snapshot you came from.
|
|
1236
|
+
*/
|
|
1237
|
+
tabIdFor(page) {
|
|
1238
|
+
const tabId = this.tabs.idOf(page);
|
|
1239
|
+
if (!this.lastUse.has(page)) this.lastUse.set(page, Date.now());
|
|
1240
|
+
if (!this.trackedPages.has(page)) {
|
|
1241
|
+
this.trackedPages.add(page);
|
|
1242
|
+
page.on("close", () => {
|
|
1243
|
+
this.tabs.release(page);
|
|
1244
|
+
this.emulationByTab.delete(tabId);
|
|
1245
|
+
this.trackedPages.delete(page);
|
|
1246
|
+
});
|
|
1247
|
+
}
|
|
1248
|
+
return tabId;
|
|
1249
|
+
}
|
|
1250
|
+
clearRefs(page) {
|
|
1251
|
+
this.tabs.clearRefs(this.tabIdFor(page));
|
|
1252
|
+
}
|
|
1253
|
+
/** Any real use of a page resets its idle clock; sidebar listing does not. */
|
|
1254
|
+
touch(page) {
|
|
1255
|
+
this.lastUse.set(page, Date.now());
|
|
1256
|
+
}
|
|
1257
|
+
async sweepIdleTabs(input) {
|
|
1258
|
+
const context = this.context;
|
|
1259
|
+
if (context === null) return [];
|
|
1260
|
+
const keep = new Set(input.keep ?? []);
|
|
1261
|
+
const pages = context.pages();
|
|
1262
|
+
const closed = [];
|
|
1263
|
+
const now = Date.now();
|
|
1264
|
+
for (const page of pages) {
|
|
1265
|
+
if (pages.length - closed.length <= 1) break;
|
|
1266
|
+
if (page === this.page || page.isClosed()) continue;
|
|
1267
|
+
const tabId = this.tabIdFor(page);
|
|
1268
|
+
if (keep.has(tabId)) continue;
|
|
1269
|
+
const last = this.lastUse.get(page) ?? now;
|
|
1270
|
+
if (now - last < input.idleMs) continue;
|
|
1271
|
+
await page.close().catch(() => void 0);
|
|
1272
|
+
if (page.isClosed()) closed.push(tabId);
|
|
1273
|
+
}
|
|
1274
|
+
return closed;
|
|
1275
|
+
}
|
|
1276
|
+
/** Page still attached to this context and not closed. */
|
|
1277
|
+
isLivePage(page) {
|
|
1278
|
+
if (page === null || typeof page !== "object") return false;
|
|
1279
|
+
const candidate = page;
|
|
1280
|
+
if (typeof candidate.isClosed !== "function" || candidate.isClosed()) return false;
|
|
1281
|
+
return this.context?.pages().includes(candidate) === true;
|
|
1044
1282
|
}
|
|
1045
1283
|
status() {
|
|
1046
1284
|
const ready = this.context !== null && this.page !== null && !this.page.isClosed();
|
|
@@ -1093,7 +1331,7 @@ var PlaywrightDriver = class {
|
|
|
1093
1331
|
this.context = null;
|
|
1094
1332
|
this.page = null;
|
|
1095
1333
|
this.launchedProfileDir = null;
|
|
1096
|
-
this.
|
|
1334
|
+
this.capture = null;
|
|
1097
1335
|
});
|
|
1098
1336
|
return;
|
|
1099
1337
|
} catch (error) {
|
|
@@ -1122,6 +1360,7 @@ var PlaywrightDriver = class {
|
|
|
1122
1360
|
}
|
|
1123
1361
|
}
|
|
1124
1362
|
let webkitExe;
|
|
1363
|
+
const { webkit } = await loadPlaywright();
|
|
1125
1364
|
try {
|
|
1126
1365
|
webkitExe = webkit.executablePath();
|
|
1127
1366
|
} catch (error) {
|
|
@@ -1149,6 +1388,7 @@ var PlaywrightDriver = class {
|
|
|
1149
1388
|
this.lastError = `${kind} is not installed or not found on PATH`;
|
|
1150
1389
|
return null;
|
|
1151
1390
|
}
|
|
1391
|
+
const { chromium } = await loadPlaywright();
|
|
1152
1392
|
return chromium.launchPersistentContext(profileDir, {
|
|
1153
1393
|
executablePath: resolved.executable,
|
|
1154
1394
|
headless: this.headless,
|
|
@@ -1176,6 +1416,7 @@ var PlaywrightDriver = class {
|
|
|
1176
1416
|
if (this.page === null || this.page.isClosed()) {
|
|
1177
1417
|
throw new Error("Playwright page is not available");
|
|
1178
1418
|
}
|
|
1419
|
+
this.touch(this.page);
|
|
1179
1420
|
return this.page;
|
|
1180
1421
|
}
|
|
1181
1422
|
async pageStatus() {
|
|
@@ -1184,7 +1425,7 @@ var PlaywrightDriver = class {
|
|
|
1184
1425
|
connected: true,
|
|
1185
1426
|
url: page.url(),
|
|
1186
1427
|
title: await page.title().catch(() => ""),
|
|
1187
|
-
tabId:
|
|
1428
|
+
tabId: this.tabIdFor(page),
|
|
1188
1429
|
bound: true
|
|
1189
1430
|
};
|
|
1190
1431
|
}
|
|
@@ -1199,18 +1440,22 @@ var PlaywrightDriver = class {
|
|
|
1199
1440
|
}
|
|
1200
1441
|
await page.goto(url, { waitUntil: "domcontentloaded" });
|
|
1201
1442
|
await settlePage(page);
|
|
1202
|
-
this.
|
|
1443
|
+
this.touch(page);
|
|
1444
|
+
this.clearRefs(page);
|
|
1203
1445
|
return {
|
|
1204
1446
|
url: page.url(),
|
|
1205
1447
|
title: await page.title().catch(() => ""),
|
|
1206
|
-
tabId:
|
|
1448
|
+
tabId: this.tabIdFor(page)
|
|
1207
1449
|
};
|
|
1208
1450
|
}
|
|
1209
1451
|
async snapshot() {
|
|
1210
1452
|
const page = await this.requirePage();
|
|
1211
|
-
const
|
|
1212
|
-
|
|
1213
|
-
|
|
1453
|
+
const tabId = this.tabIdFor(page);
|
|
1454
|
+
const { body, refs } = await capturePlaywrightSnapshot(page, { startRef: this.nextRef });
|
|
1455
|
+
this.nextRef += body.nodes.length;
|
|
1456
|
+
this.tabs.setRefs(tabId, refs);
|
|
1457
|
+
const emulation = this.emulationByTab.get(tabId);
|
|
1458
|
+
return { ...body, ...emulation === void 0 ? {} : { emulation }, tabId };
|
|
1214
1459
|
}
|
|
1215
1460
|
async extract(input = {}) {
|
|
1216
1461
|
const page = await this.requirePage();
|
|
@@ -1223,14 +1468,15 @@ var PlaywrightDriver = class {
|
|
|
1223
1468
|
text: clipped.slice(0, maxChars),
|
|
1224
1469
|
truncated: clipped.length > maxChars,
|
|
1225
1470
|
...input.focus === void 0 || input.focus.trim() === "" ? {} : { focus: input.focus.trim() },
|
|
1226
|
-
tabId:
|
|
1471
|
+
tabId: this.tabIdFor(page)
|
|
1227
1472
|
};
|
|
1228
1473
|
}
|
|
1229
1474
|
async click(ref) {
|
|
1230
1475
|
const page = await this.requirePage();
|
|
1231
|
-
const
|
|
1476
|
+
const tabId = this.tabIdFor(page);
|
|
1477
|
+
const record2 = this.tabs.ref(tabId, ref);
|
|
1232
1478
|
if (record2 === void 0) {
|
|
1233
|
-
throw new Error(
|
|
1479
|
+
throw new Error(this.tabs.unknownRefMessage(ref, tabId));
|
|
1234
1480
|
}
|
|
1235
1481
|
const beforeUrl = page.url();
|
|
1236
1482
|
const href = /^https?:\/\//i.test(record2.href) ? record2.href : "";
|
|
@@ -1246,14 +1492,14 @@ var PlaywrightDriver = class {
|
|
|
1246
1492
|
if (href !== "" && pathsDiffer(beforeUrl, href)) {
|
|
1247
1493
|
await page.goto(href, { waitUntil: "domcontentloaded" });
|
|
1248
1494
|
await settlePage(page);
|
|
1249
|
-
this.
|
|
1495
|
+
this.clearRefs(page);
|
|
1250
1496
|
const after = page.url();
|
|
1251
1497
|
return {
|
|
1252
1498
|
url: after,
|
|
1253
1499
|
title: await page.title().catch(() => ""),
|
|
1254
1500
|
changed: pathsDiffer(beforeUrl, after),
|
|
1255
1501
|
href,
|
|
1256
|
-
tabId:
|
|
1502
|
+
tabId: this.tabIdFor(page),
|
|
1257
1503
|
warning: "Opened this ref's href after snapshot bound a nearby document link."
|
|
1258
1504
|
};
|
|
1259
1505
|
}
|
|
@@ -1265,14 +1511,14 @@ var PlaywrightDriver = class {
|
|
|
1265
1511
|
const adopted = await adoptPopup(popup, beforeUrl);
|
|
1266
1512
|
if (adopted) {
|
|
1267
1513
|
this.page = popup;
|
|
1268
|
-
this.
|
|
1514
|
+
this.clearRefs(page);
|
|
1269
1515
|
await settlePage(popup);
|
|
1270
1516
|
return {
|
|
1271
1517
|
url: popup.url(),
|
|
1272
1518
|
title: await popup.title().catch(() => ""),
|
|
1273
1519
|
changed: true,
|
|
1274
1520
|
...href !== "" ? { href } : {},
|
|
1275
|
-
tabId:
|
|
1521
|
+
tabId: this.tabIdFor(popup),
|
|
1276
1522
|
warning: "Click opened a new tab; rebound the browser-agent session to it."
|
|
1277
1523
|
};
|
|
1278
1524
|
}
|
|
@@ -1296,7 +1542,7 @@ var PlaywrightDriver = class {
|
|
|
1296
1542
|
changed = pathsDiffer(beforeUrl, afterUrl);
|
|
1297
1543
|
followedHref = changed;
|
|
1298
1544
|
}
|
|
1299
|
-
this.
|
|
1545
|
+
this.clearRefs(page);
|
|
1300
1546
|
let pageLinks = [];
|
|
1301
1547
|
if (!changed && href === "") {
|
|
1302
1548
|
pageLinks = await listHttpAnchors(page);
|
|
@@ -1305,7 +1551,7 @@ var PlaywrightDriver = class {
|
|
|
1305
1551
|
url: afterUrl,
|
|
1306
1552
|
title: await page.title().catch(() => ""),
|
|
1307
1553
|
changed,
|
|
1308
|
-
tabId:
|
|
1554
|
+
tabId: this.tabIdFor(page),
|
|
1309
1555
|
...href !== "" ? { href } : {},
|
|
1310
1556
|
...pageLinks.length > 0 ? { pageLinks: pageLinks.slice(0, 8) } : {},
|
|
1311
1557
|
...followedHref ? { warning: "Click missed; opened this ref's own href via navigation." } : !changed ? {
|
|
@@ -1317,14 +1563,14 @@ var PlaywrightDriver = class {
|
|
|
1317
1563
|
if (href !== "" && pathsDiffer(beforeUrl, href)) {
|
|
1318
1564
|
await page.goto(href, { waitUntil: "domcontentloaded" });
|
|
1319
1565
|
await settlePage(page);
|
|
1320
|
-
this.
|
|
1566
|
+
this.clearRefs(page);
|
|
1321
1567
|
const after = page.url();
|
|
1322
1568
|
return {
|
|
1323
1569
|
url: after,
|
|
1324
1570
|
title: await page.title().catch(() => ""),
|
|
1325
1571
|
changed: pathsDiffer(beforeUrl, after),
|
|
1326
1572
|
href,
|
|
1327
|
-
tabId:
|
|
1573
|
+
tabId: this.tabIdFor(page),
|
|
1328
1574
|
warning: "Ref stamp missing; opened this ref's href directly."
|
|
1329
1575
|
};
|
|
1330
1576
|
}
|
|
@@ -1334,12 +1580,12 @@ var PlaywrightDriver = class {
|
|
|
1334
1580
|
await settlePage(page);
|
|
1335
1581
|
const afterUrl = page.url();
|
|
1336
1582
|
const changed = pathsDiffer(beforeUrl, afterUrl);
|
|
1337
|
-
this.
|
|
1583
|
+
this.clearRefs(page);
|
|
1338
1584
|
return {
|
|
1339
1585
|
url: afterUrl,
|
|
1340
1586
|
title: await page.title().catch(() => ""),
|
|
1341
1587
|
changed,
|
|
1342
|
-
tabId:
|
|
1588
|
+
tabId: this.tabIdFor(page),
|
|
1343
1589
|
...href !== "" ? { href } : {},
|
|
1344
1590
|
...!changed ? {
|
|
1345
1591
|
warning: "Pathname unchanged after coordinate click. browser_snapshot again or browser_navigate by href."
|
|
@@ -1348,8 +1594,9 @@ var PlaywrightDriver = class {
|
|
|
1348
1594
|
}
|
|
1349
1595
|
async type(ref, text3) {
|
|
1350
1596
|
const page = await this.requirePage();
|
|
1351
|
-
|
|
1352
|
-
|
|
1597
|
+
const tabId = this.tabIdFor(page);
|
|
1598
|
+
if (this.tabs.ref(tabId, ref) === void 0) {
|
|
1599
|
+
throw new Error(this.tabs.unknownRefMessage(ref, tabId));
|
|
1353
1600
|
}
|
|
1354
1601
|
const locator = page.locator(`[${PLAYWRIGHT_REF_ATTR}="${ref}"]`).first();
|
|
1355
1602
|
const count = await locator.count().catch(() => 0);
|
|
@@ -1364,12 +1611,12 @@ var PlaywrightDriver = class {
|
|
|
1364
1611
|
await locator.pressSequentially(text3, { delay: 10 });
|
|
1365
1612
|
}
|
|
1366
1613
|
await settlePage(page);
|
|
1367
|
-
this.
|
|
1614
|
+
this.clearRefs(page);
|
|
1368
1615
|
return {
|
|
1369
1616
|
url: page.url(),
|
|
1370
1617
|
title: await page.title().catch(() => ""),
|
|
1371
1618
|
changed: false,
|
|
1372
|
-
tabId:
|
|
1619
|
+
tabId: this.tabIdFor(page)
|
|
1373
1620
|
};
|
|
1374
1621
|
}
|
|
1375
1622
|
async scroll(dy) {
|
|
@@ -1380,7 +1627,7 @@ var PlaywrightDriver = class {
|
|
|
1380
1627
|
url: page.url(),
|
|
1381
1628
|
title: await page.title().catch(() => ""),
|
|
1382
1629
|
changed: false,
|
|
1383
|
-
tabId:
|
|
1630
|
+
tabId: this.tabIdFor(page)
|
|
1384
1631
|
};
|
|
1385
1632
|
}
|
|
1386
1633
|
async wait(input = {}) {
|
|
@@ -1401,7 +1648,7 @@ var PlaywrightDriver = class {
|
|
|
1401
1648
|
url: page.url(),
|
|
1402
1649
|
title: await page.title().catch(() => ""),
|
|
1403
1650
|
matched,
|
|
1404
|
-
tabId:
|
|
1651
|
+
tabId: this.tabIdFor(page)
|
|
1405
1652
|
};
|
|
1406
1653
|
}
|
|
1407
1654
|
async screenshot() {
|
|
@@ -1410,7 +1657,7 @@ var PlaywrightDriver = class {
|
|
|
1410
1657
|
return {
|
|
1411
1658
|
mime: "image/png",
|
|
1412
1659
|
base64: buf.toString("base64"),
|
|
1413
|
-
tabId:
|
|
1660
|
+
tabId: this.tabIdFor(page)
|
|
1414
1661
|
};
|
|
1415
1662
|
}
|
|
1416
1663
|
async listTabs() {
|
|
@@ -1419,25 +1666,166 @@ var PlaywrightDriver = class {
|
|
|
1419
1666
|
return { tabs: [], boundTabId: null };
|
|
1420
1667
|
}
|
|
1421
1668
|
return {
|
|
1422
|
-
tabs: await Promise.all(pages.map(async (p
|
|
1423
|
-
tabId:
|
|
1669
|
+
tabs: await Promise.all(pages.map(async (p) => ({
|
|
1670
|
+
tabId: this.tabIdFor(p),
|
|
1424
1671
|
title: await p.title().catch(() => ""),
|
|
1425
1672
|
url: p.url(),
|
|
1426
1673
|
active: p === this.page,
|
|
1427
|
-
// Session bind
|
|
1428
|
-
bound: p === this.page
|
|
1674
|
+
// Session bind and read-only scope are layered in install.listTabs.
|
|
1675
|
+
bound: p === this.page,
|
|
1676
|
+
readOnly: false
|
|
1429
1677
|
}))),
|
|
1430
|
-
boundTabId: this.page ?
|
|
1678
|
+
boundTabId: this.page === null ? null : this.tabIdFor(this.page)
|
|
1431
1679
|
};
|
|
1432
1680
|
}
|
|
1681
|
+
startCapture() {
|
|
1682
|
+
if (this.capture !== null) return;
|
|
1683
|
+
const context = this.context;
|
|
1684
|
+
if (context === null) return;
|
|
1685
|
+
this.capture = new CaptureBuffer(300);
|
|
1686
|
+
for (const page of context.pages()) this.attachCapture(page);
|
|
1687
|
+
context.on("page", (page) => this.attachCapture(page));
|
|
1688
|
+
}
|
|
1689
|
+
/**
|
|
1690
|
+
* Stop recording and drop the buffer. Listeners stay attached (they close over
|
|
1691
|
+
* the old buffer), so each one checks that it is still the live buffer.
|
|
1692
|
+
*/
|
|
1693
|
+
stopCapture() {
|
|
1694
|
+
this.capture = null;
|
|
1695
|
+
}
|
|
1696
|
+
attachCapture(page) {
|
|
1697
|
+
if (this.capture === null || this.captureStartedPages.has(page)) return;
|
|
1698
|
+
this.captureStartedPages.add(page);
|
|
1699
|
+
const tabId = this.tabIdFor(page);
|
|
1700
|
+
const stamp = () => Date.now();
|
|
1701
|
+
const record2 = (entry) => {
|
|
1702
|
+
this.capture?.push(entry);
|
|
1703
|
+
};
|
|
1704
|
+
page.on("console", (message) => {
|
|
1705
|
+
if (this.capture === null) return;
|
|
1706
|
+
try {
|
|
1707
|
+
record2({
|
|
1708
|
+
kind: "console",
|
|
1709
|
+
at: stamp(),
|
|
1710
|
+
tabId,
|
|
1711
|
+
level: message.type(),
|
|
1712
|
+
// Console text can embed a request URL, so it gets the same masking as
|
|
1713
|
+
// the network layer; otherwise a failed fetch leaks its query string.
|
|
1714
|
+
text: clipText(redactText(message.text()), 500),
|
|
1715
|
+
...message.location().url === "" ? {} : { location: redactText(`${message.location().url}:${message.location().lineNumber}`) }
|
|
1716
|
+
});
|
|
1717
|
+
} catch {
|
|
1718
|
+
}
|
|
1719
|
+
});
|
|
1720
|
+
page.on("pageerror", (error) => {
|
|
1721
|
+
if (this.capture === null) return;
|
|
1722
|
+
record2({
|
|
1723
|
+
kind: "console",
|
|
1724
|
+
at: stamp(),
|
|
1725
|
+
tabId,
|
|
1726
|
+
level: "pageerror",
|
|
1727
|
+
text: clipText(redactText(error instanceof Error ? error.message : String(error)), 500)
|
|
1728
|
+
});
|
|
1729
|
+
});
|
|
1730
|
+
page.on("request", (request) => {
|
|
1731
|
+
if (this.capture === null) return;
|
|
1732
|
+
this.requestStart.set(request, performance.now());
|
|
1733
|
+
});
|
|
1734
|
+
page.on("response", (response) => {
|
|
1735
|
+
if (this.capture === null) return;
|
|
1736
|
+
const request = response.request();
|
|
1737
|
+
const started = this.requestStart.get(request);
|
|
1738
|
+
record2({
|
|
1739
|
+
kind: "request",
|
|
1740
|
+
at: stamp(),
|
|
1741
|
+
tabId,
|
|
1742
|
+
method: request.method(),
|
|
1743
|
+
url: redactUrl(response.url()),
|
|
1744
|
+
resourceType: request.resourceType(),
|
|
1745
|
+
status: response.status(),
|
|
1746
|
+
...started === void 0 ? {} : { durationMs: Math.round(performance.now() - started) }
|
|
1747
|
+
});
|
|
1748
|
+
});
|
|
1749
|
+
page.on("requestfailed", (request) => {
|
|
1750
|
+
if (this.capture === null) return;
|
|
1751
|
+
const started = this.requestStart.get(request);
|
|
1752
|
+
record2({
|
|
1753
|
+
kind: "request",
|
|
1754
|
+
at: stamp(),
|
|
1755
|
+
tabId,
|
|
1756
|
+
method: request.method(),
|
|
1757
|
+
url: redactUrl(request.url()),
|
|
1758
|
+
resourceType: request.resourceType(),
|
|
1759
|
+
...started === void 0 ? {} : { durationMs: Math.round(performance.now() - started) },
|
|
1760
|
+
failure: clipText(request.failure()?.errorText ?? "request failed", 160)
|
|
1761
|
+
});
|
|
1762
|
+
});
|
|
1763
|
+
}
|
|
1764
|
+
readCapture(input) {
|
|
1765
|
+
if (this.capture === null) return { entries: [], dropped: 0, skipped: 0 };
|
|
1766
|
+
return this.capture.read(input.kind, {
|
|
1767
|
+
...input.limit === void 0 ? {} : { limit: input.limit },
|
|
1768
|
+
...input.clear === void 0 ? {} : { clear: input.clear },
|
|
1769
|
+
...input.tabId === void 0 ? {} : { tabId: input.tabId }
|
|
1770
|
+
});
|
|
1771
|
+
}
|
|
1772
|
+
async emulate(input) {
|
|
1773
|
+
const page = await this.requirePage();
|
|
1774
|
+
const applied = [];
|
|
1775
|
+
const media = {};
|
|
1776
|
+
if (input.colorScheme !== void 0) {
|
|
1777
|
+
media.colorScheme = input.colorScheme === "reset" ? null : input.colorScheme;
|
|
1778
|
+
applied.push(`colorScheme=${input.colorScheme}`);
|
|
1779
|
+
}
|
|
1780
|
+
if (input.reducedMotion !== void 0) {
|
|
1781
|
+
media.reducedMotion = input.reducedMotion === "reset" ? null : input.reducedMotion;
|
|
1782
|
+
applied.push(`reducedMotion=${input.reducedMotion}`);
|
|
1783
|
+
}
|
|
1784
|
+
if (Object.keys(media).length > 0) await page.emulateMedia(media);
|
|
1785
|
+
if (input.viewport !== void 0) {
|
|
1786
|
+
const width = Math.min(Math.max(Math.trunc(input.viewport.width), 320), 3840);
|
|
1787
|
+
const height = Math.min(Math.max(Math.trunc(input.viewport.height), 240), 2160);
|
|
1788
|
+
await page.setViewportSize({ width, height });
|
|
1789
|
+
applied.push(`viewport=${width}x${height}`);
|
|
1790
|
+
}
|
|
1791
|
+
const tabId = this.tabIdFor(page);
|
|
1792
|
+
this.rememberEmulation(tabId, input);
|
|
1793
|
+
return {
|
|
1794
|
+
url: page.url(),
|
|
1795
|
+
title: await page.title().catch(() => ""),
|
|
1796
|
+
applied,
|
|
1797
|
+
tabId: this.tabIdFor(page)
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
/** Record what is now emulated on this tab, so snapshot can echo it. */
|
|
1801
|
+
rememberEmulation(tabId, input) {
|
|
1802
|
+
const next = { ...this.emulationByTab.get(tabId) ?? {} };
|
|
1803
|
+
if (input.colorScheme !== void 0) {
|
|
1804
|
+
if (input.colorScheme === "reset") delete next.colorScheme;
|
|
1805
|
+
else next.colorScheme = input.colorScheme;
|
|
1806
|
+
}
|
|
1807
|
+
if (input.reducedMotion !== void 0) {
|
|
1808
|
+
if (input.reducedMotion === "reset") delete next.reducedMotion;
|
|
1809
|
+
else next.reducedMotion = input.reducedMotion;
|
|
1810
|
+
}
|
|
1811
|
+
if (input.viewport !== void 0) {
|
|
1812
|
+
next.viewport = {
|
|
1813
|
+
width: Math.min(Math.max(Math.trunc(input.viewport.width), 320), 3840),
|
|
1814
|
+
height: Math.min(Math.max(Math.trunc(input.viewport.height), 240), 2160)
|
|
1815
|
+
};
|
|
1816
|
+
}
|
|
1817
|
+
if (Object.keys(next).length === 0) this.emulationByTab.delete(tabId);
|
|
1818
|
+
else this.emulationByTab.set(tabId, next);
|
|
1819
|
+
}
|
|
1433
1820
|
async followTab(tabId, _activate = false) {
|
|
1434
1821
|
await this.ensureReady();
|
|
1435
|
-
const
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
this.
|
|
1440
|
-
|
|
1822
|
+
const candidate = this.tabs.page(tabId);
|
|
1823
|
+
if (!this.isLivePage(candidate)) {
|
|
1824
|
+
throw new Error(`No running browser tab for tabId ${tabId} (it may have been closed); call browser_list_tabs for current ids`);
|
|
1825
|
+
}
|
|
1826
|
+
this.page = candidate;
|
|
1827
|
+
this.touch(candidate);
|
|
1828
|
+
return { tabId, url: candidate.url(), title: await candidate.title().catch(() => "") };
|
|
1441
1829
|
}
|
|
1442
1830
|
async bind(tabId, _sessionId) {
|
|
1443
1831
|
return this.followTab(tabId, true);
|
|
@@ -1449,7 +1837,7 @@ var PlaywrightDriver = class {
|
|
|
1449
1837
|
this.page = null;
|
|
1450
1838
|
this.channel = null;
|
|
1451
1839
|
this.launchedProfileDir = null;
|
|
1452
|
-
this.
|
|
1840
|
+
this.capture = null;
|
|
1453
1841
|
if (ctx !== null) {
|
|
1454
1842
|
await ctx.close().catch(() => void 0);
|
|
1455
1843
|
}
|
|
@@ -1463,6 +1851,10 @@ function sleep(ms) {
|
|
|
1463
1851
|
setTimeout(resolve17, ms);
|
|
1464
1852
|
});
|
|
1465
1853
|
}
|
|
1854
|
+
function clipText(text3, max) {
|
|
1855
|
+
const flat = text3.replace(/\s+/g, " ").trim();
|
|
1856
|
+
return flat.length > max ? `${flat.slice(0, max)}\u2026` : flat;
|
|
1857
|
+
}
|
|
1466
1858
|
async function settlePage(page, quietMs = 800) {
|
|
1467
1859
|
await page.waitForLoadState("domcontentloaded").catch(() => void 0);
|
|
1468
1860
|
await Promise.race([
|
|
@@ -1482,11 +1874,6 @@ async function adoptPopup(popup, beforeUrl) {
|
|
|
1482
1874
|
const url = popup.isClosed() ? "" : popup.url();
|
|
1483
1875
|
return /^https?:\/\//i.test(url) && pathsDiffer(beforeUrl, url);
|
|
1484
1876
|
}
|
|
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
1877
|
async function listHttpAnchors(page) {
|
|
1491
1878
|
return page.evaluate(`(() => {
|
|
1492
1879
|
var out = [];
|
|
@@ -1559,22 +1946,43 @@ function registerBrowserAgentPrompt(ctx) {
|
|
|
1559
1946
|
|
|
1560
1947
|
// src/host/browser-agent/session-state.ts
|
|
1561
1948
|
var MAX_AUDIT = 40;
|
|
1949
|
+
function emptyMemory() {
|
|
1950
|
+
return { refs: /* @__PURE__ */ new Set(), hrefs: /* @__PURE__ */ new Map(), names: /* @__PURE__ */ new Map(), dead: /* @__PURE__ */ new Set() };
|
|
1951
|
+
}
|
|
1562
1952
|
var BrowserSessionState = class {
|
|
1563
1953
|
tabBySession = /* @__PURE__ */ new Map();
|
|
1564
1954
|
sessionByTab = /* @__PURE__ */ new Map();
|
|
1565
1955
|
needsHumanBySession = /* @__PURE__ */ new Map();
|
|
1566
|
-
/**
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
/**
|
|
1573
|
-
|
|
1956
|
+
/**
|
|
1957
|
+
* Snapshot memory lives with the tab, not the session: refs captured in a tab
|
|
1958
|
+
* stay valid when the session switches away and back (refs are unique per
|
|
1959
|
+
* driver, so there is no cross-tab aliasing).
|
|
1960
|
+
*/
|
|
1961
|
+
memoryByTab = /* @__PURE__ */ new Map();
|
|
1962
|
+
/** Snapshots taken before a tab is bound (rare, first call) land here. */
|
|
1963
|
+
memoryUnbound = /* @__PURE__ */ new Map();
|
|
1574
1964
|
/** Last http(s) page URL for approval origin when pageStatus is blank/about:blank. */
|
|
1575
1965
|
lastHttpUrlBySession = /* @__PURE__ */ new Map();
|
|
1576
1966
|
conflict = null;
|
|
1577
1967
|
audit = [];
|
|
1968
|
+
/** Memory for this session's current tab, creating it on first use. */
|
|
1969
|
+
memoryOf(sessionId) {
|
|
1970
|
+
const tabId = this.tabBySession.get(sessionId);
|
|
1971
|
+
if (tabId === void 0) {
|
|
1972
|
+
let memory2 = this.memoryUnbound.get(sessionId);
|
|
1973
|
+
if (memory2 === void 0) {
|
|
1974
|
+
memory2 = emptyMemory();
|
|
1975
|
+
this.memoryUnbound.set(sessionId, memory2);
|
|
1976
|
+
}
|
|
1977
|
+
return memory2;
|
|
1978
|
+
}
|
|
1979
|
+
let memory = this.memoryByTab.get(tabId);
|
|
1980
|
+
if (memory === void 0) {
|
|
1981
|
+
memory = emptyMemory();
|
|
1982
|
+
this.memoryByTab.set(tabId, memory);
|
|
1983
|
+
}
|
|
1984
|
+
return memory;
|
|
1985
|
+
}
|
|
1578
1986
|
bind(sessionId, tabId) {
|
|
1579
1987
|
const prev = this.tabBySession.get(sessionId);
|
|
1580
1988
|
if (prev !== void 0 && prev !== tabId) this.sessionByTab.delete(prev);
|
|
@@ -1590,15 +1998,49 @@ var BrowserSessionState = class {
|
|
|
1590
1998
|
sessionOf(tabId) {
|
|
1591
1999
|
return this.sessionByTab.get(tabId);
|
|
1592
2000
|
}
|
|
2001
|
+
/** Tab ids that some session is bound to; idle-close must never take these. */
|
|
2002
|
+
boundTabIds() {
|
|
2003
|
+
return [...this.sessionByTab.keys()];
|
|
2004
|
+
}
|
|
2005
|
+
/**
|
|
2006
|
+
* The tab went away (closed by idle sweep or by the user): drop the binding and
|
|
2007
|
+
* the refs captured there, so the next tool call re-snapshots instead of
|
|
2008
|
+
* resolving refs that no longer exist.
|
|
2009
|
+
*/
|
|
2010
|
+
unbindTab(tabId) {
|
|
2011
|
+
const sessionId = this.sessionByTab.get(tabId);
|
|
2012
|
+
this.sessionByTab.delete(tabId);
|
|
2013
|
+
this.memoryByTab.delete(tabId);
|
|
2014
|
+
if (sessionId === void 0) return void 0;
|
|
2015
|
+
if (this.tabBySession.get(sessionId) === tabId) this.tabBySession.delete(sessionId);
|
|
2016
|
+
this.memoryUnbound.delete(sessionId);
|
|
2017
|
+
if (this.conflict?.sessionId === sessionId) this.conflict = null;
|
|
2018
|
+
return sessionId;
|
|
2019
|
+
}
|
|
2020
|
+
/** Which tab still holds this ref (refs are driver-unique), if any. */
|
|
2021
|
+
tabHoldingRef(ref, exceptTabId) {
|
|
2022
|
+
for (const [tabId, memory] of this.memoryByTab) {
|
|
2023
|
+
if (tabId === exceptTabId) continue;
|
|
2024
|
+
if (memory.refs.has(ref)) return tabId;
|
|
2025
|
+
}
|
|
2026
|
+
return void 0;
|
|
2027
|
+
}
|
|
2028
|
+
/** Drop snapshot memory for tabs that no longer exist. */
|
|
2029
|
+
retainTabs(tabIds) {
|
|
2030
|
+
const alive = new Set(tabIds);
|
|
2031
|
+
for (const tabId of [...this.memoryByTab.keys()]) {
|
|
2032
|
+
if (!alive.has(tabId)) this.memoryByTab.delete(tabId);
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
1593
2035
|
clearSession(sessionId) {
|
|
1594
2036
|
const tabId = this.tabBySession.get(sessionId);
|
|
1595
2037
|
this.tabBySession.delete(sessionId);
|
|
1596
|
-
if (tabId !== void 0)
|
|
2038
|
+
if (tabId !== void 0) {
|
|
2039
|
+
this.sessionByTab.delete(tabId);
|
|
2040
|
+
this.memoryByTab.delete(tabId);
|
|
2041
|
+
}
|
|
2042
|
+
this.memoryUnbound.delete(sessionId);
|
|
1597
2043
|
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
2044
|
this.lastHttpUrlBySession.delete(sessionId);
|
|
1603
2045
|
if (this.conflict?.sessionId === sessionId) this.conflict = null;
|
|
1604
2046
|
for (let i = this.audit.length - 1; i >= 0; i -= 1) {
|
|
@@ -1606,36 +2048,36 @@ var BrowserSessionState = class {
|
|
|
1606
2048
|
}
|
|
1607
2049
|
}
|
|
1608
2050
|
setLastRefs(sessionId, refs) {
|
|
1609
|
-
|
|
1610
|
-
|
|
2051
|
+
const memory = this.memoryOf(sessionId);
|
|
2052
|
+
memory.refs = new Set(refs.filter((ref) => Number.isFinite(ref)));
|
|
2053
|
+
memory.dead = /* @__PURE__ */ new Set();
|
|
1611
2054
|
}
|
|
1612
2055
|
setLastHrefs(sessionId, hrefs) {
|
|
1613
|
-
this.
|
|
2056
|
+
this.memoryOf(sessionId).hrefs = new Map(hrefs);
|
|
1614
2057
|
}
|
|
1615
2058
|
setLastNames(sessionId, names) {
|
|
1616
|
-
this.
|
|
2059
|
+
this.memoryOf(sessionId).names = new Map(names);
|
|
1617
2060
|
}
|
|
1618
2061
|
clearLastRefs(sessionId) {
|
|
1619
|
-
this.
|
|
1620
|
-
|
|
1621
|
-
|
|
2062
|
+
const memory = this.memoryOf(sessionId);
|
|
2063
|
+
memory.refs = /* @__PURE__ */ new Set();
|
|
2064
|
+
memory.hrefs = /* @__PURE__ */ new Map();
|
|
2065
|
+
memory.names = /* @__PURE__ */ new Map();
|
|
1622
2066
|
}
|
|
1623
2067
|
markDeadClickRef(sessionId, ref) {
|
|
1624
|
-
|
|
1625
|
-
set.add(ref);
|
|
1626
|
-
this.deadClickRefsBySession.set(sessionId, set);
|
|
2068
|
+
this.memoryOf(sessionId).dead.add(ref);
|
|
1627
2069
|
}
|
|
1628
2070
|
isDeadClickRef(sessionId, ref) {
|
|
1629
|
-
return this.
|
|
2071
|
+
return this.memoryOf(sessionId).dead.has(ref);
|
|
1630
2072
|
}
|
|
1631
2073
|
hasRef(sessionId, ref) {
|
|
1632
|
-
return this.
|
|
2074
|
+
return this.memoryOf(sessionId).refs.has(ref);
|
|
1633
2075
|
}
|
|
1634
2076
|
hrefOfRef(sessionId, ref) {
|
|
1635
|
-
return this.
|
|
2077
|
+
return this.memoryOf(sessionId).hrefs.get(ref);
|
|
1636
2078
|
}
|
|
1637
2079
|
nameOfRef(sessionId, ref) {
|
|
1638
|
-
return this.
|
|
2080
|
+
return this.memoryOf(sessionId).names.get(ref);
|
|
1639
2081
|
}
|
|
1640
2082
|
rememberHttpUrl(sessionId, url) {
|
|
1641
2083
|
if (!/^https?:\/\//i.test(url)) return;
|
|
@@ -1645,7 +2087,7 @@ var BrowserSessionState = class {
|
|
|
1645
2087
|
return this.lastHttpUrlBySession.get(sessionId);
|
|
1646
2088
|
}
|
|
1647
2089
|
lastRefList(sessionId) {
|
|
1648
|
-
return [...this.
|
|
2090
|
+
return [...this.memoryOf(sessionId).refs];
|
|
1649
2091
|
}
|
|
1650
2092
|
setConflict(conflict) {
|
|
1651
2093
|
this.conflict = conflict;
|
|
@@ -1656,18 +2098,18 @@ var BrowserSessionState = class {
|
|
|
1656
2098
|
currentConflict() {
|
|
1657
2099
|
return this.conflict;
|
|
1658
2100
|
}
|
|
1659
|
-
setNeedsHuman(sessionId, detail) {
|
|
1660
|
-
this.needsHumanBySession.set(sessionId, detail);
|
|
2101
|
+
setNeedsHuman(sessionId, detail, kind = "human") {
|
|
2102
|
+
this.needsHumanBySession.set(sessionId, { detail, kind });
|
|
1661
2103
|
}
|
|
1662
2104
|
clearNeedsHuman(sessionId) {
|
|
1663
2105
|
this.needsHumanBySession.delete(sessionId);
|
|
1664
2106
|
}
|
|
1665
2107
|
needsHuman(sessionId) {
|
|
1666
|
-
return this.needsHumanBySession.get(sessionId);
|
|
2108
|
+
return this.needsHumanBySession.get(sessionId)?.detail;
|
|
1667
2109
|
}
|
|
1668
2110
|
anyNeedsHuman() {
|
|
1669
|
-
for (const [sessionId,
|
|
1670
|
-
return { sessionId, detail };
|
|
2111
|
+
for (const [sessionId, value] of this.needsHumanBySession) {
|
|
2112
|
+
return { sessionId, detail: value.detail, kind: value.kind };
|
|
1671
2113
|
}
|
|
1672
2114
|
return null;
|
|
1673
2115
|
}
|
|
@@ -1680,6 +2122,101 @@ var BrowserSessionState = class {
|
|
|
1680
2122
|
}
|
|
1681
2123
|
};
|
|
1682
2124
|
|
|
2125
|
+
// src/host/browser-agent/tab-scope.ts
|
|
2126
|
+
var TabScopeStore = class {
|
|
2127
|
+
readOnlyTabs = /* @__PURE__ */ new Set();
|
|
2128
|
+
setReadOnly(tabId, readOnly) {
|
|
2129
|
+
if (readOnly) {
|
|
2130
|
+
this.readOnlyTabs.add(tabId);
|
|
2131
|
+
return;
|
|
2132
|
+
}
|
|
2133
|
+
this.readOnlyTabs.delete(tabId);
|
|
2134
|
+
}
|
|
2135
|
+
isReadOnly(tabId) {
|
|
2136
|
+
return tabId !== void 0 && this.readOnlyTabs.has(tabId);
|
|
2137
|
+
}
|
|
2138
|
+
/** Drop scopes for tabs that no longer exist. */
|
|
2139
|
+
retain(tabIds) {
|
|
2140
|
+
const alive = new Set(tabIds);
|
|
2141
|
+
for (const tabId of [...this.readOnlyTabs]) {
|
|
2142
|
+
if (!alive.has(tabId)) this.readOnlyTabs.delete(tabId);
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
clear() {
|
|
2146
|
+
this.readOnlyTabs.clear();
|
|
2147
|
+
}
|
|
2148
|
+
/** Model-facing refusal, shared so every mutating tool says the same thing. */
|
|
2149
|
+
refusal(tabId) {
|
|
2150
|
+
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 }).`;
|
|
2151
|
+
}
|
|
2152
|
+
};
|
|
2153
|
+
|
|
2154
|
+
// src/host/browser-agent/diagnose.ts
|
|
2155
|
+
var PROFILE_LOCK = /ProcessSingleton|SingletonLock|already in use|profile.*(?:lock|use)|EBUSY|EACCES|EPERM/i;
|
|
2156
|
+
var AVAILABILITY = { chrome: "chrome", edge: "edge", safari: "safari" };
|
|
2157
|
+
function usableBrowsers(input) {
|
|
2158
|
+
const { availability, platform } = input;
|
|
2159
|
+
const order = input.preference === "auto" ? platform === "win32" ? ["edge", "chrome"] : platform === "darwin" ? ["safari", "chrome"] : ["chrome"] : [AVAILABILITY[input.preference]];
|
|
2160
|
+
return order.filter((name2) => availability[name2] === true);
|
|
2161
|
+
}
|
|
2162
|
+
function diagnose(input) {
|
|
2163
|
+
return { ...classify(input), browsers: input.availability };
|
|
2164
|
+
}
|
|
2165
|
+
function classify(input) {
|
|
2166
|
+
const detail = typeof input.lastError === "string" && input.lastError.trim() !== "" ? input.lastError.trim() : void 0;
|
|
2167
|
+
if (!input.enabled) {
|
|
2168
|
+
return {
|
|
2169
|
+
code: "disabled",
|
|
2170
|
+
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."
|
|
2171
|
+
};
|
|
2172
|
+
}
|
|
2173
|
+
if (input.ready) {
|
|
2174
|
+
return {
|
|
2175
|
+
code: "ok",
|
|
2176
|
+
nextStep: "Ready: page tools act on the bound tab listed above."
|
|
2177
|
+
};
|
|
2178
|
+
}
|
|
2179
|
+
const usable = usableBrowsers(input);
|
|
2180
|
+
if (detail !== void 0 && /WEBKIT_MISSING/i.test(detail)) {
|
|
2181
|
+
return {
|
|
2182
|
+
code: "webkit_missing",
|
|
2183
|
+
detail,
|
|
2184
|
+
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."
|
|
2185
|
+
};
|
|
2186
|
+
}
|
|
2187
|
+
if (input.preference === "safari" && !input.availability.safari) {
|
|
2188
|
+
return {
|
|
2189
|
+
code: "browser_missing",
|
|
2190
|
+
detail,
|
|
2191
|
+
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."
|
|
2192
|
+
};
|
|
2193
|
+
}
|
|
2194
|
+
if (usable.length === 0 && detail === void 0) {
|
|
2195
|
+
return {
|
|
2196
|
+
code: "browser_missing",
|
|
2197
|
+
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.`
|
|
2198
|
+
};
|
|
2199
|
+
}
|
|
2200
|
+
if (detail !== void 0 && PROFILE_LOCK.test(detail)) {
|
|
2201
|
+
return {
|
|
2202
|
+
code: "profile_locked",
|
|
2203
|
+
detail,
|
|
2204
|
+
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."
|
|
2205
|
+
};
|
|
2206
|
+
}
|
|
2207
|
+
if (detail !== void 0) {
|
|
2208
|
+
return {
|
|
2209
|
+
code: "launch_failed",
|
|
2210
|
+
detail,
|
|
2211
|
+
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."
|
|
2212
|
+
};
|
|
2213
|
+
}
|
|
2214
|
+
return {
|
|
2215
|
+
code: "idle",
|
|
2216
|
+
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."
|
|
2217
|
+
};
|
|
2218
|
+
}
|
|
2219
|
+
|
|
1683
2220
|
// src/host/browser-agent/tools.ts
|
|
1684
2221
|
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
1685
2222
|
var HUMAN_WAIT_TIMEOUT_MS = 15 * 6e4;
|
|
@@ -1714,9 +2251,21 @@ function formatSnapshot(body, extra) {
|
|
|
1714
2251
|
typeof body.source === "string" ? `snapshot_source: ${body.source}` : null,
|
|
1715
2252
|
typeof body.extensionVersion === "string" ? `extension: ${body.extensionVersion}` : null,
|
|
1716
2253
|
typeof body.anchorCount === "number" ? `anchors_in_dom: ${body.anchorCount}` : null,
|
|
2254
|
+
body.harvest === void 0 ? null : `harvest: interactive=${body.harvest.interactive} controls=${body.harvest.controls} anchors=${body.harvest.anchors}`,
|
|
2255
|
+
body.emulation === void 0 ? null : `emulation: ${[
|
|
2256
|
+
body.emulation.colorScheme === void 0 ? null : `colorScheme=${body.emulation.colorScheme}`,
|
|
2257
|
+
body.emulation.reducedMotion === void 0 ? null : `reducedMotion=${body.emulation.reducedMotion}`,
|
|
2258
|
+
body.emulation.viewport === void 0 ? null : `viewport=${body.emulation.viewport.width}x${body.emulation.viewport.height}`
|
|
2259
|
+
].filter((part) => part !== null).join(" ")}`,
|
|
1717
2260
|
typeof body.note === "string" && body.note.trim() !== "" ? `note: ${body.note.trim()}` : null,
|
|
1718
2261
|
...extra ?? [],
|
|
1719
|
-
|
|
2262
|
+
(() => {
|
|
2263
|
+
const links = body.nodes.filter((node) => node.tag === "a").length;
|
|
2264
|
+
const controls = body.nodes.length - links;
|
|
2265
|
+
const shown = body.nodes.length;
|
|
2266
|
+
const tally = controls > 0 ? `${links} link / ${controls} control` : `${links} link`;
|
|
2267
|
+
return controls > 0 ? `interactive (${shown} shown: ${tally} \u2014 controls listed first; 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):`;
|
|
2268
|
+
})(),
|
|
1720
2269
|
...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
2270
|
"text_preview (short \u2014 use browser_extract for long/below-fold content):",
|
|
1722
2271
|
body.textPreview.slice(0, 2e3)
|
|
@@ -1780,6 +2329,14 @@ function driverOf(options) {
|
|
|
1780
2329
|
const value = options.driver;
|
|
1781
2330
|
return typeof value === "function" ? value() : value;
|
|
1782
2331
|
}
|
|
2332
|
+
function pickEnum(value, allowed, field) {
|
|
2333
|
+
if (value === void 0 || value === null || value === "") return void 0;
|
|
2334
|
+
const text3 = String(value).trim().toLowerCase();
|
|
2335
|
+
if (!allowed.includes(text3)) {
|
|
2336
|
+
throw new Error(`${field} must be one of: ${allowed.join(" | ")}`);
|
|
2337
|
+
}
|
|
2338
|
+
return text3;
|
|
2339
|
+
}
|
|
1783
2340
|
function registerBrowserTools(ctx, options) {
|
|
1784
2341
|
const disposers = [];
|
|
1785
2342
|
const guardEnabled = () => {
|
|
@@ -1810,6 +2367,29 @@ function registerBrowserTools(ctx, options) {
|
|
|
1810
2367
|
}
|
|
1811
2368
|
await driverOf(options).ensureReady(startUrl);
|
|
1812
2369
|
};
|
|
2370
|
+
const requireDebugTools = (tool) => {
|
|
2371
|
+
if (options.debugTools?.() === true) return;
|
|
2372
|
+
try {
|
|
2373
|
+
driverOf(options).stopCapture?.();
|
|
2374
|
+
} catch {
|
|
2375
|
+
}
|
|
2376
|
+
throw new Error(
|
|
2377
|
+
`${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\u4E0E\u9875\u9762\u6A21\u62DF, then retry.`
|
|
2378
|
+
);
|
|
2379
|
+
};
|
|
2380
|
+
const requireWritableTab = (sessionId, tool) => {
|
|
2381
|
+
const scope = options.tabScope;
|
|
2382
|
+
if (scope === void 0) return;
|
|
2383
|
+
const tabId = options.sessions.tabOf(sessionId);
|
|
2384
|
+
if (tabId === void 0 || !scope.isReadOnly(tabId)) return;
|
|
2385
|
+
options.sessions.record({
|
|
2386
|
+
sessionId,
|
|
2387
|
+
tool,
|
|
2388
|
+
summary: `Blocked: tab ${tabId} is read-only`,
|
|
2389
|
+
outcome: "denied"
|
|
2390
|
+
});
|
|
2391
|
+
throw new Error(scope.refusal(tabId));
|
|
2392
|
+
};
|
|
1813
2393
|
const requireMutation = async (exec, tool, summary, url) => {
|
|
1814
2394
|
const sessionId = sessionIdOf(exec);
|
|
1815
2395
|
let effectiveUrl = typeof url === "string" && /^https?:\/\//i.test(url) ? url : void 0;
|
|
@@ -1856,13 +2436,14 @@ function registerBrowserTools(ctx, options) {
|
|
|
1856
2436
|
}
|
|
1857
2437
|
};
|
|
1858
2438
|
const pauseForHuman = async (input) => {
|
|
1859
|
-
options.sessions.setNeedsHuman(input.sessionId, input.detail);
|
|
2439
|
+
options.sessions.setNeedsHuman(input.sessionId, input.detail, input.kind ?? "human");
|
|
1860
2440
|
await focusBoundTab(input.sessionId, input.tabId);
|
|
1861
2441
|
try {
|
|
1862
2442
|
return await options.human.waitForHuman({
|
|
1863
2443
|
sessionId: input.sessionId,
|
|
1864
2444
|
prompt: input.prompt,
|
|
1865
2445
|
detail: input.detail,
|
|
2446
|
+
...input.kind === void 0 ? {} : { kind: input.kind },
|
|
1866
2447
|
...input.url === void 0 ? {} : { url: input.url },
|
|
1867
2448
|
signal: input.signal
|
|
1868
2449
|
});
|
|
@@ -1889,6 +2470,13 @@ function registerBrowserTools(ctx, options) {
|
|
|
1889
2470
|
};
|
|
1890
2471
|
const requireFreshRef = (sessionId, ref, tool) => {
|
|
1891
2472
|
if (options.sessions.hasRef(sessionId, ref)) return;
|
|
2473
|
+
const active = options.sessions.tabOf(sessionId);
|
|
2474
|
+
const owner = options.sessions.tabHoldingRef(ref, active);
|
|
2475
|
+
if (owner !== void 0) {
|
|
2476
|
+
throw new Error(
|
|
2477
|
+
`${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.`
|
|
2478
|
+
);
|
|
2479
|
+
}
|
|
1892
2480
|
const known = options.sessions.lastRefList(sessionId);
|
|
1893
2481
|
if (known.length === 0) {
|
|
1894
2482
|
throw new Error(
|
|
@@ -1976,30 +2564,29 @@ function registerBrowserTools(ctx, options) {
|
|
|
1976
2564
|
};
|
|
1977
2565
|
disposers.push(ctx.tools.register(textTool(
|
|
1978
2566
|
"browser_status",
|
|
1979
|
-
"Check the Desktop dedicated
|
|
2567
|
+
"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
2568
|
{},
|
|
1981
2569
|
async (_args, exec) => {
|
|
1982
2570
|
guardEnabled();
|
|
1983
2571
|
const sessionId = sessionIdOf(exec);
|
|
2572
|
+
const diag = options.diagnosis?.();
|
|
2573
|
+
const diagLines = diag === void 0 ? [] : [
|
|
2574
|
+
`diagnosis: ${diag.code}`,
|
|
2575
|
+
`next: ${diag.nextStep}`,
|
|
2576
|
+
diag.detail === void 0 ? null : `detail: ${diag.detail}`
|
|
2577
|
+
].filter((line) => line !== null);
|
|
1984
2578
|
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) {
|
|
2579
|
+
if (!st.listening || !st.ready) {
|
|
1994
2580
|
try {
|
|
1995
2581
|
await ensureConnected();
|
|
1996
2582
|
} catch (error) {
|
|
1997
2583
|
return [
|
|
1998
2584
|
`driver: ${st.kind}`,
|
|
1999
|
-
st.
|
|
2000
|
-
|
|
2585
|
+
`browser: ${st.listening ? "listening, not ready" : "not started"}`,
|
|
2586
|
+
st.endpoint !== void 0 ? `endpoint: ${st.endpoint}` : null,
|
|
2587
|
+
...diagLines,
|
|
2001
2588
|
formatBridgeError(error)
|
|
2002
|
-
].join("\n");
|
|
2589
|
+
].filter((line) => line !== null).join("\n");
|
|
2003
2590
|
}
|
|
2004
2591
|
}
|
|
2005
2592
|
try {
|
|
@@ -2008,8 +2595,8 @@ function registerBrowserTools(ctx, options) {
|
|
|
2008
2595
|
await rememberTab(sessionId, tab.tabId);
|
|
2009
2596
|
return [
|
|
2010
2597
|
`driver: ${driverOf(options).kind}`,
|
|
2011
|
-
"
|
|
2012
|
-
|
|
2598
|
+
"browser: ready",
|
|
2599
|
+
...diagLines,
|
|
2013
2600
|
`url: ${tab.url}`,
|
|
2014
2601
|
`title: ${tab.title}`,
|
|
2015
2602
|
`tabId: ${tab.tabId}`,
|
|
@@ -2020,9 +2607,12 @@ function registerBrowserTools(ctx, options) {
|
|
|
2020
2607
|
].filter((line) => line !== null).join("\n");
|
|
2021
2608
|
} catch (error) {
|
|
2022
2609
|
noteHuman(sessionId, {}, error);
|
|
2023
|
-
return
|
|
2024
|
-
|
|
2025
|
-
|
|
2610
|
+
return [
|
|
2611
|
+
`driver: ${driverOf(options).kind}`,
|
|
2612
|
+
"browser: ready, status call failed",
|
|
2613
|
+
...diagLines,
|
|
2614
|
+
formatBridgeError(error)
|
|
2615
|
+
].join("\n");
|
|
2026
2616
|
}
|
|
2027
2617
|
}
|
|
2028
2618
|
)));
|
|
@@ -2087,6 +2677,8 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
|
|
|
2087
2677
|
sessionId,
|
|
2088
2678
|
prompt,
|
|
2089
2679
|
detail: prompt.slice(0, 240),
|
|
2680
|
+
// A generic "do this in the browser" request must not wear the login card.
|
|
2681
|
+
kind: "ask",
|
|
2090
2682
|
...url === void 0 ? {} : { url },
|
|
2091
2683
|
...tabId === void 0 ? {} : { tabId },
|
|
2092
2684
|
signal: exec.signal
|
|
@@ -2132,6 +2724,7 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
|
|
|
2132
2724
|
if (url === "") throw new Error("url is required");
|
|
2133
2725
|
await ensureConnected(url);
|
|
2134
2726
|
await ensureSessionTab(sessionId);
|
|
2727
|
+
if (!newTab) requireWritableTab(sessionId, "browser_navigate");
|
|
2135
2728
|
await requireMutation(
|
|
2136
2729
|
exec,
|
|
2137
2730
|
"browser_navigate",
|
|
@@ -2187,6 +2780,7 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
|
|
|
2187
2780
|
if (!Number.isFinite(ref)) throw new Error("ref must be a number");
|
|
2188
2781
|
await ensureConnected();
|
|
2189
2782
|
await ensureSessionTab(sessionId);
|
|
2783
|
+
requireWritableTab(sessionId, "browser_click");
|
|
2190
2784
|
let url;
|
|
2191
2785
|
try {
|
|
2192
2786
|
url = (await driverOf(options).pageStatus()).url;
|
|
@@ -2307,6 +2901,7 @@ extension: connected but status failed: ${formatBridgeError(error)}`;
|
|
|
2307
2901
|
if (!Number.isFinite(ref)) throw new Error("ref must be a number");
|
|
2308
2902
|
await ensureConnected();
|
|
2309
2903
|
await ensureSessionTab(sessionId);
|
|
2904
|
+
requireWritableTab(sessionId, "browser_type");
|
|
2310
2905
|
let url;
|
|
2311
2906
|
try {
|
|
2312
2907
|
url = (await driverOf(options).pageStatus()).url;
|
|
@@ -2546,6 +3141,162 @@ Action: browser_extract or browser_snapshot next. Do not navigate away unless th
|
|
|
2546
3141
|
].filter((line) => line !== null).join("\n");
|
|
2547
3142
|
}
|
|
2548
3143
|
)));
|
|
3144
|
+
disposers.push(ctx.tools.register(textTool(
|
|
3145
|
+
"browser_network",
|
|
3146
|
+
"Read buffered network activity for the bound tab (method, url, status, duration, failures). Read-only; no approval. Defaults to the bound tab; pass allTabs: true to include other tabs. 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.",
|
|
3147
|
+
{
|
|
3148
|
+
limit: {
|
|
3149
|
+
type: "number",
|
|
3150
|
+
description: "Newest N entries (default 40, max 200)."
|
|
3151
|
+
},
|
|
3152
|
+
allTabs: {
|
|
3153
|
+
type: "boolean",
|
|
3154
|
+
description: "Read every tab instead of only the bound tab."
|
|
3155
|
+
},
|
|
3156
|
+
clear: {
|
|
3157
|
+
type: "boolean",
|
|
3158
|
+
description: "Drop the returned entries from the buffer."
|
|
3159
|
+
}
|
|
3160
|
+
},
|
|
3161
|
+
async (args, exec) => {
|
|
3162
|
+
guardEnabled();
|
|
3163
|
+
requireDebugTools("browser_network");
|
|
3164
|
+
const sessionId = sessionIdOf(exec);
|
|
3165
|
+
await ensureConnected();
|
|
3166
|
+
await ensureSessionTab(sessionId);
|
|
3167
|
+
const limit = Number(args.limit);
|
|
3168
|
+
const tabId = options.sessions.tabOf(sessionId);
|
|
3169
|
+
const allTabs = args.allTabs === true || tabId === void 0;
|
|
3170
|
+
const driver = driverOf(options);
|
|
3171
|
+
driver.startCapture();
|
|
3172
|
+
const { entries, dropped, skipped } = driver.readCapture({
|
|
3173
|
+
kind: "network",
|
|
3174
|
+
...Number.isFinite(limit) ? { limit } : {},
|
|
3175
|
+
...args.clear === true ? { clear: true } : {},
|
|
3176
|
+
...allTabs ? {} : { tabId }
|
|
3177
|
+
});
|
|
3178
|
+
const rows = entries.filter((entry) => entry.kind === "request");
|
|
3179
|
+
if (rows.length === 0) {
|
|
3180
|
+
return [
|
|
3181
|
+
allTabs ? "no network activity buffered yet." : `no network activity buffered for tab ${tabId ?? "?"}.`,
|
|
3182
|
+
...skipped > 0 ? [`${skipped} entries came from other tabs \u2014 pass allTabs: true to read them.`] : [],
|
|
3183
|
+
"Navigate or wait for the page to load, then call browser_network again."
|
|
3184
|
+
].join("\n");
|
|
3185
|
+
}
|
|
3186
|
+
return [
|
|
3187
|
+
`network entries: ${rows.length} (${allTabs ? "all tabs" : `tab ${tabId}`})${dropped > 0 ? ` (${dropped} older dropped)` : ""}`,
|
|
3188
|
+
...skipped > 0 ? [`${skipped} entries from other tabs not shown \u2014 pass allTabs: true to include them.`] : [],
|
|
3189
|
+
...rows.map((entry) => {
|
|
3190
|
+
const status = entry.kind !== "request" ? "" : entry.status === void 0 ? entry.failure ?? "failed" : String(entry.status);
|
|
3191
|
+
const ms = entry.kind === "request" && entry.durationMs !== void 0 ? ` ${entry.durationMs}ms` : "";
|
|
3192
|
+
const method = entry.kind === "request" ? entry.method : "GET";
|
|
3193
|
+
return `- [${entry.tabId}] ${status} ${method} ${entry.kind === "request" ? entry.url : ""}${ms}`;
|
|
3194
|
+
})
|
|
3195
|
+
].join("\n");
|
|
3196
|
+
}
|
|
3197
|
+
)));
|
|
3198
|
+
disposers.push(ctx.tools.register(textTool(
|
|
3199
|
+
"browser_console",
|
|
3200
|
+
"Read buffered console messages and uncaught page errors for the bound tab. Read-only; no approval. Defaults to the bound tab; pass allTabs: true to include other tabs. Requires the Debug tools switch in Settings \u2192 \u667A\u80FD\u4F53\u589E\u5F3A \u2192 \u6D4F\u89C8\u5668 Agent.",
|
|
3201
|
+
{
|
|
3202
|
+
limit: {
|
|
3203
|
+
type: "number",
|
|
3204
|
+
description: "Newest N entries (default 40, max 200)."
|
|
3205
|
+
},
|
|
3206
|
+
allTabs: {
|
|
3207
|
+
type: "boolean",
|
|
3208
|
+
description: "Read every tab instead of only the bound tab."
|
|
3209
|
+
},
|
|
3210
|
+
clear: {
|
|
3211
|
+
type: "boolean",
|
|
3212
|
+
description: "Drop the returned entries from the buffer."
|
|
3213
|
+
}
|
|
3214
|
+
},
|
|
3215
|
+
async (args, exec) => {
|
|
3216
|
+
guardEnabled();
|
|
3217
|
+
requireDebugTools("browser_console");
|
|
3218
|
+
const sessionId = sessionIdOf(exec);
|
|
3219
|
+
await ensureConnected();
|
|
3220
|
+
await ensureSessionTab(sessionId);
|
|
3221
|
+
const limit = Number(args.limit);
|
|
3222
|
+
const tabId = options.sessions.tabOf(sessionId);
|
|
3223
|
+
const allTabs = args.allTabs === true || tabId === void 0;
|
|
3224
|
+
const driver = driverOf(options);
|
|
3225
|
+
driver.startCapture();
|
|
3226
|
+
const { entries, skipped } = driver.readCapture({
|
|
3227
|
+
kind: "console",
|
|
3228
|
+
...Number.isFinite(limit) ? { limit } : {},
|
|
3229
|
+
...args.clear === true ? { clear: true } : {},
|
|
3230
|
+
...allTabs ? {} : { tabId }
|
|
3231
|
+
});
|
|
3232
|
+
if (entries.length === 0) {
|
|
3233
|
+
return [
|
|
3234
|
+
allTabs ? "no console output buffered yet." : `no console output buffered for tab ${tabId ?? "?"}.`,
|
|
3235
|
+
...skipped > 0 ? [`${skipped} entries came from other tabs \u2014 pass allTabs: true to read them.`] : [],
|
|
3236
|
+
"Reload or interact with the page, then call browser_console again."
|
|
3237
|
+
].join("\n");
|
|
3238
|
+
}
|
|
3239
|
+
return [
|
|
3240
|
+
`console entries: ${entries.length} (${allTabs ? "all tabs" : `tab ${tabId}`})`,
|
|
3241
|
+
...skipped > 0 ? [`${skipped} entries from other tabs not shown \u2014 pass allTabs: true to include them.`] : [],
|
|
3242
|
+
...entries.map((entry) => {
|
|
3243
|
+
if (entry.kind !== "console") return "";
|
|
3244
|
+
const where = entry.location === void 0 ? "" : ` (${entry.location})`;
|
|
3245
|
+
return `- [${entry.tabId}] ${entry.level}: ${entry.text}${where}`;
|
|
3246
|
+
})
|
|
3247
|
+
].filter((line) => line !== "").join("\n");
|
|
3248
|
+
}
|
|
3249
|
+
)));
|
|
3250
|
+
disposers.push(ctx.tools.register(textTool(
|
|
3251
|
+
"browser_emulate",
|
|
3252
|
+
"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.",
|
|
3253
|
+
{
|
|
3254
|
+
colorScheme: {
|
|
3255
|
+
type: "string",
|
|
3256
|
+
description: "light | dark | no-preference | reset"
|
|
3257
|
+
},
|
|
3258
|
+
reducedMotion: {
|
|
3259
|
+
type: "string",
|
|
3260
|
+
description: "reduce | no-preference | reset"
|
|
3261
|
+
},
|
|
3262
|
+
width: {
|
|
3263
|
+
type: "number",
|
|
3264
|
+
description: "Viewport width in CSS px (320\u20133840)."
|
|
3265
|
+
},
|
|
3266
|
+
height: {
|
|
3267
|
+
type: "number",
|
|
3268
|
+
description: "Viewport height in CSS px (240\u20132160)."
|
|
3269
|
+
}
|
|
3270
|
+
},
|
|
3271
|
+
async (args, exec) => {
|
|
3272
|
+
guardEnabled();
|
|
3273
|
+
requireDebugTools("browser_emulate");
|
|
3274
|
+
const sessionId = sessionIdOf(exec);
|
|
3275
|
+
const colorScheme = pickEnum(args.colorScheme, ["light", "dark", "no-preference", "reset"], "colorScheme");
|
|
3276
|
+
const reducedMotion = pickEnum(args.reducedMotion, ["reduce", "no-preference", "reset"], "reducedMotion");
|
|
3277
|
+
const width = Number(args.width);
|
|
3278
|
+
const height = Number(args.height);
|
|
3279
|
+
const hasViewport = Number.isFinite(width) && Number.isFinite(height);
|
|
3280
|
+
if (colorScheme === void 0 && reducedMotion === void 0 && !hasViewport) {
|
|
3281
|
+
throw new Error("browser_emulate: pass colorScheme, reducedMotion, or width+height");
|
|
3282
|
+
}
|
|
3283
|
+
await ensureConnected();
|
|
3284
|
+
await ensureSessionTab(sessionId);
|
|
3285
|
+
const result = await runBridge(() => driverOf(options).emulate({
|
|
3286
|
+
...colorScheme === void 0 ? {} : { colorScheme },
|
|
3287
|
+
...reducedMotion === void 0 ? {} : { reducedMotion },
|
|
3288
|
+
...hasViewport ? { viewport: { width, height } } : {}
|
|
3289
|
+
}));
|
|
3290
|
+
await rememberTab(sessionId, result.tabId);
|
|
3291
|
+
return [
|
|
3292
|
+
`emulated: ${result.applied.join(", ")}`,
|
|
3293
|
+
`url: ${result.url}`,
|
|
3294
|
+
`title: ${result.title}`,
|
|
3295
|
+
result.tabId !== void 0 ? `tabId: ${result.tabId}` : null,
|
|
3296
|
+
"Action: browser_snapshot now echoes the emulation line, so you can confirm the mode the page is in."
|
|
3297
|
+
].filter((line) => line !== null).join("\n");
|
|
3298
|
+
}
|
|
3299
|
+
)));
|
|
2549
3300
|
disposers.push(ctx.tools.register(textTool(
|
|
2550
3301
|
"browser_list_tabs",
|
|
2551
3302
|
"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 +3377,33 @@ title: ${result.title}`;
|
|
|
2626
3377
|
}
|
|
2627
3378
|
|
|
2628
3379
|
// src/host/browser-agent/install.ts
|
|
3380
|
+
var IDLE_TICK_MS = 6e4;
|
|
2629
3381
|
function installBrowserAgent(ctx, options) {
|
|
2630
3382
|
const approval = new BrowserApprovalGate();
|
|
2631
3383
|
const human = new BrowserHumanGate();
|
|
2632
3384
|
const sessions = new BrowserSessionState();
|
|
3385
|
+
const tabScope = new TabScopeStore();
|
|
3386
|
+
let availabilityCache = null;
|
|
3387
|
+
const browserAvailability = () => {
|
|
3388
|
+
if (availabilityCache !== null) return availabilityCache;
|
|
3389
|
+
availabilityCache = {
|
|
3390
|
+
chrome: resolveBrowserExecutable("chrome") !== null,
|
|
3391
|
+
edge: resolveBrowserExecutable("edge") !== null,
|
|
3392
|
+
safari: resolveBrowserExecutable("safari") !== null
|
|
3393
|
+
};
|
|
3394
|
+
return availabilityCache;
|
|
3395
|
+
};
|
|
3396
|
+
const diagnoseNow = () => {
|
|
3397
|
+
const status = activeDriver?.status();
|
|
3398
|
+
return diagnose({
|
|
3399
|
+
enabled: options.enabled(),
|
|
3400
|
+
ready: status?.ready === true,
|
|
3401
|
+
preference: options.browserPreference(),
|
|
3402
|
+
platform: process.platform,
|
|
3403
|
+
lastError: status?.lastError ?? null,
|
|
3404
|
+
availability: browserAvailability()
|
|
3405
|
+
});
|
|
3406
|
+
};
|
|
2633
3407
|
let unregisterTools = null;
|
|
2634
3408
|
let unregisterPrompt = null;
|
|
2635
3409
|
let active = false;
|
|
@@ -2667,6 +3441,7 @@ function installBrowserAgent(ctx, options) {
|
|
|
2667
3441
|
const previousPreference = mountedPreference;
|
|
2668
3442
|
activeDriver = null;
|
|
2669
3443
|
mountedPreference = null;
|
|
3444
|
+
tabScope.clear();
|
|
2670
3445
|
const pw = playwrightDriver;
|
|
2671
3446
|
playwrightDriver = null;
|
|
2672
3447
|
if (pw !== null) {
|
|
@@ -2724,6 +3499,9 @@ function installBrowserAgent(ctx, options) {
|
|
|
2724
3499
|
approval,
|
|
2725
3500
|
human,
|
|
2726
3501
|
sessions,
|
|
3502
|
+
tabScope,
|
|
3503
|
+
debugTools: () => options.debugTools?.() === true,
|
|
3504
|
+
diagnosis: diagnoseNow,
|
|
2727
3505
|
// Gate on settings only — `active` flips false during driver align and
|
|
2728
3506
|
// must not make browser_* look "disabled" mid-turn.
|
|
2729
3507
|
enabled: () => options.enabled(),
|
|
@@ -2738,6 +3516,7 @@ function installBrowserAgent(ctx, options) {
|
|
|
2738
3516
|
try {
|
|
2739
3517
|
if (preferenceMatchesRunning(preference)) {
|
|
2740
3518
|
await requireDriver().ensureReady(startUrl);
|
|
3519
|
+
primeCapture();
|
|
2741
3520
|
active = true;
|
|
2742
3521
|
return { ok: true };
|
|
2743
3522
|
}
|
|
@@ -2758,6 +3537,7 @@ function installBrowserAgent(ctx, options) {
|
|
|
2758
3537
|
ensureToolsRegistered();
|
|
2759
3538
|
active = true;
|
|
2760
3539
|
await activeDriver.ensureReady(startUrl);
|
|
3540
|
+
primeCapture();
|
|
2761
3541
|
mountedPreference = preference;
|
|
2762
3542
|
return { ok: true };
|
|
2763
3543
|
} catch (error) {
|
|
@@ -2768,12 +3548,21 @@ function installBrowserAgent(ctx, options) {
|
|
|
2768
3548
|
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
2769
3549
|
}
|
|
2770
3550
|
};
|
|
3551
|
+
const primeCapture = () => {
|
|
3552
|
+
if (options.debugTools?.() !== true) return;
|
|
3553
|
+
try {
|
|
3554
|
+
requireDriver().startCapture();
|
|
3555
|
+
} catch {
|
|
3556
|
+
}
|
|
3557
|
+
};
|
|
2771
3558
|
const mount = () => {
|
|
2772
3559
|
const preference = options.browserPreference();
|
|
2773
3560
|
createDriver(preference);
|
|
2774
3561
|
ensureToolsRegistered();
|
|
2775
3562
|
};
|
|
2776
3563
|
const refresh = () => {
|
|
3564
|
+
availabilityCache = null;
|
|
3565
|
+
if (options.debugTools?.() !== true) activeDriver?.stopCapture?.();
|
|
2777
3566
|
const want = options.enabled();
|
|
2778
3567
|
if (!want) {
|
|
2779
3568
|
if (!active && playwrightDriver === null && unregisterTools === null && !switchPending) {
|
|
@@ -2797,6 +3586,37 @@ function installBrowserAgent(ctx, options) {
|
|
|
2797
3586
|
active = true;
|
|
2798
3587
|
};
|
|
2799
3588
|
refresh();
|
|
3589
|
+
const sweepIdleTabs = async () => {
|
|
3590
|
+
if (!options.enabled()) return;
|
|
3591
|
+
const idleMs = browserAgentIdleCloseMs(options.idleClose?.() ?? "10m");
|
|
3592
|
+
if (idleMs === null) return;
|
|
3593
|
+
const driver = activeDriver;
|
|
3594
|
+
if (driver === null || driver.status().ready !== true) return;
|
|
3595
|
+
try {
|
|
3596
|
+
const closed = await driver.sweepIdleTabs({
|
|
3597
|
+
idleMs,
|
|
3598
|
+
keep: sessions.boundTabIds()
|
|
3599
|
+
});
|
|
3600
|
+
for (const tabId of closed) {
|
|
3601
|
+
const sessionId = sessions.unbindTab(tabId);
|
|
3602
|
+
tabScope.setReadOnly(tabId, false);
|
|
3603
|
+
sessions.record({
|
|
3604
|
+
sessionId: sessionId ?? "host",
|
|
3605
|
+
tool: "browser_idle_close",
|
|
3606
|
+
summary: `Closed idle tab ${tabId}`,
|
|
3607
|
+
outcome: "ok"
|
|
3608
|
+
});
|
|
3609
|
+
}
|
|
3610
|
+
} catch (error) {
|
|
3611
|
+
ctx.logger.warn(
|
|
3612
|
+
`agent-enhancer: idle tab sweep failed: ${error instanceof Error ? error.message : String(error)}`
|
|
3613
|
+
);
|
|
3614
|
+
}
|
|
3615
|
+
};
|
|
3616
|
+
const idleTimer = setInterval(() => {
|
|
3617
|
+
void sweepIdleTabs();
|
|
3618
|
+
}, IDLE_TICK_MS);
|
|
3619
|
+
idleTimer.unref?.();
|
|
2800
3620
|
return {
|
|
2801
3621
|
approval,
|
|
2802
3622
|
human,
|
|
@@ -2804,6 +3624,9 @@ function installBrowserAgent(ctx, options) {
|
|
|
2804
3624
|
driverStatus() {
|
|
2805
3625
|
return activeDriver?.status() ?? null;
|
|
2806
3626
|
},
|
|
3627
|
+
diagnose() {
|
|
3628
|
+
return diagnoseNow();
|
|
3629
|
+
},
|
|
2807
3630
|
activeProfileDir() {
|
|
2808
3631
|
if (mountedPreference !== null) {
|
|
2809
3632
|
return browserAgentProfileDirFor(options.profileRoot, mountedPreference);
|
|
@@ -2823,10 +3646,13 @@ function installBrowserAgent(ctx, options) {
|
|
|
2823
3646
|
}
|
|
2824
3647
|
try {
|
|
2825
3648
|
const body = await activeDriver.listTabs();
|
|
3649
|
+
tabScope.retain(body.tabs.map((tab) => tab.tabId));
|
|
3650
|
+
sessions.retainTabs(body.tabs.map((tab) => tab.tabId));
|
|
2826
3651
|
return {
|
|
2827
3652
|
tabs: body.tabs.map((tab) => ({
|
|
2828
3653
|
...tab,
|
|
2829
|
-
bound: sessions.sessionOf(tab.tabId) !== void 0
|
|
3654
|
+
bound: sessions.sessionOf(tab.tabId) !== void 0,
|
|
3655
|
+
readOnly: tabScope.isReadOnly(tab.tabId)
|
|
2830
3656
|
})),
|
|
2831
3657
|
boundTabId: body.boundTabId
|
|
2832
3658
|
};
|
|
@@ -2834,6 +3660,17 @@ function installBrowserAgent(ctx, options) {
|
|
|
2834
3660
|
return { tabs: [], boundTabId: null };
|
|
2835
3661
|
}
|
|
2836
3662
|
},
|
|
3663
|
+
setTabReadOnly(input) {
|
|
3664
|
+
if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
|
|
3665
|
+
tabScope.setReadOnly(input.tabId, input.readOnly);
|
|
3666
|
+
sessions.record({
|
|
3667
|
+
sessionId: "sidebar",
|
|
3668
|
+
tool: "browser_tab_read_only",
|
|
3669
|
+
summary: `${input.readOnly ? "Read-only" : "Writable"} tab ${input.tabId}`,
|
|
3670
|
+
outcome: "ok"
|
|
3671
|
+
});
|
|
3672
|
+
return { ok: true };
|
|
3673
|
+
},
|
|
2837
3674
|
async selectTab(input) {
|
|
2838
3675
|
if (!options.enabled()) return { ok: false, error: "Browser agent disabled" };
|
|
2839
3676
|
await switchGate.catch(() => void 0);
|
|
@@ -2977,6 +3814,7 @@ function installBrowserAgent(ctx, options) {
|
|
|
2977
3814
|
},
|
|
2978
3815
|
async dispose() {
|
|
2979
3816
|
active = false;
|
|
3817
|
+
clearInterval(idleTimer);
|
|
2980
3818
|
approval.clearAll();
|
|
2981
3819
|
human.clearAll();
|
|
2982
3820
|
await switchGate.catch(() => void 0);
|
|
@@ -12819,7 +13657,7 @@ function installAutoSessionRoute(ctx, options) {
|
|
|
12819
13657
|
const settings = options.settings();
|
|
12820
13658
|
const map = autoRouteMapOf(settings);
|
|
12821
13659
|
const note = (agent === void 0 ? void 0 : notes.get(agent)) ?? loggedTurn(asAgent(agent));
|
|
12822
|
-
const
|
|
13660
|
+
const classify2 = settings.autoClassifierEnabled ? createClassifier({ prepareCall: innerPrepare }, map.classifier) : void 0;
|
|
12823
13661
|
let mapped;
|
|
12824
13662
|
try {
|
|
12825
13663
|
mapped = await resolveAutoRoute({
|
|
@@ -12828,7 +13666,7 @@ function installAutoSessionRoute(ctx, options) {
|
|
|
12828
13666
|
toolHeavy: note?.toolHeavy ?? false,
|
|
12829
13667
|
map,
|
|
12830
13668
|
classifierEnabled: settings.autoClassifierEnabled,
|
|
12831
|
-
classify,
|
|
13669
|
+
classify: classify2,
|
|
12832
13670
|
isAvailable: (provider, model) => provider !== "" && model !== "" && !isAutoModel({ provider, model }),
|
|
12833
13671
|
signal,
|
|
12834
13672
|
fallback: fallbackRoute(ctx, asAgent(agent))
|
|
@@ -13220,7 +14058,7 @@ var AuxiliaryModels = class {
|
|
|
13220
14058
|
async resolveAutoRouteFor(session, override, text3, feature, toolHeavy) {
|
|
13221
14059
|
const settings = this.enhancerSettings();
|
|
13222
14060
|
const map = autoRouteMapOf(settings);
|
|
13223
|
-
const
|
|
14061
|
+
const classify2 = settings.autoClassifierEnabled ? createClassifier(this.ctx.llm, map.classifier) : void 0;
|
|
13224
14062
|
let mapped;
|
|
13225
14063
|
try {
|
|
13226
14064
|
mapped = await resolveAutoRoute({
|
|
@@ -13229,7 +14067,7 @@ var AuxiliaryModels = class {
|
|
|
13229
14067
|
toolHeavy,
|
|
13230
14068
|
map,
|
|
13231
14069
|
classifierEnabled: settings.autoClassifierEnabled,
|
|
13232
|
-
classify,
|
|
14070
|
+
classify: classify2,
|
|
13233
14071
|
isAvailable: (provider, model) => this.modelExists(provider, model),
|
|
13234
14072
|
fallback: this.fallbackFromSession(session, override)
|
|
13235
14073
|
});
|
|
@@ -14940,7 +15778,9 @@ var browserAgentTabConflictSchema = z4.strictObject({
|
|
|
14940
15778
|
});
|
|
14941
15779
|
var browserAgentNeedsHumanSchema = z4.strictObject({
|
|
14942
15780
|
sessionId: z4.string().min(1),
|
|
14943
|
-
detail: z4.string().min(1)
|
|
15781
|
+
detail: z4.string().min(1),
|
|
15782
|
+
/** `human` = login/captcha on the page; `ask` = any other browser-side request. */
|
|
15783
|
+
kind: z4.enum(["human", "ask"])
|
|
14944
15784
|
});
|
|
14945
15785
|
var browserAgentAuditEntrySchema = z4.strictObject({
|
|
14946
15786
|
at: z4.number(),
|
|
@@ -14957,7 +15797,21 @@ var browserAgentTabEntrySchema = z4.strictObject({
|
|
|
14957
15797
|
/** True when this is the driver's currently focused page. */
|
|
14958
15798
|
active: z4.boolean(),
|
|
14959
15799
|
/** True when any chat session is bound to this tab. */
|
|
14960
|
-
bound: z4.boolean()
|
|
15800
|
+
bound: z4.boolean(),
|
|
15801
|
+
/** User marked the tab read-only: mutating tools fail fast there. */
|
|
15802
|
+
readOnly: z4.boolean()
|
|
15803
|
+
});
|
|
15804
|
+
var browserAgentAvailabilitySchema = z4.strictObject({
|
|
15805
|
+
chrome: z4.boolean(),
|
|
15806
|
+
edge: z4.boolean(),
|
|
15807
|
+
safari: z4.boolean()
|
|
15808
|
+
});
|
|
15809
|
+
var browserAgentDiagnosisSchema = z4.strictObject({
|
|
15810
|
+
code: z4.enum(["disabled", "idle", "ok", "webkit_missing", "browser_missing", "profile_locked", "launch_failed"]),
|
|
15811
|
+
/** English, model-facing: what to do next. */
|
|
15812
|
+
nextStep: z4.string(),
|
|
15813
|
+
detail: z4.string().optional(),
|
|
15814
|
+
browsers: browserAgentAvailabilitySchema
|
|
14961
15815
|
});
|
|
14962
15816
|
var browserAgentSnapshotSchema = z4.strictObject({
|
|
14963
15817
|
enabled: z4.boolean(),
|
|
@@ -14976,6 +15830,8 @@ var browserAgentSnapshotSchema = z4.strictObject({
|
|
|
14976
15830
|
lastError: z4.string().nullable()
|
|
14977
15831
|
}),
|
|
14978
15832
|
pending: browserAgentPendingSchema.nullable(),
|
|
15833
|
+
/** Why the browser is (not) usable and the concrete next step. */
|
|
15834
|
+
diagnosis: browserAgentDiagnosisSchema,
|
|
14979
15835
|
tabConflict: browserAgentTabConflictSchema.nullable(),
|
|
14980
15836
|
needsHuman: browserAgentNeedsHumanSchema.nullable(),
|
|
14981
15837
|
boundTabId: z4.number().int().nullable(),
|
|
@@ -15128,6 +15984,23 @@ var browserAgentSelectTabResultCodec = codec(
|
|
|
15128
15984
|
"dsh-agent-enhancer#BrowserAgentSelectTabResult",
|
|
15129
15985
|
browserAgentSelectTabResultSchema
|
|
15130
15986
|
);
|
|
15987
|
+
var browserAgentSetTabReadOnlyRequestSchema = z4.strictObject({
|
|
15988
|
+
tabId: z4.number().int().positive(),
|
|
15989
|
+
readOnly: z4.boolean()
|
|
15990
|
+
});
|
|
15991
|
+
var browserAgentSetTabReadOnlyRequestCodec = codec(
|
|
15992
|
+
"dsh-agent-enhancer#BrowserAgentSetTabReadOnlyRequest",
|
|
15993
|
+
browserAgentSetTabReadOnlyRequestSchema
|
|
15994
|
+
);
|
|
15995
|
+
var browserAgentSetTabReadOnlyResultSchema = z4.strictObject({
|
|
15996
|
+
ok: z4.boolean(),
|
|
15997
|
+
error: z4.string().optional(),
|
|
15998
|
+
snapshot: browserAgentSnapshotSchema
|
|
15999
|
+
});
|
|
16000
|
+
var browserAgentSetTabReadOnlyResultCodec = codec(
|
|
16001
|
+
"dsh-agent-enhancer#BrowserAgentSetTabReadOnlyResult",
|
|
16002
|
+
browserAgentSetTabReadOnlyResultSchema
|
|
16003
|
+
);
|
|
15131
16004
|
var instructionScopeSchema = z4.enum(["global", "shared", "project"]);
|
|
15132
16005
|
var instructionFileEntrySchema = z4.strictObject({
|
|
15133
16006
|
id: z4.string().min(1),
|
|
@@ -15866,6 +16739,18 @@ var remoteInfo = createTypertRemoteInfo({
|
|
|
15866
16739
|
}],
|
|
15867
16740
|
result: browserAgentSelectTabResultCodec
|
|
15868
16741
|
},
|
|
16742
|
+
"agentEnhancer/browserAgentSetTabReadOnly": {
|
|
16743
|
+
service: "agentEnhancer",
|
|
16744
|
+
implementation: "browserAgentSetTabReadOnly",
|
|
16745
|
+
invocation: { kind: "direct" },
|
|
16746
|
+
parameters: [{
|
|
16747
|
+
name: "request",
|
|
16748
|
+
source: "json",
|
|
16749
|
+
codec: browserAgentSetTabReadOnlyRequestCodec,
|
|
16750
|
+
strictCodec: browserAgentSetTabReadOnlyRequestCodec
|
|
16751
|
+
}],
|
|
16752
|
+
result: browserAgentSetTabReadOnlyResultCodec
|
|
16753
|
+
},
|
|
15869
16754
|
"agentEnhancer/listInstructionsSkills": {
|
|
15870
16755
|
service: "agentEnhancer",
|
|
15871
16756
|
implementation: "listInstructionsSkills",
|
|
@@ -16541,6 +17426,10 @@ var Config = z5.object({
|
|
|
16541
17426
|
/** High-risk; default off. */
|
|
16542
17427
|
browserAgentEnabled: z5.boolean().default(false).volatile(),
|
|
16543
17428
|
browserAgentBrowser: z5.string().default("auto").volatile(),
|
|
17429
|
+
/** Debug tools (network / console / emulate); default off, gated per tool. */
|
|
17430
|
+
browserAgentDebugTools: z5.boolean().default(false).volatile(),
|
|
17431
|
+
/** Close idle agent tabs after ~10 min; coerced via resolveBrowserAgentIdleClose. */
|
|
17432
|
+
browserAgentIdleClose: z5.union([z5.boolean(), z5.string()]).default("10m").volatile(),
|
|
16544
17433
|
/** Default off; embeds official web chat + import to work. */
|
|
16545
17434
|
webChatBridgeEnabled: z5.boolean().default(true).volatile(),
|
|
16546
17435
|
instructionsSkillsEnabled: z5.boolean().default(true).volatile(),
|
|
@@ -16632,10 +17521,12 @@ var AgentEnhancerService = class extends TypertRemoteService {
|
|
|
16632
17521
|
const waiting = this.browserAgent?.human.current() ?? null;
|
|
16633
17522
|
const needsHuman = waiting !== null ? {
|
|
16634
17523
|
sessionId: waiting.sessionId,
|
|
16635
|
-
detail: waiting.prompt.trim() !== "" ? waiting.prompt : waiting.detail
|
|
17524
|
+
detail: waiting.prompt.trim() !== "" ? waiting.prompt : waiting.detail,
|
|
17525
|
+
kind: waiting.kind
|
|
16636
17526
|
} : this.browserAgent?.sessions.anyNeedsHuman() ?? null;
|
|
16637
17527
|
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
17528
|
const connected = driverStatus?.ready === true;
|
|
17529
|
+
const diag = this.browserAgent?.diagnose();
|
|
16639
17530
|
const listed = connected ? await this.browserAgent?.listTabs() : void 0;
|
|
16640
17531
|
const tabs = listed?.tabs ?? [];
|
|
16641
17532
|
const boundTabId = overlayBound ?? listed?.boundTabId ?? null;
|
|
@@ -16662,6 +17553,11 @@ var AgentEnhancerService = class extends TypertRemoteService {
|
|
|
16662
17553
|
...pending.url === void 0 ? {} : { url: pending.url },
|
|
16663
17554
|
...pending.origin === void 0 ? {} : { origin: pending.origin }
|
|
16664
17555
|
},
|
|
17556
|
+
diagnosis: diag ?? {
|
|
17557
|
+
code: settings.enabled ? "idle" : "disabled",
|
|
17558
|
+
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.",
|
|
17559
|
+
browsers: { chrome: false, edge: false, safari: false }
|
|
17560
|
+
},
|
|
16665
17561
|
tabConflict: conflict,
|
|
16666
17562
|
needsHuman,
|
|
16667
17563
|
boundTabId,
|
|
@@ -17364,6 +18260,18 @@ var AgentEnhancerService = class extends TypertRemoteService {
|
|
|
17364
18260
|
snapshot: await this.browserSnapshotNow()
|
|
17365
18261
|
};
|
|
17366
18262
|
}
|
|
18263
|
+
async browserAgentSetTabReadOnly(request) {
|
|
18264
|
+
this.assertOwner();
|
|
18265
|
+
const result = this.browserAgent?.setTabReadOnly({
|
|
18266
|
+
tabId: request.tabId,
|
|
18267
|
+
readOnly: request.readOnly
|
|
18268
|
+
});
|
|
18269
|
+
return {
|
|
18270
|
+
ok: result?.ok === true,
|
|
18271
|
+
...result?.error === void 0 ? {} : { error: result.error },
|
|
18272
|
+
snapshot: await this.browserSnapshotNow()
|
|
18273
|
+
};
|
|
18274
|
+
}
|
|
17367
18275
|
};
|
|
17368
18276
|
function resolveCheckpointRoot(dshHome2) {
|
|
17369
18277
|
const base = join30(dshHome2, "profiles", "desktop", "plugin-data");
|
|
@@ -17447,6 +18355,8 @@ function readSettings(config) {
|
|
|
17447
18355
|
runAlertsLevel: resolveRunAlertsLevel(config.runAlertsLevel.get()),
|
|
17448
18356
|
browserAgentEnabled: config.browserAgentEnabled.get(),
|
|
17449
18357
|
browserAgentBrowser: hostBrowserPreference(config.browserAgentBrowser.get()),
|
|
18358
|
+
browserAgentDebugTools: config.browserAgentDebugTools.get(),
|
|
18359
|
+
browserAgentIdleClose: resolveBrowserAgentIdleClose(config.browserAgentIdleClose.get()),
|
|
17450
18360
|
webChatBridgeEnabled: config.webChatBridgeEnabled.get(),
|
|
17451
18361
|
instructionsSkillsEnabled: config.instructionsSkillsEnabled.get(),
|
|
17452
18362
|
mcpConnectorsEnabled: config.mcpConnectorsEnabled.get(),
|
|
@@ -17533,6 +18443,8 @@ function apply(ctx, config) {
|
|
|
17533
18443
|
const browserAgent = installBrowserAgent(ctx, {
|
|
17534
18444
|
enabled: () => browserAgentLive.enabled,
|
|
17535
18445
|
browserPreference: () => browserAgentLive.browser,
|
|
18446
|
+
debugTools: () => settings().browserAgentDebugTools,
|
|
18447
|
+
idleClose: () => settings().browserAgentIdleClose,
|
|
17536
18448
|
profileRoot: pluginDataPackageRoot,
|
|
17537
18449
|
softPause: softPauseGate,
|
|
17538
18450
|
softPauseEnabled: () => settings().softPauseEnabled,
|