@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,332 @@
1
+ /**
2
+ * Input gestures — everything a person does with a mouse, keyboard or finger.
3
+ *
4
+ * These are `kind: 'input'`, so the runner hands consecutive ones to the native
5
+ * gesture engine in a single call: pointer movement stays continuous and the
6
+ * pacing between them is the engine's, not a round trip per click.
7
+ */
8
+
9
+ import { z } from 'zod';
10
+ import type { ActionDef } from './types';
11
+ import { commonFields, pointSchema, targetFields, targetFieldsNoText, toTarget } from './shared';
12
+ import { resolveProjectFiles } from '../paths';
13
+
14
+ export const click: ActionDef = {
15
+ type: 'click',
16
+ kind: 'input',
17
+ doc: `click {selector|text|x,y, button?, clickCount?} — click an element or a point.
18
+ Prefer selector/text: resolution scrolls the element into view and aims at its centre, so it survives reflow. Coordinates are for canvases and anything without a DOM handle.
19
+ button: left (default) | right | middle. clickCount: 2 for double-click, 3 to select a line.`,
20
+ schema: z.object({
21
+ type: z.literal('click'),
22
+ ...targetFields,
23
+ button: z.enum(['left', 'right', 'middle']).optional().describe('Mouse button (default: left).'),
24
+ clickCount: z.number().int().min(1).max(3).optional().describe('1 = single (default), 2 = double, 3 = triple.'),
25
+ ...commonFields
26
+ }),
27
+ toInput: (a) => ({ type: 'click', target: toTarget(a), button: a.button, clickCount: a.clickCount })
28
+ };
29
+
30
+ export const type_: ActionDef = {
31
+ type: 'type',
32
+ kind: 'input',
33
+ doc: `type {text, selector?|x,y?, clearFirst?, key?} — type into the focused field.
34
+ Give a selector/coords to focus a field first, so one batch can fill a whole form without interleaving clicks.
35
+ clearFirst defaults to true (selects all, then overwrites). Set false to append.
36
+ For a single key use \`key\` (Enter, Tab, Escape, ArrowDown…); for a chord use the \`press\` action.`,
37
+ schema: z.object({
38
+ type: z.literal('type'),
39
+ text: z.string().optional().describe('Text to type, character by character.'),
40
+ key: z.string().optional().describe('A single key to press instead of typing text (Enter, Tab, Escape, ArrowDown, Backspace…).'),
41
+ clearFirst: z.boolean().optional().describe('Clear the field before typing (default: true).'),
42
+ delay: z.number().optional().describe('Milliseconds between keystrokes (default: 30).'),
43
+ ...targetFieldsNoText,
44
+ ...commonFields
45
+ }),
46
+ toInput: (a) => ({
47
+ type: 'type',
48
+ text: a.text,
49
+ key: a.key,
50
+ clearFirst: a.clearFirst,
51
+ delay: a.delay,
52
+ // `text` here is what to type, so targeting is by selector/coords only.
53
+ target: a.selector || typeof a.x === 'number' ? toTarget({ x: a.x, y: a.y, selector: a.selector, nth: a.nth }) : undefined
54
+ })
55
+ };
56
+
57
+ export const press: ActionDef = {
58
+ type: 'press',
59
+ kind: 'input',
60
+ doc: `press {keys} — a key chord: "Control+A", "Meta+Shift+P", "Alt+ArrowLeft".
61
+ Modifiers are held for the duration and released in reverse, which is what shortcuts and IDE-like pages expect.`,
62
+ schema: z.object({
63
+ type: z.literal('press'),
64
+ keys: z.string().describe('Chord, e.g. "Control+Shift+K". Aliases: Ctrl, Cmd, Command, Option, Meta.'),
65
+ ...commonFields
66
+ }),
67
+ toInput: (a) => ({ type: 'press', keys: a.keys })
68
+ };
69
+
70
+ export const paste: ActionDef = {
71
+ type: 'paste',
72
+ kind: 'input',
73
+ doc: `paste {text} — insert text into the focused field as a paste.
74
+ Faster than \`type\` for long strings, and raises the same input events. Note this pastes the given text, not the user's clipboard.`,
75
+ schema: z.object({
76
+ type: z.literal('paste'),
77
+ text: z.string().describe('Text to insert at the caret.'),
78
+ ...commonFields
79
+ }),
80
+ toInput: (a) => ({ type: 'paste', text: a.text })
81
+ };
82
+
83
+ export const move: ActionDef = {
84
+ type: 'move',
85
+ kind: 'input',
86
+ doc: `move {selector|text|x,y, dwellMs?} — move the pointer without clicking.
87
+ Use dwellMs to linger so hover menus and tooltips have time to appear; that delay is usually why a submenu "never opens".`,
88
+ schema: z.object({
89
+ type: z.literal('move'),
90
+ ...targetFields,
91
+ dwellMs: z.number().optional().describe('Stay put for this long after arriving (hover reveals).'),
92
+ steps: z.number().optional().describe('Interpolation steps for the movement (default: 8).'),
93
+ ...commonFields
94
+ }),
95
+ toInput: (a) => ({ type: 'move', target: toTarget(a), dwellMs: a.dwellMs, steps: a.steps })
96
+ };
97
+
98
+ export const scroll: ActionDef = {
99
+ type: 'scroll',
100
+ kind: 'input',
101
+ doc: `scroll {deltaY, deltaX?, selector?|x,y?, smooth?} — wheel scroll.
102
+ deltaY positive scrolls down. Give a selector/coords to scroll a specific pane: the wheel applies to whatever is under the pointer, so an inner scroller needs the pointer over it.`,
103
+ schema: z.object({
104
+ type: z.literal('scroll'),
105
+ deltaX: z.number().optional().describe('Horizontal pixels (positive = right).'),
106
+ deltaY: z.number().optional().describe('Vertical pixels (positive = down).'),
107
+ smooth: z.boolean().optional().describe('Break the scroll into steps, as a trackpad would.'),
108
+ ...targetFields,
109
+ ...commonFields
110
+ }),
111
+ toInput: (a) => ({
112
+ type: 'scroll',
113
+ deltaX: a.deltaX,
114
+ deltaY: a.deltaY,
115
+ smooth: a.smooth,
116
+ target: a.selector || a.text || typeof a.x === 'number' ? toTarget(a) : undefined
117
+ })
118
+ };
119
+
120
+ export const drag: ActionDef = {
121
+ type: 'drag',
122
+ kind: 'input',
123
+ doc: `drag {from, to, mode?, holdMs?, durationMs?} — press, move, release.
124
+ Covers sliders, canvases, sortable lists, kanban cards and map panning.
125
+ mode is detected from the source element: "pointer" (mouse events, what JS drag libraries listen for) or "native" (HTML5 draggable="true", which ignores plain mouse events and needs CDP drag interception). Override only when detection is wrong.`,
126
+ schema: z.object({
127
+ type: z.literal('drag'),
128
+ from: pointSchema.describe('Where the drag starts.'),
129
+ to: pointSchema.describe('Where it is dropped.'),
130
+ mode: z.enum(['pointer', 'native']).optional().describe('Force a drag protocol instead of detecting it.'),
131
+ holdMs: z.number().optional().describe('Pause after pressing before moving (default: 120). Many drag libraries need this to arm.'),
132
+ durationMs: z.number().optional().describe('How long the movement itself takes.'),
133
+ steps: z.number().optional().describe('Interpolation steps (default: 16). More steps = smoother for canvases.'),
134
+ button: z.enum(['left', 'right', 'middle']).optional(),
135
+ ...commonFields
136
+ }),
137
+ toInput: (a) => ({
138
+ type: 'drag',
139
+ from: toTarget(a.from),
140
+ to: toTarget(a.to),
141
+ mode: a.mode,
142
+ holdMs: a.holdMs,
143
+ durationMs: a.durationMs,
144
+ steps: a.steps,
145
+ button: a.button
146
+ })
147
+ };
148
+
149
+ export const longPress: ActionDef = {
150
+ type: 'long_press',
151
+ kind: 'input',
152
+ doc: `long_press {selector|text|x,y, holdMs?} — press and hold (default 700ms).
153
+ Raises context menus and triggers touch-style "press and hold" affordances.`,
154
+ schema: z.object({
155
+ type: z.literal('long_press'),
156
+ ...targetFields,
157
+ holdMs: z.number().optional().describe('Hold duration in ms (default: 700).'),
158
+ button: z.enum(['left', 'right', 'middle']).optional(),
159
+ ...commonFields
160
+ }),
161
+ toInput: (a) => ({ type: 'long_press', target: toTarget(a), holdMs: a.holdMs, button: a.button })
162
+ };
163
+
164
+ export const tap: ActionDef = {
165
+ type: 'tap',
166
+ kind: 'input',
167
+ doc: `tap {selector|text|x,y} — a real touch tap.
168
+ Touch emulation is switched on for the gesture, so the page's touch handlers fire and touch feature detection reports true. Use on mobile/tablet viewports where a mouse click takes a different code path.`,
169
+ schema: z.object({
170
+ type: z.literal('tap'),
171
+ ...targetFields,
172
+ holdMs: z.number().optional().describe('Contact time before lifting (default: 60).'),
173
+ ...commonFields
174
+ }),
175
+ toInput: (a) => ({ type: 'tap', target: toTarget(a), holdMs: a.holdMs })
176
+ };
177
+
178
+ export const swipe: ActionDef = {
179
+ type: 'swipe',
180
+ kind: 'input',
181
+ doc: `swipe {from, to, durationMs?} — a one-finger touch drag.
182
+ This is how carousels, pull-to-refresh, bottom sheets and swipe-to-delete are tested; a wheel scroll does not exercise any of them.`,
183
+ schema: z.object({
184
+ type: z.literal('swipe'),
185
+ from: pointSchema.describe('Where the finger lands.'),
186
+ to: pointSchema.describe('Where it lifts.'),
187
+ durationMs: z.number().optional().describe('Gesture duration (default: 300). Shorter reads as a fling.'),
188
+ steps: z.number().optional().describe('Touch move samples (default: 12).'),
189
+ ...commonFields
190
+ }),
191
+ toInput: (a) => ({
192
+ type: 'swipe',
193
+ from: toTarget(a.from),
194
+ to: toTarget(a.to),
195
+ durationMs: a.durationMs,
196
+ steps: a.steps
197
+ })
198
+ };
199
+
200
+ export const pinch: ActionDef = {
201
+ type: 'pinch',
202
+ kind: 'input',
203
+ doc: `pinch {scale, x?, y?, durationMs?} — two-finger pinch about a point.
204
+ scale > 1 zooms in, < 1 zooms out. Defaults to the viewport centre.`,
205
+ schema: z.object({
206
+ type: z.literal('pinch'),
207
+ scale: z.number().optional().describe('Zoom factor (default: 2). Below 1 pinches in.'),
208
+ x: z.number().optional().describe('Centre X (default: viewport centre).'),
209
+ y: z.number().optional().describe('Centre Y (default: viewport centre).'),
210
+ durationMs: z.number().optional(),
211
+ ...commonFields
212
+ }),
213
+ toInput: (a) => ({
214
+ type: 'pinch',
215
+ scale: a.scale,
216
+ center: typeof a.x === 'number' && typeof a.y === 'number' ? { x: a.x, y: a.y } : undefined,
217
+ durationMs: a.durationMs
218
+ })
219
+ };
220
+
221
+ export const wait: ActionDef = {
222
+ type: 'wait',
223
+ kind: 'input',
224
+ doc: `wait {ms} — pause.
225
+ A blunt instrument: prefer wait_for, which returns as soon as the condition holds instead of always costing the full delay.`,
226
+ schema: z.object({
227
+ type: z.literal('wait'),
228
+ ms: z.number().describe('Milliseconds to pause.'),
229
+ ...commonFields
230
+ }),
231
+ toInput: (a) => ({ type: 'wait', delay: a.ms })
232
+ };
233
+
234
+ export const focus: ActionDef = {
235
+ type: 'focus',
236
+ kind: 'input',
237
+ doc: `focus {selector|text} — focus an element without clicking it.
238
+ Useful when a click would also trigger something (a link, a toggle).`,
239
+ schema: z.object({
240
+ type: z.literal('focus'),
241
+ ...targetFields,
242
+ ...commonFields
243
+ }),
244
+ toInput: (a) => ({ type: 'focus', target: toTarget(a) })
245
+ };
246
+
247
+ export const clear: ActionDef = {
248
+ type: 'clear',
249
+ kind: 'input',
250
+ doc: `clear {selector?|x,y?} — empty a field (select all, delete).`,
251
+ schema: z.object({
252
+ type: z.literal('clear'),
253
+ ...targetFields,
254
+ ...commonFields
255
+ }),
256
+ toInput: (a) => ({ type: 'clear', target: toTarget(a) })
257
+ };
258
+
259
+ export const selectOption: ActionDef = {
260
+ type: 'select_option',
261
+ kind: 'input',
262
+ doc: `select_option {selector, value|label|index} — choose from a native <select>.
263
+ Clicking a <select> opens a browser-owned popup that is not part of the page, so it cannot be driven by clicks; this sets the value and raises input+change.`,
264
+ schema: z.object({
265
+ type: z.literal('select_option'),
266
+ ...targetFields,
267
+ value: z.string().optional().describe('Match the option\'s value attribute.'),
268
+ label: z.string().optional().describe('Match the option\'s visible text (exact, then substring).'),
269
+ index: z.number().int().min(0).optional().describe('Match by position.'),
270
+ ...commonFields
271
+ }),
272
+ toInput: (a) => ({
273
+ type: 'select_option',
274
+ target: toTarget(a),
275
+ value: a.value,
276
+ label: a.label,
277
+ index: a.index
278
+ })
279
+ };
280
+
281
+ export const extract: ActionDef = {
282
+ type: 'extract',
283
+ kind: 'input',
284
+ doc: `extract {selector, attribute?, all?} — read a value out of the page.
285
+ The selector is forgiving: "email", "#email" and [name=email] all resolve. attribute reads a specific one; all returns every match.`,
286
+ schema: z.object({
287
+ type: z.literal('extract'),
288
+ selector: z.string().describe('Element identifier: a CSS selector, an id, a name, or a test id.'),
289
+ attribute: z.string().optional().describe('Read this attribute instead of auto-detecting value/text.'),
290
+ all: z.boolean().optional().describe('Return every match instead of the first.'),
291
+ ...commonFields
292
+ }),
293
+ toInput: (a) => ({ type: 'extract_data', selector: a.selector, attribute: a.attribute, all: a.all })
294
+ };
295
+
296
+ export const upload: ActionDef = {
297
+ type: 'upload',
298
+ kind: 'input',
299
+ doc: `upload {selector, files} — attach files to a file input.
300
+ Paths are relative to the project directory and must stay inside it. A file chooser cannot be driven any other way: it is an OS dialog, not part of the page.`,
301
+ schema: z.object({
302
+ type: z.literal('upload'),
303
+ ...targetFieldsNoText,
304
+ files: z.array(z.string()).min(1).describe('Project-relative file paths.'),
305
+ ...commonFields
306
+ }),
307
+ toInput: async (a, ctx) => ({
308
+ type: 'upload',
309
+ target: toTarget({ x: a.x, y: a.y, selector: a.selector, nth: a.nth }),
310
+ files: await resolveProjectFiles(a.files, ctx.projectId)
311
+ })
312
+ };
313
+
314
+ export const inputActions: ActionDef[] = [
315
+ click,
316
+ type_,
317
+ press,
318
+ paste,
319
+ move,
320
+ scroll,
321
+ drag,
322
+ longPress,
323
+ tap,
324
+ swipe,
325
+ pinch,
326
+ wait,
327
+ focus,
328
+ clear,
329
+ selectOption,
330
+ extract,
331
+ upload
332
+ ];
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Reading the page: locating elements, extracting its content, capturing it.
3
+ */
4
+
5
+ import { z } from 'zod';
6
+ import { writeFile } from 'node:fs/promises';
7
+ import { relative } from 'node:path';
8
+ import { findElements } from '$backend/preview/browser/element-locator';
9
+ import { projectQueries } from '$backend/database/queries/project-queries';
10
+ import type { ActionDef } from './types';
11
+ import { commonFields } from './shared';
12
+ import { analyzePage } from './dom-analyze';
13
+ import { resolveWritePath } from '../paths';
14
+
15
+ export const find: ActionDef = {
16
+ type: 'find',
17
+ kind: 'control',
18
+ doc: `find {selector?, text?, role?, limit?} — locate elements and get their positions.
19
+ Returns tag, text, a reusable selector and a centre point for each match, iframes included.
20
+ This is the cheap alternative to a screenshot: to click something you can name, find it and click by selector — no image, no vision, no coordinate guessing.`,
21
+ schema: z.object({
22
+ type: z.literal('find'),
23
+ selector: z.string().optional().describe('CSS selector to match.'),
24
+ text: z.string().optional().describe('Visible text to match, when no selector is known.'),
25
+ role: z.string().optional().describe('Filter by ARIA role or tag (button, link, textbox…).'),
26
+ limit: z.number().int().min(1).max(100).optional().describe('Maximum matches (default: 20).'),
27
+ visibleOnly: z.boolean().optional().describe('Skip hidden elements (default: true).'),
28
+ ...commonFields
29
+ }),
30
+ run: async (args, ctx) => {
31
+ if (!args.selector && !args.text && !args.role) {
32
+ throw new Error('find needs one of: selector, text, or role');
33
+ }
34
+
35
+ const matches = await findElements(ctx.tab.page, {
36
+ selector: args.selector,
37
+ text: args.text,
38
+ role: args.role,
39
+ limit: args.limit,
40
+ visibleOnly: args.visibleOnly
41
+ });
42
+
43
+ if (matches.length === 0) return { summary: 'no matches' };
44
+
45
+ const lines = matches.map((m, i) => {
46
+ const bits = [
47
+ `[${i}] <${m.tag}> "${m.text || m.name || m.placeholder || ''}"`,
48
+ ` at (${m.x}, ${m.y}) · ${m.box.width}×${m.box.height}${m.inFrame ? ' · in iframe' : ''}${m.enabled ? '' : ' · disabled'}`,
49
+ ` selector: ${m.selector}`
50
+ ];
51
+ if (m.href) bits.push(` href: ${m.href}`);
52
+ if (m.value) bits.push(` value: ${m.value}`);
53
+ return bits.join('\n');
54
+ });
55
+
56
+ return { summary: `${matches.length} match(es)`, detail: lines.join('\n') };
57
+ }
58
+ };
59
+
60
+ export const analyzeDom: ActionDef = {
61
+ type: 'analyze_dom',
62
+ kind: 'control',
63
+ doc: `analyze_dom {include?} — the page as text: links, headings, content, forms, metadata.
64
+ The primary tool for reading and exploring. Far cheaper than a screenshot and it sees the whole document, not just the part currently on screen — scrolling to "see more" is never necessary.
65
+ include: navigation | structure | content | forms | summary. Omit for all.
66
+ Blind spots: no coordinates, and it cannot see inside iframes (summary.hasIframes tells you when that matters).`,
67
+ schema: z.object({
68
+ type: z.literal('analyze_dom'),
69
+ include: z
70
+ .array(z.enum(['navigation', 'structure', 'content', 'forms', 'summary']))
71
+ .optional()
72
+ .describe('Sections to return. ["navigation","content"] covers most reading tasks.'),
73
+ ...commonFields
74
+ }),
75
+ run: async (args, ctx) => {
76
+ const analysis = await analyzePage(ctx.tab.page);
77
+
78
+ const wanted = args.include ? new Set<string>(args.include) : null;
79
+ const filtered = wanted
80
+ ? Object.fromEntries(Object.entries(analysis).filter(([key]) => wanted.has(key)))
81
+ : analysis;
82
+
83
+ const linkCount = analysis.navigation.links.length;
84
+ return {
85
+ summary: `${linkCount} link(s), ${analysis.structure.headings.length} heading(s), ${analysis.content.paragraphs.length} text block(s)`,
86
+ detail: JSON.stringify(filtered, null, 2)
87
+ };
88
+ }
89
+ };
90
+
91
+ export const screenshot: ActionDef = {
92
+ type: 'screenshot',
93
+ kind: 'control',
94
+ doc: `screenshot {fullPage?, selector?, format?, quality?, saveTo?, return?} — capture the page.
95
+ Needed for what the DOM cannot express: canvases, charts, iframes, captchas, and any visual check of layout or styling.
96
+ saveTo writes a file under the project directory; with return:"file" the image is not sent back at all, which is what makes "capture twenty pages" affordable.
97
+ format:"jpeg" with quality is much smaller than the default PNG when only the gist matters.`,
98
+ schema: z.object({
99
+ type: z.literal('screenshot'),
100
+ fullPage: z.boolean().optional().describe('Capture the whole scrollable page instead of the viewport.'),
101
+ selector: z.string().optional().describe('Capture just this element.'),
102
+ format: z.enum(['png', 'jpeg']).optional().describe('Image format (default: png).'),
103
+ quality: z.number().int().min(1).max(100).optional().describe('JPEG quality (default: 80). Ignored for PNG.'),
104
+ saveTo: z.string().optional().describe('Project-relative path to write the image to.'),
105
+ return: z.enum(['inline', 'file', 'both']).optional().describe('inline (default) sends the image back; file only writes it; both does both.'),
106
+ ...commonFields
107
+ }),
108
+ run: async (args, ctx) => {
109
+ const format = args.format ?? 'png';
110
+ const mode = args.return ?? (args.saveTo ? 'both' : 'inline');
111
+
112
+ if (mode !== 'inline' && !args.saveTo) throw new Error('return:"file"/"both" needs saveTo');
113
+
114
+ const options = {
115
+ type: format,
116
+ fullPage: !!args.fullPage,
117
+ ...(format === 'jpeg' ? { quality: args.quality ?? 80 } : {})
118
+ } as const;
119
+
120
+ let buffer: Uint8Array;
121
+ if (args.selector) {
122
+ const element = await ctx.tab.page.$(args.selector);
123
+ if (!element) throw new Error(`No element matched "${args.selector}"`);
124
+ try {
125
+ buffer = await element.screenshot(options);
126
+ } finally {
127
+ await element.dispose().catch(() => {});
128
+ }
129
+ } else {
130
+ buffer = await ctx.tab.page.screenshot(options);
131
+ }
132
+
133
+ const parts: string[] = [`${format}, ${Math.round(buffer.byteLength / 1024)}KB${args.fullPage ? ', full page' : ''}`];
134
+
135
+ if (args.saveTo) {
136
+ const absolute = await resolveWritePath(args.saveTo, ctx.projectId);
137
+ await writeFile(absolute, buffer);
138
+ const root = projectQueries.getById(ctx.projectId)?.path;
139
+ parts.push(`saved to ${root ? relative(root, absolute) : absolute}`);
140
+ }
141
+
142
+ return {
143
+ summary: parts.join(' · '),
144
+ images:
145
+ mode === 'file'
146
+ ? undefined
147
+ : [
148
+ {
149
+ data: Buffer.from(buffer).toString('base64'),
150
+ mimeType: format === 'jpeg' ? 'image/jpeg' : 'image/png',
151
+ label: args.selector ? `screenshot of ${args.selector}` : 'screenshot'
152
+ }
153
+ ]
154
+ };
155
+ }
156
+ };
157
+
158
+ export const inspectActions: ActionDef[] = [find, analyzeDom, screenshot];
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Navigation and synchronisation.
3
+ *
4
+ * `wait_for` lives here rather than with the input gestures because it is not
5
+ * a gesture: it is how a batch stays honest about the page having caught up.
6
+ */
7
+
8
+ import { z } from 'zod';
9
+ import { sleep } from '$shared/utils/async';
10
+ import type { ActionDef } from './types';
11
+ import { commonFields } from './shared';
12
+
13
+ export const navigate: ActionDef = {
14
+ type: 'navigate',
15
+ kind: 'control',
16
+ doc: `navigate {url} — load a URL in the current tab.
17
+ Following a link you already have the href for is cheaper and far more reliable than clicking it. Session state (cookies, storage) is kept.`,
18
+ schema: z.object({
19
+ type: z.literal('navigate'),
20
+ url: z.string().url().describe('Target URL including protocol. Redirects are followed.'),
21
+ ...commonFields
22
+ }),
23
+ run: async (args, ctx) => {
24
+ // Goes through the service, not page.goto: the service is what records
25
+ // the navigation, re-reads title/favicon and re-baselines history, which
26
+ // is what keeps the toolbar and tab strip truthful.
27
+ const finalUrl = await ctx.service.navigateTab(ctx.tab.id, args.url);
28
+ await sleep(300);
29
+ return { summary: `→ ${finalUrl}` };
30
+ }
31
+ };
32
+
33
+ export const goBack: ActionDef = {
34
+ type: 'go_back',
35
+ kind: 'control',
36
+ doc: `go_back {steps?} — walk back through the tab's history.`,
37
+ schema: z.object({
38
+ type: z.literal('go_back'),
39
+ steps: z.number().int().min(1).optional().describe('How many entries (default: 1).'),
40
+ ...commonFields
41
+ }),
42
+ run: async (args, ctx) => {
43
+ const moved = await ctx.service.goHistory(ctx.tab.id, -(args.steps ?? 1));
44
+ if (!moved) throw new Error('Nothing to go back to');
45
+ await sleep(300);
46
+ return { summary: `← ${ctx.service.getTab(ctx.tab.id)?.url ?? ''}` };
47
+ }
48
+ };
49
+
50
+ export const goForward: ActionDef = {
51
+ type: 'go_forward',
52
+ kind: 'control',
53
+ doc: `go_forward {steps?} — walk forward through the tab's history.`,
54
+ schema: z.object({
55
+ type: z.literal('go_forward'),
56
+ steps: z.number().int().min(1).optional().describe('How many entries (default: 1).'),
57
+ ...commonFields
58
+ }),
59
+ run: async (args, ctx) => {
60
+ const moved = await ctx.service.goHistory(ctx.tab.id, args.steps ?? 1);
61
+ if (!moved) throw new Error('Nothing to go forward to');
62
+ await sleep(300);
63
+ return { summary: `→ ${ctx.service.getTab(ctx.tab.id)?.url ?? ''}` };
64
+ }
65
+ };
66
+
67
+ export const reload: ActionDef = {
68
+ type: 'reload',
69
+ kind: 'control',
70
+ doc: `reload {hard?} — reload the page. hard bypasses the cache.`,
71
+ schema: z.object({
72
+ type: z.literal('reload'),
73
+ hard: z.boolean().optional().describe('Ignore the cache.'),
74
+ ...commonFields
75
+ }),
76
+ run: async (args, ctx) => {
77
+ if (args.hard) {
78
+ await ctx.tab.page.evaluate(() => window.location.reload());
79
+ } else {
80
+ await ctx.tab.page.reload({ waitUntil: 'domcontentloaded', timeout: 30_000 });
81
+ }
82
+ await sleep(300);
83
+ return { summary: ctx.tab.page.url() };
84
+ }
85
+ };
86
+
87
+ export const waitFor: ActionDef = {
88
+ type: 'wait_for',
89
+ kind: 'control',
90
+ doc: `wait_for {selector|text|urlContains|state, timeout?} — wait for the page to catch up.
91
+ Returns the moment the condition holds, so it costs only what it has to.
92
+ state: visible (default, with selector/text) · hidden · navigation · networkIdle.
93
+ Reach for this instead of wait{ms} — a fixed delay is either too short and the batch fails, or too long and every run pays for it.`,
94
+ schema: z.object({
95
+ type: z.literal('wait_for'),
96
+ selector: z.string().optional().describe('Wait for this CSS selector.'),
97
+ text: z.string().optional().describe('Wait for this text to appear on the page.'),
98
+ urlContains: z.string().optional().describe('Wait until the URL contains this substring.'),
99
+ state: z.enum(['visible', 'hidden', 'navigation', 'networkIdle']).optional().describe('What to wait for (default: visible).'),
100
+ timeout: z.number().optional().describe('Milliseconds before giving up (default: 10000).'),
101
+ ...commonFields
102
+ }),
103
+ run: async (args, ctx) => {
104
+ const timeout = args.timeout ?? 10_000;
105
+ const page = ctx.tab.page;
106
+ const started = Date.now();
107
+ const took = () => `${Date.now() - started}ms`;
108
+
109
+ if (args.state === 'navigation') {
110
+ await page.waitForNavigation({ waitUntil: 'domcontentloaded', timeout });
111
+ return { summary: `navigated in ${took()} → ${page.url()}` };
112
+ }
113
+
114
+ if (args.state === 'networkIdle') {
115
+ await page.waitForNetworkIdle({ timeout }).catch(() => {
116
+ throw new Error(`Network did not settle within ${timeout}ms`);
117
+ });
118
+ return { summary: `network idle in ${took()}` };
119
+ }
120
+
121
+ if (args.urlContains) {
122
+ await page.waitForFunction(
123
+ (needle: string) => window.location.href.includes(needle),
124
+ { timeout, polling: 200 },
125
+ args.urlContains
126
+ );
127
+ return { summary: `url matched in ${took()} → ${page.url()}` };
128
+ }
129
+
130
+ if (args.selector) {
131
+ await page.waitForSelector(args.selector, {
132
+ timeout,
133
+ visible: args.state !== 'hidden',
134
+ hidden: args.state === 'hidden'
135
+ });
136
+ return { summary: `"${args.selector}" ${args.state ?? 'visible'} in ${took()}` };
137
+ }
138
+
139
+ if (args.text) {
140
+ const shouldVanish = args.state === 'hidden';
141
+ await page.waitForFunction(
142
+ (needle: string, gone: boolean) => {
143
+ const present = (document.body?.innerText ?? '').includes(needle);
144
+ return gone ? !present : present;
145
+ },
146
+ { timeout, polling: 200 },
147
+ args.text,
148
+ shouldVanish
149
+ );
150
+ return { summary: `text ${shouldVanish ? 'gone' : 'present'} in ${took()}` };
151
+ }
152
+
153
+ throw new Error('wait_for needs one of: selector, text, urlContains, or state');
154
+ }
155
+ };
156
+
157
+ export const navigationActions: ActionDef[] = [navigate, goBack, goForward, reload, waitFor];