Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/cli/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ Surface: [cli.mdx](../../website/src/content/docs/docs/reference/cli.mdx) — ev
first (a bad one fails on this stderr), launch the daemon detached, retry every 50 ms
for `DAEMON_STARTUP_TIMEOUT_MS`; a launched daemon that exits fails the command at once
with `startErrorFrom`'s text, unless another daemon answers a last connect. After a launch, `status.get` probes the connection
before handing it to a command, within that same deadline. A connection loss during this
before handing it to a command, within that same deadline. A connection loss during the handshake or 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.
Expand Down
52 changes: 30 additions & 22 deletions src/cli/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class AutoLaunchAdminConnector {

async connect(resolveCredential: () => Promise<string | undefined>): Promise<SimlockAdminClient> {
try {
return await this.finishConnection(await this.connectClient(resolveCredential));
return await this.finishConnection(this.connectClient(resolveCredential));
} catch (error: unknown) {
if (!(await isUnavailable(error))) throw error;
}
Expand All @@ -52,7 +52,7 @@ class AutoLaunchAdminConnector {
let lastError: unknown;
while (this.clock.now() < deadline) {
try {
return await this.finishConnection(await this.connectClient(resolveCredential));
return await this.finishConnection(this.connectClient(resolveCredential));
} catch (error: unknown) {
if (!(await isUnavailable(error))) throw error;
lastError = error;
Expand All @@ -77,7 +77,7 @@ class AutoLaunchAdminConnector {
): Promise<SimlockAdminClient> {
const output = await launched.readOutput().catch(() => "");
try {
return await this.finishConnection(await this.connectClient(resolveCredential));
return await this.finishConnection(this.connectClient(resolveCredential));
} catch (error: unknown) {
if (!(await isUnavailable(error))) throw error;
}
Expand All @@ -86,35 +86,43 @@ class AutoLaunchAdminConnector {
throw new SimlockError("DAEMON_STARTUP_FAILED", "transport", startErrorFrom(exit, output), {});
}

private async finishConnection(client: SimlockAdminClient): Promise<SimlockAdminClient> {
if (this.startupDeadline === undefined) return client;
private async finishConnection(
connecting: Promise<SimlockAdminClient>,
): Promise<SimlockAdminClient> {
const { isSimlockError, SimlockError } = await import("../contract/index.js");
const remainingMs = Math.max(0, this.startupDeadline - this.clock.now());
let client: SimlockAdminClient | undefined;
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 {
client = await connecting;
if (this.startupDeadline === undefined) return client;
const remainingMs = Math.max(0, this.startupDeadline - this.clock.now());
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",
{},
),
);
});
});
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") {
if (timedOut) void client?.close().catch(() => undefined);
else await client?.close();
if (
this.startupDeadline !== undefined &&
isSimlockError(error) &&
error.code === "DAEMON_CONNECTION_LOST"
) {
throw new SimlockError(
"DAEMON_STARTUP_FAILED",
"transport",
Expand Down
83 changes: 82 additions & 1 deletion src/cli/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1743,10 +1743,19 @@ describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)",
const launcher = new FakeDaemonLauncher(() => {
launched = true;
});
let probeSent = false;
const ipc: IpcConnector = {
connect: async () => {
if (!launched) throw new IpcError("endpoint-not-found", "not yet", undefined);
return real.connect(socketPath);
const connection = await real.connect(socketPath);
const write = connection.write.bind(connection);
connection.write = async (contents) => {
await write(contents);
if ((JSON.parse(contents.trim()) as { type: string }).type === "status.get") {
probeSent = true;
}
};
return connection;
},
};
const output = outputCapture({ ...realCliEnvironmentPorts(), ipc, clock, launcher });
Expand All @@ -1762,6 +1771,9 @@ describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)",
await new Promise((resolve) => setTimeout(resolve, 5));
}
expect(hellos).toBe(1);
// why: the server observing hello does not mean the client has read its reply and armed
// the probe deadline; advance the fake clock only after the client sends that probe.
await expect.poll(() => probeSent).toBe(true);
clock.advance(20_000);
await expect.poll(() => settled, { timeout: 2_000 }).toBe(true);
expect(await run).toBe(1);
Expand All @@ -1774,6 +1786,75 @@ describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)",
}
});

