Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

tools.ts

357 lines15.6 KB

1import {
2 OrchestratorMcpFailure,
3 ToolActivityIcon,
4 PreviewAutomationClickInput,
5 PreviewAutomationDialogInput,
6 PreviewAutomationDragInput,
7 PreviewAutomationError,
8 PreviewAutomationEvaluateInput,
9 PreviewAutomationHoverInput,
10 PreviewAutomationNavigateInput,
11 PreviewAutomationOpenInput,
12 PreviewAutomationPressInput,
13 PreviewAutomationRecordingArtifact,
14 PreviewAutomationRecordingStatus,
15 PreviewAutomationResizeInput,
16 PreviewAutomationResizeResult,
17 PreviewAutomationScrollInput,
18 PreviewAutomationSelectInput,
19 PreviewAutomationSelectResult,
20 PreviewAutomationSetColorSchemeInput,
21 PreviewAutomationSetColorSchemeResult,
22 PreviewAutomationSnapshot,
23 PreviewAutomationStatus,
24 PreviewAutomationTabTargetInput,
25 PreviewAutomationTypeInput,
26 PreviewAutomationUploadInput,
27 PreviewAutomationWaitForInput,
28} from "@t3tools/contracts";
29import * as Schema from "effect/Schema";
30import * as FileSystem from "effect/FileSystem";
31import { Tool, Toolkit } from "effect/ai";
32​
33import * as McpInvocationContext from "../../McpInvocationContext.ts";
34import * as PreviewAutomationBroker from "../../PreviewAutomationBroker.ts";
35import * as ServerConfig from "../../../config.ts";
36import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
37​
38const dependencies = [
39 McpInvocationContext.McpInvocationContext,
40 ThreadManagementService.ThreadManagementService,
41 PreviewAutomationBroker.PreviewAutomationBroker,
42];
43​
44/** What a browser action fails with, including the access gate's refusal. */
45const PreviewToolFailure = Schema.Union([PreviewAutomationError, OrchestratorMcpFailure]);
46​
47const presentationFields = { toolIcon: Schema.optional(ToolActivityIcon) };
48​
49const PreviewActionResult = Schema.Struct(presentationFields).annotate({
50 description: "The preview action completed successfully.",
51});
52​
53/** Drives the real browser and can destroy page state. */
54const browserTool = <T extends Tool.Any>(tool: T): T =>
55 tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, true) as T;
56​
57/** Same open-world browser access, but the action does not destroy page state. */
58const safeBrowserTool = <T extends Tool.Any>(tool: T): T =>
59 tool.annotate(Tool.OpenWorld, true).annotate(Tool.Destructive, false) as T;
60​
61/** A safe browser action that only observes, so it is also repeatable. */
62const readonlyBrowserTool = <T extends Tool.Any>(tool: T): T =>
63 safeBrowserTool(tool).annotate(Tool.Readonly, true).annotate(Tool.Idempotent, true) as T;
64​
65const PreviewStatusTool = Tool.make("preview_status", {
66 description:
67 "Report whether a collaborative browser tab is automation-capable, including its control owner, pending dialog, URL, title, visibility, loading state, viewport mode, and measured CSS-pixel size. Pass tabId to inspect a specific tab; omit it to use this agent session's current tab.",
68 parameters: PreviewAutomationTabTargetInput,
69 success: PreviewAutomationStatus,
70 failure: PreviewToolFailure,
71 dependencies,
72})
73 .annotate(Tool.Title, "Get preview status")
74 .annotate(Tool.Readonly, true)
75 .annotate(Tool.Destructive, false)
76 .annotate(Tool.Idempotent, true);
77​
78const PreviewOpenTool = browserTool(
79 Tool.make("preview_open", {
80 description:
81 "Initialize a collaborative browser tab and open its thread-bound inline preview by default. Set open=false for background-only automation. Pass tabId to reuse a specific existing tab, set reuseExistingTab=false to create another tab, or omit both to use this agent session's current tab. Parallel subagents sharing a provider session must each open with reuseExistingTab=false and pass their returned tabId on every call. Server tabs use isolated storage and cannot be operated by a different agent session.",
82 parameters: PreviewAutomationOpenInput,
83 success: PreviewAutomationStatus,
84 failure: PreviewToolFailure,
85 dependencies,
86 })
87 .annotate(Tool.Title, "Open browser preview")
88 .annotate(Tool.Destructive, false),
89);
90​
91const PreviewDialogTool = browserTool(
92 Tool.make("preview_dialog", {
93 description:
94 "Accept or dismiss the server browser dialog reported by preview_status. For a prompt, supply promptText when accepting. Requires this agent to own the tab. Desktop hosts may not support this operation.",
95 parameters: PreviewAutomationDialogInput,
96 success: PreviewAutomationStatus,
97 failure: PreviewToolFailure,
98 dependencies,
99 }).annotate(Tool.Title, "Resolve browser dialog"),
100);
101​
102const PreviewNavigateTool = safeBrowserTool(
103 Tool.make("preview_navigate", {
104 description:
105 "Navigate a collaborative browser tab. Pass tabId to target a specific tab, plus {url:'https://t3.chat'} for a website or {target:{kind:'environment-port',port:5173}} for a dev server. Exactly one of url or target is required.",
106 parameters: PreviewAutomationNavigateInput,
107 success: PreviewAutomationStatus,
108 failure: PreviewToolFailure,
109 dependencies,
110 }).annotate(Tool.Title, "Navigate browser preview"),
111);
112​
113const PreviewResizeTool = safeBrowserTool(
114 Tool.make("preview_resize", {
115 description:
116 "Resize a collaborative browser tab, optionally selected by tabId. Use {mode:'fill'}, {mode:'freeform',width:1024,height:768}, or {mode:'preset',preset:'iphone-12-pro',orientation:'portrait'}. This changes CSS layout breakpoints without changing the desktop browser user agent.",
117 parameters: PreviewAutomationResizeInput,
118 success: Schema.Struct({ ...PreviewAutomationResizeResult.fields, ...presentationFields }),
119 failure: PreviewToolFailure,
120 dependencies,
121 })
122 .annotate(Tool.Title, "Resize browser viewport")
123 .annotate(Tool.Idempotent, true),
124);
125​
126const PreviewSetAppearanceTool = safeBrowserTool(
127 Tool.make("preview_set_appearance", {
128 description:
129 "Emulate prefers-color-scheme in a collaborative browser tab, optionally selected by tabId. Use {colorScheme:'dark'} or {colorScheme:'light'} to preview the page in that appearance, and {colorScheme:'system'} to clear the override and follow the OS appearance.",
130 parameters: PreviewAutomationSetColorSchemeInput,
131 success: Schema.Struct({
132 ...PreviewAutomationSetColorSchemeResult.fields,
133 ...presentationFields,
134 }),
135 failure: PreviewToolFailure,
136 dependencies,
137 })
138 .annotate(Tool.Title, "Set preview appearance")
139 .annotate(Tool.Idempotent, true),
140);
141​
142export const PreviewSnapshotTool = readonlyBrowserTool(
143 Tool.make("preview_snapshot", {
144 description:
145 "Inspect a page before interacting. Pass tabId to inspect a specific tab; omit it to use this agent session's current tab. Returns page state, semantic elements, diagnostics, action history, and a PNG screenshot. Server snapshots include an accessibilityTree with refs; pass locator=aria-ref=<ref> to target one exact element, including inside frames. Refresh refs after navigation, another snapshot, or human takeover. The text is capped near 20 KB and lists what it omitted; use preview_evaluate to read more. Set includeImage=false for text-only output with the same page metadata. Set save=true to also write the PNG to disk and get screenshotPath back; with includeImage=false, save=true returns only the url and screenshotPath. Embed that path in your reply as ![alt](screenshotPath) so the user sees it. This is the only way to show the user a screenshot; the image in the tool result is not saved anywhere.",
146 parameters: Schema.Struct({
147 ...PreviewAutomationTabTargetInput.fields,
148 includeImage: Schema.optional(
149 Schema.Boolean.annotate({
150 description:
151 "Include the PNG image in the tool response. Defaults to true. Set false for text-only output.",
152 }),
153 ),
154 save: Schema.optional(
155 Schema.Boolean.annotate({
156 description:
157 "Write the screenshot PNG to disk and return its absolute path as screenshotPath. With includeImage=false, return only the url and screenshotPath. Defaults to false.",
158 }),
159 ),
160 }),
161 success: PreviewAutomationSnapshot,
162 failure: PreviewToolFailure,
163 dependencies,
164 }).annotate(Tool.Title, "Inspect browser page"),
165);
166​
167const PreviewClickTool = browserTool(
168 Tool.make("preview_click", {
169 description:
170 "Click exactly one target in the tab selected by tabId, or this agent session's current tab when omitted. Prefer a Playwright locator; selector accepts legacy CSS; x and y must be supplied together. Set button=right for a context menu or clickCount=2 for a double-click; server browser tabs only.",
171 parameters: PreviewAutomationClickInput,
172 success: PreviewActionResult,
173 failure: PreviewToolFailure,
174 dependencies,
175 }).annotate(Tool.Title, "Click preview page"),
176);
177​
178const PreviewTypeTool = browserTool(
179 Tool.make("preview_type", {
180 description:
181 "Insert literal text into one input in the tab selected by tabId, or this agent session's current tab when omitted. Prefer a Playwright locator; set clear=true to replace existing text.",
182 parameters: PreviewAutomationTypeInput,
183 success: PreviewActionResult,
184 failure: PreviewToolFailure,
185 dependencies,
186 }).annotate(Tool.Title, "Type into preview page"),
187);
188​
189const PreviewHoverTool = safeBrowserTool(
190 Tool.make("preview_hover", {
191 description:
192 "Move the mouse over exactly one target in the tab selected by tabId, or this agent session's current tab when omitted, to reveal hover menus and tooltips. Server browser tabs only.",
193 parameters: PreviewAutomationHoverInput,
194 success: PreviewActionResult,
195 failure: PreviewToolFailure,
196 dependencies,
197 }).annotate(Tool.Title, "Hover preview page"),
198);
199​
200const PreviewSelectTool = browserTool(
201 Tool.make("preview_select", {
202 description:
203 "Choose options in one native <select> in the tab selected by tabId, or this agent session's current tab when omitted, by option value or visible label. Custom dropdowns are not <select>; click them open and click the option instead. Server browser tabs only.",
204 parameters: PreviewAutomationSelectInput,
205 success: Schema.Struct({
206 ...PreviewAutomationSelectResult.fields,
207 ...presentationFields,
208 }),
209 failure: PreviewToolFailure,
210 dependencies,
211 }).annotate(Tool.Title, "Select preview option"),
212);
213​
214const PreviewDragTool = browserTool(
215 Tool.make("preview_drag", {
216 description:
217 "Drag one element onto another in the tab selected by tabId, or this agent session's current tab when omitted. Server browser tabs only.",
218 parameters: PreviewAutomationDragInput,
219 success: PreviewActionResult,
220 failure: PreviewToolFailure,
221 dependencies,
222 }).annotate(Tool.Title, "Drag in preview page"),
223);
224​
225const PreviewUploadTool = browserTool(
226 Tool.make("preview_upload", {
227 description:
228 "Give files on the environment to the page in the tab selected by tabId, or this agent session's current tab when omitted. After clicking an upload control, preview_status reports the open fileChooser; call this with absolute paths to answer it, or with an empty list to cancel. Pass a locator for an <input type=file> to set its files without a picker. Server browser tabs only.",
229 parameters: PreviewAutomationUploadInput,
230 success: PreviewActionResult,
231 failure: PreviewToolFailure,
232 dependencies,
233 }).annotate(Tool.Title, "Upload files to preview page"),
234);
235​
236const PreviewPressTool = browserTool(
237 Tool.make("preview_press", {
238 description:
239 "Press one keyboard key in the tab selected by tabId, or this agent session's current tab when omitted. Examples: {key:'Enter'}, {key:'Escape'}, or {key:'a',modifiers:['Meta']}.",
240 parameters: PreviewAutomationPressInput,
241 success: PreviewActionResult,
242 failure: PreviewToolFailure,
243 dependencies,
244 }).annotate(Tool.Title, "Press key in preview page"),
245);
246​
247const PreviewScrollTool = safeBrowserTool(
248 Tool.make("preview_scroll", {
249 description:
250 "Scroll the tab selected by tabId, or this agent session's current tab when omitted. Positive deltaY scrolls down and positive deltaX scrolls right; a locator/selector targets a container.",
251 parameters: PreviewAutomationScrollInput,
252 success: PreviewActionResult,
253 failure: PreviewToolFailure,
254 dependencies,
255 }).annotate(Tool.Title, "Scroll preview page"),
256);
257​
258/**
259 * MCP `structuredContent` must be a JSON object, and Claude Code rejects the
260 * whole result when it is not. Wrapping keeps arrays, strings, numbers, and
261 * null valid instead of failing only for non-object expressions.
262 */
263export const PreviewEvaluateResult = Schema.Struct({
264 ...presentationFields,
265 value: Schema.Unknown.annotate({
266 description: "The JSON-serializable value the expression produced, or null.",
267 }),
268}).annotate({ description: "The evaluated expression result." });
269​
270const PreviewEvaluateTool = browserTool(
271 Tool.make("preview_evaluate", {
272 description:
273 "Evaluate JavaScript in the tab selected by tabId, or this agent session's current tab when omitted. Returns {value} with a serializable result up to 64 KB; the expression may mutate page state.",
274 parameters: PreviewAutomationEvaluateInput,
275 success: PreviewEvaluateResult,
276 failure: PreviewToolFailure,
277 dependencies,
278 }).annotate(Tool.Title, "Evaluate JavaScript in preview"),
279);
280​
281const PreviewWaitForTool = readonlyBrowserTool(
282 Tool.make("preview_wait_for", {
283 description:
284 "Wait in the tab selected by tabId, or this agent session's current tab when omitted, until all supplied locator, selector, text, and URL conditions match.",
285 parameters: PreviewAutomationWaitForInput,
286 success: PreviewActionResult,
287 failure: PreviewToolFailure,
288 dependencies,
289 }).annotate(Tool.Title, "Wait for preview page condition"),
290);
291​
292const PreviewRecordingStartTool = safeBrowserTool(
293 Tool.make("preview_recording_start", {
294 description:
295 "Start recording the collaborative browser tab selected by tabId, or this agent session's current tab when omitted.",
296 parameters: PreviewAutomationTabTargetInput,
297 success: Schema.Struct({ ...PreviewAutomationRecordingStatus.fields, ...presentationFields }),
298 failure: PreviewToolFailure,
299 dependencies,
300 }).annotate(Tool.Title, "Start browser recording"),
301);
302​
303const PreviewRecordingStopTool = safeBrowserTool(
304 Tool.make("preview_recording_stop", {
305 description:
306 "Stop recording the collaborative browser tab selected by tabId, or this agent session's current tab when omitted, and transfer the compressed recording once (up to 50 MiB) to an evidence file readable in this agent's environment. Returns its environment-local path after transfer succeeds.",
307 parameters: PreviewAutomationTabTargetInput,
308 success: Schema.Struct({ ...PreviewAutomationRecordingArtifact.fields, ...presentationFields }),
309 failure: PreviewToolFailure,
310 dependencies: [...dependencies, FileSystem.FileSystem, ServerConfig.ServerConfig],
311 }).annotate(Tool.Title, "Stop browser recording"),
312);
313​
314export const PreviewToolkit = Toolkit.make(
315 PreviewDialogTool,
316 PreviewStatusTool,
317 PreviewOpenTool,
318 PreviewNavigateTool,
319 PreviewResizeTool,
320 PreviewSetAppearanceTool,
321 PreviewSnapshotTool,
322 PreviewClickTool,
323 PreviewTypeTool,
324 PreviewHoverTool,
325 PreviewSelectTool,
326 PreviewDragTool,
327 PreviewUploadTool,
328 PreviewPressTool,
329 PreviewScrollTool,
330 PreviewEvaluateTool,
331 PreviewWaitForTool,
332 PreviewRecordingStartTool,
333 PreviewRecordingStopTool,
334);
335​
336export const PreviewStandardToolkit = Toolkit.make(
337 PreviewDialogTool,
338 PreviewStatusTool,
339 PreviewOpenTool,
340 PreviewNavigateTool,
341 PreviewResizeTool,
342 PreviewSetAppearanceTool,
343 PreviewClickTool,
344 PreviewTypeTool,
345 PreviewHoverTool,
346 PreviewSelectTool,
347 PreviewDragTool,
348 PreviewUploadTool,
349 PreviewPressTool,
350 PreviewScrollTool,
351 PreviewEvaluateTool,
352 PreviewWaitForTool,
353 PreviewRecordingStartTool,
354 PreviewRecordingStopTool,
355);
356​
357export const PreviewSnapshotToolkit = Toolkit.make(PreviewSnapshotTool);