@wordbricks/playwright-mcp 0.1.25 → 0.1.26

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 (82) hide show
  1. package/lib/browserContextFactory.js +399 -0
  2. package/lib/browserServerBackend.js +86 -0
  3. package/lib/config.js +300 -0
  4. package/lib/context.js +311 -0
  5. package/lib/extension/cdpRelay.js +352 -0
  6. package/lib/extension/extensionContextFactory.js +56 -0
  7. package/lib/frameworkPatterns.js +35 -0
  8. package/lib/hooks/antiBotDetectionHook.js +178 -0
  9. package/lib/hooks/core.js +145 -0
  10. package/lib/hooks/eventConsumer.js +52 -0
  11. package/lib/hooks/events.js +42 -0
  12. package/lib/hooks/formatToolCallEvent.js +12 -0
  13. package/lib/hooks/frameworkStateHook.js +182 -0
  14. package/lib/hooks/grouping.js +72 -0
  15. package/lib/hooks/jsonLdDetectionHook.js +182 -0
  16. package/lib/hooks/networkFilters.js +82 -0
  17. package/lib/hooks/networkSetup.js +61 -0
  18. package/lib/hooks/networkTrackingHook.js +67 -0
  19. package/lib/hooks/pageHeightHook.js +75 -0
  20. package/lib/hooks/registry.js +41 -0
  21. package/lib/hooks/requireTabHook.js +26 -0
  22. package/lib/hooks/schema.js +89 -0
  23. package/lib/hooks/waitHook.js +33 -0
  24. package/lib/index.js +41 -0
  25. package/lib/mcp/inProcessTransport.js +71 -0
  26. package/lib/mcp/proxyBackend.js +130 -0
  27. package/lib/mcp/server.js +91 -0
  28. package/lib/mcp/tool.js +44 -0
  29. package/lib/mcp/transport.js +188 -0
  30. package/lib/playwrightTransformer.js +520 -0
  31. package/lib/program.js +112 -0
  32. package/lib/response.js +192 -0
  33. package/lib/sessionLog.js +123 -0
  34. package/lib/tab.js +251 -0
  35. package/lib/tools/common.js +55 -0
  36. package/lib/tools/console.js +33 -0
  37. package/lib/tools/dialogs.js +50 -0
  38. package/lib/tools/evaluate.js +62 -0
  39. package/lib/tools/extractFrameworkState.js +225 -0
  40. package/lib/tools/files.js +48 -0
  41. package/lib/tools/form.js +66 -0
  42. package/lib/tools/getSnapshot.js +36 -0
  43. package/lib/tools/getVisibleHtml.js +68 -0
  44. package/lib/tools/install.js +51 -0
  45. package/lib/tools/keyboard.js +83 -0
  46. package/lib/tools/mouse.js +97 -0
  47. package/lib/tools/navigate.js +66 -0
  48. package/lib/tools/network.js +121 -0
  49. package/lib/tools/networkDetail.js +238 -0
  50. package/lib/tools/networkSearch/bodySearch.js +161 -0
  51. package/lib/tools/networkSearch/grouping.js +37 -0
  52. package/lib/tools/networkSearch/helpers.js +32 -0
  53. package/lib/tools/networkSearch/searchHtml.js +76 -0
  54. package/lib/tools/networkSearch/types.js +1 -0
  55. package/lib/tools/networkSearch/urlSearch.js +124 -0
  56. package/lib/tools/networkSearch.js +278 -0
  57. package/lib/tools/pdf.js +41 -0
  58. package/lib/tools/repl.js +414 -0
  59. package/lib/tools/screenshot.js +103 -0
  60. package/lib/tools/scroll.js +131 -0
  61. package/lib/tools/snapshot.js +161 -0
  62. package/lib/tools/tabs.js +62 -0
  63. package/lib/tools/tool.js +35 -0
  64. package/lib/tools/utils.js +78 -0
  65. package/lib/tools/wait.js +60 -0
  66. package/lib/tools.js +68 -0
  67. package/lib/utils/adBlockFilter.js +90 -0
  68. package/lib/utils/codegen.js +55 -0
  69. package/lib/utils/extensionPath.js +10 -0
  70. package/lib/utils/fileUtils.js +40 -0
  71. package/lib/utils/graphql.js +269 -0
  72. package/lib/utils/guid.js +22 -0
  73. package/lib/utils/httpServer.js +39 -0
  74. package/lib/utils/log.js +21 -0
  75. package/lib/utils/manualPromise.js +111 -0
  76. package/lib/utils/networkFormat.js +14 -0
  77. package/lib/utils/package.js +20 -0
  78. package/lib/utils/result.js +2 -0
  79. package/lib/utils/sanitizeHtml.js +130 -0
  80. package/lib/utils/truncate.js +103 -0
  81. package/lib/utils/withTimeout.js +7 -0
  82. package/package.json +11 -1
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { renderModalStates } from "./tab.js";
17
+ import { formatTruncationLine, truncateStringTo } from "./utils/truncate.js";
18
+ const MAX_RESULT_CHARS = 25000;
19
+ export class Response {
20
+ _result = [];
21
+ _events = [];
22
+ _code = [];
23
+ _images = [];
24
+ _context;
25
+ _includeSnapshot = false;
26
+ _includeTabs = false;
27
+ _includeCode = false;
28
+ _tabSnapshot;
29
+ toolName;
30
+ toolArgs;
31
+ _isError;
32
+ constructor(context, toolName, toolArgs) {
33
+ this._context = context;
34
+ this.toolName = toolName;
35
+ this.toolArgs = toolArgs;
36
+ }
37
+ addResult(result) {
38
+ this._result.push(result);
39
+ }
40
+ addEvent(event) {
41
+ this._events.push(event);
42
+ }
43
+ addError(error) {
44
+ this._result.push(error);
45
+ this._isError = true;
46
+ }
47
+ isError() {
48
+ return this._isError;
49
+ }
50
+ result() {
51
+ return this._result.join("\n");
52
+ }
53
+ addCode(code) {
54
+ this._code.push(code);
55
+ }
56
+ code() {
57
+ return this._code.join("\n");
58
+ }
59
+ addImage(image) {
60
+ this._images.push(image);
61
+ }
62
+ images() {
63
+ return this._images;
64
+ }
65
+ // NOTE Wordbricks Disabled: Page state logging not needed
66
+ setIncludeSnapshot(full) {
67
+ // this._includeSnapshot = full ?? 'incremental';
68
+ }
69
+ setIncludeTabs() {
70
+ this._includeTabs = true;
71
+ }
72
+ async finish() {
73
+ // All the async snapshotting post-action is happening here.
74
+ // Everything below should race against modal states.
75
+ if (this._includeSnapshot && this._context.currentTab())
76
+ this._tabSnapshot = await this._context
77
+ .currentTabOrDie()
78
+ .captureSnapshot();
79
+ for (const tab of this._context.tabs())
80
+ await tab.updateTitle();
81
+ }
82
+ tabSnapshot() {
83
+ return this._tabSnapshot;
84
+ }
85
+ serialize() {
86
+ const response = [];
87
+ // Start with command result.
88
+ if (this._result.length) {
89
+ const resultText = this._result.join("\n");
90
+ const { text: clipped, truncated } = truncateStringTo(resultText, MAX_RESULT_CHARS);
91
+ response.push("### Result");
92
+ response.push(clipped);
93
+ if (truncated) {
94
+ const total = resultText.length;
95
+ const shown = clipped.length;
96
+ response.push(formatTruncationLine(shown, total, { units: "chars" }));
97
+ }
98
+ response.push("");
99
+ }
100
+ // Then show events
101
+ if (this._events.length) {
102
+ response.push("### Events");
103
+ response.push(this._events.join("\n"));
104
+ response.push("");
105
+ }
106
+ // Add code if it exists.
107
+ if (this._includeCode && this._code.length) {
108
+ response.push(`### Ran Playwright code
109
+ \`\`\`js
110
+ ${this._code.join("\n")}
111
+ \`\`\``);
112
+ response.push("");
113
+ }
114
+ // List browser tabs.
115
+ if (this._includeSnapshot || this._includeTabs)
116
+ response.push(...renderTabsMarkdown(this._context.tabs(), this._includeTabs));
117
+ // Add snapshot if provided.
118
+ if (this._tabSnapshot?.modalStates.length) {
119
+ response.push(...renderModalStates(this._context, this._tabSnapshot.modalStates));
120
+ response.push("");
121
+ }
122
+ else if (this._tabSnapshot) {
123
+ response.push(renderTabSnapshot(this._tabSnapshot));
124
+ response.push("");
125
+ }
126
+ // Main response part
127
+ const content = [
128
+ { type: "text", text: response.join("\n") },
129
+ ];
130
+ // Image attachments.
131
+ if (this._context.config.imageResponses !== "omit") {
132
+ for (const image of this._images)
133
+ content.push({
134
+ type: "image",
135
+ data: image.data.toString("base64"),
136
+ mimeType: image.contentType,
137
+ });
138
+ }
139
+ return { content, isError: this._isError };
140
+ }
141
+ }
142
+ function renderTabSnapshot(tabSnapshot) {
143
+ const lines = [];
144
+ if (tabSnapshot.consoleMessages.length) {
145
+ lines.push(`### New console messages`);
146
+ for (const message of tabSnapshot.consoleMessages)
147
+ lines.push(`- ${trim(message.toString(), 100)}`);
148
+ lines.push("");
149
+ }
150
+ if (tabSnapshot.downloads.length) {
151
+ lines.push(`### Downloads`);
152
+ for (const entry of tabSnapshot.downloads) {
153
+ if (entry.finished)
154
+ lines.push(`- Downloaded file ${entry.download.suggestedFilename()} to ${entry.outputFile}`);
155
+ else
156
+ lines.push(`- Downloading file ${entry.download.suggestedFilename()} ...`);
157
+ }
158
+ lines.push("");
159
+ }
160
+ lines.push(`### Page state`);
161
+ lines.push(`- Page URL: ${tabSnapshot.url}`);
162
+ lines.push(`- Page Title: ${tabSnapshot.title}`);
163
+ lines.push(`- Page Snapshot:`);
164
+ lines.push("```yaml");
165
+ lines.push(tabSnapshot.ariaSnapshot);
166
+ lines.push("```");
167
+ return lines.join("\n");
168
+ }
169
+ function renderTabsMarkdown(tabs, force = false) {
170
+ if (tabs.length === 1 && !force)
171
+ return [];
172
+ if (!tabs.length) {
173
+ return [
174
+ "### Open tabs",
175
+ 'No open tabs. Use the "browser_navigate" tool to navigate to a page first.',
176
+ "",
177
+ ];
178
+ }
179
+ const lines = ["### Open tabs"];
180
+ for (let i = 0; i < tabs.length; i++) {
181
+ const tab = tabs[i];
182
+ const current = tab.isCurrentTab() ? " (current)" : "";
183
+ lines.push(`- ${i}:${current} [${tab.lastTitle()}] (${tab.page.url()})`);
184
+ }
185
+ lines.push("");
186
+ return lines;
187
+ }
188
+ function trim(text, maxLength) {
189
+ if (text.length <= maxLength)
190
+ return text;
191
+ return text.slice(0, maxLength) + "...";
192
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import fs from "fs";
17
+ import path from "path";
18
+ import { outputFile } from "./config.js";
19
+ import { logUnhandledError } from "./utils/log.js";
20
+ export class SessionLog {
21
+ _folder;
22
+ _file;
23
+ _ordinal = 0;
24
+ _pendingEntries = [];
25
+ _sessionFileQueue = Promise.resolve();
26
+ _flushEntriesTimeout;
27
+ constructor(sessionFolder) {
28
+ this._folder = sessionFolder;
29
+ this._file = path.join(this._folder, "session.md");
30
+ }
31
+ static async create(config, rootPath) {
32
+ const sessionFolder = await outputFile(config, rootPath, `session-${Date.now()}`);
33
+ await fs.promises.mkdir(sessionFolder, { recursive: true });
34
+ // eslint-disable-next-line no-console
35
+ console.error(`Session: ${sessionFolder}`);
36
+ return new SessionLog(sessionFolder);
37
+ }
38
+ logResponse(response) {
39
+ const entry = {
40
+ timestamp: performance.now(),
41
+ toolCall: {
42
+ toolName: response.toolName,
43
+ toolArgs: response.toolArgs,
44
+ result: response.result(),
45
+ isError: response.isError(),
46
+ },
47
+ code: response.code(),
48
+ tabSnapshot: response.tabSnapshot(),
49
+ };
50
+ this._appendEntry(entry);
51
+ }
52
+ logUserAction(action, tab, code, isUpdate) {
53
+ code = code.trim();
54
+ if (isUpdate) {
55
+ const lastEntry = this._pendingEntries[this._pendingEntries.length - 1];
56
+ if (lastEntry.userAction?.name === action.name) {
57
+ lastEntry.userAction = action;
58
+ lastEntry.code = code;
59
+ return;
60
+ }
61
+ }
62
+ if (action.name === "navigate") {
63
+ // Already logged at this location.
64
+ const lastEntry = this._pendingEntries[this._pendingEntries.length - 1];
65
+ if (lastEntry?.tabSnapshot?.url === action.url)
66
+ return;
67
+ }
68
+ const entry = {
69
+ timestamp: performance.now(),
70
+ userAction: action,
71
+ code,
72
+ tabSnapshot: {
73
+ url: tab.page.url(),
74
+ title: "",
75
+ ariaSnapshot: action.ariaSnapshot || "",
76
+ modalStates: [],
77
+ consoleMessages: [],
78
+ downloads: [],
79
+ },
80
+ };
81
+ this._appendEntry(entry);
82
+ }
83
+ _appendEntry(entry) {
84
+ this._pendingEntries.push(entry);
85
+ if (this._flushEntriesTimeout)
86
+ clearTimeout(this._flushEntriesTimeout);
87
+ this._flushEntriesTimeout = setTimeout(() => this._flushEntries(), 1000);
88
+ }
89
+ async _flushEntries() {
90
+ clearTimeout(this._flushEntriesTimeout);
91
+ const entries = this._pendingEntries;
92
+ this._pendingEntries = [];
93
+ const lines = [""];
94
+ for (const entry of entries) {
95
+ const ordinal = (++this._ordinal).toString().padStart(3, "0");
96
+ if (entry.toolCall) {
97
+ lines.push(`### Tool call: ${entry.toolCall.toolName}`, `- Args`, "```json", JSON.stringify(entry.toolCall.toolArgs, null, 2), "```");
98
+ if (entry.toolCall.result) {
99
+ lines.push(entry.toolCall.isError ? `- Error` : `- Result`, "```", entry.toolCall.result, "```");
100
+ }
101
+ }
102
+ if (entry.userAction) {
103
+ const actionData = { ...entry.userAction };
104
+ delete actionData.ariaSnapshot;
105
+ delete actionData.selector;
106
+ delete actionData.signals;
107
+ lines.push(`### User action: ${entry.userAction.name}`, `- Args`, "```json", JSON.stringify(actionData, null, 2), "```");
108
+ }
109
+ if (entry.code) {
110
+ lines.push(`- Code`, "```js", entry.code, "```");
111
+ }
112
+ if (entry.tabSnapshot) {
113
+ const fileName = `${ordinal}.snapshot.yml`;
114
+ fs.promises
115
+ .writeFile(path.join(this._folder, fileName), entry.tabSnapshot.ariaSnapshot)
116
+ .catch(logUnhandledError);
117
+ lines.push(`- Snapshot: ${fileName}`);
118
+ }
119
+ lines.push("", "");
120
+ }
121
+ this._sessionFileQueue = this._sessionFileQueue.then(() => fs.promises.appendFile(this._file, lines.join("\n")));
122
+ }
123
+ }
package/lib/tab.js ADDED
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { EventEmitter } from "events";
17
+ import { callOnPageNoTrace, waitForCompletion } from "./tools/utils.js";
18
+ import { logUnhandledError } from "./utils/log.js";
19
+ import { ManualPromise } from "./utils/manualPromise.js";
20
+ export const TabEvents = {
21
+ modalState: "modalState",
22
+ };
23
+ export class Tab extends EventEmitter {
24
+ context;
25
+ page;
26
+ _lastTitle = "about:blank";
27
+ _consoleMessages = [];
28
+ _recentConsoleMessages = [];
29
+ _requests = new Map();
30
+ _onPageClose;
31
+ _modalStates = [];
32
+ _downloads = [];
33
+ constructor(context, page, onPageClose) {
34
+ super();
35
+ this.context = context;
36
+ this.page = page;
37
+ this._onPageClose = onPageClose;
38
+ page.on("console", (event) => this._handleConsoleMessage(messageToConsoleMessage(event)));
39
+ page.on("pageerror", (error) => this._handleConsoleMessage(pageErrorToConsoleMessage(error)));
40
+ page.on("request", (request) => this._requests.set(request, null));
41
+ page.on("response", (response) => this._requests.set(response.request(), response));
42
+ page.on("close", () => this._onClose());
43
+ page.on("filechooser", (chooser) => {
44
+ this.setModalState({
45
+ type: "fileChooser",
46
+ description: "File chooser",
47
+ fileChooser: chooser,
48
+ });
49
+ });
50
+ page.on("dialog", (dialog) => this._dialogShown(dialog));
51
+ // page.on('download', download => {
52
+ // void this._downloadStarted(download);
53
+ // });
54
+ page.setDefaultNavigationTimeout(60000);
55
+ page.setDefaultTimeout(5000);
56
+ page[tabSymbol] = this;
57
+ }
58
+ static forPage(page) {
59
+ return page[tabSymbol];
60
+ }
61
+ modalStates() {
62
+ return this._modalStates;
63
+ }
64
+ setModalState(modalState) {
65
+ this._modalStates.push(modalState);
66
+ this.emit(TabEvents.modalState, modalState);
67
+ }
68
+ clearModalState(modalState) {
69
+ this._modalStates = this._modalStates.filter((state) => state !== modalState);
70
+ }
71
+ modalStatesMarkdown() {
72
+ return renderModalStates(this.context, this.modalStates());
73
+ }
74
+ _dialogShown(dialog) {
75
+ this.setModalState({
76
+ type: "dialog",
77
+ description: `"${dialog.type()}" dialog with message "${dialog.message()}"`,
78
+ dialog,
79
+ });
80
+ }
81
+ async _downloadStarted(download) {
82
+ const entry = {
83
+ download,
84
+ finished: false,
85
+ outputFile: await this.context.outputFile(download.suggestedFilename()),
86
+ };
87
+ this._downloads.push(entry);
88
+ await download.saveAs(entry.outputFile);
89
+ entry.finished = true;
90
+ }
91
+ _clearCollectedArtifacts() {
92
+ this._consoleMessages.length = 0;
93
+ this._recentConsoleMessages.length = 0;
94
+ this._requests.clear();
95
+ }
96
+ _handleConsoleMessage(message) {
97
+ this._consoleMessages.push(message);
98
+ this._recentConsoleMessages.push(message);
99
+ }
100
+ _onClose() {
101
+ this._clearCollectedArtifacts();
102
+ this._onPageClose(this);
103
+ }
104
+ async updateTitle() {
105
+ await this._raceAgainstModalStates(async () => {
106
+ this._lastTitle = await callOnPageNoTrace(this.page, (page) => page.title());
107
+ });
108
+ }
109
+ lastTitle() {
110
+ return this._lastTitle;
111
+ }
112
+ isCurrentTab() {
113
+ return this === this.context.currentTab();
114
+ }
115
+ async waitForLoadState(state, options) {
116
+ await callOnPageNoTrace(this.page, (page) => page.waitForLoadState(state, options).catch(logUnhandledError));
117
+ }
118
+ async navigate(url) {
119
+ this._clearCollectedArtifacts();
120
+ // const downloadEvent = callOnPageNoTrace(this.page, page => page.waitForEvent('download').catch(logUnhandledError));
121
+ const downloadEvent = Promise.resolve(undefined);
122
+ try {
123
+ await this.page.goto(url, { waitUntil: "domcontentloaded" });
124
+ }
125
+ catch (_e) {
126
+ const e = _e;
127
+ const mightBeDownload = e.message.includes("net::ERR_ABORTED") || // chromium
128
+ e.message.includes("Download is starting"); // firefox + webkit
129
+ if (!mightBeDownload)
130
+ throw e;
131
+ // on chromium, the download event is fired *after* page.goto rejects, so we wait a lil bit
132
+ const download = await Promise.race([
133
+ downloadEvent,
134
+ new Promise((resolve) => setTimeout(resolve, 3000)),
135
+ ]);
136
+ if (!download)
137
+ throw e;
138
+ // Make sure other "download" listeners are notified first.
139
+ await new Promise((resolve) => setTimeout(resolve, 500));
140
+ return;
141
+ }
142
+ // Cap load event to 5 seconds, the page is operational at this point.
143
+ await this.waitForLoadState("load", { timeout: 5000 });
144
+ }
145
+ consoleMessages() {
146
+ return this._consoleMessages;
147
+ }
148
+ requests() {
149
+ return this._requests;
150
+ }
151
+ async captureSnapshot() {
152
+ let tabSnapshot;
153
+ const modalStates = await this._raceAgainstModalStates(async () => {
154
+ const snapshot = await this.page._snapshotForAI();
155
+ tabSnapshot = {
156
+ url: this.page.url(),
157
+ title: await this.page.title(),
158
+ ariaSnapshot: snapshot,
159
+ modalStates: [],
160
+ consoleMessages: [],
161
+ downloads: this._downloads,
162
+ };
163
+ });
164
+ if (tabSnapshot) {
165
+ // Assign console message late so that we did not lose any to modal state.
166
+ tabSnapshot.consoleMessages = this._recentConsoleMessages;
167
+ this._recentConsoleMessages = [];
168
+ }
169
+ return (tabSnapshot ?? {
170
+ url: this.page.url(),
171
+ title: "",
172
+ ariaSnapshot: "",
173
+ modalStates,
174
+ consoleMessages: [],
175
+ downloads: [],
176
+ });
177
+ }
178
+ _javaScriptBlocked() {
179
+ return this._modalStates.some((state) => state.type === "dialog");
180
+ }
181
+ async _raceAgainstModalStates(action) {
182
+ if (this.modalStates().length)
183
+ return this.modalStates();
184
+ const promise = new ManualPromise();
185
+ const listener = (modalState) => promise.resolve([modalState]);
186
+ this.once(TabEvents.modalState, listener);
187
+ return await Promise.race([
188
+ action().then(() => {
189
+ this.off(TabEvents.modalState, listener);
190
+ return [];
191
+ }),
192
+ promise,
193
+ ]);
194
+ }
195
+ async waitForCompletion(callback) {
196
+ await this._raceAgainstModalStates(() => waitForCompletion(this, callback));
197
+ }
198
+ async refLocator(params) {
199
+ return (await this.refLocators([params]))[0];
200
+ }
201
+ async refLocators(params) {
202
+ // Ensure aria-ref mapping is present without validating refs against a fresh snapshot.
203
+ // This avoids invalidating refs obtained from browser_get_snapshot while still
204
+ // initializing the mapping when needed (e.g., after navigation).
205
+ await this.page._snapshotForAI();
206
+ return params.map((param) => this.page.locator(`aria-ref=${param.ref}`));
207
+ }
208
+ async waitForTimeout(time) {
209
+ if (this._javaScriptBlocked()) {
210
+ await new Promise((f) => setTimeout(f, time));
211
+ return;
212
+ }
213
+ await callOnPageNoTrace(this.page, (page) => {
214
+ return page.evaluate(() => new Promise((f) => setTimeout(f, 1000)));
215
+ });
216
+ }
217
+ }
218
+ function messageToConsoleMessage(message) {
219
+ return {
220
+ type: message.type(),
221
+ text: message.text(),
222
+ toString: () => `[${message.type().toUpperCase()}] ${message.text()} @ ${message.location().url}:${message.location().lineNumber}`,
223
+ };
224
+ }
225
+ function pageErrorToConsoleMessage(errorOrValue) {
226
+ if (errorOrValue instanceof Error) {
227
+ return {
228
+ type: undefined,
229
+ text: errorOrValue.message,
230
+ toString: () => errorOrValue.stack || errorOrValue.message,
231
+ };
232
+ }
233
+ return {
234
+ type: undefined,
235
+ text: String(errorOrValue),
236
+ toString: () => String(errorOrValue),
237
+ };
238
+ }
239
+ export function renderModalStates(context, modalStates) {
240
+ const result = ["### Modal state"];
241
+ if (modalStates.length === 0)
242
+ result.push("- There is no modal state present");
243
+ for (const state of modalStates) {
244
+ const tool = context.tools
245
+ .filter((tool) => "clearsModalState" in tool)
246
+ .find((tool) => tool.clearsModalState === state.type);
247
+ result.push(`- [${state.description}]: can be handled by the "${tool?.schema.name}" tool`);
248
+ }
249
+ return result;
250
+ }
251
+ const tabSymbol = Symbol("tabSymbol");
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { z } from "zod";
17
+ import { defineTabTool, defineTool } from "./tool.js";
18
+ const close = defineTool({
19
+ capability: "core",
20
+ schema: {
21
+ name: "browser_close",
22
+ title: "Close browser",
23
+ description: "Close the page",
24
+ inputSchema: z.object({}),
25
+ type: "readOnly",
26
+ },
27
+ handle: async (context, params, response) => {
28
+ await context.closeBrowserContext();
29
+ response.setIncludeTabs();
30
+ response.addCode(`await page.close()`);
31
+ },
32
+ });
33
+ const resize = defineTabTool({
34
+ capability: "core",
35
+ schema: {
36
+ name: "browser_resize",
37
+ title: "Resize browser window",
38
+ description: "Resize the browser window",
39
+ inputSchema: z.object({
40
+ width: z.number().describe("Width of the browser window"),
41
+ height: z.number().describe("Height of the browser window"),
42
+ }),
43
+ type: "readOnly",
44
+ },
45
+ handle: async (tab, params, response) => {
46
+ response.addCode(`await page.setViewportSize({ width: ${params.width}, height: ${params.height} });`);
47
+ await tab.waitForCompletion(async () => {
48
+ await tab.page.setViewportSize({
49
+ width: params.width,
50
+ height: params.height,
51
+ });
52
+ });
53
+ },
54
+ });
55
+ export default [close, resize];
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { z } from "zod";
17
+ import { defineTabTool } from "./tool.js";
18
+ const console = defineTabTool({
19
+ capability: "core",
20
+ schema: {
21
+ name: "browser_console_messages",
22
+ title: "Get console messages",
23
+ description: "Returns all console messages",
24
+ inputSchema: z.object({}),
25
+ type: "readOnly",
26
+ },
27
+ handle: async (tab, params, response) => {
28
+ tab
29
+ .consoleMessages()
30
+ .map((message) => response.addResult(message.toString()));
31
+ },
32
+ });
33
+ export default [console];