Open History to see the last commit
1import { Schema } from "effect";
2
3import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
4import {
5 PREVIEW_VIEWPORT_MAX_AREA,
6 PreviewRenderedViewportSize,
7 PreviewTabId,
8 PreviewViewportPresetId,
9 PreviewViewportSetting,
10 PreviewViewportSize,
11} from "./preview.ts";
12import { ProviderInstanceId } from "./providerInstance.ts";
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});
556export type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type;
557
558export const PreviewAutomationRecordingStatus = Schema.Struct({
559 tabId: PreviewTabId,
560 recording: Schema.Boolean,
561 startedAt: Schema.NullOr(Schema.String),
562});
563export type PreviewAutomationRecordingStatus = typeof PreviewAutomationRecordingStatus.Type;
564
565export const PREVIEW_RECORDING_STOP_TIMEOUT_MS = 120_000;
566
567export const PreviewAutomationRecordingArtifact = Schema.Struct({
568 id: Schema.String,
569 tabId: PreviewTabId,
570 path: Schema.String,
571 mimeType: Schema.String,
572 sizeBytes: Schema.Int,
573 createdAt: Schema.String,
574});
575export type PreviewAutomationRecordingArtifact = typeof PreviewAutomationRecordingArtifact.Type;
576
577export const PreviewAutomationClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
578export type PreviewAutomationClientId = typeof PreviewAutomationClientId.Type;
579export const PreviewAutomationConnectionId = TrimmedNonEmptyString.check(Schema.isMaxLength(64));
580export type PreviewAutomationConnectionId = typeof PreviewAutomationConnectionId.Type;
581
582export const PreviewAutomationHostIdentity = Schema.Struct({
583 clientId: PreviewAutomationClientId,
584 environmentId: EnvironmentId,
585});
586export type PreviewAutomationHostIdentity = typeof PreviewAutomationHostIdentity.Type;
587
588export const PreviewAutomationHost = Schema.Struct({
589 ...PreviewAutomationHostIdentity.fields,
590 /** Missing means the V1 operation set from before capability negotiation. */
591 supportedOperations: Schema.optional(Schema.Array(PreviewAutomationOperation)),
592});
593export type PreviewAutomationHost = typeof PreviewAutomationHost.Type;
594
595export const PreviewAutomationHostFocus = Schema.Struct({
596 ...PreviewAutomationHostIdentity.fields,
597 connectionId: PreviewAutomationConnectionId,
598 focused: Schema.Boolean,
599 liveTabs: Schema.optional(
600 Schema.Array(
601 Schema.Struct({
602 threadId: ThreadId,
603 tabId: PreviewTabId,
604 visible: Schema.optional(Schema.Boolean),
605 }),
606 ),
607 ),
608});
609export type PreviewAutomationHostFocus = typeof PreviewAutomationHostFocus.Type;
610
611export const PreviewAutomationRequest = Schema.Struct({
612 requestId: TrimmedNonEmptyString,
613 threadId: ThreadId,
614 tabId: Schema.optional(PreviewTabId),
615 tabIdExplicit: Schema.optional(Schema.Boolean),
616 /** Supplied by the broker from authenticated scope, never from tool input. */
617 agentSessionId: Schema.optional(Schema.String),
618 operation: PreviewAutomationOperation,
619 input: Schema.Unknown,
620 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
621});
622export type PreviewAutomationRequest = typeof PreviewAutomationRequest.Type;
623
624export const PreviewAutomationStreamEvent = Schema.Union([
625 Schema.Struct({
626 type: Schema.Literal("connected"),
627 connectionId: PreviewAutomationConnectionId,
628 }),
629 Schema.Struct({
630 type: Schema.Literal("request"),
631 connectionId: PreviewAutomationConnectionId,
632 request: PreviewAutomationRequest,
633 }),
634]);
635export type PreviewAutomationStreamEvent = typeof PreviewAutomationStreamEvent.Type;
636
637export const PreviewAutomationResponse = Schema.Struct({
638 clientId: PreviewAutomationClientId,
639 connectionId: PreviewAutomationConnectionId,
640 requestId: TrimmedNonEmptyString,
641 ok: Schema.Boolean,
642 result: Schema.optional(Schema.Unknown),
643 error: Schema.optional(
644 Schema.Struct({
645 _tag: TrimmedNonEmptyString,
646 message: Schema.String,
647 detail: Schema.optional(Schema.Unknown),
648 }),
649 ),
650});
651export type PreviewAutomationResponse = typeof PreviewAutomationResponse.Type;
652
653const McpCapabilityErrorFields = {
654 environmentId: EnvironmentId,
655 threadId: Schema.optional(ThreadId),
656 providerSessionId: Schema.optional(TrimmedNonEmptyString),
657 providerInstanceId: Schema.optional(ProviderInstanceId),
658};
659
660export class PreviewAutomationUnavailableError extends Schema.TaggedError<PreviewAutomationUnavailableError>()(
661 "PreviewAutomationUnavailableError",
662 {
663 capability: Schema.Literal("preview"),
664 ...McpCapabilityErrorFields,
665 },
666) {
667 override get message(): string {
668 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.`;
669 }
670}
671
672export class McpCapabilityUnavailableError extends Schema.TaggedError<McpCapabilityUnavailableError>()(
673 "McpCapabilityUnavailableError",
674 {
675 capability: TrimmedNonEmptyString,
676 ...McpCapabilityErrorFields,
677 },
678) {
679 override get message(): string {
680 return `MCP credential does not grant the ${this.capability} capability.`;
681 }
682}
683
684const PreviewAutomationScopeErrorFields = {
685 operation: PreviewAutomationOperation,
686 environmentId: EnvironmentId,
687 threadId: ThreadId,
688 providerSessionId: TrimmedNonEmptyString,
689 providerInstanceId: ProviderInstanceId,
690};
691
692export const SERVER_BROWSER_AUTOMATION_CLIENT_ID = "server-browser";
693
694const PreviewAutomationRequestErrorFields = {
695 ...PreviewAutomationScopeErrorFields,
696 clientId: TrimmedNonEmptyString,
697 connectionId: PreviewAutomationConnectionId,
698 requestId: TrimmedNonEmptyString,
699 tabId: Schema.optional(PreviewTabId),
700 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
701};
702
703const PreviewAutomationRemoteDiagnosticFields = {
704 remoteTag: TrimmedNonEmptyString,
705 remoteMessageLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
706 remoteDetailKind: Schema.optional(
707 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
708 ),
709 cause: Schema.Defect(),
710};
711
712const PreviewAutomationOptionalRemoteDiagnosticFields = {
713 remoteTag: Schema.optional(TrimmedNonEmptyString),
714 remoteMessageLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
715 remoteDetailKind: Schema.optional(
716 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
717 ),
718 cause: Schema.optional(Schema.Defect()),
719};
720
721export class PreviewAutomationNoAvailableHostError extends Schema.TaggedError<PreviewAutomationNoAvailableHostError>()(
722 "PreviewAutomationNoAvailableHostError",
723 {
724 ...PreviewAutomationScopeErrorFields,
725 clientId: Schema.optional(TrimmedNonEmptyString),
726 connectionId: Schema.optional(PreviewAutomationConnectionId),
727 requestId: Schema.optional(TrimmedNonEmptyString),
728 tabId: Schema.optional(PreviewTabId),
729 timeoutMs: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
730 ...PreviewAutomationOptionalRemoteDiagnosticFields,
731 },
732) {
733 override get message(): string {
734 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.`;
735 }
736}
737
738export class PreviewAutomationUnsupportedClientError extends Schema.TaggedError<PreviewAutomationUnsupportedClientError>()(
739 "PreviewAutomationUnsupportedClientError",
740 {
741 ...PreviewAutomationRequestErrorFields,
742 ...PreviewAutomationRemoteDiagnosticFields,
743 },
744) {
745 override get message(): string {
746 return `Preview automation client ${this.clientId} does not support ${this.operation}.`;
747 }
748}
749
750export class PreviewAutomationTabNotFoundError extends Schema.TaggedError<PreviewAutomationTabNotFoundError>()(
751 "PreviewAutomationTabNotFoundError",
752 {
753 ...PreviewAutomationRequestErrorFields,
754 ...PreviewAutomationRemoteDiagnosticFields,
755 },
756) {
757 override get message(): string {
758 return this.tabId
759 ? `Preview tab ${this.tabId} was not found for ${this.operation}. Omit tabId to use the current tab, or call preview_open.`
760 : `No active preview tab was found for ${this.operation}. Call preview_open first.`;
761 }
762}
763
764export class PreviewAutomationTimeoutError extends Schema.TaggedError<PreviewAutomationTimeoutError>()(
765 "PreviewAutomationTimeoutError",
766 {
767 ...PreviewAutomationRequestErrorFields,
768 ...PreviewAutomationOptionalRemoteDiagnosticFields,
769 },
770) {
771 override get message(): string {
772 const summary = `Preview automation ${this.operation} timed out after ${this.timeoutMs}ms.`;
773 return summary;
774 }
775}
776
777export const PreviewAutomationControlReason = Schema.Literals([
778 "agentMismatch",
779 "humanControl",
780 "tabRequired",
781 "closed",
782 "interrupted",
783 "dialogPending",
784 "tabLimit",
785]);
786export type PreviewAutomationControlReason = typeof PreviewAutomationControlReason.Type;
787
788export class PreviewAutomationControlInterruptedError extends Schema.TaggedError<PreviewAutomationControlInterruptedError>()(
789 "PreviewAutomationControlInterruptedError",
790 {
791 ...PreviewAutomationRequestErrorFields,
792 ...PreviewAutomationRemoteDiagnosticFields,
793 reason: Schema.optional(PreviewAutomationControlReason),
794 },
795) {
796 override get message(): string {
797 if (this.reason === "agentMismatch")
798 return "This browser tab belongs to another agent session or a human. Open your own tab.";
799 if (this.reason === "humanControl")
800 return "A human controls this browser tab. Wait until they release control.";
801 if (this.reason === "tabRequired")
802 return "Multiple browser tabs belong to this session. Pass a tabId from preview_open or from the tabs listed by preview_status.";
803 if (this.reason === "dialogPending")
804 return "A browser dialog is pending. Read preview_status and resolve it with preview_dialog.";
805 if (this.reason === "tabLimit")
806 return "Too many server browser tabs are open. Close one with t3_preview_close, or reuse a tabId from preview_status tabs.";
807 if (this.reason === "closed") return "This browser tab is closed. Call preview_open.";
808 if (this.reason === "interrupted")
809 return "Browser control changed. Take a fresh snapshot before trying again.";
810 return `Preview automation ${this.operation} was interrupted on client ${this.clientId}.`;
811 }
812}
813
814export class PreviewAutomationExecutionError extends Schema.TaggedError<PreviewAutomationExecutionError>()(
815 "PreviewAutomationExecutionError",
816 {
817 ...PreviewAutomationRequestErrorFields,
818 ...PreviewAutomationRemoteDiagnosticFields,
819 reason: Schema.optional(Schema.String),
820 },
821) {
822 override get message(): string {
823 return this.reason === undefined
824 ? `Preview automation ${this.operation} failed on client ${this.clientId}.`
825 : `Preview automation ${this.operation} failed: ${this.reason}`;
826 }
827}
828
829export class PreviewAutomationInvalidSelectorError extends Schema.TaggedError<PreviewAutomationInvalidSelectorError>()(
830 "PreviewAutomationInvalidSelectorError",
831 {
832 ...PreviewAutomationRequestErrorFields,
833 ...PreviewAutomationRemoteDiagnosticFields,
834 selectorKind: Schema.optional(Schema.Literals(["locator", "selector"])),
835 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
836 staleRef: Schema.optional(Schema.Boolean),
837 },
838) {
839 override get message(): string {
840 if (this.staleRef)
841 return "This element ref is stale. Navigation, dialogs, and new snapshots replace refs; take a fresh snapshot and use its refs.";
842 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
843 return `Preview automation ${this.operation} received an invalid ${this.selectorKind} (${this.selectorLength} characters).`;
844 }
845 return `Preview automation ${this.operation} received an invalid selector.`;
846 }
847}
848
849export class PreviewAutomationTargetNotEditableError extends Schema.TaggedError<PreviewAutomationTargetNotEditableError>()(
850 "PreviewAutomationTargetNotEditableError",
851 {
852 ...PreviewAutomationRequestErrorFields,
853 ...PreviewAutomationRemoteDiagnosticFields,
854 selectorKind: Schema.optional(Schema.Literals(["focused-element", "locator", "selector"])),
855 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
856 },
857) {
858 override get message(): string {
859 if (this.selectorKind === "focused-element") {
860 return `Preview automation ${this.operation} requires an editable focused element.`;
861 }
862 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
863 return `Preview automation ${this.operation} requires an editable ${this.selectorKind} (${this.selectorLength} characters).`;
864 }
865 return `Preview automation ${this.operation} requires an editable target.`;
866 }
867}
868
869export class PreviewAutomationResultTooLargeError extends Schema.TaggedError<PreviewAutomationResultTooLargeError>()(
870 "PreviewAutomationResultTooLargeError",
871 {
872 ...PreviewAutomationRequestErrorFields,
873 ...PreviewAutomationRemoteDiagnosticFields,
874 maximumBytes: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
875 },
876) {
877 override get message(): string {
878 const summary =
879 this.maximumBytes === undefined
880 ? `Preview automation ${this.operation} produced a result that is too large.`
881 : `Preview automation ${this.operation} produced a result larger than ${this.maximumBytes} bytes.`;
882 return summary;
883 }
884}
885
886export class PreviewAutomationClientDisconnectedError extends Schema.TaggedError<PreviewAutomationClientDisconnectedError>()(
887 "PreviewAutomationClientDisconnectedError",
888 PreviewAutomationRequestErrorFields,
889) {
890 override get message(): string {
891 return `Preview automation client ${this.clientId} disconnected during ${this.operation}.`;
892 }
893}
894
895export class PreviewAutomationRequestQueueClosedError extends Schema.TaggedError<PreviewAutomationRequestQueueClosedError>()(
896 "PreviewAutomationRequestQueueClosedError",
897 PreviewAutomationRequestErrorFields,
898) {
899 override get message(): string {
900 return `Preview automation client ${this.clientId} stopped accepting ${this.operation} requests.`;
901 }
902}
903
904export class PreviewAutomationRemoteUnavailableError extends Schema.TaggedError<PreviewAutomationRemoteUnavailableError>()(
905 "PreviewAutomationRemoteUnavailableError",
906 {
907 ...PreviewAutomationRequestErrorFields,
908 ...PreviewAutomationRemoteDiagnosticFields,
909 },
910) {
911 override get message(): string {
912 return `Preview automation ${this.operation} is unavailable on client ${this.clientId}.`;
913 }
914}
915
916export class PreviewAutomationMalformedResponseError extends Schema.TaggedError<PreviewAutomationMalformedResponseError>()(
917 "PreviewAutomationMalformedResponseError",
918 PreviewAutomationRequestErrorFields,
919) {
920 override get message(): string {
921 return `Preview automation client ${this.clientId} returned a malformed response for ${this.operation}.`;
922 }
923}
924
925export class PreviewAutomationRecordingTransferError extends Schema.TaggedError<PreviewAutomationRecordingTransferError>()(
926 "PreviewAutomationRecordingTransferError",
927 {
928 threadId: ThreadId,
929 cause: Schema.optional(Schema.Defect()),
930 },
931) {
932 override get message(): string {
933 return "Preview recording could not be saved to the agent environment.";
934 }
935}
936
937export class PreviewAutomationRecordingDesktopUpdateRequiredError extends Schema.TaggedError<PreviewAutomationRecordingDesktopUpdateRequiredError>()(
938 "PreviewAutomationRecordingDesktopUpdateRequiredError",
939 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
940) {
941 override get message(): string {
942 return "Update the desktop app to transfer recordings. The recording remains on the desktop.";
943 }
944}
945
946export class PreviewAutomationRecordingTooLargeError extends Schema.TaggedError<PreviewAutomationRecordingTooLargeError>()(
947 "PreviewAutomationRecordingTooLargeError",
948 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
949) {
950 override get message(): string {
951 return "The recording exceeds 50 MiB. Make a shorter recording.";
952 }
953}
954
955export class PreviewAutomationRecordingDeadlineExpiredError extends Schema.TaggedError<PreviewAutomationRecordingDeadlineExpiredError>()(
956 "PreviewAutomationRecordingDeadlineExpiredError",
957 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
958) {
959 override get message(): string {
960 return "The recording transfer deadline expired.";
961 }
962}
963
964export const PreviewAutomationError = Schema.Union([
965 PreviewAutomationRecordingTransferError,
966 PreviewAutomationRecordingDesktopUpdateRequiredError,
967 PreviewAutomationRecordingTooLargeError,
968 PreviewAutomationRecordingDeadlineExpiredError,
969 PreviewAutomationUnavailableError,
970 PreviewAutomationNoAvailableHostError,
971 PreviewAutomationUnsupportedClientError,
972 PreviewAutomationTabNotFoundError,
973 PreviewAutomationTimeoutError,
974 PreviewAutomationControlInterruptedError,
975 PreviewAutomationExecutionError,
976 PreviewAutomationInvalidSelectorError,
977 PreviewAutomationTargetNotEditableError,
978 PreviewAutomationResultTooLargeError,
979 PreviewAutomationClientDisconnectedError,
980 PreviewAutomationRequestQueueClosedError,
981 PreviewAutomationRemoteUnavailableError,
982 PreviewAutomationMalformedResponseError,
983]);
984export type PreviewAutomationError = typeof PreviewAutomationError.Type;
985
986export const PreviewUrlResolution = Schema.Struct({
987 requestedUrl: Schema.String,
988 resolvedUrl: Schema.String,
989 resolutionKind: Schema.Literals(["direct", "direct-private-network"]),
990 environmentId: EnvironmentId,
991});
992export type PreviewUrlResolution = typeof PreviewUrlResolution.Type;