@playwright/mcp 0.0.36 → 0.0.37-alpha-2025-09-08

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 (61) hide show
  1. package/README.md +82 -47
  2. package/cli.js +7 -1
  3. package/config.d.ts +24 -0
  4. package/index.d.ts +1 -1
  5. package/index.js +2 -2
  6. package/package.json +14 -40
  7. package/lib/browserContextFactory.js +0 -211
  8. package/lib/browserServerBackend.js +0 -77
  9. package/lib/config.js +0 -246
  10. package/lib/context.js +0 -226
  11. package/lib/extension/cdpRelay.js +0 -358
  12. package/lib/extension/extensionContextFactory.js +0 -56
  13. package/lib/extension/protocol.js +0 -18
  14. package/lib/index.js +0 -40
  15. package/lib/loop/loop.js +0 -69
  16. package/lib/loop/loopClaude.js +0 -152
  17. package/lib/loop/loopOpenAI.js +0 -141
  18. package/lib/loop/main.js +0 -60
  19. package/lib/loopTools/context.js +0 -67
  20. package/lib/loopTools/main.js +0 -54
  21. package/lib/loopTools/perform.js +0 -32
  22. package/lib/loopTools/snapshot.js +0 -29
  23. package/lib/loopTools/tool.js +0 -18
  24. package/lib/mcp/http.js +0 -135
  25. package/lib/mcp/inProcessTransport.js +0 -72
  26. package/lib/mcp/manualPromise.js +0 -111
  27. package/lib/mcp/mdb.js +0 -198
  28. package/lib/mcp/proxyBackend.js +0 -104
  29. package/lib/mcp/server.js +0 -123
  30. package/lib/mcp/tool.js +0 -32
  31. package/lib/program.js +0 -132
  32. package/lib/response.js +0 -165
  33. package/lib/sessionLog.js +0 -121
  34. package/lib/tab.js +0 -249
  35. package/lib/tools/common.js +0 -55
  36. package/lib/tools/console.js +0 -33
  37. package/lib/tools/dialogs.js +0 -47
  38. package/lib/tools/evaluate.js +0 -53
  39. package/lib/tools/files.js +0 -44
  40. package/lib/tools/form.js +0 -57
  41. package/lib/tools/install.js +0 -53
  42. package/lib/tools/keyboard.js +0 -78
  43. package/lib/tools/mouse.js +0 -99
  44. package/lib/tools/navigate.js +0 -54
  45. package/lib/tools/network.js +0 -41
  46. package/lib/tools/pdf.js +0 -40
  47. package/lib/tools/screenshot.js +0 -79
  48. package/lib/tools/snapshot.js +0 -139
  49. package/lib/tools/tabs.js +0 -59
  50. package/lib/tools/tool.js +0 -33
  51. package/lib/tools/utils.js +0 -74
  52. package/lib/tools/verify.js +0 -137
  53. package/lib/tools/wait.js +0 -55
  54. package/lib/tools.js +0 -54
  55. package/lib/utils/codegen.js +0 -49
  56. package/lib/utils/fileUtils.js +0 -36
  57. package/lib/utils/guid.js +0 -22
  58. package/lib/utils/log.js +0 -21
  59. package/lib/utils/package.js +0 -20
  60. package/lib/vscode/host.js +0 -128
  61. package/lib/vscode/main.js +0 -62
