@playwright/mcp 0.0.30 → 0.0.32

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 (54) hide show
  1. package/README.md +180 -320
  2. package/config.d.ts +5 -14
  3. package/index.d.ts +1 -6
  4. package/lib/browserContextFactory.js +3 -35
  5. package/lib/browserServerBackend.js +54 -0
  6. package/lib/config.js +64 -7
  7. package/lib/context.js +50 -163
  8. package/lib/extension/cdpRelay.js +370 -0
  9. package/lib/extension/main.js +33 -0
  10. package/lib/httpServer.js +20 -182
  11. package/lib/index.js +3 -2
  12. package/lib/log.js +21 -0
  13. package/lib/loop/loop.js +69 -0
  14. package/lib/loop/loopClaude.js +152 -0
  15. package/lib/loop/loopOpenAI.js +141 -0
  16. package/lib/loop/main.js +60 -0
  17. package/lib/loopTools/context.js +66 -0
  18. package/lib/loopTools/main.js +49 -0
  19. package/lib/loopTools/perform.js +32 -0
  20. package/lib/loopTools/snapshot.js +29 -0
  21. package/lib/loopTools/tool.js +18 -0
  22. package/lib/mcp/inProcessTransport.js +72 -0
  23. package/lib/mcp/server.js +88 -0
  24. package/lib/{transport.js → mcp/transport.js} +30 -42
  25. package/lib/package.js +3 -3
  26. package/lib/program.js +47 -17
  27. package/lib/response.js +98 -0
  28. package/lib/sessionLog.js +70 -0
  29. package/lib/tab.js +166 -21
  30. package/lib/tools/common.js +13 -25
  31. package/lib/tools/console.js +4 -15
  32. package/lib/tools/dialogs.js +14 -19
  33. package/lib/tools/evaluate.js +53 -0
  34. package/lib/tools/files.js +13 -19
  35. package/lib/tools/install.js +4 -8
  36. package/lib/tools/keyboard.js +51 -17
  37. package/lib/tools/mouse.js +99 -0
  38. package/lib/tools/navigate.js +22 -42
  39. package/lib/tools/network.js +5 -15
  40. package/lib/tools/pdf.js +8 -15
  41. package/lib/tools/screenshot.js +29 -30
  42. package/lib/tools/snapshot.js +49 -109
  43. package/lib/tools/tabs.js +21 -52
  44. package/lib/tools/tool.js +14 -0
  45. package/lib/tools/utils.js +7 -6
  46. package/lib/tools/wait.js +8 -11
  47. package/lib/tools.js +15 -26
  48. package/package.json +12 -5
  49. package/lib/browserServer.js +0 -151
  50. package/lib/connection.js +0 -82
  51. package/lib/pageSnapshot.js +0 -43
  52. package/lib/server.js +0 -48
  53. package/lib/tools/testing.js +0 -60
  54. package/lib/tools/vision.js +0 -189
