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

previewAutomation.ts

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