@myrialabs/clopen 0.4.20 → 0.4.22

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 (116) hide show
  1. package/README.md +2 -1
  2. package/backend/artifacts/generate.ts +11 -5
  3. package/backend/auth/permissions.ts +8 -8
  4. package/backend/bootstrap.ts +39 -0
  5. package/backend/chat/stream-manager.ts +15 -0
  6. package/backend/database/migrations/065_add_session_reasoning_effort.ts +28 -0
  7. package/backend/database/migrations/index.ts +7 -0
  8. package/backend/database/queries/session-queries.ts +10 -0
  9. package/backend/engine/README.md +11 -8
  10. package/backend/engine/adapters/claude/models.ts +46 -23
  11. package/backend/engine/adapters/claude/stream.ts +18 -4
  12. package/backend/engine/adapters/codex/error-handler.ts +1 -1
  13. package/backend/engine/adapters/codex/models.ts +19 -2
  14. package/backend/engine/adapters/codex/stream.ts +10 -3
  15. package/backend/engine/adapters/copilot/models.ts +20 -1
  16. package/backend/engine/adapters/copilot/stream.ts +11 -1
  17. package/backend/engine/adapters/cursor/models.ts +27 -3
  18. package/backend/engine/adapters/cursor/stream.ts +23 -3
  19. package/backend/engine/adapters/pi/models.ts +20 -2
  20. package/backend/engine/adapters/pi/stream.ts +6 -3
  21. package/backend/engine/adapters/qwen/error-handler.ts +1 -1
  22. package/backend/engine/bootstrap-default-engine.ts +18 -5
  23. package/backend/engine/docs/adapter-contract.md +66 -2
  24. package/backend/engine/docs/adding-an-engine.md +46 -7
  25. package/backend/engine/docs/frontend-and-chat.md +80 -17
  26. package/backend/engine/docs/lessons-learned.md +126 -7
  27. package/backend/engine/docs/quick-reference.md +12 -3
  28. package/backend/engine/docs/{system-tools.md → stack.md} +35 -6
  29. package/backend/engine/docs/websocket-routes.md +54 -15
  30. package/backend/engine/install-runner.ts +4 -4
  31. package/backend/engine/resolve-model.ts +87 -0
  32. package/backend/engine/structured-helpers.test.ts +64 -0
  33. package/backend/engine/structured-helpers.ts +105 -13
  34. package/backend/engine/types.ts +6 -0
  35. package/backend/index.ts +6 -9
  36. package/backend/mcp/README.md +32 -11
  37. package/backend/mcp/internal/config.ts +3 -20
  38. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +65 -0
  39. package/backend/mcp/internal/servers/browser-automation/actions/dom-analyze.ts +202 -0
  40. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +31 -0
  41. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +332 -0
  42. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +158 -0
  43. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +157 -0
  44. package/backend/mcp/internal/servers/browser-automation/actions/shared.ts +60 -0
  45. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +146 -0
  46. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +63 -0
  47. package/backend/mcp/internal/servers/browser-automation/context.ts +82 -0
  48. package/backend/mcp/internal/servers/browser-automation/description.ts +59 -0
  49. package/backend/mcp/internal/servers/browser-automation/format.ts +56 -0
  50. package/backend/mcp/internal/servers/browser-automation/index.ts +36 -784
  51. package/backend/mcp/internal/servers/browser-automation/paths.ts +71 -0
  52. package/backend/mcp/internal/servers/browser-automation/runner.ts +260 -0
  53. package/backend/mcp/internal/servers/browser-automation/schema.ts +26 -0
  54. package/backend/preview/browser/browser-console-manager.ts +310 -156
  55. package/backend/preview/browser/browser-dialog-handler.ts +45 -16
  56. package/backend/preview/browser/browser-host-bridge.ts +471 -0
  57. package/backend/preview/browser/browser-interaction-handler.ts +868 -297
  58. package/backend/preview/browser/browser-mcp-control.ts +7 -2
  59. package/backend/preview/browser/browser-native-ui-handler.ts +455 -81
  60. package/backend/preview/browser/browser-navigation-tracker.ts +56 -0
  61. package/backend/preview/browser/browser-pool.ts +83 -9
  62. package/backend/preview/browser/browser-preview-service.ts +432 -53
  63. package/backend/preview/browser/browser-tab-manager.ts +16 -16
  64. package/backend/preview/browser/browser-video-capture.ts +1334 -386
  65. package/backend/preview/browser/capture-profile.ts +213 -0
  66. package/backend/preview/browser/element-locator.ts +357 -0
  67. package/backend/preview/browser/frame-targeting.ts +92 -0
  68. package/backend/preview/browser/scripts/audio-stream.ts +258 -78
  69. package/backend/preview/browser/scripts/host-bridge.ts +1277 -0
  70. package/backend/preview/browser/scripts/video-stream.ts +803 -177
  71. package/backend/preview/browser/types.ts +397 -37
  72. package/backend/utils/cli.ts +1 -1
  73. package/backend/utils/path-enrich.ts +2 -2
  74. package/backend/ws/README.md +1 -1
  75. package/backend/ws/artifacts/generate.ts +2 -1
  76. package/backend/ws/chat/stream.ts +38 -2
  77. package/backend/ws/engine/codex/accounts.ts +1 -1
  78. package/backend/ws/engine/codex/status.ts +1 -1
  79. package/backend/ws/git/branch-name.ts +11 -5
  80. package/backend/ws/git/commit-message.ts +11 -5
  81. package/backend/ws/index.ts +3 -3
  82. package/backend/ws/preview/browser/host.ts +95 -0
  83. package/backend/ws/preview/browser/interact.ts +204 -10
  84. package/backend/ws/preview/browser/native-ui.ts +31 -1
  85. package/backend/ws/preview/browser/tab-info.ts +10 -1
  86. package/backend/ws/preview/browser/tab.ts +43 -0
  87. package/backend/ws/preview/browser/webcodecs.ts +180 -53
  88. package/backend/ws/preview/index.ts +58 -1
  89. package/backend/ws/{system-tools → stack}/access.ts +1 -1
  90. package/backend/ws/stack/index.ts +16 -0
  91. package/backend/ws/{system-tools → stack}/install.ts +7 -7
  92. package/backend/ws/{system-tools → stack}/status.ts +7 -7
  93. package/backend/ws/system/device-info.ts +290 -0
  94. package/backend/ws/system/index.ts +2 -0
  95. package/backend/ws/system/operations.ts +7 -0
  96. package/backend/ws/user/crud.ts +6 -3
  97. package/dist/assets/{index-BqBxKeAv.js → index-DH_GO0Lf.js} +1 -1
  98. package/dist/assets/{index-DdrcY5TE.js → index-igSQ3JaM.js} +1 -1
  99. package/dist/assets/main-BD3-qPfT.css +1 -0
  100. package/dist/assets/main-D-d8SFfW.js +616 -0
  101. package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
  102. package/dist/index.html +2 -2
  103. package/package.json +2 -1
  104. package/shared/constants/engines.ts +23 -0
  105. package/shared/types/database/schema.ts +1 -0
  106. package/shared/types/stores/settings.ts +12 -0
  107. package/shared/types/unified/engine.ts +33 -0
  108. package/shared/types/unified/index.ts +2 -0
  109. package/shared/types/unified/message.ts +6 -0
  110. package/shared/types/unified/stream.ts +6 -0
  111. package/backend/mcp/internal/servers/browser-automation/actions.ts +0 -159
  112. package/backend/mcp/internal/servers/browser-automation/browser.ts +0 -375
  113. package/backend/mcp/internal/servers/browser-automation/inspection.ts +0 -495
  114. package/backend/ws/system-tools/index.ts +0 -16
  115. package/dist/assets/main-BBxAj17T.js +0 -582
  116. package/dist/assets/main-Cry3pLcl.css +0 -1
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Preview Capture Profile
3
+ *
4
+ * Single source of truth for "how much work is this host allowed to do per
5
+ * frame". Every expensive stage of the preview pipeline — Chrome's screencast
6
+ * JPEG encode, the in-page VideoEncoder, the wire, and the viewer's decoder —
7
+ * scales with `pixels × framerate`, so both are budgeted here instead of being
8
+ * hard-coded at each call site.
9
+ *
10
+ * Two independent mechanisms feed into the final capture size:
11
+ *
12
+ * 1. **Display-matched resolution** (`computeCaptureSize`). The preview is
13
+ * almost always displayed smaller than the emulated viewport (a 1440×900
14
+ * laptop preview shown in a half-width panel). Capturing at the full
15
+ * viewport means encoding ~5× more pixels than the screen can show. We
16
+ * capture at `displayScale × devicePixelRatio` instead, which is exactly
17
+ * one captured pixel per physical screen pixel — sharper is impossible to
18
+ * see, so this costs nothing visually. On a Retina display at 50% fit the
19
+ * factor is 0.5 × 2 = 1.0 and we capture natively, exactly as before.
20
+ *
21
+ * 2. **Host budget** (`getHostCaptureProfile`). A 2-core VPS cannot software-
22
+ * encode 1080p24 in realtime no matter how large the panel is, so the tier
23
+ * caps total pixels, framerate, and quality. The runtime ladder in
24
+ * BrowserVideoCapture adapts within these bounds.
25
+ */
26
+
27
+ import os from 'os';
28
+ import { debug } from '$shared/utils/logger';
29
+
30
+ export type QualityTier = 'high' | 'balanced' | 'low';
31
+
32
+ export interface CaptureProfile {
33
+ tier: QualityTier;
34
+ /** Hard ceiling on captured pixels per frame (width × height). */
35
+ maxPixels: number;
36
+ /** Upper bound of the adaptive framerate ladder. */
37
+ maxFramerate: number;
38
+ /** Lower bound — below this, motion stops reading as motion. */
39
+ minFramerate: number;
40
+ /** VP9 per-frame quantizer while the page is moving (higher = cheaper). */
41
+ motionQuantizer: number;
42
+ /** VP9 quantizer for the still-page refresh frame (lower = sharper). */
43
+ topOffQuantizer: number;
44
+ /** JPEG quality of CDP screencast source frames. */
45
+ screenshotQuality: number;
46
+ /**
47
+ * Still-page refresh capture format. PNG is lossless but costs a full
48
+ * raster + deflate pass and produces multi-megabyte base64 payloads;
49
+ * JPEG at high quality is visually equivalent for UI text at a fraction
50
+ * of the CPU on both ends.
51
+ */
52
+ topOffFormat: 'png' | 'jpeg';
53
+ topOffQuality: number;
54
+ audioBitrate: number;
55
+ }
56
+
57
+ const PROFILES: Record<QualityTier, Omit<CaptureProfile, 'tier'>> = {
58
+ high: {
59
+ maxPixels: 1920 * 1080,
60
+ // 24 was inherited from the fixed-rate era, where every frame cost a
61
+ // JPEG encode and a base64 round-trip. In-page capture hands compositor
62
+ // frames straight to the encoder, so the headroom now goes to motion
63
+ // smoothness — which is the difference the eye actually notices.
64
+ maxFramerate: 30,
65
+ minFramerate: 10,
66
+ motionQuantizer: 38,
67
+ topOffQuantizer: 10,
68
+ screenshotQuality: 80,
69
+ topOffFormat: 'jpeg',
70
+ topOffQuality: 95,
71
+ audioBitrate: 128_000
72
+ },
73
+ balanced: {
74
+ maxPixels: 1440 * 900,
75
+ maxFramerate: 20,
76
+ minFramerate: 8,
77
+ motionQuantizer: 42,
78
+ topOffQuantizer: 14,
79
+ screenshotQuality: 72,
80
+ topOffFormat: 'jpeg',
81
+ topOffQuality: 92,
82
+ audioBitrate: 96_000
83
+ },
84
+ low: {
85
+ maxPixels: 1280 * 720,
86
+ maxFramerate: 12,
87
+ minFramerate: 6,
88
+ motionQuantizer: 48,
89
+ topOffQuantizer: 20,
90
+ screenshotQuality: 65,
91
+ topOffFormat: 'jpeg',
92
+ topOffQuality: 88,
93
+ audioBitrate: 64_000
94
+ }
95
+ };
96
+
97
+ /**
98
+ * Discrete capture scales. Every change reconfigures the encoder and forces a
99
+ * keyframe, so a continuous scale would thrash on every resize pixel. Snapping
100
+ * to a short ladder keeps reconfigurations rare while staying within ~15% of
101
+ * the ideal resolution.
102
+ */
103
+ const CAPTURE_SCALE_STEPS = [0.25, 0.35, 0.5, 0.6, 0.75, 0.85, 1] as const;
104
+
105
+ /** Below this the preview stops being readable regardless of panel size. */
106
+ const MIN_CAPTURE_WIDTH = 360;
107
+
108
+ let cachedProfile: CaptureProfile | null = null;
109
+
110
+ function detectTier(): QualityTier {
111
+ const override = (process.env.CLOPEN_PREVIEW_QUALITY || '').trim().toLowerCase();
112
+ if (override === 'high' || override === 'balanced' || override === 'low') {
113
+ return override;
114
+ }
115
+
116
+ // os.cpus() can return an empty array in some containers — treat unknown
117
+ // as constrained rather than assuming a fast host.
118
+ const cores = os.cpus()?.length || 2;
119
+ const memGb = os.totalmem() / 1024 ** 3;
120
+
121
+ if (cores <= 2 || memGb < 2.5) return 'low';
122
+ if (cores <= 4 || memGb < 6) return 'balanced';
123
+ return 'high';
124
+ }
125
+
126
+ /**
127
+ * Host capability tier. Cached — hardware doesn't change at runtime, and the
128
+ * per-session ladder handles transient load.
129
+ */
130
+ export function getHostCaptureProfile(): CaptureProfile {
131
+ if (cachedProfile) return cachedProfile;
132
+
133
+ const tier = detectTier();
134
+ cachedProfile = { tier, ...PROFILES[tier] };
135
+
136
+ debug.log(
137
+ 'webcodecs',
138
+ `Capture profile: ${tier} (${os.cpus()?.length || '?'} cores, ` +
139
+ `${(os.totalmem() / 1024 ** 3).toFixed(1)} GB, ${os.platform()}) — ` +
140
+ `≤${(cachedProfile.maxPixels / 1e6).toFixed(2)}MP @ ${cachedProfile.maxFramerate}fps`
141
+ );
142
+
143
+ return cachedProfile;
144
+ }
145
+
146
+ function evenRound(value: number): number {
147
+ return Math.max(2, Math.round(value / 2) * 2);
148
+ }
149
+
150
+ export interface CaptureSize {
151
+ width: number;
152
+ height: number;
153
+ /** Effective scale relative to the emulated viewport (for CDP clip). */
154
+ scale: number;
155
+ }
156
+
157
+ /**
158
+ * Resolve the capture resolution for a viewport.
159
+ *
160
+ * `displayScale` is the CSS fit-scale the frontend applies to the preview and
161
+ * `devicePixelRatio` is the viewer's screen density; their product is how many
162
+ * physical screen pixels each viewport pixel actually occupies. Capturing above
163
+ * that is invisible work; capturing below it is the upscaling blur this
164
+ * pipeline was rewritten to remove — so the product is the target, clamped to
165
+ * [floor, native] and to the host's pixel budget.
166
+ */
167
+ export function computeCaptureSize(
168
+ viewportWidth: number,
169
+ viewportHeight: number,
170
+ displayScale: number | undefined,
171
+ devicePixelRatio: number | undefined,
172
+ profile: CaptureProfile
173
+ ): CaptureSize {
174
+ // Unknown display metrics (first frame, headless MCP use) → capture native
175
+ // and let the client's first metrics report narrow it down.
176
+ const fit = displayScale && displayScale > 0 ? Math.min(1, displayScale) : 1;
177
+ const dpr = devicePixelRatio && devicePixelRatio > 0 ? Math.min(4, devicePixelRatio) : 1;
178
+
179
+ const wanted = Math.min(1, fit * dpr);
180
+ const step = CAPTURE_SCALE_STEPS.find((s) => s >= wanted - 0.001) ?? 1;
181
+
182
+ // Width leads and height follows the viewport's exact aspect ratio.
183
+ // Rounding both independently drifts the aspect, and the screencast — which
184
+ // always preserves the viewport ratio — then delivers frames a pixel or two
185
+ // away from what was asked for, on every single restart.
186
+ const aspect = viewportHeight / viewportWidth;
187
+ let width = evenRound(viewportWidth * step);
188
+
189
+ // Host budget — shrink so the frame fits the pixel ceiling.
190
+ if (width * (width * aspect) > profile.maxPixels) {
191
+ width = evenRound(Math.sqrt(profile.maxPixels / aspect));
192
+ }
193
+
194
+ // Readability floor, but never above the emulated viewport itself.
195
+ if (width < MIN_CAPTURE_WIDTH) {
196
+ width = evenRound(Math.min(viewportWidth, MIN_CAPTURE_WIDTH));
197
+ }
198
+
199
+ width = Math.min(evenRound(width), evenRound(viewportWidth));
200
+ const height = Math.min(evenRound(width * aspect), evenRound(viewportHeight));
201
+
202
+ return { width, height, scale: width / viewportWidth };
203
+ }
204
+
205
+ /**
206
+ * Bits-per-pixel target for codecs driven by bitrate rather than a per-frame
207
+ * quantizer (VP8 fallback, H.264). 0.045 bpp ≈ 1.1 Mbps at 1280×800@24.
208
+ */
209
+ const BITS_PER_PIXEL = 0.045;
210
+
211
+ export function computeBitrate(width: number, height: number, framerate: number): number {
212
+ return Math.max(400_000, Math.round(width * height * framerate * BITS_PER_PIXEL));
213
+ }
@@ -0,0 +1,357 @@
1
+ /**
2
+ * Element Locator
3
+ *
4
+ * Turns a CSS selector or a piece of visible text into page coordinates.
5
+ *
6
+ * Coordinates are what every input primitive ultimately needs — CDP dispatches
7
+ * mouse and touch events at a point, not at an element. Resolving here means an
8
+ * agent can say "click the Login button" without first taking a screenshot and
9
+ * guessing pixels from it, and means the same query keeps working after the
10
+ * page reflows.
11
+ *
12
+ * Every lookup sweeps all frames, not just the main one. `boundingBox()` is
13
+ * already reported relative to the main frame, so an element inside an iframe
14
+ * resolves to a directly clickable point with no offset arithmetic.
15
+ */
16
+
17
+ import type { ElementHandle, Frame, Page } from 'puppeteer';
18
+ import type { BrowserActionTarget } from './types';
19
+
20
+ export interface LocatedElement {
21
+ /** Centre of the element, in page coordinates — where input is aimed. */
22
+ x: number;
23
+ y: number;
24
+ box: { x: number; y: number; width: number; height: number };
25
+ tag: string;
26
+ /** Trimmed visible text, capped for readability. */
27
+ text: string;
28
+ /** A selector that addresses this element again, when one can be built. */
29
+ selector: string;
30
+ role?: string;
31
+ name?: string;
32
+ href?: string;
33
+ value?: string;
34
+ placeholder?: string;
35
+ type?: string;
36
+ enabled: boolean;
37
+ visible: boolean;
38
+ /** True when the element lives inside an iframe. */
39
+ inFrame: boolean;
40
+ frameUrl?: string;
41
+ }
42
+
43
+ export interface LocateQuery {
44
+ selector?: string;
45
+ text?: string;
46
+ /** Filter by ARIA role or input type, e.g. "button", "link", "textbox". */
47
+ role?: string;
48
+ nth?: number;
49
+ visibleOnly?: boolean;
50
+ limit?: number;
51
+ /** Scroll the first match into view before measuring (default true). */
52
+ scrollIntoView?: boolean;
53
+ }
54
+
55
+ /** Metadata read out of the page for one element. */
56
+ interface ElementMeta {
57
+ tag: string;
58
+ text: string;
59
+ selector: string;
60
+ role?: string;
61
+ name?: string;
62
+ href?: string;
63
+ value?: string;
64
+ placeholder?: string;
65
+ type?: string;
66
+ enabled: boolean;
67
+ visible: boolean;
68
+ }
69
+
70
+ /**
71
+ * XPath that matches the *innermost* elements containing the text.
72
+ *
73
+ * Without the `not(.//*[...])` guard every ancestor up to <body> matches too,
74
+ * and the first hit would be the whole document rather than the button the
75
+ * agent meant.
76
+ */
77
+ function innermostTextXPath(text: string): string {
78
+ const escaped = xpathLiteral(text.toLowerCase());
79
+ const lower = `translate(normalize-space(.), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')`;
80
+ return `xpath///*[contains(${lower}, ${escaped}) and not(.//*[contains(${lower}, ${escaped})])]`;
81
+ }
82
+
83
+ /** XPath has no escape character; a mixed-quote string must be built with concat(). */
84
+ function xpathLiteral(value: string): string {
85
+ if (!value.includes("'")) return `'${value}'`;
86
+ if (!value.includes('"')) return `"${value}"`;
87
+ const parts = value.split("'").map((part) => `'${part}'`);
88
+ return `concat(${parts.join(`, "'", `)})`;
89
+ }
90
+
91
+ /** Read everything the caller might want to show, in one round trip per element. */
92
+ async function readMeta(handle: ElementHandle<Element>): Promise<ElementMeta> {
93
+ return handle.evaluate((el) => {
94
+ const style = window.getComputedStyle(el);
95
+ const rect = el.getBoundingClientRect();
96
+ const visible =
97
+ style.display !== 'none' &&
98
+ style.visibility !== 'hidden' &&
99
+ Number(style.opacity) !== 0 &&
100
+ rect.width > 0 &&
101
+ rect.height > 0;
102
+
103
+ // Prefer a stable hook (id, test id, name) over a positional path so the
104
+ // selector survives re-renders.
105
+ const buildSelector = (node: Element): string => {
106
+ if (node.id) return `#${CSS.escape(node.id)}`;
107
+ const testId = node.getAttribute('data-testid') || node.getAttribute('data-test-id');
108
+ if (testId) return `[data-testid="${testId}"]`;
109
+ const name = node.getAttribute('name');
110
+ if (name) return `${node.tagName.toLowerCase()}[name="${name}"]`;
111
+
112
+ const path: string[] = [];
113
+ let current: Element | null = node;
114
+ while (current && current.nodeType === 1 && path.length < 5) {
115
+ let part = current.tagName.toLowerCase();
116
+ const parent: Element | null = current.parentElement;
117
+ if (parent) {
118
+ const siblings = Array.from(parent.children).filter((c) => c.tagName === current!.tagName);
119
+ if (siblings.length > 1) part += `:nth-of-type(${siblings.indexOf(current) + 1})`;
120
+ }
121
+ path.unshift(part);
122
+ if (current.id) {
123
+ path[0] = `#${CSS.escape(current.id)}`;
124
+ break;
125
+ }
126
+ current = parent;
127
+ }
128
+ return path.join(' > ');
129
+ };
130
+
131
+ const input = el as HTMLInputElement;
132
+ const anchor = el as HTMLAnchorElement;
133
+
134
+ return {
135
+ tag: el.tagName.toLowerCase(),
136
+ text: (el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 120),
137
+ selector: buildSelector(el),
138
+ role: el.getAttribute('role') || undefined,
139
+ name:
140
+ el.getAttribute('aria-label') ||
141
+ el.getAttribute('name') ||
142
+ el.getAttribute('title') ||
143
+ undefined,
144
+ href: anchor.href || undefined,
145
+ value: typeof input.value === 'string' ? input.value.slice(0, 120) : undefined,
146
+ placeholder: input.placeholder || undefined,
147
+ type: input.type || undefined,
148
+ enabled: !(el as HTMLButtonElement).disabled,
149
+ visible
150
+ };
151
+ });
152
+ }
153
+
154
+ /** Collect candidate handles for a query, main frame first. */
155
+ async function collectHandles(page: Page, query: LocateQuery): Promise<Array<{ handle: ElementHandle<Element>; frame: Frame }>> {
156
+ const found: Array<{ handle: ElementHandle<Element>; frame: Frame }> = [];
157
+
158
+ for (const frame of page.frames()) {
159
+ if (frame.isDetached()) continue;
160
+
161
+ try {
162
+ const handles: ElementHandle<Element>[] = [];
163
+
164
+ if (query.selector) {
165
+ handles.push(...(await frame.$$(query.selector)));
166
+ } else if (query.text) {
167
+ handles.push(...(await frame.$$(innermostTextXPath(query.text))));
168
+ } else if (query.role) {
169
+ // A role is expressed either explicitly or by the element itself:
170
+ // `<button>` carries the button role without saying so. Both are
171
+ // tried, and an invalid tag selector simply yields nothing.
172
+ for (const selector of [`[role="${query.role}"]`, query.role]) {
173
+ try {
174
+ handles.push(...(await frame.$$(selector)));
175
+ } catch {
176
+ continue;
177
+ }
178
+ }
179
+ }
180
+
181
+ for (const handle of handles) found.push({ handle, frame });
182
+ } catch {
183
+ // A bad selector or a frame that navigated mid-sweep — neither should
184
+ // abort the other frames' results.
185
+ }
186
+ }
187
+
188
+ return found;
189
+ }
190
+
191
+ /**
192
+ * Find every element matching a query, ordered as the document does.
193
+ * Handles are disposed before returning; only plain data escapes.
194
+ */
195
+ export async function findElements(page: Page, query: LocateQuery): Promise<LocatedElement[]> {
196
+ const limit = query.limit ?? 20;
197
+ const visibleOnly = query.visibleOnly !== false;
198
+ const candidates = await collectHandles(page, query);
199
+ const results: LocatedElement[] = [];
200
+ // The role query runs two selectors, so `<button role="button">` can match
201
+ // twice; geometry plus tag identifies the element well enough to drop the
202
+ // repeat.
203
+ const seen = new Set<string>();
204
+
205
+ try {
206
+ for (const { handle, frame } of candidates) {
207
+ if (results.length >= limit) break;
208
+
209
+ const meta = await readMeta(handle).catch(() => null);
210
+ if (!meta) continue;
211
+ if (visibleOnly && !meta.visible) continue;
212
+ if (query.role && meta.role !== query.role && meta.tag !== query.role) continue;
213
+ // Both a selector and text narrows: matches must satisfy both.
214
+ if (query.selector && query.text && !meta.text.toLowerCase().includes(query.text.toLowerCase())) continue;
215
+
216
+ const box = await handle.boundingBox().catch(() => null);
217
+ if (!box && visibleOnly) continue;
218
+
219
+ const signature = `${meta.tag}@${box ? `${box.x},${box.y},${box.width}x${box.height}` : meta.selector}`;
220
+ if (seen.has(signature)) continue;
221
+ seen.add(signature);
222
+
223
+ results.push({
224
+ x: box ? Math.round(box.x + box.width / 2) : 0,
225
+ y: box ? Math.round(box.y + box.height / 2) : 0,
226
+ box: box
227
+ ? { x: Math.round(box.x), y: Math.round(box.y), width: Math.round(box.width), height: Math.round(box.height) }
228
+ : { x: 0, y: 0, width: 0, height: 0 },
229
+ tag: meta.tag,
230
+ text: meta.text,
231
+ selector: meta.selector,
232
+ role: meta.role,
233
+ name: meta.name,
234
+ href: meta.href,
235
+ value: meta.value,
236
+ placeholder: meta.placeholder,
237
+ type: meta.type,
238
+ enabled: meta.enabled,
239
+ visible: meta.visible,
240
+ inFrame: frame !== page.mainFrame(),
241
+ frameUrl: frame !== page.mainFrame() ? frame.url() : undefined
242
+ });
243
+ }
244
+ } finally {
245
+ for (const { handle } of candidates) {
246
+ await handle.dispose().catch(() => {});
247
+ }
248
+ }
249
+
250
+ return results;
251
+ }
252
+
253
+ /**
254
+ * Resolve the handle for a target, scrolled into view.
255
+ * The caller owns the handle and must dispose it.
256
+ */
257
+ export async function resolveHandle(
258
+ page: Page,
259
+ target: BrowserActionTarget,
260
+ opts: { scrollIntoView?: boolean } = {}
261
+ ): Promise<ElementHandle<Element> | null> {
262
+ const candidates = await collectHandles(page, { selector: target.selector, text: target.text });
263
+ if (candidates.length === 0) return null;
264
+
265
+ const wanted = target.nth ?? 0;
266
+ let picked: ElementHandle<Element> | null = null;
267
+ let seen = 0;
268
+
269
+ for (const { handle } of candidates) {
270
+ const visible = await handle.evaluate((el) => {
271
+ const style = window.getComputedStyle(el);
272
+ const rect = el.getBoundingClientRect();
273
+ return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
274
+ }).catch(() => false);
275
+
276
+ if (!visible) continue;
277
+ if (seen === wanted) {
278
+ picked = handle;
279
+ break;
280
+ }
281
+ seen++;
282
+ }
283
+
284
+ for (const { handle } of candidates) {
285
+ if (handle !== picked) await handle.dispose().catch(() => {});
286
+ }
287
+
288
+ if (!picked) return null;
289
+
290
+ if (opts.scrollIntoView !== false) {
291
+ // A point outside the viewport cannot receive input, so scrolling is part
292
+ // of resolving rather than something the agent has to remember to do.
293
+ await picked.scrollIntoView().catch(() => {});
294
+ }
295
+
296
+ return picked;
297
+ }
298
+
299
+ /**
300
+ * Resolve a target to a point. Explicit coordinates win; otherwise the element
301
+ * is located, scrolled into view and aimed at its centre.
302
+ */
303
+ export async function resolveTarget(
304
+ page: Page,
305
+ target: BrowserActionTarget | undefined,
306
+ opts: { scrollIntoView?: boolean } = {}
307
+ ): Promise<{ x: number; y: number; described: string }> {
308
+ if (!target) throw new Error('No target given');
309
+
310
+ if (typeof target.x === 'number' && typeof target.y === 'number') {
311
+ return { x: target.x, y: target.y, described: `(${target.x}, ${target.y})` };
312
+ }
313
+
314
+ if (!target.selector && !target.text) {
315
+ throw new Error('Target needs either x/y coordinates, a selector, or text');
316
+ }
317
+
318
+ const handle = await resolveHandle(page, target, opts);
319
+ const label = target.selector ? `selector "${target.selector}"` : `text "${target.text}"`;
320
+ if (!handle) throw new Error(`No visible element matched ${label}`);
321
+
322
+ try {
323
+ const box = await handle.boundingBox();
324
+ if (!box) throw new Error(`${label} matched an element with no layout box (hidden or zero-sized)`);
325
+
326
+ return {
327
+ x: Math.round(box.x + box.width / 2),
328
+ y: Math.round(box.y + box.height / 2),
329
+ described: `${label} at (${Math.round(box.x + box.width / 2)}, ${Math.round(box.y + box.height / 2)})`
330
+ };
331
+ } finally {
332
+ await handle.dispose().catch(() => {});
333
+ }
334
+ }
335
+
336
+ /** Whether the element at a target uses the HTML5 drag-and-drop protocol. */
337
+ export async function isNativeDraggable(page: Page, target: BrowserActionTarget): Promise<boolean> {
338
+ if (!target.selector && !target.text) return false;
339
+
340
+ const handle = await resolveHandle(page, target, { scrollIntoView: false });
341
+ if (!handle) return false;
342
+
343
+ try {
344
+ return await handle.evaluate((el) => {
345
+ let node: Element | null = el;
346
+ while (node) {
347
+ if ((node as HTMLElement).draggable === true) return true;
348
+ node = node.parentElement;
349
+ }
350
+ return false;
351
+ });
352
+ } catch {
353
+ return false;
354
+ } finally {
355
+ await handle.dispose().catch(() => {});
356
+ }
357
+ }
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Frame Targeting
3
+ *
4
+ * Everything the preview inspects at a coordinate — the select under a click,
5
+ * the element under a right-click, the field a paste lands in — used to run
6
+ * `page.evaluate`, which only ever sees the **main frame**. Inside an iframe
7
+ * `document.elementFromPoint()` returns the `<iframe>` element itself, so every
8
+ * one of those features silently did nothing there.
9
+ *
10
+ * This walks the frame tree to find the frame that actually owns a point and
11
+ * converts the coordinate into that frame's own viewport space, so the caller
12
+ * can evaluate against the real element.
13
+ *
14
+ * `ElementHandle.boundingBox()` reports **main-frame** coordinates at every
15
+ * depth, which is what makes the walk simple: the containment test always runs
16
+ * against the original point, and only the returned offset accumulates.
17
+ */
18
+
19
+ import type { Frame, Page } from 'puppeteer';
20
+
21
+ export interface FrameTarget {
22
+ frame: Frame;
23
+ /** The point, in `frame`'s own viewport coordinates. */
24
+ x: number;
25
+ y: number;
26
+ }
27
+
28
+ /**
29
+ * Depth cap. Real pages nest an ad in a widget in a consent wrapper and stop;
30
+ * anything deeper is far more likely to be a frame loop than a real target.
31
+ */
32
+ const MAX_FRAME_DEPTH = 8;
33
+
34
+ /**
35
+ * Resolve which frame owns a point, and where the point sits inside it.
36
+ * Falls back to the main frame whenever the tree cannot be walked.
37
+ */
38
+ export async function resolveFrameTarget(page: Page, x: number, y: number): Promise<FrameTarget> {
39
+ let frame: Frame = page.mainFrame();
40
+ let localX = x;
41
+ let localY = y;
42
+
43
+ for (let depth = 0; depth < MAX_FRAME_DEPTH; depth += 1) {
44
+ const children = frame.childFrames();
45
+ if (children.length === 0) break;
46
+
47
+ let descended = false;
48
+
49
+ for (const child of children) {
50
+ try {
51
+ const element = await child.frameElement();
52
+ if (!element) continue;
53
+
54
+ const box = await element.boundingBox();
55
+ if (!box) {
56
+ await element.dispose();
57
+ continue;
58
+ }
59
+
60
+ const contains = x >= box.x && x <= box.x + box.width && y >= box.y && y <= box.y + box.height;
61
+ if (!contains) {
62
+ await element.dispose();
63
+ continue;
64
+ }
65
+
66
+ // The frame's viewport starts inside its border and padding, so the
67
+ // element box alone would be off by however thick those are.
68
+ const inset = await element.evaluate((node) => {
69
+ const style = getComputedStyle(node);
70
+ return {
71
+ left: parseFloat(style.borderLeftWidth) + parseFloat(style.paddingLeft),
72
+ top: parseFloat(style.borderTopWidth) + parseFloat(style.paddingTop)
73
+ };
74
+ });
75
+ await element.dispose();
76
+
77
+ localX = x - box.x - (inset.left || 0);
78
+ localY = y - box.y - (inset.top || 0);
79
+ frame = child;
80
+ descended = true;
81
+ break;
82
+ } catch {
83
+ // Detached mid-walk (frames come and go constantly on real pages) —
84
+ // try the next sibling rather than abandoning the whole resolution.
85
+ }
86
+ }
87
+
88
+ if (!descended) break;
89
+ }
90
+
91
+ return { frame, x: Math.round(localX), y: Math.round(localY) };
92
+ }