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

previewAutomation.ts

1,006 lines36.9 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 returnByValue: Schema.optional(
467 Schema.Boolean.annotate({
468 description: "False returns a ref. Default true.",
469 }),
470 ),
471});
472export type PreviewAutomationEvaluateInput = typeof PreviewAutomationEvaluateInput.Type;
473​
474export const PreviewAutomationWaitForInput = Schema.Struct({
475 ...PreviewAutomationTabTargetFields,
476 selector: Schema.optional(LegacySelector),
477 locator: Schema.optional(Locator),
478 text: Schema.optional(TrimmedNonEmptyString).annotate({
479 description: "Case counts.",
480 }),
481 urlIncludes: Schema.optional(TrimmedNonEmptyString),
482 timeoutMs: OptionalTimeoutMs,
483}).check(
484 Schema.makeFilter((input) => {
485 if (input.selector !== undefined && input.locator !== undefined) {
486 return "Provide at most one of selector or locator.";
487 }
488 return (
489 input.selector !== undefined ||
490 input.locator !== undefined ||
491 input.text !== undefined ||
492 input.urlIncludes !== undefined ||
493 "Provide at least one wait condition."
494 );
495 }),
496);
497export type PreviewAutomationWaitForInput = typeof PreviewAutomationWaitForInput.Type;
498​
499export const PreviewAutomationElement = Schema.Struct({
500 tag: Schema.String,
501 role: Schema.NullOr(Schema.String),
502 name: Schema.String,
503 selector: Schema.String,
504 x: Schema.Number,
505 y: Schema.Number,
506 width: Schema.Number,
507 height: Schema.Number,
508});
509export type PreviewAutomationElement = typeof PreviewAutomationElement.Type;
510​
511export const PreviewAutomationConsoleEntry = Schema.Struct({
512 level: Schema.String,
513 text: Schema.String,
514 timestamp: Schema.String,
515 source: Schema.optional(Schema.String),
516});
517export type PreviewAutomationConsoleEntry = typeof PreviewAutomationConsoleEntry.Type;
518​
519export const PreviewAutomationNetworkEntry = Schema.Struct({
520 url: Schema.String,
521 method: Schema.String,
522 status: Schema.NullOr(Schema.Number),
523 failed: Schema.Boolean,
524 errorText: Schema.optional(Schema.String),
525 timestamp: Schema.String,
526});
527export type PreviewAutomationNetworkEntry = typeof PreviewAutomationNetworkEntry.Type;
528​
529export const PreviewAutomationActionEvent = Schema.Struct({
530 id: Schema.String,
531 action: Schema.String,
532 status: Schema.Literals(["running", "succeeded", "failed", "interrupted"]),
533 startedAt: Schema.String,
534 completedAt: Schema.optional(Schema.String),
535 error: Schema.optional(Schema.String),
536});
537export type PreviewAutomationActionEvent = typeof PreviewAutomationActionEvent.Type;
538​
539export const PreviewAutomationSnapshot = Schema.Struct({
540 url: Schema.String,
541 title: Schema.String,
542 loading: Schema.Boolean,
543 visibleText: Schema.String,
544 interactiveElements: Schema.Array(PreviewAutomationElement),
545 accessibilityTree: Schema.Unknown,
546 consoleEntries: Schema.Array(PreviewAutomationConsoleEntry),
547 networkEntries: Schema.Array(PreviewAutomationNetworkEntry),
548 actionTimeline: Schema.Array(PreviewAutomationActionEvent),
549 screenshot: Schema.Struct({
550 mimeType: Schema.Literal("image/png"),
551 data: Schema.String,
552 width: Schema.Int,
553 height: Schema.Int,
554 }),
555 /** The capture before `screenshot` was capped for the agent, when requested and larger. */
556 fullScreenshot: Schema.optional(
557 Schema.Struct({ data: Schema.String, width: Schema.Int, height: Schema.Int }),
558 ),
559});
560export type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type;
561​
562export const PreviewAutomationSnapshotInput = Schema.Struct({
563 fullScreenshot: Schema.optional(Schema.Boolean),
564});
565export type PreviewAutomationSnapshotInput = typeof PreviewAutomationSnapshotInput.Type;
566​
567export const PreviewAutomationRecordingStatus = Schema.Struct({
568 tabId: PreviewTabId,
569 recording: Schema.Boolean,
570 startedAt: Schema.NullOr(Schema.String),
571});
572export type PreviewAutomationRecordingStatus = typeof PreviewAutomationRecordingStatus.Type;
573​
574export const PREVIEW_RECORDING_STOP_TIMEOUT_MS = 120_000;
575​
576export const PreviewAutomationRecordingArtifact = Schema.Struct({
577 id: Schema.String,
578 tabId: PreviewTabId,
579 path: Schema.String,
580 mimeType: Schema.String,
581 sizeBytes: Schema.Int,
582 createdAt: Schema.String,
583});
584export type PreviewAutomationRecordingArtifact = typeof PreviewAutomationRecordingArtifact.Type;
585​
586export const PreviewAutomationClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
587export type PreviewAutomationClientId = typeof PreviewAutomationClientId.Type;
588export const PreviewAutomationConnectionId = TrimmedNonEmptyString.check(Schema.isMaxLength(64));
589export type PreviewAutomationConnectionId = typeof PreviewAutomationConnectionId.Type;
590​
591export const PreviewAutomationHostIdentity = Schema.Struct({
592 clientId: PreviewAutomationClientId,
593 environmentId: EnvironmentId,
594});
595export type PreviewAutomationHostIdentity = typeof PreviewAutomationHostIdentity.Type;
596​
597export const PreviewAutomationHost = Schema.Struct({
598 ...PreviewAutomationHostIdentity.fields,
599 /** Missing means the V1 operation set from before capability negotiation. */
600 supportedOperations: Schema.optional(Schema.Array(PreviewAutomationOperation)),
601});
602export type PreviewAutomationHost = typeof PreviewAutomationHost.Type;
603​
604export const PreviewAutomationHostFocus = Schema.Struct({
605 ...PreviewAutomationHostIdentity.fields,
606 connectionId: PreviewAutomationConnectionId,
607 focused: Schema.Boolean,
608 liveTabs: Schema.optional(
609 Schema.Array(
610 Schema.Struct({
611 threadId: ThreadId,
612 tabId: PreviewTabId,
613 visible: Schema.optional(Schema.Boolean),
614 }),
615 ),
616 ),
617});
618export type PreviewAutomationHostFocus = typeof PreviewAutomationHostFocus.Type;
619​
620export const PreviewAutomationRequest = Schema.Struct({
621 requestId: TrimmedNonEmptyString,
622 threadId: ThreadId,
623 tabId: Schema.optional(PreviewTabId),
624 tabIdExplicit: Schema.optional(Schema.Boolean),
625 /** Supplied by the broker from authenticated scope, never from tool input. */
626 agentSessionId: Schema.optional(Schema.String),
627 operation: PreviewAutomationOperation,
628 input: Schema.Unknown,
629 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
630});
631export type PreviewAutomationRequest = typeof PreviewAutomationRequest.Type;
632​
633export const PreviewAutomationStreamEvent = Schema.Union([
634 Schema.Struct({
635 type: Schema.Literal("connected"),
636 connectionId: PreviewAutomationConnectionId,
637 }),
638 Schema.Struct({
639 type: Schema.Literal("request"),
640 connectionId: PreviewAutomationConnectionId,
641 request: PreviewAutomationRequest,
642 }),
643]);
644export type PreviewAutomationStreamEvent = typeof PreviewAutomationStreamEvent.Type;
645​
646export const PreviewAutomationResponse = Schema.Struct({
647 clientId: PreviewAutomationClientId,
648 connectionId: PreviewAutomationConnectionId,
649 requestId: TrimmedNonEmptyString,
650 ok: Schema.Boolean,
651 result: Schema.optional(Schema.Unknown),
652 error: Schema.optional(
653 Schema.Struct({
654 _tag: TrimmedNonEmptyString,
655 message: Schema.String,
656 detail: Schema.optional(Schema.Unknown),
657 }),
658 ),
659});
660export type PreviewAutomationResponse = typeof PreviewAutomationResponse.Type;
661​
662const McpCapabilityErrorFields = {
663 environmentId: EnvironmentId,
664 threadId: Schema.optional(ThreadId),
665 providerSessionId: Schema.optional(TrimmedNonEmptyString),
666 providerInstanceId: Schema.optional(ProviderInstanceId),
667};
668​
669export class PreviewAutomationUnavailableError extends Schema.TaggedError<PreviewAutomationUnavailableError>()(
670 "PreviewAutomationUnavailableError",
671 {
672 capability: Schema.Literal("preview"),
673 ...McpCapabilityErrorFields,
674 },
675) {
676 override get message(): string {
677 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.`;
678 }
680​
681export class McpCapabilityUnavailableError extends Schema.TaggedError<McpCapabilityUnavailableError>()(
682 "McpCapabilityUnavailableError",
683 {
684 capability: TrimmedNonEmptyString,
685 ...McpCapabilityErrorFields,
686 },
687) {
688 override get message(): string {
689 return `MCP credential does not grant the ${this.capability} capability.`;
690 }
692​
693const PreviewAutomationScopeErrorFields = {
694 operation: PreviewAutomationOperation,
695 environmentId: EnvironmentId,
696 threadId: ThreadId,
697 providerSessionId: TrimmedNonEmptyString,
698 providerInstanceId: ProviderInstanceId,
699};
700​
701export const SERVER_BROWSER_AUTOMATION_CLIENT_ID = "server-browser";
702​
703const PreviewAutomationRequestErrorFields = {
704 ...PreviewAutomationScopeErrorFields,
705 clientId: TrimmedNonEmptyString,
706 connectionId: PreviewAutomationConnectionId,
707 requestId: TrimmedNonEmptyString,
708 tabId: Schema.optional(PreviewTabId),
709 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
710};
711​
712const PreviewAutomationRemoteDiagnosticFields = {
713 remoteTag: TrimmedNonEmptyString,
714 remoteMessageLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
715 remoteDetailKind: Schema.optional(
716 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
717 ),
718 cause: Schema.Defect(),
719};
720​
721const PreviewAutomationOptionalRemoteDiagnosticFields = {
722 remoteTag: Schema.optional(TrimmedNonEmptyString),
723 remoteMessageLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
724 remoteDetailKind: Schema.optional(
725 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
726 ),
727 cause: Schema.optional(Schema.Defect()),
728};
729​
730export class PreviewAutomationNoAvailableHostError extends Schema.TaggedError<PreviewAutomationNoAvailableHostError>()(
731 "PreviewAutomationNoAvailableHostError",
732 {
733 ...PreviewAutomationScopeErrorFields,
734 clientId: Schema.optional(TrimmedNonEmptyString),
735 connectionId: Schema.optional(PreviewAutomationConnectionId),
736 requestId: Schema.optional(TrimmedNonEmptyString),
737 tabId: Schema.optional(PreviewTabId),
738 timeoutMs: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
739 ...PreviewAutomationOptionalRemoteDiagnosticFields,
740 },
741) {
742 override get message(): string {
743 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.`;
744 }
746​
747export class PreviewAutomationUnsupportedClientError extends Schema.TaggedError<PreviewAutomationUnsupportedClientError>()(
748 "PreviewAutomationUnsupportedClientError",
749 {
750 ...PreviewAutomationRequestErrorFields,
751 ...PreviewAutomationRemoteDiagnosticFields,
752 },
753) {
754 override get message(): string {
755 return `Preview automation client ${this.clientId} does not support ${this.operation}.`;
756 }
758​
759export class PreviewAutomationTabNotFoundError extends Schema.TaggedError<PreviewAutomationTabNotFoundError>()(
760 "PreviewAutomationTabNotFoundError",
761 {
762 ...PreviewAutomationRequestErrorFields,
763 ...PreviewAutomationRemoteDiagnosticFields,
764 },
765) {
766 override get message(): string {
767 return this.tabId
768 ? `Preview tab ${this.tabId} was not found for ${this.operation}. Omit tabId to use the current tab, or call preview_open.`
769 : `No active preview tab was found for ${this.operation}. Call preview_open first.`;
770 }
772​
773export class PreviewAutomationTimeoutError extends Schema.TaggedError<PreviewAutomationTimeoutError>()(
774 "PreviewAutomationTimeoutError",
775 {
776 ...PreviewAutomationRequestErrorFields,
777 ...PreviewAutomationOptionalRemoteDiagnosticFields,
778 reason: Schema.optional(Schema.String),
779 },
780) {
781 override get message(): string {
782 const summary = `Preview automation ${this.operation} timed out after ${this.timeoutMs}ms.`;
783 return this.reason === undefined ? summary : `${summary} ${this.reason}`;
784 }
786​
787export const PreviewAutomationControlReason = Schema.Literals([
788 "agentMismatch",
789 "humanControl",
790 "tabRequired",
791 "closed",
792 "interrupted",
793 "dialogPending",
794 "tabLimit",
795]);
796export type PreviewAutomationControlReason = typeof PreviewAutomationControlReason.Type;
797​
798export class PreviewAutomationControlInterruptedError extends Schema.TaggedError<PreviewAutomationControlInterruptedError>()(
799 "PreviewAutomationControlInterruptedError",
800 {
801 ...PreviewAutomationRequestErrorFields,
802 ...PreviewAutomationRemoteDiagnosticFields,
803 reason: Schema.optional(PreviewAutomationControlReason),
804 },
805) {
806 override get message(): string {
807 if (this.reason === "agentMismatch")
808 return "This browser tab belongs to another agent session or a human. Open your own tab.";
809 if (this.reason === "humanControl")
810 return "A human controls this browser tab. Wait until they release control.";
811 if (this.reason === "tabRequired")
812 return "Multiple browser tabs belong to this session. Pass a tabId from preview_open or from the tabs listed by preview_status.";
813 if (this.reason === "dialogPending")
814 return "A browser dialog is pending. Read preview_status and resolve it with preview_dialog.";
815 if (this.reason === "tabLimit")
816 return "Too many server browser tabs are open. Close one with t3_preview_close, or reuse a tabId from preview_status tabs.";
817 if (this.reason === "closed") return "This browser tab is closed. Call preview_open.";
818 if (this.reason === "interrupted")
819 return "Browser control changed. Take a fresh snapshot before trying again.";
820 return `Preview automation ${this.operation} was interrupted on client ${this.clientId}.`;
821 }
823​
824export class PreviewAutomationExecutionError extends Schema.TaggedError<PreviewAutomationExecutionError>()(
825 "PreviewAutomationExecutionError",
826 {
827 ...PreviewAutomationRequestErrorFields,
828 ...PreviewAutomationRemoteDiagnosticFields,
829 reason: Schema.optional(Schema.String),
830 },
831) {
832 override get message(): string {
833 return this.reason === undefined
834 ? `Preview automation ${this.operation} failed on client ${this.clientId}.`
835 : `Preview automation ${this.operation} failed: ${this.reason}`;
836 }
838​
839export class PreviewAutomationInvalidSelectorError extends Schema.TaggedError<PreviewAutomationInvalidSelectorError>()(
840 "PreviewAutomationInvalidSelectorError",
841 {
842 ...PreviewAutomationRequestErrorFields,
843 ...PreviewAutomationRemoteDiagnosticFields,
844 selectorKind: Schema.optional(Schema.Literals(["locator", "selector"])),
845 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
846 staleRef: Schema.optional(Schema.Boolean),
847 },
848) {
849 override get message(): string {
850 if (this.staleRef)
851 return "This element ref is stale. Navigation, dialogs, and new snapshots replace refs; take a fresh snapshot and use its refs.";
852 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
853 const guidance =
854 this.selectorKind === "locator"
855 ? "Use aria-ref=<ref> from the latest snapshot or a Playwright role/text selector; put CSS in selector."
856 : "selector takes CSS; use locator for aria-ref=<ref>, role, or text targets.";
857 return `Preview automation ${this.operation} received an invalid ${this.selectorKind} (${this.selectorLength} characters). ${guidance}`;
858 }
859 return `Preview automation ${this.operation} received an invalid selector.`;
860 }
862​
863export class PreviewAutomationTargetNotEditableError extends Schema.TaggedError<PreviewAutomationTargetNotEditableError>()(
864 "PreviewAutomationTargetNotEditableError",
865 {
866 ...PreviewAutomationRequestErrorFields,
867 ...PreviewAutomationRemoteDiagnosticFields,
868 selectorKind: Schema.optional(Schema.Literals(["focused-element", "locator", "selector"])),
869 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
870 },
871) {
872 override get message(): string {
873 if (this.selectorKind === "focused-element") {
874 return `Preview automation ${this.operation} requires an editable focused element.`;
875 }
876 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
877 return `Preview automation ${this.operation} requires an editable ${this.selectorKind} (${this.selectorLength} characters).`;
878 }
879 return `Preview automation ${this.operation} requires an editable target.`;
880 }
882​
883export class PreviewAutomationResultTooLargeError extends Schema.TaggedError<PreviewAutomationResultTooLargeError>()(
884 "PreviewAutomationResultTooLargeError",
885 {
886 ...PreviewAutomationRequestErrorFields,
887 ...PreviewAutomationRemoteDiagnosticFields,
888 maximumBytes: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
889 },
890) {
891 override get message(): string {
892 const summary =
893 this.maximumBytes === undefined
894 ? `Preview automation ${this.operation} produced a result that is too large.`
895 : `Preview automation ${this.operation} produced a result larger than ${this.maximumBytes} bytes.`;
896 return summary;
897 }
899​
900export class PreviewAutomationClientDisconnectedError extends Schema.TaggedError<PreviewAutomationClientDisconnectedError>()(
901 "PreviewAutomationClientDisconnectedError",
902 PreviewAutomationRequestErrorFields,
903) {
904 override get message(): string {
905 return `Preview automation client ${this.clientId} disconnected during ${this.operation}.`;
906 }
908​
909export class PreviewAutomationRequestQueueClosedError extends Schema.TaggedError<PreviewAutomationRequestQueueClosedError>()(
910 "PreviewAutomationRequestQueueClosedError",
911 PreviewAutomationRequestErrorFields,
912) {
913 override get message(): string {
914 return `Preview automation client ${this.clientId} stopped accepting ${this.operation} requests.`;
915 }
917​
918export class PreviewAutomationRemoteUnavailableError extends Schema.TaggedError<PreviewAutomationRemoteUnavailableError>()(
919 "PreviewAutomationRemoteUnavailableError",
920 {
921 ...PreviewAutomationRequestErrorFields,
922 ...PreviewAutomationRemoteDiagnosticFields,
923 },
924) {
925 override get message(): string {
926 return `Preview automation ${this.operation} is unavailable on client ${this.clientId}.`;
927 }
929​
930export class PreviewAutomationMalformedResponseError extends Schema.TaggedError<PreviewAutomationMalformedResponseError>()(
931 "PreviewAutomationMalformedResponseError",
932 PreviewAutomationRequestErrorFields,
933) {
934 override get message(): string {
935 return `Preview automation client ${this.clientId} returned a malformed response for ${this.operation}.`;
936 }
938​
939export class PreviewAutomationRecordingTransferError extends Schema.TaggedError<PreviewAutomationRecordingTransferError>()(
940 "PreviewAutomationRecordingTransferError",
941 {
942 threadId: ThreadId,
943 cause: Schema.optional(Schema.Defect()),
944 },
945) {
946 override get message(): string {
947 return "Preview recording could not be saved to the agent environment.";
948 }
950​
951export class PreviewAutomationRecordingDesktopUpdateRequiredError extends Schema.TaggedError<PreviewAutomationRecordingDesktopUpdateRequiredError>()(
952 "PreviewAutomationRecordingDesktopUpdateRequiredError",
953 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
954) {
955 override get message(): string {
956 return "Update the desktop app to transfer recordings. The recording remains on the desktop.";
957 }
959​
960export class PreviewAutomationRecordingTooLargeError extends Schema.TaggedError<PreviewAutomationRecordingTooLargeError>()(
961 "PreviewAutomationRecordingTooLargeError",
962 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
963) {
964 override get message(): string {
965 return "The recording exceeds 50 MiB. Make a shorter recording.";
966 }
968​
969export class PreviewAutomationRecordingDeadlineExpiredError extends Schema.TaggedError<PreviewAutomationRecordingDeadlineExpiredError>()(
970 "PreviewAutomationRecordingDeadlineExpiredError",
971 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
972) {
973 override get message(): string {
974 return "The recording transfer deadline expired.";
975 }
977​
978export const PreviewAutomationError = Schema.Union([
979 PreviewAutomationRecordingTransferError,
980 PreviewAutomationRecordingDesktopUpdateRequiredError,
981 PreviewAutomationRecordingTooLargeError,
982 PreviewAutomationRecordingDeadlineExpiredError,
983 PreviewAutomationUnavailableError,
984 PreviewAutomationNoAvailableHostError,
985 PreviewAutomationUnsupportedClientError,
986 PreviewAutomationTabNotFoundError,
987 PreviewAutomationTimeoutError,
988 PreviewAutomationControlInterruptedError,
989 PreviewAutomationExecutionError,
990 PreviewAutomationInvalidSelectorError,
991 PreviewAutomationTargetNotEditableError,
992 PreviewAutomationResultTooLargeError,
993 PreviewAutomationClientDisconnectedError,
994 PreviewAutomationRequestQueueClosedError,
995 PreviewAutomationRemoteUnavailableError,
996 PreviewAutomationMalformedResponseError,
997]);
998export type PreviewAutomationError = typeof PreviewAutomationError.Type;
999​
1000export const PreviewUrlResolution = Schema.Struct({
1001 requestedUrl: Schema.String,
1002 resolvedUrl: Schema.String,
1003 resolutionKind: Schema.Literals(["direct", "direct-private-network"]),
1004 environmentId: EnvironmentId,
1005});
1006export type PreviewUrlResolution = typeof PreviewUrlResolution.Type;