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