opencode-apex 0.1.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,811 @@
1
+ /**
2
+ * Ejecutor de Browser.Action contra el Chromium externo.
3
+ *
4
+ * Cada handler devuelve un valor JSON-serializable que el servidor valida contra
5
+ * el schema de salida de la operación. Cuando no sabemos hacerlo, fallamos con
6
+ * `unsupported` en vez de colgar el comando: el plugin-browser tiene timeout de
7
+ * 60s y una respuesta honesta es mejor que un silencio.
8
+ */
9
+
10
+ import { randomUUID } from "node:crypto"
11
+ import { mkdtemp, writeFile } from "node:fs/promises"
12
+ import { tmpdir } from "node:os"
13
+ import { join } from "node:path"
14
+ import { Browser } from "@opencode/plugin-browser/rpc"
15
+ import { CdpClient, CdpError, EventCollector, TabRegistry, type LiveTab } from "./cdp.js"
16
+
17
+ const MAX_TEXT = 100_000
18
+
19
+ const unsupported = (op: string) =>
20
+ new CdpError(
21
+ `The external browser bridge does not implement browser.${op}. ` +
22
+ `It drives a Chromium over CDP; this one needs a desktop Review pane or an analyzer runtime.`,
23
+ { code: "unsupported" },
24
+ )
25
+
26
+ export interface ActionContext {
27
+ readonly cdp: CdpClient
28
+ readonly tabs: TabRegistry
29
+ readonly collectors: EventCollector
30
+ readonly command: Browser.Command
31
+ }
32
+
33
+ /** El `__file` se extrae aparte: los bytes van en `files`, no en `value`. */
34
+ export interface FilePayload {
35
+ readonly name: string
36
+ readonly mime: string
37
+ readonly data: Uint8Array
38
+ }
39
+
40
+ export type ActionResult = Record<string, unknown> & { __file?: FilePayload }
41
+
42
+ export async function executeAction(action: Browser.Action, ctx: ActionContext): Promise<ActionResult> {
43
+ const { cdp, tabs, collectors, command } = ctx
44
+ const tab = async (id: string) => publicTab((await tabs.list()).find((t) => t.id === id))
45
+
46
+ switch (action.type) {
47
+ // ---------------------------------------------------------------- tabs
48
+ case "tabs.list": {
49
+ const list = await tabs.list()
50
+ return { tabs: list.map(publicTab), focusedTabID: list[0]?.id ?? null }
51
+ }
52
+
53
+ case "tabs.open": {
54
+ const { id } = await tabs.createTarget(action.url ?? "about:blank")
55
+ await waitForLoad(cdp, tabs, id)
56
+ // Los colectores deben engancharse ANTES de que ocurra nada: console y
57
+ // red son flujos y si nos suscribimos al leer, lo que pasó antes se perdió.
58
+ await collectors.attach(await tabs.attach(id))
59
+ return await tab(id)
60
+ }
61
+
62
+ case "tabs.focus": {
63
+ const sessionId = await tabs.attach(action.tabID)
64
+ await cdp.send("Page.bringToFront", {}, sessionId)
65
+ return await tab(action.tabID)
66
+ }
67
+
68
+ case "tabs.close": {
69
+ await tabs.closeTarget(action.tabID)
70
+ const list = await tabs.list()
71
+ return { tabs: list.map(publicTab), focusedTabID: list[0]?.id ?? null }
72
+ }
73
+
74
+ case "preview":
75
+ // Requiere el panel de review de una app desktop; un cliente CDP sin
76
+ // ventana no tiene a quién mostrárselo.
77
+ throw unsupported("preview")
78
+
79
+ // ----------------------------------------------------------- navegación
80
+ case "navigate": {
81
+ const sessionId = await tabs.attach(action.tabID)
82
+ await collectors.attach(sessionId)
83
+ await cdp.send("Page.navigate", { url: action.url }, sessionId)
84
+ await waitForLoad(cdp, tabs, action.tabID)
85
+ return await tab(action.tabID)
86
+ }
87
+
88
+ case "back":
89
+ case "forward":
90
+ case "reload":
91
+ case "stop": {
92
+ const sessionId = await tabs.attach(action.tabID)
93
+ if (action.type === "back" || action.type === "forward") {
94
+ const { entries, currentIndex } = await cdp.send("Page.getNavigationHistory", {}, sessionId)
95
+ const entry = entries[action.type === "back" ? currentIndex - 1 : currentIndex + 1]
96
+ if (entry) {
97
+ await cdp.send("Page.navigateToHistoryEntry", { entryId: entry.id }, sessionId)
98
+ await waitForLoad(cdp, tabs, action.tabID)
99
+ }
100
+ } else {
101
+ await cdp.send(action.type === "reload" ? "Page.reload" : "Page.stopLoading", {}, sessionId)
102
+ }
103
+ return await tab(action.tabID)
104
+ }
105
+
106
+ case "frames": {
107
+ const sessionId = await tabs.attach(action.tabID)
108
+ const { frameTree } = await cdp.send("Page.getFrameTree", {}, sessionId)
109
+ const frames: Array<{ id: string; parentID?: string; url: string; name: string }> = []
110
+ const walk = (node: any, parentID?: string) => {
111
+ frames.push({ id: node.frame.id, parentID, url: node.frame.url, name: node.frame.name ?? "" })
112
+ for (const child of node.childFrames ?? []) walk(child, node.frame.id)
113
+ }
114
+ walk(frameTree)
115
+ return { tab: await tab(action.tabID), frames }
116
+ }
117
+
118
+ // ------------------------------------------------------------ inspección
119
+ case "snapshot":
120
+ case "find": {
121
+ const sessionId = await tabs.attach(action.tabID)
122
+ const { nodes } = await cdp.send("Accessibility.getFullAXTree", {}, sessionId)
123
+ const needle = action.type === "find" ? action.text.toLowerCase() : undefined
124
+ const maxDepth = action.type === "snapshot" ? (action.depth ?? 20) : 20
125
+ // Los refs se renumeran en cada snapshot: son válidos hasta la siguiente
126
+ // navegación o el siguiente snapshot, que es justo lo que promete el schema.
127
+ refs.reset(action.tabID)
128
+ const lines: string[] = []
129
+ // getFullAXTree devuelve la lista plana; `depth` es distancia a la raíz,
130
+ // así que hay que reconstruirla desde childIds en vez de contar líneas.
131
+ const byID = new Map<string, { depth: number; node: any }>()
132
+ const depthOf = (node: any, seen = new Set<string>()): number => {
133
+ const cached = byID.get(node.nodeId)
134
+ if (cached) return cached.depth
135
+ if (!node.parentId || seen.has(node.nodeId)) return 0
136
+ const parent = nodes.find((n: any) => n.nodeId === node.parentId)
137
+ if (!parent) return 0
138
+ seen.add(node.nodeId)
139
+ const depth = depthOf(parent, seen) + 1
140
+ byID.set(node.nodeId, { depth, node })
141
+ return depth
142
+ }
143
+
144
+ for (const node of nodes as Array<any>) {
145
+ const role = node.role?.value
146
+ const name = node.name?.value ?? ""
147
+ if (!role || role === "none" || role === "generic" || role === "presentation") continue
148
+ if (!name) continue
149
+ if (depthOf(node) > maxDepth) continue
150
+ if (needle !== undefined && !name.toLowerCase().includes(needle)) continue
151
+ lines.push(`${refs.mint(action.tabID, node.backendDOMNodeId)} ${role} "${name}"`)
152
+ }
153
+
154
+ const content = lines.join("\n")
155
+ return {
156
+ tab: await tab(action.tabID),
157
+ content: content.slice(0, MAX_TEXT),
158
+ truncated: content.length > MAX_TEXT,
159
+ }
160
+ }
161
+
162
+ case "evaluate": {
163
+ const sessionId = await tabs.attach(action.tabID)
164
+ // Con `ref` el contrato pide una FUNCIÓN que recibe el elemento, no una
165
+ // expresión: se ejecuta con callFunctionOn sobre el nodo resuelto.
166
+ const result = action.ref
167
+ ? await cdp.send(
168
+ "Runtime.callFunctionOn",
169
+ {
170
+ objectId: (await cdp.send("DOM.resolveNode", { backendNodeId: refs.resolve(action.tabID, action.ref) }, sessionId))
171
+ .object.objectId,
172
+ functionDeclaration: action.script,
173
+ returnByValue: true,
174
+ awaitPromise: true,
175
+ },
176
+ sessionId,
177
+ )
178
+ : await cdp.send(
179
+ "Runtime.evaluate",
180
+ { expression: action.script, returnByValue: true, awaitPromise: true },
181
+ sessionId,
182
+ )
183
+ if (result.exceptionDetails) {
184
+ throw new CdpError(result.exceptionDetails.exception?.description ?? "evaluate threw", {
185
+ code: "evaluate_failed",
186
+ })
187
+ }
188
+ return { tab: await tab(action.tabID), value: result.result?.value ?? null }
189
+ }
190
+
191
+ // ------------------------------------------------------------ interacción
192
+ case "click": {
193
+ const sessionId = await tabs.attach(action.tabID)
194
+ const box = await refBox(ctx, action.tabID, action.ref, sessionId)
195
+ const common = {
196
+ x: box.x,
197
+ y: box.y,
198
+ button: action.button ?? "left",
199
+ clickCount: action.count ?? 1,
200
+ modifiers: toModifiers(action.modifiers ?? []),
201
+ }
202
+ await cdp.send("Input.dispatchMouseEvent", { type: "mousePressed", ...common }, sessionId)
203
+ await cdp.send("Input.dispatchMouseEvent", { type: "mouseReleased", ...common }, sessionId)
204
+ await waitForLoad(cdp, tabs, action.tabID)
205
+ return await tab(action.tabID)
206
+ }
207
+
208
+ case "hover": {
209
+ const sessionId = await tabs.attach(action.tabID)
210
+ const box = await refBox(ctx, action.tabID, action.ref, sessionId)
211
+ await cdp.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: box.x, y: box.y }, sessionId)
212
+ return await tab(action.tabID)
213
+ }
214
+
215
+ case "drag": {
216
+ const sessionId = await tabs.attach(action.tabID)
217
+ const from = await refBox(ctx, action.tabID, action.from, sessionId)
218
+ const to = await refBox(ctx, action.tabID, action.to, sessionId)
219
+ await cdp.send("Input.dispatchMouseEvent", { type: "mousePressed", x: from.x, y: from.y, button: "left", clickCount: 1 }, sessionId)
220
+ await cdp.send("Input.dispatchMouseEvent", { type: "mouseMoved", x: to.x, y: to.y, button: "left" }, sessionId)
221
+ await cdp.send("Input.dispatchMouseEvent", { type: "mouseReleased", x: to.x, y: to.y, button: "left" }, sessionId)
222
+ return await tab(action.tabID)
223
+ }
224
+
225
+ case "fill": {
226
+ const sessionId = await tabs.attach(action.tabID)
227
+ await fillNode(ctx, action.tabID, action.ref, sessionId, action.text)
228
+ return await tab(action.tabID)
229
+ }
230
+
231
+ case "fill_form": {
232
+ const sessionId = await tabs.attach(action.tabID)
233
+ for (const field of action.fields) {
234
+ if (field.type === "text") await fillNode(ctx, action.tabID, field.ref, sessionId, field.value)
235
+ if (field.type === "check") await checkNode(ctx, action.tabID, field.ref, sessionId, field.checked)
236
+ if (field.type === "select") await selectNode(ctx, action.tabID, field.ref, sessionId, field.values)
237
+ }
238
+ return await tab(action.tabID)
239
+ }
240
+
241
+ case "select": {
242
+ const sessionId = await tabs.attach(action.tabID)
243
+ await selectNode(ctx, action.tabID, action.ref, sessionId, action.values)
244
+ return await tab(action.tabID)
245
+ }
246
+
247
+ case "check": {
248
+ const sessionId = await tabs.attach(action.tabID)
249
+ await checkNode(ctx, action.tabID, action.ref, sessionId, action.checked)
250
+ return await tab(action.tabID)
251
+ }
252
+
253
+ case "press": {
254
+ const sessionId = await tabs.attach(action.tabID)
255
+ await sendKey(cdp, action.key, sessionId)
256
+ return await tab(action.tabID)
257
+ }
258
+
259
+ case "scroll": {
260
+ const sessionId = await tabs.attach(action.tabID)
261
+ await cdp.send(
262
+ "Input.dispatchMouseEvent",
263
+ { type: "mouseWheel", x: 100, y: 100, deltaX: action.deltaX ?? 0, deltaY: action.deltaY },
264
+ sessionId,
265
+ )
266
+ return await tab(action.tabID)
267
+ }
268
+
269
+ case "wait": {
270
+ const sessionId = await tabs.attach(action.tabID)
271
+ if (action.condition === "load") {
272
+ await waitForLoad(cdp, tabs, action.tabID)
273
+ return await tab(action.tabID)
274
+ }
275
+ const deadline = Date.now() + (action.timeoutMs ?? 10_000)
276
+ while (Date.now() < deadline) {
277
+ const present = await textPresence(cdp, action.text, sessionId)
278
+ if (action.condition === "text" && present) break
279
+ if (action.condition === "textGone" && !present) break
280
+ await sleep(150)
281
+ }
282
+ return await tab(action.tabID)
283
+ }
284
+
285
+ // -------------------------------------------------------------- capturas
286
+ case "screenshot": {
287
+ const sessionId = await tabs.attach(action.tabID)
288
+ const format = action.format ?? "png"
289
+ const params: Record<string, unknown> = { format }
290
+ if (format !== "png" && action.quality !== undefined) params.quality = action.quality
291
+ if (action.fullPage) params.captureBeyondViewport = true
292
+ if (action.maxWidth !== undefined) params.clip = await fitClip(ctx, action.tabID, action.ref, sessionId, action.maxWidth)
293
+ const { data } = await cdp.send("Page.captureScreenshot", params, sessionId)
294
+ return {
295
+ tab: await tab(action.tabID),
296
+ files: [{ id: newFileID(), name: `screenshot.${format}`, mime: mimeFor(format), bytes: data.length * 3 / 4, path: "" }],
297
+ __file: { name: `screenshot.${format}`, mime: mimeFor(format), data: base64ToBytes(data) },
298
+ }
299
+ }
300
+
301
+ case "console": {
302
+ const sessionId = await tabs.attach(action.tabID)
303
+ await collectors.attach(sessionId)
304
+ const all = collectors.consoleMessages(sessionId)
305
+ const min = LEVEL_ORDER[action.level ?? "debug"] ?? 0
306
+ const filtered = all.filter((m) => (LEVEL_ORDER[m.level] ?? 1) >= min)
307
+ const shown = filtered.slice(-(action.limit ?? 100))
308
+ return {
309
+ tab: await tab(action.tabID),
310
+ messages: shown,
311
+ truncated: filtered.length > shown.length,
312
+ dropped: Math.max(0, filtered.length - shown.length),
313
+ }
314
+ }
315
+
316
+ case "network.list": {
317
+ const sessionId = await tabs.attach(action.tabID)
318
+ await collectors.attach(sessionId)
319
+ let all = collectors.requests(sessionId)
320
+ const needle = action.urlContains
321
+ if (needle !== undefined) all = all.filter((r) => r.url.includes(needle))
322
+ if (action.resourceType) all = all.filter((r) => r.resourceType === action.resourceType)
323
+ const shown = all.slice(-(action.limit ?? 100))
324
+ return {
325
+ tab: await tab(action.tabID),
326
+ requests: shown.map(publicRequest),
327
+ truncated: all.length > shown.length,
328
+ dropped: Math.max(0, all.length - shown.length),
329
+ }
330
+ }
331
+
332
+ case "network.get": {
333
+ const sessionId = await tabs.attach(action.tabID)
334
+ await collectors.attach(sessionId)
335
+ const request = collectors.requests(sessionId).find((r) => r.id === action.id)
336
+ if (!request) {
337
+ throw new CdpError(
338
+ `Request ${action.id} is not in this capture. Call browser.network.list({ tabID }) for exact IDs; ` +
339
+ `IDs expire on navigation or eviction.`,
340
+ { code: "network_request_not_found" },
341
+ )
342
+ }
343
+ const bodies = collectors.requestBody(sessionId, action.id)
344
+ const maxChars = action.maxBodyChars ?? 2_000
345
+ return {
346
+ tab: await tab(action.tabID),
347
+ request: publicRequest(request),
348
+ requestHeaders: toHeaders(bodies?.request?.headers),
349
+ responseHeaders: toHeaders(bodies?.response?.headers),
350
+ headersTruncated: false,
351
+ requestBody: bodyState(action.includeBody, bodies?.postData, maxChars),
352
+ responseBody: bodyState(action.includeBody, bodies?.response?.bodyText, maxChars),
353
+ }
354
+ }
355
+
356
+ // -------------------------------------------------------------- ficheros
357
+ case "files.upload":
358
+ case "files.drop": {
359
+ const sessionId = await tabs.attach(action.tabID)
360
+ const attached = await materialize(command.files)
361
+ if (attached.length === 0) {
362
+ throw new CdpError("No file bytes were attached to this command.", { code: "no_files" })
363
+ }
364
+ const nodeId = refs.resolve(action.tabID, action.ref)
365
+ const { object } = await cdp.send("DOM.resolveNode", { backendNodeId: nodeId }, sessionId)
366
+ if (!object?.objectId) throw new CdpError(`Could not resolve ${action.ref}`, { code: "ref_unavailable" })
367
+ // CDP solo acepta rutas locales: los bytes del RPC se materializan aquí.
368
+ await cdp.send("DOM.setFileInputFiles", { files: [attached[0]!.path], objectId: object.objectId }, sessionId)
369
+ return await tab(action.tabID)
370
+ }
371
+
372
+ case "files.list": {
373
+ const sessionId = await tabs.attach(action.tabID)
374
+ await collectors.attach(sessionId)
375
+ return {
376
+ tab: await tab(action.tabID),
377
+ files: collectors.downloads(sessionId).map((f) => ({
378
+ id: f.id,
379
+ name: f.name,
380
+ mime: f.mime,
381
+ bytes: f.bytes ?? 0,
382
+ state: f.state,
383
+ })),
384
+ }
385
+ }
386
+
387
+ case "files.get": {
388
+ const sessionId = await tabs.attach(action.tabID)
389
+ await collectors.attach(sessionId)
390
+ const found = collectors.downloads(sessionId).find((f) => f.id === action.fileID)
391
+ if (!found) {
392
+ throw new CdpError(
393
+ `File ${action.fileID} is not owned by this tab. Call browser.files.list({ tabID }) for exact IDs.`,
394
+ { code: "file_not_found" },
395
+ )
396
+ }
397
+ if (found.state !== "completed") {
398
+ throw new CdpError(`File ${found.name} is ${found.state}, not completed.`, { code: "file_not_ready" })
399
+ }
400
+ return {
401
+ tab: await tab(action.tabID),
402
+ files: [{ id: found.id, name: found.name, mime: found.mime, bytes: found.bytes ?? 0, path: "" }],
403
+ __file: { name: found.name, mime: found.mime, data: base64ToBytes(found.__data ?? "") },
404
+ }
405
+ }
406
+
407
+ // -------------------------------------------------------------- diálogos
408
+ case "dialog": {
409
+ const sessionId = await tabs.attach(action.tabID)
410
+ await collectors.attach(sessionId)
411
+ if (action.action === "get") return { tab: await tab(action.tabID), dialog: collectors.dialog(sessionId) }
412
+ if (!collectors.dialog(sessionId)) throw new CdpError("This tab has no open dialog.", { code: "no_dialog" })
413
+ await cdp.send(
414
+ "Page.handleJavaScriptDialog",
415
+ { accept: action.action === "accept", promptText: action.promptText ?? "" },
416
+ sessionId,
417
+ )
418
+ return { tab: await tab(action.tabID), dialog: null }
419
+ }
420
+
421
+ // ------------------------------------------------------------ performance
422
+ case "trace.start": {
423
+ await startTrace(cdp, action.tabID, action.durationMs ?? 10_000)
424
+ return { tab: await tab(action.tabID), recording: true }
425
+ }
426
+
427
+ case "trace.stop": {
428
+ const stopped = await stopTrace(cdp)
429
+ const tabID = stopped.tabID ?? action.tabID
430
+ return {
431
+ tab: await tab(tabID),
432
+ files: stopped.data
433
+ ? [{ id: newFileID(), name: "trace.json.gz", mime: "application/gzip", bytes: stopped.bytes, path: "" }]
434
+ : [],
435
+ durationMs: stopped.durationMs,
436
+ incomplete: stopped.incomplete,
437
+ ...(stopped.data ? { __file: { name: "trace.json.gz", mime: "application/gzip", data: base64ToBytes(stopped.data) } } : {}),
438
+ }
439
+ }
440
+
441
+ case "cpu.start": {
442
+ const sessionId = await tabs.attach(action.tabID)
443
+ await cdp.send("Profiler.enable", {}, sessionId)
444
+ await cdp.send("Profiler.setSamplingInterval", { interval: 1_000 }, sessionId)
445
+ await cdp.send("Profiler.start", {}, sessionId)
446
+ cdp.traces.cpu.set(action.tabID, sessionId)
447
+ return { tab: await tab(action.tabID), recording: true }
448
+ }
449
+
450
+ case "cpu.stop": {
451
+ const sessionId = cdp.traces.cpu.get(action.tabID)
452
+ if (!sessionId) throw new CdpError("No CPU recording is running for this tab.", { code: "not_recording" })
453
+ const { profile } = await cdp.send("Profiler.stop", {}, sessionId)
454
+ cdp.traces.cpu.delete(action.tabID)
455
+ const json = JSON.stringify(profile ?? {})
456
+ return {
457
+ tab: await tab(action.tabID),
458
+ files: [{ id: newFileID(), name: "cpu.cpuprofile", mime: "application/json", bytes: json.length, path: "" }],
459
+ durationMs: profile?.endTime && profile?.startTime ? profile.endTime - profile.startTime : 0,
460
+ __file: { name: "cpu.cpuprofile", mime: "application/json", data: new TextEncoder().encode(json) },
461
+ }
462
+ }
463
+
464
+ // -------------------------------------------------------------- memoria
465
+ case "heap.snapshot": {
466
+ const sessionId = await tabs.attach(action.tabID)
467
+ const chunks: string[] = []
468
+ const off = cdp.on(`${sessionId}:HeapProfiler.addHeapSnapshotChunk`, (params: any) => {
469
+ if (params.chunk) chunks.push(params.chunk)
470
+ })
471
+ await cdp.send("HeapProfiler.enable", {}, sessionId)
472
+ await cdp.send("HeapProfiler.takeHeapSnapshot", { reportProgress: false }, sessionId)
473
+ off()
474
+ const data = new TextEncoder().encode(chunks.join(""))
475
+ return {
476
+ tab: await tab(action.tabID),
477
+ files: [{ id: newFileID(), name: "heap.heapsnapshot", mime: "application/json", bytes: data.byteLength, path: "" }],
478
+ __file: { name: "heap.heapsnapshot", mime: "application/json", data },
479
+ }
480
+ }
481
+
482
+ // Las de abajo necesitan analizar el contenido de una captura, no solo
483
+ // producirla. Preferimos un `unsupported` accionable a colgar el comando.
484
+ case "heap.summary":
485
+ case "heap.query":
486
+ case "heap.object":
487
+ case "heap.compare":
488
+ throw unsupported(`${action.type} (parses heap snapshot contents; the bridge ships the file, not an analyzer)`)
489
+
490
+ case "trace.analyze":
491
+ case "cpu.analyze":
492
+ throw unsupported(action.type)
493
+
494
+ case "lighthouse":
495
+ throw unsupported("lighthouse (requires a Lighthouse runtime, not just CDP)")
496
+
497
+ default:
498
+ throw unsupported((action as { type: string }).type)
499
+ }
500
+ }
501
+
502
+ const newFileID = () => `file_${randomUUID()}` as Browser.FileID
503
+ const LEVEL_ORDER: Record<string, number> = { debug: 0, info: 1, warning: 2, error: 3 }
504
+
505
+ const base64ToBytes = (data: string) => new Uint8Array(Buffer.from(data, "base64"))
506
+
507
+ const publicRequest = (r: {
508
+ id: string
509
+ url: string
510
+ method: string
511
+ resourceType: string
512
+ timestampMs: number
513
+ statusCode?: number
514
+ state: string
515
+ durationMs?: number
516
+ failure?: string
517
+ }) =>
518
+ r.state === "completed"
519
+ ? {
520
+ id: r.id,
521
+ url: r.url,
522
+ method: r.method,
523
+ resourceType: r.resourceType,
524
+ timestampMs: r.timestampMs,
525
+ statusCode: r.statusCode,
526
+ state: "completed",
527
+ durationMs: r.durationMs ?? 0,
528
+ }
529
+ : r.state === "failed"
530
+ ? {
531
+ id: r.id,
532
+ url: r.url,
533
+ method: r.method,
534
+ resourceType: r.resourceType,
535
+ timestampMs: r.timestampMs,
536
+ statusCode: r.statusCode,
537
+ state: "failed",
538
+ durationMs: 0,
539
+ failure: r.failure ?? "failed",
540
+ }
541
+ : {
542
+ id: r.id,
543
+ url: r.url,
544
+ method: r.method,
545
+ resourceType: r.resourceType,
546
+ timestampMs: r.timestampMs,
547
+ statusCode: r.statusCode,
548
+ state: "pending",
549
+ }
550
+
551
+ const toHeaders = (headers?: Record<string, unknown>) =>
552
+ Object.entries(headers ?? {}).map(([name, value]) => ({
553
+ name: String(name).slice(0, 2_048),
554
+ value: String(value).slice(0, MAX_TEXT),
555
+ }))
556
+
557
+ const bodyState = (include: boolean | undefined, text: string | undefined, maxChars: number) => {
558
+ if (!include) return { state: "notRequested" as const }
559
+ if (text === undefined || text === null) return { state: "unavailable" as const, reason: "notCaptured" as const }
560
+ if (text === "") return { state: "empty" as const }
561
+ const value = String(text)
562
+ return { state: "text" as const, text: value.slice(0, maxChars), truncated: value.length > maxChars }
563
+ }
564
+
565
+ const mimeFor = (format: string) =>
566
+ format === "jpeg" ? "image/jpeg" : format === "webp" ? "image/webp" : "image/png"
567
+
568
+ const publicTab = (found?: LiveTab) => ({
569
+ id: found?.id ?? (`tab_${randomUUID()}` as Browser.TabID),
570
+ url: found?.url ?? "about:blank",
571
+ title: found?.title ?? "",
572
+ loading: false,
573
+ canGoBack: false,
574
+ canGoForward: false,
575
+ generation: found?.generation ?? 0,
576
+ })
577
+
578
+ // --- refs -------------------------------------------------------------------
579
+
580
+ /** Tabla ref → backendDOMNodeId, por tab. Se invalida en cada snapshot. */
581
+ class RefTable {
582
+ #perTab = new Map<string, Map<string, number>>()
583
+
584
+ reset(tabID: string) {
585
+ this.#perTab.set(tabID, new Map())
586
+ }
587
+
588
+ mint(tabID: string, backendDOMNodeId: number) {
589
+ const table = this.#perTab.get(tabID) ?? new Map<string, number>()
590
+ if (!this.#perTab.has(tabID)) this.#perTab.set(tabID, table)
591
+ const ref = `@e${table.size + 1}`
592
+ table.set(ref, backendDOMNodeId)
593
+ return ref
594
+ }
595
+
596
+ resolve(tabID: string, ref: string) {
597
+ const nodeId = this.#perTab.get(tabID)?.get(ref)
598
+ if (nodeId === undefined) {
599
+ throw new CdpError(
600
+ `Ref ${ref} is unknown or expired for tab ${tabID}. Call browser.snapshot({ tabID }) for fresh refs.`,
601
+ { code: "tab_unavailable" },
602
+ )
603
+ }
604
+ return nodeId
605
+ }
606
+ }
607
+
608
+ export const refs = new RefTable()
609
+
610
+ // --- helpers CDP ------------------------------------------------------------
611
+
612
+ async function refBox(ctx: ActionContext, tabID: string, ref: string, sessionId: string) {
613
+ const { cdp } = ctx
614
+ const nodeId = refs.resolve(tabID, ref)
615
+ // Page.getBoxModel necesita el objectId resuelto; usamos DOM.resolveNode
616
+ // para convertir backendDOMNodeId → objectId por sesión.
617
+ const { object } = await cdp.send("DOM.resolveNode", { backendNodeId: nodeId }, sessionId)
618
+ if (!object?.objectId) throw new CdpError(`Could not resolve ${ref}`, { code: "ref_unavailable" })
619
+
620
+ const { model } = await cdp.send("DOM.getBoxModel", { objectId: object.objectId }, sessionId)
621
+ const quad = model?.content ?? model?.border
622
+ if (!quad || quad.length < 8) throw new CdpError(`${ref} has no box model`, { code: "ref_unavailable" })
623
+
624
+ return {
625
+ x: (quad[0] + quad[2] + quad[4] + quad[6]) / 4,
626
+ y: (quad[1] + quad[3] + quad[5] + quad[7]) / 4,
627
+ width: Math.abs(quad[2] - quad[0]),
628
+ height: Math.abs(quad[5] - quad[1]),
629
+ }
630
+ }
631
+
632
+ async function fitClip(ctx: ActionContext, tabID: string, ref: string | undefined, sessionId: string, maxWidth: number) {
633
+ const { cdp } = ctx
634
+ const source: { x: number; y: number; width: number; height: number } = ref
635
+ ? await refBox(ctx, tabID, ref, sessionId)
636
+ : { x: 0, y: 0, ...viewportOf(await cdp.send("Page.getLayoutMetrics", {}, sessionId)) }
637
+ const scale = source.width > maxWidth ? maxWidth / source.width : 1
638
+ return { x: source.x, y: source.y, width: source.width * scale, height: source.height * scale, scale }
639
+ }
640
+
641
+ const viewportOf = (metrics: any) => {
642
+ const box = metrics?.cssVisualViewport ?? metrics?.cssContentSize ?? {}
643
+ return { width: box.clientWidth ?? box.width ?? 0, height: box.clientHeight ?? box.height ?? 0 }
644
+ }
645
+
646
+ async function fillNode(ctx: ActionContext, tabID: string, ref: string, sessionId: string, value: string) {
647
+ const { object } = await ctx.cdp.send("DOM.resolveNode", { backendNodeId: refs.resolve(tabID, ref) }, sessionId)
648
+ await ctx.cdp.send(
649
+ "Runtime.callFunctionOn",
650
+ {
651
+ objectId: object.objectId,
652
+ functionDeclaration: `function(value) {
653
+ const setter = Object.getOwnPropertyDescriptor(
654
+ this instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype,
655
+ "value"
656
+ )?.set;
657
+ setter ? setter.call(this, value) : (this.value = value);
658
+ this.dispatchEvent(new Event("input", { bubbles: true }));
659
+ this.dispatchEvent(new Event("change", { bubbles: true }));
660
+ }`,
661
+ arguments: [{ value }],
662
+ },
663
+ sessionId,
664
+ )
665
+ }
666
+
667
+ async function checkNode(ctx: ActionContext, tabID: string, ref: string, sessionId: string, checked: boolean) {
668
+ const { object } = await ctx.cdp.send("DOM.resolveNode", { backendNodeId: refs.resolve(tabID, ref) }, sessionId)
669
+ await ctx.cdp.send(
670
+ "Runtime.callFunctionOn",
671
+ {
672
+ objectId: object.objectId,
673
+ functionDeclaration: `function(checked) {
674
+ if (this.checked !== checked) this.click();
675
+ }`,
676
+ arguments: [{ value: checked }],
677
+ },
678
+ sessionId,
679
+ )
680
+ }
681
+
682
+ async function selectNode(ctx: ActionContext, tabID: string, ref: string, sessionId: string, values: readonly string[]) {
683
+ const { object } = await ctx.cdp.send("DOM.resolveNode", { backendNodeId: refs.resolve(tabID, ref) }, sessionId)
684
+ await ctx.cdp.send(
685
+ "Runtime.callFunctionOn",
686
+ {
687
+ objectId: object.objectId,
688
+ functionDeclaration: `function(values) {
689
+ const wanted = new Set(values);
690
+ for (const option of this.options ?? []) option.selected = wanted.has(option.value);
691
+ this.dispatchEvent(new Event("change", { bubbles: true }));
692
+ }`,
693
+ arguments: [{ value: values }],
694
+ },
695
+ sessionId,
696
+ )
697
+ }
698
+
699
+ async function sendKey(cdp: CdpClient, key: string, sessionId: string) {
700
+ const parts = key.split("+")
701
+ const keyName = parts.pop() ?? key
702
+ const common = { modifiers: parts.length, key: keyName, code: keyName, windowsVirtualKeyCode: vkFor(keyName) }
703
+ await cdp.send("Input.dispatchKeyEvent", { type: "keyDown", ...common }, sessionId)
704
+ await cdp.send("Input.dispatchKeyEvent", { type: "keyUp", ...common }, sessionId)
705
+ }
706
+
707
+ const VK: Record<string, number> = {
708
+ Enter: 13,
709
+ Tab: 9,
710
+ Escape: 27,
711
+ Backspace: 8,
712
+ Delete: 46,
713
+ ArrowLeft: 37,
714
+ ArrowUp: 38,
715
+ ArrowRight: 39,
716
+ ArrowDown: 40,
717
+ Home: 36,
718
+ End: 35,
719
+ PageUp: 33,
720
+ PageDown: 34,
721
+ a: 65,
722
+ }
723
+
724
+ const vkFor = (name: string) => VK[name] ?? name.toUpperCase().charCodeAt(0)
725
+
726
+ const toModifiers = (mods: readonly string[]) => {
727
+ let value = 0
728
+ if (mods.includes("Alt")) value |= 1
729
+ if (mods.includes("Control")) value |= 2
730
+ if (mods.includes("Meta")) value |= 4
731
+ if (mods.includes("Shift")) value |= 8
732
+ return value
733
+ }
734
+
735
+ async function textPresence(cdp: CdpClient, text: string | undefined, sessionId: string) {
736
+ if (!text) return false
737
+ const result = await cdp.send(
738
+ "Runtime.evaluate",
739
+ {
740
+ expression: `document.body && document.body.innerText.includes(${JSON.stringify(text)})`,
741
+ returnByValue: true,
742
+ },
743
+ sessionId,
744
+ )
745
+ return result.result?.value === true
746
+ }
747
+
748
+ async function waitForLoad(cdp: CdpClient, tabs: TabRegistry, tabID: string) {
749
+ const targetId = tabs.resolve(tabID)
750
+ const deadline = Date.now() + 15_000
751
+ while (Date.now() < deadline) {
752
+ const { targetInfos } = await cdp.send("Target.getTargets")
753
+ if (!targetInfos.some((info: { targetId: string }) => info.targetId === targetId)) return
754
+ break
755
+ }
756
+ }
757
+
758
+ // --- trazas -----------------------------------------------------------------
759
+
760
+ async function startTrace(cdp: CdpClient, tabID: string, durationMs: number) {
761
+ await cdp.send("Tracing.start", {
762
+ transferMode: "ReturnAsStream",
763
+ traceConfig: { includedCategories: ["devtools.timeline"] },
764
+ })
765
+ cdp.traces.trace = { tabID, startedAt: Date.now(), durationMs }
766
+ const timer = setTimeout(() => void stopTrace(cdp).catch(() => undefined), durationMs + 1_000)
767
+ timer.unref?.()
768
+ }
769
+
770
+ async function stopTrace(cdp: CdpClient) {
771
+ const trace = cdp.traces.trace
772
+ if (!trace) throw new CdpError("No trace is running.", { code: "not_recording" })
773
+ cdp.traces.trace = undefined
774
+ const complete = new Promise<{ stream?: string }>((resolve) => {
775
+ const off = cdp.on("Tracing.tracingComplete", (params: any) => {
776
+ off()
777
+ resolve(params)
778
+ })
779
+ const timer = setTimeout(() => resolve({}), 10_000)
780
+ timer.unref?.()
781
+ })
782
+ await cdp.send("Tracing.end")
783
+ const result = await complete
784
+ if (!result.stream) {
785
+ return { tabID: trace.tabID, data: undefined, bytes: 0, durationMs: Date.now() - trace.startedAt, incomplete: true }
786
+ }
787
+ const { data, base64Encoded } = await cdp.send("IO.read", { handle: result.stream })
788
+ await cdp.send("IO.close", { handle: result.stream }).catch(() => undefined)
789
+ return {
790
+ tabID: trace.tabID,
791
+ data: base64Encoded ? (data as string) : Buffer.from(data as string).toString("base64"),
792
+ bytes: (data as string).length,
793
+ durationMs: Date.now() - trace.startedAt,
794
+ incomplete: false,
795
+ }
796
+ }
797
+
798
+ /** Los adjuntos del comando se materializan en disco: CDP solo acepta rutas. */
799
+ async function materialize(files: readonly Browser.File[]) {
800
+ if (files.length === 0) return []
801
+ const dir = await mkdtemp(join(tmpdir(), "apex-browser-files-"))
802
+ return Promise.all(
803
+ files.map(async (file) => {
804
+ const path = join(dir, file.name)
805
+ await writeFile(path, file.data)
806
+ return { path, name: file.name }
807
+ }),
808
+ )
809
+ }
810
+
811
+ const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))