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