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

previewAutomation.ts

954 lines36.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 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​
645// Thread fields are absent when the caller signed in from outside a T3 thread.
646const McpCapabilityErrorFields = {
647 environmentId: EnvironmentId,
648 threadId: Schema.optional(ThreadId),
649 providerSessionId: Schema.optional(TrimmedNonEmptyString),
650 providerInstanceId: Schema.optional(ProviderInstanceId),
651};
652​
653/** Agents read this message, so it names the next step and not only the failure. */
654export class PreviewAutomationUnavailableError extends Schema.TaggedError<PreviewAutomationUnavailableError>()(
655 "PreviewAutomationUnavailableError",
656 {
657 capability: Schema.Literal("preview"),
658 ...McpCapabilityErrorFields,
659 },
660) {
661 override get message(): string {
662 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.`;
663 }
665​
666/** A `t3-code` MCP tool was called with a credential that does not carry its capability. */
667export class McpCapabilityUnavailableError extends Schema.TaggedError<McpCapabilityUnavailableError>()(
668 "McpCapabilityUnavailableError",
669 {
670 capability: TrimmedNonEmptyString,
671 ...McpCapabilityErrorFields,
672 },
673) {
674 override get message(): string {
675 return `MCP credential does not grant the ${this.capability} capability.`;
676 }
678​
679const PreviewAutomationScopeErrorFields = {
680 operation: PreviewAutomationOperation,
681 environmentId: EnvironmentId,
682 threadId: ThreadId,
683 providerSessionId: TrimmedNonEmptyString,
684 providerInstanceId: ProviderInstanceId,
685};
686​
687const PreviewAutomationRequestErrorFields = {
688 ...PreviewAutomationScopeErrorFields,
689 clientId: TrimmedNonEmptyString,
690 connectionId: PreviewAutomationConnectionId,
691 requestId: TrimmedNonEmptyString,
692 tabId: Schema.optional(PreviewTabId),
693 timeoutMs: Schema.Int.check(Schema.isGreaterThan(0)),
694};
695​
696const PreviewAutomationRemoteDiagnosticFields = {
697 remoteTag: TrimmedNonEmptyString,
698 remoteMessageLength: Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)),
699 remoteDetailKind: Schema.optional(
700 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
701 ),
702 cause: Schema.Defect(),
703};
704​
705const PreviewAutomationOptionalRemoteDiagnosticFields = {
706 remoteTag: Schema.optional(TrimmedNonEmptyString),
707 remoteMessageLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
708 remoteDetailKind: Schema.optional(
709 Schema.Literals(["null", "array", "object", "string", "number", "boolean"]),
710 ),
711 cause: Schema.optional(Schema.Defect()),
712};
713​
714export class PreviewAutomationNoAvailableHostError extends Schema.TaggedError<PreviewAutomationNoAvailableHostError>()(
715 "PreviewAutomationNoAvailableHostError",
716 {
717 ...PreviewAutomationScopeErrorFields,
718 clientId: Schema.optional(TrimmedNonEmptyString),
719 connectionId: Schema.optional(PreviewAutomationConnectionId),
720 requestId: Schema.optional(TrimmedNonEmptyString),
721 tabId: Schema.optional(PreviewTabId),
722 timeoutMs: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
723 ...PreviewAutomationOptionalRemoteDiagnosticFields,
724 },
725) {
726 override get message(): string {
727 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.`;
728 }
730​
731export class PreviewAutomationUnsupportedClientError extends Schema.TaggedError<PreviewAutomationUnsupportedClientError>()(
732 "PreviewAutomationUnsupportedClientError",
733 {
734 ...PreviewAutomationRequestErrorFields,
735 ...PreviewAutomationRemoteDiagnosticFields,
736 },
737) {
738 override get message(): string {
739 return `Preview automation client ${this.clientId} does not support ${this.operation}.`;
740 }
742​
743export class PreviewAutomationTabNotFoundError extends Schema.TaggedError<PreviewAutomationTabNotFoundError>()(
744 "PreviewAutomationTabNotFoundError",
745 {
746 ...PreviewAutomationRequestErrorFields,
747 ...PreviewAutomationRemoteDiagnosticFields,
748 },
749) {
750 override get message(): string {
751 return this.tabId
752 ? `Preview tab ${this.tabId} was not found for ${this.operation}. Omit tabId to use the current tab, or call preview_open.`
753 : `No active preview tab was found for ${this.operation}. Call preview_open first.`;
754 }
756​
757export class PreviewAutomationTimeoutError extends Schema.TaggedError<PreviewAutomationTimeoutError>()(
758 "PreviewAutomationTimeoutError",
759 {
760 ...PreviewAutomationRequestErrorFields,
761 ...PreviewAutomationOptionalRemoteDiagnosticFields,
762 },
763) {
764 override get message(): string {
765 const summary = `Preview automation ${this.operation} timed out after ${this.timeoutMs}ms.`;
766 return summary;
767 }
769​
770export class PreviewAutomationControlInterruptedError extends Schema.TaggedError<PreviewAutomationControlInterruptedError>()(
771 "PreviewAutomationControlInterruptedError",
772 {
773 ...PreviewAutomationRequestErrorFields,
774 ...PreviewAutomationRemoteDiagnosticFields,
775 },
776) {
777 override get message(): string {
778 return `Preview automation ${this.operation} was interrupted on client ${this.clientId}.`;
779 }
781​
782export class PreviewAutomationExecutionError extends Schema.TaggedError<PreviewAutomationExecutionError>()(
783 "PreviewAutomationExecutionError",
784 {
785 ...PreviewAutomationRequestErrorFields,
786 ...PreviewAutomationRemoteDiagnosticFields,
787 },
788) {
789 override get message(): string {
790 return `Preview automation ${this.operation} failed on client ${this.clientId}.`;
791 }
793​
794export class PreviewAutomationInvalidSelectorError extends Schema.TaggedError<PreviewAutomationInvalidSelectorError>()(
795 "PreviewAutomationInvalidSelectorError",
796 {
797 ...PreviewAutomationRequestErrorFields,
798 ...PreviewAutomationRemoteDiagnosticFields,
799 selectorKind: Schema.optional(Schema.Literals(["locator", "selector"])),
800 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
801 },
802) {
803 override get message(): string {
804 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
805 return `Preview automation ${this.operation} received an invalid ${this.selectorKind} (${this.selectorLength} characters).`;
806 }
807 return `Preview automation ${this.operation} received an invalid selector.`;
808 }
810​
811export class PreviewAutomationTargetNotEditableError extends Schema.TaggedError<PreviewAutomationTargetNotEditableError>()(
812 "PreviewAutomationTargetNotEditableError",
813 {
814 ...PreviewAutomationRequestErrorFields,
815 ...PreviewAutomationRemoteDiagnosticFields,
816 selectorKind: Schema.optional(Schema.Literals(["focused-element", "locator", "selector"])),
817 selectorLength: Schema.optional(Schema.Int.check(Schema.isGreaterThanOrEqualTo(0))),
818 },
819) {
820 override get message(): string {
821 if (this.selectorKind === "focused-element") {
822 return `Preview automation ${this.operation} requires an editable focused element.`;
823 }
824 if (this.selectorKind !== undefined && this.selectorLength !== undefined) {
825 return `Preview automation ${this.operation} requires an editable ${this.selectorKind} (${this.selectorLength} characters).`;
826 }
827 return `Preview automation ${this.operation} requires an editable target.`;
828 }
830​
831export class PreviewAutomationResultTooLargeError extends Schema.TaggedError<PreviewAutomationResultTooLargeError>()(
832 "PreviewAutomationResultTooLargeError",
833 {
834 ...PreviewAutomationRequestErrorFields,
835 ...PreviewAutomationRemoteDiagnosticFields,
836 maximumBytes: Schema.optional(Schema.Int.check(Schema.isGreaterThan(0))),
837 },
838) {
839 override get message(): string {
840 const summary =
841 this.maximumBytes === undefined
842 ? `Preview automation ${this.operation} produced a result that is too large.`
843 : `Preview automation ${this.operation} produced a result larger than ${this.maximumBytes} bytes.`;
844 return summary;
845 }
847​
848export class PreviewAutomationClientDisconnectedError extends Schema.TaggedError<PreviewAutomationClientDisconnectedError>()(
849 "PreviewAutomationClientDisconnectedError",
850 PreviewAutomationRequestErrorFields,
851) {
852 override get message(): string {
853 return `Preview automation client ${this.clientId} disconnected during ${this.operation}.`;
854 }
856​
857export class PreviewAutomationRequestQueueClosedError extends Schema.TaggedError<PreviewAutomationRequestQueueClosedError>()(
858 "PreviewAutomationRequestQueueClosedError",
859 PreviewAutomationRequestErrorFields,
860) {
861 override get message(): string {
862 return `Preview automation client ${this.clientId} stopped accepting ${this.operation} requests.`;
863 }
865​
866export class PreviewAutomationRemoteUnavailableError extends Schema.TaggedError<PreviewAutomationRemoteUnavailableError>()(
867 "PreviewAutomationRemoteUnavailableError",
868 {
869 ...PreviewAutomationRequestErrorFields,
870 ...PreviewAutomationRemoteDiagnosticFields,
871 },
872) {
873 override get message(): string {
874 return `Preview automation ${this.operation} is unavailable on client ${this.clientId}.`;
875 }
877​
878export class PreviewAutomationMalformedResponseError extends Schema.TaggedError<PreviewAutomationMalformedResponseError>()(
879 "PreviewAutomationMalformedResponseError",
880 PreviewAutomationRequestErrorFields,
881) {
882 override get message(): string {
883 return `Preview automation client ${this.clientId} returned a malformed response for ${this.operation}.`;
884 }
886​
887export class PreviewAutomationRecordingTransferError extends Schema.TaggedError<PreviewAutomationRecordingTransferError>()(
888 "PreviewAutomationRecordingTransferError",
889 {
890 threadId: ThreadId,
891 cause: Schema.optional(Schema.Defect()),
892 },
893) {
894 override get message(): string {
895 return "Preview recording could not be saved to the agent environment. The saved copy remains on the desktop.";
896 }
898​
899export class PreviewAutomationRecordingDesktopUpdateRequiredError extends Schema.TaggedError<PreviewAutomationRecordingDesktopUpdateRequiredError>()(
900 "PreviewAutomationRecordingDesktopUpdateRequiredError",
901 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
902) {
903 override get message(): string {
904 return "Update the desktop app to transfer recordings. The recording remains on the desktop.";
905 }
907​
908export class PreviewAutomationRecordingTooLargeError extends Schema.TaggedError<PreviewAutomationRecordingTooLargeError>()(
909 "PreviewAutomationRecordingTooLargeError",
910 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
911) {
912 override get message(): string {
913 return "The recording exceeds 50 MiB. The saved copy remains on the desktop.";
914 }
916​
917export class PreviewAutomationRecordingDeadlineExpiredError extends Schema.TaggedError<PreviewAutomationRecordingDeadlineExpiredError>()(
918 "PreviewAutomationRecordingDeadlineExpiredError",
919 { threadId: ThreadId, cause: Schema.optional(Schema.Defect()) },
920) {
921 override get message(): string {
922 return "The recording transfer deadline expired. The saved copy remains on the desktop.";
923 }
925​
926export const PreviewAutomationError = Schema.Union([
927 PreviewAutomationRecordingTransferError,
928 PreviewAutomationRecordingDesktopUpdateRequiredError,
929 PreviewAutomationRecordingTooLargeError,
930 PreviewAutomationRecordingDeadlineExpiredError,
931 PreviewAutomationUnavailableError,
932 PreviewAutomationNoAvailableHostError,
933 PreviewAutomationUnsupportedClientError,
934 PreviewAutomationTabNotFoundError,
935 PreviewAutomationTimeoutError,
936 PreviewAutomationControlInterruptedError,
937 PreviewAutomationExecutionError,
938 PreviewAutomationInvalidSelectorError,
939 PreviewAutomationTargetNotEditableError,
940 PreviewAutomationResultTooLargeError,
941 PreviewAutomationClientDisconnectedError,
942 PreviewAutomationRequestQueueClosedError,
943 PreviewAutomationRemoteUnavailableError,
944 PreviewAutomationMalformedResponseError,
945]);
946export type PreviewAutomationError = typeof PreviewAutomationError.Type;
947​
948export const PreviewUrlResolution = Schema.Struct({
949 requestedUrl: Schema.String,
950 resolvedUrl: Schema.String,
951 resolutionKind: Schema.Literals(["direct", "direct-private-network"]),
952 environmentId: EnvironmentId,
953});
954export type PreviewUrlResolution = typeof PreviewUrlResolution.Type;