it("exits 1 for a socket closed before hello and reports DAEMON_STARTUP_FAILED only after launch", async () => {
for (const scenario of [
{ launch: false, afterExit: false, code: "DAEMON_CONNECTION_LOST", connects: 1 },
{ launch: true, afterExit: false, code: "DAEMON_STARTUP_FAILED", connects: 2 },
{ launch: true, afterExit: true, code: "DAEMON_STARTUP_FAILED", connects: 3 },
]) {
const directory = await mkdtemp(join(tmpdir(), "simlock-closed-"));
temporaryDirectories.push(directory);
const socketPath = join(directory, "daemon.sock");
let accepted = 0;
// why: the daemon that refuses its history accepts the CLI's connection, then stops and
// closes it; the CLI is still reading `admin.token` then, so the close lands before `hello`.
const server = createServer((socket) => {
accepted += 1;
socket.destroy();
});
await new Promise<void>((resolve) => server.listen(socketPath, resolve));
try {
const real = new NodeIpcTransport();
let launched = !scenario.launch;
const clock = new FakeClock(0);
const launcher = new FakeDaemonLauncher(
() => {
launched = true;
},
{ exit: { code: 1, signal: null } },
);
let connects = 0;
const ipc: IpcConnector = {
connect: async () => {
connects += 1;
if (!launched || (scenario.afterExit && connects === 2)) {
throw new IpcError("endpoint-not-found", "not yet", undefined);
}
const connection = await real.connect(socketPath);
await expect.poll(() => connection.closed).toBe(true);
return connection;
},
};
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 < 100 && !settled; tick += 1) {
clock.advance(50);
await new Promise((resolve) => setTimeout(resolve, 5));
}
expect(launcher.launches).toBe(scenario.launch ? 1 : 0);
expect(accepted).toBe(1);
expect(connects).toBe(scenario.connects);
expect(
settled,
`simlock daemon start still had not settled at ${String(clock.now())}ms`,
).toBe(true);
expect(await run).toBe(1);
expect(output.stdout).toBe("");
expect(JSON.parse(output.stderr.trim().split("\n").at(-1)!)).toMatchObject({
error: { code: scenario.code },
});
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
}
});

