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