diff --git a/docs/CLI.md b/docs/CLI.md index b9a0efe87..0f4426960 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -19,7 +19,8 @@ On failure, every command writes one structured line to stderr: `code` is the daemon's own error code where the failure came from the daemon, or a stable CLI-level code otherwise: `USAGE` for bad flags/missing -arguments/unknown commands, `INTERNAL` for anything unexpected. An unknown +arguments/unknown commands, `DAEMON_STARTUP_FAILED` for a failed auto-start, +`INTERNAL` for anything unexpected. An unknown command or a missing required argument gets a `message` that ends with a pointer to `simlock --help`, so a human hitting one from a terminal isn't stranded with only a JSON blob — the full command banner itself is no @@ -78,7 +79,7 @@ command starts it again) to bring the platform up. |---|---|---| | 0 | — | success (for a `lease` that stayed alive: the lease ended normally) | | 1 | `INTERNAL` | internal / unexpected error | -| 1 | `DAEMON_STARTUP_FAILED` | the daemon was started but did not accept connections before the startup timeout | +| 1 | `DAEMON_STARTUP_FAILED` | the daemon was started but did not accept connections before the startup timeout, or answered the handshake then closed before the CLI's startup status probe answered | | 1 | `PROVISION_FAILED` | creating a device for the request failed twice; the message is the driver's error | | 1 | `HISTORY_UNAVAILABLE` | `stats` while `history.db` could not be opened, so the usage figures cannot be read; the daemon's log says why | | 1 | `WORKER_UNREACHABLE` | the gateway cannot reach the worker this lease or request lives on (its uplink is down), or a worker named with `component install --worker` cannot be asked | @@ -2414,6 +2415,16 @@ Totals ## `simlock daemon ` +If a command auto-starts a daemon and it answers the handshake but closes +before the CLI's startup status probe answers, the command reports +`DAEMON_STARTUP_FAILED` (exit 1). The probe shares the launch timeout and runs +before the command's operation, including after a rejected credential falls +back to an agent session. Once status answers (even `starting`), later deaths +report `DAEMON_CONNECTION_LOST`, including while a lease request queues or +boots, during a held lease, or during an operation on the same connection. An +unanswered probe times out with `DAEMON_STARTUP_FAILED`. A connection to an +already listening daemon keeps the usual `DAEMON_CONNECTION_LOST` behavior. + Manage the daemon explicitly. Other commands auto-start it on demand; `daemon` exists for operators and debugging. `start` starts whichever mode `config.mode` selects — a worker (the default) or a gateway — and diff --git a/src/cli/AGENTS.md b/src/cli/AGENTS.md index 6dbbf1f9c..31d000448 100644 --- a/src/cli/AGENTS.md +++ b/src/cli/AGENTS.md @@ -54,9 +54,15 @@ Surface: [CLI.md](../../docs/CLI.md) — every command, flag and exit code. `resolveRequesterId(env, )`. Credential, first found: `--token` → `SIMLOCK_ADMIN_TOKEN` → `admin.token` in the data directory (3 reads, 50 ms apart). None, or a rejected one → an `agent` session and one stderr `notice` line. -3. **Auto-launch** (`AutoLaunchIpcConnector`) — when nothing listens: load the config +3. **Auto-launch** (`AutoLaunchAdminConnector`) — when nothing listens: load the config first (a bad one fails on this stderr), launch the daemon detached, retry every 50 ms - for `DAEMON_STARTUP_TIMEOUT_MS`. + for `DAEMON_STARTUP_TIMEOUT_MS`. After a launch, `status.get` probes the connection + before handing it to a command, within that same deadline. A connection loss during this + probe becomes `DAEMON_STARTUP_FAILED`; a silent probe times out with that code and starts closing + its client without waiting for the daemon to end its side. An answered probe ends the window, including a `starting` status: subsequent + command failures retain their original codes even while a lease queues or boots. + The connector retains the launch deadline across a rejected credential and agent fallback. + A pre-existing daemon is never probed or reclassified; other daemon errors keep their codes. 4. **`simlock lease`** — `requestLease`; progress pushes as JSON lines on stderr; one result line on stdout, with the session's `role` (`--export-env`: shell lines). `--agent-id` sets the requester. Then, unless `--detach`: diff --git a/src/cli/environment.ts b/src/cli/environment.ts index 83bc8d958..78dcf5ad7 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -10,7 +10,6 @@ import type { Clock, DaemonLauncher, Filesystem, - IpcConnection, IpcConnector, ParentWatch, ParentWatchHandle, @@ -20,17 +19,21 @@ import { readLogFile } from "./log-file.js"; import { readPipedStdin } from "./stdio.js"; import type { CliEnvironment, CliEnvironmentPorts } from "./types.js"; -class AutoLaunchIpcConnector implements IpcConnector { +class AutoLaunchAdminConnector { + private startupDeadline: number | undefined; + constructor( - private readonly ipc: IpcConnector, + private readonly connectClient: ( + resolveCredential: () => Promise, + ) => Promise, private readonly clock: Clock, private readonly launcher: DaemonLauncher, private readonly checkConfig: () => Promise, ) {} - async connect(endpoint: string): Promise { + async connect(resolveCredential: () => Promise): Promise { try { - return await this.ipc.connect(endpoint); + return await this.finishConnection(await this.connectClient(resolveCredential)); } catch (error: unknown) { if (!(await isUnavailable(error))) throw error; } @@ -39,10 +42,11 @@ class AutoLaunchIpcConnector implements IpcConnector { // why: the constant lives behind the ports barrel, which loads on the first connection that needs it. const { DAEMON_STARTUP_TIMEOUT_MS } = await import("../ports/index.js"); const deadline = this.clock.now() + DAEMON_STARTUP_TIMEOUT_MS; + this.startupDeadline = deadline; let lastError: unknown; while (this.clock.now() < deadline) { try { - return await this.ipc.connect(endpoint); + return await this.finishConnection(await this.connectClient(resolveCredential)); } catch (error: unknown) { if (!(await isUnavailable(error))) throw error; lastError = error; @@ -57,6 +61,48 @@ class AutoLaunchIpcConnector implements IpcConnector { {}, ); } + + private async finishConnection(client: SimlockAdminClient): Promise { + if (this.startupDeadline === undefined) return client; + const { isSimlockError, SimlockError } = await import("../contract/index.js"); + const remainingMs = Math.max(0, this.startupDeadline - this.clock.now()); + let timer: ReturnType | undefined; + let timedOut = false; + const timeout = new Promise((_resolve, reject) => { + timer = this.clock.setTimer(remainingMs, () => { + timedOut = true; + reject( + new SimlockError( + "DAEMON_STARTUP_FAILED", + "transport", + "Timed out starting simlock daemon: the startup status probe was not answered", + {}, + ), + ); + }); + }); + try { + await Promise.race([client.getStatus(), timeout]); + this.startupDeadline = undefined; + return client; + } catch (error: unknown) { + // why: a daemon that went silent after `hello` never ends its side, so awaiting the close + // would hang the start this deadline bounds; other failures close against a live peer. + if (timedOut) void client.close().catch(() => undefined); + else await client.close(); + if (isSimlockError(error) && error.code === "DAEMON_CONNECTION_LOST") { + throw new SimlockError( + "DAEMON_STARTUP_FAILED", + "transport", + "The daemon closed its connection while starting, before answering the startup status probe", + {}, + ); + } + throw error; + } finally { + if (timer !== undefined) this.clock.cancel(timer); + } + } } /** why: the class lives behind the ports barrel, which this module must not load at CLI start; @@ -132,9 +178,9 @@ export function buildCliEnvironment( const logPath = join(dataDirectory, "daemon.log"); const adminTokenPath = join(dataDirectory, "admin.token"); const requesterId = resolveRequesterId(env, String(process.pid)); - // why: the daemon refuses to boot on a config `loadConfig` rejects and only its log says so; - // loading the same file before the launch puts the `ConfigError` on the CLI's stderr. - const autoLaunchIpc = new AutoLaunchIpcConnector(ipc, clock, launcher, async () => { + const checkConfig = async (): Promise => { + // why: the daemon refuses to boot on a config `loadConfig` rejects and only its log says so; + // loading the same file before the launch puts the `ConfigError` on the CLI's stderr. const { loadConfig } = await import("../core/index.js"); await loadConfig({ configPath, @@ -142,7 +188,7 @@ export function buildCliEnvironment( modules: await moduleConfigEntries(), systemStats, }); - }); + }; const connect = async ( connector: IpcConnector, @@ -166,11 +212,18 @@ export function buildCliEnvironment( }); }; + const autoLaunch = new AutoLaunchAdminConnector( + (resolveCredential) => connect(ipc, resolveCredential), + clock, + launcher, + checkConfig, + ); + return { clock, configPath, requesterId, - connectAdmin: (resolveCredential) => connect(autoLaunchIpc, resolveCredential), + connectAdmin: (resolveCredential) => autoLaunch.connect(resolveCredential), connectExistingAdmin: (resolveCredential) => connect(ipc, resolveCredential), ...(env.SIMLOCK_ADMIN_TOKEN === undefined ? {} diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 9995239a4..0b22c925f 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -2,6 +2,7 @@ import { EventEmitter } from "node:events"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; +import { createServer, type Socket } from "node:net"; import { Readable } from "node:stream"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -16,6 +17,7 @@ import { FakeClock, FakeDaemonLauncher, FakeParentWatch, + IpcError, MemoryFilesystem, MemoryIpcTransport, FakeKeySetFetcher, @@ -24,12 +26,15 @@ import { NoopLogger, type Filesystem, type IdGenerator, + type IpcConnection, + type IpcConnector, } from "../ports/index.js"; import { FakeSystemStats } from "../ports/index.js"; import { type Auth, createAuth } from "../auth/index.js"; import { DaemonEndpointHost } from "../daemon/connection-host.js"; import { DaemonServer } from "../daemon/server.js"; import { + PROTOCOL_VERSION_RANGE, fromWireError, SimlockError, waitingRequestSchema, @@ -1444,6 +1449,336 @@ describe("CLI: auto-launch's failed start (#672)", () => { }); }); +describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", () => { + it.each([ + { closeAfter: "hello", rejectedCredential: false }, + { closeAfter: "request", rejectedCredential: false }, + { closeAfter: "hello", rejectedCredential: true }, + { closeAfter: "request", rejectedCredential: true }, + ] as const)( + "reports a daemon it launched that answers hello then dies during that start as a failed start, not a lost connection (after $closeAfter, credential rejected: $rejectedCredential)", + async ({ closeAfter, rejectedCredential }) => { + // why: this stages the daemon that loses its HTTP port race exactly as the socket shows it + // to the CLI: absent before the launch, then listening, answering `hello`, and closing on + // its own `http-start-failed` stop before the command's first real request is answered. + const dyingDaemon = new HelloThenDeathIpc(closeAfter, rejectedCredential); + const clock = new FakeClock(0); + const launcher = new FakeDaemonLauncher(() => { + dyingDaemon.startListening(); + }); + const output = outputCapture({ + filesystem: new MemoryFilesystem(), + clock, + systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), + ipc: dyingDaemon, + launcher, + dataDirectory: "/simlock", + }); + let settled = false; + const exitCode = runCli( + ["daemon", "start", "--json", "--token", "probe"], + output.environmentWith(), + ).then((code) => { + settled = true; + return code; + }); + // why: the tick bound is generous because #671 made every module a command loads lazy, so + // one `daemon start` now passes through several more import turns than when this repro was + // first staged; the clock is fake and the loop stops the moment the command settles, so the + // extra headroom pins nothing -- it only keeps a hung command failing on this named + // assertion instead of on a test timeout. + for (let tick = 0; tick < 100 && !settled; tick += 1) { + clock.advance(50); + await settle(); + await settle(); + } + expect( + settled, + `simlock daemon start still had not settled at ${String(clock.now())}ms`, + ).toBe(true); + + // why: the staging itself, proven from the fake's side -- the socket was absent until this + // command launched the daemon and answered `hello` before it closed the connection. Without + // these the assertion below could be + // reached by a connection that never saw a daemon at all. + expect(launcher.launches).toBe(1); + expect(dyingDaemon.helloReplies).toBe(1); + expect(dyingDaemon.deaths).toBe(1); + expect(dyingDaemon.rejectedCredentials).toBe(rejectedCredential ? 1 : 0); + + expect(await exitCode).toBe(1); + expect(output.stdout).toBe(""); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1)!)).toMatchObject({ + error: { + code: "DAEMON_STARTUP_FAILED", + message: expect.stringContaining("daemon"), + }, + }); + }, + ); + + it.each([false, true])( + "keeps a pre-existing daemon's hello-then-close as DAEMON_CONNECTION_LOST (credential rejected: %s)", + async (rejectedCredential) => { + const dyingDaemon = new HelloThenDeathIpc("hello", rejectedCredential); + dyingDaemon.startListening(); + const launcher = new FakeDaemonLauncher(); + const output = outputCapture({ + ...realCliEnvironmentPorts(), + ipc: dyingDaemon, + launcher, + }); + + expect( + await runCli(["daemon", "start", "--json", "--token", "probe"], output.environmentWith()), + ).toBe(1); + expect(launcher.launches).toBe(0); + expect(dyingDaemon.helloReplies).toBe(1); + expect(dyingDaemon.deaths).toBe(1); + expect(output.stdout).toBe(""); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1)!)).toEqual({ + error: { code: "DAEMON_CONNECTION_LOST", message: "Daemon connection closed" }, + }); + }, + ); + + it("preserves DAEMON_STOPPING from the startup status probe and closes its client", async () => { + const daemon = new HelloThenDeathIpc("stopping"); + const launcher = new FakeDaemonLauncher(() => daemon.startListening()); + const output = outputCapture({ ...realCliEnvironmentPorts(), ipc: daemon, launcher }); + expect(await runCli(["daemon", "start", "--token", "probe"], output.environmentWith())).toBe(1); + expect(launcher.launches).toBe(1); + expect(daemon.helloReplies).toBe(1); + expect(daemon.clientCloses).toBe(1); + expect(JSON.parse(output.stderr)).toMatchObject({ error: { code: "DAEMON_STOPPING" } }); + }); + + it("bounds the startup status probe by the original launch deadline and closes its client", async () => { + const daemon = new HelloThenDeathIpc("silent"); + const clock = new FakeClock(0); + const launcher = new FakeDaemonLauncher(() => { + clock.setTimer(19_000, () => daemon.startListening()); + }); + const output = outputCapture({ ...realCliEnvironmentPorts(), ipc: daemon, clock, launcher }); + let settled = false; + const run = runCli(["daemon", "start", "--token", "probe"], output.environmentWith()).then( + (code) => { + settled = true; + return code; + }, + ); + for (let tick = 0; tick < 500 && !settled; tick += 1) { + clock.advance(50); + await settle(); + } + expect(settled, "silent startup probe must settle within the launch budget").toBe(true); + expect( + clock.now(), + "probe must use the budget left after the socket appeared", + ).toBeLessThanOrEqual(20_050); + expect(clock.now(), "probe must wait out the launch deadline").toBeGreaterThanOrEqual(20_000); + expect(await run).toBe(1); + expect(launcher.launches).toBe(1); + expect(daemon.helloReplies).toBe(1); + expect(daemon.clientCloses).toBe(1); + expect(JSON.parse(output.stderr)).toMatchObject({ + error: { + code: "DAEMON_STARTUP_FAILED", + message: expect.stringContaining("Timed out starting"), + }, + }); + }); + + it("fails a start with DAEMON_STARTUP_FAILED when the daemon stops reading after hello, without waiting for its side of the close", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-wedged-")); + temporaryDirectories.push(directory); + const socketPath = join(directory, "daemon.sock"); + const sockets: Socket[] = []; + let hellos = 0; + const server = createServer((socket) => { + sockets.push(socket); + let buffered = ""; + socket.on("data", (chunk) => { + buffered += chunk.toString(); + for (const line of buffered.split("\n").slice(0, -1)) { + const frame = JSON.parse(line) as { id: number; type: string }; + if (frame.type !== "hello") continue; + hellos += 1; + socket.write( + `${JSON.stringify({ + id: frame.id, + ok: true, + payload: { + protocolVersion: PROTOCOL_VERSION_RANGE.max, + daemonProtocolRange: PROTOCOL_VERSION_RANGE, + version: "0.0.0-test", + role: "admin", + principal: "test-requester", + }, + })}\n`, + ); + // why: a daemon wedged after `hello` neither answers nor ends its side of the socket. + socket.pause(); + } + buffered = buffered.slice(buffered.lastIndexOf("\n") + 1); + }); + }); + await new Promise((resolve) => server.listen(socketPath, resolve)); + try { + const real = new NodeIpcTransport(); + let launched = false; + const clock = new FakeClock(0); + const launcher = new FakeDaemonLauncher(() => { + launched = true; + }); + const ipc: IpcConnector = { + connect: async () => { + if (!launched) throw new IpcError("endpoint-not-found", "not yet", undefined); + return real.connect(socketPath); + }, + }; + const output = outputCapture({ ...realCliEnvironmentPorts(), ipc, clock, launcher }); + let settled = false; + const run = runCli(["daemon", "start", "--token", "probe"], output.environmentWith()).then( + (code) => { + settled = true; + return code; + }, + ); + for (let tick = 0; tick < 200 && hellos === 0; tick += 1) { + clock.advance(50); + await new Promise((resolve) => setTimeout(resolve, 5)); + } + expect(hellos).toBe(1); + clock.advance(20_000); + await expect.poll(() => settled, { timeout: 2_000 }).toBe(true); + expect(await run).toBe(1); + expect(JSON.parse(output.stderr)).toMatchObject({ + error: { code: "DAEMON_STARTUP_FAILED" }, + }); + } finally { + for (const socket of sockets) socket.destroy(); + await new Promise((resolve) => server.close(() => resolve())); + } + }); + + it.each([ + { operation: "pending lease", health: "running" }, + { operation: "pending lease", health: "starting" }, + { operation: "held lease", health: "running" }, + { operation: "in-flight request", health: "running" }, + ] as const)( + "keeps an auto-launched daemon's death after its startup status probe as DAEMON_CONNECTION_LOST during $operation (status: $health)", + async ({ operation, health }) => { + const ipc = new MemoryIpcTransport(); + const clock = new FakeClock(0); + const requests: string[] = []; + const replies: string[] = []; + const connections: IpcConnection[] = []; + const launcher = new FakeDaemonLauncher(async () => { + await ipc.listen("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/simlock/daemon.sock", (connection) => { + connections.push(connection); + connection.onData((contents) => { + const frame = JSON.parse(contents) as { id: number; type: string }; + requests.push(frame.type); + const payload = + frame.type === "hello" + ? { + protocolVersion: PROTOCOL_VERSION_RANGE.max, + daemonProtocolRange: PROTOCOL_VERSION_RANGE, + version: "0.0.0-test", + role: "admin", + principal: "test-requester", + } + : frame.type === "lease.request" && operation !== "pending lease" + ? detachedGrant + : frame.type === "status.get" + ? { ...EMPTY_STATUS, daemon: { ...EMPTY_STATUS.daemon, health } } + : undefined; + if (payload === undefined) return; + replies.push(frame.type); + void connection.write(`${JSON.stringify({ id: frame.id, ok: true, payload })}\n`); + }); + }); + }); + const output = outputCapture({ + ...realCliEnvironmentPorts(), + ipc, + clock, + launcher, + }); + let settled = false; + const runPromise = runCli( + operation !== "in-flight request" + ? ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--token", "probe"] + : ["simctl", "list", "--token", "probe"], + output.environmentWith(), + ).then((code) => { + settled = true; + return code; + }); + const ready = (): boolean => + operation === "held lease" + ? output.stdout !== "" + : requests.includes( + operation === "pending lease" ? "lease.request" : "driver.passthrough", + ); + for (let tick = 0; tick < 100 && !ready() && !settled; tick += 1) { + clock.advance(50); + await settle(); + await settle(); + } + expect(ready()).toBe(true); + expect(settled).toBe(false); + expect(launcher.launches).toBe(1); + expect(connections).toHaveLength(1); + expect(requests).toContain( + operation === "in-flight request" ? "driver.passthrough" : "lease.request", + ); + if (operation === "pending lease") expect(replies).not.toContain("lease.request"); + await connections[0]!.close(); + expect(await runPromise).toBe(1); + expect(JSON.parse(output.stderr)).toMatchObject({ + error: { code: "DAEMON_CONNECTION_LOST" }, + }); + expect(replies).toContain("status.get"); + if (operation === "held lease") { + expect(JSON.parse(output.stdout)).toMatchObject({ lease: detachedGrant.lease }); + expect(JSON.parse(output.stderr).error.message).toContain(detachedGrant.lease.id); + expect(requests).toContain("lease.request"); + } else { + expect(output.stdout).toBe(""); + } + }, + ); + + it("preserves the daemon's refusal of the first auto-launched request", async () => { + const filesystem = new MemoryFilesystem(); + const ipc = new MemoryIpcTransport(); + const launcher = new FakeDaemonLauncher(async () => { + await startInMemoryDaemon({ + filesystem, + ipcTransport: ipc, + socketPath: "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/simlock/daemon.sock", + adminTokenPath: "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/simlock/admin.token", + }); + }); + const output = outputCapture({ + ...realCliEnvironmentPorts(), + filesystem, + ipc, + launcher, + }); + + expect( + await runCli(["lease", "--platform", "android", "--detach"], output.environmentWith()), + ).toBe(12); + expect(launcher.launches).toBe(1); + expect(output.stdout).toBe(""); + expect(JSON.parse(output.stderr)).toMatchObject({ error: { code: "NO_DRIVER" } }); + }); +}); + describe("CLI: daemon status (ADR 0003 §11)", () => { it("reports stopped when the socket cannot be reached at all", async () => { const output = outputCapture(); @@ -6420,6 +6755,138 @@ function outputCapture(ports?: CliEnvironmentPorts): OutputCapture { return capture; } +class HelloThenDeathIpc implements IpcConnector { + helloReplies = 0; + deaths = 0; + #listening = false; + + rejectedCredentials = 0; + clientCloses = 0; + + constructor( + readonly closeAfter: "hello" | "request" | "silent" | "stopping" = "hello", + readonly rejectCredential = false, + ) {} + + startListening(): void { + this.#listening = true; + } + + async connect(): Promise { + if (!this.#listening) { + throw new IpcError("endpoint-not-found", "No IPC endpoint yet", undefined); + } + return new HelloThenDeathConnection(this); + } +} + +class HelloThenDeathConnection implements IpcConnection { + readonly #dataListeners = new Set<(chunk: string) => void>(); + readonly #closeListeners = new Set<() => void>(); + #closed = false; + + constructor(private readonly daemon: HelloThenDeathIpc) {} + + get closed(): boolean { + return this.#closed; + } + + onData(listener: (chunk: string) => void): () => void { + this.#dataListeners.add(listener); + return () => this.#dataListeners.delete(listener); + } + + onClose(listener: () => void): () => void { + this.#closeListeners.add(listener); + return () => this.#closeListeners.delete(listener); + } + + onError(): () => void { + return () => {}; + } + + async write(contents: string): Promise { + if (this.#closed) return; + let answeredHello = false; + for (const line of contents.split("\n")) { + answeredHello = this.#receiveFrame(line) || answeredHello; + if (this.#closed) return; + } + if ( + this.daemon.closeAfter === "hello" || + (!answeredHello && this.daemon.closeAfter === "request") + ) + this.#shutDown(true); + } + + #receiveFrame(line: string): boolean { + if (line.trim() === "") return false; + const frame = JSON.parse(line) as { + id?: unknown; + type?: unknown; + payload?: { credential?: string }; + }; + if (frame.type === "status.get" && this.daemon.closeAfter === "stopping") { + const reply = { + id: frame.id, + ok: false, + error: { + code: "DAEMON_STOPPING", + message: "Daemon is stopping", + details: {}, + }, + }; + for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); + } + if (frame.type !== "hello" || typeof frame.id !== "number") return false; + this.#answerHello(frame.id, frame.payload?.credential); + return true; + } + + #answerHello(id: number, credential: string | undefined): void { + if (this.daemon.rejectCredential && credential !== undefined) { + this.daemon.rejectedCredentials += 1; + const reply = { + id: id, + ok: false, + error: { + code: "ADMIN_AUTHENTICATION_FAILED", + message: "Rejected credential", + details: {}, + }, + }; + for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); + this.#shutDown(false); + return; + } + this.daemon.helloReplies += 1; + const reply = { + id: id, + ok: true, + payload: { + protocolVersion: PROTOCOL_VERSION_RANGE.max, + daemonProtocolRange: PROTOCOL_VERSION_RANGE, + version: "0.0.0-test", + role: "admin", + principal: "test-requester", + }, + }; + for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); + } + + async close(): Promise { + this.daemon.clientCloses += 1; + this.#shutDown(false); + } + + #shutDown(killedByDaemon: boolean): void { + if (this.#closed) return; + this.#closed = true; + if (killedByDaemon) this.daemon.deaths += 1; + for (const listener of this.#closeListeners) listener(); + } +} + function sequence(): IdGenerator { let next = 0; return { generate: () => `id${next++}` }; diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 23538c28b..465846957 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -17,8 +17,6 @@ Flows: [startup](../../docs/internal/flows/startup.md), [device.exec](../../docs | `dispatch.ts` | `runDispatch` pipeline, `DispatchSession`, `DispatchError` | | `dispatcher.ts` | `Dispatcher`: the worker's handlers | | `connection-host.ts` | `DaemonEndpointHost`: socket claim, stale-socket recovery | -| `admin-secret.ts` | `AdminSecretManager`: per-start secret, `admin.token` | -| `session.ts` | `createCredentialRoleResolver`: credential → role | | `owner-routed-facts.ts` | `OwnerRoutedFactBus`: lease facts with their owner | | `gateway-uplink.ts` | `GatewayUplink`: a worker's dial to its gateway | | `relay.ts` | `RelayTargets`, `RelayConnection`: relays over the uplink |