-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
509 lines (406 loc) · 17.2 KB
/
Copy pathindex.ts
File metadata and controls
509 lines (406 loc) · 17.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
import { tool, type PluginInput, type PluginOptions } from "@opencode-ai/plugin"
import { chromium, type Page, type BrowserContext } from "playwright"
import path from "path"
import fs from "fs"
import os from "os"
const PROFILE_DIR = path.join(os.homedir(), ".opencode", "browser-profile")
interface BrowserState {
context: BrowserContext | null
pages: Map<string, Page>
currentPageId: string | null
pageCounter: number
refs: Map<string, Map<string, { role: string; name?: string; nth?: number }>>
headless: boolean
lastActivityTime: number
}
const state: BrowserState = {
context: null,
pages: new Map(),
currentPageId: null,
pageCounter: 0,
refs: new Map(),
headless: true,
lastActivityTime: 0,
}
const IDLE_TIMEOUT = 30 * 60 * 1000
let idleCheckInterval: Timer | null = null
function touchActivity() {
state.lastActivityTime = Date.now()
}
function startIdleWatchdog() {
if (idleCheckInterval) clearInterval(idleCheckInterval)
idleCheckInterval = setInterval(async () => {
if (!state.context) return
const idle = Date.now() - state.lastActivityTime
if (idle >= IDLE_TIMEOUT) {
await stopBrowser()
}
}, 60 * 1000)
}
function stopIdleWatchdog() {
if (idleCheckInterval) {
clearInterval(idleCheckInterval)
idleCheckInterval = null
}
}
interface BrowserResult {
success: boolean
error?: string
}
async function ensureBrowser(headless: boolean = true): Promise<BrowserResult> {
touchActivity()
if (state.context) {
if (!headless && state.headless) {
await stopBrowser()
} else {
startIdleWatchdog()
return { success: true }
}
}
try {
state.headless = headless
if (!fs.existsSync(PROFILE_DIR)) {
fs.mkdirSync(PROFILE_DIR, { recursive: true })
}
state.context = await chromium.launchPersistentContext(PROFILE_DIR, {
headless,
viewport: { width: 1280, height: 720 },
})
state.context.on("page", (page) => {
const pageId = nextPageId()
state.pages.set(pageId, page)
state.currentPageId = pageId
state.refs.set(pageId, new Map())
})
startIdleWatchdog()
return { success: true }
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
return { success: false, error: errorMessage }
}
}
async function stopBrowser(): Promise<void> {
stopIdleWatchdog()
if (state.context) {
await state.context.close()
}
state.context = null
state.pages.clear()
state.currentPageId = null
state.pageCounter = 0
state.refs.clear()
state.headless = true
}
function nextPageId(): string {
state.pageCounter++
return `page_${state.pageCounter}`
}
function getPage(pageId: string): Page | undefined {
return state.pages.get(pageId)
}
function getRefs(pageId: string): Map<string, { role: string; name?: string; nth?: number }> {
if (!state.refs.has(pageId)) {
state.refs.set(pageId, new Map())
}
return state.refs.get(pageId)!
}
async function getLocatorByRef(page: Page, pageId: string, ref: string) {
const refs = getRefs(pageId)
const info = refs.get(ref)
if (!info) return null
const locator = page.getByRole(info.role as any, { name: info.name })
return info.nth && info.nth > 0 ? locator.nth(info.nth) : locator
}
async function buildSnapshot(page: Page): Promise<{ snapshot: string; refs: string[] }> {
const snapshot = await page.locator("body").ariaSnapshot()
const refs = new Map<string, { role: string; name?: string; nth?: number }>()
const lines = snapshot.split("\n")
const counter = { value: 0 }
const roleCounts = new Map<string, number>()
const processedLines = lines.map((line) => {
const match = line.match(/^(\s*)-\s*(\w+)(?:\s+"([^"]*)")?/)
if (!match) return line
const [, indent, role, name] = match
const roleKey = `${role}:${name || ""}`
const count = roleCounts.get(roleKey) || 0
roleCounts.set(roleKey, count + 1)
const interactiveRoles = [
"button", "link", "textbox", "checkbox", "radio", "combobox",
"listbox", "menuitem", "searchbox", "slider", "switch", "tab",
]
if (interactiveRoles.includes(role.toLowerCase())) {
counter.value++
const ref = `e${counter.value}`
refs.set(ref, { role: role.toLowerCase(), name, nth: count > 0 ? count : undefined })
let processed = `${indent}- ${role}`
if (name) processed += ` "${name}"`
processed += ` [ref=${ref}]`
if (count > 0) processed += ` [nth=${count}]`
return processed
}
return line
})
const pageId = state.currentPageId || "default"
state.refs.set(pageId, refs)
return {
snapshot: processedLines.join("\n"),
refs: Array.from(refs.keys()),
}
}
function resolvePageId(args: { page_id?: string }) {
return args.page_id || state.currentPageId || "default"
}
function resolvePage(pageId: string): Page | string {
const page = getPage(pageId)
if (!page) return "Error: Page not found"
return page
}
export default {
id: "browser",
async server(input: PluginInput, options?: PluginOptions) {
return {
tool: {
browser: tool({
description: `Control a web browser using Playwright. Actions: start, stop, open, navigate, snapshot, screenshot, click, type, evaluate, wait.
Workflow:
1. start (headed=true for visible window)
2. open url
3. snapshot to get element refs
4. click/type using refs
5. stop when done
Use ref from snapshot for stable element targeting. Multiple tabs supported via page_id.`,
args: {
action: tool.schema.string().describe("Action: start, stop, open, navigate, snapshot, screenshot, click, type, evaluate, wait, close, back"),
url: tool.schema.string().optional().describe("URL to open or navigate to"),
page_id: tool.schema.string().optional().default("default").describe("Page/tab identifier (default: 'default')"),
ref: tool.schema.string().optional().describe("Element ref from snapshot (preferred over selector)"),
selector: tool.schema.string().optional().describe("CSS selector (use ref when possible)"),
text: tool.schema.string().optional().describe("Text to type"),
code: tool.schema.string().optional().describe("JavaScript code to evaluate"),
path: tool.schema.string().optional().describe("File path for screenshot"),
wait: tool.schema.number().optional().default(0).describe("Milliseconds to wait"),
full_page: tool.schema.boolean().optional().default(false).describe("Full page screenshot"),
headed: tool.schema.boolean().optional().default(false).describe("Show visible browser window"),
submit: tool.schema.boolean().optional().default(false).describe("Press Enter after typing"),
slowly: tool.schema.boolean().optional().default(false).describe("Type character by character"),
timeout: tool.schema.number().optional().default(30000).describe("Timeout in milliseconds"),
},
async execute(args, context) {
const action = args.action.toLowerCase().trim()
try {
touchActivity()
if (action === "start") {
const headless = !(args.headed ?? false)
const result = await ensureBrowser(headless)
if (!result.success) {
return `Failed to start browser: ${result.error}. Make sure Playwright is installed: bunx playwright install chromium`
}
return `Browser started (${args.headed ? "visible window" : "headless"})`
}
if (action === "stop") {
await stopBrowser()
return "Browser stopped"
}
if (action === "open") {
if (!args.url) return "Error: url required for open action"
const result = await ensureBrowser()
if (!result.success) {
return `Error: Failed to start browser: ${result.error}`
}
const pageId = args.page_id || nextPageId()
const page = await state.context!.newPage()
state.pages.set(pageId, page)
state.currentPageId = pageId
state.refs.set(pageId, new Map())
await page.goto(args.url, { timeout: args.timeout })
return `Opened ${args.url} (page_id: ${pageId})`
}
if (action === "navigate") {
if (!args.url) return "Error: url required for navigate action"
const page = resolvePage(resolvePageId(args))
if (typeof page === "string") return page
await page.goto(args.url, { timeout: args.timeout })
return `Navigated to ${args.url}`
}
if (action === "back") {
const page = resolvePage(resolvePageId(args))
if (typeof page === "string") return page
await page.goBack({ timeout: args.timeout })
return "Navigated back"
}
if (action === "snapshot") {
const page = resolvePage(resolvePageId(args))
if (typeof page === "string") return page
const result = await buildSnapshot(page)
let output = `Page: ${page.url()}\n\n`
output += `Interactive Elements:\n${result.snapshot}\n\n`
output += `Available refs: ${result.refs.join(", ")}`
if (args.path) {
const filePath = path.isAbsolute(args.path)
? args.path
: path.join(context.directory, args.path)
await fs.promises.writeFile(filePath, output, "utf-8")
output += `\n\nSnapshot saved to: ${args.path}`
}
return output
}
if (action === "screenshot") {
const pageId = resolvePageId(args)
const page = resolvePage(pageId)
if (typeof page === "string") return page
const screenshotPath = args.path || `screenshot-${Date.now()}.png`
const filePath = path.isAbsolute(screenshotPath)
? screenshotPath
: path.join(context.directory, screenshotPath)
if (args.ref) {
const locator = await getLocatorByRef(page, pageId, args.ref)
if (!locator) return `Error: Ref '${args.ref}' not found`
await locator.screenshot({ path: filePath })
} else {
await page.screenshot({ path: filePath, fullPage: args.full_page })
}
return `Screenshot saved to ${screenshotPath}`
}
if (action === "click") {
const pageId = resolvePageId(args)
const page = resolvePage(pageId)
if (typeof page === "string") return page
if (!args.ref && !args.selector) {
return "Error: ref or selector required for click"
}
const locator = args.ref
? await getLocatorByRef(page, pageId, args.ref)
: page.locator(args.selector!).first()
if (!locator) return `Error: Ref '${args.ref}' not found`
await locator.click({ timeout: args.timeout })
if (args.wait && args.wait > 0) {
await page.waitForTimeout(args.wait)
}
return `Clicked ${args.ref || args.selector}`
}
if (action === "type") {
const pageId = resolvePageId(args)
const page = resolvePage(pageId)
if (typeof page === "string") return page
if (!args.ref && !args.selector) {
return "Error: ref or selector required for type"
}
if (!args.text) {
return "Error: text required for type action"
}
const locator = args.ref
? await getLocatorByRef(page, pageId, args.ref)
: page.locator(args.selector!).first()
if (!locator) return `Error: Ref '${args.ref}' not found`
if (args.slowly) {
await locator.pressSequentially(args.text)
} else {
await locator.fill(args.text)
}
if (args.submit) {
await locator.press("Enter")
}
return `Typed into ${args.ref || args.selector}`
}
if (action === "evaluate" || action === "eval") {
const page = resolvePage(resolvePageId(args))
if (typeof page === "string") return page
if (!args.code) return "Error: code required for evaluate"
const result = await page.evaluate(args.code)
return `Result: ${JSON.stringify(result, null, 2)}`
}
if (action === "wait") {
const page = resolvePage(resolvePageId(args))
if (typeof page === "string") return page
if (args.wait && args.wait > 0) {
await page.waitForTimeout(args.wait)
return `Waited ${args.wait}ms`
}
await page.waitForLoadState("networkidle", { timeout: args.timeout })
return "Waited for network idle"
}
if (action === "close") {
const pageId = args.page_id || state.currentPageId
if (!pageId) return "Error: No page to close"
const page = getPage(pageId)
if (!page) return "Error: Page not found"
await page.close()
state.pages.delete(pageId)
state.refs.delete(pageId)
if (state.currentPageId === pageId) {
state.currentPageId = state.pages.keys().next().value || null
}
return `Closed page ${pageId}`
}
return `Error: Unknown action '${action}'. Available: start, stop, open, navigate, back, snapshot, screenshot, click, type, evaluate, wait, close`
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
return `Error: ${errorMessage}`
}
},
}),
browser_start: tool({
description: "Start browser in visible mode (headed) for debugging or demos",
args: {
headed: tool.schema.boolean().default(true).describe("Show visible browser window"),
},
async execute(args) {
const headless = !args.headed
const result = await ensureBrowser(headless)
return result.success
? `Browser started in ${args.headed ? "visible" : "headless"} mode`
: `Failed to start browser: ${result.error}`
},
}),
browser_snapshot: tool({
description: "Take a snapshot of the current page to get interactive element refs",
args: {
page_id: tool.schema.string().optional().describe("Page ID (optional)"),
},
async execute(args) {
const pageId = args.page_id || state.currentPageId || "default"
const page = getPage(pageId)
if (!page) return "Error: Page not found. Open a page first."
const result = await buildSnapshot(page)
return `Page: ${page.url()}\n\n${result.snapshot}\n\nRefs: ${result.refs.join(", ")}`
},
}),
browser_click: tool({
description: "Click an element using ref from snapshot",
args: {
ref: tool.schema.string().describe("Element ref from snapshot"),
page_id: tool.schema.string().optional().describe("Page ID (optional)"),
},
async execute(args) {
const pageId = args.page_id || state.currentPageId || "default"
const page = getPage(pageId)
if (!page) return "Error: Page not found"
const locator = await getLocatorByRef(page, pageId, args.ref)
if (!locator) return `Error: Ref '${args.ref}' not found`
await locator.click()
return `Clicked ${args.ref}`
},
}),
browser_type: tool({
description: "Type text into an element using ref from snapshot",
args: {
ref: tool.schema.string().describe("Element ref from snapshot"),
text: tool.schema.string().describe("Text to type"),
submit: tool.schema.boolean().optional().default(false).describe("Press Enter after typing"),
page_id: tool.schema.string().optional().describe("Page ID (optional)"),
},
async execute(args) {
const pageId = args.page_id || state.currentPageId || "default"
const page = getPage(pageId)
if (!page) return "Error: Page not found"
const locator = await getLocatorByRef(page, pageId, args.ref)
if (!locator) return `Error: Ref '${args.ref}' not found`
await locator.fill(args.text)
if (args.submit) await locator.press("Enter")
return `Typed into ${args.ref}`
},
}),
},
}
},
}