@myrialabs/clopen 0.4.21 → 0.4.23
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.
- package/README.md +2 -1
- package/backend/artifacts/generate.ts +11 -5
- package/backend/auth/permissions.ts +8 -8
- package/backend/engine/README.md +11 -8
- package/backend/engine/adapters/codex/error-handler.ts +1 -1
- package/backend/engine/adapters/qwen/error-handler.ts +1 -1
- package/backend/engine/docs/adapter-contract.md +66 -2
- package/backend/engine/docs/adding-an-engine.md +46 -7
- package/backend/engine/docs/frontend-and-chat.md +80 -17
- package/backend/engine/docs/lessons-learned.md +126 -7
- package/backend/engine/docs/quick-reference.md +12 -3
- package/backend/engine/docs/{system-tools.md → stack.md} +35 -6
- package/backend/engine/docs/websocket-routes.md +54 -15
- package/backend/engine/install-runner.ts +4 -4
- package/backend/engine/resolve-model.ts +87 -0
- package/backend/engine/structured-helpers.test.ts +64 -0
- package/backend/engine/structured-helpers.ts +105 -13
- package/backend/mcp/README.md +32 -11
- package/backend/mcp/internal/config.ts +3 -20
- package/backend/mcp/internal/servers/browser-automation/actions/console.ts +65 -0
- package/backend/mcp/internal/servers/browser-automation/actions/dom-analyze.ts +202 -0
- package/backend/mcp/internal/servers/browser-automation/actions/index.ts +31 -0
- package/backend/mcp/internal/servers/browser-automation/actions/input.ts +332 -0
- package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +158 -0
- package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +157 -0
- package/backend/mcp/internal/servers/browser-automation/actions/shared.ts +60 -0
- package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -0
- package/backend/mcp/internal/servers/browser-automation/actions/types.ts +79 -0
- package/backend/mcp/internal/servers/browser-automation/context.ts +100 -0
- package/backend/mcp/internal/servers/browser-automation/description.ts +60 -0
- package/backend/mcp/internal/servers/browser-automation/format.ts +62 -0
- package/backend/mcp/internal/servers/browser-automation/index.ts +36 -784
- package/backend/mcp/internal/servers/browser-automation/paths.ts +71 -0
- package/backend/mcp/internal/servers/browser-automation/runner.ts +269 -0
- package/backend/mcp/internal/servers/browser-automation/schema.ts +26 -0
- package/backend/preview/browser/browser-console-manager.ts +310 -156
- package/backend/preview/browser/browser-dialog-handler.ts +45 -16
- package/backend/preview/browser/browser-host-bridge.ts +471 -0
- package/backend/preview/browser/browser-interaction-handler.ts +868 -297
- package/backend/preview/browser/browser-mcp-control.ts +7 -2
- package/backend/preview/browser/browser-native-ui-handler.ts +455 -81
- package/backend/preview/browser/browser-navigation-tracker.ts +56 -0
- package/backend/preview/browser/browser-pool.ts +83 -9
- package/backend/preview/browser/browser-preview-service.ts +432 -53
- package/backend/preview/browser/browser-tab-manager.ts +16 -16
- package/backend/preview/browser/browser-video-capture.ts +1334 -386
- package/backend/preview/browser/capture-profile.ts +213 -0
- package/backend/preview/browser/element-locator.ts +357 -0
- package/backend/preview/browser/frame-targeting.ts +92 -0
- package/backend/preview/browser/scripts/audio-stream.ts +258 -78
- package/backend/preview/browser/scripts/host-bridge.ts +1277 -0
- package/backend/preview/browser/scripts/video-stream.ts +803 -177
- package/backend/preview/browser/types.ts +397 -37
- package/backend/utils/cli.ts +1 -1
- package/backend/utils/path-enrich.ts +2 -2
- package/backend/ws/README.md +1 -1
- package/backend/ws/artifacts/generate.ts +2 -1
- package/backend/ws/engine/codex/accounts.ts +1 -1
- package/backend/ws/engine/codex/status.ts +1 -1
- package/backend/ws/git/branch-name.ts +11 -5
- package/backend/ws/git/commit-message.ts +11 -5
- package/backend/ws/index.ts +3 -3
- package/backend/ws/preview/browser/host.ts +95 -0
- package/backend/ws/preview/browser/interact.ts +204 -10
- package/backend/ws/preview/browser/native-ui.ts +31 -1
- package/backend/ws/preview/browser/tab-info.ts +10 -1
- package/backend/ws/preview/browser/tab.ts +43 -0
- package/backend/ws/preview/browser/webcodecs.ts +180 -53
- package/backend/ws/preview/index.ts +58 -1
- package/backend/ws/{system-tools → stack}/access.ts +1 -1
- package/backend/ws/stack/index.ts +16 -0
- package/backend/ws/{system-tools → stack}/install.ts +7 -7
- package/backend/ws/{system-tools → stack}/status.ts +7 -7
- package/dist/assets/{index-CEGW8vEt.js → index-DH_GO0Lf.js} +1 -1
- package/dist/assets/{index-B8YRz8wG.js → index-igSQ3JaM.js} +1 -1
- package/dist/assets/main-BD3-qPfT.css +1 -0
- package/dist/assets/{main-D-2ByODy.js → main-D-d8SFfW.js} +384 -358
- package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/stores/settings.ts +6 -0
- package/backend/mcp/internal/servers/browser-automation/actions.ts +0 -159
- package/backend/mcp/internal/servers/browser-automation/browser.ts +0 -375
- package/backend/mcp/internal/servers/browser-automation/inspection.ts +0 -495
- package/backend/ws/system-tools/index.ts +0 -16
- package/dist/assets/main-D8I0MfRQ.css +0 -1
|
@@ -12,17 +12,97 @@ export function buildJsonPrompt(prompt: string, schema: Record<string, unknown>)
|
|
|
12
12
|
return `${prompt}
|
|
13
13
|
|
|
14
14
|
IMPORTANT: You MUST respond with ONLY a valid JSON object matching this schema, no other text, no markdown fences, no commentary:
|
|
15
|
-
${JSON.stringify(schema, null, 2)}
|
|
15
|
+
${JSON.stringify(schema, null, 2)}
|
|
16
|
+
|
|
17
|
+
End your response immediately after the closing brace — no explanation, no follow-up. Inside string values, escape every newline as \\n and every quote as \\".`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Scan out every top-level `{ … }` object in `text`.
|
|
22
|
+
*
|
|
23
|
+
* Brace counting alone is not enough: a `}` inside a string value would close
|
|
24
|
+
* the object early, so this tracks string/escape state as it walks. Unbalanced
|
|
25
|
+
* tails (a truncated response) yield nothing rather than a half object.
|
|
26
|
+
*/
|
|
27
|
+
function balancedObjects(text: string): string[] {
|
|
28
|
+
const objects: string[] = [];
|
|
29
|
+
let depth = 0;
|
|
30
|
+
let start = -1;
|
|
31
|
+
let inString = false;
|
|
32
|
+
let escaped = false;
|
|
33
|
+
|
|
34
|
+
for (let i = 0; i < text.length; i++) {
|
|
35
|
+
const ch = text[i];
|
|
36
|
+
|
|
37
|
+
if (inString) {
|
|
38
|
+
if (escaped) escaped = false;
|
|
39
|
+
else if (ch === '\\') escaped = true;
|
|
40
|
+
else if (ch === '"') inString = false;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (ch === '"') inString = true;
|
|
45
|
+
else if (ch === '{') {
|
|
46
|
+
if (depth === 0) start = i;
|
|
47
|
+
depth++;
|
|
48
|
+
} else if (ch === '}' && depth > 0) {
|
|
49
|
+
depth--;
|
|
50
|
+
if (depth === 0 && start !== -1) {
|
|
51
|
+
objects.push(text.slice(start, i + 1));
|
|
52
|
+
start = -1;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
return objects;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Escape raw control characters that appear inside string literals.
|
|
62
|
+
*
|
|
63
|
+
* JSON forbids a literal newline or tab inside a string, but models emit them
|
|
64
|
+
* constantly when a field holds Markdown (an artifact body, a commit body).
|
|
65
|
+
* Characters outside strings are left alone so structure is never altered.
|
|
66
|
+
*/
|
|
67
|
+
function escapeControlCharsInStrings(text: string): string {
|
|
68
|
+
const ESCAPES: Record<string, string> = { '\n': '\\n', '\r': '\\r', '\t': '\\t', '\f': '\\f', '\b': '\\b' };
|
|
69
|
+
let out = '';
|
|
70
|
+
let inString = false;
|
|
71
|
+
let escaped = false;
|
|
72
|
+
|
|
73
|
+
for (const ch of text) {
|
|
74
|
+
if (inString) {
|
|
75
|
+
if (escaped) escaped = false;
|
|
76
|
+
else if (ch === '\\') escaped = true;
|
|
77
|
+
else if (ch === '"') inString = false;
|
|
78
|
+
|
|
79
|
+
if (!escaped && ch < ' ') {
|
|
80
|
+
out += ESCAPES[ch] ?? `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
} else if (ch === '"') {
|
|
84
|
+
inString = true;
|
|
85
|
+
}
|
|
86
|
+
out += ch;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return out;
|
|
16
90
|
}
|
|
17
91
|
|
|
18
92
|
/**
|
|
19
93
|
* Extract a JSON object from a model response.
|
|
20
94
|
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
* 1. ```json … ```
|
|
24
|
-
* 2.
|
|
25
|
-
*
|
|
95
|
+
* Prompt-engineered engines get whatever the model felt like emitting, so this
|
|
96
|
+
* tries, in order:
|
|
97
|
+
* 1. Every ```json … ``` fenced block
|
|
98
|
+
* 2. Every top-level balanced `{ … }` object — models routinely append
|
|
99
|
+
* commentary after the JSON, and that commentary can itself contain braces
|
|
100
|
+
* 3. First `{` … last `}` — salvages an object whose braces only look
|
|
101
|
+
* unbalanced because of a stray brace in a string
|
|
102
|
+
* 4. The raw trimmed text
|
|
103
|
+
*
|
|
104
|
+
* Each candidate is parsed as-is first, then with control characters inside
|
|
105
|
+
* strings escaped.
|
|
26
106
|
*
|
|
27
107
|
* Throws if nothing parses.
|
|
28
108
|
*/
|
|
@@ -33,8 +113,11 @@ export function extractJson<T = unknown>(text: string): T {
|
|
|
33
113
|
}
|
|
34
114
|
|
|
35
115
|
const candidates: string[] = [];
|
|
36
|
-
const
|
|
37
|
-
|
|
116
|
+
for (const fence of trimmed.matchAll(/```(?:json)?\s*([\s\S]*?)```/g)) {
|
|
117
|
+
candidates.push(fence[1].trim());
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
candidates.push(...balancedObjects(trimmed));
|
|
38
121
|
|
|
39
122
|
const braceStart = trimmed.indexOf('{');
|
|
40
123
|
const braceEnd = trimmed.lastIndexOf('}');
|
|
@@ -46,14 +129,23 @@ export function extractJson<T = unknown>(text: string): T {
|
|
|
46
129
|
|
|
47
130
|
let lastError: unknown;
|
|
48
131
|
for (const candidate of candidates) {
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
132
|
+
const repaired = escapeControlCharsInStrings(candidate);
|
|
133
|
+
for (const variant of repaired === candidate ? [candidate] : [candidate, repaired]) {
|
|
134
|
+
try {
|
|
135
|
+
return JSON.parse(variant) as T;
|
|
136
|
+
} catch (err) {
|
|
137
|
+
lastError = err;
|
|
138
|
+
}
|
|
53
139
|
}
|
|
54
140
|
}
|
|
141
|
+
|
|
142
|
+
// Show both ends: a truncated response and a response with trailing prose
|
|
143
|
+
// fail identically from the head alone.
|
|
144
|
+
const preview = trimmed.length > 400
|
|
145
|
+
? `${trimmed.slice(0, 200)}… [${trimmed.length} chars] …${trimmed.slice(-200)}`
|
|
146
|
+
: trimmed;
|
|
55
147
|
throw new Error(
|
|
56
|
-
`Response did not contain valid JSON: ${
|
|
148
|
+
`Response did not contain valid JSON: ${preview}` +
|
|
57
149
|
(lastError instanceof Error ? ` (${lastError.message})` : '')
|
|
58
150
|
);
|
|
59
151
|
}
|
package/backend/mcp/README.md
CHANGED
|
@@ -187,10 +187,14 @@ backend/mcp/
|
|
|
187
187
|
│ │ ├── index.ts
|
|
188
188
|
│ │ └── get-temperature.ts
|
|
189
189
|
│ └── browser-automation/ # Example: Browser automation service
|
|
190
|
-
│ ├── index.ts
|
|
191
|
-
│ ├──
|
|
192
|
-
│ ├──
|
|
193
|
-
│
|
|
190
|
+
│ ├── index.ts # One tool (`actions`), assembled from the registry
|
|
191
|
+
│ ├── schema.ts # Discriminated union over every action
|
|
192
|
+
│ ├── description.ts # Tool docs, generated from the registry
|
|
193
|
+
│ ├── runner.ts # Batch execution: grouping, retargeting, reporting
|
|
194
|
+
│ ├── context.ts # Project / chat-session / tab resolution
|
|
195
|
+
│ ├── format.ts # Run report → MCP content blocks
|
|
196
|
+
│ ├── paths.ts # Project-scoped file paths (screenshot, upload)
|
|
197
|
+
│ └── actions/ # One module per group; index.ts is the registry
|
|
194
198
|
├── external/ # User-installed servers from the official registry
|
|
195
199
|
│ ├── types.ts # CatalogServer / ResolvedExternalServer
|
|
196
200
|
│ ├── registry-client.ts # Fetch + normalise registry.modelcontextprotocol.io
|
|
@@ -220,19 +224,36 @@ servers/
|
|
|
220
224
|
└── utils.ts # Shared utilities
|
|
221
225
|
```
|
|
222
226
|
|
|
223
|
-
|
|
227
|
+
`browser-automation` goes one step further: it exposes a **single** tool whose
|
|
228
|
+
first argument is an array of actions, so an agent batches a whole interaction
|
|
229
|
+
into one call instead of paying a round trip per click. Its actions live in a
|
|
230
|
+
registry, and the tool's schema, its documentation and the runner's dispatch
|
|
231
|
+
table are all derived from that one list — adding an action is one file plus one
|
|
232
|
+
registry line, and the three cannot drift apart.
|
|
233
|
+
|
|
224
234
|
```
|
|
225
235
|
servers/browser-automation/
|
|
226
|
-
├── index.ts #
|
|
227
|
-
├──
|
|
228
|
-
├──
|
|
229
|
-
├──
|
|
230
|
-
|
|
231
|
-
|
|
236
|
+
├── index.ts # defineServer, one tool
|
|
237
|
+
├── schema.ts # z.discriminatedUnion over every action's schema
|
|
238
|
+
├── description.ts # Prose + a reference generated from each action's `doc`
|
|
239
|
+
├── runner.ts # Runs the batch, reports per action
|
|
240
|
+
└── actions/
|
|
241
|
+
├── index.ts # THE registry
|
|
242
|
+
├── tabs.ts · navigation.ts · input.ts · inspect.ts · console.ts
|
|
243
|
+
└── dom-analyze.ts # Large browser-side program, kept on its own
|
|
232
244
|
```
|
|
233
245
|
|
|
234
246
|
### Data Flow
|
|
235
247
|
|
|
248
|
+
> **Where the DB rows come from.** Code-defined internal servers are mirrored
|
|
249
|
+
> into `mcp_servers` by `syncInternalServers()` (`internal/config.ts`), which is
|
|
250
|
+
> called from `backend/bootstrap.ts::bootstrapAfterDbInit()` — shared by server
|
|
251
|
+
> startup **and** the "Clear All Data" handler. Clear-data wipes `~/.clopen` and
|
|
252
|
+
> re-runs only migrations + seeders on the live process, so a built-in synced
|
|
253
|
+
> from code (Browser Automation, …) would otherwise disappear from Settings →
|
|
254
|
+
> MCP until the next restart. Anything else established from code after
|
|
255
|
+
> `initializeDatabase()` belongs in that same function.
|
|
256
|
+
|
|
236
257
|
**Claude Code (in-process):**
|
|
237
258
|
```
|
|
238
259
|
1. Server Definition (servers/weather/index.ts)
|
|
@@ -33,26 +33,9 @@ import { getMcpServiceToken } from './service-token';
|
|
|
33
33
|
export const mcpServersConfig: Record<ServerName, ServerConfig> = {
|
|
34
34
|
"browser-automation": {
|
|
35
35
|
enabled: true,
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
"switch_tab",
|
|
40
|
-
"open_new_tab",
|
|
41
|
-
"close_tab",
|
|
42
|
-
|
|
43
|
-
// Navigation
|
|
44
|
-
"navigate",
|
|
45
|
-
|
|
46
|
-
// Browser Actions
|
|
47
|
-
"actions",
|
|
48
|
-
|
|
49
|
-
// Page Inspection
|
|
50
|
-
"analyze_dom",
|
|
51
|
-
"take_screenshot",
|
|
52
|
-
"get_console_logs",
|
|
53
|
-
"clear_console_logs",
|
|
54
|
-
"execute_console",
|
|
55
|
-
]
|
|
36
|
+
// One tool. Every browser capability is an action inside `actions`, so a
|
|
37
|
+
// whole interaction is one call and the agent decides what to batch.
|
|
38
|
+
tools: ["actions"]
|
|
56
39
|
}
|
|
57
40
|
};
|
|
58
41
|
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Console: reading what the page logged, and running code in it.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import type { ActionDef } from './types';
|
|
7
|
+
import { commonFields } from './shared';
|
|
8
|
+
|
|
9
|
+
export const consoleLogs: ActionDef = {
|
|
10
|
+
type: 'console_logs',
|
|
11
|
+
kind: 'control',
|
|
12
|
+
doc: `console_logs {limit?, level?} — the page's console output, oldest first.
|
|
13
|
+
Where to look when an action "worked" but the page did not react: the error is usually here and invisible on screen.`,
|
|
14
|
+
schema: z.object({
|
|
15
|
+
type: z.literal('console_logs'),
|
|
16
|
+
limit: z.number().int().min(1).max(200).optional().describe('How many entries (default: 20).'),
|
|
17
|
+
level: z.enum(['log', 'info', 'warn', 'error', 'debug']).optional().describe('Only this level.'),
|
|
18
|
+
...commonFields
|
|
19
|
+
}),
|
|
20
|
+
run: async (args, ctx) => {
|
|
21
|
+
const all = ctx.service.getConsoleLogs(ctx.tab.id);
|
|
22
|
+
const filtered = args.level ? all.filter((log) => log.type === args.level) : all;
|
|
23
|
+
|
|
24
|
+
if (filtered.length === 0) return { summary: 'no console output' };
|
|
25
|
+
|
|
26
|
+
const limit = args.limit ?? 20;
|
|
27
|
+
const shown = filtered.slice(-limit);
|
|
28
|
+
const lines = shown.map((log) => {
|
|
29
|
+
const time = new Date(log.timestamp).toLocaleTimeString();
|
|
30
|
+
return `[${time}] ${log.type.toUpperCase().padEnd(5)} ${log.text}`;
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
return { summary: `${shown.length} of ${filtered.length} entries`, detail: lines.join('\n') };
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
export const clearConsole: ActionDef = {
|
|
38
|
+
type: 'clear_console',
|
|
39
|
+
kind: 'control',
|
|
40
|
+
doc: `clear_console {} — drop stored console output.
|
|
41
|
+
Put this before the step you are debugging so what follows is only that step's output.`,
|
|
42
|
+
schema: z.object({ type: z.literal('clear_console'), ...commonFields }),
|
|
43
|
+
run: async (_args, ctx) => {
|
|
44
|
+
if (!ctx.service.clearConsoleLogs(ctx.tab.id)) throw new Error('Could not clear console logs');
|
|
45
|
+
return { summary: 'cleared' };
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
export const evaluate: ActionDef = {
|
|
50
|
+
type: 'eval',
|
|
51
|
+
kind: 'control',
|
|
52
|
+
doc: `eval {expression} — run JavaScript in the page and return the result.
|
|
53
|
+
For state that is not in the DOM: computed styles, localStorage, framework internals, window globals. The result must be JSON-serialisable.`,
|
|
54
|
+
schema: z.object({
|
|
55
|
+
type: z.literal('eval'),
|
|
56
|
+
expression: z.string().min(1).describe('JavaScript expression, e.g. document.title or localStorage.getItem("token").'),
|
|
57
|
+
...commonFields
|
|
58
|
+
}),
|
|
59
|
+
run: async (args, ctx) => {
|
|
60
|
+
const result = await ctx.service.executeConsoleCommand(ctx.tab.id, args.expression);
|
|
61
|
+
return { summary: args.expression, detail: JSON.stringify(result, null, 2) };
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
export const consoleActions: ActionDef[] = [consoleLogs, clearConsole, evaluate];
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whole-page DOM extraction.
|
|
3
|
+
*
|
|
4
|
+
* Everything below the `page.evaluate` boundary runs in the page, so it can use
|
|
5
|
+
* no imports and nothing from this module's scope. It is kept in its own file
|
|
6
|
+
* because it is one large browser-side program, not because it is one action.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { Page } from 'puppeteer';
|
|
10
|
+
|
|
11
|
+
export interface PageAnalysis {
|
|
12
|
+
navigation: { links: Array<{ text: string; href: string }> };
|
|
13
|
+
structure: {
|
|
14
|
+
headings: Array<{ level: number; text: string; id: string }>;
|
|
15
|
+
sections: Array<{ heading: string; summary: string }>;
|
|
16
|
+
};
|
|
17
|
+
content: { paragraphs: string[] };
|
|
18
|
+
forms: Array<{
|
|
19
|
+
formId: string;
|
|
20
|
+
action: string;
|
|
21
|
+
fields: Array<{
|
|
22
|
+
label: string;
|
|
23
|
+
type: string;
|
|
24
|
+
name: string;
|
|
25
|
+
placeholder: string;
|
|
26
|
+
required: boolean;
|
|
27
|
+
currentValue: string;
|
|
28
|
+
}>;
|
|
29
|
+
}>;
|
|
30
|
+
summary: {
|
|
31
|
+
url: string;
|
|
32
|
+
title: string;
|
|
33
|
+
hasIframes: boolean;
|
|
34
|
+
hasCaptcha: boolean;
|
|
35
|
+
scrollableHeight: number;
|
|
36
|
+
viewportHeight: number;
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export async function analyzePage(page: Page): Promise<PageAnalysis> {
|
|
41
|
+
return page.evaluate(() => {
|
|
42
|
+
/**
|
|
43
|
+
* Text as a reader would see it: hidden subtrees dropped, block
|
|
44
|
+
* boundaries preserved as ` || ` so a card's fields do not run together
|
|
45
|
+
* into one unreadable sentence.
|
|
46
|
+
*/
|
|
47
|
+
const getVisibleText = (el: Element, maxLength: number = 500): string => {
|
|
48
|
+
const isBlockElement = (elem: Element): boolean => {
|
|
49
|
+
const style = window.getComputedStyle(elem);
|
|
50
|
+
return (
|
|
51
|
+
style.display === 'block' ||
|
|
52
|
+
style.display === 'flex' ||
|
|
53
|
+
style.display === 'grid' ||
|
|
54
|
+
style.display === 'list-item' ||
|
|
55
|
+
style.display === 'table'
|
|
56
|
+
);
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const isVisible = (elem: Element): boolean => {
|
|
60
|
+
const style = window.getComputedStyle(elem);
|
|
61
|
+
if (style.display === 'none' || style.visibility === 'hidden') return false;
|
|
62
|
+
const tagName = elem.tagName.toLowerCase();
|
|
63
|
+
return tagName !== 'script' && tagName !== 'style';
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const extractText = (node: Node): string[] => {
|
|
67
|
+
const parts: string[] = [];
|
|
68
|
+
|
|
69
|
+
if (node.nodeType === Node.TEXT_NODE) {
|
|
70
|
+
const text = node.textContent?.trim();
|
|
71
|
+
if (text && text.length > 0) parts.push(text);
|
|
72
|
+
return parts;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (node.nodeType !== Node.ELEMENT_NODE) return parts;
|
|
76
|
+
|
|
77
|
+
const elem = node as Element;
|
|
78
|
+
if (!isVisible(elem)) return parts;
|
|
79
|
+
|
|
80
|
+
const childParts: string[] = [];
|
|
81
|
+
for (let i = 0; i < node.childNodes.length; i++) {
|
|
82
|
+
const childResults = extractText(node.childNodes[i]);
|
|
83
|
+
if (childResults.length > 0) childParts.push(...childResults);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
if (childParts.length > 0) {
|
|
87
|
+
parts.push(childParts.join(' '));
|
|
88
|
+
if (isBlockElement(elem) && node.nextSibling) parts.push('|BLOCK|');
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return parts;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
let result = extractText(el).join(' ');
|
|
95
|
+
result = result.replace(/\s*\|BLOCK\|\s*/g, ' || ');
|
|
96
|
+
result = result.replace(/\s+/g, ' ').trim();
|
|
97
|
+
result = result.replace(/\|\s+\|/g, '').replace(/^\|\s*|\s*\|$/g, '').trim();
|
|
98
|
+
|
|
99
|
+
return result.substring(0, maxLength);
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const summary = {
|
|
103
|
+
url: window.location.href,
|
|
104
|
+
title: document.title,
|
|
105
|
+
hasIframes: document.querySelectorAll('iframe').length > 0,
|
|
106
|
+
hasCaptcha: !!(
|
|
107
|
+
document.querySelector('iframe[src*="recaptcha"]') ||
|
|
108
|
+
document.querySelector('iframe[title*="recaptcha" i]') ||
|
|
109
|
+
document.querySelector('.g-recaptcha') ||
|
|
110
|
+
document.querySelector('[data-sitekey]') ||
|
|
111
|
+
document.querySelector('iframe[src*="hcaptcha"]') ||
|
|
112
|
+
document.querySelector('.h-captcha') ||
|
|
113
|
+
document.querySelector('.cf-challenge-running') ||
|
|
114
|
+
document.querySelector('#challenge-running') ||
|
|
115
|
+
document.querySelector('div[id*="cf-challenge"]') ||
|
|
116
|
+
document.querySelector('iframe[src*="turnstile"]') ||
|
|
117
|
+
document.querySelector('.cf-turnstile') ||
|
|
118
|
+
document.querySelector('iframe[src*="funcaptcha"]') ||
|
|
119
|
+
document.querySelector('iframe[src*="arkoselabs"]') ||
|
|
120
|
+
document.querySelector('[class*="captcha" i]') ||
|
|
121
|
+
document.querySelector('[id*="captcha" i]') ||
|
|
122
|
+
document.querySelector('img[alt*="captcha" i]') ||
|
|
123
|
+
document.querySelector('img[src*="captcha" i]')
|
|
124
|
+
),
|
|
125
|
+
scrollableHeight: Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
|
|
126
|
+
viewportHeight: window.innerHeight
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
const forms: PageAnalysis['forms'] = [];
|
|
130
|
+
document.querySelectorAll('form').forEach((form, formIdx) => {
|
|
131
|
+
const fields: PageAnalysis['forms'][number]['fields'] = [];
|
|
132
|
+
|
|
133
|
+
form.querySelectorAll('input, textarea, select').forEach((field) => {
|
|
134
|
+
const tagName = field.tagName.toLowerCase();
|
|
135
|
+
const type = tagName === 'input' ? (field as HTMLInputElement).type : tagName;
|
|
136
|
+
|
|
137
|
+
let label = '';
|
|
138
|
+
if (field.id) {
|
|
139
|
+
const labelEl = document.querySelector(`label[for="${field.id}"]`);
|
|
140
|
+
if (labelEl) label = getVisibleText(labelEl);
|
|
141
|
+
}
|
|
142
|
+
if (!label) {
|
|
143
|
+
label = (field as HTMLInputElement).placeholder || (field as HTMLInputElement).name || '(no label)';
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
fields.push({
|
|
147
|
+
label,
|
|
148
|
+
type,
|
|
149
|
+
name: (field as HTMLInputElement).name || '',
|
|
150
|
+
placeholder: (field as HTMLInputElement).placeholder || '',
|
|
151
|
+
required: (field as HTMLInputElement).required || false,
|
|
152
|
+
currentValue: (field as HTMLInputElement).value || ''
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
forms.push({ formId: form.id || `form-${formIdx}`, action: form.action || '', fields });
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
// Every link on the page, not just <nav> — deduplicated by href, since a
|
|
160
|
+
// header/footer pair would otherwise report the same destination twice.
|
|
161
|
+
const navigation = { links: [] as Array<{ text: string; href: string }> };
|
|
162
|
+
const seenHrefs = new Set<string>();
|
|
163
|
+
document.querySelectorAll('a[href]').forEach((link) => {
|
|
164
|
+
const href = (link as HTMLAnchorElement).href;
|
|
165
|
+
const text = getVisibleText(link, 150);
|
|
166
|
+
if (!href || !text || seenHrefs.has(href) || href.startsWith('#')) return;
|
|
167
|
+
seenHrefs.add(href);
|
|
168
|
+
navigation.links.push({ text, href });
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const structure: PageAnalysis['structure'] = { headings: [], sections: [] };
|
|
172
|
+
document.querySelectorAll('h1, h2, h3, h4, h5, h6').forEach((heading) => {
|
|
173
|
+
structure.headings.push({
|
|
174
|
+
level: parseInt(heading.tagName.substring(1)),
|
|
175
|
+
text: getVisibleText(heading),
|
|
176
|
+
id: heading.id || ''
|
|
177
|
+
});
|
|
178
|
+
});
|
|
179
|
+
document.querySelectorAll('section, article, main').forEach((section, idx) => {
|
|
180
|
+
const heading = section.querySelector('h1, h2, h3, h4, h5, h6');
|
|
181
|
+
structure.sections.push({
|
|
182
|
+
heading: heading ? getVisibleText(heading, 200) : `Section ${idx + 1}`,
|
|
183
|
+
summary: getVisibleText(section, 400)
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
const content = { paragraphs: [] as string[] };
|
|
188
|
+
const seenTexts = new Set<string>();
|
|
189
|
+
// Leaf-ish containers only: matching every div would report each block of
|
|
190
|
+
// text again for every ancestor that wraps it.
|
|
191
|
+
const textSelectors = 'p, div:not(:has(p)):not(:has(div)), li, td, span:not(:has(span))';
|
|
192
|
+
document.querySelectorAll(textSelectors).forEach((el) => {
|
|
193
|
+
if (content.paragraphs.length >= 100) return;
|
|
194
|
+
const text = getVisibleText(el, 800);
|
|
195
|
+
if (text.length < 10 || seenTexts.has(text)) return;
|
|
196
|
+
seenTexts.add(text);
|
|
197
|
+
content.paragraphs.push(text);
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
return { navigation, structure, content, forms, summary };
|
|
201
|
+
});
|
|
202
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Action registry — the single source of truth.
|
|
3
|
+
*
|
|
4
|
+
* The tool's schema, its documentation and the runner's dispatch table are all
|
|
5
|
+
* derived from this list, so an action cannot exist in one and be missing from
|
|
6
|
+
* another.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { ActionDef } from './types';
|
|
10
|
+
import { tabActions } from './tabs';
|
|
11
|
+
import { navigationActions } from './navigation';
|
|
12
|
+
import { inputActions } from './input';
|
|
13
|
+
import { inspectActions } from './inspect';
|
|
14
|
+
import { consoleActions } from './console';
|
|
15
|
+
|
|
16
|
+
/** Grouped for the documentation; order is the order an agent meets them. */
|
|
17
|
+
export const ACTION_GROUPS: Array<{ title: string; actions: ActionDef[] }> = [
|
|
18
|
+
{ title: 'Tabs & viewport', actions: tabActions },
|
|
19
|
+
{ title: 'Navigation & waiting', actions: navigationActions },
|
|
20
|
+
{ title: 'Input (mouse, keyboard, touch)', actions: inputActions },
|
|
21
|
+
{ title: 'Inspection', actions: inspectActions },
|
|
22
|
+
{ title: 'Console', actions: consoleActions }
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
export const ALL_ACTIONS: ActionDef[] = ACTION_GROUPS.flatMap((group) => group.actions);
|
|
26
|
+
|
|
27
|
+
export const ACTIONS_BY_TYPE: Map<string, ActionDef> = new Map(
|
|
28
|
+
ALL_ACTIONS.map((action) => [action.type, action])
|
|
29
|
+
);
|
|
30
|
+
|
|
31
|
+
export type { ActionContext, ActionDef, ActionOutput } from './types';
|