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

previewAutomation.ts

1,172 lines44.3 KB

1import { Schema } from "effect";
2​
3import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
4import {
5 PREVIEW_VIEWPORT_MAX_AREA,
6 PreviewRenderedViewportSize,
7 PreviewTabId,
8 PreviewViewportPresetId,
9 PreviewViewportSetting,
10 PreviewViewportSize,
11} from "./preview.ts";
12import { ProviderInstanceId } from "./providerInstance.ts";
13import { BrowserProfileId } from "./browserProfile.ts";
14​
15const BoundedUrl = Schema.String.check(Schema.isTrimmed())
16 .check(Schema.isNonEmpty())
17 .check(Schema.isMaxLength(2048));
18const URL_GUIDANCE =
19 "Absolute http(s) URL or a schemeless host such as t3.chat or localhost:5173. Schemeless public hosts use https; loopback hosts use http.";
20const PROFILE_GUIDANCE =
21 "Browser profile for a new tab, by id or name (case-insensitive) from preview_status profiles. Omit to use the user's default profile. A tab keeps the profile it opened with.";
22const OptionalTimeoutMs = Schema.optional(
23 Schema.Int.check(Schema.isGreaterThan(0))
24 .check(Schema.isLessThanOrEqualTo(60_000))
25 .annotate({ description: "Maximum wait in milliseconds. Defaults to 15000; maximum 60000." }),
26).annotate({ description: "Maximum wait in milliseconds. Defaults to 15000; maximum 60000." });
27​
28export const PREVIEW_AUTOMATION_V1_OPERATIONS = [
29 "status",
30 "open",
31 "navigate",
32 "snapshot",
33 "click",
34 "type",
35 "press",
36 "scroll",
37 "evaluate",
38 "waitFor",
39 "recordingStart",
40 "recordingStop",
41] as const;
42​
43const PREVIEW_AUTOMATION_OPERATIONS = [
44 ...PREVIEW_AUTOMATION_V1_OPERATIONS,
45 "resize",
46 "setColorScheme",
47] as const;
48​
49export const PREVIEW_AUTOMATION_SERVER_OPERATIONS = [
50 ...PREVIEW_AUTOMATION_OPERATIONS,
51 "dialog",
52 "close",
53 "upload",
54 "hover",
55 "select",
56 "drag",
57] as const;
58export const PreviewAutomationOperation = Schema.Literals(PREVIEW_AUTOMATION_SERVER_OPERATIONS);
59export type PreviewAutomationOperation = typeof PreviewAutomationOperation.Type;
60​
61const PreviewAutomationTabTargetFields = {
62 tabId: Schema.optional(
63 PreviewTabId.annotate({
64 description:
65 "Exact collaborative browser tab to target, including a tab the user opened (see preview_status tabs). Omit to use this agent session's current tab, or the user's visible tab when this session has none.",
66 }),
67 ).annotate({
68 description:
69 "Exact collaborative browser tab to target, including a tab the user opened (see preview_status tabs). Omit to use this agent session's current tab, or the user's visible tab when this session has none.",
70 }),
71};
72​
73export const PreviewAutomationTabTargetInput = Schema.Struct(PreviewAutomationTabTargetFields);
74export type PreviewAutomationTabTargetInput = typeof PreviewAutomationTabTargetInput.Type;
75​
76export const PreviewAutomationTabOwner = Schema.Literals(["agent", "human", "unclaimed"]);
77​
78export const PreviewAutomationProfile = Schema.Struct({
79 id: BrowserProfileId,
80 name: Schema.String,
81 incognito: Schema.optional(Schema.Boolean),
82});
83export type PreviewAutomationProfile = typeof PreviewAutomationProfile.Type;
84​
85export const PreviewAutomationStatus = Schema.Struct({
86 available: Schema.Boolean,
87 visible: Schema.Boolean,
88 tabId: Schema.NullOr(PreviewTabId),
89 url: Schema.NullOr(Schema.String),
90 title: Schema.NullOr(Schema.String),
91 loading: Schema.Boolean,
92 control: Schema.optional(
93 Schema.Struct({
94 owner: PreviewAutomationTabOwner,
95 ownedByCaller: Schema.Boolean,
96 generation: Schema.Number,
97 }),
98 ),
99 dialog: Schema.optional(
100 Schema.NullOr(
101 Schema.Struct({
102 type: Schema.String,
103 message: Schema.String,
104 defaultValue: Schema.String,
105 }),
106 ),
107 ),
108 viewportSetting: Schema.optional(PreviewViewportSetting),
109 viewport: Schema.optional(PreviewRenderedViewportSize),
110 fileChooser: Schema.optional(
111 Schema.NullOr(Schema.Struct({ multiple: Schema.Boolean, accept: Schema.String })),
112 ),
113 downloads: Schema.optional(
114 Schema.Array(
115 Schema.Struct({
116 fileName: Schema.String,
117 path: Schema.String,
118 sizeBytes: Schema.Number,
119 url: Schema.String,
120 completedAt: Schema.String,
121 }),
122 ),
123 ),
124 /**
125 * Server hosts: every tab in the thread, including ones the user or another
126 * agent session opened. Any of them can be read; acting needs `ownedByCaller`,
127 * or an `unclaimed` tab while no human controls it.
128 */
129 tabs: Schema.optional(
130 Schema.Array(
131 Schema.Struct({
132 tabId: PreviewTabId,
133 url: Schema.NullOr(Schema.String),
134 openerTabId: Schema.optional(PreviewTabId),
135 owner: Schema.optional(PreviewAutomationTabOwner),
136 ownedByCaller: Schema.optional(Schema.Boolean),
137 visible: Schema.optional(Schema.Boolean),
138 profileId: Schema.optional(BrowserProfileId),
139 }),
140 ),
141 ),
142 profiles: Schema.optional(Schema.Array(PreviewAutomationProfile)),
143 defaultProfileId: Schema.optional(BrowserProfileId),
144});
145export type PreviewAutomationStatus = typeof PreviewAutomationStatus.Type;
146​
147export const PreviewAutomationDialogInput = Schema.Struct({
148 ...PreviewAutomationTabTargetFields,
149 accept: Schema.Boolean.annotate({
150 description: "Accept the pending browser dialog when true, or dismiss it when false.",
151 }),
152 promptText: Schema.optional(Schema.String).annotate({
153 description: "Optional text to submit when accepting a prompt dialog.",
154 }),
155});
156export type PreviewAutomationDialogInput = typeof PreviewAutomationDialogInput.Type;
157​
158export const PreviewAutomationOpenInput = Schema.Struct({
159 ...PreviewAutomationTabTargetFields,
160 url: Schema.optional(BoundedUrl).annotate({
161 description: `Optional initial page URL. ${URL_GUIDANCE} Omit to open a blank tab.`,
162 }),
163 open: Schema.optional(
164 Schema.Boolean.annotate({
165 description:
166 "Whether to open the thread-bound inline preview for the human. Defaults to true; set false for background-only automation.",
167 }),
168 ),
169 show: Schema.optional(
170 Schema.Boolean.annotate({
171 description:
172 "Deprecated alias for open. Whether to reveal the thread-bound inline preview to the human.",
173 }),
174 ),
175 reuseExistingTab: Schema.optional(
176 Schema.Boolean.annotate({
177 description:
178 "Reuse tabId when supplied, otherwise this agent session's current tab. Defaults to true; set false to create a new tab.",
179 }),
180 ),
181 profileId: Schema.optional(
182 TrimmedNonEmptyString.check(Schema.isMaxLength(64)).annotate({
183 description: PROFILE_GUIDANCE,
184 }),
185 ).annotate({ description: PROFILE_GUIDANCE }),
186})
187 .check(
188 Schema.makeFilter(
189 (input) =>
190 !(input.tabId !== undefined && input.reuseExistingTab === false) ||
191 "tabId cannot be combined with reuseExistingTab=false.",
192 ),
193 )
194 .annotate({
195 description:
196 "Opens the collaborative browser for the current thread. Use preview_navigate afterward when readiness waiting matters.",
197 });
198export type PreviewAutomationOpenInput = typeof PreviewAutomationOpenInput.Type;
199​
200export const BrowserNavigationTarget = Schema.Union([
201 Schema.Struct({
202 kind: Schema.Literal("url").annotate({
203 description: "Selects direct URL navigation.",
204 }),
205 url: BoundedUrl.annotate({
206 description: `Direct website URL. ${URL_GUIDANCE}`,
207 }),
208 }),
209 Schema.Struct({
210 kind: Schema.Literal("environment-port").annotate({
211 description: "Selects a dev-server port relative to the current execution environment.",
212 }),
213 port: Schema.Int.check(Schema.isGreaterThan(0))
214 .check(Schema.isLessThan(65_536))
215 .annotate({ description: "Dev-server TCP port inside the current environment." }),
216 protocol: Schema.optional(
217 Schema.Literals(["http", "https"]).annotate({
218 description: "Dev-server protocol. Defaults to http.",
219 }),
220 ),
221 path: Schema.optional(
222 Schema.String.annotate({
223 description: "Optional path, query, and fragment, for example /settings?tab=account.",
224 }),
225 ),
226 }),
227]);
228export type BrowserNavigationTarget = typeof BrowserNavigationTarget.Type;
229​
230export const PreviewAutomationNavigateInput = Schema.Struct({
231 ...PreviewAutomationTabTargetFields,
232 url: Schema.optional(BoundedUrl).annotate({
233 description: `Website URL. ${URL_GUIDANCE} Use this for public pages and directly reachable URLs.`,
234 }),
235 target: Schema.optional(
236 BrowserNavigationTarget.annotate({
237 description:
238 "Environment-relative target. Prefer {kind:'environment-port',port:5173} for a dev server in the current environment.",
239 }),
240 ).annotate({
241 description:
242 "Environment-relative target. Prefer {kind:'environment-port',port:5173} for a dev server in the current environment.",
243 }),
244 readiness: Schema.optional(
245 Schema.Literals(["load", "domContentLoaded", "none"]).annotate({
246 description:
247 "Readiness milestone before returning. 'load' waits for loading to stop (default), 'domContentLoaded' waits for an interactive document, and 'none' returns immediately.",
248 }),
249 ).annotate({
250 description:
251 "Readiness milestone before returning. 'load' is the default; use 'none' only when a later wait call will verify the page.",
252 }),
253 timeoutMs: OptionalTimeoutMs,
254})
255 .check(
256 Schema.makeFilter(
257 (input) =>
258 Number(input.url !== undefined) + Number(input.target !== undefined) === 1 ||
259 "Provide exactly one of url or target.",
260 ),
261 )
262 .annotate({
263 description:
264 "Navigates the active browser tab. Provide exactly one of url or target; for most public pages use url.",
265 });
266export type PreviewAutomationNavigateInput = typeof PreviewAutomationNavigateInput.Type;
267​
268export const PreviewAutomationResizeInput = Schema.Struct({
269 ...PreviewAutomationTabTargetFields,
270 mode: Schema.Literals(["fill", "freeform", "preset"]).annotate({
271 description:
272 "Viewport mode: fill follows the preview panel, freeform uses exact independently resizable dimensions, and preset uses a named device size.",
273 }),
274 preset: Schema.optional(
275 PreviewViewportPresetId.annotate({
276 description: "Named viewport from Chrome DevTools' standard device catalog.",
277 }),
278 ).annotate({
279 description: "Named device size. Required only when mode is preset.",
280 }),
281 width: Schema.optional(
282 PreviewViewportSize.fields.width.annotate({
283 description: "Freeform viewport width in CSS pixels. Required only in freeform mode.",
284 }),
285 ).annotate({
286 description: "Freeform viewport width in CSS pixels. Required only in freeform mode.",
287 }),
288 height: Schema.optional(
289 PreviewViewportSize.fields.height.annotate({
290 description: "Freeform viewport height in CSS pixels. Required only in freeform mode.",
291 }),
292 ).annotate({
293 description: "Freeform viewport height in CSS pixels. Required only in freeform mode.",
294 }),
295 orientation: Schema.optional(
296 Schema.Literals(["portrait", "landscape"]).annotate({
297 description:
298 "Orientation for a fixed device preset. Defaults to the preset's native orientation.",
299 }),
300 ).annotate({
301 description:
302 "Orientation for a named device preset. It is not accepted in fill or freeform mode.",
303 }),
304 timeoutMs: OptionalTimeoutMs,
305})
306 .check(
307 Schema.makeFilter((input) => {
308 const hasPreset = input.preset !== undefined;
309 const hasWidth = input.width !== undefined;
310 const hasHeight = input.height !== undefined;
311 if (hasWidth !== hasHeight) return "Custom dimensions require both width and height.";
312 if (input.mode === "fill") {
313 return !hasPreset && !hasWidth && input.orientation === undefined
314 ? true
315 : "Fill mode does not accept a preset, dimensions, or orientation.";
316 }
317 if (input.mode === "freeform") {
318 if (!hasWidth || !hasHeight || hasPreset || input.orientation !== undefined) {
319 return "Freeform mode requires width and height and does not accept a preset or orientation.";
320 }
321 } else if (!hasPreset || hasWidth || hasHeight) {
322 return "Preset mode requires a preset and does not accept custom dimensions.";
323 }
324 if (hasWidth && hasHeight && input.width! * input.height! > PREVIEW_VIEWPORT_MAX_AREA) {
325 return `Custom viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`;
326 }
327 return true;
328 }),
329 )
330 .annotate({
331 description:
332 "Sets the active browser tab to fill-panel, independently resizable freeform, or named device-preset sizing.",
333 });
334export type PreviewAutomationResizeInput = typeof PreviewAutomationResizeInput.Type;
335​
336export const PreviewAutomationResizeResult = Schema.Struct({
337 tabId: PreviewTabId,
338 setting: PreviewViewportSetting,
339 viewport: PreviewRenderedViewportSize,
340});
341export type PreviewAutomationResizeResult = typeof PreviewAutomationResizeResult.Type;
342​
343/** Mirrors DesktopPreviewColorScheme; declared here to keep this module free of ipc.ts imports. */
344export const PreviewAutomationColorScheme = Schema.Literals(["system", "light", "dark"]);
345export type PreviewAutomationColorScheme = typeof PreviewAutomationColorScheme.Type;
346​
347export const PreviewAutomationSetColorSchemeInput = Schema.Struct({
348 ...PreviewAutomationTabTargetFields,
349 colorScheme: PreviewAutomationColorScheme.annotate({
350 description:
351 "Emulated prefers-color-scheme for the page: light, dark, or system to follow the OS appearance.",
352 }),
353}).annotate({
354 description:
355 "Emulates prefers-color-scheme in the active browser tab without changing the OS or app theme.",
356});
357export type PreviewAutomationSetColorSchemeInput = typeof PreviewAutomationSetColorSchemeInput.Type;
358​
359export const PreviewAutomationSetColorSchemeResult = Schema.Struct({
360 tabId: PreviewTabId,
361 colorScheme: PreviewAutomationColorScheme,
362});
363export type PreviewAutomationSetColorSchemeResult =
364 typeof PreviewAutomationSetColorSchemeResult.Type;
365​
366const Locator = TrimmedNonEmptyString.annotate({
367 description:
368 "Use locator='aria-ref=<ref>' with a ref from the latest server snapshot (including iframe elements), or a unique Playwright role/text selector. Refs expire on navigation, a new snapshot, or control handoff; refresh the snapshot after a stale-ref error.",
369});
370​
371const LegacySelector = TrimmedNonEmptyString.annotate({
372 description:
373 "Legacy CSS selector such as button[type='submit']. Prefer locator for resilient role/text targeting.",
374});
375​
376const PointerTargetFields = {
377 ...PreviewAutomationTabTargetFields,
378 selector: Schema.optional(LegacySelector).annotate({
379 description:
380 "Legacy CSS selector such as button[type='submit']. Prefer locator for resilient role/text targeting.",
381 }),
382 locator: Schema.optional(Locator).annotate({
383 description:
384 "Use locator='aria-ref=<ref>' with a ref from the latest server snapshot (including iframe elements), or a unique Playwright role/text selector. Refs expire on navigation, a new snapshot, or control handoff; refresh the snapshot after a stale-ref error.",
385 }),
386 x: Schema.optional(
387 Schema.Finite.annotate({
388 description: "Viewport-relative X coordinate in CSS pixels. Must be paired with y.",
389 }),
390 ),
391 y: Schema.optional(
392 Schema.Finite.annotate({
393 description: "Viewport-relative Y coordinate in CSS pixels. Must be paired with x.",
394 }),
395 ),
396 timeoutMs: OptionalTimeoutMs,
397};
398​
399const singlePointerTarget = Schema.makeFilter(
400 (input: {
401 readonly selector?: string | undefined;
402 readonly locator?: string | undefined;
403 readonly x?: number | undefined;
404 readonly y?: number | undefined;
405 }) => {
406 const selectorModes =
407 Number(input.selector !== undefined) + Number(input.locator !== undefined);
408 const hasX = input.x !== undefined;
409 const hasY = input.y !== undefined;
410 if (hasX !== hasY) return "Coordinates require both x and y.";
411 const coordinateModes = hasX && hasY ? 1 : 0;
412 return selectorModes + coordinateModes === 1 || "Provide exactly one target.";
413 },
414);
415​
416export const PreviewAutomationClickInput = Schema.Struct({
417 ...PointerTargetFields,
418 button: Schema.optional(
419 Schema.Literals(["left", "right", "middle"]).annotate({
420 description: "Mouse button. Defaults to left; right opens the page's context menu.",
421 }),
422 ),
423 clickCount: Schema.optional(
424 Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 3 })).annotate({
425 description: "1 for a click, 2 for a double-click, 3 for a triple-click. Defaults to 1.",
426 }),
427 ),
428})
429 .check(singlePointerTarget)
430 .annotate({
431 description:
432 "Clicks one target. Provide exactly one of locator, selector, or the x/y coordinate pair.",
433 });
434export type PreviewAutomationClickInput = typeof PreviewAutomationClickInput.Type;
435​
436export const PreviewAutomationHoverInput = Schema.Struct(PointerTargetFields)
437 .check(singlePointerTarget)
438 .annotate({
439 description:
440 "Moves the mouse over one target. Provide exactly one of locator, selector, or the x/y coordinate pair.",
441 });
442export type PreviewAutomationHoverInput = typeof PreviewAutomationHoverInput.Type;
443​
444export const PreviewAutomationSelectInput = Schema.Struct({
445 ...PreviewAutomationTabTargetFields,
446 selector: Schema.optional(LegacySelector).annotate({
447 description: "Legacy CSS selector for a <select>. Prefer locator.",
448 }),
449 locator: Schema.optional(Locator).annotate({
450 description: "The <select> element, for example aria-ref=<ref> or role=combobox[name='Size'].",
451 }),
452 values: Schema.Array(Schema.String).check(Schema.isMaxLength(100)).annotate({
453 description:
454 "Option values or visible labels to select. Pass several for a multiple select, or an empty list to clear it.",
455 }),
456 timeoutMs: OptionalTimeoutMs,
457})
458 .check(
459 Schema.makeFilter(
460 (input) =>
461 Number(input.selector !== undefined) + Number(input.locator !== undefined) === 1 ||
462 "Provide exactly one of selector or locator.",
463 ),
464 )
465 .annotate({ description: "Chooses options in one native <select> element." });
466export type PreviewAutomationSelectInput = typeof PreviewAutomationSelectInput.Type;
467​
468export const PreviewAutomationSelectResult = Schema.Struct({
469 selected: Schema.Array(Schema.String).annotate({
470 description: "The values of the options now selected.",
471 }),
472});
473export type PreviewAutomationSelectResult = typeof PreviewAutomationSelectResult.Type;
474​
475/** Its JSON schema keeps only the description on its last check. */
476const DescribedLocator = (description: string) =>
477 Schema.String.check(Schema.isTrimmed())
478 .check(Schema.isNonEmpty({ description }))
479 .annotateKey({ description });
480​
481export const PreviewAutomationDragInput = Schema.Struct({
482 ...PreviewAutomationTabTargetFields,
483 source: DescribedLocator(
484 "Locator of the element to drag, for example aria-ref=<ref> from the latest snapshot.",
485 ),
486 target: DescribedLocator("Locator of the element to drop onto, for example aria-ref=<ref>."),
487 timeoutMs: OptionalTimeoutMs,
488}).annotate({ description: "Drags one element and drops it onto another." });
489export type PreviewAutomationDragInput = typeof PreviewAutomationDragInput.Type;
490​
491export const PreviewAutomationUploadInput = Schema.Struct({
492 ...PreviewAutomationTabTargetFields,
493 paths: Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(20)).annotate({
494 description:
495 "Absolute paths of files on the environment to give the page. An empty list cancels the open file picker.",
496 }),
497 selector: Schema.optional(LegacySelector).annotate({
498 description: "Legacy CSS selector for an <input type=file>. Prefer locator.",
499 }),
500 locator: Schema.optional(Locator).annotate({
501 description:
502 "Set files directly on this <input type=file> instead of answering the open file picker.",
503 }),
504 timeoutMs: OptionalTimeoutMs,
505})
506 .check(
507 Schema.makeFilter(
508 (input) =>
509 !(input.selector !== undefined && input.locator !== undefined) ||
510 "Provide at most one of selector or locator.",
511 ),
512 )
513 .annotate({
514 description:
515 "Answers the page's open file picker, or sets files on a file input when locator/selector is given.",
516 });
517export type PreviewAutomationUploadInput = typeof PreviewAutomationUploadInput.Type;
518​
519export const PreviewAutomationTypeInput = Schema.Struct({
520 ...PreviewAutomationTabTargetFields,
521 text: Schema.String.annotate({ description: "Literal text to insert." }),
522 selector: Schema.optional(LegacySelector).annotate({
523 description: "Legacy CSS selector for the input. Prefer locator.",
524 }),
525 locator: Schema.optional(Locator).annotate({
526 description:
527 "Playwright selector for the input, for example role=textbox[name='Message'] or textarea[placeholder*='Message'].",
528 }),
529 clear: Schema.optional(
530 Schema.Boolean.annotate({
531 description: "Clear the existing input value before inserting text. Defaults to false.",
532 }),
533 ),
534 timeoutMs: OptionalTimeoutMs,
535})
536 .check(
537 Schema.makeFilter(
538 (input) =>
539 !(input.selector !== undefined && input.locator !== undefined) ||
540 "Provide at most one of selector or locator.",
541 ),
542 )
543 .annotate({
544 description:
545 "Types into locator/selector, or into the currently focused element when neither target is provided.",
546 });
547export type PreviewAutomationTypeInput = typeof PreviewAutomationTypeInput.Type;
548​
549export const PreviewAutomationPressInput = Schema.Struct({
550 ...PreviewAutomationTabTargetFields,
551 key: Schema.String.check(Schema.isTrimmed())
552 .check(
553 Schema.isNonEmpty({
554 description:
555 "Keyboard key name such as Enter, Escape, Tab, ArrowDown, Backspace, or a single character.",
556 }),
557 )
558 .annotateKey({
559 description:
560 "Keyboard key name such as Enter, Escape, Tab, ArrowDown, Backspace, or a single character.",
561 }),
562 modifiers: Schema.optional(
563 Schema.Array(Schema.Literals(["Alt", "Control", "Meta", "Shift"])).annotate({
564 description: "Modifier keys held while pressing key.",
565 }),
566 ),
567}).annotate({ description: "Presses one keyboard key in the active browser tab." });
568export type PreviewAutomationPressInput = typeof PreviewAutomationPressInput.Type;
569​
570export const PreviewAutomationScrollInput = Schema.Struct({
571 ...PreviewAutomationTabTargetFields,
572 deltaX: Schema.optional(
573 Schema.Finite.annotate({
574 description: "Horizontal scroll delta in CSS pixels. Positive scrolls right. Defaults to 0.",
575 }),
576 ),
577 deltaY: Schema.optional(
578 Schema.Finite.annotate({
579 description: "Vertical scroll delta in CSS pixels. Positive scrolls down. Defaults to 0.",
580 }),
581 ),
582 selector: Schema.optional(LegacySelector).annotate({
583 description: "Legacy CSS selector for a scrollable container. Omit to scroll the viewport.",
584 }),
585 locator: Schema.optional(Locator).annotate({
586 description: "Playwright selector for a scrollable container. Omit to scroll the viewport.",
587 }),
588})
589 .check(
590 Schema.makeFilter((input) => {
591 if (input.selector !== undefined && input.locator !== undefined) {
592 return "Provide at most one of selector or locator.";
593 }
594 return (
595 input.deltaX !== undefined || input.deltaY !== undefined || "Provide deltaX or deltaY."
596 );
597 }),
598 )
599 .annotate({
600 description:
601 "Scrolls the viewport, or a locator/selector container. Provide deltaX, deltaY, or both.",
602 });
603export type PreviewAutomationScrollInput = typeof PreviewAutomationScrollInput.Type;
604​
605export const PreviewAutomationEvaluateInput = Schema.Struct({
606 ...PreviewAutomationTabTargetFields,
607 expression: Schema.String.check(Schema.isTrimmed())
608 .check(
609 Schema.isNonEmpty({
610 description:
611 "JavaScript expression evaluated in the page's main frame, for example document.title or (() => ({href: location.href}))().",
612 }),
613 )
614 .check(Schema.isMaxLength(64_000))
615 .annotateKey({
616 description:
617 "JavaScript expression evaluated in the page's main frame, for example document.title or (() => ({href: location.href}))().",
618 }),
619 awaitPromise: Schema.optional(
620 Schema.Boolean.annotate({ description: "Await a returned Promise. Defaults to true." }),
621 ),
622 returnByValue: Schema.optional(
623 Schema.Boolean.annotate({
624 description:
625 "Serialize and return the value instead of a remote object reference. Defaults to true.",
626 }),
627 ),
628}).annotate({
629 description:
630 "Evaluates JavaScript in the page. Prefer snapshot and semantic actions; use evaluate for inspection or unsupported interactions.",
631});
632export type PreviewAutomationEvaluateInput = typeof PreviewAutomationEvaluateInput.Type;
633​
634export const PreviewAutomationWaitForInput = Schema.Struct({
635 ...PreviewAutomationTabTargetFields,
636 selector: Schema.optional(LegacySelector).annotate({
637 description: "Legacy CSS selector that must match an element. Prefer locator.",
638 }),
639 locator: Schema.optional(Locator).annotate({
640 description:
641 "Playwright selector that must match an element, for example role=button[name='Send'].",
642 }),
643 text: Schema.optional(
644 TrimmedNonEmptyString.annotate({
645 description: "Case-sensitive substring that must appear in visible document text.",
646 }),
647 ).annotate({
648 description: "Case-sensitive substring that must appear in visible document text.",
649 }),
650 urlIncludes: Schema.optional(
651 TrimmedNonEmptyString.annotate({
652 description: "Substring that must appear in the current absolute URL.",
653 }),
654 ).annotate({ description: "Substring that must appear in the current absolute URL." }),
655 timeoutMs: OptionalTimeoutMs,
656})
657 .check(
658 Schema.makeFilter((input) => {
659 if (input.selector !== undefined && input.locator !== undefined) {
660 return "Provide at most one of selector or locator.";
661 }
662 return (
663 input.selector !== undefined ||
664 input.locator !== undefined ||
665 input.text !== undefined ||
666 input.urlIncludes !== undefined ||
667 "Provide at least one wait condition."
668 );
669 }),
670 )
671 .annotate({
672 description:
673 "Waits until all provided conditions match. Use after click/type when the page changes asynchronously.",
674 });
675export type PreviewAutomationWaitForInput = typeof PreviewAutomationWaitForInput.Type;
676​
677export const PreviewAutomationElement = Schema.Struct({
678 tag: Schema.String,
679 role: Schema.NullOr(Schema.String),
680 name: Schema.String,
681 selector: Schema.String,
682 x: Schema.Number,
683 y: Schema.Number,
684 width: Schema.Number,
685 height: Schema.Number,
686});
687export type PreviewAutomationElement = typeof PreviewAutomationElement.Type;
688​
689export const PreviewAutomationConsoleEntry = Schema.Struct({
690 level: Schema.String,
691 text: Schema.String,
692 timestamp: Schema.String,
693 source: Schema.optional(Schema.String),
694});
695export type PreviewAutomationConsoleEntry = typeof PreviewAutomationConsoleEntry.Type;
696​
697export const PreviewAutomationNetworkEntry = Schema.Struct({
698 url: Schema.String,
699 method: Schema.String,
700 status: Schema.NullOr(Schema.Number),
701 failed: Schema.Boolean,
702 errorText: Schema.optional(Schema.String),
703 timestamp: Schema.String,
704});
705export type PreviewAutomationNetworkEntry = typeof PreviewAutomationNetworkEntry.Type;
706​
707export const PreviewAutomationActionEvent = Schema.Struct({
708 id: Schema.String,
709 action: Schema.String,
710 status: Schema.Literals(["running", "succeeded", "failed", "interrupted"]),
711 startedAt: Schema.String,
712 completedAt: Schema.optional(Schema.String),
713 error: Schema.optional(Schema.String),
714});
715export type PreviewAutomationActionEvent = typeof PreviewAutomationActionEvent.Type;
716​
717export const PreviewAutomationSnapshot = Schema.Struct({
718 url: Schema.String,
719 title: Schema.String,
720 loading: Schema.Boolean,
721 visibleText: Schema.String,
722 interactiveElements: Schema.Array(PreviewAutomationElement),
723 accessibilityTree: Schema.Unknown,
724 consoleEntries: Schema.Array(PreviewAutomationConsoleEntry),
725 networkEntries: Schema.Array(PreviewAutomationNetworkEntry),
726 actionTimeline: Schema.Array(PreviewAutomationActionEvent),
727 screenshot: Schema.Struct({
728 mimeType: Schema.Literal("image/png"),
729 data: Schema.String,
730 width: Schema.Int,
731 height: Schema.Int,
732 }),
733});
734export type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type;
735​
736export const PreviewAutomationRecordingStatus = Schema.Struct({
737 tabId: PreviewTabId,
738 recording: Schema.Boolean,
739 startedAt: Schema.NullOr(Schema.String),
740});
741export type PreviewAutomationRecordingStatus = typeof PreviewAutomationRecordingStatus.Type;
742​
743export const PREVIEW_RECORDING_STOP_TIMEOUT_MS = 120_000;
744​
745export const PreviewAutomationRecordingArtifact = Schema.Struct({
746 id: Schema.String,
747 tabId: PreviewTabId,
748 path: Schema.String,
749 mimeType: Schema.String,
750 sizeBytes: Schema.Int,
751 createdAt: Schema.String,
752});
753export type PreviewAutomationRecordingArtifact = typeof PreviewAutomationRecordingArtifact.Type;
754​
755export const PreviewAutomationClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
756export type PreviewAutomationClientId = typeof PreviewAutomationClientId.Type;
757export const PreviewAutomationConnectionId = TrimmedNonEmptyString.check(Schema.isMaxLength(64));
758export type PreviewAutomationConnectionId = typeof PreviewAutomationConnectionId.Type;
759​
760export const PreviewAutomationHostIdentity = Schema.Struct({
761 clientId: PreviewAutomationClientId,
762 environmentId: EnvironmentId,
763});
764export type PreviewAutomationHostIdentity = typeof PreviewAutomationHostIdentity.Type;
765​
766export const PreviewAutomationHost = Schema.Struct({
767 ...PreviewAutomationHostIdentity.fields,
768 /**
769 * Missing means the pre-capability-negotiation V1 operation set.
770 */
771 supportedOperations: Schema.optional(Schema.Array(PreviewAutomationOperation)),
772});
773export type PreviewAutomationHost = typeof PreviewAutomationHost.Type;
774​
775export const PreviewAutomationHostFocus = Schema.Struct({
776 ...PreviewAutomationHostIdentity.fields,
777 connectionId: PreviewAutomationConnectionId,
778 focused: Schema.Boolean,
779 liveTabs: Schema.optional(
780 Schema.Array(
781 Schema.Struct({
782 threadId: ThreadId,
783 tabId: PreviewTabId,
784 visible: Schema.optional(Schema.Boolean),
785 }),
786 ),
787 ),
788});
789export type PreviewAutomationHostFocus = typeof PreviewAutomationHostFocus.Type;
790​
791export const PreviewAutomationRequest = Schema.Struct({
792 requestId: TrimmedNonEmptyString,
793 threadId: ThreadId,
794 tabId: Schema.optional(PreviewTabId),
795 tabIdExplicit: Schema.optional(Schema.Boolean),
796 /** Supplied by the broker from authenticated scope, never from tool input. */
797 agentSessionId: Schema.optional(Schema.String),
798 operation: PreviewAutomationOperation,
799 input: Schema.Unknown,
800 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
801});
802export type PreviewAutomationRequest = typeof PreviewAutomationRequest.Type;
803​
804export const PreviewAutomationStreamEvent = Schema.Union([
805 Schema.Struct({
806 type: Schema.Literal("connected"),
807 connectionId: PreviewAutomationConnectionId,
808 }),
809 Schema.Struct({
810 type: Schema.Literal("request"),
811 connectionId: PreviewAutomationConnectionId,
812 request: PreviewAutomationRequest,
813 }),
814]);
815export type PreviewAutomationStreamEvent = typeof PreviewAutomationStreamEvent.Type;
816​
817export const PreviewAutomationResponse = Schema.Struct({
818 clientId: PreviewAutomationClientId,
819 connectionId: PreviewAutomationConnectionId,
820 requestId: TrimmedNonEmptyString,
821 ok: Schema.Boolean,
822 result: Schema.optional(Schema.Unknown),
823 error: Schema.optional(
824 Schema.Struct({
825 _tag: TrimmedNonEmptyString,
826 message: Schema.String,
827 detail: Schema.optional(Schema.Unknown),
828 }),
829 ),
830});
831export type PreviewAutomationResponse = typeof PreviewAutomationResponse.Type;
832​
833const McpCapabilityErrorFields = {
834 environmentId: EnvironmentId,
835 threadId: Schema.optional(ThreadId),
836 providerSessionId: Schema.optional(TrimmedNonEmptyString),
837 providerInstanceId: Schema.optional(ProviderInstanceId),
838};
839​
840export class PreviewAutomationUnavailableError extends Schema.TaggedError<PreviewAutomationUnavailableError>()(
841 "PreviewAutomationUnavailableError",
842 {
843 capability: Schema.Literal("preview"),
844 ...McpCapabilityErrorFields,
845 },
846) {
847 override get message(): string {
848 return `MCP credential does not grant the ${this.capability} capability: browser preview tools are off for this thread. Do not retry them. To check a page, use a headless browser from the shell, such as Playwright, or curl. The user can turn on "Agent browser access" in Settings; it applies when the agent session next starts.`;
849 }
851​
852export class McpCapabilityUnavailableError extends Schema.TaggedError<McpCapabilityUnavailableError>()(
853 "McpCapabilityUnavailableError",
854 {
855 capability: TrimmedNonEmptyString,
856 ...McpCapabilityErrorFields,
857 },
858) {
859 override get message(): string {
860 return `MCP credential does not grant the ${this.capability} capability.`;
861 }
863​
864const PreviewAutomationScopeErrorFields = {
865 operation: PreviewAutomationOperation,
866 environmentId: EnvironmentId,
867 threadId: ThreadId,
868 providerSessionId: TrimmedNonEmptyString,
869 providerInstanceId: ProviderInstanceId,
870};
871​
872export const SERVER_BROWSER_AUTOMATION_CLIENT_ID = "server-browser";
873​
874const PreviewAutomationRequestErrorFields = {
875 ...PreviewAutomationScopeErrorFields,
876 clientId: TrimmedNonEmptyString,
877 connectionId: PreviewAutomationConnectionId,
878 requestId: TrimmedNonEmptyString,
879 tabId: Schema.optional(PreviewTabId),
880 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
881};
882​
883const PreviewAutomationRemoteDiagnosticFields = {
884 remoteTag: TrimmedNonEmptyString,
885 remoteMessageLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
886 remoteDetailKind: Schema.optional(
887 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
888 ),
889 cause: Schema.Defect(),
890};
891​
892const PreviewAutomationOptionalRemoteDiagnosticFields = {
893 remoteTag: Schema.optional(TrimmedNonEmptyString),
894 remoteMessageLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
895 remoteDetailKind: Schema.optional(
896 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
897 ),
898 cause: Schema.optional(Schema.Defect()),
899};
900​
901export class PreviewAutomationNoAvailableHostError extends Schema.TaggedError<PreviewAutomationNoAvailableHostError>()(
902 "PreviewAutomationNoAvailableHostError",
903 {
904 ...PreviewAutomationScopeErrorFields,
905 clientId: Schema.optional(TrimmedNonEmptyString),
906 connectionId: Schema.optional(PreviewAutomationConnectionId),
907 requestId: Schema.optional(TrimmedNonEmptyString),
908 tabId: Schema.optional(PreviewTabId),
909 timeoutMs: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
910 ...PreviewAutomationOptionalRemoteDiagnosticFields,
911 },
912) {
913 override get message(): string {
914 return `No preview automation host is available for ${this.operation} in environment ${this.environmentId}. The server-owned browser may be starting or reconnecting. Retry preview_status, then call preview_open if no tab is available. If it remains unavailable, report the browser connection failure.`;
915 }
917​
918export class PreviewAutomationUnsupportedClientError extends Schema.TaggedError<PreviewAutomationUnsupportedClientError>()(
919 "PreviewAutomationUnsupportedClientError",
920 {
921 ...PreviewAutomationRequestErrorFields,
922 ...PreviewAutomationRemoteDiagnosticFields,
923 },
924) {
925 override get message(): string {
926 return `Preview automation client ${this.clientId} does not support ${this.operation}.`;
927 }
929​
930export class PreviewAutomationTabNotFoundError extends Schema.TaggedError<PreviewAutomationTabNotFoundError>()(
931 "PreviewAutomationTabNotFoundError",
932 {
933 ...PreviewAutomationRequestErrorFields,
934 ...PreviewAutomationRemoteDiagnosticFields,
935 },
936) {
937 override get message(): string {
938 return this.tabId
939 ? `Preview tab ${this.tabId} was not found for ${this.operation}. Omit tabId to use the current tab, or call preview_open.`
940 : `No active preview tab was found for ${this.operation}. Call preview_open first.`;
941 }
943​
944export class PreviewAutomationTimeoutError extends Schema.TaggedError<PreviewAutomationTimeoutError>()(
945 "PreviewAutomationTimeoutError",
946 {
947 ...PreviewAutomationRequestErrorFields,
948 ...PreviewAutomationOptionalRemoteDiagnosticFields,
949 },
950) {
951 override get message(): string {
952 const summary = `Preview automation ${this.operation} timed out after ${this.timeoutMs}ms.`;
953 return summary;
954 }
956​
957export const PreviewAutomationControlReason = Schema.Literals([
958 "agentMismatch",
959 "humanControl",
960 "tabRequired",
961 "closed",
962 "interrupted",
963 "dialogPending",
964 "tabLimit",
965]);
966export type PreviewAutomationControlReason = typeof PreviewAutomationControlReason.Type;
967​
968export class PreviewAutomationControlInterruptedError extends Schema.TaggedError<PreviewAutomationControlInterruptedError>()(
969 "PreviewAutomationControlInterruptedError",
970 {
971 ...PreviewAutomationRequestErrorFields,
972 ...PreviewAutomationRemoteDiagnosticFields,
973 reason: Schema.optional(PreviewAutomationControlReason),
974 },
975) {
976 override get message(): string {
977 if (this.reason === "agentMismatch")
978 return "This browser tab belongs to another agent session or a human. Open your own tab.";
979 if (this.reason === "humanControl")
980 return "A human controls this browser tab. Wait until they release control.";
981 if (this.reason === "tabRequired")
982 return "Multiple browser tabs belong to this session. Pass a tabId from preview_open or from the tabs listed by preview_status.";
983 if (this.reason === "dialogPending")
984 return "A browser dialog is pending. Read preview_status and resolve it with preview_dialog.";
985 if (this.reason === "tabLimit")
986 return "Too many server browser tabs are open. Close one with t3_preview_close, or reuse a tabId from preview_status tabs.";
987 if (this.reason === "closed") return "This browser tab is closed. Call preview_open.";
988 if (this.reason === "interrupted")
989 return "Browser control changed. Take a fresh snapshot before trying again.";
990 return `Preview automation ${this.operation} was interrupted on client ${this.clientId}.`;
991 }
993​
994export class PreviewAutomationExecutionError extends Schema.TaggedError<PreviewAutomationExecutionError>()(
995 "PreviewAutomationExecutionError",
996 {
997 ...PreviewAutomationRequestErrorFields,
998 ...PreviewAutomationRemoteDiagnosticFields,
999 reason: Schema.optional(Schema.String),
1000 },
1001) {
1002 override get message(): string {
1003 return this.reason === undefined
1004 ? `Preview automation ${this.operation} failed on client ${this.clientId}.`
1005 : `Preview automation ${this.operation} failed: ${this.reason}`;
1008​
1009export class PreviewAutomationInvalidSelectorError extends Schema.TaggedError<PreviewAutomationInvalidSelectorError>()(
1010 "PreviewAutomationInvalidSelectorError",
1012 ...PreviewAutomationRequestErrorFields,
1013 ...PreviewAutomationRemoteDiagnosticFields,
1014 selectorKind: Schema.optional(Schema.Literals(["locator", "selector"])),
1015 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
1016 staleRef: Schema.optional(Schema.Boolean),
1017 },
1018) {
1019 override get message(): string {
1020 if (this.staleRef)
1021 return "This element ref is stale. Navigation, dialogs, and new snapshots replace refs; take a fresh snapshot and use its refs.";
1022 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
1023 return `Preview automation ${this.operation} received an invalid ${this.selectorKind} (${this.selectorLength} characters).`;
1025 return `Preview automation ${this.operation} received an invalid selector.`;
1028​
1029export class PreviewAutomationTargetNotEditableError extends Schema.TaggedError<PreviewAutomationTargetNotEditableError>()(
1030 "PreviewAutomationTargetNotEditableError",
1032 ...PreviewAutomationRequestErrorFields,
1033 ...PreviewAutomationRemoteDiagnosticFields,
1034 selectorKind: Schema.optional(Schema.Literals(["focused-element", "locator", "selector"])),
1035 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
1036 },
1037) {
1038 override get message(): string {
1039 if (this.selectorKind === "focused-element") {
1040 return `Preview automation ${this.operation} requires an editable focused element.`;
1042 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
1043 return `Preview automation ${this.operation} requires an editable ${this.selectorKind} (${this.selectorLength} characters).`;
1045 return `Preview automation ${this.operation} requires an editable target.`;
1048​
1049export class PreviewAutomationResultTooLargeError extends Schema.TaggedError<PreviewAutomationResultTooLargeError>()(
1050 "PreviewAutomationResultTooLargeError",
1052 ...PreviewAutomationRequestErrorFields,
1053 ...PreviewAutomationRemoteDiagnosticFields,
1054 maximumBytes: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
1055 },
1056) {
1057 override get message(): string {
1058 const summary =
1059 this.maximumBytes === undefined
1060 ? `Preview automation ${this.operation} produced a result that is too large.`
1061 : `Preview automation ${this.operation} produced a result larger than ${this.maximumBytes} bytes.`;
1062 return summary;
1065​
1066export class PreviewAutomationClientDisconnectedError extends Schema.TaggedError<PreviewAutomationClientDisconnectedError>()(
1067 "PreviewAutomationClientDisconnectedError",
1068 PreviewAutomationRequestErrorFields,
1069) {
1070 override get message(): string {
1071 return `Preview automation client ${this.clientId} disconnected during ${this.operation}.`;
1074​
1075export class PreviewAutomationRequestQueueClosedError extends Schema.TaggedError<PreviewAutomationRequestQueueClosedError>()(
1076 "PreviewAutomationRequestQueueClosedError",
1077 PreviewAutomationRequestErrorFields,
1078) {
1079 override get message(): string {
1080 return `Preview automation client ${this.clientId} stopped accepting ${this.operation} requests.`;
1083​
1084export class PreviewAutomationRemoteUnavailableError extends Schema.TaggedError<PreviewAutomationRemoteUnavailableError>()(
1085 "PreviewAutomationRemoteUnavailableError",
1087 ...PreviewAutomationRequestErrorFields,
1088 ...PreviewAutomationRemoteDiagnosticFields,
1089 },
1090) {
1091 override get message(): string {
1092 return `Preview automation ${this.operation} is unavailable on client ${this.clientId}.`;
1095​
1096export class PreviewAutomationMalformedResponseError extends Schema.TaggedError<PreviewAutomationMalformedResponseError>()(
1097 "PreviewAutomationMalformedResponseError",
1098 PreviewAutomationRequestErrorFields,
1099) {
1100 override get message(): string {
1101 return `Preview automation client ${this.clientId} returned a malformed response for ${this.operation}.`;
1104​
1105export class PreviewAutomationRecordingTransferError extends Schema.TaggedError<PreviewAutomationRecordingTransferError>()(
1106 "PreviewAutomationRecordingTransferError",
1108 threadId: ThreadId,
1109 cause: Schema.optional(Schema.Defect()),
1110 },
1111) {
1112 override get message(): string {
1113 return "Preview recording could not be saved to the agent environment.";
1116​
1117export class PreviewAutomationRecordingDesktopUpdateRequiredError extends Schema.TaggedError<PreviewAutomationRecordingDesktopUpdateRequiredError>()(
1118 "PreviewAutomationRecordingDesktopUpdateRequiredError",
1119 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
1120) {
1121 override get message(): string {
1122 return "Update the desktop app to transfer recordings. The recording remains on the desktop.";
1125​
1126export class PreviewAutomationRecordingTooLargeError extends Schema.TaggedError<PreviewAutomationRecordingTooLargeError>()(
1127 "PreviewAutomationRecordingTooLargeError",
1128 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
1129) {
1130 override get message(): string {
1131 return "The recording exceeds 50 MiB. Make a shorter recording.";
1134​
1135export class PreviewAutomationRecordingDeadlineExpiredError extends Schema.TaggedError<PreviewAutomationRecordingDeadlineExpiredError>()(
1136 "PreviewAutomationRecordingDeadlineExpiredError",
1137 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
1138) {
1139 override get message(): string {
1140 return "The recording transfer deadline expired.";
1143​
1144export const PreviewAutomationError = Schema.Union([
1145 PreviewAutomationRecordingTransferError,
1146 PreviewAutomationRecordingDesktopUpdateRequiredError,
1147 PreviewAutomationRecordingTooLargeError,
1148 PreviewAutomationRecordingDeadlineExpiredError,
1149 PreviewAutomationUnavailableError,
1150 PreviewAutomationNoAvailableHostError,
1151 PreviewAutomationUnsupportedClientError,
1152 PreviewAutomationTabNotFoundError,
1153 PreviewAutomationTimeoutError,
1154 PreviewAutomationControlInterruptedError,
1155 PreviewAutomationExecutionError,
1156 PreviewAutomationInvalidSelectorError,
1157 PreviewAutomationTargetNotEditableError,
1158 PreviewAutomationResultTooLargeError,
1159 PreviewAutomationClientDisconnectedError,
1160 PreviewAutomationRequestQueueClosedError,
1161 PreviewAutomationRemoteUnavailableError,
1162 PreviewAutomationMalformedResponseError,
1163]);
1164export type PreviewAutomationError = typeof PreviewAutomationError.Type;
1165​
1166export const PreviewUrlResolution = Schema.Struct({
1167 requestedUrl: Schema.String,
1168 resolvedUrl: Schema.String,
1169 resolutionKind: Schema.Literals(["direct", "direct-private-network"]),
1170 environmentId: EnvironmentId,
1171});
1172export type PreviewUrlResolution = typeof PreviewUrlResolution.Type;