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

previewAutomation.ts

945 lines35.0 KB

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