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

previewAutomation.ts

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