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