@ejazullah/browser-mcp 0.0.56
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/LICENSE +202 -0
- package/README.md +860 -0
- package/cli.js +19 -0
- package/index.d.ts +23 -0
- package/index.js +1061 -0
- package/lib/auth.js +82 -0
- package/lib/browserContextFactory.js +205 -0
- package/lib/browserServerBackend.js +125 -0
- package/lib/config.js +266 -0
- package/lib/context.js +232 -0
- package/lib/databaseLogger.js +264 -0
- package/lib/extension/cdpRelay.js +346 -0
- package/lib/extension/extensionContextFactory.js +56 -0
- package/lib/extension/main.js +26 -0
- package/lib/fileUtils.js +32 -0
- package/lib/httpServer.js +39 -0
- package/lib/index.js +39 -0
- package/lib/javascript.js +49 -0
- package/lib/log.js +21 -0
- package/lib/loop/loop.js +69 -0
- package/lib/loop/loopClaude.js +152 -0
- package/lib/loop/loopOpenAI.js +143 -0
- package/lib/loop/main.js +60 -0
- package/lib/loopTools/context.js +66 -0
- package/lib/loopTools/main.js +49 -0
- package/lib/loopTools/perform.js +32 -0
- package/lib/loopTools/snapshot.js +29 -0
- package/lib/loopTools/tool.js +18 -0
- package/lib/manualPromise.js +111 -0
- package/lib/mcp/inProcessTransport.js +72 -0
- package/lib/mcp/server.js +93 -0
- package/lib/mcp/transport.js +217 -0
- package/lib/mongoDBLogger.js +252 -0
- package/lib/package.js +20 -0
- package/lib/program.js +113 -0
- package/lib/response.js +172 -0
- package/lib/sessionLog.js +156 -0
- package/lib/tab.js +266 -0
- package/lib/tools/cdp.js +169 -0
- package/lib/tools/common.js +55 -0
- package/lib/tools/console.js +33 -0
- package/lib/tools/dialogs.js +47 -0
- package/lib/tools/evaluate.js +53 -0
- package/lib/tools/extraction.js +217 -0
- package/lib/tools/files.js +44 -0
- package/lib/tools/forms.js +180 -0
- package/lib/tools/getext.js +99 -0
- package/lib/tools/install.js +53 -0
- package/lib/tools/interactions.js +191 -0
- package/lib/tools/keyboard.js +86 -0
- package/lib/tools/mouse.js +99 -0
- package/lib/tools/navigate.js +70 -0
- package/lib/tools/network.js +41 -0
- package/lib/tools/pdf.js +40 -0
- package/lib/tools/screenshot.js +75 -0
- package/lib/tools/selectors.js +233 -0
- package/lib/tools/snapshot.js +169 -0
- package/lib/tools/states.js +147 -0
- package/lib/tools/tabs.js +87 -0
- package/lib/tools/tool.js +33 -0
- package/lib/tools/utils.js +74 -0
- package/lib/tools/wait.js +56 -0
- package/lib/tools.js +64 -0
- package/lib/utils.js +26 -0
- package/openapi.json +683 -0
- package/package.json +92 -0
package/lib/program.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
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 { program, Option } from 'commander';
|
|
17
|
+
// @ts-ignore
|
|
18
|
+
import { startTraceViewerServer } from 'playwright-core/lib/server';
|
|
19
|
+
import * as mcpTransport from './mcp/transport.js';
|
|
20
|
+
import { commaSeparatedList, resolveCLIConfig, semicolonSeparatedList } from './config.js';
|
|
21
|
+
import { buildAuthConfig } from './auth.js';
|
|
22
|
+
import { packageJSON } from './package.js';
|
|
23
|
+
import { createExtensionContextFactory, runWithExtension } from './extension/main.js';
|
|
24
|
+
import { BrowserServerBackend } from './browserServerBackend.js';
|
|
25
|
+
import { Context } from './context.js';
|
|
26
|
+
import { contextFactory } from './browserContextFactory.js';
|
|
27
|
+
import { runLoopTools } from './loopTools/main.js';
|
|
28
|
+
program
|
|
29
|
+
.version('Version ' + packageJSON.version)
|
|
30
|
+
.name(packageJSON.name)
|
|
31
|
+
.option('--allowed-origins <origins>', 'semicolon-separated list of origins to allow the browser to request. Default is to allow all.', semicolonSeparatedList)
|
|
32
|
+
.option('--blocked-origins <origins>', 'semicolon-separated list of origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed.', semicolonSeparatedList)
|
|
33
|
+
.option('--block-service-workers', 'block service workers')
|
|
34
|
+
.option('--browser <browser>', 'browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.')
|
|
35
|
+
.option('--caps <caps>', 'comma-separated list of additional capabilities to enable, possible values: vision, pdf.', commaSeparatedList)
|
|
36
|
+
.option('--cdp-endpoint <endpoint>', 'CDP endpoint to connect to.')
|
|
37
|
+
.option('--config <path>', 'path to the configuration file.')
|
|
38
|
+
.option('--device <device>', 'device to emulate, for example: "iPhone 15"')
|
|
39
|
+
.option('--executable-path <path>', 'path to the browser executable.')
|
|
40
|
+
.option('--headless', 'run browser in headless mode, headed by default')
|
|
41
|
+
.option('--host <host>', 'host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.')
|
|
42
|
+
.option('--ignore-https-errors', 'ignore https errors')
|
|
43
|
+
.option('--isolated', 'keep the browser profile in memory, do not save it to disk.')
|
|
44
|
+
.option('--image-responses <mode>', 'whether to send image responses to the client. Can be "allow" or "omit", Defaults to "allow".')
|
|
45
|
+
.option('--no-sandbox', 'disable the sandbox for all process types that are normally sandboxed.')
|
|
46
|
+
.option('--output-dir <path>', 'path to the directory for output files.')
|
|
47
|
+
.option('--port <port>', 'port to listen on for SSE transport.')
|
|
48
|
+
.option('--proxy-bypass <bypass>', 'comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"')
|
|
49
|
+
.option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"')
|
|
50
|
+
.option('--save-session', 'Whether to save the Playwright MCP session into the output directory.')
|
|
51
|
+
.option('--save-trace', 'Whether to save the Playwright Trace of the session into the output directory.')
|
|
52
|
+
.option('--storage-state <path>', 'path to the storage state file for isolated sessions.')
|
|
53
|
+
.option('--user-agent <ua string>', 'specify user agent string')
|
|
54
|
+
.option('--user-data-dir <path>', 'path to the user data directory. If not specified, a temporary directory will be created.')
|
|
55
|
+
.option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"')
|
|
56
|
+
.option('--mongodb-url <url>', 'MongoDB connection URL. Example: mongodb://localhost:27017')
|
|
57
|
+
.option('--mongodb-db <name>', 'MongoDB database name. Default: playwright_mcp')
|
|
58
|
+
.option('--mongodb-collection <name>', 'MongoDB collection name. Default: element_interactions')
|
|
59
|
+
.option('--auth', 'Enable OAuth2/JWT authentication for HTTP transport.')
|
|
60
|
+
.option('--jwt-secret <secret>', 'JWT signing secret. Auto-generated if not provided.')
|
|
61
|
+
.option('--token-expiry <duration>', 'JWT token expiry (e.g. 1h, 30m, 7d). Default: 1h')
|
|
62
|
+
.option('--api-keys <keys>', 'Comma-separated API keys for simple authentication.')
|
|
63
|
+
.option('--oauth-clients <json>', 'JSON string of OAuth2 client configurations.')
|
|
64
|
+
.addOption(new Option('--extension', 'Connect to a running browser instance (Edge/Chrome only). Requires the "Playwright MCP Bridge" browser extension to be installed.').hideHelp())
|
|
65
|
+
.addOption(new Option('--connect-tool', 'Allow to switch between different browser connection methods.').hideHelp())
|
|
66
|
+
.addOption(new Option('--loop-tools', 'Run loop tools').hideHelp())
|
|
67
|
+
.addOption(new Option('--vision', 'Legacy option, use --caps=vision instead').hideHelp())
|
|
68
|
+
.action(async (options) => {
|
|
69
|
+
setupExitWatchdog();
|
|
70
|
+
if (options.vision) {
|
|
71
|
+
// eslint-disable-next-line no-console
|
|
72
|
+
console.error('The --vision option is deprecated, use --caps=vision instead');
|
|
73
|
+
options.caps = 'vision';
|
|
74
|
+
}
|
|
75
|
+
const config = await resolveCLIConfig(options);
|
|
76
|
+
if (options.extension) {
|
|
77
|
+
await runWithExtension(config);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (options.loopTools) {
|
|
81
|
+
await runLoopTools(config);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
const browserContextFactory = contextFactory(config);
|
|
85
|
+
const factories = [browserContextFactory];
|
|
86
|
+
if (options.connectTool)
|
|
87
|
+
factories.push(createExtensionContextFactory(config));
|
|
88
|
+
const serverBackendFactory = () => new BrowserServerBackend(config, factories);
|
|
89
|
+
const authConfig = buildAuthConfig(options);
|
|
90
|
+
await mcpTransport.start(serverBackendFactory, config.server, authConfig);
|
|
91
|
+
if (config.saveTrace) {
|
|
92
|
+
const server = await startTraceViewerServer();
|
|
93
|
+
const urlPrefix = server.urlPrefix('human-readable');
|
|
94
|
+
const url = urlPrefix + '/trace/index.html?trace=' + config.browser.launchOptions.tracesDir + '/trace.json';
|
|
95
|
+
// eslint-disable-next-line no-console
|
|
96
|
+
console.error('\nTrace viewer listening on ' + url);
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
function setupExitWatchdog() {
|
|
100
|
+
let isExiting = false;
|
|
101
|
+
const handleExit = async () => {
|
|
102
|
+
if (isExiting)
|
|
103
|
+
return;
|
|
104
|
+
isExiting = true;
|
|
105
|
+
setTimeout(() => process.exit(0), 15000);
|
|
106
|
+
await Context.disposeAll();
|
|
107
|
+
process.exit(0);
|
|
108
|
+
};
|
|
109
|
+
process.stdin.on('close', handleExit);
|
|
110
|
+
process.on('SIGINT', handleExit);
|
|
111
|
+
process.on('SIGTERM', handleExit);
|
|
112
|
+
}
|
|
113
|
+
void program.parseAsync(process.argv);
|
package/lib/response.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
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
|
+
export class Response {
|
|
18
|
+
_result = [];
|
|
19
|
+
_code = [];
|
|
20
|
+
_images = [];
|
|
21
|
+
_context;
|
|
22
|
+
_includeSnapshot = false;
|
|
23
|
+
_includeTabs = false;
|
|
24
|
+
_tabSnapshot;
|
|
25
|
+
_elementInteraction;
|
|
26
|
+
toolName;
|
|
27
|
+
toolArgs;
|
|
28
|
+
_isError;
|
|
29
|
+
constructor(context, toolName, toolArgs) {
|
|
30
|
+
this._context = context;
|
|
31
|
+
this.toolName = toolName;
|
|
32
|
+
this.toolArgs = toolArgs;
|
|
33
|
+
}
|
|
34
|
+
addResult(result) {
|
|
35
|
+
this._result.push(result);
|
|
36
|
+
}
|
|
37
|
+
addError(error) {
|
|
38
|
+
this._result.push(error);
|
|
39
|
+
this._isError = true;
|
|
40
|
+
}
|
|
41
|
+
isError() {
|
|
42
|
+
return this._isError;
|
|
43
|
+
}
|
|
44
|
+
result() {
|
|
45
|
+
return this._result.join('\n');
|
|
46
|
+
}
|
|
47
|
+
addCode(code) {
|
|
48
|
+
this._code.push(code);
|
|
49
|
+
}
|
|
50
|
+
code() {
|
|
51
|
+
return this._code.join('\n');
|
|
52
|
+
}
|
|
53
|
+
addImage(image) {
|
|
54
|
+
this._images.push(image);
|
|
55
|
+
}
|
|
56
|
+
images() {
|
|
57
|
+
return this._images;
|
|
58
|
+
}
|
|
59
|
+
setIncludeSnapshot() {
|
|
60
|
+
this._includeSnapshot = true;
|
|
61
|
+
}
|
|
62
|
+
setIncludeTabs() {
|
|
63
|
+
this._includeTabs = true;
|
|
64
|
+
}
|
|
65
|
+
async finish() {
|
|
66
|
+
// All the async snapshotting post-action is happening here.
|
|
67
|
+
// Everything below should race against modal states.
|
|
68
|
+
if (this._includeSnapshot && this._context.currentTab())
|
|
69
|
+
this._tabSnapshot = await this._context.currentTabOrDie().captureSnapshot();
|
|
70
|
+
for (const tab of this._context.tabs())
|
|
71
|
+
await tab.updateTitle();
|
|
72
|
+
}
|
|
73
|
+
tabSnapshot() {
|
|
74
|
+
return this._tabSnapshot;
|
|
75
|
+
}
|
|
76
|
+
setElementInteraction(interaction) {
|
|
77
|
+
this._elementInteraction = interaction;
|
|
78
|
+
}
|
|
79
|
+
getElementInteraction() {
|
|
80
|
+
return this._elementInteraction;
|
|
81
|
+
}
|
|
82
|
+
serialize() {
|
|
83
|
+
const response = [];
|
|
84
|
+
// Start with command result.
|
|
85
|
+
if (this._result.length) {
|
|
86
|
+
response.push('### Result');
|
|
87
|
+
response.push(this._result.join('\n'));
|
|
88
|
+
response.push('');
|
|
89
|
+
}
|
|
90
|
+
// Add code if it exists.
|
|
91
|
+
if (this._code.length) {
|
|
92
|
+
response.push(`### Ran Playwright code
|
|
93
|
+
\`\`\`js
|
|
94
|
+
${this._code.join('\n')}
|
|
95
|
+
\`\`\``);
|
|
96
|
+
response.push('');
|
|
97
|
+
}
|
|
98
|
+
// List browser tabs.
|
|
99
|
+
if (this._includeSnapshot || this._includeTabs)
|
|
100
|
+
response.push(...renderTabsMarkdown(this._context.tabs(), this._includeTabs));
|
|
101
|
+
// Add snapshot if provided.
|
|
102
|
+
if (this._tabSnapshot?.modalStates.length) {
|
|
103
|
+
response.push(...renderModalStates(this._context, this._tabSnapshot.modalStates));
|
|
104
|
+
response.push('');
|
|
105
|
+
}
|
|
106
|
+
else if (this._tabSnapshot) {
|
|
107
|
+
response.push(renderTabSnapshot(this._tabSnapshot));
|
|
108
|
+
response.push('');
|
|
109
|
+
}
|
|
110
|
+
// Main response part
|
|
111
|
+
const content = [
|
|
112
|
+
{ type: 'text', text: response.join('\n') },
|
|
113
|
+
];
|
|
114
|
+
// Image attachments.
|
|
115
|
+
if (this._context.config.imageResponses !== 'omit') {
|
|
116
|
+
for (const image of this._images)
|
|
117
|
+
content.push({ type: 'image', data: image.data.toString('base64'), mimeType: image.contentType });
|
|
118
|
+
}
|
|
119
|
+
return { content, isError: this._isError };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
function renderTabSnapshot(tabSnapshot) {
|
|
123
|
+
const lines = [];
|
|
124
|
+
if (tabSnapshot.consoleMessages.length) {
|
|
125
|
+
lines.push(`### New console messages`);
|
|
126
|
+
for (const message of tabSnapshot.consoleMessages)
|
|
127
|
+
lines.push(`- ${trim(message.toString(), 100)}`);
|
|
128
|
+
lines.push('');
|
|
129
|
+
}
|
|
130
|
+
if (tabSnapshot.downloads.length) {
|
|
131
|
+
lines.push(`### Downloads`);
|
|
132
|
+
for (const entry of tabSnapshot.downloads) {
|
|
133
|
+
if (entry.finished)
|
|
134
|
+
lines.push(`- Downloaded file ${entry.download.suggestedFilename()} to ${entry.outputFile}`);
|
|
135
|
+
else
|
|
136
|
+
lines.push(`- Downloading file ${entry.download.suggestedFilename()} ...`);
|
|
137
|
+
}
|
|
138
|
+
lines.push('');
|
|
139
|
+
}
|
|
140
|
+
lines.push(`### Page state`);
|
|
141
|
+
lines.push(`- Page URL: ${tabSnapshot.url}`);
|
|
142
|
+
lines.push(`- Page Title: ${tabSnapshot.title}`);
|
|
143
|
+
lines.push(`- Page Snapshot:`);
|
|
144
|
+
lines.push('```yaml');
|
|
145
|
+
lines.push(tabSnapshot.ariaSnapshot);
|
|
146
|
+
lines.push('```');
|
|
147
|
+
return lines.join('\n');
|
|
148
|
+
}
|
|
149
|
+
function renderTabsMarkdown(tabs, force = false) {
|
|
150
|
+
if (tabs.length === 1 && !force)
|
|
151
|
+
return [];
|
|
152
|
+
if (!tabs.length) {
|
|
153
|
+
return [
|
|
154
|
+
'### Open tabs',
|
|
155
|
+
'No open tabs. Use the "browser_navigate" tool to navigate to a page first.',
|
|
156
|
+
'',
|
|
157
|
+
];
|
|
158
|
+
}
|
|
159
|
+
const lines = ['### Open tabs'];
|
|
160
|
+
for (let i = 0; i < tabs.length; i++) {
|
|
161
|
+
const tab = tabs[i];
|
|
162
|
+
const current = tab.isCurrentTab() ? ' (current)' : '';
|
|
163
|
+
lines.push(`- ${i}:${current} [${tab.lastTitle()}] (${tab.page.url()})`);
|
|
164
|
+
}
|
|
165
|
+
lines.push('');
|
|
166
|
+
return lines;
|
|
167
|
+
}
|
|
168
|
+
function trim(text, maxLength) {
|
|
169
|
+
if (text.length <= maxLength)
|
|
170
|
+
return text;
|
|
171
|
+
return text.slice(0, maxLength) + '...';
|
|
172
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
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 { logUnhandledError } from './log.js';
|
|
19
|
+
import { outputFile } from './config.js';
|
|
20
|
+
import { createDatabaseLogger } from './databaseLogger.js';
|
|
21
|
+
export class SessionLog {
|
|
22
|
+
_folder;
|
|
23
|
+
_file;
|
|
24
|
+
_ordinal = 0;
|
|
25
|
+
_pendingEntries = [];
|
|
26
|
+
_sessionFileQueue = Promise.resolve();
|
|
27
|
+
_flushEntriesTimeout;
|
|
28
|
+
_dbLogger;
|
|
29
|
+
constructor(sessionFolder, config) {
|
|
30
|
+
this._folder = sessionFolder;
|
|
31
|
+
this._file = path.join(this._folder, 'session.md');
|
|
32
|
+
// Extract MongoDB config from FullConfig
|
|
33
|
+
const mongoConfig = config?.mongodb ? {
|
|
34
|
+
mongoUrl: config.mongodb.url,
|
|
35
|
+
dbName: config.mongodb.dbName,
|
|
36
|
+
collectionName: config.mongodb.collectionName,
|
|
37
|
+
} : undefined;
|
|
38
|
+
this._dbLogger = createDatabaseLogger(sessionFolder, mongoConfig);
|
|
39
|
+
}
|
|
40
|
+
static async create(config, rootPath) {
|
|
41
|
+
const sessionFolder = await outputFile(config, rootPath, `session-${Date.now()}`);
|
|
42
|
+
await fs.promises.mkdir(sessionFolder, { recursive: true });
|
|
43
|
+
// eslint-disable-next-line no-console
|
|
44
|
+
console.error(`Session: ${sessionFolder}`);
|
|
45
|
+
// eslint-disable-next-line no-console
|
|
46
|
+
console.error(`Database: ${path.join(sessionFolder, 'interactions.json')}`);
|
|
47
|
+
return new SessionLog(sessionFolder, config);
|
|
48
|
+
}
|
|
49
|
+
getDatabaseLogger() {
|
|
50
|
+
return this._dbLogger;
|
|
51
|
+
}
|
|
52
|
+
logResponse(response) {
|
|
53
|
+
const entry = {
|
|
54
|
+
timestamp: performance.now(),
|
|
55
|
+
toolCall: {
|
|
56
|
+
toolName: response.toolName,
|
|
57
|
+
toolArgs: response.toolArgs,
|
|
58
|
+
result: response.result(),
|
|
59
|
+
isError: response.isError(),
|
|
60
|
+
},
|
|
61
|
+
code: response.code(),
|
|
62
|
+
tabSnapshot: response.tabSnapshot(),
|
|
63
|
+
};
|
|
64
|
+
this._appendEntry(entry);
|
|
65
|
+
// Log element interaction to database if available
|
|
66
|
+
const elementInteraction = response.getElementInteraction();
|
|
67
|
+
if (elementInteraction && elementInteraction.elementRef) {
|
|
68
|
+
const tabSnapshot = response.tabSnapshot();
|
|
69
|
+
const interaction = {
|
|
70
|
+
timestamp: new Date().toISOString(),
|
|
71
|
+
toolName: response.toolName,
|
|
72
|
+
elementRef: elementInteraction.elementRef,
|
|
73
|
+
elementDescription: elementInteraction.elementDescription || '',
|
|
74
|
+
playwrightSelector: elementInteraction.playwrightSelector || '',
|
|
75
|
+
resolvedSelector: elementInteraction.resolvedSelector,
|
|
76
|
+
url: tabSnapshot?.url || '',
|
|
77
|
+
pageTitle: tabSnapshot?.title || '',
|
|
78
|
+
additionalArgs: this._extractAdditionalArgs(response.toolArgs),
|
|
79
|
+
};
|
|
80
|
+
this._dbLogger.logInteraction(interaction);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
_extractAdditionalArgs(toolArgs) {
|
|
84
|
+
const { element, ref, ...rest } = toolArgs;
|
|
85
|
+
return rest;
|
|
86
|
+
}
|
|
87
|
+
logUserAction(action, tab, code, isUpdate) {
|
|
88
|
+
code = code.trim();
|
|
89
|
+
if (isUpdate) {
|
|
90
|
+
const lastEntry = this._pendingEntries[this._pendingEntries.length - 1];
|
|
91
|
+
if (lastEntry.userAction?.name === action.name) {
|
|
92
|
+
lastEntry.userAction = action;
|
|
93
|
+
lastEntry.code = code;
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (action.name === 'navigate') {
|
|
98
|
+
// Already logged at this location.
|
|
99
|
+
const lastEntry = this._pendingEntries[this._pendingEntries.length - 1];
|
|
100
|
+
if (lastEntry?.tabSnapshot?.url === action.url)
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const entry = {
|
|
104
|
+
timestamp: performance.now(),
|
|
105
|
+
userAction: action,
|
|
106
|
+
code,
|
|
107
|
+
tabSnapshot: {
|
|
108
|
+
url: tab.page.url(),
|
|
109
|
+
title: '',
|
|
110
|
+
ariaSnapshot: action.ariaSnapshot || '',
|
|
111
|
+
modalStates: [],
|
|
112
|
+
consoleMessages: [],
|
|
113
|
+
downloads: [],
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
this._appendEntry(entry);
|
|
117
|
+
}
|
|
118
|
+
_appendEntry(entry) {
|
|
119
|
+
this._pendingEntries.push(entry);
|
|
120
|
+
if (this._flushEntriesTimeout)
|
|
121
|
+
clearTimeout(this._flushEntriesTimeout);
|
|
122
|
+
this._flushEntriesTimeout = setTimeout(() => this._flushEntries(), 1000);
|
|
123
|
+
}
|
|
124
|
+
async _flushEntries() {
|
|
125
|
+
clearTimeout(this._flushEntriesTimeout);
|
|
126
|
+
const entries = this._pendingEntries;
|
|
127
|
+
this._pendingEntries = [];
|
|
128
|
+
const lines = [''];
|
|
129
|
+
for (const entry of entries) {
|
|
130
|
+
const ordinal = (++this._ordinal).toString().padStart(3, '0');
|
|
131
|
+
if (entry.toolCall) {
|
|
132
|
+
lines.push(`### Tool call: ${entry.toolCall.toolName}`, `- Args`, '```json', JSON.stringify(entry.toolCall.toolArgs, null, 2), '```');
|
|
133
|
+
if (entry.toolCall.result) {
|
|
134
|
+
lines.push(entry.toolCall.isError ? `- Error` : `- Result`, '```', entry.toolCall.result, '```');
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
if (entry.userAction) {
|
|
138
|
+
const actionData = { ...entry.userAction };
|
|
139
|
+
delete actionData.ariaSnapshot;
|
|
140
|
+
delete actionData.selector;
|
|
141
|
+
delete actionData.signals;
|
|
142
|
+
lines.push(`### User action: ${entry.userAction.name}`, `- Args`, '```json', JSON.stringify(actionData, null, 2), '```');
|
|
143
|
+
}
|
|
144
|
+
if (entry.code) {
|
|
145
|
+
lines.push(`- Code`, '```js', entry.code, '```');
|
|
146
|
+
}
|
|
147
|
+
if (entry.tabSnapshot) {
|
|
148
|
+
const fileName = `${ordinal}.snapshot.yml`;
|
|
149
|
+
fs.promises.writeFile(path.join(this._folder, fileName), entry.tabSnapshot.ariaSnapshot).catch(logUnhandledError);
|
|
150
|
+
lines.push(`- Snapshot: ${fileName}`);
|
|
151
|
+
}
|
|
152
|
+
lines.push('', '');
|
|
153
|
+
}
|
|
154
|
+
this._sessionFileQueue = this._sessionFileQueue.then(() => fs.promises.appendFile(this._file, lines.join('\n')));
|
|
155
|
+
}
|
|
156
|
+
}
|