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

previewAutomation.ts

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