@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.
Files changed (86) 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/engine/README.md +11 -8
  5. package/backend/engine/adapters/codex/error-handler.ts +1 -1
  6. package/backend/engine/adapters/qwen/error-handler.ts +1 -1
  7. package/backend/engine/docs/adapter-contract.md +66 -2
  8. package/backend/engine/docs/adding-an-engine.md +46 -7
  9. package/backend/engine/docs/frontend-and-chat.md +80 -17
  10. package/backend/engine/docs/lessons-learned.md +126 -7
  11. package/backend/engine/docs/quick-reference.md +12 -3
  12. package/backend/engine/docs/{system-tools.md → stack.md} +35 -6
  13. package/backend/engine/docs/websocket-routes.md +54 -15
  14. package/backend/engine/install-runner.ts +4 -4
  15. package/backend/engine/resolve-model.ts +87 -0
  16. package/backend/engine/structured-helpers.test.ts +64 -0
  17. package/backend/engine/structured-helpers.ts +105 -13
  18. package/backend/mcp/README.md +32 -11
  19. package/backend/mcp/internal/config.ts +3 -20
  20. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +65 -0
  21. package/backend/mcp/internal/servers/browser-automation/actions/dom-analyze.ts +202 -0
  22. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +31 -0
  23. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +332 -0
  24. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +158 -0
  25. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +157 -0
  26. package/backend/mcp/internal/servers/browser-automation/actions/shared.ts +60 -0
  27. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -0
  28. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +79 -0
  29. package/backend/mcp/internal/servers/browser-automation/context.ts +100 -0
  30. package/backend/mcp/internal/servers/browser-automation/description.ts +60 -0
  31. package/backend/mcp/internal/servers/browser-automation/format.ts +62 -0
  32. package/backend/mcp/internal/servers/browser-automation/index.ts +36 -784
  33. package/backend/mcp/internal/servers/browser-automation/paths.ts +71 -0
  34. package/backend/mcp/internal/servers/browser-automation/runner.ts +269 -0
  35. package/backend/mcp/internal/servers/browser-automation/schema.ts +26 -0
  36. package/backend/preview/browser/browser-console-manager.ts +310 -156
  37. package/backend/preview/browser/browser-dialog-handler.ts +45 -16
  38. package/backend/preview/browser/browser-host-bridge.ts +471 -0
  39. package/backend/preview/browser/browser-interaction-handler.ts +868 -297
  40. package/backend/preview/browser/browser-mcp-control.ts +7 -2
  41. package/backend/preview/browser/browser-native-ui-handler.ts +455 -81
  42. package/backend/preview/browser/browser-navigation-tracker.ts +56 -0
  43. package/backend/preview/browser/browser-pool.ts +83 -9
  44. package/backend/preview/browser/browser-preview-service.ts +432 -53
  45. package/backend/preview/browser/browser-tab-manager.ts +16 -16
  46. package/backend/preview/browser/browser-video-capture.ts +1334 -386
  47. package/backend/preview/browser/capture-profile.ts +213 -0
  48. package/backend/preview/browser/element-locator.ts +357 -0
  49. package/backend/preview/browser/frame-targeting.ts +92 -0
  50. package/backend/preview/browser/scripts/audio-stream.ts +258 -78
  51. package/backend/preview/browser/scripts/host-bridge.ts +1277 -0
  52. package/backend/preview/browser/scripts/video-stream.ts +803 -177
  53. package/backend/preview/browser/types.ts +397 -37
  54. package/backend/utils/cli.ts +1 -1
  55. package/backend/utils/path-enrich.ts +2 -2
  56. package/backend/ws/README.md +1 -1
  57. package/backend/ws/artifacts/generate.ts +2 -1
  58. package/backend/ws/engine/codex/accounts.ts +1 -1
  59. package/backend/ws/engine/codex/status.ts +1 -1
  60. package/backend/ws/git/branch-name.ts +11 -5
  61. package/backend/ws/git/commit-message.ts +11 -5
  62. package/backend/ws/index.ts +3 -3
  63. package/backend/ws/preview/browser/host.ts +95 -0
  64. package/backend/ws/preview/browser/interact.ts +204 -10
  65. package/backend/ws/preview/browser/native-ui.ts +31 -1
  66. package/backend/ws/preview/browser/tab-info.ts +10 -1
  67. package/backend/ws/preview/browser/tab.ts +43 -0
  68. package/backend/ws/preview/browser/webcodecs.ts +180 -53
  69. package/backend/ws/preview/index.ts +58 -1
  70. package/backend/ws/{system-tools → stack}/access.ts +1 -1
  71. package/backend/ws/stack/index.ts +16 -0
  72. package/backend/ws/{system-tools → stack}/install.ts +7 -7
  73. package/backend/ws/{system-tools → stack}/status.ts +7 -7
  74. package/dist/assets/{index-CEGW8vEt.js → index-DH_GO0Lf.js} +1 -1
  75. package/dist/assets/{index-B8YRz8wG.js → index-igSQ3JaM.js} +1 -1
  76. package/dist/assets/main-BD3-qPfT.css +1 -0
  77. package/dist/assets/{main-D-2ByODy.js → main-D-d8SFfW.js} +384 -358
  78. package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
  79. package/dist/index.html +2 -2
  80. package/package.json +1 -1
  81. package/shared/types/stores/settings.ts +6 -0
  82. package/backend/mcp/internal/servers/browser-automation/actions.ts +0 -159
  83. package/backend/mcp/internal/servers/browser-automation/browser.ts +0 -375
  84. package/backend/mcp/internal/servers/browser-automation/inspection.ts +0 -495
  85. package/backend/ws/system-tools/index.ts +0 -16
  86. package/dist/assets/main-D8I0MfRQ.css +0 -1
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Project-scoped path resolution for actions that touch the filesystem
3
+ * (screenshot → file, file upload).
4
+ *
5
+ * Agent-supplied paths are resolved against the project directory and must
6
+ * stay inside it. Symlinks are followed on both sides before comparing, so a
7
+ * link inside the project cannot be used to reach out of it.
8
+ */
9
+
10
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
11
+ import { mkdir, realpath, stat } from 'node:fs/promises';
12
+ import { projectQueries } from '$backend/database/queries/project-queries';
13
+
14
+ async function resolveRealPath(p: string): Promise<string> {
15
+ const abs = resolve(p);
16
+ try {
17
+ return await realpath(abs);
18
+ } catch {
19
+ // Not created yet — resolve the deepest existing ancestor and rejoin the
20
+ // tail, so a symlinked parent is still followed.
21
+ const parent = dirname(abs);
22
+ if (parent === abs) return abs;
23
+ return join(await resolveRealPath(parent), basename(abs));
24
+ }
25
+ }
26
+
27
+ async function isPathInside(rootPath: string, candidatePath: string): Promise<boolean> {
28
+ const root = await resolveRealPath(rootPath);
29
+ const candidate = await resolveRealPath(candidatePath);
30
+ const rel = relative(root, candidate);
31
+ return rel === '' || (!!rel && !rel.startsWith('..') && !isAbsolute(rel));
32
+ }
33
+
34
+ function projectRoot(projectId: string): string {
35
+ const project = projectQueries.getById(projectId);
36
+ if (!project?.path) throw new Error(`Project ${projectId} has no directory on disk`);
37
+ return project.path;
38
+ }
39
+
40
+ /** Resolve one agent-supplied path inside the project. */
41
+ export async function resolveProjectPath(inputPath: string, projectId: string): Promise<string> {
42
+ const root = projectRoot(projectId);
43
+ const absolute = isAbsolute(inputPath) ? inputPath : resolve(root, inputPath);
44
+
45
+ if (!(await isPathInside(root, absolute))) {
46
+ throw new Error(`Path "${inputPath}" resolves outside the project directory`);
47
+ }
48
+
49
+ return absolute;
50
+ }
51
+
52
+ /** Resolve paths that must already exist (uploads). */
53
+ export async function resolveProjectFiles(inputPaths: string[], projectId: string): Promise<string[]> {
54
+ const resolved: string[] = [];
55
+
56
+ for (const inputPath of inputPaths) {
57
+ const absolute = await resolveProjectPath(inputPath, projectId);
58
+ const info = await stat(absolute).catch(() => null);
59
+ if (!info?.isFile()) throw new Error(`File not found: ${inputPath}`);
60
+ resolved.push(absolute);
61
+ }
62
+
63
+ return resolved;
64
+ }
65
+
66
+ /** Resolve a write destination, creating its parent directory. */
67
+ export async function resolveWritePath(inputPath: string, projectId: string): Promise<string> {
68
+ const absolute = await resolveProjectPath(inputPath, projectId);
69
+ await mkdir(dirname(absolute), { recursive: true });
70
+ return absolute;
71
+ }
@@ -0,0 +1,269 @@
1
+ /**
2
+ * Batch runner.
3
+ *
4
+ * Walks the requested actions in order and turns them into one honest report.
5
+ *
6
+ * Three things it owns, each of which was a bug when it lived somewhere else:
7
+ *
8
+ * - **Coalescing.** Consecutive input gestures go to the native engine in a
9
+ * single call, so pointer movement stays continuous and the engine's own
10
+ * pacing applies. Split per action, a five-click sequence looks like five
11
+ * unrelated jumps.
12
+ * - **Re-targeting.** Opening, switching or closing a tab changes what "the
13
+ * current tab" means; the target is resolved again before the next action
14
+ * rather than captured once at the start.
15
+ * - **Truthful reporting.** Interrupted and failed runs say how far they got.
16
+ * Claiming success for actions that never ran is worse than failing, because
17
+ * the agent then plans on top of a state that does not exist.
18
+ */
19
+
20
+ import type { BrowserAutonomousAction, BrowserTab } from '$backend/preview/browser/types';
21
+ import { projectContextService } from '$backend/mcp/internal/project-context';
22
+ import { debug } from '$shared/utils/logger';
23
+ import { ACTIONS_BY_TYPE } from './actions';
24
+ import type { ActionContext, ActionImage, TablessActionContext } from './actions/types';
25
+ import { getActiveTabSession, getPreviewService, peekSessionTab } from './context';
26
+
27
+ interface ActionArgs {
28
+ type: string;
29
+ optional?: boolean;
30
+ [key: string]: unknown;
31
+ }
32
+
33
+ export interface RunArgs {
34
+ actions: ActionArgs[];
35
+ onError?: 'stop' | 'continue';
36
+ projectId?: string;
37
+ }
38
+
39
+ interface StepReport {
40
+ index: number;
41
+ type: string;
42
+ ok: boolean;
43
+ summary?: string;
44
+ detail?: string;
45
+ error?: string;
46
+ }
47
+
48
+ export interface RunReport {
49
+ steps: StepReport[];
50
+ images: ActionImage[];
51
+ /** Actions that never ran, because a failure or an interrupt stopped the batch. */
52
+ skipped: number;
53
+ aborted: boolean;
54
+ failed: boolean;
55
+ tabId?: string;
56
+ url?: string;
57
+ /** Set when the batch had to open a tab because the browser had none. */
58
+ openedTabId?: string;
59
+ }
60
+
61
+ /** Consecutive input gestures form one native run; control actions stand alone. */
62
+ function groupActions(actions: ActionArgs[]): Array<{ kind: 'input' | 'control'; items: Array<{ index: number; args: ActionArgs }> }> {
63
+ const groups: Array<{ kind: 'input' | 'control'; items: Array<{ index: number; args: ActionArgs }> }> = [];
64
+
65
+ actions.forEach((args, index) => {
66
+ const def = ACTIONS_BY_TYPE.get(args.type);
67
+ const kind = def?.kind ?? 'control';
68
+ const last = groups[groups.length - 1];
69
+
70
+ if (kind === 'input' && last?.kind === 'input') {
71
+ last.items.push({ index, args });
72
+ } else {
73
+ groups.push({ kind, items: [{ index, args }] });
74
+ }
75
+ });
76
+
77
+ return groups;
78
+ }
79
+
80
+ export async function runActions(args: RunArgs): Promise<RunReport> {
81
+ const signal = projectContextService.getCurrentSignal();
82
+ const service = getPreviewService(args.projectId);
83
+ const projectId = service.getProjectId();
84
+ const chatSessionId = projectContextService.getCurrentChatSessionId() ?? '';
85
+
86
+ const report: RunReport = { steps: [], images: [], skipped: 0, aborted: false, failed: false };
87
+
88
+ let tabStale = true;
89
+ let tab: BrowserTab | null = null;
90
+
91
+ /** The tab to act on — opened on the spot if the browser has none. */
92
+ const resolveTab = async () => {
93
+ if (!tabStale && tab) return tab;
94
+ const resolved = await getActiveTabSession(args.projectId);
95
+ if (resolved.opened) report.openedTabId = resolved.tab.id;
96
+ tab = resolved.tab;
97
+ tabStale = false;
98
+ return tab;
99
+ };
100
+
101
+ /** Where the batch stands, without opening anything or taking control. */
102
+ const peekTab = () => (!tabStale && tab ? tab : peekSessionTab(service, chatSessionId));
103
+
104
+ // `needsTab: false` actions declare their context as TablessActionContext,
105
+ // so the null this can carry never reaches one that dereferences it.
106
+ const makeContext = (target: BrowserTab | null): ActionContext =>
107
+ ({
108
+ service,
109
+ tab: target,
110
+ projectId,
111
+ chatSessionId,
112
+ signal,
113
+ invalidateTab: () => (tabStale = true)
114
+ } satisfies TablessActionContext as ActionContext);
115
+
116
+ const groups = groupActions(args.actions);
117
+ let stopped = false;
118
+ let consumed = 0;
119
+
120
+ /** A failure only stops the batch if it was not asked to be tolerated. */
121
+ const tolerates = (step: StepReport) =>
122
+ args.actions[step.index]?.optional === true || args.onError === 'continue';
123
+
124
+ for (const group of groups) {
125
+ if (stopped || signal?.aborted) break;
126
+
127
+ const deps: RunDeps = { args, service, signal, resolveTab, peekTab, makeContext };
128
+ const before = report.steps.length;
129
+
130
+ consumed += group.kind === 'input'
131
+ ? await runInputGroup(group.items, deps, report)
132
+ : await runControl(group.items[0], deps, report);
133
+
134
+ if (signal?.aborted) {
135
+ report.aborted = true;
136
+ break;
137
+ }
138
+
139
+ // Check every step this group produced, not just the last: one native
140
+ // run can fail in the middle and still finish with a successful action.
141
+ stopped = report.steps.slice(before).some((step) => !step.ok && !tolerates(step));
142
+ }
143
+
144
+ report.failed = report.steps.some((step) => !step.ok && !tolerates(step));
145
+ report.skipped = Math.max(0, args.actions.length - consumed);
146
+ if (signal?.aborted) report.aborted = true;
147
+
148
+ // Report where the batch left the browser: the next call's plan depends on
149
+ // it, and it is the cheapest way to notice a navigation nobody asked for.
150
+ // Peeked, not resolved: a batch that closed its last tab should say so, not
151
+ // get a fresh one opened just to have something to report.
152
+ try {
153
+ const current = peekTab();
154
+ if (current) {
155
+ report.tabId = current.id;
156
+ report.url = current.page.url();
157
+ }
158
+ } catch {
159
+ // No tab left (closed by the batch, or none was ever open).
160
+ }
161
+
162
+ return report;
163
+ }
164
+
165
+ interface RunDeps {
166
+ args: RunArgs;
167
+ service: ReturnType<typeof getPreviewService>;
168
+ signal?: AbortSignal;
169
+ resolveTab: () => Promise<BrowserTab>;
170
+ peekTab: () => BrowserTab | null;
171
+ makeContext: (target: BrowserTab | null) => ActionContext;
172
+ }
173
+
174
+ /** Run one control action. Returns how many actions were consumed. */
175
+ async function runControl(item: { index: number; args: ActionArgs }, deps: RunDeps, report: RunReport): Promise<number> {
176
+ const def = ACTIONS_BY_TYPE.get(item.args.type);
177
+ if (!def?.run) {
178
+ report.steps.push({ index: item.index, type: item.args.type, ok: false, error: `Unknown action "${item.args.type}"` });
179
+ return 1;
180
+ }
181
+
182
+ try {
183
+ // The tab actions run on an empty browser — they are how it stops being
184
+ // empty. Everything else gets a tab opened for it first.
185
+ const tab = def.needsTab === false ? deps.peekTab() : await deps.resolveTab();
186
+
187
+ const output = await def.run(item.args, deps.makeContext(tab));
188
+ report.steps.push({ index: item.index, type: def.type, ok: true, summary: output.summary, detail: output.detail });
189
+ if (output.images?.length) report.images.push(...output.images);
190
+ } catch (error) {
191
+ const message = error instanceof Error ? error.message : 'Unknown error';
192
+ debug.warn('mcp', `browser action ${item.args.type} failed: ${message}`);
193
+ report.steps.push({ index: item.index, type: item.args.type, ok: false, error: message });
194
+ }
195
+
196
+ return 1;
197
+ }
198
+
199
+ /**
200
+ * Run a run of input gestures as one native batch.
201
+ *
202
+ * The engine reports per action, so a partial run maps back onto the original
203
+ * indices — including which of them never happened.
204
+ */
205
+ async function runInputGroup(items: Array<{ index: number; args: ActionArgs }>, deps: RunDeps, report: RunReport): Promise<number> {
206
+ let tab;
207
+ try {
208
+ tab = await deps.resolveTab();
209
+ } catch (error) {
210
+ const message = error instanceof Error ? error.message : 'Unknown error';
211
+ report.steps.push({ index: items[0].index, type: items[0].args.type, ok: false, error: message });
212
+ return 1;
213
+ }
214
+
215
+ const ctx = deps.makeContext(tab);
216
+
217
+ // Translation can fail on its own (a path outside the project, a missing
218
+ // field). Those actions never reach the engine, so they are reported here
219
+ // and the rest of the group still runs.
220
+ const primitives: BrowserAutonomousAction[] = [];
221
+ const mapped: Array<{ index: number; type: string }> = [];
222
+
223
+ for (const item of items) {
224
+ const def = ACTIONS_BY_TYPE.get(item.args.type);
225
+ if (!def?.toInput) {
226
+ report.steps.push({ index: item.index, type: item.args.type, ok: false, error: `Unknown action "${item.args.type}"` });
227
+ continue;
228
+ }
229
+
230
+ try {
231
+ primitives.push(await def.toInput(item.args, ctx));
232
+ mapped.push({ index: item.index, type: def.type });
233
+ } catch (error) {
234
+ report.steps.push({
235
+ index: item.index,
236
+ type: item.args.type,
237
+ ok: false,
238
+ error: error instanceof Error ? error.message : 'Unknown error'
239
+ });
240
+ }
241
+ }
242
+
243
+ if (primitives.length === 0) return items.length;
244
+
245
+ const outcome = await deps.service.performAutonomousActions(tab.id, primitives, deps.signal);
246
+
247
+ // One engine result per primitive, in order.
248
+ mapped.forEach((entry, position) => {
249
+ const result = outcome.results[position];
250
+ if (!result) {
251
+ // The engine stopped before reaching this one.
252
+ report.steps.push({ index: entry.index, type: entry.type, ok: false, error: 'did not run (batch stopped earlier)' });
253
+ return;
254
+ }
255
+
256
+ report.steps.push({
257
+ index: entry.index,
258
+ type: entry.type,
259
+ ok: result.ok,
260
+ summary: result.detail,
261
+ detail: result.data !== undefined ? JSON.stringify(result.data, null, 2) : undefined,
262
+ error: result.error
263
+ });
264
+ });
265
+
266
+ if (outcome.aborted) report.aborted = true;
267
+
268
+ return items.length;
269
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Tool schema, assembled from the action registry.
3
+ */
4
+
5
+ import { z } from 'zod';
6
+ import { ALL_ACTIONS } from './actions';
7
+
8
+ const members = ALL_ACTIONS.map((action) => action.schema) as unknown as [
9
+ z.ZodObject<any>,
10
+ z.ZodObject<any>,
11
+ ...z.ZodObject<any>[]
12
+ ];
13
+
14
+ /** One action. Discriminated on `type`, so a wrong field is rejected up front. */
15
+ export const actionSchema = z.discriminatedUnion('type', members);
16
+
17
+ export const actionsToolSchema = {
18
+ actions: z
19
+ .array(actionSchema)
20
+ .min(1)
21
+ .describe('Actions to run in order. Batch everything that does not depend on what you would learn from the result.'),
22
+ onError: z
23
+ .enum(['stop', 'continue'])
24
+ .optional()
25
+ .describe('stop (default): remaining actions are skipped after a failure. continue: run them all. Per-action `optional: true` overrides this for that action.')
26
+ };