@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.
- package/README.md +2 -1
- package/backend/artifacts/generate.ts +11 -5
- package/backend/auth/permissions.ts +8 -8
- package/backend/bootstrap.ts +39 -0
- package/backend/chat/stream-manager.ts +15 -0
- package/backend/database/migrations/065_add_session_reasoning_effort.ts +28 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/session-queries.ts +10 -0
- package/backend/engine/README.md +11 -8
- package/backend/engine/adapters/claude/models.ts +46 -23
- package/backend/engine/adapters/claude/stream.ts +18 -4
- package/backend/engine/adapters/codex/error-handler.ts +1 -1
- package/backend/engine/adapters/codex/models.ts +19 -2
- package/backend/engine/adapters/codex/stream.ts +10 -3
- package/backend/engine/adapters/copilot/models.ts +20 -1
- package/backend/engine/adapters/copilot/stream.ts +11 -1
- package/backend/engine/adapters/cursor/models.ts +27 -3
- package/backend/engine/adapters/cursor/stream.ts +23 -3
- package/backend/engine/adapters/pi/models.ts +20 -2
- package/backend/engine/adapters/pi/stream.ts +6 -3
- package/backend/engine/adapters/qwen/error-handler.ts +1 -1
- package/backend/engine/bootstrap-default-engine.ts +18 -5
- 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/engine/types.ts +6 -0
- package/backend/index.ts +6 -9
- 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 +146 -0
- package/backend/mcp/internal/servers/browser-automation/actions/types.ts +63 -0
- package/backend/mcp/internal/servers/browser-automation/context.ts +82 -0
- package/backend/mcp/internal/servers/browser-automation/description.ts +59 -0
- package/backend/mcp/internal/servers/browser-automation/format.ts +56 -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 +260 -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/chat/stream.ts +38 -2
- 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/backend/ws/system/device-info.ts +290 -0
- package/backend/ws/system/index.ts +2 -0
- package/backend/ws/system/operations.ts +7 -0
- package/backend/ws/user/crud.ts +6 -3
- package/dist/assets/{index-BqBxKeAv.js โ index-DH_GO0Lf.js} +1 -1
- package/dist/assets/{index-DdrcY5TE.js โ index-igSQ3JaM.js} +1 -1
- package/dist/assets/main-BD3-qPfT.css +1 -0
- package/dist/assets/main-D-d8SFfW.js +616 -0
- package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
- package/dist/index.html +2 -2
- package/package.json +2 -1
- package/shared/constants/engines.ts +23 -0
- package/shared/types/database/schema.ts +1 -0
- package/shared/types/stores/settings.ts +12 -0
- package/shared/types/unified/engine.ts +33 -0
- package/shared/types/unified/index.ts +2 -0
- package/shared/types/unified/message.ts +6 -0
- package/shared/types/unified/stream.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-BBxAj17T.js +0 -582
- package/dist/assets/main-Cry3pLcl.css +0 -1
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pieces every action group reuses: the targeting fields and the shared
|
|
3
|
+
* per-action options.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { z } from 'zod';
|
|
7
|
+
import type { BrowserActionTarget } from '$backend/preview/browser/types';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* How an action says *where* to act.
|
|
11
|
+
*
|
|
12
|
+
* Flat rather than nested because a model fills flat fields far more reliably,
|
|
13
|
+
* and because the three ways to aim are mutually exclusive in practice:
|
|
14
|
+
* coordinates from a screenshot, a CSS selector, or visible text.
|
|
15
|
+
*/
|
|
16
|
+
// Kept terse on purpose: these five fields repeat across most actions, so every
|
|
17
|
+
// word here is paid for ~15 times in the JSON schema the engine receives. The
|
|
18
|
+
// tool description explains targeting once, in prose.
|
|
19
|
+
export const targetFields = {
|
|
20
|
+
x: z.number().optional().describe('X in page viewport.'),
|
|
21
|
+
y: z.number().optional().describe('Y in page viewport.'),
|
|
22
|
+
selector: z.string().optional().describe('CSS selector; all frames.'),
|
|
23
|
+
text: z.string().optional().describe('Visible text to match.'),
|
|
24
|
+
nth: z.number().int().min(0).optional().describe('Which match (0-based).')
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Targeting for actions that already use `text` for content (type, paste).
|
|
29
|
+
* Two different meanings on one key would be ambiguous for the model and
|
|
30
|
+
* impossible to resolve at runtime.
|
|
31
|
+
*/
|
|
32
|
+
export const targetFieldsNoText = {
|
|
33
|
+
x: targetFields.x,
|
|
34
|
+
y: targetFields.y,
|
|
35
|
+
selector: targetFields.selector,
|
|
36
|
+
nth: targetFields.nth
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** Nested target, for actions with two endpoints (drag, swipe). */
|
|
40
|
+
export const pointSchema = z.object(targetFields).describe('A point: coordinates, a selector, or visible text.');
|
|
41
|
+
|
|
42
|
+
/** Options accepted by every action. Terse for the same reason as above. */
|
|
43
|
+
export const commonFields = {
|
|
44
|
+
optional: z.boolean().optional().describe('Failure does not stop the batch.')
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export function toTarget(args: {
|
|
48
|
+
x?: number;
|
|
49
|
+
y?: number;
|
|
50
|
+
selector?: string;
|
|
51
|
+
text?: string;
|
|
52
|
+
nth?: number;
|
|
53
|
+
}): BrowserActionTarget {
|
|
54
|
+
return { x: args.x, y: args.y, selector: args.selector, text: args.text, nth: args.nth };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** True when an action named a place to act at all. */
|
|
58
|
+
export function hasTarget(args: { x?: number; y?: number; selector?: string; text?: string }): boolean {
|
|
59
|
+
return (typeof args.x === 'number' && typeof args.y === 'number') || !!args.selector || !!args.text;
|
|
60
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tab and viewport actions.
|
|
3
|
+
*
|
|
4
|
+
* All of these can change which tab subsequent actions target, so each one
|
|
5
|
+
* calls `ctx.invalidateTab()` โ without it a batch like
|
|
6
|
+
* `[open_tab, navigate, screenshot]` would open a tab and then keep driving the
|
|
7
|
+
* old one.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { z } from 'zod';
|
|
11
|
+
import { browserMcpControl } from '$backend/preview';
|
|
12
|
+
import { debug } from '$shared/utils/logger';
|
|
13
|
+
import type { ActionDef } from './types';
|
|
14
|
+
import { commonFields } from './shared';
|
|
15
|
+
|
|
16
|
+
const DEVICE_SIZES = ['desktop', 'laptop', 'tablet', 'mobile'] as const;
|
|
17
|
+
const ROTATIONS = ['portrait', 'landscape'] as const;
|
|
18
|
+
|
|
19
|
+
/** Devices that read as held rather than sat in front of. */
|
|
20
|
+
function defaultRotation(deviceSize: string): 'portrait' | 'landscape' {
|
|
21
|
+
return deviceSize === 'desktop' || deviceSize === 'laptop' ? 'landscape' : 'portrait';
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const listTabs: ActionDef = {
|
|
25
|
+
type: 'list_tabs',
|
|
26
|
+
kind: 'control',
|
|
27
|
+
doc: `list_tabs {} โ every open tab with its id, URL, viewport and who controls it.
|
|
28
|
+
Use the id, not the position, with switch_tab/close_tab.`,
|
|
29
|
+
schema: z.object({ type: z.literal('list_tabs'), ...commonFields }),
|
|
30
|
+
run: async (_args, ctx) => {
|
|
31
|
+
const tabs = ctx.service.getAllTabs();
|
|
32
|
+
if (tabs.length === 0) return { summary: 'no tabs open' };
|
|
33
|
+
|
|
34
|
+
const lines = tabs.map((tab, index) => {
|
|
35
|
+
const owner = browserMcpControl.getTabOwner(tab.id);
|
|
36
|
+
const control = owner ? (owner === ctx.chatSessionId ? ' [yours]' : ' [another session]') : '';
|
|
37
|
+
return [
|
|
38
|
+
`${index + 1}. ${tab.isActive ? '*' : ' '} ${tab.id}${control} โ ${tab.title || 'Untitled'}`,
|
|
39
|
+
` ${tab.url || '(empty)'}`,
|
|
40
|
+
` ${tab.deviceSize}/${tab.rotation}${tab.isLoading ? ' ยท loading' : ''}`
|
|
41
|
+
].join('\n');
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
return { summary: `${tabs.length} tab(s)`, detail: lines.join('\n') };
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export const openTab: ActionDef = {
|
|
49
|
+
type: 'open_tab',
|
|
50
|
+
kind: 'control',
|
|
51
|
+
doc: `open_tab {url?, deviceSize?, rotation?} โ open a tab and make it the target.
|
|
52
|
+
deviceSize: desktop 1920ร1080 ยท laptop 1440ร900 (default) ยท tablet 834ร1194 ยท mobile 402ร874.
|
|
53
|
+
rotation defaults to landscape for desktop/laptop, portrait for tablet/mobile.`,
|
|
54
|
+
schema: z.object({
|
|
55
|
+
type: z.literal('open_tab'),
|
|
56
|
+
url: z.string().url().optional().describe('URL to load, including protocol. Omit for a blank tab.'),
|
|
57
|
+
deviceSize: z.enum(DEVICE_SIZES).optional().describe('Viewport preset (default: laptop).'),
|
|
58
|
+
rotation: z.enum(ROTATIONS).optional().describe('Orientation. Omit for the device default.'),
|
|
59
|
+
...commonFields
|
|
60
|
+
}),
|
|
61
|
+
run: async (args, ctx) => {
|
|
62
|
+
const deviceSize = args.deviceSize || 'laptop';
|
|
63
|
+
const rotation = args.rotation || defaultRotation(deviceSize);
|
|
64
|
+
|
|
65
|
+
const tab = await ctx.service.createTab(args.url || undefined, deviceSize, rotation);
|
|
66
|
+
browserMcpControl.acquireControl(tab.id, ctx.chatSessionId, ctx.projectId);
|
|
67
|
+
ctx.invalidateTab();
|
|
68
|
+
|
|
69
|
+
debug.log('mcp', `๐ Opened tab ${tab.id} (${deviceSize}/${rotation})`);
|
|
70
|
+
return { summary: `${tab.id} ยท ${tab.url || '(blank)'} ยท ${deviceSize}/${rotation}` };
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
export const switchTab: ActionDef = {
|
|
75
|
+
type: 'switch_tab',
|
|
76
|
+
kind: 'control',
|
|
77
|
+
doc: `switch_tab {tabId} โ make another tab the target of following actions.`,
|
|
78
|
+
schema: z.object({
|
|
79
|
+
type: z.literal('switch_tab'),
|
|
80
|
+
tabId: z.string().min(1).describe('Tab id from list_tabs.'),
|
|
81
|
+
...commonFields
|
|
82
|
+
}),
|
|
83
|
+
run: async (args, ctx) => {
|
|
84
|
+
if (!ctx.service.switchTab(args.tabId)) throw new Error(`Tab '${args.tabId}' not found`);
|
|
85
|
+
|
|
86
|
+
const tab = ctx.service.getTab(args.tabId);
|
|
87
|
+
if (tab) {
|
|
88
|
+
const acquired = browserMcpControl.acquireControl(tab.id, ctx.chatSessionId, ctx.projectId);
|
|
89
|
+
if (!acquired) {
|
|
90
|
+
const owner = browserMcpControl.getTabOwner(tab.id);
|
|
91
|
+
throw new Error(`Tab '${args.tabId}' is controlled by another chat session (${owner?.slice(0, 8)}...)`);
|
|
92
|
+
}
|
|
93
|
+
// Promote so the tab resolver targets this one next.
|
|
94
|
+
browserMcpControl.promoteSessionTab(tab.id, ctx.chatSessionId);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
ctx.invalidateTab();
|
|
98
|
+
return { summary: `${args.tabId} ยท ${tab?.url || '(empty)'}` };
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
export const closeTab: ActionDef = {
|
|
103
|
+
type: 'close_tab',
|
|
104
|
+
kind: 'control',
|
|
105
|
+
doc: `close_tab {tabId?} โ close a tab (default: the current one).`,
|
|
106
|
+
schema: z.object({
|
|
107
|
+
type: z.literal('close_tab'),
|
|
108
|
+
tabId: z.string().optional().describe('Tab id from list_tabs. Omit to close the current tab.'),
|
|
109
|
+
...commonFields
|
|
110
|
+
}),
|
|
111
|
+
run: async (args, ctx) => {
|
|
112
|
+
const tabId = args.tabId || ctx.tab.id;
|
|
113
|
+
const result = await ctx.service.closeTab(tabId);
|
|
114
|
+
if (!result.success) throw new Error(`Tab '${tabId}' not found`);
|
|
115
|
+
|
|
116
|
+
ctx.invalidateTab();
|
|
117
|
+
|
|
118
|
+
if (!result.newActiveTabId) return { summary: `${tabId} closed ยท no tabs left` };
|
|
119
|
+
const next = ctx.service.getTab(result.newActiveTabId);
|
|
120
|
+
return { summary: `${tabId} closed ยท now on ${result.newActiveTabId} (${next?.url || 'empty'})` };
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
export const setViewport: ActionDef = {
|
|
125
|
+
type: 'set_viewport',
|
|
126
|
+
kind: 'control',
|
|
127
|
+
doc: `set_viewport {deviceSize?, rotation?} โ resize the current tab.
|
|
128
|
+
Changing this re-runs the page's media queries, so it is how responsive layouts get tested.`,
|
|
129
|
+
schema: z.object({
|
|
130
|
+
type: z.literal('set_viewport'),
|
|
131
|
+
deviceSize: z.enum(DEVICE_SIZES).optional().describe('Omit to keep the current size.'),
|
|
132
|
+
rotation: z.enum(ROTATIONS).optional().describe('Omit to keep the current orientation.'),
|
|
133
|
+
...commonFields
|
|
134
|
+
}),
|
|
135
|
+
run: async (args, ctx) => {
|
|
136
|
+
const deviceSize = args.deviceSize || ctx.tab.deviceSize;
|
|
137
|
+
const rotation = args.rotation || ctx.tab.rotation;
|
|
138
|
+
|
|
139
|
+
const ok = await ctx.service.setViewport(ctx.tab.id, deviceSize, rotation);
|
|
140
|
+
if (!ok) throw new Error(`Could not resize tab '${ctx.tab.id}'`);
|
|
141
|
+
|
|
142
|
+
return { summary: `${deviceSize}/${rotation}` };
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
|
|
146
|
+
export const tabActions: ActionDef[] = [listTabs, openTab, switchTab, closeTab, setViewport];
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Action contract.
|
|
3
|
+
*
|
|
4
|
+
* One module per group of actions, each exporting `ActionDef`s. The registry
|
|
5
|
+
* assembles them into the tool's schema, its documentation, and the runner's
|
|
6
|
+
* dispatch table โ so adding an action is one file and one registry line, and
|
|
7
|
+
* the three can never drift apart.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { z } from 'zod';
|
|
11
|
+
import type { BrowserPreviewService } from '$backend/preview';
|
|
12
|
+
import type { BrowserAutonomousAction, BrowserTab } from '$backend/preview/browser/types';
|
|
13
|
+
|
|
14
|
+
export interface ActionContext {
|
|
15
|
+
service: BrowserPreviewService;
|
|
16
|
+
/** The tab this action targets. Re-resolved by the runner after tab changes. */
|
|
17
|
+
tab: BrowserTab;
|
|
18
|
+
projectId: string;
|
|
19
|
+
chatSessionId: string;
|
|
20
|
+
signal?: AbortSignal;
|
|
21
|
+
/**
|
|
22
|
+
* Tell the runner the target tab may have changed (opened, switched,
|
|
23
|
+
* closed), so the next action resolves it again instead of driving a tab
|
|
24
|
+
* that is no longer in front.
|
|
25
|
+
*/
|
|
26
|
+
invalidateTab(): void;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface ActionImage {
|
|
30
|
+
data: string;
|
|
31
|
+
mimeType: string;
|
|
32
|
+
label?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export interface ActionOutput {
|
|
36
|
+
/** One line for the batch report, e.g. `โ https://example.com/pricing`. */
|
|
37
|
+
summary: string;
|
|
38
|
+
/** Payload printed under the summary (JSON dumps, log listings). */
|
|
39
|
+
detail?: string;
|
|
40
|
+
/** Images returned as their own content blocks, after the report. */
|
|
41
|
+
images?: ActionImage[];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* `input` actions are gestures: the runner coalesces consecutive ones into a
|
|
46
|
+
* single native run so pointer movement and inter-action timing stay smooth.
|
|
47
|
+
* `control` actions run on their own โ they are tab, navigation or inspection
|
|
48
|
+
* operations, not input.
|
|
49
|
+
*/
|
|
50
|
+
export type ActionKind = 'input' | 'control';
|
|
51
|
+
|
|
52
|
+
export interface ActionDef {
|
|
53
|
+
type: string;
|
|
54
|
+
kind: ActionKind;
|
|
55
|
+
/** Reference entry for this action, rendered into the tool description. */
|
|
56
|
+
doc: string;
|
|
57
|
+
/** Zod object whose `type` field is the discriminator. */
|
|
58
|
+
schema: z.ZodObject<any>;
|
|
59
|
+
/** `input` actions: translate to the native gesture primitive. */
|
|
60
|
+
toInput?: (args: any, ctx: ActionContext) => BrowserAutonomousAction | Promise<BrowserAutonomousAction>;
|
|
61
|
+
/** `control` actions: run directly. */
|
|
62
|
+
run?: (args: any, ctx: ActionContext) => Promise<ActionOutput>;
|
|
63
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Execution context for browser actions.
|
|
3
|
+
*
|
|
4
|
+
* Every action needs the same three things โ which project's browser, which
|
|
5
|
+
* chat session is driving it, and which tab is the target โ and getting any of
|
|
6
|
+
* them wrong is silent: a tool call lands on another project's browser, or on a
|
|
7
|
+
* tab someone else's session owns. Resolving them in one place is what keeps
|
|
8
|
+
* that from being re-derived (and re-broken) per action.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { browserMcpControl, browserPreviewServiceManager, type BrowserPreviewService } from '$backend/preview';
|
|
12
|
+
import type { BrowserTab } from '$backend/preview/browser/types';
|
|
13
|
+
import { projectContextService } from '$backend/mcp/internal/project-context';
|
|
14
|
+
import { debug } from '$shared/utils/logger';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Resolve the BrowserPreviewService for the current MCP call.
|
|
18
|
+
*
|
|
19
|
+
* Order matters: an explicit id beats the ambient stream context, which beats
|
|
20
|
+
* "whatever project happens to be open". The last one is a fallback for
|
|
21
|
+
* transports that lose the context across an HTTP boundary, and it warns
|
|
22
|
+
* because acting on a guessed project is worth noticing in the logs.
|
|
23
|
+
*/
|
|
24
|
+
export function getPreviewService(projectId?: string): BrowserPreviewService {
|
|
25
|
+
if (projectId) return browserPreviewServiceManager.getService(projectId);
|
|
26
|
+
|
|
27
|
+
const contextProjectId = projectContextService.getCurrentProjectId();
|
|
28
|
+
if (contextProjectId) return browserPreviewServiceManager.getService(contextProjectId);
|
|
29
|
+
|
|
30
|
+
const activeProjects = browserPreviewServiceManager.getActiveProjects();
|
|
31
|
+
if (activeProjects.length > 0) {
|
|
32
|
+
debug.warn('mcp', `โ ๏ธ No project context found, falling back to first active project: ${activeProjects[0]}`);
|
|
33
|
+
return browserPreviewServiceManager.getService(activeProjects[0]);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
throw new Error('No active browser preview service found. Project isolation requires projectId.');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The chat session driving this call โ MCP control is scoped to it. */
|
|
40
|
+
export function getChatSessionId(): string {
|
|
41
|
+
const chatSessionId = projectContextService.getCurrentChatSessionId();
|
|
42
|
+
if (!chatSessionId) {
|
|
43
|
+
throw new Error('No chat session context available. Cannot acquire MCP control.');
|
|
44
|
+
}
|
|
45
|
+
return chatSessionId;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* The tab this call should act on, with MCP control acquired for it.
|
|
50
|
+
*
|
|
51
|
+
* A chat session accumulates tabs (open/switch add to its set), and the most
|
|
52
|
+
* recently used one is the target โ not the frontend's active tab, which the
|
|
53
|
+
* user may have changed while the agent was working.
|
|
54
|
+
*/
|
|
55
|
+
export async function getActiveTabSession(projectId?: string): Promise<{ tab: BrowserTab; service: BrowserPreviewService }> {
|
|
56
|
+
const service = getPreviewService(projectId);
|
|
57
|
+
const resolvedProjectId = service.getProjectId();
|
|
58
|
+
const chatSessionId = getChatSessionId();
|
|
59
|
+
|
|
60
|
+
const sessionTabs = browserMcpControl.getSessionTabs(chatSessionId);
|
|
61
|
+
if (sessionTabs.length > 0) {
|
|
62
|
+
const lastTabId = sessionTabs[sessionTabs.length - 1];
|
|
63
|
+
const controlledTab = service.getTab(lastTabId);
|
|
64
|
+
if (controlledTab) {
|
|
65
|
+
debug.log('mcp', `๐ฎ Using session-controlled tab: ${controlledTab.id}`);
|
|
66
|
+
return { tab: controlledTab, service };
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const tab = service.getActiveTab();
|
|
71
|
+
if (!tab) {
|
|
72
|
+
throw new Error("No open tab. Start with an `open_tab` action.");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const acquired = browserMcpControl.acquireControl(tab.id, chatSessionId, resolvedProjectId);
|
|
76
|
+
if (!acquired) {
|
|
77
|
+
const owner = browserMcpControl.getTabOwner(tab.id);
|
|
78
|
+
throw new Error(`Tab '${tab.id}' is controlled by another chat session (${owner?.slice(0, 8)}...). Use a different tab.`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
return { tab, service };
|
|
82
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The tool description.
|
|
3
|
+
*
|
|
4
|
+
* MCP ships this text on every request, so it is written to earn its tokens:
|
|
5
|
+
* the operating rules first, then the four workflows that cover almost all
|
|
6
|
+
* real use, then a reference generated from the action registry itself โ which
|
|
7
|
+
* is why it can never document an action that no longer exists.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { ACTION_GROUPS } from './actions';
|
|
11
|
+
|
|
12
|
+
const PREAMBLE = `Drive the built-in preview browser: tabs, navigation, input, and reading the page.
|
|
13
|
+
|
|
14
|
+
Everything is one call. Pass an array of actions and they run in order, which is what makes this fast โ one round trip instead of one per click.
|
|
15
|
+
|
|
16
|
+
HOW TO USE IT WELL
|
|
17
|
+
|
|
18
|
+
1. Batch. Put every step you can predict into one call: open_tab โ wait_for โ click โ type โ click โ screenshot is a single call, not six. Split only where the next step depends on something you must read first.
|
|
19
|
+
2. Target by selector or text, not coordinates. Elements are resolved in every frame, scrolled into view, and aimed at their centre โ coordinates go stale the moment the page reflows. Use \`find\` when you are unsure what to name; use x/y only for canvases and images.
|
|
20
|
+
3. Read with analyze_dom, not screenshots. Text, links and structure come back as text, for the whole document, at a fraction of the cost. Screenshot when the answer is visual: canvas, charts, layout, iframes, captchas.
|
|
21
|
+
4. Navigate by URL. If analyze_dom gave you an href, \`navigate\` to it. Clicking a link to move around is slower and fails more.
|
|
22
|
+
5. Synchronise with wait_for, not wait. wait_for returns the instant the condition holds; a fixed delay is either too short (the batch fails) or too long (every run pays for it).
|
|
23
|
+
6. Failure stops the batch. Anything after a failed action is skipped and reported as skipped. Mark a step \`optional: true\` when it may legitimately not apply โ dismissing a cookie banner that might not be there โ or set onError:"continue" for genuinely independent steps.
|
|
24
|
+
7. Obstacles are yours to clear. Captcha, modal, cookie wall: solve or dismiss it and carry on. Do not stop to ask.
|
|
25
|
+
8. Check the report. Every action reports its own outcome, and the report ends with the tab and URL you left behind. If a result contradicts your plan, say so and re-plan rather than continuing on the assumption it worked.
|
|
26
|
+
|
|
27
|
+
WORKFLOWS
|
|
28
|
+
|
|
29
|
+
Read a page / explore a site
|
|
30
|
+
[{navigate}, {analyze_dom, include:["navigation","content"]}]
|
|
31
|
+
then navigate to hrefs you found. No screenshots.
|
|
32
|
+
|
|
33
|
+
Fill a form
|
|
34
|
+
[{find, text:"Email"}] โ then one batch:
|
|
35
|
+
[{type, selector:"#email", text:"โฆ"}, {type, selector:"#password", text:"โฆ"}, {click, selector:"button[type=submit]"}, {wait_for, urlContains:"/dashboard"}]
|
|
36
|
+
|
|
37
|
+
Check a layout on mobile
|
|
38
|
+
[{set_viewport, deviceSize:"mobile"}, {wait_for, state:"networkIdle"}, {screenshot}]
|
|
39
|
+
|
|
40
|
+
Debug a page that misbehaves
|
|
41
|
+
[{clear_console}, {click, selector:"#save"}, {wait, ms:500}, {console_logs, level:"error"}]`;
|
|
42
|
+
|
|
43
|
+
const OUTRO = `NOTES
|
|
44
|
+
|
|
45
|
+
- Coordinates are in the page's own viewport (CSS pixels), the same space a screenshot is captured in.
|
|
46
|
+
- Selectors are searched in every frame, so an element inside an iframe is addressed the same way as one in the main document.
|
|
47
|
+
- A tab opened, switched to or closed mid-batch becomes the target for the actions that follow it.
|
|
48
|
+
- The user can interrupt at any time; the batch stops and the report says how far it got.`;
|
|
49
|
+
|
|
50
|
+
function renderReference(): string {
|
|
51
|
+
const sections = ACTION_GROUPS.map((group) => {
|
|
52
|
+
const entries = group.actions.map((action) => `- ${action.doc}`).join('\n');
|
|
53
|
+
return `${group.title}\n${entries}`;
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
return `ACTIONS\n\n${sections.join('\n\n')}`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export const actionsToolDescription = [PREAMBLE, renderReference(), OUTRO].join('\n\n');
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rendering the run report.
|
|
3
|
+
*
|
|
4
|
+
* The report is the agent's only view of what happened, so it leads with the
|
|
5
|
+
* count that matters (`4/6`), lists every action with its own outcome, and
|
|
6
|
+
* ends with where the browser was left. Images follow as their own blocks,
|
|
7
|
+
* each labelled with the action that produced it.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { RunReport } from './runner';
|
|
11
|
+
|
|
12
|
+
export function formatReport(report: RunReport): {
|
|
13
|
+
content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }>;
|
|
14
|
+
isError?: boolean;
|
|
15
|
+
} {
|
|
16
|
+
const ran = report.steps.length;
|
|
17
|
+
const total = ran + report.skipped;
|
|
18
|
+
const ok = report.steps.filter((s) => s.ok).length;
|
|
19
|
+
|
|
20
|
+
const header = [`Executed ${ok}/${total} action(s)`];
|
|
21
|
+
if (report.tabId) header.push(report.tabId);
|
|
22
|
+
if (report.url) header.push(report.url);
|
|
23
|
+
|
|
24
|
+
const lines: string[] = [header.join(' ยท ')];
|
|
25
|
+
|
|
26
|
+
for (const step of report.steps) {
|
|
27
|
+
const label = `[${step.index + 1}] ${step.type}`;
|
|
28
|
+
lines.push(step.ok ? `${label} ok${step.summary ? ` โ ${step.summary}` : ''}` : `${label} FAILED โ ${step.error}`);
|
|
29
|
+
if (step.detail) lines.push(indent(step.detail));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
if (report.aborted) {
|
|
33
|
+
lines.push('', 'Interrupted: the chat stream was cancelled, so the remaining actions did not run.');
|
|
34
|
+
} else if (report.skipped > 0) {
|
|
35
|
+
lines.push('', `${report.skipped} action(s) skipped after the failure above (onError defaults to "stop").`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }> = [
|
|
39
|
+
{ type: 'text', text: lines.join('\n') }
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
for (const image of report.images) {
|
|
43
|
+
if (image.label) content.push({ type: 'text', text: `โ ${image.label} โ` });
|
|
44
|
+
content.push({ type: 'image', data: image.data, mimeType: image.mimeType });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return { content, isError: report.failed || report.aborted ? true : undefined };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Keep multi-line payloads visually attached to their action. */
|
|
51
|
+
function indent(text: string): string {
|
|
52
|
+
return text
|
|
53
|
+
.split('\n')
|
|
54
|
+
.map((line) => ` ${line}`)
|
|
55
|
+
.join('\n');
|
|
56
|
+
}
|