Open History to see the last commit
1import {
2 BrowserNavigationTarget,
3 OrchestratorMcpFailure,
4 ToolActivityIcon,
5 PreviewAutomationActInput,
6 PreviewAutomationDialogInput,
7 PreviewAutomationError,
8 PreviewAutomationEvaluateInput,
9 PreviewAutomationNavigateInput,
10 PreviewAutomationOpenInput,
11 PreviewAutomationRecordingArtifact,
12 PreviewAutomationRecordingStatus,
13 PreviewAutomationResizeInput,
14 PreviewAutomationResizeResult,
15 PreviewAutomationSelectResult,
16 PreviewAutomationSetColorSchemeInput,
17 PreviewAutomationSetColorSchemeResult,
18 PreviewAutomationSnapshot,
19 PreviewAutomationStatus,
20 PreviewAutomationTabTargetInput,
21 PreviewAutomationWaitForInput,
22} from "@t3tools/contracts";
23import * as Schema from "effect/Schema";
24import * as FileSystem from "effect/FileSystem";
25import { Tool, Toolkit } from "effect/ai";
26
27import * as McpInvocationContext from "../../McpInvocationContext.ts";
28import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
29import * as ServerConfig from "../../../config.ts";
30import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
31
32const dependencies = [
33 McpInvocationContext.McpInvocationContext,
34 ThreadManagementService.ThreadManagementService,
35 PreviewAutomationBroker.PreviewAutomationBroker,
36];
37
38const PreviewToolFailure = Schema.Union([PreviewAutomationError, OrchestratorMcpFailure]);
39
40const presentationFields = { toolIcon: Schema.optional(ToolActivityIcon) };
41
42const PreviewActionResult = Schema.Struct(presentationFields);
43
44const browserTool = <T extends Tool.Any>(tool: T): T =>
45 tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, true) as T;
46
47const safeBrowserTool = <T extends Tool.Any>(tool: T): T =>
48 tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, false) as T;
49
50const readonlyBrowserTool = <T extends Tool.Any>(tool: T): T =>
51 safeBrowserTool(tool).annotate(Tool.Readonly, true).annotate(Tool.Idempotent, true) as T;
52
53const PreviewStatusTool = Tool.make("preview_status", {
54 description:
55 "Report preview tab state: owner, pending dialog, URL, title, loading, viewport, and size. `tabs` lists this thread's tabs. `profiles` lists logins for `preview_open`. Read any listed tab. Act only on your tab, or an unclaimed tab with no human in control.",
56 parameters: PreviewAutomationTabTargetInput,
57 success: PreviewAutomationStatus,
58 failure: PreviewToolFailure,
59 dependencies,
60})
61 .annotate(Tool.Title, "Get preview status")
62 .annotate(Tool.Readonly, true)
63 .annotate(Tool.Destructive, false)
64 .annotate(Tool.Idempotent, true);
65
66// `url` already covers websites, so open only adds the dev-server target.
67const EnvironmentPortTarget = BrowserNavigationTarget.members[1];
68
69const PreviewOpenTool = browserTool(
70 Tool.make("preview_open", {
71 description:
72 "Open a preview tab in this thread and show it. For a dev server, pass `target` instead of `url`. `open=false` keeps it in the background. Reuses your current tab unless `tabId` or `reuseExistingTab=false` says otherwise. Parallel subagents in one session must each use `reuseExistingTab=false`, then their own returned `tabId`.",
73 parameters: PreviewAutomationOpenInput.mapFields(
74 (fields) => ({ ...fields, target: Schema.optional(EnvironmentPortTarget) }),
75 { unsafePreserveChecks: true },
76 ),
77 success: PreviewAutomationStatus,
78 failure: PreviewToolFailure,
79 dependencies,
80 })
81 .annotate(Tool.Title, "Open browser preview")
82 .annotate(Tool.Destructive, false),
83);
84
85const PreviewDialogTool = browserTool(
86 Tool.make("preview_dialog", {
87 description:
88 "Accept or dismiss the dialog `preview_status` reports. Pass `promptText` to accept a prompt. Needs your own tab, or an unclaimed one. Desktop hosts may not support this.",
89 parameters: PreviewAutomationDialogInput,
90 success: PreviewAutomationStatus,
91 failure: PreviewToolFailure,
92 dependencies,
93 }).annotate(Tool.Title, "Resolve browser dialog"),
94);
95
96const PreviewNavigateTool = safeBrowserTool(
97 Tool.make("preview_navigate", {
98 description:
99 "Navigate the chosen tab. Pass `url` for a website, or `target:{kind:'environment-port',port}` for a dev server. Exactly one of `url` and `target`.",
100 parameters: PreviewAutomationNavigateInput,
101 success: PreviewAutomationStatus,
102 failure: PreviewToolFailure,
103 dependencies,
104 }).annotate(Tool.Title, "Navigate browser preview"),
105);
106
107const PreviewResizeTool = safeBrowserTool(
108 Tool.make("preview_resize", {
109 description:
110 "Resize the chosen tab: {mode:'fill'}, {mode:'freeform',width,height}, or {mode:'preset',preset,orientation}. Changes CSS size only, not the user agent.",
111 parameters: PreviewAutomationResizeInput,
112 success: Schema.Struct({ ...PreviewAutomationResizeResult.fields, ...presentationFields }),
113 failure: PreviewToolFailure,
114 dependencies,
115 })
116 .annotate(Tool.Title, "Resize browser viewport")
117 .annotate(Tool.Idempotent, true),
118);
119
120const PreviewSetAppearanceTool = safeBrowserTool(
121 Tool.make("preview_set_appearance", {
122 description:
123 "Set `prefers-color-scheme` for the chosen tab: 'dark', 'light', or 'system' to clear the override.",
124 parameters: PreviewAutomationSetColorSchemeInput,
125 success: Schema.Struct({
126 ...PreviewAutomationSetColorSchemeResult.fields,
127 ...presentationFields,
128 }),
129 failure: PreviewToolFailure,
130 dependencies,
131 })
132 .annotate(Tool.Title, "Set preview appearance")
133 .annotate(Tool.Idempotent, true),
134);
135
136// Not read-only: save=true writes the screenshot to disk.
137export const PreviewSnapshotTool = safeBrowserTool(
138 Tool.make("preview_snapshot", {
139 description:
140 "Use it only when the current request asks for browser work, including checking an edit in the browser. Never use it unasked to verify your own edit, or to repeat a snapshot from an earlier turn. Works on a tab the user is driving. Returns page state, elements, diagnostics, and screenshot size. Target one element with `locator='aria-ref=<ref>'` from `accessibilityTree`, even in frames. Refs die on navigation, a new snapshot, or handoff. Text caps near 20 KB; on your own or an unclaimed tab, `preview_evaluate` reads more. To show a screenshot when asked: `save=true`, then embed .",
141 parameters: Schema.Struct({
142 ...PreviewAutomationTabTargetInput.fields,
143 includeImage: Schema.optional(
144 Schema.Boolean.annotate({
145 description: "Default false. True only to see the page.",
146 }),
147 ),
148 save: Schema.optional(
149 Schema.Boolean.annotate({
150 description: "Write PNG, return `screenshotPath`.",
151 }),
152 ),
153 }),
154 success: PreviewAutomationSnapshot,
155 failure: PreviewToolFailure,
156 dependencies,
157 }).annotate(Tool.Title, "Inspect browser page"),
158);
159
160const PreviewActTool = browserTool(
161 Tool.make("preview_act", {
162 description:
163 "Act on the chosen tab. Target with `locator='aria-ref=<ref>'` from `preview_snapshot`; `x` and `y` go together. `timeoutMs` defaults to 15000. click: `button`, `clickCount` 1 to 3. type: literal `text`, `clear=true` replaces it. hover: shows menus or tooltips. select: `values` in one native <select>, by value or label; for a custom dropdown, click it open, then click the option. drag: `source` onto `target`. upload: absolute `paths` answer the file picker `preview_status` reports, [] cancels it, or a `locator` sets an <input type=file>. press: one `key`, such as 'Enter', with `modifiers`, to the focused element; click a field first to focus it. scroll: the tab, or one container with a locator; positive `deltaY` scrolls down, positive `deltaX` right.",
164 parameters: PreviewAutomationActInput,
165 success: Schema.Union([
166 Schema.Struct({ ...PreviewAutomationSelectResult.fields, ...presentationFields }),
167 PreviewActionResult,
168 ]),
169 failure: PreviewToolFailure,
170 dependencies,
171 }).annotate(Tool.Title, "Act in preview page"),
172);
173
174/** Wrap non-objects: MCP requires object structuredContent, and Claude Code rejects invalid results entirely. */
175export const PreviewEvaluateResult = Schema.Struct({
176 ...presentationFields,
177 value: Schema.Unknown.annotate({
178 description: "The JSON-serializable value the expression produced, or null.",
179 }),
180});
181
182const PreviewEvaluateTool = browserTool(
183 Tool.make("preview_evaluate", {
184 description:
185 "Run JavaScript in the page. It can change page state. Returns `{value}`, up to 64 KB. Needs your tab, or an unclaimed one. To read a tab the user drives, use `preview_snapshot`. Page tools write only on user request. Show results with `html_render`, never page tools.",
186 parameters: PreviewAutomationEvaluateInput,
187 success: PreviewEvaluateResult,
188 failure: PreviewToolFailure,
189 dependencies,
190 }).annotate(Tool.Title, "Evaluate JavaScript in preview"),
191);
192
193const PreviewWaitForTool = readonlyBrowserTool(
194 Tool.make("preview_wait_for", {
195 description:
196 "Wait until all given locator, selector, text, and URL conditions match in the chosen tab.",
197 parameters: PreviewAutomationWaitForInput,
198 success: PreviewActionResult,
199 failure: PreviewToolFailure,
200 dependencies,
201 }).annotate(Tool.Title, "Wait for preview page condition"),
202);
203
204const PreviewRecordingStartTool = safeBrowserTool(
205 Tool.make("preview_recording_start", {
206 description: "Start recording the chosen tab.",
207 parameters: PreviewAutomationTabTargetInput,
208 success: Schema.Struct({ ...PreviewAutomationRecordingStatus.fields, ...presentationFields }),
209 failure: PreviewToolFailure,
210 dependencies,
211 }).annotate(Tool.Title, "Start browser recording"),
212);
213
214const PreviewRecordingStopTool = safeBrowserTool(
215 Tool.make("preview_recording_stop", {
216 description:
217 "Stop recording the chosen tab. Returns a local path to the recording file (max 50 MiB).",
218 parameters: PreviewAutomationTabTargetInput,
219 success: Schema.Struct({ ...PreviewAutomationRecordingArtifact.fields, ...presentationFields }),
220 failure: PreviewToolFailure,
221 dependencies: [...dependencies, FileSystem.FileSystem, ServerConfig.ServerConfig],
222 }).annotate(Tool.Title, "Stop browser recording"),
223);
224
225export const PreviewToolkit = Toolkit.make(
226 PreviewDialogTool,
227 PreviewStatusTool,
228 PreviewOpenTool,
229 PreviewNavigateTool,
230 PreviewResizeTool,
231 PreviewSetAppearanceTool,
232 PreviewSnapshotTool,
233 PreviewActTool,
234 PreviewEvaluateTool,
235 PreviewWaitForTool,
236 PreviewRecordingStartTool,
237 PreviewRecordingStopTool,
238);
239
240export const PreviewStandardToolkit = Toolkit.make(
241 PreviewDialogTool,
242 PreviewStatusTool,
243 PreviewOpenTool,
244 PreviewNavigateTool,
245 PreviewResizeTool,
246 PreviewSetAppearanceTool,
247 PreviewActTool,
248 PreviewEvaluateTool,
249 PreviewWaitForTool,
250 PreviewRecordingStartTool,
251 PreviewRecordingStopTool,
252);
253
254export const PreviewSnapshotToolkit = Toolkit.make(PreviewSnapshotTool);