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
6 changes: 6 additions & 0 deletions docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,8 @@ silo stop [--name <agent>] [--all]
4. Writes `proxy.running = false` to config
5. Removes the `silo-sandbox-net` Docker network (if no other containers attached)

Exits 1 if any container or the proxy could not be stopped. The rest of the shutdown still runs.

**Stopping a named agent:** When `--name` is used, only that specific container is stopped. The proxy and network remain active for other agents.

**Stopping all agents:** When `--all` is used, all containers with the `managed-by=silo` Docker label are discovered and stopped.
Expand Down Expand Up @@ -626,6 +628,8 @@ Delete a saved snapshot.
silo snapshot delete "clean-install"
```

Exits 1 if the snapshot doesn't exist or can't be deleted.

---

### `silo doctor`
Expand All @@ -638,6 +642,8 @@ silo doctor

Checks: Node.js version, Docker availability, Docker daemon status, config file existence, proxy health, container status.

Exits 1 if any check fails. Warnings alone exit 0, so `silo doctor` can gate a script or CI job.

---

### `silo quickstart`
Expand Down
13 changes: 12 additions & 1 deletion src/commands/doctor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ export async function runDoctor(): Promise<void> {
fix: "Run `silo onboard` to set up SILO",
});
// Can't check more without config
printResults(results);
reportResults(results);
return;
}

Expand Down Expand Up @@ -346,7 +346,18 @@ export async function runDoctor(): Promise<void> {
});
}

reportResults(results);
}

/**
* Print the results and set a failing exit code when any check failed, so
* `silo doctor` can gate scripts and CI. Warnings alone still exit 0.
*/
function reportResults(results: CheckResult[]): void {
printResults(results);
if (results.some((r) => r.status === "fail")) {
process.exitCode = 1;
}
}

// ---------------------------------------------------------------------------
Expand Down
1 change: 1 addition & 0 deletions src/commands/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ export async function runSnapshotDelete(
spinner.succeed(`Snapshot "${chalk.cyan(snapshotName)}" deleted.`);
} catch {
spinner.fail(`Snapshot "${snapshotName}" not found or could not be deleted.`);
process.exitCode = 1;
}

log.blank();
Expand Down
56 changes: 35 additions & 21 deletions src/commands/stop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,15 @@ export async function runStop(opts: StopOptions = {}): Promise<void> {
await assertDockerAvailable();

let stoppedSomething = false;
// What couldn't be stopped. Anything here means a non-zero exit, so scripts
// and uninstall.sh don't carry on as if the sandbox were down.
const failures: string[] = [];

if (opts.all) {
// ── Stop ALL silo-managed containers ────────────────────────────────
stoppedSomething = await stopAllAgents();
const result = await stopAllAgents();
stoppedSomething = result.stopped;
failures.push(...result.failed);
} else {
// ── Stop a single container ────────────────────────────────────────
const containerName = opts.name ? `silo-${opts.name}` : config.sandbox.containerName;
Expand All @@ -50,6 +55,7 @@ export async function runStop(opts: StopOptions = {}): Promise<void> {
} catch (err) {
spinner.fail("Failed to stop proxy daemon");
log.error(err instanceof Error ? err.message : String(err));
failures.push("inference proxy");
}
} else {
log.info("Proxy daemon is not running — skipping.");
Expand All @@ -66,7 +72,11 @@ export async function runStop(opts: StopOptions = {}): Promise<void> {
await cleanupSiloNetwork();
}

if (stoppedSomething) {
if (failures.length > 0) {
log.blank();
log.error(`Could not stop: ${failures.join(", ")}.`);
process.exitCode = 1;
} else if (stoppedSomething) {
log.blank();
log.success("Sandbox shut down cleanly.");
}
Expand Down Expand Up @@ -99,35 +109,39 @@ async function stopSingleAgent(containerName: string): Promise<boolean> {
return false;
}

async function stopAllAgents(): Promise<boolean> {
async function stopAllAgents(): Promise<{ stopped: boolean; failed: string[] }> {
let names: string[];
try {
const { stdout } = await execa("docker", [
"ps", "-a",
"--filter", "label=managed-by=silo",
"--format", "{{.Names}}",
]);
names = stdout.trim().split("\n").filter(Boolean);
} catch (err) {
log.error(`Could not list SILO containers: ${err instanceof Error ? err.message : String(err)}`);
return { stopped: false, failed: ["container list"] };
}

const names = stdout.trim().split("\n").filter(Boolean);
if (names.length === 0) {
log.info("No SILO agent containers found.");
return false;
}
if (names.length === 0) {
log.info("No SILO agent containers found.");
return { stopped: false, failed: [] };
}

let stopped = false;
for (const name of names) {
const spinner = ora(`Stopping "${name}"…`).start();
try {
await stopContainer(name);
spinner.succeed(`Removed "${name}"`);
stopped = true;
} catch (err) {
spinner.fail(`Failed to stop "${name}": ${err instanceof Error ? err.message : String(err)}`);
}
let stopped = false;
const failed: string[] = [];
for (const name of names) {
const spinner = ora(`Stopping "${name}"…`).start();
try {
await stopContainer(name);
spinner.succeed(`Removed "${name}"`);
stopped = true;
} catch (err) {
spinner.fail(`Failed to stop "${name}": ${err instanceof Error ? err.message : String(err)}`);
failed.push(name);
}
return stopped;
} catch {
return false;
}
return { stopped, failed };
}

// ---------------------------------------------------------------------------
Expand Down
97 changes: 95 additions & 2 deletions tests/cli.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeAll, afterAll } from "vitest";
import { execa } from "execa";
import { mkdtempSync, rmSync } from "node:fs";
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
Expand All @@ -11,6 +11,13 @@ import { fileURLToPath } from "node:url";
const repoRoot = fileURLToPath(new URL("..", import.meta.url));
let home: string;

// conf stores the config under $XDG_CONFIG_HOME on Linux when it's set (CI
// runners set it), ignoring HOME. Pin it inside each throwaway HOME, or every
// test shares, and writes to, the runner's real config directory.
function isolatedEnv(homeDir: string): Record<string, string> {
return { HOME: homeDir, XDG_CONFIG_HOME: join(homeDir, ".config") };
}

beforeAll(() => {
home = mkdtempSync(join(tmpdir(), "silo-cli-test-"));
});
Expand All @@ -22,7 +29,7 @@ afterAll(() => {
function silo(...args: string[]) {
return execa("node", ["--import", "tsx", "src/cli.ts", ...args], {
cwd: repoRoot,
env: { HOME: home },
env: isolatedEnv(home),
reject: false,
});
}
Expand All @@ -47,3 +54,89 @@ describe("CLI exit codes", () => {
30_000,
);
});

// ---------------------------------------------------------------------------
// Commands that fail must exit non-zero, so scripts and CI can rely on them.
// A fake `docker` on PATH stands in for the daemon. FAKE_DOCKER_FAIL picks what
// fails: "all", "rmi", or "rm:<container>".
// ---------------------------------------------------------------------------

const FAKE_DOCKER = `#!/bin/sh
[ "$FAKE_DOCKER_FAIL" = "all" ] && { echo "Cannot connect to the Docker daemon" >&2; exit 1; }
case "$1" in
info|version|stop) exit 0 ;;
ps) printf 'silo-a\\nsilo-b\\n'; exit 0 ;;
rm) for a in "$@"; do [ "rm:$a" = "$FAKE_DOCKER_FAIL" ] && { echo "Error: could not remove $a" >&2; exit 1; }; done; exit 0 ;;
rmi) [ "$FAKE_DOCKER_FAIL" = "rmi" ] && { echo "Error: No such image" >&2; exit 1; }; exit 0 ;;
*) exit 1 ;;
esac
`;

describe("exit codes when a command fails", () => {
let fakeBin: string;
let configuredHome: string;

beforeAll(async () => {
fakeBin = mkdtempSync(join(tmpdir(), "silo-fake-docker-"));
writeFileSync(join(fakeBin, "docker"), FAKE_DOCKER);
chmodSync(join(fakeBin, "docker"), 0o755);

// A real, valid config written through the config manager.
configuredHome = mkdtempSync(join(tmpdir(), "silo-cli-home-"));
mkdirSync(join(configuredHome, "ws"));
const write = `
const { writeConfig } = await import("./src/config/manager.ts");
const { SiloConfigSchema } = await import("./src/config/schema.ts");
writeConfig(SiloConfigSchema.parse({
version: "1",
llm: { provider: "openai", apiKey: "sk-test-key", model: "gpt-4o" },
sandbox: { image: "silo-sandbox:latest", containerName: "silo-agent",
workspacePath: ${JSON.stringify(join(configuredHome, "ws"))}, cpuLimit: "1.0", memoryLimit: "1g", autoOpenLogs: false },
}));`;
await execa("node", ["--import", "tsx", "--input-type=module", "-e", write], {
cwd: repoRoot,
env: isolatedEnv(configuredHome),
});
}, 30_000);

afterAll(() => {
rmSync(fakeBin, { recursive: true, force: true });
rmSync(configuredHome, { recursive: true, force: true });
});

function siloWith(homeDir: string, fail: string, ...args: string[]) {
return execa("node", ["--import", "tsx", "src/cli.ts", ...args], {
cwd: repoRoot,
env: { ...isolatedEnv(homeDir), PATH: `${fakeBin}:${process.env.PATH}`, FAKE_DOCKER_FAIL: fail },
reject: false,
});
}

it("doctor exits 1 when a check fails", async () => {
const result = await siloWith(home, "all", "doctor");
expect(result.stdout + result.stderr).toMatch(/critical issue/);
expect(result.exitCode).toBe(1);
}, 30_000);

it("snapshot delete exits 1 when the snapshot can't be deleted", async () => {
const result = await siloWith(configuredHome, "rmi", "snapshot", "delete", "missing");
expect(result.exitCode).toBe(1);
}, 30_000);

it("stop --all exits 1 when a container can't be stopped", async () => {
const result = await siloWith(configuredHome, "rm:silo-b", "stop", "--all");
expect(result.stdout + result.stderr).toMatch(/Could not stop: silo-b/);
expect(result.exitCode).toBe(1);
}, 30_000);

it("stop --all still exits 0 when everything stops", async () => {
const result = await siloWith(configuredHome, "", "stop", "--all");
expect(result.stdout + result.stderr).toMatch(/shut down cleanly/);
expect(result.exitCode).toBe(0);
}, 30_000);

it("snapshot delete still exits 0 when the snapshot is deleted", async () => {
const result = await siloWith(configuredHome, "", "snapshot", "delete", "present");
expect(result.exitCode).toBe(0);
}, 30_000);
});
Loading