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

previewAutomation.ts

888 lines32.9 KB

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