it.each([
{ operation: "pending lease", health: "running" },
{ operation: "pending lease", health: "starting" },
Expand Down
3 changes: 2 additions & 1 deletion src/mcp/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ Surface: [connect-your-agent.mdx](../../website/src/content/docs/docs/getting-st
(`connection-refused`, `endpoint-not-found`), retries every 50 ms for
`startupTimeoutMs` (default `DAEMON_STARTUP_TIMEOUT_MS`), else `DAEMON_STARTUP_FAILED`;
a launched daemon that exits fails at once with `startErrorFrom`'s text, unless another
daemon answers a last connect;
daemon answers a last connect; a connection lost during the launched daemon's handshake
is `DAEMON_STARTUP_FAILED`, while a pre-existing daemon keeps `DAEMON_CONNECTION_LOST`;
- the renew timer → `connectToRunningDaemon`: never launches.
The lease survives either way: the daemon released nothing.
7. **End** — stdin EOF, `SIGINT`/`SIGTERM` or transport close → `McpSession.close`: stop
Expand Down
90 changes: 90 additions & 0 deletions src/mcp/connect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,3 +160,93 @@ describe("MCP: auto-launch's daemon that exits while starting (#760)", () => {
expect(result).toBe("The daemon exited with code 3 while starting; see `simlock daemon logs`");
});
});

// why: the stdio host mocks this connector; this seam can force a socket to close before hello
// both in the launch loop and in the final connection after the launched process exits.
describe("MCP: a socket closed before hello (#790)", () => {
it("reports only a closed handshake after launching the daemon as a failed start", async () => {
for (const scenario of [
{
launch: false,
afterExit: false,
refused: false,
code: "DAEMON_CONNECTION_LOST",
connects: 1,
},
{
launch: true,
afterExit: false,
refused: false,
code: "DAEMON_STARTUP_FAILED",
connects: 2,
},
{ launch: true, afterExit: true, refused: false, code: "DAEMON_STARTUP_FAILED", connects: 3 },
{
launch: true,
afterExit: false,
refused: true,
code: "ADMIN_AUTHENTICATION_FAILED",
connects: 2,
},
{
launch: true,
afterExit: true,
refused: true,
code: "ADMIN_AUTHENTICATION_FAILED",
connects: 3,
},
]) {
const transport = new MemoryIpcTransport();
const socketPath = "/simlock/daemon.sock";
let accepted = 0;
const listen = () =>
transport.listen(socketPath, (connection) => {
accepted += 1;
if (scenario.refused) {
connection.onData((chunk) => {
const frame = JSON.parse(chunk.trim()) as { id: number };
void connection.write(
`${JSON.stringify({
id: frame.id,
ok: false,
error: { code: "ADMIN_AUTHENTICATION_FAILED", message: "refused" },
})}\n`,
);
});
} else {
void connection.close();
}
});
if (!scenario.launch) await listen();
const launcher = new FakeDaemonLauncher(
async () => {
await listen();
},
{ exit: { code: 1, signal: null } },
);
let connects = 0;
const result = await connectWithAutoLaunch({
clock: new FakeClock(0),
ipc: {
connect: async (endpoint) => {
connects += 1;
if (scenario.afterExit && connects === 2) {
throw new IpcError("endpoint-not-found", "not yet listening", undefined);
}
return transport.connect(endpoint);
},
},
launcher,
principal: "agent-1",
socketPath,
}).then(
() => ({ code: "connected" }),
(error: unknown) => error,
);
expect(result, JSON.stringify(scenario)).toMatchObject({ code: scenario.code });
expect(launcher.launches).toBe(scenario.launch ? 1 : 0);
expect(connects).toBe(scenario.connects);
expect(accepted).toBe(1);
}
});
});
22 changes: 20 additions & 2 deletions src/mcp/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export async function connectWithAutoLaunch(
let lastError: unknown;
while (options.clock.now() < deadline) {
try {
return await connectToRunningDaemon(options);
return await connectStartingDaemon(options);
} catch (error: unknown) {
if (!isUnavailable(error)) throw error;
lastError = error;
Expand All @@ -88,13 +88,31 @@ async function connectAfterExit(
): Promise<SimlockClient> {
const output = await launched.readOutput().catch(() => "");
try {
return await connectToRunningDaemon(options);
return await connectStartingDaemon(options);
} catch (error: unknown) {
if (!isUnavailable(error)) throw error;
}
throw new SimlockError("DAEMON_STARTUP_FAILED", "transport", startErrorFrom(exit, output), {});
}

async function connectStartingDaemon(
options: ConnectToRunningDaemonOptions,
): Promise<SimlockClient> {
try {
return await connectToRunningDaemon(options);
} catch (error: unknown) {
if (isSimlockError(error) && error.code === "DAEMON_CONNECTION_LOST") {
throw new SimlockError(
"DAEMON_STARTUP_FAILED",
"transport",
"The daemon closed its connection while starting, before answering hello",
{},
);
}
throw error;
}
}

/**
* Connects only to a daemon that is already listening, and never launches one -- which is
* exactly `connectWithAutoLaunch` minus its one extra power, so the latter is written in terms
Expand Down
7 changes: 6 additions & 1 deletion src/simlock-client/wire.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,11 @@ export class SimlockWire {
new SimlockError("DAEMON_CONNECTION_LOST", "transport", "Daemon connection closed", {}),
),
);
if (connection.closed) {
this.#die(
new SimlockError("DAEMON_CONNECTION_LOST", "transport", "Daemon connection closed", {}),
);
}
}

/** Sends `hello` and returns its reply, or throws the contract's typed mismatch/auth error.
Expand Down Expand Up @@ -205,7 +210,6 @@ export class SimlockWire {
* `client.ts` is responsible for input/output schema validation; this only moves bytes and
* correlates frame ids. */
call(type: string, payload: unknown, hooks: CallHooks = {}): Promise<unknown> {
if (this.#dead !== undefined) return Promise.reject(this.#dead);
return this.#send(type, payload, hooks);
}

Expand Down Expand Up @@ -233,6 +237,7 @@ export class SimlockWire {
}

#send(type: string, payload: unknown, hooks: CallHooks): Promise<unknown> {
if (this.#dead !== undefined) return Promise.reject(this.#dead);
const id = this.#nextId++;
return new Promise((resolve, reject) => {
this.#pending.set(id, { ...hooks, reject, resolve });
Expand Down
2 changes: 1 addition & 1 deletion website/src/content/docs/docs/reference/errors.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ Branch on `code`, not on the message: the message wording can change, the code d

| Code | Exit | HTTP | Meaning | What to do |
| --- | --- | --- | --- | --- |
| `DAEMON_STARTUP_FAILED` | 1 | 503 | The CLI started the daemon, and it did not answer within 20 seconds, exited while starting, or closed the connection before it finished. The message carries the daemon's start error. | Read the message and `simlock daemon logs`, fix the cause (often the configuration), and run the command again. |
| `DAEMON_STARTUP_FAILED` | 1 | 503 | The CLI started the daemon, and it did not answer within 20 seconds, exited while starting, or closed the connection during the handshake or before the startup check finished. The message carries the daemon's start error. | Read the message and `simlock daemon logs`, fix the cause (often the configuration), and run the command again. |
| `DAEMON_CONNECTION_LOST` | 1 | 503 | The connection to the daemon dropped mid-command. A lease held by `simlock lease` is not released and stays yours until its deadline. | Start the daemon again; renew the lease with `simlock lease renew <lease-id>` or let it expire. |
| `DAEMON_STOPPING` | 1 | 503 | The daemon is shutting down, or stopped while an install was running. | Run the command again once the daemon is back. |
| `PROTOCOL_VERSION_UNSUPPORTED` | 1 | 400 | The CLI and the running daemon are different Simlock versions that cannot talk to each other. | Restart the daemon after an upgrade: `simlock daemon stop`, then any command. |
Expand Down
Loading