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

previewAutomation.ts

953 lines35.9 KB

1import { Schema } from "effect";
2​
3import { EnvironmentId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
4import {
5 PREVIEW_VIEWPORT_MAX_AREA,
6 PreviewRenderedViewportSize,
7 PreviewTabId,
8 PreviewViewportPresetId,
9 PreviewViewportSetting,
10 PreviewViewportSize,
11} from "./preview.ts";
12import { ProviderInstanceId } from "./providerInstance.ts";
13​
14const BoundedUrl = Schema.String.check(Schema.isTrimmed())
15 .check(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 liveTabs: Schema.optional(
594 Schema.Array(
595 Schema.Struct({
596 threadId: ThreadId,
597 tabId: PreviewTabId,
598 visible: Schema.optional(Schema.Boolean),
599 }),
600 ),
601 ),
602});
603export type PreviewAutomationHostFocus = typeof PreviewAutomationHostFocus.Type;
604​
605export const PreviewAutomationRequest = Schema.Struct({
606 requestId: TrimmedNonEmptyString,
607 threadId: ThreadId,
608 tabId: Schema.optional(PreviewTabId),
609 tabIdExplicit: Schema.optional(Schema.Boolean),
610 operation: PreviewAutomationOperation,
611 input: Schema.Unknown,
612 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
613});
614export type PreviewAutomationRequest = typeof PreviewAutomationRequest.Type;
615​
616export const PreviewAutomationStreamEvent = Schema.Union([
617 Schema.Struct({
618 type: Schema.Literal("connected"),
619 connectionId: PreviewAutomationConnectionId,
620 }),
621 Schema.Struct({
622 type: Schema.Literal("request"),
623 connectionId: PreviewAutomationConnectionId,
624 request: PreviewAutomationRequest,
625 }),
626]);
627export type PreviewAutomationStreamEvent = typeof PreviewAutomationStreamEvent.Type;
628​
629export const PreviewAutomationResponse = Schema.Struct({
630 clientId: PreviewAutomationClientId,
631 connectionId: PreviewAutomationConnectionId,
632 requestId: TrimmedNonEmptyString,
633 ok: Schema.Boolean,
634 result: Schema.optional(Schema.Unknown),
635 error: Schema.optional(
636 Schema.Struct({
637 _tag: TrimmedNonEmptyString,
638 message: Schema.String,
639 detail: Schema.optional(Schema.Unknown),
640 }),
641 ),
642});
643export type PreviewAutomationResponse = typeof PreviewAutomationResponse.Type;
644​
645const McpCapabilityErrorFields = {
646 environmentId: EnvironmentId,
647 threadId: ThreadId,
648 providerSessionId: TrimmedNonEmptyString,
649 providerInstanceId: ProviderInstanceId,
650};
651​
652/** Agents read this message, so it names the next step and not only the failure. */
653export class PreviewAutomationUnavailableError extends Schema.TaggedError<PreviewAutomationUnavailableError>()(
654 "PreviewAutomationUnavailableError",
655 {
656 capability: Schema.Literal("preview"),
657 ...McpCapabilityErrorFields,
658 },
659) {
660 override get message(): string {
661 return `MCP credential does not grant the ${this.capability} capability: browser preview tools are off for this thread. Do not retry them. To check a page, use a headless browser from the shell, such as Playwright, or curl. The user can turn on "Agent browser access" in Settings; it applies when the agent session next starts.`;
662 }
664​
665/** A `t3-code` MCP tool was called with a credential that does not carry its capability. */
666export class McpCapabilityUnavailableError extends Schema.TaggedError<McpCapabilityUnavailableError>()(
667 "McpCapabilityUnavailableError",
668 {
669 capability: TrimmedNonEmptyString,
670 ...McpCapabilityErrorFields,
671 },
672) {
673 override get message(): string {
674 return `MCP credential does not grant the ${this.capability} capability.`;
675 }
677​
678const PreviewAutomationScopeErrorFields = {
679 operation: PreviewAutomationOperation,
680 environmentId: EnvironmentId,
681 threadId: ThreadId,
682 providerSessionId: TrimmedNonEmptyString,
683 providerInstanceId: ProviderInstanceId,
684};
685​
686const PreviewAutomationRequestErrorFields = {
687 ...PreviewAutomationScopeErrorFields,
688 clientId: TrimmedNonEmptyString,
689 connectionId: PreviewAutomationConnectionId,
690 requestId: TrimmedNonEmptyString,
691 tabId: Schema.optional(PreviewTabId),
692 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
693};
694​
695const PreviewAutomationRemoteDiagnosticFields = {
696 remoteTag: TrimmedNonEmptyString,
697 remoteMessageLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
698 remoteDetailKind: Schema.optional(
699 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
700 ),
701 cause: Schema.Defect(),
702};
703​
704const PreviewAutomationOptionalRemoteDiagnosticFields = {
705 remoteTag: Schema.optional(TrimmedNonEmptyString),
706 remoteMessageLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
707 remoteDetailKind: Schema.optional(
708 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
709 ),
710 cause: Schema.optional(Schema.Defect()),
711};
712​
713export class PreviewAutomationNoAvailableHostError extends Schema.TaggedError<PreviewAutomationNoAvailableHostError>()(
714 "PreviewAutomationNoAvailableHostError",
715 {
716 ...PreviewAutomationScopeErrorFields,
717 clientId: Schema.optional(TrimmedNonEmptyString),
718 connectionId: Schema.optional(PreviewAutomationConnectionId),
719 requestId: Schema.optional(TrimmedNonEmptyString),
720 tabId: Schema.optional(PreviewTabId),
721 timeoutMs: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
722 ...PreviewAutomationOptionalRemoteDiagnosticFields,
723 },
724) {
725 override get message(): string {
726 return `No preview automation host is available for ${this.operation} in environment ${this.environmentId}. Preview tools run in a T3 Code desktop app that is open and connected to this environment; a headless server has no browser of its own. Do not retry. To check a page, use a headless browser from the shell, such as Playwright, or curl, or ask the user to open this thread in the T3 Code desktop app.`;
727 }
729​
730export class PreviewAutomationUnsupportedClientError extends Schema.TaggedError<PreviewAutomationUnsupportedClientError>()(
731 "PreviewAutomationUnsupportedClientError",
732 {
733 ...PreviewAutomationRequestErrorFields,
734 ...PreviewAutomationRemoteDiagnosticFields,
735 },
736) {
737 override get message(): string {
738 return `Preview automation client ${this.clientId} does not support ${this.operation}.`;
739 }
741​
742export class PreviewAutomationTabNotFoundError extends Schema.TaggedError<PreviewAutomationTabNotFoundError>()(
743 "PreviewAutomationTabNotFoundError",
744 {
745 ...PreviewAutomationRequestErrorFields,
746 ...PreviewAutomationRemoteDiagnosticFields,
747 },
748) {
749 override get message(): string {
750 return this.tabId
751 ? `Preview tab ${this.tabId} was not found for ${this.operation}. Omit tabId to use the current tab, or call preview_open.`
752 : `No active preview tab was found for ${this.operation}. Call preview_open first.`;
753 }
755​
756export class PreviewAutomationTimeoutError extends Schema.TaggedError<PreviewAutomationTimeoutError>()(
757 "PreviewAutomationTimeoutError",
758 {
759 ...PreviewAutomationRequestErrorFields,
760 ...PreviewAutomationOptionalRemoteDiagnosticFields,
761 },
762) {
763 override get message(): string {
764 const summary = `Preview automation ${this.operation} timed out after ${this.timeoutMs}ms.`;
765 return summary;
766 }
768​
769export class PreviewAutomationControlInterruptedError extends Schema.TaggedError<PreviewAutomationControlInterruptedError>()(
770 "PreviewAutomationControlInterruptedError",
771 {
772 ...PreviewAutomationRequestErrorFields,
773 ...PreviewAutomationRemoteDiagnosticFields,
774 },
775) {
776 override get message(): string {
777 return `Preview automation ${this.operation} was interrupted on client ${this.clientId}.`;
778 }
780​
781export class PreviewAutomationExecutionError extends Schema.TaggedError<PreviewAutomationExecutionError>()(
782 "PreviewAutomationExecutionError",
783 {
784 ...PreviewAutomationRequestErrorFields,
785 ...PreviewAutomationRemoteDiagnosticFields,
786 },
787) {
788 override get message(): string {
789 return `Preview automation ${this.operation} failed on client ${this.clientId}.`;
790 }
792​
793export class PreviewAutomationInvalidSelectorError extends Schema.TaggedError<PreviewAutomationInvalidSelectorError>()(
794 "PreviewAutomationInvalidSelectorError",
795 {
796 ...PreviewAutomationRequestErrorFields,
797 ...PreviewAutomationRemoteDiagnosticFields,
798 selectorKind: Schema.optional(Schema.Literals(["locator", "selector"])),
799 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
800 },
801) {
802 override get message(): string {
803 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
804 return `Preview automation ${this.operation} received an invalid ${this.selectorKind} (${this.selectorLength} characters).`;
805 }
806 return `Preview automation ${this.operation} received an invalid selector.`;
807 }
809​
810export class PreviewAutomationTargetNotEditableError extends Schema.TaggedError<PreviewAutomationTargetNotEditableError>()(
811 "PreviewAutomationTargetNotEditableError",
812 {
813 ...PreviewAutomationRequestErrorFields,
814 ...PreviewAutomationRemoteDiagnosticFields,
815 selectorKind: Schema.optional(Schema.Literals(["focused-element", "locator", "selector"])),
816 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
817 },
818) {
819 override get message(): string {
820 if (this.selectorKind === "focused-element") {
821 return `Preview automation ${this.operation} requires an editable focused element.`;
822 }
823 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
824 return `Preview automation ${this.operation} requires an editable ${this.selectorKind} (${this.selectorLength} characters).`;
825 }
826 return `Preview automation ${this.operation} requires an editable target.`;
827 }
829​
830export class PreviewAutomationResultTooLargeError extends Schema.TaggedError<PreviewAutomationResultTooLargeError>()(
831 "PreviewAutomationResultTooLargeError",
832 {
833 ...PreviewAutomationRequestErrorFields,
834 ...PreviewAutomationRemoteDiagnosticFields,
835 maximumBytes: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
836 },
837) {
838 override get message(): string {
839 const summary =
840 this.maximumBytes === undefined
841 ? `Preview automation ${this.operation} produced a result that is too large.`
842 : `Preview automation ${this.operation} produced a result larger than ${this.maximumBytes} bytes.`;
843 return summary;
844 }
846​
847export class PreviewAutomationClientDisconnectedError extends Schema.TaggedError<PreviewAutomationClientDisconnectedError>()(
848 "PreviewAutomationClientDisconnectedError",
849 PreviewAutomationRequestErrorFields,
850) {
851 override get message(): string {
852 return `Preview automation client ${this.clientId} disconnected during ${this.operation}.`;
853 }
855​
856export class PreviewAutomationRequestQueueClosedError extends Schema.TaggedError<PreviewAutomationRequestQueueClosedError>()(
857 "PreviewAutomationRequestQueueClosedError",
858 PreviewAutomationRequestErrorFields,
859) {
860 override get message(): string {
861 return `Preview automation client ${this.clientId} stopped accepting ${this.operation} requests.`;
862 }
864​
865export class PreviewAutomationRemoteUnavailableError extends Schema.TaggedError<PreviewAutomationRemoteUnavailableError>()(
866 "PreviewAutomationRemoteUnavailableError",
867 {
868 ...PreviewAutomationRequestErrorFields,
869 ...PreviewAutomationRemoteDiagnosticFields,
870 },
871) {
872 override get message(): string {
873 return `Preview automation ${this.operation} is unavailable on client ${this.clientId}.`;
874 }
876​
877export class PreviewAutomationMalformedResponseError extends Schema.TaggedError<PreviewAutomationMalformedResponseError>()(
878 "PreviewAutomationMalformedResponseError",
879 PreviewAutomationRequestErrorFields,
880) {
881 override get message(): string {
882 return `Preview automation client ${this.clientId} returned a malformed response for ${this.operation}.`;
883 }
885​
886export class PreviewAutomationRecordingTransferError extends Schema.TaggedError<PreviewAutomationRecordingTransferError>()(
887 "PreviewAutomationRecordingTransferError",
888 {
889 threadId: ThreadId,
890 cause: Schema.optional(Schema.Defect()),
891 },
892) {
893 override get message(): string {
894 return "Preview recording could not be saved to the agent environment. The saved copy remains on the desktop.";
895 }
897​
898export class PreviewAutomationRecordingDesktopUpdateRequiredError extends Schema.TaggedError<PreviewAutomationRecordingDesktopUpdateRequiredError>()(
899 "PreviewAutomationRecordingDesktopUpdateRequiredError",
900 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
901) {
902 override get message(): string {
903 return "Update the desktop app to transfer recordings. The recording remains on the desktop.";
904 }
906​
907export class PreviewAutomationRecordingTooLargeError extends Schema.TaggedError<PreviewAutomationRecordingTooLargeError>()(
908 "PreviewAutomationRecordingTooLargeError",
909 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
910) {
911 override get message(): string {
912 return "The recording exceeds 50 MiB. The saved copy remains on the desktop.";
913 }
915​
916export class PreviewAutomationRecordingDeadlineExpiredError extends Schema.TaggedError<PreviewAutomationRecordingDeadlineExpiredError>()(
917 "PreviewAutomationRecordingDeadlineExpiredError",
918 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
919) {
920 override get message(): string {
921 return "The recording transfer deadline expired. The saved copy remains on the desktop.";
922 }
924​
925export const PreviewAutomationError = Schema.Union([
926 PreviewAutomationRecordingTransferError,
927 PreviewAutomationRecordingDesktopUpdateRequiredError,
928 PreviewAutomationRecordingTooLargeError,
929 PreviewAutomationRecordingDeadlineExpiredError,
930 PreviewAutomationUnavailableError,
931 PreviewAutomationNoAvailableHostError,
932 PreviewAutomationUnsupportedClientError,
933 PreviewAutomationTabNotFoundError,
934 PreviewAutomationTimeoutError,
935 PreviewAutomationControlInterruptedError,
936 PreviewAutomationExecutionError,
937 PreviewAutomationInvalidSelectorError,
938 PreviewAutomationTargetNotEditableError,
939 PreviewAutomationResultTooLargeError,
940 PreviewAutomationClientDisconnectedError,
941 PreviewAutomationRequestQueueClosedError,
942 PreviewAutomationRemoteUnavailableError,
943 PreviewAutomationMalformedResponseError,
944]);
945export type PreviewAutomationError = typeof PreviewAutomationError.Type;
946​
947export const PreviewUrlResolution = Schema.Struct({
948 requestedUrl: Schema.String,
949 resolvedUrl: Schema.String,
950 resolutionKind: Schema.Literals(["direct", "direct-private-network"]),
951 environmentId: EnvironmentId,
952});
953export type PreviewUrlResolution = typeof PreviewUrlResolution.Type;