Open History to see the last commit
1import { Schema } from "effect";
2
3import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
4import {
5 PREVIEW_VIEWPORT_MAX_AREA,
6 PreviewRenderedViewportSize,
7 PreviewTabId,
8 PreviewViewportPresetId,
9 PreviewViewportSetting,
10 PreviewViewportSize,
11} from "./preview.ts";
12import { ProviderInstanceId } from "./providerInstance.ts";
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 PREVIEW_RECORDING_STOP_TIMEOUT_MS = 120_000;
557
558export const PreviewAutomationRecordingArtifact = Schema.Struct({
559 id: Schema.String,
560 tabId: PreviewTabId,
561 path: Schema.String,
562 mimeType: Schema.String,
563 sizeBytes: Schema.Int,
564 createdAt: Schema.String,
565});
566export type PreviewAutomationRecordingArtifact = typeof PreviewAutomationRecordingArtifact.Type;
567
568export const PreviewAutomationClientId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
569export type PreviewAutomationClientId = typeof PreviewAutomationClientId.Type;
570export const PreviewAutomationConnectionId = TrimmedNonEmptyString.check(Schema.isMaxLength(64));
571export type PreviewAutomationConnectionId = typeof PreviewAutomationConnectionId.Type;
572
573export const PreviewAutomationHostIdentity = Schema.Struct({
574 clientId: PreviewAutomationClientId,
575 environmentId: EnvironmentId,
576});
577export type PreviewAutomationHostIdentity = typeof PreviewAutomationHostIdentity.Type;
578
579export const PreviewAutomationHost = Schema.Struct({
580 ...PreviewAutomationHostIdentity.fields,
581 /**
582 * Missing means the pre-capability-negotiation V1 operation set. This lets
583 * a newer server safely coexist with an older desktop during rollout.
584 */
585 supportedOperations: Schema.optional(Schema.Array(PreviewAutomationOperation)),
586});
587export type PreviewAutomationHost = typeof PreviewAutomationHost.Type;
588
589export const PreviewAutomationHostFocus = Schema.Struct({
590 ...PreviewAutomationHostIdentity.fields,
591 connectionId: PreviewAutomationConnectionId,
592 focused: Schema.Boolean,
593});
594export type PreviewAutomationHostFocus = typeof PreviewAutomationHostFocus.Type;
595
596export const PreviewAutomationRequest = Schema.Struct({
597 requestId: TrimmedNonEmptyString,
598 threadId: ThreadId,
599 tabId: Schema.optional(PreviewTabId),
600 tabIdExplicit: Schema.optional(Schema.Boolean),
601 operation: PreviewAutomationOperation,
602 input: Schema.Unknown,
603 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
604});
605export type PreviewAutomationRequest = typeof PreviewAutomationRequest.Type;
606
607export const PreviewAutomationStreamEvent = Schema.Union([
608 Schema.Struct({
609 type: Schema.Literal("connected"),
610 connectionId: PreviewAutomationConnectionId,
611 }),
612 Schema.Struct({
613 type: Schema.Literal("request"),
614 connectionId: PreviewAutomationConnectionId,
615 request: PreviewAutomationRequest,
616 }),
617]);
618export type PreviewAutomationStreamEvent = typeof PreviewAutomationStreamEvent.Type;
619
620export const PreviewAutomationResponse = Schema.Struct({
621 clientId: PreviewAutomationClientId,
622 connectionId: PreviewAutomationConnectionId,
623 requestId: TrimmedNonEmptyString,
624 ok: Schema.Boolean,
625 result: Schema.optional(Schema.Unknown),
626 error: Schema.optional(
627 Schema.Struct({
628 _tag: TrimmedNonEmptyString,
629 message: Schema.String,
630 detail: Schema.optional(Schema.Unknown),
631 }),
632 ),
633});
634export type PreviewAutomationResponse = typeof PreviewAutomationResponse.Type;
635
636export class PreviewAutomationUnavailableError extends Schema.TaggedError<PreviewAutomationUnavailableError>()(
637 "PreviewAutomationUnavailableError",
638 {
639 capability: Schema.Literal("preview"),
640 environmentId: EnvironmentId,
641 threadId: ThreadId,
642 providerSessionId: TrimmedNonEmptyString,
643 providerInstanceId: ProviderInstanceId,
644 },
645) {
646 override get message(): string {
647 return `MCP credential does not grant the ${this.capability} capability.`;
648 }
649}
650
651const PreviewAutomationScopeErrorFields = {
652 operation: PreviewAutomationOperation,
653 environmentId: EnvironmentId,
654 threadId: ThreadId,
655 providerSessionId: TrimmedNonEmptyString,
656 providerInstanceId: ProviderInstanceId,
657};
658
659const PreviewAutomationRequestErrorFields = {
660 ...PreviewAutomationScopeErrorFields,
661 clientId: TrimmedNonEmptyString,
662 connectionId: PreviewAutomationConnectionId,
663 requestId: TrimmedNonEmptyString,
664 tabId: Schema.optional(PreviewTabId),
665 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
666};
667
668const PreviewAutomationRemoteDiagnosticFields = {
669 remoteTag: TrimmedNonEmptyString,
670 remoteMessageLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
671 remoteDetailKind: Schema.optional(
672 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
673 ),
674 cause: Schema.Defect(),
675};
676
677const PreviewAutomationOptionalRemoteDiagnosticFields = {
678 remoteTag: Schema.optional(TrimmedNonEmptyString),
679 remoteMessageLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
680 remoteDetailKind: Schema.optional(
681 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
682 ),
683 cause: Schema.optional(Schema.Defect()),
684};
685
686export class PreviewAutomationNoAvailableHostError extends Schema.TaggedError<PreviewAutomationNoAvailableHostError>()(
687 "PreviewAutomationNoAvailableHostError",
688 {
689 ...PreviewAutomationScopeErrorFields,
690 clientId: Schema.optional(TrimmedNonEmptyString),
691 connectionId: Schema.optional(PreviewAutomationConnectionId),
692 requestId: Schema.optional(TrimmedNonEmptyString),
693 tabId: Schema.optional(PreviewTabId),
694 timeoutMs: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
695 ...PreviewAutomationOptionalRemoteDiagnosticFields,
696 },
697) {
698 override get message(): string {
699 const summary = `No preview automation host is available for ${this.operation} in environment ${this.environmentId}.`;
700 return summary;
701 }
702}
703
704export class PreviewAutomationUnsupportedClientError extends Schema.TaggedError<PreviewAutomationUnsupportedClientError>()(
705 "PreviewAutomationUnsupportedClientError",
706 {
707 ...PreviewAutomationRequestErrorFields,
708 ...PreviewAutomationRemoteDiagnosticFields,
709 },
710) {
711 override get message(): string {
712 return `Preview automation client ${this.clientId} does not support ${this.operation}.`;
713 }
714}
715
716export class PreviewAutomationTabNotFoundError extends Schema.TaggedError<PreviewAutomationTabNotFoundError>()(
717 "PreviewAutomationTabNotFoundError",
718 {
719 ...PreviewAutomationRequestErrorFields,
720 ...PreviewAutomationRemoteDiagnosticFields,
721 },
722) {
723 override get message(): string {
724 const summary = this.tabId
725 ? `Preview tab ${this.tabId} was not found for ${this.operation}.`
726 : `No active preview tab was found for ${this.operation}.`;
727 return summary;
728 }
729}
730
731export class PreviewAutomationTimeoutError extends Schema.TaggedError<PreviewAutomationTimeoutError>()(
732 "PreviewAutomationTimeoutError",
733 {
734 ...PreviewAutomationRequestErrorFields,
735 ...PreviewAutomationOptionalRemoteDiagnosticFields,
736 },
737) {
738 override get message(): string {
739 const summary = `Preview automation ${this.operation} timed out after ${this.timeoutMs}ms.`;
740 return summary;
741 }
742}
743
744export class PreviewAutomationControlInterruptedError extends Schema.TaggedError<PreviewAutomationControlInterruptedError>()(
745 "PreviewAutomationControlInterruptedError",
746 {
747 ...PreviewAutomationRequestErrorFields,
748 ...PreviewAutomationRemoteDiagnosticFields,
749 },
750) {
751 override get message(): string {
752 return `Preview automation ${this.operation} was interrupted on client ${this.clientId}.`;
753 }
754}
755
756export class PreviewAutomationExecutionError extends Schema.TaggedError<PreviewAutomationExecutionError>()(
757 "PreviewAutomationExecutionError",
758 {
759 ...PreviewAutomationRequestErrorFields,
760 ...PreviewAutomationRemoteDiagnosticFields,
761 },
762) {
763 override get message(): string {
764 return `Preview automation ${this.operation} failed on client ${this.clientId}.`;
765 }
766}
767
768export class PreviewAutomationInvalidSelectorError extends Schema.TaggedError<PreviewAutomationInvalidSelectorError>()(
769 "PreviewAutomationInvalidSelectorError",
770 {
771 ...PreviewAutomationRequestErrorFields,
772 ...PreviewAutomationRemoteDiagnosticFields,
773 selectorKind: Schema.optional(Schema.Literals(["locator", "selector"])),
774 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
775 },
776) {
777 override get message(): string {
778 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
779 return `Preview automation ${this.operation} received an invalid ${this.selectorKind} (${this.selectorLength} characters).`;
780 }
781 return `Preview automation ${this.operation} received an invalid selector.`;
782 }
783}
784
785export class PreviewAutomationTargetNotEditableError extends Schema.TaggedError<PreviewAutomationTargetNotEditableError>()(
786 "PreviewAutomationTargetNotEditableError",
787 {
788 ...PreviewAutomationRequestErrorFields,
789 ...PreviewAutomationRemoteDiagnosticFields,
790 selectorKind: Schema.optional(Schema.Literals(["focused-element", "locator", "selector"])),
791 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
792 },
793) {
794 override get message(): string {
795 if (this.selectorKind === "focused-element") {
796 return `Preview automation ${this.operation} requires an editable focused element.`;
797 }
798 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
799 return `Preview automation ${this.operation} requires an editable ${this.selectorKind} (${this.selectorLength} characters).`;
800 }
801 return `Preview automation ${this.operation} requires an editable target.`;
802 }
803}
804
805export class PreviewAutomationResultTooLargeError extends Schema.TaggedError<PreviewAutomationResultTooLargeError>()(
806 "PreviewAutomationResultTooLargeError",
807 {
808 ...PreviewAutomationRequestErrorFields,
809 ...PreviewAutomationRemoteDiagnosticFields,
810 maximumBytes: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
811 },
812) {
813 override get message(): string {
814 const summary =
815 this.maximumBytes === undefined
816 ? `Preview automation ${this.operation} produced a result that is too large.`
817 : `Preview automation ${this.operation} produced a result larger than ${this.maximumBytes} bytes.`;
818 return summary;
819 }
820}
821
822export class PreviewAutomationClientDisconnectedError extends Schema.TaggedError<PreviewAutomationClientDisconnectedError>()(
823 "PreviewAutomationClientDisconnectedError",
824 PreviewAutomationRequestErrorFields,
825) {
826 override get message(): string {
827 return `Preview automation client ${this.clientId} disconnected during ${this.operation}.`;
828 }
829}
830
831export class PreviewAutomationRequestQueueClosedError extends Schema.TaggedError<PreviewAutomationRequestQueueClosedError>()(
832 "PreviewAutomationRequestQueueClosedError",
833 PreviewAutomationRequestErrorFields,
834) {
835 override get message(): string {
836 return `Preview automation client ${this.clientId} stopped accepting ${this.operation} requests.`;
837 }
838}
839
840export class PreviewAutomationRemoteUnavailableError extends Schema.TaggedError<PreviewAutomationRemoteUnavailableError>()(
841 "PreviewAutomationRemoteUnavailableError",
842 {
843 ...PreviewAutomationRequestErrorFields,
844 ...PreviewAutomationRemoteDiagnosticFields,
845 },
846) {
847 override get message(): string {
848 return `Preview automation ${this.operation} is unavailable on client ${this.clientId}.`;
849 }
850}
851
852export class PreviewAutomationMalformedResponseError extends Schema.TaggedError<PreviewAutomationMalformedResponseError>()(
853 "PreviewAutomationMalformedResponseError",
854 PreviewAutomationRequestErrorFields,
855) {
856 override get message(): string {
857 return `Preview automation client ${this.clientId} returned a malformed response for ${this.operation}.`;
858 }
859}
860
861export class PreviewAutomationRecordingTransferError extends Schema.TaggedError<PreviewAutomationRecordingTransferError>()(
862 "PreviewAutomationRecordingTransferError",
863 {
864 threadId: ThreadId,
865 cause: Schema.optional(Schema.Defect()),
866 },
867) {
868 override get message(): string {
869 return "Preview recording could not be saved to the agent environment. The saved copy remains on the desktop.";
870 }
871}
872
873export class PreviewAutomationRecordingDesktopUpdateRequiredError extends Schema.TaggedError<PreviewAutomationRecordingDesktopUpdateRequiredError>()(
874 "PreviewAutomationRecordingDesktopUpdateRequiredError",
875 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
876) {
877 override get message(): string {
878 return "Update the desktop app to transfer recordings. The recording remains on the desktop.";
879 }
880}
881
882export class PreviewAutomationRecordingTooLargeError extends Schema.TaggedError<PreviewAutomationRecordingTooLargeError>()(
883 "PreviewAutomationRecordingTooLargeError",
884 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
885) {
886 override get message(): string {
887 return "The recording exceeds 50 MiB. The saved copy remains on the desktop.";
888 }
889}
890
891export class PreviewAutomationRecordingDeadlineExpiredError extends Schema.TaggedError<PreviewAutomationRecordingDeadlineExpiredError>()(
892 "PreviewAutomationRecordingDeadlineExpiredError",
893 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
894) {
895 override get message(): string {
896 return "The recording transfer deadline expired. The saved copy remains on the desktop.";
897 }
898}
899
900export const PreviewAutomationError = Schema.Union([
901 PreviewAutomationRecordingTransferError,
902 PreviewAutomationRecordingDesktopUpdateRequiredError,
903 PreviewAutomationRecordingTooLargeError,
904 PreviewAutomationRecordingDeadlineExpiredError,
905 PreviewAutomationUnavailableError,
906 PreviewAutomationNoAvailableHostError,
907 PreviewAutomationUnsupportedClientError,
908 PreviewAutomationTabNotFoundError,
909 PreviewAutomationTimeoutError,
910 PreviewAutomationControlInterruptedError,
911 PreviewAutomationExecutionError,
912 PreviewAutomationInvalidSelectorError,
913 PreviewAutomationTargetNotEditableError,
914 PreviewAutomationResultTooLargeError,
915 PreviewAutomationClientDisconnectedError,
916 PreviewAutomationRequestQueueClosedError,
917 PreviewAutomationRemoteUnavailableError,
918 PreviewAutomationMalformedResponseError,
919]);
920export type PreviewAutomationError = typeof PreviewAutomationError.Type;
921
922export const PreviewUrlResolution = Schema.Struct({
923 requestedUrl: Schema.String,
924 resolvedUrl: Schema.String,
925 resolutionKind: Schema.Literals(["direct", "direct-private-network"]),
926 environmentId: EnvironmentId,
927});
928export type PreviewUrlResolution = typeof PreviewUrlResolution.Type;