package/lib/mcp/server.js DELETED
@@ -1,123 +0,0 @@
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 debug from 'debug';
17
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
18
- import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
19
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
20
- import { httpAddressToString, installHttpTransport, startHttpServer } from './http.js';
21
- import { InProcessTransport } from './inProcessTransport.js';
22
- const serverDebug = debug('pw:mcp:server');
23
- const errorsDebug = debug('pw:mcp:errors');
24
- export async function connect(factory, transport, runHeartbeat) {
25
- const server = createServer(factory.name, factory.version, factory.create(), runHeartbeat);
26
- await server.connect(transport);
27
- }
28
- export async function wrapInProcess(backend) {
29
- const server = createServer('Internal', '0.0.0', backend, false);
30
- return new InProcessTransport(server);
31
- }
32
- export function createServer(name, version, backend, runHeartbeat) {
33
- let initializedPromiseResolve = () => { };
34
- const initializedPromise = new Promise(resolve => initializedPromiseResolve = resolve);
35
- const server = new Server({ name, version }, {
36
- capabilities: {
37
- tools: {},
38
- }
39
- });
40
- server.setRequestHandler(ListToolsRequestSchema, async () => {
41
- serverDebug('listTools');
42
- await initializedPromise;
43
- const tools = await backend.listTools();
44
- return { tools };
45
- });
46
- let heartbeatRunning = false;
47
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
48
- serverDebug('callTool', request);
49
- await initializedPromise;
50
- if (runHeartbeat && !heartbeatRunning) {
51
- heartbeatRunning = true;
52
- startHeartbeat(server);
53
- }
54
- try {
55
- return await backend.callTool(request.params.name, request.params.arguments || {});
56
- }
57
- catch (error) {
58
- return {
59
- content: [{ type: 'text', text: '### Result\n' + String(error) }],
60
- isError: true,
61
- };
62
- }
63
- });
64
- addServerListener(server, 'initialized', async () => {
65
- try {
66
- const capabilities = server.getClientCapabilities();
67
- let clientRoots = [];
68
- if (capabilities?.roots) {
69
- const { roots } = await server.listRoots(undefined, { timeout: 2_000 }).catch(() => ({ roots: [] }));
70
- clientRoots = roots;
71
- }
72
- const clientVersion = server.getClientVersion() ?? { name: 'unknown', version: 'unknown' };
73
- await backend.initialize?.(server, clientVersion, clientRoots);
74
- initializedPromiseResolve();
75
- }
76
- catch (e) {
77
- errorsDebug(e);
78
- }
79
- });
80
- addServerListener(server, 'close', () => backend.serverClosed?.(server));
81
- return server;
82
- }
83
- const startHeartbeat = (server) => {
84
- const beat = () => {
85
- Promise.race([
86
- server.ping(),
87
- new Promise((_, reject) => setTimeout(() => reject(new Error('ping timeout')), 5000)),
88
- ]).then(() => {
89
- setTimeout(beat, 3000);
90
- }).catch(() => {
91
- void server.close();
92
- });
93
- };
94
- beat();
95
- };
96
- function addServerListener(server, event, listener) {
97
- const oldListener = server[`on${event}`];
98
- server[`on${event}`] = () => {
99
- oldListener?.();
100
- listener();
101
- };
102
- }
103
- export async function start(serverBackendFactory, options) {
104
- if (options.port === undefined) {
105
- await connect(serverBackendFactory, new StdioServerTransport(), false);
106
- return;
107
- }
108
- const httpServer = await startHttpServer(options);
109
- await installHttpTransport(httpServer, serverBackendFactory);
110
- const url = httpAddressToString(httpServer.address());
111
- const mcpConfig = { mcpServers: {} };
112
- mcpConfig.mcpServers[serverBackendFactory.nameInConfig] = {
113
- url: `${url}/mcp`
114
- };
115
- const message = [
116
- `Listening on ${url}`,
117
- 'Put this in your client config:',
118
- JSON.stringify(mcpConfig, undefined, 2),
119
- 'For legacy SSE transport support, you can use the /sse endpoint instead.',
120
- ].join('\n');
121
- // eslint-disable-next-line no-console
122
- console.error(message);
123
- }
package/lib/mcp/tool.js DELETED
@@ -1,32 +0,0 @@
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 { zodToJsonSchema } from 'zod-to-json-schema';
17
- export function toMcpTool(tool) {
18
- return {
19
- name: tool.name,
20
- description: tool.description,
21
- inputSchema: zodToJsonSchema(tool.inputSchema, { strictUnions: true }),
22
- annotations: {
23
- title: tool.title,
24
- readOnlyHint: tool.type === 'readOnly',
25
- destructiveHint: tool.type === 'destructive',
26
- openWorldHint: true,
27
- },
28
- };
29
- }
30
- export function defineToolSchema(tool) {
31
- return tool;
32
- }
package/lib/program.js DELETED
@@ -1,132 +0,0 @@
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
- import * as mcpServer from './mcp/server.js';
18
- import { commaSeparatedList, resolveCLIConfig, semicolonSeparatedList } from './config.js';
19
- import { packageJSON } from './utils/package.js';
20
- import { Context } from './context.js';
21
- import { contextFactory } from './browserContextFactory.js';
22
- import { runLoopTools } from './loopTools/main.js';
23
- import { ProxyBackend } from './mcp/proxyBackend.js';
24
- import { BrowserServerBackend } from './browserServerBackend.js';
25
- import { ExtensionContextFactory } from './extension/extensionContextFactory.js';
26
- import { runVSCodeTools } from './vscode/host.js';
27
- program
28
- .version('Version ' + packageJSON.version)
29
- .name(packageJSON.name)
30
- .option('--allowed-origins <origins>', 'semicolon-separated list of origins to allow the browser to request. Default is to allow all.', semicolonSeparatedList)
31
- .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)
32
- .option('--block-service-workers', 'block service workers')
33
- .option('--browser <browser>', 'browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.')
34
- .option('--caps <caps>', 'comma-separated list of additional capabilities to enable, possible values: vision, pdf.', commaSeparatedList)
35
- .option('--cdp-endpoint <endpoint>', 'CDP endpoint to connect to.')
36
- .option('--config <path>', 'path to the configuration file.')
37
- .option('--device <device>', 'device to emulate, for example: "iPhone 15"')
38
- .option('--executable-path <path>', 'path to the browser executable.')
39
- .option('--extension', 'Connect to a running browser instance (Edge/Chrome only). Requires the "Playwright MCP Bridge" browser extension to be installed.')
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
- .addOption(new Option('--connect-tool', 'Allow to switch between different browser connection methods.').hideHelp())
57
- .addOption(new Option('--vscode', 'VS Code tools.').hideHelp())
58
- .addOption(new Option('--loop-tools', 'Run loop tools').hideHelp())
59
- .addOption(new Option('--vision', 'Legacy option, use --caps=vision instead').hideHelp())
60
- .action(async (options) => {
61
- setupExitWatchdog();
62
- if (options.vision) {
63
- // eslint-disable-next-line no-console
64
- console.error('The --vision option is deprecated, use --caps=vision instead');
65
- options.caps = 'vision';
66
- }
67
- const config = await resolveCLIConfig(options);
68
- const browserContextFactory = contextFactory(config);
69
- const extensionContextFactory = new ExtensionContextFactory(config.browser.launchOptions.channel || 'chrome', config.browser.userDataDir, config.browser.launchOptions.executablePath);
70
- if (options.extension) {
71
- const serverBackendFactory = {
72
- name: 'Playwright w/ extension',
73
- nameInConfig: 'playwright-extension',
74
- version: packageJSON.version,
75
- create: () => new BrowserServerBackend(config, extensionContextFactory)
76
- };
77
- await mcpServer.start(serverBackendFactory, config.server);
78
- return;
79
- }
80
- if (options.vscode) {
81
- await runVSCodeTools(config);
82
- return;
83
- }
84
- if (options.loopTools) {
85
- await runLoopTools(config);
86
- return;
87
- }
88
- if (options.connectTool) {
89
- const providers = [
90
- {
91
- name: 'default',
92
- description: 'Starts standalone browser',
93
- connect: () => mcpServer.wrapInProcess(new BrowserServerBackend(config, browserContextFactory)),
94
- },
95
- {
96
- name: 'extension',
97
- description: 'Connect to a browser using the Playwright MCP extension',
98
- connect: () => mcpServer.wrapInProcess(new BrowserServerBackend(config, extensionContextFactory)),
99
- },
100
- ];
101
- const factory = {
102
- name: 'Playwright w/ switch',
103
- nameInConfig: 'playwright-switch',
104
- version: packageJSON.version,
105
- create: () => new ProxyBackend(providers),
106
- };
107
- await mcpServer.start(factory, config.server);
108
- return;
109
- }
110
- const factory = {
111
- name: 'Playwright',
112
- nameInConfig: 'playwright',
113
- version: packageJSON.version,
114
- create: () => new BrowserServerBackend(config, browserContextFactory)
115
- };
116
- await mcpServer.start(factory, config.server);
117
- });
118
- function setupExitWatchdog() {
119
- let isExiting = false;
120
- const handleExit = async () => {
121
- if (isExiting)
122
- return;
123
- isExiting = true;
124
- setTimeout(() => process.exit(0), 15000);
125
- await Context.disposeAll();
126
- process.exit(0);
127
- };
128
- process.stdin.on('close', handleExit);
129
- process.on('SIGINT', handleExit);
130
- process.on('SIGTERM', handleExit);
131
- }
132
- void program.parseAsync(process.argv);
package/lib/response.js DELETED
@@ -1,165 +0,0 @@
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
- toolName;
26
- toolArgs;
27
- _isError;
28
- constructor(context, toolName, toolArgs) {
29
- this._context = context;
30
- this.toolName = toolName;
31
- this.toolArgs = toolArgs;
32
- }
33
- addResult(result) {
34
- this._result.push(result);
35
- }
36
- addError(error) {
37
- this._result.push(error);
38
- this._isError = true;
39
- }
40
- isError() {
41
- return this._isError;
42
- }
43
- result() {
44
- return this._result.join('\n');
45
- }
46
- addCode(code) {
47
- this._code.push(code);
48
- }
49
- code() {
50
- return this._code.join('\n');
51
- }
52
- addImage(image) {
53
- this._images.push(image);
54
- }
55
- images() {
56
- return this._images;
57
- }
58
- setIncludeSnapshot() {
59
- this._includeSnapshot = true;
60
- }
61
- setIncludeTabs() {
62
- this._includeTabs = true;
63
- }
64
- async finish() {
65
- // All the async snapshotting post-action is happening here.
66
- // Everything below should race against modal states.
67
- if (this._includeSnapshot && this._context.currentTab())
68
- this._tabSnapshot = await this._context.currentTabOrDie().captureSnapshot();
69
- for (const tab of this._context.tabs())
70
- await tab.updateTitle();
71
- }
72
- tabSnapshot() {
73
- return this._tabSnapshot;
74
- }
75
- serialize() {
76
- const response = [];
77
- // Start with command result.
78
- if (this._result.length) {
79
- response.push('### Result');
80
- response.push(this._result.join('\n'));
81
- response.push('');
82
- }
83
- // Add code if it exists.
84
- if (this._code.length) {
85
- response.push(`### Ran Playwright code
86
- \`\`\`js
87
- ${this._code.join('\n')}
88
- \`\`\``);
89
- response.push('');
90
- }
91
- // List browser tabs.
92
- if (this._includeSnapshot || this._includeTabs)
93
- response.push(...renderTabsMarkdown(this._context.tabs(), this._includeTabs));
94
- // Add snapshot if provided.
95
- if (this._tabSnapshot?.modalStates.length) {
96
- response.push(...renderModalStates(this._context, this._tabSnapshot.modalStates));
97
- response.push('');
98
- }
99
- else if (this._tabSnapshot) {
100
- response.push(renderTabSnapshot(this._tabSnapshot));
101
- response.push('');
102
- }
103
- // Main response part
104
- const content = [
105
- { type: 'text', text: response.join('\n') },
106
- ];
107
- // Image attachments.
108
- if (this._context.config.imageResponses !== 'omit') {
109
- for (const image of this._images)
110
- content.push({ type: 'image', data: image.data.toString('base64'), mimeType: image.contentType });
111
- }
112
- return { content, isError: this._isError };
113
- }
114
- }
115
- function renderTabSnapshot(tabSnapshot) {
116
- const lines = [];
117
- if (tabSnapshot.consoleMessages.length) {
118
- lines.push(`### New console messages`);
119
- for (const message of tabSnapshot.consoleMessages)
120
- lines.push(`- ${trim(message.toString(), 100)}`);
121
- lines.push('');
122
- }
123
- if (tabSnapshot.downloads.length) {
124
- lines.push(`### Downloads`);
125
- for (const entry of tabSnapshot.downloads) {
126
- if (entry.finished)
127
- lines.push(`- Downloaded file ${entry.download.suggestedFilename()} to ${entry.outputFile}`);
128
- else
129
- lines.push(`- Downloading file ${entry.download.suggestedFilename()} ...`);
130
- }
131
- lines.push('');
132
- }
133
- lines.push(`### Page state`);
134
- lines.push(`- Page URL: ${tabSnapshot.url}`);
135
- lines.push(`- Page Title: ${tabSnapshot.title}`);
136
- lines.push(`- Page Snapshot:`);
137
- lines.push('```yaml');
138
- lines.push(tabSnapshot.ariaSnapshot);
139
- lines.push('```');
140
- return lines.join('\n');
141
- }
142
- function renderTabsMarkdown(tabs, force = false) {
143
- if (tabs.length === 1 && !force)
144
- return [];
145
- if (!tabs.length) {
146
- return [
147
- '### Open tabs',
148
- 'No open tabs. Use the "browser_navigate" tool to navigate to a page first.',
149
- '',
150
- ];
151
- }
152
- const lines = ['### Open tabs'];
153
- for (let i = 0; i < tabs.length; i++) {
154
- const tab = tabs[i];
155
- const current = tab.isCurrentTab() ? ' (current)' : '';
156
- lines.push(`- ${i}:${current} [${tab.lastTitle()}] (${tab.page.url()})`);
157
- }
158
- lines.push('');
159
- return lines;
160
- }
161
- function trim(text, maxLength) {
162
- if (text.length <= maxLength)
163
- return text;
164
- return text.slice(0, maxLength) + '...';
165
- }
package/lib/sessionLog.js DELETED
@@ -1,121 +0,0 @@
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 './utils/log.js';
19
- import { outputFile } from './config.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.writeFile(path.join(this._folder, fileName), entry.tabSnapshot.ariaSnapshot).catch(logUnhandledError);
115
- lines.push(`- Snapshot: ${fileName}`);
116
- }
117
- lines.push('', '');
118
- }
119
- this._sessionFileQueue = this._sessionFileQueue.then(() => fs.promises.appendFile(this._file, lines.join('\n')));
120
- }
121
- }