Open History to see the last commit
1import {
2 type DeviceHostSummary,
3 type DevicePlatform,
4 DevicePlatformAvailability,
5 DeviceToolVersions,
6 deviceToolInstallMessage,
7 type SshDeviceHostConfig,
8} from "@t3tools/contracts";
9import { runSshCommand, baseSshArgs, resolveSshCommand } from "@t3tools/ssh/command";
10import { SshCommandError } from "@t3tools/ssh/errors";
11import * as NetService from "@t3tools/shared/Net";
12import { waitForHttpReady } from "@t3tools/shared/httpReadiness";
13import * as Digest from "effect/crypto/Digest";
14import * as Exit from "effect/Exit";
15import * as Effect from "effect/Effect";
16import * as FileSystem from "effect/FileSystem";
17import * as Path from "effect/Path";
18import * as Scope from "effect/Scope";
19import * as Semaphore from "effect/Semaphore";
20import * as Schema from "effect/Schema";
21import * as Stream from "effect/Stream";
22import * as Hex from "effect/encoding/Hex";
23import * as HttpClient from "effect/http/HttpClient";
24import * as ChildProcess from "effect/process/ChildProcess";
25import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
26import * as ServerConfig from "../config.ts";
27import { releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";
28import * as DeviceHost from "./DeviceHost.ts";
29import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
30import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./sshDeviceScript.ts";
31
32const UNHEALTHY_PROBE_LIMIT = 3;
33
34/** The host bootstrap failed on a host identified as Windows. */
35export class SshWindowsHostError extends Schema.TaggedError<SshWindowsHostError>()(
36 "SshWindowsHostError",
37 { cause: Schema.Defect() },
38) {
39 override get message(): string {
40 return "Connected over SSH, but this host runs Windows, and SSH device hosts currently need macOS or Linux. To use this machine's devices, run T3 Code on it and connect to that environment.";
41 }
42}
43export const isSshWindowsHostError = Schema.is(SshWindowsHostError);
44
45const Probe = Schema.Struct({
46 nodePath: Schema.String,
47 tools: Schema.optional(DeviceToolVersions),
48 platforms: Schema.Array(DevicePlatformAvailability),
49});
50const Started = Schema.Struct({
51 ...Probe.fields,
52 hostPlatform: Schema.String,
53 hubPort: Schema.Int,
54 daemonPort: Schema.optionalKey(Schema.Int),
55 token: Schema.optionalKey(Schema.String),
56 entryPath: Schema.optionalKey(Schema.String),
57 helpers: Schema.Struct({
58 serveSimAxSettings: Schema.NullOr(Schema.String),
59 serveSimCli: Schema.NullOr(Schema.String),
60 }),
61});
62const decodeProbe = Schema.decodeUnknownEffect(Schema.fromJsonString(Probe));
63const decodeStarted = Schema.decodeUnknownEffect(Schema.fromJsonString(Started));
64const targetFor = (config: SshDeviceHostConfig) => ({
65 alias: config.target,
66 hostname: config.target,
67 username: null,
68 port: config.port ?? null,
69});
70const identityArgs = (config: SshDeviceHostConfig) =>
71 config.identityFile ? ["-i", config.identityFile] : [];
72const commandArgs = (script: string) => [
73 "sh",
74 "-c",
75 quoteRemoteArg(remoteDeviceEnvironment + script),
76];
77const bootstrap = (
78 config: SshDeviceHostConfig,
79 owner: string,
80 mode: "probe" | "start" | "agent-start" | "stop-agent" | "stop",
81) =>
82 runSshCommand(targetFor(config), {
83 preHostArgs: identityArgs(config),
84 remoteCommandArgs: commandArgs(
85 'command -v node >/dev/null 2>&1 || { echo "Node is missing from the non-interactive SSH PATH" >&2; exit 1; }; exec node',
86 ),
87 stdin: remoteDeviceScript(owner, mode),
88 timeoutMs: mode === "start" || mode === "agent-start" ? 1_300_000 : 45_000,
89 }).pipe(
90 Effect.mapError(
91 (cause) => new DeviceHost.DeviceHostError({ hostId: config.id, step: mode, cause }),
92 ),
93 );
94
95const isSshCommandError = Schema.is(SshCommandError);
96
97// cmd expands only %OS% and PowerShell only $env:OS; POSIX shells expand neither to Windows_NT.
98const explainWindowsHost = Effect.fn("SshDeviceHost.explainWindowsHost")(function* (
99 config: SshDeviceHostConfig,
100 error: DeviceHost.DeviceHostError,
101) {
102 const cause = error.cause;
103 // Windows ssh.exe preserves full remote exit statuses such as 9009.
104 if (
105 !isSshCommandError(cause) ||
106 cause.exitCode === null ||
107 cause.exitCode < 1 ||
108 (cause.exitCode > 254 && cause.exitCode !== 9009)
109 )
110 return yield* error;
111 let windows = yield* runSshCommand(targetFor(config), {
112 preHostArgs: identityArgs(config),
113 remoteCommandArgs: ["echo %OS% $env:OS"],
114 timeoutMs: 15_000,
115 }).pipe(
116 Effect.map(({ stdout }) => /(?:^|\s)Windows_NT(?:\s|$)/u.test(stdout)),
117 Effect.orElseSucceed(() => false),
118 );
119 if (!windows) {
120 // Git Bash does not expand Windows shell variables, but its Node still reports win32.
121 windows = yield* runSshCommand(targetFor(config), {
122 preHostArgs: identityArgs(config),
123 remoteCommandArgs: ["node", "-p", "process.platform"],
124 timeoutMs: 15_000,
125 }).pipe(
126 Effect.map(({ stdout }) => stdout.trim() === "win32"),
127 Effect.orElseSucceed(() => false),
128 );
129 }
130 if (!windows) return yield* error;
131 return yield* new DeviceHost.DeviceHostError({
132 hostId: config.id,
133 step: error.step,
134 cause: new SshWindowsHostError({ cause }),
135 });
136});
137
138const ownerFor = Effect.fn("SshDeviceHost.ownerFor")(function* (hostId: string) {
139 const fs = yield* FileSystem.FileSystem;
140 const server = yield* ServerConfig.ServerConfig;
141 const environmentId = yield* fs
142 .readFileString(server.environmentIdPath)
143 .pipe(Effect.orElseSucceed(() => server.stateDir));
144 const digest = yield* Digest.Digest;
145 const owner = yield* digest
146 .digest(
147 Digest.sha256,
148 new TextEncoder().encode(`${environmentId}\0${server.stateDir}\0${hostId}`),
149 )
150 .pipe(Effect.map(Hex.encode), Effect.orDie);
151 return owner.slice(0, 24);
152});
153
154export const probe = Effect.fn("SshDeviceHost.probe")(function* (
155 config: SshDeviceHostConfig,
156 owner?: string,
157) {
158 const result = yield* bootstrap(config, owner ?? (yield* ownerFor(config.id)), "probe").pipe(
159 Effect.catchTags({ DeviceHostError: (error) => explainWindowsHost(config, error) }),
160 );
161 const value = yield* decodeProbe(result.stdout.trim()).pipe(
162 Effect.mapError(
163 (cause) =>
164 new DeviceHost.DeviceHostError({ hostId: config.id, step: "reading probe result", cause }),
165 ),
166 );
167 return {
168 id: config.id,
169 label: config.label,
170 kind: "ssh",
171 tools: value.tools,
172 hubInstalled:
173 value.tools?.hub.installedVersions.includes(value.tools.hub.requiredVersion) ?? false,
174 agentDeviceInstalled:
175 value.tools?.agent.installedVersions.includes(value.tools.agent.requiredVersion) ?? false,
176 platforms: value.platforms,
177 } satisfies DeviceHostSummary;
178});
179
180export const make = Effect.fn("SshDeviceHost.make")(function* (
181 config: SshDeviceHostConfig,
182 onReady: (
183 ready: DeviceHost.DeviceHostAgentReady,
184 ) => Effect.Effect<void, DeviceHost.DeviceHostError> = () => Effect.void,
185 onStatus: (
186 status: "starting" | "ready" | "failed",
187 detail?: string,
188 ) => Effect.Effect<void> = () => Effect.void,
189) {
190 const fs = yield* FileSystem.FileSystem;
191 const path = yield* Path.Path;
192 const server = yield* ServerConfig.ServerConfig;
193 const net = yield* NetService.NetService;
194 const http = yield* HttpClient.HttpClient;
195 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
196 const digest = yield* Digest.Digest;
197 const parentScope = yield* Scope.Scope;
198 const ssh = yield* resolveSshCommand;
199 const owner = yield* ownerFor(config.id);
200 const provide = <A, E>(
201 effect: Effect.Effect<
202 A,
203 E,
204 | FileSystem.FileSystem
205 | Path.Path
206 | ChildProcessSpawner.ChildProcessSpawner
207 | Digest.Digest
208 | ServerConfig.ServerConfig
209 >,
210 ) =>
211 effect.pipe(
212 Effect.provideService(FileSystem.FileSystem, fs),
213 Effect.provideService(Path.Path, path),
214 Effect.provideService(ServerConfig.ServerConfig, server),
215 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
216 Effect.provideService(Digest.Digest, digest),
217 );
218 const lock = yield* Semaphore.make(1);
219 let stopped = false;
220 let activated = false;
221 let wantsAgent = false;
222 let ready:
223 | (DeviceHost.DeviceHostReady & {
224 agentDevice?: DeviceHost.DeviceHostAgentReady["agentDevice"];
225 })
226 | null = null;
227 let connectionScope: Scope.Closeable | null = null;
228 let summary: DeviceHostSummary = {
229 id: config.id,
230 label: config.label,
231 kind: "ssh",
232 hubInstalled: false,
233 agentDeviceInstalled: false,
234 platforms: [],
235 };
236
237 const run: DeviceHost.DeviceHostReady["run"] = (command, args, options) =>
238 provide(
239 runSshCommand(targetFor(config), {
240 preHostArgs: identityArgs(config),
241 // Match the hub cwd so relative executables and PATH entries resolve identically.
242 remoteCommandArgs: commandArgs(
243 `cd "$HOME/.t3/device/hosts/${owner}" && exec ${[command, ...args].map(quoteRemoteArg).join(" ")}`,
244 ),
245 keepErrorOutputTail: true,
246 ...(options?.stdin === undefined ? {} : { stdin: options.stdin }),
247 ...(options?.timeoutMs === undefined ? {} : { timeoutMs: options.timeoutMs }),
248 }),
249 ).pipe(
250 Effect.map((result) => ({ ...result, code: 0 })),
251 Effect.catch((error) =>
252 Effect.succeed({
253 stdout: "stdout" in error ? (error.stdout ?? "") : "",
254 stderr: error.message,
255 code: "exitCode" in error ? (error.exitCode ?? 127) : 127,
256 }),
257 ),
258 );
259
260 const platformAvailability: DeviceHost.DeviceHost["Service"]["platformAvailability"] = (
261 platform,
262 ) =>
263 provide(probe(config, owner)).pipe(
264 Effect.map((value) => {
265 summary = { ...summary, platforms: value.platforms };
266 return value.platforms.find((p) => p.platform === platform)!;
267 }),
268 Effect.orElseSucceed(() => ({
269 platform,
270 available: false,
271 reason: "Cannot reach device host. Test its SSH connection in Settings.",
272 })),
273 );
274
275 const connectOnce = Effect.fn("SshDeviceHost.connectOnce")(function* (): Effect.fn.Return<
276 DeviceHost.DeviceHostReady & { agentDevice?: DeviceHost.DeviceHostAgentReady["agentDevice"] },
277 DeviceHost.DeviceHostError
278 > {
279 activated = true;
280 const result = yield* provide(bootstrap(config, owner, wantsAgent ? "agent-start" : "start"));
281 yield* onStatus("starting");
282 const remote = yield* decodeStarted(result.stdout.trim()).pipe(
283 Effect.mapError(
284 (cause) =>
285 new DeviceHost.DeviceHostError({
286 hostId: config.id,
287 step: "reading host endpoints",
288 cause,
289 }),
290 ),
291 );
292 summary = {
293 ...summary,
294 platforms: remote.platforms,
295 tools: remote.tools,
296 hubInstalled: true,
297 agentDeviceInstalled: wantsAgent || summary.agentDeviceInstalled,
298 };
299 const hubPort = yield* net.reserveLoopbackPort("127.0.0.1").pipe(
300 Effect.mapError(
301 (cause) =>
302 new DeviceHost.DeviceHostError({
303 hostId: config.id,
304 step: "reserving hub port",
305 cause,
306 }),
307 ),
308 );
309 const daemonPort = yield* net.reserveLoopbackPort("127.0.0.1").pipe(
310 Effect.mapError(
311 (cause) =>
312 new DeviceHost.DeviceHostError({
313 hostId: config.id,
314 step: "reserving daemon port",
315 cause,
316 }),
317 ),
318 );
319 const scope = yield* Scope.make();
320 connectionScope = scope;
321 const child = yield* spawner
322 .spawn(
323 ChildProcess.make(
324 ssh,
325 [
326 ...baseSshArgs(targetFor(config), { batchMode: "yes" }),
327 ...identityArgs(config),
328 "-o",
329 "ExitOnForwardFailure=yes",
330 // Multiplexed clients exit after handing forwards to the master; own this connection.
331 "-o",
332 "ControlMaster=no",
333 "-o",
334 "ControlPath=none",
335 "-o",
336 "ControlPersist=no",
337 "-o",
338 "ServerAliveInterval=10",
339 "-o",
340 "ServerAliveCountMax=3",
341 "-T",
342 "-L",
343 `127.0.0.1:${hubPort}:127.0.0.1:${remote.hubPort}`,
344 ...(remote.daemonPort === undefined
345 ? []
346 : ["-L", `127.0.0.1:${daemonPort}:127.0.0.1:${remote.daemonPort}`]),
347 config.target,
348 // The server holds the only write end of this stdin, so when it exits for any
349 // reason the remote `cat` sees EOF and ssh exits once its forwarded connections
350 // close, instead of being orphaned.
351 "sh",
352 "-c",
353 quoteRemoteArg("exec cat >/dev/null"),
354 ],
355 { stdin: "pipe", stdout: "ignore", stderr: "pipe" },
356 ),
357 )
358 .pipe(
359 Effect.provideService(Scope.Scope, scope),
360 Effect.mapError(
361 (cause) =>
362 new DeviceHost.DeviceHostError({ hostId: config.id, step: "forwarding ports", cause }),
363 ),
364 );
365 let stderr = "";
366 yield* child.stderr.pipe(
367 Stream.decodeText(),
368 Stream.runForEach((chunk) =>
369 Effect.sync(() => {
370 stderr = (stderr + chunk).slice(-2000);
371 }),
372 ),
373 Effect.forkIn(scope),
374 );
375 const hubOrigin = `http://127.0.0.1:${hubPort}`;
376 const next = {
377 nodePath: remote.nodePath,
378 hub: { origin: hubOrigin },
379 devices: makeDeviceHubOperations({
380 hostId: config.id,
381 origin: hubOrigin,
382 http,
383 run,
384 // Keep probing negative reports so an SDK installed after connecting is still found.
385 availablePlatforms: Effect.gen(function* () {
386 const isAvailable = (platform: DevicePlatform) =>
387 summary.platforms.some(
388 (candidate) => candidate.platform === platform && candidate.available,
389 );
390 if (
391 !isAvailable("android") ||
392 (remote.hostPlatform === "darwin" && !isAvailable("ios"))
393 ) {
394 const refreshed = yield* provide(probe(config, owner)).pipe(Effect.result);
395 if (refreshed._tag === "Success") {
396 summary = { ...summary, platforms: refreshed.success.platforms };
397 }
398 }
399 return { ios: isAvailable("ios"), android: isAvailable("android") };
400 }),
401 }),
402 ...(remote.daemonPort !== undefined &&
403 remote.token !== undefined &&
404 remote.entryPath !== undefined
405 ? {
406 agentDevice: {
407 baseUrl: `http://127.0.0.1:${daemonPort}`,
408 token: remote.token,
409 entryPath: remote.entryPath,
410 },
411 }
412 : {}),
413 helpers: remote.helpers,
414 run,
415 };
416 for (const [baseUrl, route] of [
417 [next.hub.origin, "/readyz"],
418 ...(next.agentDevice ? [[next.agentDevice.baseUrl, "/health"]] : []),
419 ]) {
420 yield* waitForHttpReady({
421 baseUrl: baseUrl!,
422 path: route!,
423 timeoutMs: 15000,
424 makeError: () =>
425 new DeviceHost.DeviceHostError({
426 hostId: config.id,
427 step: "waiting for SSH forward",
428 cause: new Error(stderr || "Forwarded endpoint did not answer."),
429 }),
430 }).pipe(Effect.provideService(HttpClient.HttpClient, http));
431 }
432 if (next.agentDevice) yield* onReady({ ...next, agentDevice: next.agentDevice });
433 ready = next.agentDevice
434 ? { ...next, releaseAgentSession: releaseAgentDeviceSession(http, next.agentDevice) }
435 : next;
436 yield* onStatus("ready");
437 // Reconnect also repairs helpers that died while SSH itself stayed connected.
438 // A loaded host can miss a probe or two while still working, and reconnecting
439 // then drops the forward in use, so only consecutive misses count.
440 const unhealthy = Effect.gen(function* () {
441 let misses = 0;
442 while (true) {
443 yield* Effect.sleep("10 seconds");
444 const alive = yield* http.get(`${next.hub.origin}/readyz`).pipe(
445 Effect.timeout("5 seconds"),
446 Effect.map((r) => r.status === 200),
447 Effect.orElseSucceed(() => false),
448 );
449 const daemonAlive = next.agentDevice
450 ? yield* http.get(`${next.agentDevice!.baseUrl}/health`).pipe(
451 Effect.timeout("5 seconds"),
452 Effect.map((r) => r.status === 200),
453 Effect.orElseSucceed(() => false),
454 )
455 : true;
456 misses = alive && daemonAlive ? 0 : misses + 1;
457 if (misses >= UNHEALTHY_PROBE_LIMIT) return;
458 }
459 });
460 yield* Effect.gen(function* () {
461 yield* Effect.raceFirst(child.exitCode.pipe(Effect.ignore), unhealthy);
462 if (stopped || connectionScope !== scope) return;
463 ready = null;
464 yield* onStatus("starting", "Reconnecting to device host…");
465 yield* Scope.close(scope, Exit.void);
466 let delay = 1000;
467 while (true) {
468 if (stopped || connectionScope !== scope) return;
469 yield* Effect.sleep(delay);
470 const result = yield* lock
471 .withPermit(
472 Effect.suspend(() => (stopped || ready ? Effect.void : connect().pipe(Effect.asVoid))),
473 )
474 .pipe(Effect.result);
475 if (result._tag === "Success") return;
476 yield* onStatus("failed", result.failure.message);
477 if (connectionScope && connectionScope !== scope)
478 yield* Scope.close(connectionScope, Exit.void);
479 connectionScope = scope;
480 delay = Math.min(delay * 2, 30000);
481 }
482 }).pipe(Effect.forkIn(parentScope));
483 return next;
484 });
485
486 const closeConnection = Effect.suspend(() => {
487 const failedScope = connectionScope;
488 connectionScope = null;
489 ready = null;
490 return failedScope ? Scope.close(failedScope, Exit.void) : Effect.void;
491 });
492
493 const connect = Effect.fn("SshDeviceHost.connect")(function* () {
494 for (let attempt = 0; ; attempt++) {
495 const result = yield* connectOnce().pipe(
496 Effect.onInterrupt(() => closeConnection),
497 Effect.result,
498 );
499 if (result._tag === "Success") return result.success;
500 yield* closeConnection;
501 // SSH binds after the reservation is released, so a competing bind needs fresh ports.
502 if (
503 attempt >= 2 ||
504 !["forwarding ports", "waiting for SSH forward"].includes(result.failure.step)
505 )
506 return yield* result.failure;
507 }
508 });
509
510 const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = (onPhase) =>
511 lock.withPermit(
512 Effect.gen(function* () {
513 stopped = false;
514 if (ready) return ready;
515 summary = yield* provide(probe(config, owner));
516 yield* onPhase(
517 summary.hubInstalled ? "starting" : "installing",
518 summary.hubInstalled
519 ? undefined
520 : deviceToolInstallMessage("device hub", summary.tools?.hub),
521 );
522 return yield* connect().pipe(
523 Effect.tapError(() =>
524 connectionScope ? Scope.close(connectionScope, Exit.void) : Effect.void,
525 ),
526 );
527 }),
528 );
529 const stop = lock.withPermit(
530 Effect.gen(function* () {
531 stopped = true;
532 ready = null;
533 if (connectionScope) yield* Scope.close(connectionScope, Exit.void);
534 connectionScope = null;
535 if (activated) yield* provide(bootstrap(config, owner, "stop")).pipe(Effect.ignore);
536 activated = false;
537 wantsAgent = false;
538 }),
539 );
540 const changeAgent = (enabled: boolean) =>
541 lock.withPermit(
542 Effect.gen(function* () {
543 wantsAgent = enabled;
544 if (enabled && ready?.agentDevice) return { ...ready, agentDevice: ready.agentDevice };
545 if (!enabled && !ready?.agentDevice) return null;
546 ready = null;
547 const previousScope = connectionScope;
548 connectionScope = null;
549 if (previousScope) yield* Scope.close(previousScope, Exit.void);
550 if (!enabled) yield* provide(bootstrap(config, owner, "stop-agent"));
551 return yield* connect().pipe(
552 Effect.onError(() =>
553 Effect.gen(function* () {
554 const failedScope = connectionScope;
555 connectionScope = null;
556 if (failedScope) yield* Scope.close(failedScope, Exit.void);
557 if (enabled)
558 yield* provide(bootstrap(config, owner, "stop-agent")).pipe(Effect.ignore);
559 }),
560 ),
561 );
562 }),
563 );
564 yield* Effect.addFinalizer(() => stop);
565 return {
566 id: config.id,
567 label: config.label,
568 summary: Effect.sync(() => summary),
569 inspect: provide(probe(config, owner)).pipe(
570 Effect.tap((value) =>
571 Effect.sync(() => {
572 summary = value;
573 }),
574 ),
575 ),
576 current: Effect.sync(() => ready),
577 ensureReady,
578 ensureAgentReady: (onPhase) =>
579 ensureReady(onPhase).pipe(
580 Effect.flatMap(() =>
581 onPhase(
582 summary.agentDeviceInstalled ? "starting" : "installing",
583 summary.agentDeviceInstalled
584 ? undefined
585 : deviceToolInstallMessage("agent tools", summary.tools?.agent),
586 ),
587 ),
588 Effect.flatMap(() => changeAgent(true)),
589 Effect.flatMap((value) =>
590 value?.agentDevice
591 ? Effect.succeed({ ...value, agentDevice: value.agentDevice })
592 : Effect.fail(
593 new DeviceHost.DeviceHostError({
594 hostId: config.id,
595 step: "starting agent tools",
596 cause: new Error("Daemon endpoint missing"),
597 }),
598 ),
599 ),
600 ),
601 stopAgent: changeAgent(false).pipe(Effect.asVoid, Effect.ignore),
602 stop,
603 platformAvailability,
604 } satisfies DeviceHost.DeviceHost["Service"];
605});