Skip to content
15 changes: 13 additions & 2 deletions docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 |
Expand Down Expand Up @@ -2414,6 +2415,16 @@ Totals

## `simlock daemon <start|stop|status|logs [--follow]>`

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
Expand Down
10 changes: 8 additions & 2 deletions src/cli/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,15 @@ Surface: [CLI.md](../../docs/CLI.md) — every command, flag and exit code.
`resolveRequesterId(env, <pid>)`. 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`:
Expand Down
75 changes: 64 additions & 11 deletions src/cli/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import type {
Clock,
DaemonLauncher,
Filesystem,
IpcConnection,
IpcConnector,
ParentWatch,
ParentWatchHandle,
Expand All @@ -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<string | undefined>,
) => Promise<SimlockAdminClient>,
private readonly clock: Clock,
private readonly launcher: DaemonLauncher,
private readonly checkConfig: () => Promise<void>,
) {}

async connect(endpoint: string): Promise<IpcConnection> {
async connect(resolveCredential: () => Promise<string | undefined>): Promise<SimlockAdminClient> {
try {
return await this.ipc.connect(endpoint);
return await this.finishConnection(await this.connectClient(resolveCredential));
} catch (error: unknown) {
if (!(await isUnavailable(error))) throw error;
}
Expand All @@ -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;
Expand All @@ -57,6 +61,48 @@ class AutoLaunchIpcConnector implements IpcConnector {
{},
);
}

private async finishConnection(client: SimlockAdminClient): Promise<SimlockAdminClient> {
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<Clock["setTimer"]> | undefined;
let timedOut = false;
const timeout = new Promise<never>((_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;
Expand Down Expand Up @@ -132,17 +178,17 @@ 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<void> => {
// 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,
filesystem,
modules: await moduleConfigEntries(),
systemStats,
});
});
};

const connect = async (
connector: IpcConnector,
Expand All @@ -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
? {}
Expand Down
Loading
Loading