Open History to see the last commit
1/**
2 * Alpha: devices leased from a Simlock gateway the user runs. Opening a device
3 * takes a lease through the gateway's agent-device front, so agents drive it
4 * with the same session; closing it returns the device to the pool, wiped.
5 * A lease left by a server that crashed ends one TTL after its last renewal.
6 */
7import {
8 DeviceBootError,
9 type DeviceHostSummary,
10 DeviceHostUnavailableError,
11 DeviceOperationError,
12 type DevicePlatform,
13 type DevicePlatformAvailability,
14 type SimlockDeviceHostConfig,
15} from "@t3tools/contracts";
16import * as Cause from "effect/Cause";
17import * as Clock from "effect/Clock";
18import * as Duration from "effect/Duration";
19import * as Effect from "effect/Effect";
20import * as FiberMap from "effect/FiberMap";
21import * as FileSystem from "effect/FileSystem";
22import * as Option from "effect/Option";
23import * as Path from "effect/Path";
24import * as Random from "effect/Random";
25import * as Schema from "effect/Schema";
26import * as Semaphore from "effect/Semaphore";
27import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
28import * as HostProcess from "@t3tools/shared/HostProcess";
29import type { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
30
31import * as ServerConfig from "../config.ts";
32import * as ProcessRunner from "../processRunner.ts";
33import { writeAgentDeviceConfig } from "./AgentDeviceTarget.ts";
34import * as DeviceHost from "./DeviceHost.ts";
35
36const CATALOG_TTL_MS = 60_000;
37const REQUEST_TIMEOUT = Duration.seconds(15);
38// The gateway queues a lease request for up to five minutes when every device is busy.
39const OPEN_TIMEOUT = Duration.minutes(7);
40const COMMAND_TIMEOUT = Duration.minutes(2);
41// Renewal keeps a watched but idle device; a lease this server stops renewing ends after LEASE_TTL.
42const RENEW_INTERVAL = Duration.minutes(2);
43const LEASE_TTL_MS = 10 * 60_000;
44const STREAM_PATH = /^\/vendor\/serve-sim\/helper\/([^/]+)\/stream\.avcc$/;
45const INPUT_PATH = "/vendor/serve-sim/helper/ws";
46
47const Catalog = Schema.Struct({
48 platforms: Schema.Array(
49 Schema.Struct({
50 platform: Schema.String,
51 modelRuntimes: Schema.Record(Schema.String, Schema.Array(Schema.String)),
52 modelClasses: Schema.optional(Schema.Record(Schema.String, Schema.String)),
53 modelWorkers: Schema.optional(Schema.Record(Schema.String, Schema.Array(Schema.String))),
54 }),
55 ),
56});
57const decodeCatalog = Schema.decodeUnknownEffect(Catalog);
58const decodeSessionRecord = Schema.decodeUnknownEffect(
59 Schema.fromJsonString(Schema.Struct({ leaseId: Schema.String })),
60);
61const decodeCliFailure = Schema.decodeUnknownOption(
62 Schema.fromJsonString(
63 Schema.Struct({
64 error: Schema.Struct({ message: Schema.String, hint: Schema.optional(Schema.String) }),
65 }),
66 ),
67);
68
69interface Lease {
70 readonly leaseId: string;
71 readonly platform: DevicePlatform;
72 readonly name: string;
73 readonly version: string;
74 readonly session: string;
75 readonly dir: string;
76 readonly configPath: string;
77 readonly installDirectory: string;
78}
79
80const catalogId = (platform: DevicePlatform, model: string) => `simlock:${platform}:${model}`;
81const parseCatalogId = (id: string) => {
82 const match = /^simlock:(ios|android):(.+)$/.exec(id);
83 return match ? { platform: match[1] as DevicePlatform, model: match[2]! } : null;
84};
85const platformVersion = (platform: DevicePlatform, runtime: string | undefined) =>
86 `${platform === "ios" ? "iOS" : "Android"}${runtime ? ` ${runtime}` : ""}`;
87
88const AGENT_DEVICE_PATH = "/v1/agent-device";
89const sameOrigin = (left: string, right: string) => {
90 try {
91 return new URL(left).origin === new URL(right).origin;
92 } catch {
93 return false;
94 }
95};
96
97/**
98 * The gateway and token this machine's agent-device uses, from agent-device's own remote-daemon
99 * variables, which Simlock tells its clients to set. Null unless they point at a Simlock gateway.
100 */
101export const machineSimlockToken = (environment: NodeJS.ProcessEnv) => {
102 const base = environment.AGENT_DEVICE_DAEMON_BASE_URL?.trim().replace(/\/+$/, "");
103 const agentToken = environment.AGENT_DEVICE_DAEMON_AUTH_TOKEN?.trim();
104 if (!base?.endsWith(AGENT_DEVICE_PATH) || !agentToken) return null;
105 const gatewayUrl = base.slice(0, -AGENT_DEVICE_PATH.length);
106 return URL.canParse(gatewayUrl) ? { gatewayUrl, agentToken } : null;
107};
108
109/**
110 * The saved token, else this machine's agent-device token; each only for the gateway it belongs to,
111 * so a URL being edited never receives either.
112 */
113export const resolveSimlockToken = (
114 gatewayUrl: string,
115 saved: { readonly gatewayUrl: string; readonly agentToken: string } | undefined,
116 environment: NodeJS.ProcessEnv,
117) => {
118 if (saved?.agentToken && sameOrigin(saved.gatewayUrl, gatewayUrl))
119 return { agentToken: saved.agentToken, source: "settings" as const };
120 const machine = machineSimlockToken(environment);
121 return machine && sameOrigin(machine.gatewayUrl, gatewayUrl)
122 ? { agentToken: machine.agentToken, source: "env" as const }
123 : null;
124};
125
126/** What went wrong talking to a gateway, without the gateway's own text. */
127export const describeGatewayFailure = (cause: unknown, gatewayUrl: string, tokenOwner: string) => {
128 if (Cause.isTimeoutError(cause)) return `Could not reach the Simlock gateway at ${gatewayUrl}.`;
129 if (!HttpClientError.isHttpClientError(cause))
130 return `The Simlock gateway at ${gatewayUrl} sent an answer T3 could not read.`;
131 if (cause.reason._tag === "StatusCodeError") {
132 const status = cause.reason.response.status;
133 return status === 401 || status === 403
134 ? `The Simlock gateway refused the agent token for ${tokenOwner}.`
135 : `The Simlock gateway at ${gatewayUrl} answered HTTP ${status}.`;
136 }
137 return cause.reason._tag === "TransportError"
138 ? `Could not reach the Simlock gateway at ${gatewayUrl}.`
139 : `The Simlock gateway at ${gatewayUrl} sent an answer T3 could not read.`;
140};
141
142const decodeIdentity = Schema.decodeUnknownEffect(
143 Schema.Struct({ name: Schema.String, role: Schema.String }),
144);
145
146/** Who the gateway says a token is, via GET /v1/identity. */
147export const simlockIdentity = Effect.fn("SimlockDeviceHost.identity")(function* (
148 gatewayUrl: string,
149 agentToken: string,
150) {
151 const http = yield* HttpClient.HttpClient;
152 return yield* http
153 .execute(
154 HttpClientRequest.get(`${gatewayUrl.replace(/\/$/, "")}/v1/identity`).pipe(
155 HttpClientRequest.bearerToken(agentToken),
156 ),
157 )
158 .pipe(
159 Effect.flatMap(HttpClientResponse.filterStatusOk),
160 Effect.flatMap((response) => response.json),
161 Effect.flatMap(decodeIdentity),
162 Effect.scoped,
163 Effect.timeout(REQUEST_TIMEOUT),
164 );
165});
166
167/** T3's own agent-device CLI, installed on first use. */
168export type AgentDeviceCli = Effect.Effect<
169 { readonly nodePath: string; readonly entryPath: string },
170 DeviceHost.DeviceHostError | NodeRuntimeUnavailableError
171>;
172
173export const make = Effect.fn("SimlockDeviceHost.make")(function* (
174 config: SimlockDeviceHostConfig,
175 agentDeviceCli: AgentDeviceCli,
176) {
177 const http = yield* HttpClient.HttpClient;
178 const fs = yield* FileSystem.FileSystem;
179 const path = yield* Path.Path;
180 const runner = yield* ProcessRunner.ProcessRunner;
181 const server = yield* ServerConfig.ServerConfig;
182 const services = yield* Effect.context<FileSystem.FileSystem | Path.Path>();
183 const environment = yield* HostProcess.Environment;
184 const hostId = config.id;
185 const gateway = config.gatewayUrl.replace(/\/$/, "");
186 const agentToken = resolveSimlockToken(config.gatewayUrl, config, environment)?.agentToken ?? "";
187 const agentDeviceUrl = `${gateway}/v1/agent-device`;
188 const hostDir = path.join(server.stateDir, "device", "simlock", hostId);
189 const leases = new Map<string, Lease>();
190 let starting = 0;
191 // Bumped by every stop, so an open that finishes after one returns its lease instead of keeping it.
192 let stops = 0;
193 const slotLock = yield* Semaphore.make(1);
194 const keepAlive = yield* FiberMap.make<string>();
195 let catalog: {
196 readonly at: number;
197 readonly devices: ReadonlyArray<DeviceHost.HostDevice>;
198 } | null = null;
199 // The last answer from the gateway; empty until it gives one.
200 let platforms: ReadonlyArray<DevicePlatformAvailability> = [];
201 let ready: DeviceHost.DeviceHostReady | null = null;
202 let cli: { readonly nodePath: string; readonly entryPath: string } | null = null;
203
204 const unavailable = (reason: string, cause?: unknown) =>
205 new DeviceHostUnavailableError({
206 hostId,
207 hostLabel: config.label,
208 reason,
209 ...(cause === undefined ? {} : { cause }),
210 });
211
212 const request = (
213 method: "GET" | "POST" | "DELETE",
214 route: string,
215 body?: Readonly<Record<string, unknown>>,
216 ) =>
217 http
218 .execute(
219 (method === "GET"
220 ? HttpClientRequest.get(`${gateway}${route}`)
221 : method === "POST"
222 ? HttpClientRequest.post(`${gateway}${route}`).pipe(
223 HttpClientRequest.bodyJsonUnsafe(body ?? {}),
224 )
225 : HttpClientRequest.delete(`${gateway}${route}`)
226 ).pipe(HttpClientRequest.bearerToken(agentToken)),
227 )
228 .pipe(
229 Effect.flatMap(HttpClientResponse.filterStatusOk),
230 Effect.flatMap((response) => response.json),
231 Effect.scoped,
232 Effect.timeout(REQUEST_TIMEOUT),
233 );
234
235 const agentEnvironment: NodeJS.ProcessEnv = Object.fromEntries(
236 Object.entries({
237 ...environment,
238 ELECTRON_RUN_AS_NODE: "1",
239 AGENT_DEVICE_NO_UPDATE_NOTIFIER: "1",
240 NO_COLOR: "1",
241 FORCE_COLOR: "0",
242 }).filter(
243 ([name]) =>
244 !/^AGENT_DEVICE_(DAEMON_BASE_URL|DAEMON_AUTH_TOKEN|CONFIG|STATE_DIR|SESSION)$/.test(name),
245 ),
246 );
247
248 /** Runs T3's own agent-device CLI against the lease's session; its failure message is the reason. */
249 const agentDevice = Effect.fn("SimlockDeviceHost.agentDevice")(function* (
250 lease: Pick<Lease, "session" | "configPath">,
251 args: ReadonlyArray<string>,
252 options: { readonly cwd?: string; readonly timeout?: Duration.Input } = {},
253 ) {
254 if (!cli) return yield* unavailable(`${config.label} is not ready.`);
255 const result = yield* runner
256 .run({
257 command: cli.nodePath,
258 args: [
259 cli.entryPath,
260 ...args,
261 "--session",
262 lease.session,
263 "--config",
264 lease.configPath,
265 "--json",
266 ],
267 env: agentEnvironment,
268 ...(options.cwd ? { cwd: options.cwd } : {}),
269 timeout: options.timeout ?? COMMAND_TIMEOUT,
270 })
271 .pipe(Effect.mapError((cause) => unavailable("agent-device could not run.", cause)));
272 if (result.code !== 0) {
273 const failure = decodeCliFailure(result.stdout);
274 return yield* unavailable(
275 Option.match(failure, {
276 onNone: () => `agent-device ${args[0]} failed (exit code ${result.code ?? "none"}).`,
277 onSome: ({ error }) => (error.hint ? `${error.message} ${error.hint}` : error.message),
278 }),
279 );
280 }
281 return result.stdout;
282 });
283
284 const fetchCatalog = Effect.gen(function* () {
285 const now = yield* Clock.currentTimeMillis;
286 if (catalog && now - catalog.at < CATALOG_TTL_MS) return catalog.devices;
287 if (!agentToken) {
288 return yield* unavailable(`Add an agent token for ${config.label} in Settings.`);
289 }
290 const decoded = yield* request("GET", "/v1/catalog").pipe(
291 Effect.flatMap(decodeCatalog),
292 Effect.mapError((cause) =>
293 unavailable(describeGatewayFailure(cause, gateway, config.label), cause),
294 ),
295 );
296 const byPlatform = decoded.platforms.map((entry) => {
297 if (entry.platform !== "ios" && entry.platform !== "android") return null;
298 const platform: DevicePlatform = entry.platform;
299 return Object.entries(entry.modelRuntimes).flatMap(([model, runtimes]) => {
300 const kind = entry.modelClasses?.[model];
301 const workers = entry.modelWorkers?.[model];
302 if (runtimes.length === 0 || (workers !== undefined && workers.length === 0)) return [];
303 if (kind !== undefined && kind !== "phone" && kind !== "tablet") return [];
304 return [
305 {
306 id: catalogId(platform, model),
307 platform,
308 name: model,
309 version: platformVersion(platform, runtimes.at(-1)),
310 booted: false,
311 physical: false,
312 } satisfies DeviceHost.HostDevice,
313 ];
314 });
315 });
316 const devices = byPlatform.flatMap((entry) => entry ?? []);
317 // A platform with nothing to offer is usually its workers reconnecting; caching that would
318 // hide it for the TTL, so only a catalog with devices on every platform is kept.
319 catalog =
320 devices.length > 0 && byPlatform.every((entry) => entry === null || entry.length > 0)
321 ? { at: now, devices }
322 : null;
323 return devices;
324 });
325
326 const loadCatalog = fetchCatalog.pipe(
327 Effect.tap((devices) =>
328 Effect.sync(() => {
329 platforms = (["ios", "android"] as const).map((platform) =>
330 devices.some((device) => device.platform === platform)
331 ? { platform, available: true }
332 : {
333 platform,
334 available: false,
335 reason: `The pool has no ${platform === "ios" ? "iOS" : "Android"} devices.`,
336 },
337 );
338 }),
339 ),
340 Effect.tapError((error) =>
341 Effect.sync(() => {
342 platforms = (["ios", "android"] as const).map((platform) => ({
343 platform,
344 available: false,
345 reason: error.reason,
346 }));
347 }),
348 ),
349 );
350
351 const forget = (lease: Lease) =>
352 Effect.suspend(() => {
353 leases.delete(lease.leaseId);
354 return fs.remove(lease.dir, { recursive: true, force: true }).pipe(Effect.ignore);
355 });
356
357 /** Ends the lease through its session, or over HTTP when the session is gone. */
358 const release = Effect.fn("SimlockDeviceHost.release")(function* (lease: Lease) {
359 yield* agentDevice(lease, ["close"]).pipe(
360 Effect.catch(() => request("DELETE", `/v1/leases/${encodeURIComponent(lease.leaseId)}`)),
361 Effect.tapError((cause) =>
362 Effect.logWarning("Could not release Simlock lease", { leaseId: lease.leaseId, cause }),
363 ),
364 Effect.ignore,
365 );
366 yield* forget(lease);
367 });
368
369 /** Renews until the lease ends on its own or reaches its maximum age, then releases it. */
370 const renewLoop = Effect.fn("SimlockDeviceHost.renewLoop")(function* (lease: Lease) {
371 const deadline =
372 (yield* Clock.currentTimeMillis) +
373 Duration.toMillis(Duration.minutes(config.maxLeaseMinutes));
374 while (true) {
375 const left = deadline - (yield* Clock.currentTimeMillis);
376 yield* Effect.sleep(Duration.millis(Math.min(left, Duration.toMillis(RENEW_INTERVAL))));
377 if ((yield* Clock.currentTimeMillis) >= deadline) break;
378 const renewed = yield* request(
379 "POST",
380 `/v1/leases/${encodeURIComponent(lease.leaseId)}/renew`,
381 { ttlMs: LEASE_TTL_MS },
382 ).pipe(Effect.result);
383 if (renewed._tag === "Success") continue;
384 const error = renewed.failure;
385 // Simlock ended it (lease_lost, an agent's close, or its TTL): stop listing it.
386 if (
387 error._tag === "HttpClientError" &&
388 error.reason._tag === "StatusCodeError" &&
389 error.reason.response.status === 404
390 ) {
391 return yield* forget(lease);
392 }
393 yield* Effect.logWarning("Could not renew Simlock lease", { leaseId: lease.leaseId, error });
394 }
395 yield* Effect.logInfo("Releasing Simlock lease at its maximum age", {
396 leaseId: lease.leaseId,
397 });
398 yield* release(lease);
399 });
400
401 const reserveSlot = slotLock.withPermit(
402 Effect.suspend(() => {
403 if (leases.size + starting >= config.maxLeases) {
404 return Effect.fail(
405 unavailable(
406 `${config.label} is limited to ${config.maxLeases} ${config.maxLeases === 1 ? "device" : "devices"} at once. Close one in the Device panel first.`,
407 ),
408 );
409 }
410 starting++;
411 return Effect.void;
412 }),
413 );
414
415 const openLease = Effect.fn("SimlockDeviceHost.openLease")(function* (
416 device: DeviceHost.HostDevice,
417 context: DeviceHost.DeviceOpenContext | undefined,
418 ) {
419 const target = parseCatalogId(device.id);
420 if (!target) {
421 return yield* new DeviceBootError({
422 hostId,
423 deviceId: device.id,
424 reason: "launch_failed",
425 cause: new Error("This Simlock device is no longer leased. Open it again from the list."),
426 });
427 }
428 const suffix = (yield* Random.nextIntBetween(0, 0xffffff)).toString(16).padStart(6, "0");
429 const session = `t3-${suffix}`;
430 const dir = path.join(hostDir, suffix);
431 const configPath = path.join(dir, "agent-device.json");
432 yield* writeAgentDeviceConfig(configPath, {
433 baseUrl: agentDeviceUrl,
434 token: agentToken,
435 stateDir: dir,
436 }).pipe(
437 Effect.provide(services),
438 Effect.mapError((cause) => unavailable("Could not write the agent-device config.", cause)),
439 );
440 // agent-device ties installs to the directory that opened the session.
441 const installDirectory = context?.workspaceRoot
442 ? yield* fs.realPath(context.workspaceRoot).pipe(Effect.orElseSucceed(() => dir))
443 : dir;
444 const pending = { session, configPath };
445 const stopsAtOpen = stops;
446 return yield* Effect.gen(function* () {
447 yield* agentDevice(pending, ["connect", "proxy", "--daemon-base-url", agentDeviceUrl]);
448 yield* agentDevice(
449 pending,
450 ["open", "--platform", target.platform, "--device", target.model],
451 { cwd: installDirectory, timeout: OPEN_TIMEOUT },
452 );
453 const record = yield* fs
454 .readFileString(path.join(dir, "remote-connections", `${session}.json`))
455 .pipe(
456 Effect.flatMap(decodeSessionRecord),
457 Effect.mapError((cause) => unavailable("agent-device recorded no Simlock lease.", cause)),
458 );
459 const opened: Lease = {
460 leaseId: record.leaseId,
461 platform: target.platform,
462 name: target.model,
463 version: device.version,
464 session,
465 dir,
466 configPath,
467 installDirectory,
468 };
469 if (stops !== stopsAtOpen)
470 return yield* unavailable("Device support stopped while the device was opening.");
471 leases.set(opened.leaseId, opened);
472 yield* FiberMap.run(keepAlive, opened.leaseId, renewLoop(opened));
473 return opened.leaseId;
474 }).pipe(
475 // A failed or interrupted open may still hold a lease: close the session either way.
476 Effect.onExit((exit) =>
477 exit._tag === "Success"
478 ? Effect.void
479 : agentDevice(pending, ["close"]).pipe(
480 Effect.ignore,
481 Effect.andThen(fs.remove(dir, { recursive: true, force: true }).pipe(Effect.ignore)),
482 ),
483 ),
484 Effect.mapError((error) =>
485 error._tag === "DeviceHostUnavailableError"
486 ? new DeviceBootError({
487 hostId,
488 deviceId: device.id,
489 reason: "launch_failed",
490 cause: new Error(error.reason),
491 })
492 : error,
493 ),
494 );
495 });
496
497 const leaseFor = (deviceId: string) => Option.fromNullishOr(leases.get(deviceId));
498 const operationError = (operation: string) => (cause: unknown) =>
499 new DeviceOperationError({ operation, reason: "request_failed", cause });
500
501 const screenshotLease = Effect.fn("SimlockDeviceHost.screenshot")(
502 function* (lease: Lease) {
503 const file = path.join(
504 lease.dir,
505 `screenshot-${(yield* Random.nextIntBetween(0, 0xffffff)).toString(16)}.png`,
506 );
507 yield* agentDevice(lease, ["screenshot", file]);
508 return yield* fs
509 .readFile(file)
510 .pipe(Effect.ensuring(fs.remove(file, { force: true }).pipe(Effect.ignore)));
511 },
512 Effect.mapError(operationError("screenshot")),
513 );
514
515 const devices: DeviceHost.DeviceOperations = {
516 list: loadCatalog.pipe(
517 Effect.mapError(operationError("list")),
518 Effect.map((available) => ({
519 devices: [
520 ...available,
521 ...[...leases.values()].map((lease): DeviceHost.HostDevice => ({
522 id: lease.leaseId,
523 platform: lease.platform,
524 name: lease.name,
525 version: lease.version,
526 booted: true,
527 physical: false,
528 })),
529 ],
530 detail: undefined,
531 })),
532 ),
533 boot: (device, context) =>
534 leases.has(device.id)
535 ? Effect.succeed(device.id)
536 : Effect.acquireUseRelease(
537 reserveSlot,
538 () => openLease(device, context),
539 () => Effect.sync(() => void starting--),
540 ),
541 attach: () => Effect.void,
542 shutdown: (device) =>
543 Option.match(leaseFor(device.id), {
544 onNone: () => Effect.void,
545 onSome: (lease) =>
546 FiberMap.remove(keepAlive, lease.leaseId).pipe(Effect.andThen(release(lease))),
547 }),
548 screenshot: (device) =>
549 Option.match(leaseFor(device.id), {
550 onNone: () =>
551 Effect.fail(operationError("screenshot")(new Error("The Simlock lease has ended"))),
552 onSome: screenshotLease,
553 }),
554 agentEndpoint: (deviceId) =>
555 Option.match(leaseFor(deviceId), {
556 onNone: () => Effect.fail(unavailable("This Simlock lease has ended.")),
557 onSome: (lease) =>
558 Effect.succeed({
559 baseUrl: agentDeviceUrl,
560 token: agentToken,
561 agentDeviceId: null,
562 session: lease.session,
563 stateDir: lease.dir,
564 installDirectory: lease.installDirectory,
565 }),
566 }),
567 endsDevices: true,
568 };
569
570 /**
571 * The client speaks serve-sim to every Simlock lease: its AVCC stream and its input
572 * socket map to the lease's own stream and input routes, which take the agent token.
573 */
574 const upstream: NonNullable<DeviceHost.DeviceHostReady["upstream"]> = (hubPath, search) =>
575 Effect.sync(() => {
576 const stream = STREAM_PATH.exec(hubPath);
577 let deviceId: string | null;
578 try {
579 deviceId = stream
580 ? decodeURIComponent(stream[1]!)
581 : hubPath === INPUT_PATH
582 ? search.get("device")
583 : null;
584 } catch {
585 return null;
586 }
587 const lease = deviceId === null ? undefined : leases.get(deviceId);
588 if (!lease) return null;
589 return {
590 url: `${gateway}/v1/leases/${encodeURIComponent(lease.leaseId)}/${stream ? "stream" : "input"}`,
591 headers: { authorization: `Bearer ${agentToken}` },
592 protocols: [],
593 };
594 });
595
596 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = Effect.fn(
597 "SimlockDeviceHost.ensureReady",
598 )(function* (onPhase) {
599 if (ready) return ready;
600 // A missing token or unreachable gateway does not stop readiness: listing
601 // and opening devices say what is wrong instead.
602 yield* onPhase("installing");
603 cli = yield* agentDeviceCli;
604 const { nodePath } = cli;
605 ready = {
606 nodePath,
607 hub: { origin: gateway },
608 devices,
609 upstream,
610 // Simlock relays only simctl, adb, and devicectl, and only to a lease's owner.
611 run: () =>
612 Effect.succeed({
613 stdout: "",
614 stderr: "Simlock devices cannot run host commands.",
615 code: 127,
616 }),
617 helpers: { serveSimAxSettings: null, serveSimCli: null },
618 };
619 return ready;
620 });
621
622 const stopAll = Effect.gen(function* () {
623 stops++;
624 yield* FiberMap.clear(keepAlive);
625 yield* Effect.forEach([...leases.values()], release, { discard: true, concurrency: 4 });
626 }).pipe(Effect.ignore);
627 yield* Effect.addFinalizer(() => stopAll);
628
629 const platformAvailability = (platform: DevicePlatform) =>
630 loadCatalog.pipe(
631 Effect.ignore,
632 Effect.map(
633 (): DevicePlatformAvailability =>
634 platforms.find((candidate) => candidate.platform === platform) ?? {
635 platform,
636 available: false,
637 },
638 ),
639 );
640
641 const summary: Effect.Effect<DeviceHostSummary> = Effect.sync(() => ({
642 id: hostId,
643 label: config.label,
644 kind: "simlock" as const,
645 platforms,
646 hubInstalled: true,
647 agentDeviceInstalled: true,
648 }));
649
650 return DeviceHost.DeviceHost.of({
651 id: hostId,
652 label: config.label,
653 summary,
654 platformAvailability,
655 ensureReady,
656 ensureAgentReady: Effect.fn("SimlockDeviceHost.ensureAgentReady")(function* (onPhase) {
657 return { ...(yield* ensureReady(onPhase)), agentDevice: null };
658 }),
659 current: Effect.sync(() => ready),
660 stopAgent: Effect.void,
661 stop: stopAll,
662 });
663});