@@ -0,0 +1,72 @@
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
+ export class InProcessTransport {
17
+ _server;
18
+ _serverTransport;
19
+ _connected = false;
20
+ constructor(server) {
21
+ this._server = server;
22
+ this._serverTransport = new InProcessServerTransport(this);
23
+ }
24
+ async start() {
25
+ if (this._connected)
26
+ throw new Error('InprocessTransport already started!');
27
+ await this._server.connect(this._serverTransport);
28
+ this._connected = true;
29
+ }
30
+ async send(message, options) {
31
+ if (!this._connected)
32
+ throw new Error('Transport not connected');
33
+ this._serverTransport._receiveFromClient(message);
34
+ }
35
+ async close() {
36
+ if (this._connected) {
37
+ this._connected = false;
38
+ this.onclose?.();
39
+ this._serverTransport.onclose?.();
40
+ }
41
+ }
42
+ onclose;
43
+ onerror;
44
+ onmessage;
45
+ sessionId;
46
+ setProtocolVersion;
47
+ _receiveFromServer(message, extra) {
48
+ this.onmessage?.(message, extra);
49
+ }
50
+ }
51
+ class InProcessServerTransport {
52
+ _clientTransport;
53
+ constructor(clientTransport) {
54
+ this._clientTransport = clientTransport;
55
+ }
56
+ async start() {
57
+ }
58
+ async send(message, options) {
59
+ this._clientTransport._receiveFromServer(message);
60
+ }
61
+ async close() {
62
+ this.onclose?.();
63
+ }
64
+ onclose;
65
+ onerror;
66
+ onmessage;
67
+ sessionId;
68
+ setProtocolVersion;
69
+ _receiveFromClient(message) {
70
+ this.onmessage?.(message);
71
+ }
72
+ }
@@ -0,0 +1,88 @@
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 { Server } from '@modelcontextprotocol/sdk/server/index.js';
17
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
18
+ import { zodToJsonSchema } from 'zod-to-json-schema';
19
+ export async function connect(serverBackendFactory, transport, runHeartbeat) {
20
+ const backend = serverBackendFactory();
21
+ await backend.initialize?.();
22
+ const server = createServer(backend, runHeartbeat);
23
+ await server.connect(transport);
24
+ }
25
+ export function createServer(backend, runHeartbeat) {
26
+ const server = new Server({ name: backend.name, version: backend.version }, {
27
+ capabilities: {
28
+ tools: {},
29
+ }
30
+ });
31
+ const tools = backend.tools();
32
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
33
+ return { tools: tools.map(tool => ({
34
+ name: tool.name,
35
+ description: tool.description,
36
+ inputSchema: zodToJsonSchema(tool.inputSchema),
37
+ annotations: {
38
+ title: tool.title,
39
+ readOnlyHint: tool.type === 'readOnly',
40
+ destructiveHint: tool.type === 'destructive',
41
+ openWorldHint: true,
42
+ },
43
+ })) };
44
+ });
45
+ let heartbeatRunning = false;
46
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
47
+ if (runHeartbeat && !heartbeatRunning) {
48
+ heartbeatRunning = true;
49
+ startHeartbeat(server);
50
+ }
51
+ const errorResult = (...messages) => ({
52
+ content: [{ type: 'text', text: messages.join('\n') }],
53
+ isError: true,
54
+ });
55
+ const tool = tools.find(tool => tool.name === request.params.name);
56
+ if (!tool)
57
+ return errorResult(`Tool "${request.params.name}" not found`);
58
+ try {
59
+ return await backend.callTool(tool, tool.inputSchema.parse(request.params.arguments || {}));
60
+ }
61
+ catch (error) {
62
+ return errorResult(String(error));
63
+ }
64
+ });
65
+ addServerListener(server, 'initialized', () => backend.serverInitialized?.(server.getClientVersion()));
66
+ addServerListener(server, 'close', () => backend.serverClosed?.());
67
+ return server;
68
+ }
69
+ const startHeartbeat = (server) => {
70
+ const beat = () => {
71
+ Promise.race([
72
+ server.ping(),
73
+ new Promise((_, reject) => setTimeout(() => reject(new Error('ping timeout')), 5000)),
74
+ ]).then(() => {
75
+ setTimeout(beat, 3000);
76
+ }).catch(() => {
77
+ void server.close();
78
+ });
79
+ };
80
+ beat();
81
+ };
82
+ function addServerListener(server, event, listener) {
83
+ const oldListener = server[`on${event}`];
84
+ server[`on${event}`] = () => {
85
+ oldListener?.();
86
+ listener();
87
+ };
88
+ }
@@ -13,18 +13,27 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- import http from 'node:http';
17
- import assert from 'node:assert';
18
- import crypto from 'node:crypto';
16
+ import crypto from 'crypto';
19
17
  import debug from 'debug';
20
18
  import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
