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