Open History to see the last commit
1import type {
2 DeviceBootError,
3 DeviceHostId,
4 DeviceHostUnavailableError,
5 DeviceHostSummary,
6 DeviceOperationError,
7 DevicePlatform,
8 DevicePlatformAvailability,
9 DeviceSummary,
10} from "@t3tools/contracts";
11import * as Context from "effect/Context";
12import * as Effect from "effect/Effect";
13import * as Schema from "effect/Schema";
14import type { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
15
16export class DeviceHostError extends Schema.TaggedError<DeviceHostError>()("DeviceHostError", {
17 hostId: Schema.String,
18 step: Schema.String,
19 cause: Schema.Defect(),
20}) {
21 override get message(): string {
22 return `Device host ${this.hostId} failed while ${this.step}.`;
23 }
24}
25
26export class DeviceHostTimeoutError extends Schema.TaggedError<DeviceHostTimeoutError>()(
27 "DeviceHostTimeoutError",
28 { hostId: Schema.String, timeoutMs: Schema.Number },
29) {
30 override get message(): string {
31 return `Device host ${this.hostId} did not start agent tools within ${this.timeoutMs} ms.`;
32 }
33}
34
35export class AgentDeviceStartError extends Schema.TaggedError<AgentDeviceStartError>()(
36 "AgentDeviceStartError",
37 {
38 hostId: Schema.String,
39 stateDir: Schema.String,
40 exitCode: Schema.NullOr(Schema.Int),
41 reason: Schema.Literals([
42 "daemon_lock_not_directory",
43 "daemon_registration_unproven",
44 "daemon_retirement_unconfirmed",
45 "command_failed",
46 ]),
47 cause: Schema.Defect(),
48 },
49) {
50 override get message(): string {
51 const exit = this.exitCode === null ? "" : ` (exit code ${this.exitCode})`;
52 const detail =
53 this.reason === "daemon_lock_not_directory"
54 ? "Daemon registration ownership could not be verified: daemon.lock is not a directory."
55 : this.reason === "daemon_registration_unproven"
56 ? "Daemon registration ownership could not be verified."
57 : this.reason === "daemon_retirement_unconfirmed"
58 ? "Daemon replacement could not be confirmed."
59 : "The AgentDevice startup command failed.";
60 const recovery =
61 this.reason === "command_failed"
62 ? `Inspect daemon diagnostics in ${this.stateDir}.`
63 : `Inspect daemon.lock and daemon diagnostics in ${this.stateDir}. Stop older clients and daemons with their original CLI before manually repairing retained state.`;
64 return `Agent tools failed to start${exit}. ${detail} ${recovery}`;
65 }
66}
67
68export interface DeviceHubEndpoint {
69 readonly origin: string;
70 /** The hub's session token, which the hub requires on every request. */
71 readonly token?: string;
72}
73
74export interface AgentDeviceEndpoint {
75 readonly baseUrl: string;
76 readonly token: string;
77 readonly entryPath: string;
78}
79
80export type HostDevice = Omit<DeviceSummary, "hostId">;
81
82/** Where a device is being opened from, for hosts whose devices depend on the project. */
83export interface DeviceOpenContext {
84 readonly workspaceRoot?: string | undefined;
85}
86
87export type AgentDaemonEndpoint = Pick<AgentDeviceEndpoint, "baseUrl" | "token">;
88
89export interface AgentDeviceBinding extends AgentDaemonEndpoint {
90 /** Null when the session alone picks the device and selector flags would be refused. */
91 readonly agentDeviceId: string | null;
92 /** The one session the device is leased to, shared by every thread. */
93 readonly session?: string;
94 /** agent-device state holding that session's connection. */
95 readonly stateDir?: string;
96 /** agent-device accepts installs into the session only from the directory that opened it. */
97 readonly installDirectory?: string;
98}
99
100/** Where the proxy sends a device hub request, for hosts that serve several upstreams. */
101export interface HubUpstream {
102 readonly url: string;
103 readonly headers: Readonly<Record<string, string>>;
104 readonly protocols: ReadonlyArray<string>;
105}
106
107/** Discovery and lifecycle for the devices a ready host can run. */
108export interface DeviceOperations {
109 readonly list: Effect.Effect<
110 {
111 readonly devices: ReadonlyArray<HostDevice>;
112 readonly detail: string | undefined;
113 /** Some Android virtual devices could not be listed; the rest are. */
114 readonly androidDiscoveryIncomplete?: boolean;
115 /** Platforms that could not be listed; their last known devices stay listed. */
116 readonly incompletePlatforms?: ReadonlyArray<DevicePlatform>;
117 },
118 DeviceOperationError
119 >;
120 /**
121 * Boots the device and prepares its stream. Android AVDs change id when they
122 * boot (AVD name to emulator serial), so the returned id is authoritative.
123 */
124 readonly boot: (
125 device: HostDevice,
126 context?: DeviceOpenContext,
127 ) => Effect.Effect<string, DeviceOperationError | DeviceBootError | DeviceHostUnavailableError>;
128 /** Prepares the stream of a device that is already booted. */
129 readonly attach: (device: HostDevice) => Effect.Effect<void, DeviceOperationError>;
130 readonly shutdown: (device: {
131 readonly id: string;
132 readonly platform: DevicePlatform;
133 }) => Effect.Effect<void, DeviceOperationError>;
134 readonly screenshot: (device: HostDevice) => Effect.Effect<Uint8Array, DeviceOperationError>;
135 /**
136 * For hosts that run one agent-device daemon per device instead of one per
137 * host. `agentDeviceId` is the id agent-device selects the device by, when
138 * it differs from the host's device id.
139 */
140 readonly agentEndpoint?: (
141 deviceId: string,
142 ) => Effect.Effect<AgentDeviceBinding, DeviceHostUnavailableError>;
143 /**
144 * Set by hosts that end devices on their own (Expo stops sessions at their
145 * limits), so a session on a device the host stops listing is dropped.
146 */
147 readonly endsDevices?: boolean;
148}
149
150export interface DeviceHostReady {
151 readonly nodePath: string;
152 /**
153 * Ends an agent-device session on the daemon that serves `deviceId`. Hosts
154 * with a shared daemon provide it only while that daemon runs; hosts with a
155 * daemon per device succeed when the device's daemon is gone. Cleanup never
156 * starts a daemon or a device.
157 */
158 readonly releaseAgentSession?: (
159 session: string,
160 deviceId: string,
161 ) => Effect.Effect<void, DeviceOperationError>;
162 readonly hub: DeviceHubEndpoint;
163 readonly devices: DeviceOperations;
164 readonly run: (
165 command: string,
166 args: ReadonlyArray<string>,
167 options?: {
168 readonly timeoutMs?: number;
169 readonly stdin?: string;
170 /** Local output cap; SSH output is not capped. */
171 readonly maxOutputBytes?: number;
172 },
173 ) => Effect.Effect<{ readonly stdout: string; readonly stderr: string; readonly code: number }>;
174 readonly helpers: {
175 readonly serveSimAxSettings: string | null;
176 readonly serveSimCli: string | null;
177 };
178 /** Routes proxied hub requests itself; otherwise they go to `hub.origin`. */
179 readonly upstream?: (
180 hubPath: string,
181 search: URLSearchParams,
182 ) => Effect.Effect<HubUpstream | null>;
183}
184
185export interface DeviceHostAgentReady extends DeviceHostReady {
186 /** Null when each device has its own daemon; see `DeviceOperations.agentEndpoint`. */
187 readonly agentDevice: AgentDeviceEndpoint | null;
188}
189
190export class DeviceHost extends Context.Service<
191 DeviceHost,
192 {
193 readonly id: DeviceHostId;
194 /** The name errors and the Device panel show for this host. */
195 readonly label: string;
196 readonly summary: Effect.Effect<DeviceHostSummary>;
197 readonly inspect?: Effect.Effect<DeviceHostSummary, DeviceHostError>;
198 readonly platformAvailability: (
199 platform: DevicePlatform,
200 ) => Effect.Effect<DevicePlatformAvailability>;
201 readonly ensureReady: (
202 onPhase: (phase: "installing" | "starting", detail?: string) => Effect.Effect<void>,
203 ) => Effect.Effect<DeviceHostReady, DeviceHostError | NodeRuntimeUnavailableError>;
204 readonly ensureAgentReady: (
205 onPhase: (phase: "installing" | "starting", detail?: string) => Effect.Effect<void>,
206 ) => Effect.Effect<
207 DeviceHostAgentReady,
208 DeviceHostError | DeviceHostTimeoutError | AgentDeviceStartError | NodeRuntimeUnavailableError
209 >;
210 readonly current: Effect.Effect<DeviceHostReady | null>;
211 readonly stopAgent: Effect.Effect<void>;
212 /** Stops helpers. Devices themselves keep running; the user owns those. */
213 readonly stop: Effect.Effect<void>;
214 }
215>()("t3/device/DeviceHost") {}