21
19
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
22
20
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
23
- export async function startStdioTransport(server) {
24
- await server.createConnection(new StdioServerTransport());
21
+ import { httpAddressToString, startHttpServer } from '../httpServer.js';
22
+ import * as mcpServer from './server.js';
23
+ export async function start(serverBackendFactory, options) {
24
+ if (options.port !== undefined) {
25
+ const httpServer = await startHttpServer(options);
26
+ startHttpTransport(httpServer, serverBackendFactory);
27
+ }
28
+ else {
29
+ await startStdioTransport(serverBackendFactory);
30
+ }
31
+ }
32
+ async function startStdioTransport(serverBackendFactory) {
33
+ await mcpServer.connect(serverBackendFactory, new StdioServerTransport(), false);
25
34
  }
26
35
  const testDebug = debug('pw:mcp:test');
27
- async function handleSSE(server, req, res, url, sessions) {
36
+ async function handleSSE(serverBackendFactory, req, res, url, sessions) {
28
37
  if (req.method === 'POST') {
29
38
  const sessionId = url.searchParams.get('sessionId');
30
39
  if (!sessionId) {
@@ -42,19 +51,17 @@ async function handleSSE(server, req, res, url, sessions) {
42
51
  const transport = new SSEServerTransport('/sse', res);
43
52
  sessions.set(transport.sessionId, transport);
44
53
  testDebug(`create SSE session: ${transport.sessionId}`);
45
- const connection = await server.createConnection(transport);
54
+ await mcpServer.connect(serverBackendFactory, transport, false);
46
55
  res.on('close', () => {
47
56
  testDebug(`delete SSE session: ${transport.sessionId}`);
48
57
  sessions.delete(transport.sessionId);
49
- // eslint-disable-next-line no-console
50
- void connection.close().catch(e => console.error(e));
51
58
  });
52
59
  return;
53
60
  }
54
61
  res.statusCode = 405;
55
62
  res.end('Method not allowed');
56
63
  }
57
- async function handleStreamable(server, req, res, sessions) {
64
+ async function handleStreamable(serverBackendFactory, req, res, sessions) {
58
65
  const sessionId = req.headers['mcp-session-id'];
59
66
  if (sessionId) {
60
67
  const transport = sessions.get(sessionId);
@@ -68,42 +75,33 @@ async function handleStreamable(server, req, res, sessions) {
68
75
  if (req.method === 'POST') {
69
76
  const transport = new StreamableHTTPServerTransport({
70
77
  sessionIdGenerator: () => crypto.randomUUID(),
71
- onsessioninitialized: sessionId => {
78
+ onsessioninitialized: async (sessionId) => {
79
+ testDebug(`create http session: ${transport.sessionId}`);
80
+ await mcpServer.connect(serverBackendFactory, transport, true);
72
81
  sessions.set(sessionId, transport);
73
82
  }
74
83
  });
75
84
  transport.onclose = () => {
76
- if (transport.sessionId)
77
- sessions.delete(transport.sessionId);
85
+ if (!transport.sessionId)
86
+ return;
87
+ sessions.delete(transport.sessionId);
88
+ testDebug(`delete http session: ${transport.sessionId}`);
78
89
  };
79
- await server.createConnection(transport);
80
90
  await transport.handleRequest(req, res);
81
91
  return;
82
92
  }
83
93
  res.statusCode = 400;
84
94
  res.end('Invalid request');
85
95
  }
86
- export async function startHttpServer(config) {
87
- const { host, port } = config;
88
- const httpServer = http.createServer();
89
- await new Promise((resolve, reject) => {
90
- httpServer.on('error', reject);
91
- httpServer.listen(port, host, () => {
92
- resolve();
93
- httpServer.removeListener('error', reject);
94
- });
95
- });
96
- return httpServer;
97
- }
98
- export function startHttpTransport(httpServer, mcpServer) {
96
+ function startHttpTransport(httpServer, serverBackendFactory) {
99
97
  const sseSessions = new Map();
100
98
  const streamableSessions = new Map();
101
99
  httpServer.on('request', async (req, res) => {
102
100
  const url = new URL(`http://localhost${req.url}`);
103
- if (url.pathname.startsWith('/mcp'))
104
- await handleStreamable(mcpServer, req, res, streamableSessions);
101
+ if (url.pathname.startsWith('/sse'))
102
+ await handleSSE(serverBackendFactory, req, res, url, sseSessions);
105
103
  else
106
- await handleSSE(mcpServer, req, res, url, sseSessions);
104
+ await handleStreamable(serverBackendFactory, req, res, streamableSessions);
107
105
  });
108
106
  const url = httpAddressToString(httpServer.address());
109
107
  const message = [
@@ -112,22 +110,12 @@ export function startHttpTransport(httpServer, mcpServer) {
112
110
  JSON.stringify({
113
111
  'mcpServers': {
114
112
  'playwright': {
115
- 'url': `${url}/sse`
113
+ 'url': `${url}/mcp`
116
114
  }
117
115
  }
118
116
  }, undefined, 2),
119
- 'If your client supports streamable HTTP, you can use the /mcp endpoint instead.',
117
+ 'For legacy SSE transport support, you can use the /sse endpoint instead.',
120
118
  ].join('\n');
121
119
  // eslint-disable-next-line no-console
122
120
  console.error(message);
123
121
  }
124
- export function httpAddressToString(address) {
125
- assert(address, 'Could not bind server socket');
126
- if (typeof address === 'string')
127
- return address;
128
- const resolvedPort = address.port;
129
- let resolvedHost = address.family === 'IPv4' ? address.address : `[${address.address}]`;
130
- if (resolvedHost === '0.0.0.0' || resolvedHost === '[::]')
131
- resolvedHost = 'localhost';
132
- return `http://${resolvedHost}:${resolvedPort}`;
133
- }
package/lib/package.js CHANGED
@@ -13,8 +13,8 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- import fs from 'node:fs';
17
- import url from 'node:url';
18
- import path from 'node:path';
16
+ import fs from 'fs';
17
+ import path from 'path';
18
+ import url from 'url';
19
19
  const __filename = url.fileURLToPath(import.meta.url);
20
20
  export const packageJSON = JSON.parse(fs.readFileSync(path.join(path.dirname(__filename), '..', 'package.json'), 'utf8'));
package/lib/program.js CHANGED
@@ -13,13 +13,17 @@
13
13
  * See the License for the specific language governing permissions and
14
14
  * limitations under the License.
15
15
  */
16
- import { program } from 'commander';
16
+ import { program, Option } from 'commander';
17
17
  // @ts-ignore
18
18
  import { startTraceViewerServer } from 'playwright-core/lib/server';
19
- import { startHttpServer, startHttpTransport, startStdioTransport } from './transport.js';
20
- import { resolveCLIConfig } from './config.js';
21
- import { Server } from './server.js';
19
+ import * as mcpTransport from './mcp/transport.js';
20
+ import { commaSeparatedList, resolveCLIConfig, semicolonSeparatedList } from './config.js';
22
21
  import { packageJSON } from './package.js';
22
+ import { runWithExtension } from './extension/main.js';
23
+ import { BrowserServerBackend } from './browserServerBackend.js';
24
+ import { Context } from './context.js';
25
+ import { contextFactory } from './browserContextFactory.js';
26
+ import { runLoopTools } from './loopTools/main.js';
23
27
  program
24
28
  .version('Version ' + packageJSON.version)
25
29
  .name(packageJSON.name)
@@ -27,8 +31,7 @@ program
27
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)
28
32
  .option('--block-service-workers', 'block service workers')
29
33
  .option('--browser <browser>', 'browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.')
30
- .option('--browser-agent <endpoint>', 'Use browser agent (experimental).')
31
- .option('--caps <caps>', 'comma-separated list of capabilities to enable, possible values: tabs, pdf, history, wait, files, install. Default is all.')
34
+ .option('--caps <caps>', 'comma-separated list of additional capabilities to enable, possible values: vision, pdf.', commaSeparatedList)
32
35
  .option('--cdp-endpoint <endpoint>', 'CDP endpoint to connect to.')
33
36
  .option('--config <path>', 'path to the configuration file.')
34
37
  .option('--device <device>', 'device to emulate, for example: "iPhone 15"')
@@ -37,27 +40,40 @@ program
37
40
  .option('--host <host>', 'host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.')
38
41
  .option('--ignore-https-errors', 'ignore https errors')
39
42
  .option('--isolated', 'keep the browser profile in memory, do not save it to disk.')
40
- .option('--image-responses <mode>', 'whether to send image responses to the client. Can be "allow", "omit", or "auto". Defaults to "auto", which sends images if the client can display them.')
43
+ .option('--image-responses <mode>', 'whether to send image responses to the client. Can be "allow" or "omit", Defaults to "allow".')
41
44
  .option('--no-sandbox', 'disable the sandbox for all process types that are normally sandboxed.')
42
45
  .option('--output-dir <path>', 'path to the directory for output files.')
43
46
  .option('--port <port>', 'port to listen on for SSE transport.')
44
47
  .option('--proxy-bypass <bypass>', 'comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"')
45
48
  .option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"')
49
+ .option('--save-session', 'Whether to save the Playwright MCP session into the output directory.')
46
50
  .option('--save-trace', 'Whether to save the Playwright Trace of the session into the output directory.')
47
51
  .option('--storage-state <path>', 'path to the storage state file for isolated sessions.')
48
52
  .option('--user-agent <ua string>', 'specify user agent string')
49
53
  .option('--user-data-dir <path>', 'path to the user data directory. If not specified, a temporary directory will be created.')
50
54
  .option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"')
51
- .option('--vision', 'Run server that uses screenshots (Aria snapshots are used by default)')
55
+ .addOption(new Option('--extension', 'Connect to a running browser instance (Edge/Chrome only). Requires the "Playwright MCP Bridge" browser extension to be installed.').hideHelp())
56
+ .addOption(new Option('--loop-tools', 'Run loop tools').hideHelp())
57
+ .addOption(new Option('--vision', 'Legacy option, use --caps=vision instead').hideHelp())
52
58
  .action(async (options) => {
59
+ const abortController = setupExitWatchdog();
60
+ if (options.vision) {
61
+ // eslint-disable-next-line no-console
62
+ console.error('The --vision option is deprecated, use --caps=vision instead');
63
+ options.caps = 'vision';
64
+ }
53
65
  const config = await resolveCLIConfig(options);
54
- const httpServer = config.server.port !== undefined ? await startHttpServer(config.server) : undefined;
55
- const server = new Server(config);
56
- server.setupExitWatchdog();
57
- if (httpServer)
58
- startHttpTransport(httpServer, server);
59
- else
60
- await startStdioTransport(server);
66
+ if (options.extension) {
67
+ await runWithExtension(config, abortController);
68
+ return;
69
+ }
70
+ if (options.loopTools) {
71
+ await runLoopTools(config);
72
+ return;
73
+ }
74
+ const browserContextFactory = contextFactory(config.browser);
75
+ const serverBackendFactory = () => new BrowserServerBackend(config, browserContextFactory);
76
+ await mcpTransport.start(serverBackendFactory, config.server);
61
77
  if (config.saveTrace) {
62
78
  const server = await startTraceViewerServer();
63
79
  const urlPrefix = server.urlPrefix('human-readable');
@@ -66,7 +82,21 @@ program
66
82
  console.error('\nTrace viewer listening on ' + url);
67
83
  }
68
84
  });
69
- function semicolonSeparatedList(value) {
70
- return value.split(';').map(v => v.trim());
85
+ function setupExitWatchdog() {
86
+ const abortController = new AbortController();
87
+ let isExiting = false;
88
+ const handleExit = async () => {
89
+ if (isExiting)
90
+ return;
91
+ isExiting = true;
92
+ setTimeout(() => process.exit(0), 15000);
93
+ abortController.abort('Process exiting');
94
+ await Context.disposeAll();
95
+ process.exit(0);
96
+ };
97
+ process.stdin.on('close', handleExit);
98
+ process.on('SIGINT', handleExit);
99
+ process.on('SIGTERM', handleExit);
100
+ return abortController;
71
101
  }
72
102
  void program.parseAsync(process.argv);
@@ -0,0 +1,98 @@
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
+ export class Response {
17
+ _result = [];
18
+ _code = [];
19
+ _images = [];
20
+ _context;
21
+ _includeSnapshot = false;
22
+ _includeTabs = false;
23
+ _snapshot;
24
+ toolName;
25
+ toolArgs;
26
+ constructor(context, toolName, toolArgs) {
27
+ this._context = context;
28
+ this.toolName = toolName;
29
+ this.toolArgs = toolArgs;
30
+ }
31
+ addResult(result) {
32
+ this._result.push(result);
33
+ }
34
+ result() {
35
+ return this._result.join('\n');
36
+ }
37
+ addCode(code) {
38
+ this._code.push(code);
39
+ }
40
+ code() {
41
+ return this._code.join('\n');
42
+ }
43
+ addImage(image) {
44
+ this._images.push(image);
45
+ }
46
+ images() {
47
+ return this._images;
48
+ }
49
+ setIncludeSnapshot() {
50
+ this._includeSnapshot = true;
51
+ }
52
+ setIncludeTabs() {
53
+ this._includeTabs = true;
54
+ }
55
+ async snapshot() {
56
+ if (this._snapshot !== undefined)
57
+ return this._snapshot;
58
+ if (this._includeSnapshot && this._context.currentTab())
59
+ this._snapshot = await this._context.currentTabOrDie().captureSnapshot();
60
+ else
61
+ this._snapshot = '';
62
+ return this._snapshot;
63
+ }
64
+ async serialize() {
65
+ const response = [];
66
+ // Start with command result.
67
+ if (this._result.length) {
68
+ response.push('### Result');
69
+ response.push(this._result.join('\n'));
70
+ response.push('');
71
+ }
72
+ // Add code if it exists.
73
+ if (this._code.length) {
74
+ response.push(`### Ran Playwright code
75
+ \`\`\`js
76
+ ${this._code.join('\n')}
77
+ \`\`\``);
78
+ response.push('');
79
+ }
80
+ // List browser tabs.
81
+ if (this._includeSnapshot || this._includeTabs)
82
+ response.push(...(await this._context.listTabsMarkdown(this._includeTabs)));
83
+ // Add snapshot if provided.
84
+ const snapshot = await this.snapshot();
85
+ if (snapshot)
86
+ response.push(snapshot, '');
87
+ // Main response part
88
+ const content = [
89
+ { type: 'text', text: response.join('\n') },
90
+ ];
91
+ // Image attachments.
92
+ if (this._context.config.imageResponses !== 'omit') {
93
+ for (const image of this._images)
94
+ content.push({ type: 'image', data: image.data.toString('base64'), mimeType: image.contentType });
95
+ }
96
+ return { content };
97
+ }
98
+ }
@@ -0,0 +1,70 @@
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
+ let sessionOrdinal = 0;
20
+ export class SessionLog {
21
+ _folder;
22
+ _file;
23
+ _ordinal = 0;
24
+ constructor(sessionFolder) {
25
+ this._folder = sessionFolder;
26
+ this._file = path.join(this._folder, 'session.md');
27
+ }
28
+ static async create(config) {
29
+ const sessionFolder = await outputFile(config, `session-${(++sessionOrdinal).toString().padStart(3, '0')}`);
30
+ await fs.promises.mkdir(sessionFolder, { recursive: true });
31
+ // eslint-disable-next-line no-console
32
+ console.error(`Session: ${sessionFolder}`);
33
+ return new SessionLog(sessionFolder);
34
+ }
35
+ async log(response) {
36
+ const prefix = `${(++this._ordinal).toString().padStart(3, '0')}`;
37
+ const lines = [
38
+ `### Tool: ${response.toolName}`,
39
+ ``,
40
+ `- Args`,
41
+ '```json',
42
+ JSON.stringify(response.toolArgs, null, 2),
43
+ '```',
44
+ ];
45
+ if (response.result()) {
46
+ lines.push(`- Result`, '```', response.result(), '```');
47
+ }
48
+ if (response.code()) {
49
+ lines.push(`- Code`, '```js', response.code(), '```');
50
+ }
51
+ const snapshot = await response.snapshot();
52
+ if (snapshot) {
53
+ const fileName = `${prefix}.snapshot.yml`;
54
+ await fs.promises.writeFile(path.join(this._folder, fileName), snapshot);
55
+ lines.push(`- Snapshot: ${fileName}`);
56
+ }
57
+ for (const image of response.images()) {
58
+ const fileName = `${prefix}.screenshot.${extension(image.contentType)}`;
59
+ await fs.promises.writeFile(path.join(this._folder, fileName), image.data);
60
+ lines.push(`- Screenshot: ${fileName}`);
61
+ }
62
+ lines.push('', '');
63
+ await fs.promises.appendFile(this._file, lines.join('\n'));
64
+ }
65
+ }
66
+ function extension(contentType) {
67
+ if (contentType === 'image/jpeg')
68
+ return 'jpg';
69
+ return 'png';
70
+ }