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

previewAutomation.ts

883 lines32.8 KB

1import { Schema } from "effect";
2​
3import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
4import {
5 PREVIEW_VIEWPORT_MAX_AREA,
6 PreviewRenderedViewportSize,
7 PreviewTabId,
8 PreviewViewportPresetId,
9 PreviewViewportSetting,
10 PreviewViewportSize,
11} from "./preview.ts";
12import { ProviderInstanceId } from "./providerInstance.ts";
13​
14const BoundedUrl = Schema.String.check(Schema.isTrimmed())
15 .check(Schema.isNonEmpty())
16 .check(Schema.isMaxLength(2048));
17const URL_GUIDANCE =
18 "Absolute http(s) URL or a schemeless host such as t3.chat or localhost:5173. Schemeless public hosts use https; loopback hosts use http.";
19const OptionalTimeoutMs = Schema.optional(
20 Schema.Int.check(Schema.isGreaterThan(0))
21 .check(Schema.isLessThanOrEqualTo(60_000))
22 .annotate({ description: "Maximum wait in milliseconds. Defaults to 15000; maximum 60000." }),
23).annotate({ description: "Maximum wait in milliseconds. Defaults to 15000; maximum 60000." });
24​
25/** Operations understood by desktop hosts predating viewport resizing. */
26export const PREVIEW_AUTOMATION_V1_OPERATIONS = [
27 "status",
28 "open",
29 "navigate",
30 "snapshot",
31 "click",
32 "type",
33 "press",
34 "scroll",
35 "evaluate",
36 "waitFor",
37 "recordingStart",
38 "recordingStop",
39] as const;
40​
41/** Advertised by current desktop hosts for mixed-version routing. */
42export const PREVIEW_AUTOMATION_OPERATIONS = [
43 ...PREVIEW_AUTOMATION_V1_OPERATIONS,
44 "resize",
45 "setColorScheme",
46] as const;
47​
48export const PreviewAutomationOperation = Schema.Literals(PREVIEW_AUTOMATION_OPERATIONS);
49export type PreviewAutomationOperation = typeof PreviewAutomationOperation.Type;
50​
51const PreviewAutomationTabTargetFields = {
52 tabId: Schema.optional(
53 PreviewTabId.annotate({
54 description:
55 "Exact collaborative browser tab to target. Omit to use this agent session's current tab.",
56 }),
57 ).annotate({
58 description:
59 "Exact collaborative browser tab to target. Omit to use this agent session's current tab.",
60 }),
61};
62​
63export const PreviewAutomationTabTargetInput = Schema.Struct(PreviewAutomationTabTargetFields);
64export type PreviewAutomationTabTargetInput = typeof PreviewAutomationTabTargetInput.Type;
65​
66export const PreviewAutomationStatus = Schema.Struct({
67 available: Schema.Boolean,
68 visible: Schema.Boolean,
69 tabId: Schema.NullOr(PreviewTabId),
70 url: Schema.NullOr(Schema.String),
71 title: Schema.NullOr(Schema.String),
72 loading: Schema.Boolean,
73 /** Optional for compatibility with desktop hosts predating viewport sizing. */
74 viewportSetting: Schema.optional(PreviewViewportSetting),
75 /** Measured guest-page viewport in CSS pixels when a webview is ready. */
76 viewport: Schema.optional(PreviewRenderedViewportSize),
77});
78export type PreviewAutomationStatus = typeof PreviewAutomationStatus.Type;
79​
80export const PreviewAutomationOpenInput = Schema.Struct({
81 ...PreviewAutomationTabTargetFields,
82 url: Schema.optional(BoundedUrl).annotate({
83 description: `Optional initial page URL. ${URL_GUIDANCE} Omit to open a blank tab.`,
84 }),
85 open: Schema.optional(
86 Schema.Boolean.annotate({
87 description:
88 "Whether to open the thread-bound inline preview for the human. Defaults to true; set false for background-only automation.",
89 }),
90 ),
91 show: Schema.optional(
92 Schema.Boolean.annotate({
93 description:
94 "Deprecated alias for open. Whether to reveal the thread-bound inline preview to the human.",
95 }),
96 ),
97 reuseExistingTab: Schema.optional(
98 Schema.Boolean.annotate({
99 description:
100 "Reuse tabId when supplied, otherwise this agent session's current tab. Defaults to true; set false to create a new tab.",
101 }),
102 ),
103})
104 .check(
105 Schema.makeFilter(
106 (input) =>
107 !(input.tabId !== undefined && input.reuseExistingTab === false) ||
108 "tabId cannot be combined with reuseExistingTab=false.",
109 ),
110 )
111 .annotate({
112 description:
113 "Opens the collaborative browser for the current thread. Use preview_navigate afterward when readiness waiting matters.",
114 });
115export type PreviewAutomationOpenInput = typeof PreviewAutomationOpenInput.Type;
116​
117export const BrowserNavigationTarget = Schema.Union([
118 Schema.Struct({
119 kind: Schema.Literal("url").annotate({
120 description: "Selects direct URL navigation.",
121 }),
122 url: BoundedUrl.annotate({
123 description: `Direct website URL. ${URL_GUIDANCE}`,
124 }),
125 }),
126 Schema.Struct({
127 kind: Schema.Literal("environment-port").annotate({
128 description: "Selects a dev-server port relative to the current execution environment.",
129 }),
130 port: Schema.Int.check(Schema.isGreaterThan(0))
131 .check(Schema.isLessThan(65_536))
132 .annotate({ description: "Dev-server TCP port inside the current environment." }),
133 protocol: Schema.optional(
134 Schema.Literals(["http", "https"]).annotate({
135 description: "Dev-server protocol. Defaults to http.",
136 }),
137 ),
138 path: Schema.optional(
139 Schema.String.annotate({
140 description: "Optional path, query, and fragment, for example /settings?tab=account.",
141 }),
142 ),
143 }),
144]);
145export type BrowserNavigationTarget = typeof BrowserNavigationTarget.Type;
146​
147export const PreviewAutomationNavigateInput = Schema.Struct({
148 ...PreviewAutomationTabTargetFields,
149 url: Schema.optional(BoundedUrl).annotate({
150 description: `Website URL. ${URL_GUIDANCE} Use this for public pages and directly reachable URLs.`,
151 }),
152 target: Schema.optional(
153 BrowserNavigationTarget.annotate({
154 description:
155 "Environment-relative target. Prefer {kind:'environment-port',port:5173} for a dev server in the current environment.",
156 }),
157 ).annotate({
158 description:
159 "Environment-relative target. Prefer {kind:'environment-port',port:5173} for a dev server in the current environment.",
160 }),
161 readiness: Schema.optional(
162 Schema.Literals(["load", "domContentLoaded", "none"]).annotate({
163 description:
164 "Readiness milestone before returning. 'load' waits for loading to stop (default), 'domContentLoaded' waits for an interactive document, and 'none' returns immediately.",
165 }),
166 ).annotate({
167 description:
168 "Readiness milestone before returning. 'load' is the default; use 'none' only when a later wait call will verify the page.",
169 }),
170 timeoutMs: OptionalTimeoutMs,
171})
172 .check(
173 Schema.makeFilter(
174 (input) =>
175 Number(input.url !== undefined) + Number(input.target !== undefined) === 1 ||
176 "Provide exactly one of url or target.",
177 ),
178 )
179 .annotate({
180 description:
181 "Navigates the active browser tab. Provide exactly one of url or target; for most public pages use url.",
182 });
183export type PreviewAutomationNavigateInput = typeof PreviewAutomationNavigateInput.Type;
184​
185export const PreviewAutomationResizeInput = Schema.Struct({
186 ...PreviewAutomationTabTargetFields,
187 mode: Schema.Literals(["fill", "freeform", "preset"]).annotate({
188 description:
189 "Viewport mode: fill follows the preview panel, freeform uses exact independently resizable dimensions, and preset uses a named device size.",
190 }),
191 preset: Schema.optional(
192 PreviewViewportPresetId.annotate({
193 description: "Named viewport from Chrome DevTools' standard device catalog.",
194 }),
195 ).annotate({
196 description: "Named device size. Required only when mode is preset.",
197 }),
198 width: Schema.optional(
199 PreviewViewportSize.fields.width.annotate({
200 description: "Freeform viewport width in CSS pixels. Required only in freeform mode.",
201 }),
202 ).annotate({
203 description: "Freeform viewport width in CSS pixels. Required only in freeform mode.",
204 }),
205 height: Schema.optional(
206 PreviewViewportSize.fields.height.annotate({
207 description: "Freeform viewport height in CSS pixels. Required only in freeform mode.",
208 }),
209 ).annotate({
210 description: "Freeform viewport height in CSS pixels. Required only in freeform mode.",
211 }),
212 orientation: Schema.optional(
213 Schema.Literals(["portrait", "landscape"]).annotate({
214 description:
215 "Orientation for a fixed device preset. Defaults to the preset's native orientation.",
216 }),
217 ).annotate({
218 description:
219 "Orientation for a named device preset. It is not accepted in fill or freeform mode.",
220 }),
221 timeoutMs: OptionalTimeoutMs,
222})
223 .check(
224 Schema.makeFilter((input) => {
225 const hasPreset = input.preset !== undefined;
226 const hasWidth = input.width !== undefined;
227 const hasHeight = input.height !== undefined;
228 if (hasWidth !== hasHeight) return "Custom dimensions require both width and height.";
229 if (input.mode === "fill") {
230 return !hasPreset && !hasWidth && input.orientation === undefined
231 ? true
232 : "Fill mode does not accept a preset, dimensions, or orientation.";
233 }
234 if (input.mode === "freeform") {
235 if (!hasWidth || !hasHeight || hasPreset || input.orientation !== undefined) {
236 return "Freeform mode requires width and height and does not accept a preset or orientation.";
237 }
238 } else if (!hasPreset || hasWidth || hasHeight) {
239 return "Preset mode requires a preset and does not accept custom dimensions.";
240 }
241 if (hasWidth && hasHeight && input.width! * input.height! > PREVIEW_VIEWPORT_MAX_AREA) {
242 return `Custom viewport area must not exceed ${PREVIEW_VIEWPORT_MAX_AREA} pixels.`;
243 }
244 return true;
245 }),
246 )
247 .annotate({
248 description:
249 "Sets the active browser tab to fill-panel, independently resizable freeform, or named device-preset sizing.",
250 });
251export type PreviewAutomationResizeInput = typeof PreviewAutomationResizeInput.Type;
252​
253export const PreviewAutomationResizeResult = Schema.Struct({
254 tabId: PreviewTabId,
255 setting: PreviewViewportSetting,
256 viewport: PreviewRenderedViewportSize,
257});
258export type PreviewAutomationResizeResult = typeof PreviewAutomationResizeResult.Type;
259​
260/** Mirrors DesktopPreviewColorScheme; declared here to keep this module free of ipc.ts imports. */
261export const PreviewAutomationColorScheme = Schema.Literals(["system", "light", "dark"]);
262export type PreviewAutomationColorScheme = typeof PreviewAutomationColorScheme.Type;
263​
264export const PreviewAutomationSetColorSchemeInput = Schema.Struct({
265 ...PreviewAutomationTabTargetFields,
266 colorScheme: PreviewAutomationColorScheme.annotate({
267 description:
268 "Emulated prefers-color-scheme for the page: light, dark, or system to follow the OS appearance.",
269 }),
270}).annotate({
271 description:
272 "Emulates prefers-color-scheme in the active browser tab without changing the OS or app theme.",
273});
274export type PreviewAutomationSetColorSchemeInput = typeof PreviewAutomationSetColorSchemeInput.Type;
275​
276export const PreviewAutomationSetColorSchemeResult = Schema.Struct({
277 tabId: PreviewTabId,
278 colorScheme: PreviewAutomationColorScheme,
279});
280export type PreviewAutomationSetColorSchemeResult =
281 typeof PreviewAutomationSetColorSchemeResult.Type;
282​
283const Locator = TrimmedNonEmptyString.annotate({
284 description:
285 "Playwright selector, preferably role/text based, for example role=button[name='Send'] or text=Continue. Use snapshot first to inspect the page.",
286});
287​
288const LegacySelector = TrimmedNonEmptyString.annotate({
289 description:
290 "Legacy CSS selector such as button[type='submit']. Prefer locator for resilient role/text targeting.",
291});
292​
293export const PreviewAutomationClickInput = Schema.Struct({
294 ...PreviewAutomationTabTargetFields,
295 selector: Schema.optional(LegacySelector).annotate({
296 description:
297 "Legacy CSS selector such as button[type='submit']. Prefer locator for resilient role/text targeting.",
298 }),
299 locator: Schema.optional(Locator).annotate({
300 description:
301 "Playwright selector, preferably role/text based, for example role=button[name='Send'] or text=Continue. Use snapshot first to inspect the page.",
302 }),
303 x: Schema.optional(
304 Schema.Finite.annotate({
305 description: "Viewport-relative X coordinate in CSS pixels. Must be paired with y.",
306 }),
307 ),
308 y: Schema.optional(
309 Schema.Finite.annotate({
310 description: "Viewport-relative Y coordinate in CSS pixels. Must be paired with x.",
311 }),
312 ),
313 timeoutMs: OptionalTimeoutMs,
314})
315 .check(
316 Schema.makeFilter((input) => {
317 const selectorModes =
318 Number(input.selector !== undefined) + Number(input.locator !== undefined);
319 const hasX = input.x !== undefined;
320 const hasY = input.y !== undefined;
321 if (hasX !== hasY) return "Coordinates require both x and y.";
322 const coordinateModes = hasX && hasY ? 1 : 0;
323 return selectorModes + coordinateModes === 1 || "Provide exactly one click target.";
324 }),
325 )
326 .annotate({
327 description:
328 "Clicks one target. Provide exactly one of locator, selector, or the x/y coordinate pair.",
329 });
330export type PreviewAutomationClickInput = typeof PreviewAutomationClickInput.Type;
331​
332export const PreviewAutomationTypeInput = Schema.Struct({
333 ...PreviewAutomationTabTargetFields,
334 text: Schema.String.annotate({ description: "Literal text to insert." }),
335 selector: Schema.optional(LegacySelector).annotate({
336 description: "Legacy CSS selector for the input. Prefer locator.",
337 }),
338 locator: Schema.optional(Locator).annotate({
339 description:
340 "Playwright selector for the input, for example role=textbox[name='Message'] or textarea[placeholder*='Message'].",
341 }),
342 clear: Schema.optional(
343 Schema.Boolean.annotate({
344 description: "Clear the existing input value before inserting text. Defaults to false.",
345 }),
346 ),
347 timeoutMs: OptionalTimeoutMs,
348})
349 .check(
350 Schema.makeFilter(
351 (input) =>
352 !(input.selector !== undefined && input.locator !== undefined) ||
353 "Provide at most one of selector or locator.",
354 ),
355 )
356 .annotate({
357 description:
358 "Types into locator/selector, or into the currently focused element when neither target is provided.",
359 });
360export type PreviewAutomationTypeInput = typeof PreviewAutomationTypeInput.Type;
361​
362export const PreviewAutomationPressInput = Schema.Struct({
363 ...PreviewAutomationTabTargetFields,
364 key: Schema.String.check(Schema.isTrimmed())
365 .check(
366 Schema.isNonEmpty({
367 description:
368 "Keyboard key name such as Enter, Escape, Tab, ArrowDown, Backspace, or a single character.",
369 }),
370 )
371 .annotateKey({
372 description:
373 "Keyboard key name such as Enter, Escape, Tab, ArrowDown, Backspace, or a single character.",
374 }),
375 modifiers: Schema.optional(
376 Schema.Array(Schema.Literals(["Alt", "Control", "Meta", "Shift"])).annotate({
377 description: "Modifier keys held while pressing key.",
378 }),
379 ),
380}).annotate({ description: "Presses one keyboard key in the active browser tab." });
381export type PreviewAutomationPressInput = typeof PreviewAutomationPressInput.Type;
382​
383export const PreviewAutomationScrollInput = Schema.Struct({
384 ...PreviewAutomationTabTargetFields,
385 deltaX: Schema.optional(
386 Schema.Finite.annotate({
387 description: "Horizontal scroll delta in CSS pixels. Positive scrolls right. Defaults to 0.",
388 }),
389 ),
390 deltaY: Schema.optional(
391 Schema.Finite.annotate({
392 description: "Vertical scroll delta in CSS pixels. Positive scrolls down. Defaults to 0.",
393 }),
394 ),
395 selector: Schema.optional(LegacySelector).annotate({
396 description: "Legacy CSS selector for a scrollable container. Omit to scroll the viewport.",
397 }),
398 locator: Schema.optional(Locator).annotate({
399 description: "Playwright selector for a scrollable container. Omit to scroll the viewport.",
400 }),
401})
402 .check(
403 Schema.makeFilter((input) => {
404 if (input.selector !== undefined && input.locator !== undefined) {
405 return "Provide at most one of selector or locator.";
406 }
407 return (
408 input.deltaX !== undefined || input.deltaY !== undefined || "Provide deltaX or deltaY."
409 );
410 }),
411 )
412 .annotate({
413 description:
414 "Scrolls the viewport, or a locator/selector container. Provide deltaX, deltaY, or both.",
415 });
416export type PreviewAutomationScrollInput = typeof PreviewAutomationScrollInput.Type;
417​
418export const PreviewAutomationEvaluateInput = Schema.Struct({
419 ...PreviewAutomationTabTargetFields,
420 expression: Schema.String.check(Schema.isTrimmed())
421 .check(
422 Schema.isNonEmpty({
423 description:
424 "JavaScript expression evaluated in the page's main frame, for example document.title or (() => ({href: location.href}))().",
425 }),
426 )
427 .check(Schema.isMaxLength(64_000))
428 .annotateKey({
429 description:
430 "JavaScript expression evaluated in the page's main frame, for example document.title or (() => ({href: location.href}))().",
431 }),
432 awaitPromise: Schema.optional(
433 Schema.Boolean.annotate({ description: "Await a returned Promise. Defaults to true." }),
434 ),
435 returnByValue: Schema.optional(
436 Schema.Boolean.annotate({
437 description:
438 "Serialize and return the value instead of a remote object reference. Defaults to true.",
439 }),
440 ),
441}).annotate({
442 description:
443 "Evaluates JavaScript in the page. Prefer snapshot and semantic actions; use evaluate for inspection or unsupported interactions.",
444});
445export type PreviewAutomationEvaluateInput = typeof PreviewAutomationEvaluateInput.Type;
446​
447export const PreviewAutomationWaitForInput = Schema.Struct({
448 ...PreviewAutomationTabTargetFields,
449 selector: Schema.optional(LegacySelector).annotate({
450 description: "Legacy CSS selector that must match an element. Prefer locator.",
451 }),
452 locator: Schema.optional(Locator).annotate({
453 description:
454 "Playwright selector that must match an element, for example role=button[name='Send'].",
455 }),
456 text: Schema.optional(
457 TrimmedNonEmptyString.annotate({
458 description: "Case-sensitive substring that must appear in visible document text.",
459 }),
460 ).annotate({
461 description: "Case-sensitive substring that must appear in visible document text.",
462 }),
463 urlIncludes: Schema.optional(
464 TrimmedNonEmptyString.annotate({
465 description: "Substring that must appear in the current absolute URL.",
466 }),
467 ).annotate({ description: "Substring that must appear in the current absolute URL." }),
468 timeoutMs: OptionalTimeoutMs,
469})
470 .check(
471 Schema.makeFilter((input) => {
472 if (input.selector !== undefined && input.locator !== undefined) {
473 return "Provide at most one of selector or locator.";
474 }
475 return (
476 input.selector !== undefined ||
477 input.locator !== undefined ||
478 input.text !== undefined ||
479 input.urlIncludes !== undefined ||
480 "Provide at least one wait condition."
481 );
482 }),
483 )
484 .annotate({
485 description:
486 "Waits until all provided conditions match. Use after click/type when the page changes asynchronously.",
487 });
488export type PreviewAutomationWaitForInput = typeof PreviewAutomationWaitForInput.Type;
489​
490export const PreviewAutomationElement = Schema.Struct({
491 tag: Schema.String,
492 role: Schema.NullOr(Schema.String),
493 name: Schema.String,
494 selector: Schema.String,
495 x: Schema.Number,
496 y: Schema.Number,
497 width: Schema.Number,
498 height: Schema.Number,
499});
500export type PreviewAutomationElement = typeof PreviewAutomationElement.Type;
501​
502export const PreviewAutomationConsoleEntry = Schema.Struct({
503 level: Schema.String,
504 text: Schema.String,
505 timestamp: Schema.String,
506 source: Schema.optional(Schema.String),
507});
508export type PreviewAutomationConsoleEntry = typeof PreviewAutomationConsoleEntry.Type;
509​
510export const PreviewAutomationNetworkEntry = Schema.Struct({
511 url: Schema.String,
512 method: Schema.String,
513 status: Schema.NullOr(Schema.Number),
514 failed: Schema.Boolean,
515 errorText: Schema.optional(Schema.String),
516 timestamp: Schema.String,
517});
518export type PreviewAutomationNetworkEntry = typeof PreviewAutomationNetworkEntry.Type;
519​
520export const PreviewAutomationActionEvent = Schema.Struct({
521 id: Schema.String,
522 action: Schema.String,
523 status: Schema.Literals(["running", "succeeded", "failed", "interrupted"]),
524 startedAt: Schema.String,
525 completedAt: Schema.optional(Schema.String),
526 error: Schema.optional(Schema.String),
527});
528export type PreviewAutomationActionEvent = typeof PreviewAutomationActionEvent.Type;
529​
530export const PreviewAutomationSnapshot = Schema.Struct({
531 url: Schema.String,
532 title: Schema.String,
533 loading: Schema.Boolean,
534 visibleText: Schema.String,
535 interactiveElements: Schema.Array(PreviewAutomationElement),
536 accessibilityTree: Schema.Unknown,
537 consoleEntries: Schema.Array(PreviewAutomationConsoleEntry),
538 networkEntries: Schema.Array(PreviewAutomationNetworkEntry),
539 actionTimeline: Schema.Array(PreviewAutomationActionEvent),
540 screenshot: Schema.Struct({
541 mimeType: Schema.Literal("image/png"),
542 data: Schema.String,
543 width: Schema.Int,
544 height: Schema.Int,
545 }),
546});
547export type PreviewAutomationSnapshot = typeof PreviewAutomationSnapshot.Type;
548​
549export const PreviewAutomationRecordingStatus = Schema.Struct({
550 tabId: PreviewTabId,
551 recording: Schema.Boolean,
552 startedAt: Schema.NullOr(Schema.String),
553});
554export type PreviewAutomationRecordingStatus = typeof PreviewAutomationRecordingStatus.Type;
555​
556export const PreviewAutomationRecordingArtifact = Schema.Struct({
557 id: Schema.String,
558 tabId: PreviewTabId,
559 path: Schema.String,
560 mimeType: Schema.String,
561 sizeBytes: Schema.Int,
562 createdAt: Schema.String,
563});
564export type PreviewAutomationRecordingArtifact = typeof PreviewAutomationRecordingArtifact.Type;
565​
566export const PreviewAutomationClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
567export type PreviewAutomationClientId = typeof PreviewAutomationClientId.Type;
568export const PreviewAutomationConnectionId = TrimmedNonEmptyString.check(Schema.isMaxLength(64));
569export type PreviewAutomationConnectionId = typeof PreviewAutomationConnectionId.Type;
570​
571export const PreviewAutomationHostIdentity = Schema.Struct({
572 clientId: PreviewAutomationClientId,
573 environmentId: EnvironmentId,
574});
575export type PreviewAutomationHostIdentity = typeof PreviewAutomationHostIdentity.Type;
576​
577export const PreviewAutomationHost = Schema.Struct({
578 ...PreviewAutomationHostIdentity.fields,
579 /**
580 * Missing means the pre-capability-negotiation V1 operation set. This lets
581 * a newer server safely coexist with an older desktop during rollout.
582 */
583 supportedOperations: Schema.optional(Schema.Array(PreviewAutomationOperation)),
584});
585export type PreviewAutomationHost = typeof PreviewAutomationHost.Type;
586​
587export const PreviewAutomationHostFocus = Schema.Struct({
588 ...PreviewAutomationHostIdentity.fields,
589 connectionId: PreviewAutomationConnectionId,
590 focused: Schema.Boolean,
591});
592export type PreviewAutomationHostFocus = typeof PreviewAutomationHostFocus.Type;
593​
594export const PreviewAutomationRequest = Schema.Struct({
595 requestId: TrimmedNonEmptyString,
596 threadId: ThreadId,
597 tabId: Schema.optional(PreviewTabId),
598 tabIdExplicit: Schema.optional(Schema.Boolean),
599 operation: PreviewAutomationOperation,
600 input: Schema.Unknown,
601 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
602});
603export type PreviewAutomationRequest = typeof PreviewAutomationRequest.Type;
604​
605export const PreviewAutomationStreamEvent = Schema.Union([
606 Schema.Struct({
607 type: Schema.Literal("connected"),
608 connectionId: PreviewAutomationConnectionId,
609 }),
610 Schema.Struct({
611 type: Schema.Literal("request"),
612 connectionId: PreviewAutomationConnectionId,
613 request: PreviewAutomationRequest,
614 }),
615]);
616export type PreviewAutomationStreamEvent = typeof PreviewAutomationStreamEvent.Type;
617​
618export const PreviewAutomationResponse = Schema.Struct({
619 clientId: PreviewAutomationClientId,
620 connectionId: PreviewAutomationConnectionId,
621 requestId: TrimmedNonEmptyString,
622 ok: Schema.Boolean,
623 result: Schema.optional(Schema.Unknown),
624 error: Schema.optional(
625 Schema.Struct({
626 _tag: TrimmedNonEmptyString,
627 message: Schema.String,
628 detail: Schema.optional(Schema.Unknown),
629 }),
630 ),
631});
632export type PreviewAutomationResponse = typeof PreviewAutomationResponse.Type;
633​
634export class PreviewAutomationUnavailableError extends Schema.TaggedErrorClass<PreviewAutomationUnavailableError>()(
635 "PreviewAutomationUnavailableError",
636 {
637 capability: Schema.Literal("preview"),
638 environmentId: EnvironmentId,
639 threadId: ThreadId,
640 providerSessionId: TrimmedNonEmptyString,
641 providerInstanceId: ProviderInstanceId,
642 },
643) {
644 override get message(): string {
645 return `MCP credential does not grant the ${this.capability} capability.`;
646 }
648​
649const PreviewAutomationScopeErrorFields = {
650 operation: PreviewAutomationOperation,
651 environmentId: EnvironmentId,
652 threadId: ThreadId,
653 providerSessionId: TrimmedNonEmptyString,
654 providerInstanceId: ProviderInstanceId,
655};
656​
657const PreviewAutomationRequestErrorFields = {
658 ...PreviewAutomationScopeErrorFields,
659 clientId: TrimmedNonEmptyString,
660 connectionId: PreviewAutomationConnectionId,
661 requestId: TrimmedNonEmptyString,
662 tabId: Schema.optional(PreviewTabId),
663 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
664};
665​
666const PreviewAutomationRemoteDiagnosticFields = {
667 remoteTag: TrimmedNonEmptyString,
668 remoteMessageLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
669 remoteDetailKind: Schema.optional(
670 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
671 ),
672 cause: Schema.Defect(),
673};
674​
675const PreviewAutomationOptionalRemoteDiagnosticFields = {
676 remoteTag: Schema.optional(TrimmedNonEmptyString),
677 remoteMessageLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
678 remoteDetailKind: Schema.optional(
679 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
680 ),
681 cause: Schema.optional(Schema.Defect()),
682};
683​
684export class PreviewAutomationNoAvailableHostError extends Schema.TaggedErrorClass<PreviewAutomationNoAvailableHostError>()(
685 "PreviewAutomationNoAvailableHostError",
686 {
687 ...PreviewAutomationScopeErrorFields,
688 clientId: Schema.optional(TrimmedNonEmptyString),
689 connectionId: Schema.optional(PreviewAutomationConnectionId),
690 requestId: Schema.optional(TrimmedNonEmptyString),
691 tabId: Schema.optional(PreviewTabId),
692 timeoutMs: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
693 ...PreviewAutomationOptionalRemoteDiagnosticFields,
694 },
695) {
696 override get message(): string {
697 const summary = `No preview automation host is available for ${this.operation} in environment ${this.environmentId}.`;
698 return summary;
699 }
701​
702export class PreviewAutomationUnsupportedClientError extends Schema.TaggedErrorClass<PreviewAutomationUnsupportedClientError>()(
703 "PreviewAutomationUnsupportedClientError",
704 {
705 ...PreviewAutomationRequestErrorFields,
706 ...PreviewAutomationRemoteDiagnosticFields,
707 },
708) {
709 override get message(): string {
710 return `Preview automation client ${this.clientId} does not support ${this.operation}.`;
711 }
713​
714export class PreviewAutomationTabNotFoundError extends Schema.TaggedErrorClass<PreviewAutomationTabNotFoundError>()(
715 "PreviewAutomationTabNotFoundError",
716 {
717 ...PreviewAutomationRequestErrorFields,
718 ...PreviewAutomationRemoteDiagnosticFields,
719 },
720) {
721 override get message(): string {
722 const summary = this.tabId
723 ? `Preview tab ${this.tabId} was not found for ${this.operation}.`
724 : `No active preview tab was found for ${this.operation}.`;
725 return summary;
726 }
728​
729export class PreviewAutomationTimeoutError extends Schema.TaggedErrorClass<PreviewAutomationTimeoutError>()(
730 "PreviewAutomationTimeoutError",
731 {
732 ...PreviewAutomationRequestErrorFields,
733 ...PreviewAutomationOptionalRemoteDiagnosticFields,
734 },
735) {
736 override get message(): string {
737 const summary = `Preview automation ${this.operation} timed out after ${this.timeoutMs}ms.`;
738 return summary;
739 }
741​
742export class PreviewAutomationControlInterruptedError extends Schema.TaggedErrorClass<PreviewAutomationControlInterruptedError>()(
743 "PreviewAutomationControlInterruptedError",
744 {
745 ...PreviewAutomationRequestErrorFields,
746 ...PreviewAutomationRemoteDiagnosticFields,
747 },
748) {
749 override get message(): string {
750 return `Preview automation ${this.operation} was interrupted on client ${this.clientId}.`;
751 }
753​
754export class PreviewAutomationExecutionError extends Schema.TaggedErrorClass<PreviewAutomationExecutionError>()(
755 "PreviewAutomationExecutionError",
756 {
757 ...PreviewAutomationRequestErrorFields,
758 ...PreviewAutomationRemoteDiagnosticFields,
759 },
760) {
761 override get message(): string {
762 return `Preview automation ${this.operation} failed on client ${this.clientId}.`;
763 }
765​
766export class PreviewAutomationInvalidSelectorError extends Schema.TaggedErrorClass<PreviewAutomationInvalidSelectorError>()(
767 "PreviewAutomationInvalidSelectorError",
768 {
769 ...PreviewAutomationRequestErrorFields,
770 ...PreviewAutomationRemoteDiagnosticFields,
771 selectorKind: Schema.optional(Schema.Literals(["locator", "selector"])),
772 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
773 },
774) {
775 override get message(): string {
776 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
777 return `Preview automation ${this.operation} received an invalid ${this.selectorKind} (${this.selectorLength} characters).`;
778 }
779 return `Preview automation ${this.operation} received an invalid selector.`;
780 }
782​
783export class PreviewAutomationTargetNotEditableError extends Schema.TaggedErrorClass<PreviewAutomationTargetNotEditableError>()(
784 "PreviewAutomationTargetNotEditableError",
785 {
786 ...PreviewAutomationRequestErrorFields,
787 ...PreviewAutomationRemoteDiagnosticFields,
788 selectorKind: Schema.optional(Schema.Literals(["focused-element", "locator", "selector"])),
789 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
790 },
791) {
792 override get message(): string {
793 if (this.selectorKind === "focused-element") {
794 return `Preview automation ${this.operation} requires an editable focused element.`;
795 }
796 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
797 return `Preview automation ${this.operation} requires an editable ${this.selectorKind} (${this.selectorLength} characters).`;
798 }
799 return `Preview automation ${this.operation} requires an editable target.`;
800 }
802​
803export class PreviewAutomationResultTooLargeError extends Schema.TaggedErrorClass<PreviewAutomationResultTooLargeError>()(
804 "PreviewAutomationResultTooLargeError",
805 {
806 ...PreviewAutomationRequestErrorFields,
807 ...PreviewAutomationRemoteDiagnosticFields,
808 maximumBytes: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
809 },
810) {
811 override get message(): string {
812 const summary =
813 this.maximumBytes === undefined
814 ? `Preview automation ${this.operation} produced a result that is too large.`
815 : `Preview automation ${this.operation} produced a result larger than ${this.maximumBytes} bytes.`;
816 return summary;
817 }
819​
820export class PreviewAutomationClientDisconnectedError extends Schema.TaggedErrorClass<PreviewAutomationClientDisconnectedError>()(
821 "PreviewAutomationClientDisconnectedError",
822 PreviewAutomationRequestErrorFields,
823) {
824 override get message(): string {
825 return `Preview automation client ${this.clientId} disconnected during ${this.operation}.`;
826 }
828​
829export class PreviewAutomationRequestQueueClosedError extends Schema.TaggedErrorClass<PreviewAutomationRequestQueueClosedError>()(
830 "PreviewAutomationRequestQueueClosedError",
831 PreviewAutomationRequestErrorFields,
832) {
833 override get message(): string {
834 return `Preview automation client ${this.clientId} stopped accepting ${this.operation} requests.`;
835 }
837​
838export class PreviewAutomationRemoteUnavailableError extends Schema.TaggedErrorClass<PreviewAutomationRemoteUnavailableError>()(
839 "PreviewAutomationRemoteUnavailableError",
840 {
841 ...PreviewAutomationRequestErrorFields,
842 ...PreviewAutomationRemoteDiagnosticFields,
843 },
844) {
845 override get message(): string {
846 return `Preview automation ${this.operation} is unavailable on client ${this.clientId}.`;
847 }
849​
850export class PreviewAutomationMalformedResponseError extends Schema.TaggedErrorClass<PreviewAutomationMalformedResponseError>()(
851 "PreviewAutomationMalformedResponseError",
852 PreviewAutomationRequestErrorFields,
853) {
854 override get message(): string {
855 return `Preview automation client ${this.clientId} returned a malformed response for ${this.operation}.`;
856 }
858​
859export const PreviewAutomationError = Schema.Union([
860 PreviewAutomationUnavailableError,
861 PreviewAutomationNoAvailableHostError,
862 PreviewAutomationUnsupportedClientError,
863 PreviewAutomationTabNotFoundError,
864 PreviewAutomationTimeoutError,
865 PreviewAutomationControlInterruptedError,
866 PreviewAutomationExecutionError,
867 PreviewAutomationInvalidSelectorError,
868 PreviewAutomationTargetNotEditableError,
869 PreviewAutomationResultTooLargeError,
870 PreviewAutomationClientDisconnectedError,
871 PreviewAutomationRequestQueueClosedError,
872 PreviewAutomationRemoteUnavailableError,
873 PreviewAutomationMalformedResponseError,
874]);
875export type PreviewAutomationError = typeof PreviewAutomationError.Type;
876​
877export const PreviewUrlResolution = Schema.Struct({
878 requestedUrl: Schema.String,
879 resolvedUrl: Schema.String,
880 resolutionKind: Schema.Literals(["direct", "direct-private-network"]),
881 environmentId: EnvironmentId,
882});
883export type PreviewUrlResolution = typeof PreviewUrlResolution.Type;