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

previewAutomation.ts

1,032 lines38.3 KB

1import { Schema } from "effect";
2​
3import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
4import {
5 PREVIEW_VIEWPORT_MAX_AREA,
6 PreviewRenderedViewportSize,
7 PreviewTabId,
8 PreviewViewportPresetId,
9 PreviewViewportSetting,
10 PreviewViewportSize,
11} from "./preview.ts";
12import { ProviderInstanceId } from "./providerInstance.ts";
13import { BrowserProfileId } from "./browserProfile.ts";
14​
15const BoundedUrl = Schema.String.check(Schema.isTrimmed())
16 .check(Schema.isNonEmpty())
17 .check(Schema.isMaxLength(2048));
18const URL_GUIDANCE = "Absolute http(s) URL, or a bare host (https; http for loopback).";
19const PROFILE_GUIDANCE =
20 "Profile id or name from preview_status, for a new tab. Default: the user's. A tab keeps its profile.";
21const OptionalTimeoutMs = Schema.optional(
22 Schema.Int.check(Schema.isGreaterThan(0)).check(Schema.isLessThanOrEqualTo(60_000)),
23).annotate({ description: "Default 15000." });
24​
25export const PREVIEW_AUTOMATION_V1_OPERATIONS = [
26 "status",
27 "open",
28 "navigate",
29 "snapshot",
30 "click",
31 "type",
32 "press",
33 "scroll",
34 "evaluate",
35 "waitFor",
36 "recordingStart",
37 "recordingStop",
38] as const;
39​
40const PREVIEW_AUTOMATION_OPERATIONS = [
41 ...PREVIEW_AUTOMATION_V1_OPERATIONS,
42 "resize",
43 "setColorScheme",
44] as const;
45​
46export const PREVIEW_AUTOMATION_SERVER_OPERATIONS = [
47 ...PREVIEW_AUTOMATION_OPERATIONS,
48 "dialog",
49 "close",
50 "upload",
51 "hover",
52 "select",
53 "drag",
54] as const;
55export const PreviewAutomationOperation = Schema.Literals(PREVIEW_AUTOMATION_SERVER_OPERATIONS);
56export type PreviewAutomationOperation = typeof PreviewAutomationOperation.Type;
57​
58const PreviewAutomationTabTargetFields = {
59 tabId: Schema.optional(PreviewTabId),
60};
61​
62export const PreviewAutomationTabTargetInput = Schema.Struct(PreviewAutomationTabTargetFields);
63export type PreviewAutomationTabTargetInput = typeof PreviewAutomationTabTargetInput.Type;
64​
65export const PreviewAutomationTabOwner = Schema.Literals(["agent", "human", "unclaimed"]);
66​
67export const PreviewAutomationProfile = Schema.Struct({
68 id: BrowserProfileId,
69 name: Schema.String,
70 incognito: Schema.optional(Schema.Boolean),
71});
72export type PreviewAutomationProfile = typeof PreviewAutomationProfile.Type;
73​
74const VISIBLE_DESCRIPTION =
75 "True while a client shows this tab: a streamed live view, or the desktop app's own browser panel.";
76​
77/** Why the tab shows the browser's error page instead of the page it tried to load. */
78export const PreviewAutomationLoadError = Schema.Struct({
79 url: Schema.String,
80 code: Schema.Int,
81 description: Schema.String,
82});
83export type PreviewAutomationLoadError = typeof PreviewAutomationLoadError.Type;
84​
85export const PreviewAutomationStatus = Schema.Struct({
86 available: Schema.Boolean,
87 visible: Schema.Boolean.annotate({ description: VISIBLE_DESCRIPTION }),
88 tabId: Schema.NullOr(PreviewTabId),
89 url: Schema.NullOr(Schema.String),
90 title: Schema.NullOr(Schema.String),
91 loading: Schema.Boolean,
92 loadError: Schema.optional(PreviewAutomationLoadError),
93 control: Schema.optional(
94 Schema.Struct({
95 owner: PreviewAutomationTabOwner,
96 ownedByCaller: Schema.Boolean,
97 generation: Schema.Number,
98 }),
99 ),
100 dialog: Schema.optional(
101 Schema.NullOr(
102 Schema.Struct({
103 type: Schema.String,
104 message: Schema.String,
105 defaultValue: Schema.String,
106 }),
107 ),
108 ),
109 viewportSetting: Schema.optional(PreviewViewportSetting),
110 viewport: Schema.optional(PreviewRenderedViewportSize),
111 fileChooser: Schema.optional(
112 Schema.NullOr(Schema.Struct({ multiple: Schema.Boolean, accept: Schema.String })),
113 ),
114 downloads: Schema.optional(
115 Schema.Array(
116 Schema.Struct({
117 fileName: Schema.String,
118 path: Schema.String,
119 sizeBytes: Schema.Number,
120 url: Schema.String,
121 completedAt: Schema.String,
122 }),
123 ),
124 ),
125 /** Server hosts: all thread tabs are readable; actions require ownedByCaller or an unclaimed tab without human control. */
126 tabs: Schema.optional(
127 Schema.Array(
128 Schema.Struct({
129 tabId: PreviewTabId,
130 url: Schema.NullOr(Schema.String),
131 openerTabId: Schema.optional(PreviewTabId),
132 owner: Schema.optional(PreviewAutomationTabOwner),
133 ownedByCaller: Schema.optional(Schema.Boolean),
134 visible: Schema.optional(Schema.Boolean.annotate({ description: VISIBLE_DESCRIPTION })),
135 profileId: Schema.optional(BrowserProfileId),
136 }),
137 ),
138 ),
139 profiles: Schema.optional(Schema.Array(PreviewAutomationProfile)),
140 defaultProfileId: Schema.optional(BrowserProfileId),
141});
142export type PreviewAutomationStatus = typeof PreviewAutomationStatus.Type;
143​
144export const PreviewAutomationDialogInput = Schema.Struct({
145 ...PreviewAutomationTabTargetFields,
146 accept: Schema.Boolean,
147 promptText: Schema.optional(Schema.String),
148});
149export type PreviewAutomationDialogInput = typeof PreviewAutomationDialogInput.Type;
150​
151export const PreviewAutomationOpenInput = Schema.Struct({
152 ...PreviewAutomationTabTargetFields,
153 url: Schema.optional(BoundedUrl).annotate({
154 description: `First page URL. ${URL_GUIDANCE} Omit to open a blank tab.`,
155 }),
156 open: Schema.optional(
157 Schema.Boolean.annotate({
158 description: "Show the preview to the user. Default true. False for background only.",
159 }),
160 ),
161 show: Schema.optional(
162 Schema.Boolean.annotate({
163 description: "Old alias for `open`.",
164 }),
165 ),
166 reuseExistingTab: Schema.optional(
167 Schema.Boolean.annotate({
168 description: "Reuse `tabId`, or your current tab. Default true. False makes a new tab.",
169 }),
170 ),
171 profileId: Schema.optional(TrimmedNonEmptyString.check(Schema.isMaxLength(64))).annotate({
172 description: PROFILE_GUIDANCE,
173 }),
174}).check(
175 Schema.makeFilter(
176 (input) =>
177 !(input.tabId !== undefined && input.reuseExistingTab === false) ||
178 "tabId cannot be combined with reuseExistingTab=false.",
179 ),
180);
181export type PreviewAutomationOpenInput = typeof PreviewAutomationOpenInput.Type;
182​
183export const BrowserNavigationTarget = Schema.Union([
184 Schema.Struct({
185 kind: Schema.Literal("url"),
186 url: BoundedUrl.annotate({
187 description: `Website URL. ${URL_GUIDANCE}`,
188 }),
189 }),
190 Schema.Struct({
191 kind: Schema.Literal("environment-port"),
192 port: Schema.Int.check(Schema.isGreaterThan(0))
193 .check(Schema.isLessThan(65_536))
194 .annotate({ description: "Dev-server port here." }),
195 protocol: Schema.optional(
196 Schema.Literals(["http", "https"]).annotate({
197 description: "Default http.",
198 }),
199 ),
200 path: Schema.optional(
201 Schema.String.annotate({
202 description: "Path, query, and fragment, such as /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} For public pages.`,
213 }),
214 target: Schema.optional(BrowserNavigationTarget),
215 readiness: Schema.optional(Schema.Literals(["load", "domContentLoaded", "none"])).annotate({
216 description: "Default 'load'. 'none': return at once.",
217 }),
218 timeoutMs: OptionalTimeoutMs,
219}).check(
220 Schema.makeFilter(
221 (input) =>
222 Number(input.url !== undefined) + Number(input.target !== undefined) === 1 ||
223 "Provide exactly one of url or target.",
224 ),
225);
226export type PreviewAutomationNavigateInput = typeof PreviewAutomationNavigateInput.Type;
227​
228export const PreviewAutomationResizeInput = Schema.Struct({
229 ...PreviewAutomationTabTargetFields,
230 mode: Schema.Literals(["fill", "freeform", "preset"]),
231 preset: Schema.optional(PreviewViewportPresetId),
232 width: Schema.optional(PreviewViewportSize.fields.width),
233 height: Schema.optional(PreviewViewportSize.fields.height),
234 orientation: Schema.optional(Schema.Literals(["portrait", "landscape"])),
235 timeoutMs: OptionalTimeoutMs,
236}).check(
237 Schema.makeFilter((input) => {
238 const hasPreset = input.preset !== undefined;
239 const hasWidth = input.width !== undefined;
240 const hasHeight = input.height !== undefined;
241 if (hasWidth !== hasHeight) return "Custom dimensions require both width and height.";
242 if (input.mode === "fill") {
243 return !hasPreset && !hasWidth && input.orientation === undefined
244 ? true
245 : "Fill mode does not accept a preset, dimensions, or orientation.";
246 }
247 if (input.mode === "freeform") {
248 if (!hasWidth || !hasHeight || hasPreset || input.orientation !== undefined) {
249 return "Freeform mode requires width and height and does not accept a preset or orientation.";
250 }
251 } else if (!hasPreset || hasWidth || hasHeight) {
252 return "Preset mode requires a preset and does not accept custom dimensions.";
253 }
254 if (hasWidth && hasHeight && input.width! * input.height! > PREVIEW_VIEWPORT_MAX_AREA) {
255 return `Custom viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`;
256 }
257 return true;
258 }),
259);
260export type PreviewAutomationResizeInput = typeof PreviewAutomationResizeInput.Type;
261​
262export const PreviewAutomationResizeResult = Schema.Struct({
263 tabId: PreviewTabId,
264 setting: PreviewViewportSetting,
265 viewport: Schema.optional(PreviewRenderedViewportSize).annotate({
266 description: "Viewport size after the resize. Omitted when it could not be measured.",
267 }),
268});
269export type PreviewAutomationResizeResult = typeof PreviewAutomationResizeResult.Type;
270​
271// Mirrors DesktopPreviewColorScheme without importing ipc.ts.
272export const PreviewAutomationColorScheme = Schema.Literals(["system", "light", "dark"]);
273export type PreviewAutomationColorScheme = typeof PreviewAutomationColorScheme.Type;
274​
275export const PreviewAutomationSetColorSchemeInput = Schema.Struct({
276 ...PreviewAutomationTabTargetFields,
277 colorScheme: PreviewAutomationColorScheme,
278});
279export type PreviewAutomationSetColorSchemeInput = typeof PreviewAutomationSetColorSchemeInput.Type;
280​
281export const PreviewAutomationSetColorSchemeResult = Schema.Struct({
282 tabId: PreviewTabId,
283 colorScheme: PreviewAutomationColorScheme,
284});
285export type PreviewAutomationSetColorSchemeResult =
286 typeof PreviewAutomationSetColorSchemeResult.Type;
287​
288const Locator = TrimmedNonEmptyString;
289const LegacySelector = TrimmedNonEmptyString;
290​
291const PointerTargetFields = {
292 ...PreviewAutomationTabTargetFields,
293 selector: Schema.optional(LegacySelector),
294 locator: Schema.optional(Locator),
295 x: Schema.optional(Schema.Finite),
296 y: Schema.optional(Schema.Finite),
297 timeoutMs: OptionalTimeoutMs,
298};
299​
300const singlePointerTarget = Schema.makeFilter(
301 (input: {
302 readonly selector?: string | undefined;
303 readonly locator?: string | undefined;
304 readonly x?: number | undefined;
305 readonly y?: number | undefined;
306 }) => {
307 const selectorModes =
308 Number(input.selector !== undefined) + Number(input.locator !== undefined);
309 const hasX = input.x !== undefined;
310 const hasY = input.y !== undefined;
311 if (hasX !== hasY) return "Coordinates require both x and y.";
312 const coordinateModes = hasX && hasY ? 1 : 0;
313 return selectorModes + coordinateModes === 1 || "Provide exactly one target.";
314 },
315);
316​
317export const PreviewAutomationClickInput = Schema.Struct({
318 ...PointerTargetFields,
319 button: Schema.optional(
320 Schema.Literals(["left", "right", "middle"]).annotate({
321 description: "Button. Default left. Right opens the menu.",
322 }),
323 ),
324 clickCount: Schema.optional(
325 Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 3 })).annotate({
326 description: "1 click, 2 double, 3 triple. Default 1.",
327 }),
328 ),
329}).check(singlePointerTarget);
330export type PreviewAutomationClickInput = typeof PreviewAutomationClickInput.Type;
331​
332export const PreviewAutomationHoverInput =
333 Schema.Struct(PointerTargetFields).check(singlePointerTarget);
334export type PreviewAutomationHoverInput = typeof PreviewAutomationHoverInput.Type;
335​
336export const PreviewAutomationSelectInput = Schema.Struct({
337 ...PreviewAutomationTabTargetFields,
338 selector: Schema.optional(LegacySelector),
339 locator: Schema.optional(Locator),
340 values: Schema.Array(Schema.String).check(Schema.isMaxLength(100)).annotate({
341 description: "Empty clears it.",
342 }),
343 timeoutMs: OptionalTimeoutMs,
344}).check(
345 Schema.makeFilter(
346 (input) =>
347 Number(input.selector !== undefined) + Number(input.locator !== undefined) === 1 ||
348 "Provide exactly one of selector or locator.",
349 ),
350);
351export type PreviewAutomationSelectInput = typeof PreviewAutomationSelectInput.Type;
352​
353export const PreviewAutomationSelectResult = Schema.Struct({
354 selected: Schema.Array(Schema.String).annotate({
355 description: "The values of the options now selected.",
356 }),
357});
358export type PreviewAutomationSelectResult = typeof PreviewAutomationSelectResult.Type;
359​
360export const PreviewAutomationDragInput = Schema.Struct({
361 ...PreviewAutomationTabTargetFields,
362 source: Locator,
363 target: Locator,
364 timeoutMs: OptionalTimeoutMs,
365});
366export type PreviewAutomationDragInput = typeof PreviewAutomationDragInput.Type;
367​
368export const PreviewAutomationUploadInput = Schema.Struct({
369 ...PreviewAutomationTabTargetFields,
370 paths: Schema.Array(TrimmedNonEmptyString).check(Schema.isMaxLength(20)),
371 selector: Schema.optional(LegacySelector),
372 locator: Schema.optional(Locator).annotate({
373 description: "Set files on this <input type=file> instead of the open picker.",
374 }),
375 timeoutMs: OptionalTimeoutMs,
376}).check(
377 Schema.makeFilter(
378 (input) =>
379 !(input.selector !== undefined && input.locator !== undefined) ||
380 "Provide at most one of selector or locator.",
381 ),
382);
383export type PreviewAutomationUploadInput = typeof PreviewAutomationUploadInput.Type;
384​
385export const PreviewAutomationTypeInput = Schema.Struct({
386 ...PreviewAutomationTabTargetFields,
387 text: Schema.String,
388 selector: Schema.optional(LegacySelector),
389 locator: Schema.optional(Locator),
390 clear: Schema.optional(
391 Schema.Boolean.annotate({
392 description: "Clear the input first. Default false.",
393 }),
394 ),
395 timeoutMs: OptionalTimeoutMs,
396}).check(
397 Schema.makeFilter(
398 (input) =>
399 !(input.selector !== undefined && input.locator !== undefined) ||
400 "Provide at most one of selector or locator.",
401 ),
402);
403export type PreviewAutomationTypeInput = typeof PreviewAutomationTypeInput.Type;
404​
405export const PreviewAutomationPressInput = Schema.Struct({
406 ...PreviewAutomationTabTargetFields,
407 key: Schema.String.check(Schema.isTrimmed()).check(Schema.isNonEmpty()),
408 modifiers: Schema.optional(Schema.Array(Schema.Literals(["Alt", "Control", "Meta", "Shift"]))),
409});
410export type PreviewAutomationPressInput = typeof PreviewAutomationPressInput.Type;
411​
412export const PreviewAutomationScrollInput = Schema.Struct({
413 ...PreviewAutomationTabTargetFields,
414 deltaX: Schema.optional(Schema.Finite),
415 deltaY: Schema.optional(Schema.Finite),
416 selector: Schema.optional(LegacySelector),
417 locator: Schema.optional(Locator),
418}).check(
419 Schema.makeFilter((input) => {
420 if (input.selector !== undefined && input.locator !== undefined) {
421 return "Provide at most one of selector or locator.";
422 }
423 return input.deltaX !== undefined || input.deltaY !== undefined || "Provide deltaX or deltaY.";
424 }),
425);
426export type PreviewAutomationScrollInput = typeof PreviewAutomationScrollInput.Type;
427​
428/** Strict input for each `preview_act` action. */
429export const PreviewAutomationActInputs = {
430 click: PreviewAutomationClickInput,
431 type: PreviewAutomationTypeInput,
432 hover: PreviewAutomationHoverInput,
433 select: PreviewAutomationSelectInput,
434 drag: PreviewAutomationDragInput,
435 upload: PreviewAutomationUploadInput,
436 press: PreviewAutomationPressInput,
437 scroll: PreviewAutomationScrollInput,
438} as const;
439export type PreviewAutomationAction = keyof typeof PreviewAutomationActInputs;
440​
441/** One flat shape for every page action. The server decodes it with the action's strict input. */
442export const PreviewAutomationActInput = Schema.Struct({
443 action: Schema.Literals([
444 "click",
445 "type",
446 "hover",
447 "select",
448 "drag",
449 "upload",
450 "press",
451 "scroll",
452 ]),
453 ...PreviewAutomationTabTargetFields,
454 locator: Schema.optional(Locator),
455 selector: Schema.optional(LegacySelector),
456 x: Schema.optional(Schema.Finite),
457 y: Schema.optional(Schema.Finite),
458 button: Schema.optional(Schema.Literals(["left", "right", "middle"])),
459 clickCount: Schema.optional(Schema.Int),
460 text: Schema.optional(Schema.String),
461 clear: Schema.optional(Schema.Boolean),
462 values: Schema.optional(Schema.Array(Schema.String)),
463 source: Schema.optional(Locator),
464 target: Schema.optional(Locator),
465 paths: Schema.optional(Schema.Array(Schema.String)),
466 key: Schema.optional(Schema.String),
467 modifiers: PreviewAutomationPressInput.fields.modifiers,
468 deltaX: Schema.optional(Schema.Finite),
469 deltaY: Schema.optional(Schema.Finite),
470 timeoutMs: Schema.optional(Schema.Int),
471});
472export type PreviewAutomationActInput = typeof PreviewAutomationActInput.Type;
473​
474export const PreviewAutomationEvaluateInput = Schema.Struct({
475 ...PreviewAutomationTabTargetFields,
476 expression: Schema.String.check(Schema.isTrimmed())
477 .check(Schema.isNonEmpty())
478 .check(Schema.isMaxLength(64_000)),
479 awaitPromise: Schema.optional(Schema.Boolean.annotate({ description: "Default true." })),
480});
481export type PreviewAutomationEvaluateInput = typeof PreviewAutomationEvaluateInput.Type;
482​
483export const PreviewAutomationWaitForInput = Schema.Struct({
484 ...PreviewAutomationTabTargetFields,
485 selector: Schema.optional(LegacySelector),
486 locator: Schema.optional(Locator),
487 text: Schema.optional(TrimmedNonEmptyString).annotate({
488 description: "Case counts.",
489 }),
490 urlIncludes: Schema.optional(TrimmedNonEmptyString),
491 timeoutMs: OptionalTimeoutMs,
492}).check(
493 Schema.makeFilter((input) => {
494 if (input.selector !== undefined && input.locator !== undefined) {
495 return "Provide at most one of selector or locator.";
496 }
497 return (
498 input.selector !== undefined ||
499 input.locator !== undefined ||
500 input.text !== undefined ||
501 input.urlIncludes !== undefined ||
502 "Provide at least one wait condition."
503 );
504 }),
505);
506export type PreviewAutomationWaitForInput = typeof PreviewAutomationWaitForInput.Type;
507​
508export const PreviewAutomationConsoleEntry = Schema.Struct({
509 level: Schema.String,
510 text: Schema.String,
511 timestamp: Schema.String,
512 source: Schema.optional(Schema.String),
513});
514export type PreviewAutomationConsoleEntry = typeof PreviewAutomationConsoleEntry.Type;
515​
516export const PreviewAutomationNetworkEntry = Schema.Struct({
517 url: Schema.String,
518 method: Schema.String,
519 status: Schema.NullOr(Schema.Number),
520 failed: Schema.Boolean,
521 errorText: Schema.optional(Schema.String),
522 timestamp: Schema.String,
523});
524export type PreviewAutomationNetworkEntry = typeof PreviewAutomationNetworkEntry.Type;
525​
526export const PreviewAutomationActionEvent = Schema.Struct({
527 id: Schema.String,
528 action: Schema.String,
529 status: Schema.Literals(["running", "succeeded", "failed", "interrupted"]),
530 startedAt: Schema.String,
531 completedAt: Schema.optional(Schema.String),
532 error: Schema.optional(Schema.String),
533});
534export type PreviewAutomationActionEvent = typeof PreviewAutomationActionEvent.Type;
535​
536export const PreviewAutomationSnapshot = Schema.Struct({
537 url: Schema.String,
538 title: Schema.String,
539 loading: Schema.Boolean,
540 loadError: Schema.optional(PreviewAutomationLoadError),
541 visibleText: Schema.String,
542 accessibilityTree: Schema.Unknown,
543 consoleEntries: Schema.Array(PreviewAutomationConsoleEntry),
544 networkEntries: Schema.Array(PreviewAutomationNetworkEntry),
545 actionTimeline: Schema.Array(PreviewAutomationActionEvent),
546 screenshot: Schema.Struct({
547 mimeType: Schema.Literal("image/png"),
548 data: Schema.String,
549 width: Schema.Int,
550 height: Schema.Int,
551 }),
552 /** The capture before `screenshot` was capped for the agent, when requested and larger. */
553 fullScreenshot: Schema.optional(
554 Schema.Struct({ data: Schema.String, width: Schema.Int, height: Schema.Int }),
555 ),
556});
557export type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type;
558​
559// pixelsRequired is false when the caller discards the screenshot; hosts that ignore it still return a PNG.
560export const PreviewAutomationSnapshotInput = Schema.Struct({
561 fullScreenshot: Schema.optional(Schema.Boolean),
562 pixelsRequired: Schema.optional(Schema.Boolean),
563});
564export type PreviewAutomationSnapshotInput = typeof PreviewAutomationSnapshotInput.Type;
565​
566export const PreviewAutomationSnapshotMetadata = Schema.Struct({
567 ...PreviewAutomationSnapshot.fields,
568 screenshot: Schema.Struct({ width: Schema.Int, height: Schema.Int }),
569});
570export type PreviewAutomationSnapshotMetadata = typeof PreviewAutomationSnapshotMetadata.Type;
571​
572export const PreviewAutomationRecordingStatus = Schema.Struct({
573 tabId: PreviewTabId,
574 recording: Schema.Boolean,
575 startedAt: Schema.NullOr(Schema.String),
576});
577export type PreviewAutomationRecordingStatus = typeof PreviewAutomationRecordingStatus.Type;
578​
579export const PREVIEW_RECORDING_STOP_TIMEOUT_MS = 120_000;
580​
581export const PreviewAutomationRecordingArtifact = Schema.Struct({
582 id: Schema.String,
583 tabId: PreviewTabId,
584 path: Schema.String,
585 mimeType: Schema.String,
586 sizeBytes: Schema.Int,
587 createdAt: Schema.String,
588});
589export type PreviewAutomationRecordingArtifact = typeof PreviewAutomationRecordingArtifact.Type;
590​
591export const PreviewAutomationClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
592export type PreviewAutomationClientId = typeof PreviewAutomationClientId.Type;
593export const PreviewAutomationConnectionId = TrimmedNonEmptyString.check(Schema.isMaxLength(64));
594export type PreviewAutomationConnectionId = typeof PreviewAutomationConnectionId.Type;
595​
596export const PreviewAutomationHostIdentity = Schema.Struct({
597 clientId: PreviewAutomationClientId,
598 environmentId: EnvironmentId,
599});
600export type PreviewAutomationHostIdentity = typeof PreviewAutomationHostIdentity.Type;
601​
602export const PreviewAutomationHost = Schema.Struct({
603 ...PreviewAutomationHostIdentity.fields,
604 /** Missing means the V1 operation set from before capability negotiation. */
605 supportedOperations: Schema.optional(Schema.Array(PreviewAutomationOperation)),
606});
607export type PreviewAutomationHost = typeof PreviewAutomationHost.Type;
608​
609export const PreviewAutomationHostFocus = Schema.Struct({
610 ...PreviewAutomationHostIdentity.fields,
611 connectionId: PreviewAutomationConnectionId,
612 focused: Schema.Boolean,
613 liveTabs: Schema.optional(
614 Schema.Array(
615 Schema.Struct({
616 threadId: ThreadId,
617 tabId: PreviewTabId,
618 visible: Schema.optional(Schema.Boolean),
619 }),
620 ),
621 ),
622});
623export type PreviewAutomationHostFocus = typeof PreviewAutomationHostFocus.Type;
624​
625export const PreviewAutomationRequest = Schema.Struct({
626 requestId: TrimmedNonEmptyString,
627 threadId: ThreadId,
628 tabId: Schema.optional(PreviewTabId),
629 tabIdExplicit: Schema.optional(Schema.Boolean),
630 /** Supplied by the broker from authenticated scope, never from tool input. */
631 agentSessionId: Schema.optional(Schema.String),
632 operation: PreviewAutomationOperation,
633 input: Schema.Unknown,
634 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
635});
636export type PreviewAutomationRequest = typeof PreviewAutomationRequest.Type;
637​
638export const PreviewAutomationStreamEvent = Schema.Union([
639 Schema.Struct({
640 type: Schema.Literal("connected"),
641 connectionId: PreviewAutomationConnectionId,
642 }),
643 Schema.Struct({
644 type: Schema.Literal("request"),
645 connectionId: PreviewAutomationConnectionId,
646 request: PreviewAutomationRequest,
647 }),
648]);
649export type PreviewAutomationStreamEvent = typeof PreviewAutomationStreamEvent.Type;
650​
651export const PreviewAutomationResponse = Schema.Struct({
652 clientId: PreviewAutomationClientId,
653 connectionId: PreviewAutomationConnectionId,
654 requestId: TrimmedNonEmptyString,
655 ok: Schema.Boolean,
656 result: Schema.optional(Schema.Unknown),
657 error: Schema.optional(
658 Schema.Struct({
659 _tag: TrimmedNonEmptyString,
660 message: Schema.String,
661 detail: Schema.optional(Schema.Unknown),
662 }),
663 ),
664});
665export type PreviewAutomationResponse = typeof PreviewAutomationResponse.Type;
666​
667const McpCapabilityErrorFields = {
668 environmentId: EnvironmentId,
669 threadId: Schema.optional(ThreadId),
670 providerSessionId: Schema.optional(TrimmedNonEmptyString),
671 providerInstanceId: Schema.optional(ProviderInstanceId),
672};
673​
674export class PreviewAutomationUnavailableError extends Schema.TaggedError<PreviewAutomationUnavailableError>()(
675 "PreviewAutomationUnavailableError",
676 {
677 capability: Schema.Literal("preview"),
678 ...McpCapabilityErrorFields,
679 },
680) {
681 override get message(): string {
682 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.`;
683 }
685​
686export class McpCapabilityUnavailableError extends Schema.TaggedError<McpCapabilityUnavailableError>()(
687 "McpCapabilityUnavailableError",
688 {
689 capability: TrimmedNonEmptyString,
690 ...McpCapabilityErrorFields,
691 },
692) {
693 override get message(): string {
694 return `MCP credential does not grant the ${this.capability} capability.`;
695 }
697​
698const PreviewAutomationScopeErrorFields = {
699 operation: PreviewAutomationOperation,
700 environmentId: EnvironmentId,
701 threadId: ThreadId,
702 providerSessionId: TrimmedNonEmptyString,
703 providerInstanceId: ProviderInstanceId,
704};
705​
706export const SERVER_BROWSER_AUTOMATION_CLIENT_ID = "server-browser";
707​
708const PreviewAutomationRequestErrorFields = {
709 ...PreviewAutomationScopeErrorFields,
710 clientId: TrimmedNonEmptyString,
711 connectionId: PreviewAutomationConnectionId,
712 requestId: TrimmedNonEmptyString,
713 tabId: Schema.optional(PreviewTabId),
714 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
715};
716​
717const PreviewAutomationRemoteDiagnosticFields = {
718 remoteTag: TrimmedNonEmptyString,
719 remoteMessageLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
720 remoteDetailKind: Schema.optional(
721 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
722 ),
723 cause: Schema.Defect(),
724};
725​
726const PreviewAutomationOptionalRemoteDiagnosticFields = {
727 remoteTag: Schema.optional(TrimmedNonEmptyString),
728 remoteMessageLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
729 remoteDetailKind: Schema.optional(
730 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
731 ),
732 cause: Schema.optional(Schema.Defect()),
733};
734​
735export class PreviewAutomationNoAvailableHostError extends Schema.TaggedError<PreviewAutomationNoAvailableHostError>()(
736 "PreviewAutomationNoAvailableHostError",
737 {
738 ...PreviewAutomationScopeErrorFields,
739 clientId: Schema.optional(TrimmedNonEmptyString),
740 connectionId: Schema.optional(PreviewAutomationConnectionId),
741 requestId: Schema.optional(TrimmedNonEmptyString),
742 tabId: Schema.optional(PreviewTabId),
743 timeoutMs: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
744 ...PreviewAutomationOptionalRemoteDiagnosticFields,
745 },
746) {
747 override get message(): string {
748 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.`;
749 }
751​
752export class PreviewAutomationUnsupportedClientError extends Schema.TaggedError<PreviewAutomationUnsupportedClientError>()(
753 "PreviewAutomationUnsupportedClientError",
754 {
755 ...PreviewAutomationRequestErrorFields,
756 ...PreviewAutomationRemoteDiagnosticFields,
757 },
758) {
759 override get message(): string {
760 return `Preview automation client ${this.clientId} does not support ${this.operation}.`;
761 }
763​
764export class PreviewAutomationTabNotFoundError extends Schema.TaggedError<PreviewAutomationTabNotFoundError>()(
765 "PreviewAutomationTabNotFoundError",
766 {
767 ...PreviewAutomationRequestErrorFields,
768 ...PreviewAutomationRemoteDiagnosticFields,
769 },
770) {
771 override get message(): string {
772 return this.tabId
773 ? `Preview tab ${this.tabId} was not found for ${this.operation}. Omit tabId to use the current tab, or call preview_open.`
774 : `No active preview tab was found for ${this.operation}. Call preview_open first.`;
775 }
777​
778export const PreviewAutomationSnapshotStage = Schema.Literals([
779 "metrics",
780 "frames",
781 "page state",
782 "screenshot",
783 "accessibility tree",
784]);
785​
786export const PreviewAutomationTimeoutDetail = Schema.Struct({
787 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
788 pendingStages: Schema.Array(PreviewAutomationSnapshotStage).check(Schema.isMaxLength(5)),
789});
790​
791export class PreviewAutomationTimeoutError extends Schema.TaggedError<PreviewAutomationTimeoutError>()(
792 "PreviewAutomationTimeoutError",
793 {
794 ...PreviewAutomationRequestErrorFields,
795 ...PreviewAutomationOptionalRemoteDiagnosticFields,
796 pendingStages: Schema.optional(PreviewAutomationTimeoutDetail.fields.pendingStages),
797 reason: Schema.optional(Schema.String),
798 },
799) {
800 override get message(): string {
801 const summary = `Preview automation ${this.operation} timed out after ${this.timeoutMs}ms.`;
802 const stages = this.pendingStages?.length
803 ? ` Waiting for: ${this.pendingStages.join(", ")}.`
804 : "";
805 const reason = this.reason === undefined ? "" : ` ${this.reason}`;
806 return `${summary}${stages}${reason}`;
807 }
809​
810export const PreviewAutomationControlReason = Schema.Literals([
811 "agentMismatch",
812 "unclaimedTab",
813 "humanControl",
814 "tabRequired",
815 "closed",
816 "interrupted",
817 "dialogPending",
818 "tabLimit",
819]);
820export type PreviewAutomationControlReason = typeof PreviewAutomationControlReason.Type;
821​
822export class PreviewAutomationControlInterruptedError extends Schema.TaggedError<PreviewAutomationControlInterruptedError>()(
823 "PreviewAutomationControlInterruptedError",
824 {
825 ...PreviewAutomationRequestErrorFields,
826 ...PreviewAutomationRemoteDiagnosticFields,
827 reason: Schema.optional(PreviewAutomationControlReason),
828 },
829) {
830 override get message(): string {
831 if (this.reason === "agentMismatch")
832 return "This browser tab belongs to another agent session or a human. Open your own tab.";
833 if (this.reason === "unclaimedTab")
834 return "This tab has no agent owner. Ask the user to close it in the browser panel.";
835 if (this.reason === "humanControl")
836 return "A human controls this browser tab. Wait until they release control.";
837 if (this.reason === "tabRequired")
838 return "Multiple browser tabs belong to this session. Pass a tabId from preview_open or from the tabs listed by preview_status.";
839 if (this.reason === "dialogPending")
840 return "A browser dialog is pending. Read preview_status and resolve it with preview_dialog.";
841 if (this.reason === "tabLimit")
842 return "Too many server browser tabs are open. Close one with t3_preview_close, or reuse a tabId from preview_status tabs.";
843 if (this.reason === "closed") return "This browser tab is closed. Call preview_open.";
844 if (this.reason === "interrupted")
845 return "Browser control changed. Take a fresh snapshot before trying again.";
846 return `Preview automation ${this.operation} was interrupted on client ${this.clientId}.`;
847 }
849​
850export class PreviewAutomationExecutionError extends Schema.TaggedError<PreviewAutomationExecutionError>()(
851 "PreviewAutomationExecutionError",
852 {
853 ...PreviewAutomationRequestErrorFields,
854 ...PreviewAutomationRemoteDiagnosticFields,
855 reason: Schema.optional(Schema.String),
856 },
857) {
858 override get message(): string {
859 return this.reason === undefined
860 ? `Preview automation ${this.operation} failed on client ${this.clientId}.`
861 : `Preview automation ${this.operation} failed: ${this.reason}`;
862 }
864​
865export class PreviewAutomationInvalidSelectorError extends Schema.TaggedError<PreviewAutomationInvalidSelectorError>()(
866 "PreviewAutomationInvalidSelectorError",
867 {
868 ...PreviewAutomationRequestErrorFields,
869 ...PreviewAutomationRemoteDiagnosticFields,
870 selectorKind: Schema.optional(Schema.Literals(["locator", "selector"])),
871 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
872 staleRef: Schema.optional(Schema.Boolean),
873 },
874) {
875 override get message(): string {
876 if (this.staleRef)
877 return "This element ref is stale. Navigation, dialogs, and new snapshots replace refs; take a fresh snapshot and use its refs.";
878 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
879 const guidance =
880 this.selectorKind === "locator"
881 ? "Use aria-ref=<ref> from the latest snapshot or a Playwright role/text selector; put CSS in selector."
882 : "selector takes CSS; use locator for aria-ref=<ref>, role, or text targets.";
883 return `Preview automation ${this.operation} received an invalid ${this.selectorKind} (${this.selectorLength} characters). ${guidance}`;
884 }
885 return `Preview automation ${this.operation} received an invalid selector.`;
886 }
888​
889export class PreviewAutomationTargetNotEditableError extends Schema.TaggedError<PreviewAutomationTargetNotEditableError>()(
890 "PreviewAutomationTargetNotEditableError",
891 {
892 ...PreviewAutomationRequestErrorFields,
893 ...PreviewAutomationRemoteDiagnosticFields,
894 selectorKind: Schema.optional(Schema.Literals(["focused-element", "locator", "selector"])),
895 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
896 },
897) {
898 override get message(): string {
899 if (this.selectorKind === "focused-element") {
900 return `Preview automation ${this.operation} requires an editable focused element.`;
901 }
902 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
903 return `Preview automation ${this.operation} requires an editable ${this.selectorKind} (${this.selectorLength} characters).`;
904 }
905 return `Preview automation ${this.operation} requires an editable target.`;
906 }
908​
909export class PreviewAutomationResultTooLargeError extends Schema.TaggedError<PreviewAutomationResultTooLargeError>()(
910 "PreviewAutomationResultTooLargeError",
911 {
912 ...PreviewAutomationRequestErrorFields,
913 ...PreviewAutomationRemoteDiagnosticFields,
914 maximumBytes: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
915 },
916) {
917 override get message(): string {
918 const summary =
919 this.maximumBytes === undefined
920 ? `Preview automation ${this.operation} produced a result that is too large.`
921 : `Preview automation ${this.operation} produced a result larger than ${this.maximumBytes} bytes.`;
922 return summary;
923 }
925​
926export class PreviewAutomationClientDisconnectedError extends Schema.TaggedError<PreviewAutomationClientDisconnectedError>()(
927 "PreviewAutomationClientDisconnectedError",
928 PreviewAutomationRequestErrorFields,
929) {
930 override get message(): string {
931 return `Preview automation client ${this.clientId} disconnected during ${this.operation}.`;
932 }
934​
935export class PreviewAutomationRequestQueueClosedError extends Schema.TaggedError<PreviewAutomationRequestQueueClosedError>()(
936 "PreviewAutomationRequestQueueClosedError",
937 PreviewAutomationRequestErrorFields,
938) {
939 override get message(): string {
940 return `Preview automation client ${this.clientId} stopped accepting ${this.operation} requests.`;
941 }
943​
944export class PreviewAutomationRemoteUnavailableError extends Schema.TaggedError<PreviewAutomationRemoteUnavailableError>()(
945 "PreviewAutomationRemoteUnavailableError",
946 {
947 ...PreviewAutomationRequestErrorFields,
948 ...PreviewAutomationRemoteDiagnosticFields,
949 },
950) {
951 override get message(): string {
952 return `Preview automation ${this.operation} is unavailable on client ${this.clientId}.`;
953 }
955​
956export class PreviewAutomationMalformedResponseError extends Schema.TaggedError<PreviewAutomationMalformedResponseError>()(
957 "PreviewAutomationMalformedResponseError",
958 PreviewAutomationRequestErrorFields,
959) {
960 override get message(): string {
961 return `Preview automation client ${this.clientId} returned a malformed response for ${this.operation}.`;
962 }
964​
965export class PreviewAutomationRecordingTransferError extends Schema.TaggedError<PreviewAutomationRecordingTransferError>()(
966 "PreviewAutomationRecordingTransferError",
967 {
968 threadId: ThreadId,
969 cause: Schema.optional(Schema.Defect()),
970 },
971) {
972 override get message(): string {
973 return "Preview recording could not be saved to the agent environment.";
974 }
976​
977export class PreviewAutomationRecordingDesktopUpdateRequiredError extends Schema.TaggedError<PreviewAutomationRecordingDesktopUpdateRequiredError>()(
978 "PreviewAutomationRecordingDesktopUpdateRequiredError",
979 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
980) {
981 override get message(): string {
982 return "Update the desktop app to transfer recordings. The recording remains on the desktop.";
983 }
985​
986export class PreviewAutomationRecordingTooLargeError extends Schema.TaggedError<PreviewAutomationRecordingTooLargeError>()(
987 "PreviewAutomationRecordingTooLargeError",
988 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
989) {
990 override get message(): string {
991 return "The recording exceeds 50 MiB. Make a shorter recording.";
992 }
994​
995export class PreviewAutomationRecordingDeadlineExpiredError extends Schema.TaggedError<PreviewAutomationRecordingDeadlineExpiredError>()(
996 "PreviewAutomationRecordingDeadlineExpiredError",
997 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
998) {
999 override get message(): string {
1000 return "The recording transfer deadline expired.";
1003​
1004export const PreviewAutomationError = Schema.Union([
1005 PreviewAutomationRecordingTransferError,
1006 PreviewAutomationRecordingDesktopUpdateRequiredError,
1007 PreviewAutomationRecordingTooLargeError,
1008 PreviewAutomationRecordingDeadlineExpiredError,
1009 PreviewAutomationUnavailableError,
1010 PreviewAutomationNoAvailableHostError,
1011 PreviewAutomationUnsupportedClientError,
1012 PreviewAutomationTabNotFoundError,
1013 PreviewAutomationTimeoutError,
1014 PreviewAutomationControlInterruptedError,
1015 PreviewAutomationExecutionError,
1016 PreviewAutomationInvalidSelectorError,
1017 PreviewAutomationTargetNotEditableError,
1018 PreviewAutomationResultTooLargeError,
1019 PreviewAutomationClientDisconnectedError,
1020 PreviewAutomationRequestQueueClosedError,
1021 PreviewAutomationRemoteUnavailableError,
1022 PreviewAutomationMalformedResponseError,
1023]);
1024export type PreviewAutomationError = typeof PreviewAutomationError.Type;
1025​
1026export const PreviewUrlResolution = Schema.Struct({
1027 requestedUrl: Schema.String,
1028 resolvedUrl: Schema.String,
1029 resolutionKind: Schema.Literals(["direct", "direct-private-network"]),
1030 environmentId: EnvironmentId,
1031});
1032export type PreviewUrlResolution = typeof PreviewUrlResolution.Type;