Open History to see the last commit
1import {
2 type DeviceError,
3 type DeviceHostId,
4 type DeviceId,
5 type DevicePlatform,
6 type DeviceSummary,
7 DeviceToolUnavailableError,
8 LOCAL_DEVICE_HOST_ID,
9} from "@t3tools/contracts";
10import * as Effect from "effect/Effect";
11import * as Path from "effect/Path";
12import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
13import { ServerConfig } from "../../../config.ts";
14import { ensureAgentDeviceShim } from "../../../device/AgentDeviceShim.ts";
15import { nodeRuntimeUnavailableMessage } from "@t3tools/shared/nodeRuntime";
16
17import * as DeviceService from "../../../device/DeviceService.ts";
18import * as McpInvocationContext from "../../McpInvocationContext.ts";
19import { DeviceScreenshotToolkit, DeviceStandardToolkit, DeviceToolkit } from "./tools.ts";
20
21/** The flags that pin every agent-device command to one device. */
22export function agentDeviceTargetArgs(device: DeviceSummary): ReadonlyArray<string> {
23 return device.platform === "ios"
24 ? ["--platform", "ios", "--udid", device.id]
25 : ["--platform", "android", "--serial", device.id];
26}
27
28/**
29 * Just-in-time guidance returned from `device_open`. This is the one place
30 * the agent learns how to drive the device, so it lives with the tool result
31 * rather than in the always-on prompt block; threads that never open a device
32 * never pay for it.
33 */
34export function agentDeviceQuickStart(
35 device: DeviceSummary,
36 targetArgs = agentDeviceTargetArgs(device),
37 command = "agent-device",
38): string {
39 const executable = /^[a-zA-Z0-9_./:-]+$/.test(command)
40 ? command
41 : "'" + command.replaceAll("'", "'\"'\"'") + "'";
42 const target = targetArgs
43 .map((arg) =>
44 /^[a-zA-Z0-9_./:-]+$/.test(arg) ? arg : "'" + arg.replaceAll("'", "'\"'\"'") + "'",
45 )
46 .join(" ");
47 const platformNotes =
48 device.platform === "ios"
49 ? "First use builds an XCTest runner and can take a couple of minutes; later commands are fast."
50 : "The Android snapshot helper installs itself on first use.";
51 return [
52 `The user is watching ${device.name} (${device.version}) in the Device panel.`,
53 `Drive it with ${executable}. Use this exact executable path; login shells may reset PATH. Always pass ${target}.`,
54 "Typical loop:",
55 ` ${executable} open <bundle-or-package-id> ${target} # or: open <app> <deep-link-url>`,
56 ` ${executable} snapshot -i ${target} # accessibility tree with @eN refs`,
57 ` ${executable} click @e3 ${target}`,
58 ` ${executable} fill @e5 "text" ${target}`,
59 ` ${executable} screenshot /tmp/shot.png ${target} # or call device_screenshot`,
60 ` ${executable} install <app> <path-to-.app-or-.apk> ${target}`,
61 `Prefer snapshot refs over coordinates. Run ${executable} help for workflow guides and ${executable} <command> --help for flags.`,
62 "Prefer agent-device for driving this device. simctl, adb, and xcrun remain available for anything it does not cover.",
63 "For remote hosts, arrange builds, app installation, and any Metro reverse forwarding yourself. T3 provides discovery, streaming, and control only.",
64 "Keep the returned --config and --session flags on every command. Other hosts can be used concurrently; opening one does not switch these commands.",
65 platformNotes,
66 ].join("\n");
67}
68
69const requireDeviceAccess = McpInvocationContext.requireMcpCapability("device").pipe(
70 Effect.mapError(
71 () =>
72 new DeviceToolUnavailableError({
73 reason: "Agent device access is turned off for this environment.",
74 }),
75 ),
76);
77
78const pickDevice = (
79 devices: ReadonlyArray<DeviceSummary>,
80 input: {
81 readonly deviceId?: DeviceId | undefined;
82 readonly platform?: DevicePlatform | undefined;
83 readonly hostId?: DeviceHostId | undefined;
84 },
85): Effect.Effect<DeviceSummary, DeviceToolUnavailableError> =>
86 Effect.gen(function* () {
87 const hostId = input.hostId ?? LOCAL_DEVICE_HOST_ID;
88 if (input.deviceId !== undefined) {
89 const match = devices.find(
90 (device) => device.hostId === hostId && device.id === input.deviceId,
91 );
92 if (match) return match;
93 return yield* new DeviceToolUnavailableError({
94 reason: `No device ${input.deviceId} on host ${hostId}. Call device_list for current ids.`,
95 });
96 }
97 const candidates = devices.filter(
98 (device) =>
99 device.hostId === hostId &&
100 (input.platform === undefined || device.platform === input.platform),
101 );
102 if (candidates.length === 0) {
103 return yield* new DeviceToolUnavailableError({
104 reason:
105 input.platform === undefined
106 ? "No simulators or emulators were found. Call device_list to see why."
107 : `No ${input.platform} devices were found on host ${hostId}. Call device_list to see why.`,
108 });
109 }
110 const platforms = new Set(candidates.map((device) => device.platform));
111 if (input.platform === undefined && platforms.size > 1) {
112 return yield* new DeviceToolUnavailableError({
113 reason: "Both iOS and Android devices are available; pass platform or deviceId.",
114 });
115 }
116 return candidates.find((device) => device.booted) ?? candidates[0]!;
117 });
118
119const toolError = (error: DeviceError | DeviceToolUnavailableError) => error;
120
121const handlers = {
122 device_list: (input) =>
123 Effect.gen(function* () {
124 const scope = yield* requireDeviceAccess;
125 const devices = yield* DeviceService.DeviceService;
126 const state = yield* devices.list;
127 if (state.hostStatus === "disabled") {
128 return yield* new DeviceToolUnavailableError({
129 reason:
130 "Device support is off. Ask the user to enable it in the Device panel before installing or starting device tools.",
131 });
132 }
133 const hostId = input?.hostId;
134 const open = state.sessions
135 .filter((session) => session.threadId === scope.threadId)
136 .map((session) => ({ hostId: session.hostId, deviceId: session.deviceId }));
137 return {
138 hostStatuses: Object.fromEntries(
139 Object.entries(state.hostStatuses).filter(([id]) => !hostId || id === hostId),
140 ),
141 hosts: hostId ? state.hosts.filter((host) => host.id === hostId) : state.hosts,
142 devices: hostId
143 ? state.devices.filter((device) => device.hostId === hostId)
144 : state.devices,
145 open,
146 };
147 }).pipe(Effect.mapError(toolError)),
148 device_open: (input) =>
149 Effect.gen(function* () {
150 const scope = yield* requireDeviceAccess;
151 const devices = yield* DeviceService.DeviceService;
152 const state = yield* devices.list;
153 if (state.hostStatus === "disabled") {
154 return yield* new DeviceToolUnavailableError({
155 reason:
156 "Device support is off. Ask the user to enable it in the Device panel before installing or starting device tools.",
157 });
158 }
159 const target = yield* pickDevice(state.devices, input);
160 // Resolve consent and agent connectivity before booting or registering a session.
161 const agentArgs = yield* devices.agentTarget({
162 threadId: scope.threadId,
163 hostId: target.hostId,
164 deviceId: target.id,
165 });
166 const session = yield* devices.open({
167 threadId: scope.threadId,
168 hostId: target.hostId,
169 deviceId: target.id,
170 platform: target.platform,
171 });
172 const after = yield* devices.state;
173 const device =
174 after.devices.find(
175 (candidate) => candidate.hostId === session.hostId && candidate.id === session.deviceId,
176 ) ?? target;
177 const targetArgs = [...agentDeviceTargetArgs(device), ...agentArgs];
178 const config = yield* ServerConfig;
179 const path = yield* Path.Path;
180 const platform = yield* HostProcessPlatform;
181 const shimDir = yield* ensureAgentDeviceShim({
182 entryPath: yield* devices.agentCli,
183 stateDir: config.stateDir,
184 }).pipe(
185 Effect.mapError(
186 (error) =>
187 new DeviceToolUnavailableError({
188 reason:
189 error._tag === "NodeRuntimeUnavailableError"
190 ? nodeRuntimeUnavailableMessage("Device automation")
191 : "Could not prepare the agent-device launcher.",
192 cause: error,
193 }),
194 ),
195 );
196 const command = path.join(
197 shimDir,
198 platform === "win32" ? "agent-device.cmd" : "agent-device",
199 );
200 return {
201 device,
202 agentDevice: { command, targetArgs },
203 quickStart: agentDeviceQuickStart(device, targetArgs, command),
204 };
205 }).pipe(Effect.mapError(toolError)),
206 device_screenshot: (input) =>
207 Effect.gen(function* () {
208 const scope = yield* requireDeviceAccess;
209 const devices = yield* DeviceService.DeviceService;
210 const sessions = yield* devices.sessionsForThread(scope.threadId);
211 const target =
212 input.deviceId !== undefined
213 ? { hostId: input.hostId ?? LOCAL_DEVICE_HOST_ID, deviceId: input.deviceId }
214 : sessions
215 .filter((session) => input.hostId === undefined || session.hostId === input.hostId)
216 .at(-1);
217 if (!target) {
218 return yield* new DeviceToolUnavailableError({
219 reason: "No device is open in this thread. Call device_open first.",
220 });
221 }
222 const shot = yield* devices.screenshot(target);
223 return {
224 device: shot.device,
225 screenshot: {
226 mimeType: "image/png" as const,
227 data: Buffer.from(shot.png).toString("base64"),
228 ...pngDimensions(shot.png),
229 },
230 };
231 }).pipe(Effect.mapError(toolError)),
232 device_close: (input) =>
233 Effect.gen(function* () {
234 const scope = yield* requireDeviceAccess;
235 const devices = yield* DeviceService.DeviceService;
236 yield* devices.close({
237 threadId: scope.threadId,
238 ...(input.hostId === undefined ? {} : { hostId: input.hostId }),
239 ...(input.deviceId === undefined ? {} : { deviceId: input.deviceId }),
240 ...(input.shutdown === undefined ? {} : { shutdown: input.shutdown }),
241 });
242 return {};
243 }).pipe(Effect.mapError(toolError)),
244} satisfies Parameters<typeof DeviceToolkit.toLayer>[0];
245
246/** Width and height from the IHDR chunk; a PNG that lacks one reports 0×0. */
247export function pngDimensions(png: Uint8Array): { width: number; height: number } {
248 if (png.length < 24) return { width: 0, height: 0 };
249 const view = new DataView(png.buffer, png.byteOffset, png.byteLength);
250 const isPng =
251 view.getUint32(0) === 0x89504e47 &&
252 view.getUint32(4) === 0x0d0a1a0a &&
253 view.getUint32(12) === 0x49484452;
254 return isPng
255 ? { width: view.getUint32(16), height: view.getUint32(20) }
256 : { width: 0, height: 0 };
257}
258
259const { device_screenshot, ...standardHandlers } = handlers;
260
261export const DeviceStandardToolkitHandlersLive = DeviceStandardToolkit.toLayer(standardHandlers);
262
263export const DeviceScreenshotToolkitHandlersLive = DeviceScreenshotToolkit.toLayer({
264 device_screenshot,
265});