Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SshDeviceHost.ts

663 lines23.9 KB

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