@1outres/dsh-bot-connector-browser 0.0.0-stage → 0.3.0

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.
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The browser connector's tools: Playwright MCP's, as the generator listed
3
+ * them from the pinned version (src/generated/playwright-mcp.json), with
4
+ * the connector's policy for each (which are not offered, which are
5
+ * disallowed, which only read). The server in a bot's environment must list
6
+ * exactly the same tools.
7
+ */
8
+ import generated from "../generated/playwright-mcp.json"
9
+ import { type McpTool, parseTool } from "./mcp/protocol"
10
+
11
+ export interface GeneratedServer {
12
+ readonly package: string
13
+ readonly version: string
14
+ readonly server: { readonly name: string; readonly version: string }
15
+ /** The server's arguments the tools were listed with; it runs with them. */
16
+ readonly arguments: readonly string[]
17
+ readonly tools: readonly McpTool[]
18
+ }
19
+
20
+ /** Closing the browser would close the person's Chrome; installing one is the desktop's part. */
21
+ export const NOT_OFFERED = ["browser_close", "browser_install"] as const
22
+ /** Runs any code in the server's process, beyond the tools' own checks. */
23
+ export const DISALLOWED = ["browser_run_code_unsafe"] as const
24
+
25
+ const UPSTREAM_PREFIX = "browser_"
26
+
27
+ export function parseGeneratedServer(value: unknown): GeneratedServer {
28
+ const record = value as Partial<Record<keyof GeneratedServer, unknown>>
29
+ const server = record.server as Partial<GeneratedServer["server"]> | undefined
30
+ if (
31
+ typeof record.package !== "string" ||
32
+ typeof record.version !== "string" ||
33
+ typeof server?.name !== "string" ||
34
+ typeof server.version !== "string" ||
35
+ !Array.isArray(record.arguments) ||
36
+ !record.arguments.every((argument) => typeof argument === "string") ||
37
+ !Array.isArray(record.tools)
38
+ ) {
39
+ throw new Error("src/generated/playwright-mcp.json is malformed; run the generator again")
40
+ }
41
+ return {
42
+ package: record.package,
43
+ version: record.version,
44
+ server: { name: server.name, version: server.version },
45
+ arguments: record.arguments as string[],
46
+ tools: record.tools.map((tool, index) => parseTool(tool, `generated tool ${index + 1}`)),
47
+ }
48
+ }
49
+
50
+ export const GENERATED_SERVER = parseGeneratedServer(generated)
51
+
52
+ /** One upstream tool as the connector offers it. */
53
+ export interface OfferedTool {
54
+ readonly upstream: McpTool
55
+ /** Its name in the connector (bot-core prefixes `browser_`). */
56
+ readonly name: string
57
+ readonly permission: "allow" | "disallow"
58
+ readonly readOnly: boolean
59
+ }
60
+
61
+ export function offeredTools(tools: readonly McpTool[]): readonly OfferedTool[] {
62
+ return tools
63
+ .filter((tool) => !(NOT_OFFERED as readonly string[]).includes(tool.name))
64
+ .map((tool) => {
65
+ if (!tool.name.startsWith(UPSTREAM_PREFIX)) {
66
+ throw new Error(`Playwright MCP's tool ${tool.name} is not named ${UPSTREAM_PREFIX}…`)
67
+ }
68
+ return {
69
+ upstream: tool,
70
+ name: tool.name.slice(UPSTREAM_PREFIX.length),
71
+ permission: (DISALLOWED as readonly string[]).includes(tool.name) ? "disallow" : "allow",
72
+ readOnly: tool.annotations?.readOnlyHint === true,
73
+ }
74
+ })
75
+ }
76
+
77
+ const canonical = (value: unknown): unknown => {
78
+ if (Array.isArray(value)) return value.map(canonical)
79
+ if (typeof value !== "object" || value === null) return value
80
+ return Object.fromEntries(
81
+ Object.keys(value)
82
+ .sort()
83
+ .map((key) => [key, canonical((value as Record<string, unknown>)[key])]),
84
+ )
85
+ }
86
+
87
+ /** How the tools a server lists differ from the generated ones (empty when they are the same). */
88
+ export function toolDifferences(
89
+ expected: readonly McpTool[],
90
+ listed: readonly McpTool[],
91
+ ): readonly string[] {
92
+ const byName = new Map(listed.map((tool) => [tool.name, tool]))
93
+ const differences: string[] = []
94
+ for (const tool of expected) {
95
+ const other = byName.get(tool.name)
96
+ if (other === undefined) differences.push(`${tool.name} is missing`)
97
+ else if (JSON.stringify(canonical(other)) !== JSON.stringify(canonical(tool))) {
98
+ differences.push(`${tool.name} changed`)
99
+ }
100
+ byName.delete(tool.name)
101
+ }
102
+ for (const name of byName.keys()) differences.push(`${name} is new`)
103
+ return differences
104
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * How many times each bot's connection to Playwright MCP was opened in this
3
+ * process, so that the first result on a new connection says what it lost
4
+ * (element refs of earlier snapshots). State only.
5
+ */
6
+ export class BrowserConnections {
7
+ private readonly opened = new Map<string, number>()
8
+ private readonly unseen = new Set<string>()
9
+
10
+ /** A connection opened; every one after the first is a reconnection. */
11
+ connected(botId: string): void {
12
+ const count = (this.opened.get(botId) ?? 0) + 1
13
+ this.opened.set(botId, count)
14
+ if (count > 1) this.unseen.add(botId)
15
+ }
16
+
17
+ /** Whether the next result is the first since a reconnection (it then is not any more). */
18
+ takeReconnected(botId: string): boolean {
19
+ return this.unseen.delete(botId)
20
+ }
21
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The browser connector (docs/specs/bot-connectors.md, 9 and 15): the
3
+ * desktop's Google Chrome in the bot's environment, driven by Playwright
4
+ * MCP there over DevTools, for every session of the bot. It requires the
5
+ * desktop: the browser is the one on the screen a person watches.
6
+ */
7
+ import type { BotConnector } from "@1outres/dsh-bot-core"
8
+ import { BROWSER_CONNECTOR_ID, DESKTOP_CONNECTOR_ID } from "../shared/connector"
9
+ import { type GeneratedServer, offeredTools } from "./catalog"
10
+ import { BrowserConnections } from "./connections"
11
+ import type { McpClientDeps } from "./mcp/client"
12
+ import type { McpServer } from "./mcp/server"
13
+ import { createBrowserPreparation, type McpInstallation } from "./preparation"
14
+ import { browserAttachment } from "./session"
15
+ import { browserTools } from "./tools"
16
+
17
+ /** The least memory for Chrome's pages beside Playwright MCP's Node process. */
18
+ export const BROWSER_MIN_MEMORY_MIB = 3072
19
+
20
+ export interface BrowserConnectorDeps extends McpClientDeps {
21
+ readonly generated: GeneratedServer
22
+ readonly installation: McpInstallation
23
+ }
24
+
25
+ export function createBrowserConnector(deps: BrowserConnectorDeps): BotConnector<McpServer> {
26
+ const connections = new BrowserConnections()
27
+ return {
28
+ id: BROWSER_CONNECTOR_ID,
29
+ name: "Browser",
30
+ description: {
31
+ en: "The Google Chrome on the bot's desktop, which the bot drives with Playwright MCP in its VM (page snapshots, forms, screenshots). Needs the desktop.",
32
+ ja: "ボットのデスクトップの Google Chrome。ボットは VM の中の Playwright MCP で操作します(ページのスナップショット、フォーム、スクリーンショット)。デスクトップが必要です。",
33
+ },
34
+ sessions: "bot",
35
+ minimumSpec: { memoryMiB: BROWSER_MIN_MEMORY_MIB },
36
+ requires: [DESKTOP_CONNECTOR_ID],
37
+ creationOption: "workstation",
38
+ preparation: {
39
+ ...createBrowserPreparation(deps),
40
+ hint: {
41
+ en: "The browser is prepared after the desktop; the first time can take a minute.",
42
+ ja: "ブラウザはデスクトップのあとに準備されます。初回は 1 分ほどかかることがあります。",
43
+ },
44
+ },
45
+ attachment: browserAttachment({ ...deps, connections }),
46
+ tools: browserTools(offeredTools(deps.generated.tools), connections),
47
+ }
48
+ }
@@ -0,0 +1,190 @@
1
+ /**
2
+ * An MCP client over newline-delimited JSON-RPC 2.0 on a process's standard
3
+ * input and output (Playwright MCP's stdio transport in the bot's
4
+ * environment). Replies are matched by id; the server's own requests get
5
+ * an answer (ping) or "method not found"; notifications are ignored. A line
6
+ * longer than the limit, a line that is not JSON-RPC, or a stream that ends
7
+ * fails every open call.
8
+ */
9
+ import type { BotEnvironmentProcess } from "@1outres/dsh-bot-core"
10
+ import { McpProtocolError } from "./protocol"
11
+
12
+ export interface McpClientDeps {
13
+ /** A signal that aborts after `ms`. */
14
+ deadline(ms: number): AbortSignal
15
+ }
16
+
17
+ export interface McpRequestOptions {
18
+ readonly timeoutMs: number
19
+ readonly signal?: AbortSignal
20
+ }
21
+
22
+ export interface McpClient {
23
+ request(method: string, params: object, options: McpRequestOptions): Promise<unknown>
24
+ notify(method: string, params?: object): Promise<void>
25
+ /** Settles once the stream ended; every later request fails. */
26
+ readonly closed: Promise<void>
27
+ }
28
+
29
+ /** An error the server answered a request with. */
30
+ export class McpCallError extends Error {
31
+ constructor(
32
+ readonly code: number,
33
+ message: string,
34
+ ) {
35
+ super(message)
36
+ this.name = "McpCallError"
37
+ }
38
+ }
39
+
40
+ export class McpUnavailableError extends Error {
41
+ constructor(reason: string) {
42
+ super(`Playwright MCP is not reachable: ${reason}`)
43
+ this.name = "McpUnavailableError"
44
+ }
45
+ }
46
+
47
+ const NEWLINE = 0x0a
48
+ const METHOD_NOT_FOUND = -32601
49
+
50
+ interface Pending {
51
+ resolve(value: unknown): void
52
+ reject(error: Error): void
53
+ }
54
+
55
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
56
+ typeof value === "object" && value !== null && !Array.isArray(value)
57
+
58
+ export function createMcpClient(
59
+ process: Pick<BotEnvironmentProcess, "stdin" | "stdout">,
60
+ deps: McpClientDeps,
61
+ limits: { readonly maxLineBytes: number },
62
+ ): McpClient {
63
+ const pending = new Map<number, Pending>()
64
+ const encoder = new TextEncoder()
65
+ const decoder = new TextDecoder()
66
+ let nextId = 1
67
+ let failure: Error | undefined
68
+
69
+ const send = (message: object) =>
70
+ process.stdin.write(encoder.encode(`${JSON.stringify({ jsonrpc: "2.0", ...message })}\n`))
71
+
72
+ const failAll = (error: Error) => {
73
+ failure ??= error
74
+ for (const entry of pending.values()) entry.reject(failure)
75
+ pending.clear()
76
+ }
77
+
78
+ const answerRequest = (id: unknown, method: string) => {
79
+ if (typeof id !== "number" && typeof id !== "string") return
80
+ void send(
81
+ method === "ping"
82
+ ? { id, result: {} }
83
+ : { id, error: { code: METHOD_NOT_FOUND, message: `${method} is not supported` } },
84
+ ).catch(() => {})
85
+ }
86
+
87
+ const receive = (line: Uint8Array) => {
88
+ let message: unknown
89
+ try {
90
+ message = JSON.parse(decoder.decode(line))
91
+ } catch {
92
+ throw new McpProtocolError("a line that is not JSON")
93
+ }
94
+ if (!isRecord(message) || message.jsonrpc !== "2.0") {
95
+ throw new McpProtocolError("a line that is not JSON-RPC 2.0")
96
+ }
97
+ if (typeof message.method === "string") {
98
+ if ("id" in message) answerRequest(message.id, message.method)
99
+ return
100
+ }
101
+ if (typeof message.id !== "number") throw new McpProtocolError("a reply without a request id")
102
+ const entry = pending.get(message.id)
103
+ if (entry === undefined) return
104
+ pending.delete(message.id)
105
+ const { error } = message
106
+ if (error !== undefined) {
107
+ const code = isRecord(error) && typeof error.code === "number" ? error.code : 0
108
+ const text = isRecord(error) && typeof error.message === "string" ? error.message : "an error"
109
+ entry.reject(new McpCallError(code, text.slice(0, 4_000)))
110
+ } else if ("result" in message) {
111
+ entry.resolve(message.result)
112
+ } else {
113
+ entry.reject(new McpProtocolError("a reply without a result"))
114
+ }
115
+ }
116
+
117
+ const read = async () => {
118
+ let buffer = new Uint8Array(0)
119
+ for await (const chunk of process.stdout) {
120
+ const joined = new Uint8Array(buffer.byteLength + chunk.byteLength)
121
+ joined.set(buffer)
122
+ joined.set(chunk, buffer.byteLength)
123
+ buffer = joined
124
+ let start = 0
125
+ for (
126
+ let index = buffer.indexOf(NEWLINE);
127
+ index >= 0;
128
+ index = buffer.indexOf(NEWLINE, start)
129
+ ) {
130
+ receive(buffer.subarray(start, index))
131
+ start = index + 1
132
+ }
133
+ buffer = buffer.slice(start)
134
+ if (buffer.byteLength > limits.maxLineBytes) {
135
+ throw new McpProtocolError(`a line longer than ${limits.maxLineBytes} bytes`)
136
+ }
137
+ }
138
+ throw new McpUnavailableError("its process ended")
139
+ }
140
+
141
+ const closed = read().catch((error: unknown) => {
142
+ failAll(error instanceof Error ? error : new McpUnavailableError(String(error)))
143
+ })
144
+
145
+ return {
146
+ closed,
147
+ async notify(method, params) {
148
+ if (failure !== undefined) throw failure
149
+ await send(params === undefined ? { method } : { method, params })
150
+ },
151
+ async request(method, params, options) {
152
+ if (failure !== undefined) throw failure
153
+ const id = nextId++
154
+ const deadline = deps.deadline(options.timeoutMs)
155
+ const signal =
156
+ options.signal === undefined ? deadline : AbortSignal.any([deadline, options.signal])
157
+ const answer = new Promise<unknown>((resolve, reject) => {
158
+ pending.set(id, { resolve, reject })
159
+ signal.addEventListener(
160
+ "abort",
161
+ () => {
162
+ if (!pending.delete(id)) return
163
+ const reason = deadline.aborted
164
+ ? `${method} took longer than ${options.timeoutMs} ms`
165
+ : "cancelled"
166
+ void send({
167
+ method: "notifications/cancelled",
168
+ params: { requestId: id, reason },
169
+ }).catch(() => {})
170
+ reject(
171
+ deadline.aborted
172
+ ? new McpUnavailableError(reason)
173
+ : signal.reason instanceof Error
174
+ ? signal.reason
175
+ : new Error(reason),
176
+ )
177
+ },
178
+ { once: true },
179
+ )
180
+ })
181
+ try {
182
+ await send({ id, method, params })
183
+ } catch (error) {
184
+ pending.delete(id)
185
+ throw new McpUnavailableError(error instanceof Error ? error.message : String(error))
186
+ }
187
+ return answer
188
+ },
189
+ }
190
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * The part of the Model Context Protocol the connector speaks with
3
+ * Playwright MCP, and checks of what the server answers: it runs in the
4
+ * bot's environment, where the bot is root, so every answer is untrusted.
5
+ */
6
+ export const PROTOCOL_VERSION = "2025-06-18"
7
+
8
+ /** A tool as tools/list declares it. */
9
+ export interface McpTool {
10
+ readonly name: string
11
+ readonly description: string
12
+ readonly inputSchema: { readonly type: "object"; readonly [keyword: string]: unknown }
13
+ readonly annotations?: { readonly readOnlyHint?: boolean; readonly [hint: string]: unknown }
14
+ }
15
+
16
+ export type McpContent =
17
+ | { readonly type: "text"; readonly text: string }
18
+ | { readonly type: "image"; readonly data: string; readonly mimeType: string }
19
+
20
+ export interface McpCallResult {
21
+ readonly content: readonly McpContent[]
22
+ readonly isError: boolean
23
+ }
24
+
25
+ export class McpProtocolError extends Error {
26
+ constructor(message: string) {
27
+ super(`Playwright MCP answered something unexpected: ${message}`)
28
+ this.name = "McpProtocolError"
29
+ }
30
+ }
31
+
32
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
33
+ typeof value === "object" && value !== null && !Array.isArray(value)
34
+
35
+ export function parseTool(value: unknown, where: string): McpTool {
36
+ if (!isRecord(value)) throw new McpProtocolError(`${where} is not an object`)
37
+ const { name, description, inputSchema, annotations } = value
38
+ if (typeof name !== "string" || name === "") throw new McpProtocolError(`${where} has no name`)
39
+ if (typeof description !== "string") throw new McpProtocolError(`${name} has no description`)
40
+ if (!isRecord(inputSchema) || inputSchema.type !== "object") {
41
+ throw new McpProtocolError(`${name} has no object input schema`)
42
+ }
43
+ if (annotations !== undefined && !isRecord(annotations)) {
44
+ throw new McpProtocolError(`${name} has annotations that are not an object`)
45
+ }
46
+ return {
47
+ name,
48
+ description,
49
+ inputSchema: inputSchema as McpTool["inputSchema"],
50
+ ...(annotations === undefined ? {} : { annotations: annotations as McpTool["annotations"] }),
51
+ }
52
+ }
53
+
54
+ export function parseToolList(value: unknown): readonly McpTool[] {
55
+ if (!isRecord(value) || !Array.isArray(value.tools)) {
56
+ throw new McpProtocolError("tools/list has no tools")
57
+ }
58
+ if (value.nextCursor !== undefined) {
59
+ throw new McpProtocolError("tools/list answered in pages, which the connector does not read")
60
+ }
61
+ return value.tools.map((tool, index) => parseTool(tool, `tool ${index + 1}`))
62
+ }
63
+
64
+ export function parseCallResult(value: unknown): McpCallResult {
65
+ if (!isRecord(value) || !Array.isArray(value.content)) {
66
+ throw new McpProtocolError("a tool's result has no content")
67
+ }
68
+ if (value.isError !== undefined && typeof value.isError !== "boolean") {
69
+ throw new McpProtocolError("a tool's isError is not true or false")
70
+ }
71
+ const content = value.content.map((block, index): McpContent => {
72
+ if (!isRecord(block)) throw new McpProtocolError(`content ${index + 1} is not an object`)
73
+ if (block.type === "text" && typeof block.text === "string") {
74
+ return { type: "text", text: block.text }
75
+ }
76
+ if (
77
+ block.type === "image" &&
78
+ typeof block.data === "string" &&
79
+ typeof block.mimeType === "string"
80
+ ) {
81
+ return { type: "image", data: block.data, mimeType: block.mimeType }
82
+ }
83
+ throw new McpProtocolError(`content ${index + 1} is neither text nor an image`)
84
+ })
85
+ return { content, isError: value.isError === true }
86
+ }
87
+
88
+ /** The server's name and version from its initialize result. */
89
+ export function parseInitialize(value: unknown): {
90
+ readonly name: string
91
+ readonly version: string
92
+ } {
93
+ if (!isRecord(value) || !isRecord(value.serverInfo)) {
94
+ throw new McpProtocolError("initialize has no serverInfo")
95
+ }
96
+ const { name, version } = value.serverInfo
97
+ if (typeof name !== "string" || typeof version !== "string") {
98
+ throw new McpProtocolError("initialize has no server name and version")
99
+ }
100
+ if (typeof value.protocolVersion !== "string") {
101
+ throw new McpProtocolError("initialize has no protocol version")
102
+ }
103
+ return { name, version }
104
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Playwright MCP in the bot's environment: started over bot-core's
3
+ * environment access with the arguments its tools were generated with,
4
+ * attached to the desktop's Chrome over DevTools, and initialized.
5
+ */
6
+ import type { BotConnectorEnvironment } from "@1outres/dsh-bot-core"
7
+ import { CDP_ENDPOINT, MCP_CLI, OUTPUT_MAX_BYTES, outputDir, type VmUser } from "../vm/layout"
8
+ import { createMcpClient, type McpClientDeps } from "./client"
9
+ import {
10
+ type McpCallResult,
11
+ type McpTool,
12
+ PROTOCOL_VERSION,
13
+ parseCallResult,
14
+ parseInitialize,
15
+ parseToolList,
16
+ } from "./protocol"
17
+
18
+ /** The longest line the server may send (a full-page screenshot in base64). */
19
+ export const MAX_SERVER_LINE_BYTES = 48 << 20
20
+ const START_TIMEOUT_MS = 60_000
21
+ const LIST_TIMEOUT_MS = 30_000
22
+
23
+ export interface McpServer {
24
+ readonly server: { readonly name: string; readonly version: string }
25
+ listTools(signal: AbortSignal): Promise<readonly McpTool[]>
26
+ callTool(
27
+ name: string,
28
+ args: object,
29
+ options: { readonly signal: AbortSignal; readonly timeoutMs: number },
30
+ ): Promise<McpCallResult>
31
+ /** Settles when the server's process or its stream ended. */
32
+ readonly ended: Promise<unknown>
33
+ close(): void
34
+ }
35
+
36
+ /**
37
+ * The server's command line: `toolArguments` (what its tools were listed
38
+ * with), the desktop's Chrome, results without generated code, and file
39
+ * links (screenshots, snapshots) as absolute paths the bot can read.
40
+ */
41
+ export function serverArgv(user: VmUser, toolArguments: readonly string[]): readonly string[] {
42
+ return [
43
+ "node",
44
+ MCP_CLI,
45
+ ...toolArguments,
46
+ "--cdp-endpoint",
47
+ CDP_ENDPOINT,
48
+ "--codegen",
49
+ "none",
50
+ "--file-paths",
51
+ "absolute",
52
+ "--output-dir",
53
+ outputDir(user),
54
+ "--output-max-size",
55
+ String(OUTPUT_MAX_BYTES),
56
+ ]
57
+ }
58
+
59
+ export async function startServer(
60
+ environment: BotConnectorEnvironment,
61
+ user: VmUser,
62
+ toolArguments: readonly string[],
63
+ signal: AbortSignal,
64
+ deps: McpClientDeps,
65
+ ): Promise<McpServer> {
66
+ const process = await environment.spawn({ argv: serverArgv(user, toolArguments), signal })
67
+ const client = createMcpClient(process, deps, { maxLineBytes: MAX_SERVER_LINE_BYTES })
68
+ let server: McpServer["server"]
69
+ try {
70
+ server = parseInitialize(
71
+ await client.request(
72
+ "initialize",
73
+ {
74
+ protocolVersion: PROTOCOL_VERSION,
75
+ capabilities: {},
76
+ clientInfo: { name: "dsh-bot-connector-browser", version: "1" },
77
+ },
78
+ { timeoutMs: START_TIMEOUT_MS, signal },
79
+ ),
80
+ )
81
+ await client.notify("notifications/initialized")
82
+ } catch (error) {
83
+ process.terminate()
84
+ const log = process.stderr().trim()
85
+ const reason = error instanceof Error ? error.message : String(error)
86
+ throw new Error(log === "" ? reason : `${reason} (${log.split("\n").slice(-3).join("; ")})`)
87
+ }
88
+ return {
89
+ server,
90
+ async listTools(listSignal) {
91
+ return parseToolList(
92
+ await client.request("tools/list", {}, { timeoutMs: LIST_TIMEOUT_MS, signal: listSignal }),
93
+ )
94
+ },
95
+ async callTool(name, args, options) {
96
+ return parseCallResult(await client.request("tools/call", { name, arguments: args }, options))
97
+ },
98
+ ended: Promise.race([process.done, client.closed]),
99
+ close: () => process.terminate(),
100
+ }
101
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Making the bot's environment ready for the browser, one idempotent path
3
+ * (the desktop, which runs the Chrome it drives, is ready before: the
4
+ * connector requires it): Playwright MCP installed from the pinned
5
+ * npm-shrinkwrap.json when the installed one differs, the desktop's Chrome answering DevTools,
6
+ * and the server listing exactly the generated tools.
7
+ */
8
+ import type { BotConnectorContext, BotConnectorPreparation } from "@1outres/dsh-bot-core"
9
+ import { type GeneratedServer, toolDifferences } from "./catalog"
10
+ import type { McpClientDeps } from "./mcp/client"
11
+ import { startServer } from "./mcp/server"
12
+ import { readVmUser, run } from "./vm/commands"
13
+ import { CDP_ENDPOINT, MCP_DIR, MCP_SHRINKWRAP, stagingDir, type VmUser } from "./vm/layout"
14
+
15
+ /** The package's vm/ files the preparation installs from. */
16
+ export interface McpInstallation {
17
+ readonly packageJson: Uint8Array
18
+ readonly shrinkwrap: Uint8Array
19
+ /** vm/install-mcp.sh, which the base image build runs too. */
20
+ readonly script: Uint8Array
21
+ }
22
+
23
+ export interface BrowserPreparationDeps extends McpClientDeps {
24
+ readonly generated: GeneratedServer
25
+ readonly installation: McpInstallation
26
+ }
27
+
28
+ const INSTALL_TIMEOUT_MS = 15 * 60_000
29
+
30
+ /** What the desktop's Chrome says on DevTools' /json/version. @throws for anything but Chrome. */
31
+ export function chromeVersion(answer: string): string {
32
+ let parsed: unknown
33
+ try {
34
+ parsed = JSON.parse(answer)
35
+ } catch {
36
+ throw new Error(`${CDP_ENDPOINT} did not answer with JSON`)
37
+ }
38
+ const browser = (parsed as { Browser?: unknown } | null)?.Browser
39
+ if (typeof browser !== "string" || !/^Chrome\/[0-9.]+$/.test(browser)) {
40
+ throw new Error(`${CDP_ENDPOINT} is not Chrome's DevTools`)
41
+ }
42
+ return browser
43
+ }
44
+
45
+ export function createBrowserPreparation(deps: BrowserPreparationDeps): BotConnectorPreparation {
46
+ const decoder = new TextDecoder()
47
+
48
+ const install = async (context: BotConnectorContext, user: VmUser) => {
49
+ const stage = stagingDir(user)
50
+ const { signal, environment } = context
51
+ await run(environment, ["rm", "-rf", "--", stage], { signal })
52
+ await run(environment, ["mkdir", "-p", "-m", "0700", "--", stage], { signal })
53
+ const files: readonly [string, Uint8Array][] = [
54
+ ["package.json", deps.installation.packageJson],
55
+ ["npm-shrinkwrap.json", deps.installation.shrinkwrap],
56
+ ["install-mcp.sh", deps.installation.script],
57
+ ]
58
+ for (const [name, data] of files) {
59
+ await environment.writeFile(`${stage}/${name}`, data, { mode: 0o644, signal })
60
+ }
61
+ await run(environment, ["sudo", "-n", "sh", `${stage}/install-mcp.sh`, stage, MCP_DIR], {
62
+ signal,
63
+ timeoutMs: INSTALL_TIMEOUT_MS,
64
+ })
65
+ await run(environment, ["rm", "-rf", "--", stage], { signal })
66
+ }
67
+
68
+ const installed = async (context: BotConnectorContext) => {
69
+ const current = await run(context.environment, ["cat", "--", MCP_SHRINKWRAP], {
70
+ signal: context.signal,
71
+ accept: [0, 1],
72
+ maxOutputBytes: 4 << 20,
73
+ })
74
+ return current.exitCode === 0 && current.stdout === decoder.decode(deps.installation.shrinkwrap)
75
+ }
76
+
77
+ const checkTools = async (context: BotConnectorContext, user: VmUser) => {
78
+ const server = await startServer(
79
+ context.environment,
80
+ user,
81
+ deps.generated.arguments,
82
+ context.signal,
83
+ deps,
84
+ )
85
+ try {
86
+ const differences = toolDifferences(
87
+ deps.generated.tools,
88
+ await server.listTools(context.signal),
89
+ )
90
+ if (differences.length > 0) {
91
+ throw new Error(
92
+ `Playwright MCP in the bot's VM lists other tools than this connector was built with (${deps.generated.package} ${deps.generated.version}): ${differences.slice(0, 8).join(", ")}`,
93
+ )
94
+ }
95
+ } finally {
96
+ server.close()
97
+ }
98
+ }
99
+
100
+ return {
101
+ async prepare(context, progress) {
102
+ progress("reading the bot's account")
103
+ const user = await readVmUser(context.environment, context.signal)
104
+ progress("checking Playwright MCP")
105
+ if (!(await installed(context))) {
106
+ progress(`installing Playwright MCP ${deps.generated.version}`)
107
+ await install(context, user)
108
+ }
109
+ progress("checking the desktop's Chrome")
110
+ const answer = await run(
111
+ context.environment,
112
+ ["curl", "-sf", "--max-time", "10", `${CDP_ENDPOINT}/json/version`],
113
+ { signal: context.signal },
114
+ )
115
+ chromeVersion(answer.stdout)
116
+ progress("checking Playwright MCP's tools")
117
+ await checkTools(context, user)
118
+ },
119
+ }
120
+ }