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

device.ts

546 lines17.9 KB

1/**
2 * Device - Schemas for first-class iOS Simulator and Android Emulator support.
3 *
4 * The server owns device discovery, the streaming helper (expo-device-hub),
5 * and the agent driver (agent-device). Clients render the live screen from the
6 * server-proxied stream, and agents reach devices through the `device_*` MCP
7 * tools plus the `agent-device` CLI the server preconfigures for them.
8 *
9 * Devices live on a *host*. Only the local host (the machine the server runs
10 * on) exists today; the host id is carried everywhere so SSH and cloud hosts
11 * can be added without changing the client contract.
12 *
13 * @module Device
14 */
15import { Schema } from "effect";
16​
17import { ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts";
18​
19export const DevicePlatform = Schema.Literals(["ios", "android"]);
20export type DevicePlatform = typeof DevicePlatform.Type;
21​
22export const DeviceHostId = TrimmedNonEmptyString.check(Schema.isMaxLength(128));
23export type DeviceHostId = typeof DeviceHostId.Type;
24​
25/** The server machine. Always present; other host kinds are future work. */
26export const LOCAL_DEVICE_HOST_ID = "local" as DeviceHostId;
27​
28/** SSH aliases and key paths are resolved on the environment server. */
29export const SshDeviceHostConfig = Schema.Struct({
30 id: DeviceHostId.check(
31 Schema.isPattern(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/),
32 Schema.makeFilter((id) => id !== "local" || "The local host id is reserved."),
33 ),
34 label: TrimmedNonEmptyString,
35 target: TrimmedNonEmptyString.check(Schema.isPattern(/^[^\s-][^\s]*$/)),
36 identityFile: Schema.optional(TrimmedNonEmptyString),
37 port: Schema.optional(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
38});
39export type SshDeviceHostConfig = typeof SshDeviceHostConfig.Type;
40​
41export const SshDeviceHostConfigs = Schema.Array(SshDeviceHostConfig).check(
42 Schema.makeFilter(
43 (hosts) =>
44 new Set(hosts.map((host) => host.id)).size === hosts.length ||
45 "Device host ids must be unique.",
46 ),
47);
48​
49/** Simulator udid or adb serial (an AVD name while it is not running). */
50export const DeviceId = TrimmedNonEmptyString.check(Schema.isMaxLength(256));
51export type DeviceId = typeof DeviceId.Type;
52​
53export const DeviceSummary = Schema.Struct({
54 hostId: DeviceHostId,
55 id: DeviceId,
56 platform: DevicePlatform,
57 name: TrimmedNonEmptyString,
58 /** OS label such as "iOS 18.0" or "Android 15.0". */
59 version: Schema.String,
60 booted: Schema.Boolean,
61 physical: Schema.Boolean,
62});
63export type DeviceSummary = typeof DeviceSummary.Type;
64​
65/**
66 * What the host can do right now. Platforms missing their toolchain are
67 * reported rather than hidden so the picker and the agent can explain why a
68 * platform is absent instead of showing an empty list.
69 */
70export const DevicePlatformAvailability = Schema.Struct({
71 platform: DevicePlatform,
72 available: Schema.Boolean,
73 reason: Schema.optional(Schema.String),
74});
75export type DevicePlatformAvailability = typeof DevicePlatformAvailability.Type;
76​
77export const DeviceHostSummary = Schema.Struct({
78 id: DeviceHostId,
79 kind: Schema.Literals(["local", "ssh"]),
80 label: TrimmedNonEmptyString,
81 platforms: Schema.Array(DevicePlatformAvailability),
82 hubInstalled: Schema.Boolean,
83 agentDeviceInstalled: Schema.Boolean,
84});
85export type DeviceHostSummary = typeof DeviceHostSummary.Type;
86​
87/**
88 * Lifecycle of the helper processes on a host. Tools are installed on first
89 * use, so a fresh install spends a while in `installing` before any device can
90 * stream; the UI shows that instead of an empty picker.
91 */
92export const DeviceHostStatus = Schema.Literals([
93 "disabled",
94 "idle",
95 "installing",
96 "starting",
97 "ready",
98 "failed",
99]);
100export type DeviceHostStatus = typeof DeviceHostStatus.Type;
101​
102/**
103 * A device a thread is looking at. One session per (thread, device); the same
104 * device may be open in several threads, since the stream is shared.
105 */
106export const DeviceSession = Schema.Struct({
107 threadId: ThreadId,
108 hostId: DeviceHostId,
109 deviceId: DeviceId,
110 platform: DevicePlatform,
111 openedAt: Schema.String,
112});
113export type DeviceSession = typeof DeviceSession.Type;
114​
115export const DeviceServiceState = Schema.Struct({
116 hosts: Schema.Array(DeviceHostSummary),
117 hostStatus: DeviceHostStatus,
118 hostStatusDetail: Schema.optional(Schema.String),
119 hostStatuses: Schema.Record(
120 DeviceHostId,
121 Schema.Struct({
122 status: DeviceHostStatus,
123 detail: Schema.optional(Schema.String),
124 }),
125 ),
126 devices: Schema.Array(DeviceSummary),
127 sessions: Schema.Array(DeviceSession),
128 bootingDevices: Schema.optional(
129 Schema.Array(Schema.Struct({ ...DeviceSummary.fields, threadId: ThreadId })),
130 ),
131 onboardingCompleted: Schema.Boolean,
132 agentAccessEnabled: Schema.Boolean,
133 /** Origin-relative path the client prefixes to hub routes. */
134 hubBasePath: Schema.String,
135 revision: Schema.Int,
136});
137export type DeviceServiceState = typeof DeviceServiceState.Type;
138​
139export const DeviceListInput = Schema.Struct({});
140export type DeviceListInput = typeof DeviceListInput.Type;
141​
142export const DeviceConfigureInput = Schema.Struct({
143 enabled: Schema.optional(Schema.Boolean),
144 agentAccessEnabled: Schema.optional(Schema.Boolean),
145 onboardingCompleted: Schema.optional(Schema.Boolean),
146});
147export type DeviceConfigureInput = typeof DeviceConfigureInput.Type;
148​
149export const DeviceOpenInput = Schema.Struct({
150 threadId: ThreadId,
151 hostId: Schema.optional(DeviceHostId),
152 deviceId: DeviceId,
153 platform: DevicePlatform,
154 /** Boot the simulator or emulator when it is not running. Defaults to true. */
155 boot: Schema.optional(Schema.Boolean),
156});
157export type DeviceOpenInput = typeof DeviceOpenInput.Type;
158​
159export const DeviceCloseInput = Schema.Struct({
160 hostId: Schema.optional(DeviceHostId),
161 threadId: ThreadId,
162 /** Omit to close every device session for the thread. */
163 deviceId: Schema.optional(DeviceId),
164 /** Also shut the simulator or emulator down. Defaults to false. */
165 shutdown: Schema.optional(Schema.Boolean),
166});
167export type DeviceCloseInput = typeof DeviceCloseInput.Type;
168​
169export const DeviceShutdownInput = Schema.Struct({
170 hostId: Schema.optional(DeviceHostId),
171 deviceId: DeviceId,
172 platform: DevicePlatform,
173});
174export type DeviceShutdownInput = typeof DeviceShutdownInput.Type;
175​
176// Device settings and actions. Each setting names the platforms that support
177// it; the panel hides the rest. Values are normalized across platforms where
178// both have the concept (appearance, text size) and platform-specific where
179// only one does.
180​
181export const DeviceAppearance = Schema.Literals(["light", "dark"]);
182export type DeviceAppearance = typeof DeviceAppearance.Type;
183​
184/**
185 * iOS content-size categories map onto twelve steps; Android `font_scale`
186 * is continuous. Four shared steps cover what people actually reach for.
187 */
188export const DeviceTextSize = Schema.Literals(["small", "default", "large", "extra-large"]);
189export type DeviceTextSize = typeof DeviceTextSize.Type;
190​
191export const DeviceColorFilter = Schema.Literals([
192 "none",
193 "grayscale",
194 "red-green",
195 "green-red",
196 "blue-yellow",
197]);
198export type DeviceColorFilter = typeof DeviceColorFilter.Type;
199​
200export const DeviceOrientation = Schema.Literals([
201 "portrait",
202 "landscape_left",
203 "portrait_upside_down",
204 "landscape_right",
205]);
206export type DeviceOrientation = typeof DeviceOrientation.Type;
207​
208/** Current values as read from the device; `undefined` means unsupported or unread. */
209export const DeviceSettings = Schema.Struct({
210 appearance: Schema.optional(DeviceAppearance),
211 textSize: Schema.optional(DeviceTextSize),
212 reduceMotion: Schema.optional(Schema.Boolean),
213 increaseContrast: Schema.optional(Schema.Boolean),
214 reduceTransparency: Schema.optional(Schema.Boolean),
215 showBorders: Schema.optional(Schema.Boolean),
216 voiceOver: Schema.optional(Schema.Boolean),
217 liquidGlass: Schema.optional(Schema.Literals(["clear", "tinted"])),
218 colorFilter: Schema.optional(DeviceColorFilter),
219 networkEnabled: Schema.optional(Schema.Boolean),
220 location: Schema.optional(
221 Schema.NullOr(Schema.Struct({ latitude: Schema.Number, longitude: Schema.Number })),
222 ),
223});
224export type DeviceSettings = typeof DeviceSettings.Type;
225​
226/** The app in the foreground, when the platform can tell us. */
227export const DeviceForegroundApp = Schema.Struct({
228 id: Schema.String,
229 name: Schema.optional(Schema.String),
230 version: Schema.optional(Schema.String),
231});
232export type DeviceForegroundApp = typeof DeviceForegroundApp.Type;
233​
234export const DeviceDetail = Schema.Struct({
235 hostId: DeviceHostId,
236 deviceId: DeviceId,
237 settings: DeviceSettings,
238 foregroundApp: Schema.NullOr(DeviceForegroundApp),
239 readAt: Schema.String,
240});
241export type DeviceDetail = typeof DeviceDetail.Type;
242​
243export const DevicePermission = Schema.Literals([
244 "camera",
245 "microphone",
246 "photos",
247 "contacts",
248 "calendar",
249 "reminders",
250 "location",
251 "notifications",
252 "motion",
253 "media-library",
254 "faceid",
255]);
256export type DevicePermission = typeof DevicePermission.Type;
257​
258const DeviceTarget = {
259 hostId: Schema.optional(DeviceHostId),
260 deviceId: DeviceId,
261};
262​
263export const DeviceActionInput = Schema.Union([
264 Schema.Struct({
265 ...DeviceTarget,
266 type: Schema.Literal("setAppearance"),
267 value: DeviceAppearance,
268 }),
269 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("setTextSize"), value: DeviceTextSize }),
270 Schema.Struct({
271 ...DeviceTarget,
272 type: Schema.Literal("setToggle"),
273 setting: Schema.Literals([
274 "reduceMotion",
275 "increaseContrast",
276 "reduceTransparency",
277 "showBorders",
278 "voiceOver",
279 "networkEnabled",
280 ]),
281 value: Schema.Boolean,
282 }),
283 Schema.Struct({
284 ...DeviceTarget,
285 type: Schema.Literal("setLiquidGlass"),
286 value: Schema.Literals(["clear", "tinted"]),
287 }),
288 Schema.Struct({
289 ...DeviceTarget,
290 type: Schema.Literal("setColorFilter"),
291 value: DeviceColorFilter,
292 }),
293 Schema.Struct({
294 ...DeviceTarget,
295 type: Schema.Literal("setOrientation"),
296 value: DeviceOrientation,
297 }),
298 Schema.Struct({
299 ...DeviceTarget,
300 type: Schema.Literal("setLocation"),
301 latitude: Schema.Number.check(Schema.isBetween({ minimum: -90, maximum: 90 })),
302 longitude: Schema.Number.check(Schema.isBetween({ minimum: -180, maximum: 180 })),
303 }),
304 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("clearLocation") }),
305 Schema.Struct({
306 ...DeviceTarget,
307 type: Schema.Literal("setPermission"),
308 appId: TrimmedNonEmptyString,
309 permission: DevicePermission,
310 decision: Schema.Literals(["grant", "revoke", "reset"]),
311 }),
312 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("openUrl"), url: TrimmedNonEmptyString }),
313 Schema.Struct({
314 ...DeviceTarget,
315 type: Schema.Literal("launchApp"),
316 appId: TrimmedNonEmptyString,
317 }),
318 Schema.Struct({
319 ...DeviceTarget,
320 type: Schema.Literal("terminateApp"),
321 appId: TrimmedNonEmptyString,
322 }),
323 Schema.Struct({ ...DeviceTarget, type: Schema.Literal("shake") }),
324 Schema.Struct({
325 ...DeviceTarget,
326 type: Schema.Literal("sendPush"),
327 appId: TrimmedNonEmptyString,
328 /** APNs-style payload; a bare string becomes the alert body. */
329 payload: Schema.Union([Schema.String, Schema.Record(Schema.String, Schema.Unknown)]),
330 }),
331]);
332export type DeviceActionInput = typeof DeviceActionInput.Type;
333export type DeviceActionType = DeviceActionInput["type"];
334​
335export const DeviceDetailInput = Schema.Struct(DeviceTarget);
336export type DeviceDetailInput = typeof DeviceDetailInput.Type;
337​
338export class DeviceHostUnavailableError extends Schema.TaggedError<DeviceHostUnavailableError>()(
339 "DeviceHostUnavailableError",
340 {
341 hostId: DeviceHostId,
342 reason: Schema.String,
343 },
344) {
345 override get message(): string {
346 return `Device host ${this.hostId} is unavailable: ${this.reason}`;
347 }
349​
350export class DevicePlatformUnavailableError extends Schema.TaggedError<DevicePlatformUnavailableError>()(
351 "DevicePlatformUnavailableError",
352 {
353 hostId: DeviceHostId,
354 platform: DevicePlatform,
355 reason: Schema.String,
356 },
357) {
358 override get message(): string {
359 return `${this.platform} devices are unavailable on host ${this.hostId}: ${this.reason}`;
360 }
362​
363export class DeviceNotFoundError extends Schema.TaggedError<DeviceNotFoundError>()(
364 "DeviceNotFoundError",
365 {
366 hostId: DeviceHostId,
367 deviceId: DeviceId,
368 },
369) {
370 override get message(): string {
371 return `Device ${this.deviceId} was not found on host ${this.hostId}.`;
372 }
374​
375export class DeviceBootError extends Schema.TaggedError<DeviceBootError>()("DeviceBootError", {
376 hostId: DeviceHostId,
377 deviceId: DeviceId,
378 reason: Schema.Literals(["disk_space", "timeout", "launch_failed"]),
379 cause: Schema.Defect(),
380}) {
381 override get message(): string {
382 const explanation = {
383 disk_space: "There is not enough free disk space on the environment server.",
384 timeout: "The device did not become ready in time.",
385 launch_failed:
386 "The simulator or emulator could not start. Check its configuration on the environment server.",
387 }[this.reason];
388 return `Device ${this.deviceId} failed to boot: ${explanation}`;
389 }
391​
392export class DeviceOperationError extends Schema.TaggedError<DeviceOperationError>()(
393 "DeviceOperationError",
394 {
395 operation: Schema.String,
396 reason: Schema.Literals([
397 "command_failed",
398 "request_failed",
399 "invalid_payload",
400 "settings_failed",
401 "hub_rejected",
402 ]),
403 exitCode: Schema.optional(Schema.Number),
404 cause: Schema.Defect(),
405 },
406) {
407 override get message(): string {
408 const explanation = {
409 command_failed: `The device command failed${this.exitCode === undefined ? "" : ` (exit code ${this.exitCode})`}.`,
410 request_failed: "Could not communicate with device support. Try refreshing devices.",
411 invalid_payload: "The device request could not be encoded.",
412 settings_failed: "Could not read or save device settings.",
413 hub_rejected: "The device hub could not complete the request.",
414 }[this.reason];
415 return `Device ${this.operation} failed: ${explanation}`;
416 }
418​
419export class DeviceActionUnavailableError extends Schema.TaggedError<DeviceActionUnavailableError>()(
420 "DeviceActionUnavailableError",
421 {
422 operation: Schema.String,
423 platform: DevicePlatform,
424 reason: Schema.Literals(["unsupported", "helper_missing"]),
425 },
426) {
427 override get message(): string {
428 return this.reason === "helper_missing"
429 ? `Device ${this.operation} requires a helper missing from this install. Set up device support again.`
430 : `Device ${this.operation} is not supported on ${this.platform}.`;
431 }
433​
434export const DeviceError = Schema.Union([
435 DeviceHostUnavailableError,
436 DevicePlatformUnavailableError,
437 DeviceNotFoundError,
438 DeviceBootError,
439 DeviceOperationError,
440 DeviceActionUnavailableError,
441]);
442export type DeviceError = typeof DeviceError.Type;
443​
444// MCP tool shapes. Kept next to the RPC shapes so the tool surface and the
445// panel describe devices the same way.
446​
447export const DeviceToolListResult = Schema.Struct({
448 hostStatuses: DeviceServiceState.fields.hostStatuses,
449 hosts: Schema.Array(DeviceHostSummary),
450 devices: Schema.Array(DeviceSummary),
451 /** Devices already open in this thread's Device panel. */
452 open: Schema.Array(Schema.Struct({ hostId: DeviceHostId, deviceId: DeviceId })),
453});
454export type DeviceToolListResult = typeof DeviceToolListResult.Type;
455​
456export const DeviceToolOpenInput = Schema.Struct({
457 deviceId: Schema.optional(
458 DeviceId.annotate({
459 description:
460 "Simulator udid or emulator serial from device_list. Omit to use the booted device for the platform, or the most recently used one.",
461 }),
462 ),
463 platform: Schema.optional(
464 DevicePlatform.annotate({
465 description: "Required when deviceId is omitted and both platforms are available.",
466 }),
467 ),
468 hostId: Schema.optional(
469 DeviceHostId.annotate({ description: "Device host from device_list. Defaults to local." }),
470 ),
471}).annotate({
472 description:
473 "Boots the device if needed, starts its live stream, and opens the Device panel so the user can watch. Returns how to drive it with the agent-device CLI.",
474});
475export type DeviceToolOpenInput = typeof DeviceToolOpenInput.Type;
476​
477export const DeviceToolOpenResult = Schema.Struct({
478 device: DeviceSummary,
479 /** Ready-to-run agent-device invocation pinned to this device. */
480 agentDevice: Schema.Struct({
481 command: Schema.String,
482 /** Flags that pin every command to this device, e.g. `--udid <id>`. */
483 targetArgs: Schema.Array(Schema.String),
484 }),
485 quickStart: Schema.String,
486});
487export type DeviceToolOpenResult = typeof DeviceToolOpenResult.Type;
488​
489export const DeviceToolTargetInput = Schema.Struct({
490 deviceId: Schema.optional(
491 DeviceId.annotate({
492 description:
493 "Device from device_list. Omit to use the device most recently opened in this thread.",
494 }),
495 ),
496 hostId: Schema.optional(DeviceHostId),
497});
498export type DeviceToolTargetInput = typeof DeviceToolTargetInput.Type;
499​
500export const DeviceToolScreenshotResult = Schema.Struct({
501 device: DeviceSummary,
502 screenshot: Schema.Struct({
503 mimeType: Schema.Literal("image/png"),
504 data: Schema.String,
505 width: Schema.Int,
506 height: Schema.Int,
507 }),
508});
509export type DeviceToolScreenshotResult = typeof DeviceToolScreenshotResult.Type;
510​
511export const DeviceToolCloseInput = Schema.Struct({
512 deviceId: Schema.optional(
513 DeviceId.annotate({
514 description: "Device to close. Omit to close every device in this thread.",
515 }),
516 ),
517 hostId: Schema.optional(DeviceHostId),
518 shutdown: Schema.optional(
519 Schema.Boolean.annotate({
520 description: "Also power the simulator or emulator off. Defaults to false.",
521 }),
522 ),
523});
524export type DeviceToolCloseInput = typeof DeviceToolCloseInput.Type;
525​
526export class DeviceToolUnavailableError extends Schema.TaggedError<DeviceToolUnavailableError>()(
527 "DeviceToolUnavailableError",
528 {
529 reason: Schema.String,
530 },
531) {
532 override get message(): string {
533 return this.reason;
534 }
536​
537export const DeviceToolError = Schema.Union([
538 DeviceToolUnavailableError,
539 DeviceHostUnavailableError,
540 DevicePlatformUnavailableError,
541 DeviceNotFoundError,
542 DeviceBootError,
543 DeviceOperationError,
544 DeviceActionUnavailableError,
545]);
546export type DeviceToolError = typeof DeviceToolError.Type;