feat: add Crestodian setup helper

This commit is contained in:
Peter Steinberger
2026-04-25 08:49:49 +01:00
parent e0bee76fb0
commit 2011de69d3
67 changed files with 4231 additions and 71 deletions

View File

@@ -0,0 +1,110 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { runCli, shouldStartCrestodianForBareRoot } from "../../src/cli/run-main.js";
import { clearConfigCache } from "../../src/config/config.js";
import type { OpenClawConfig } from "../../src/config/types.openclaw.js";
import { runCrestodian } from "../../src/crestodian/crestodian.js";
import type { RuntimeEnv } from "../../src/runtime.js";
function assert(condition: unknown, message: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}
function createRuntime(): { runtime: RuntimeEnv; lines: string[] } {
const lines: string[] = [];
return {
lines,
runtime: {
log: (...args) => lines.push(args.join(" ")),
error: (...args) => lines.push(args.join(" ")),
exit: (code) => {
throw new Error(`exit ${code}`);
},
},
};
}
async function main() {
const stateDir =
process.env.OPENCLAW_STATE_DIR ??
(await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-crestodian-first-run-")));
const configPath = process.env.OPENCLAW_CONFIG_PATH ?? path.join(stateDir, "openclaw.json");
process.env.OPENCLAW_STATE_DIR = stateDir;
process.env.OPENCLAW_CONFIG_PATH = configPath;
await fs.rm(stateDir, { recursive: true, force: true });
await fs.mkdir(stateDir, { recursive: true });
clearConfigCache();
assert(
shouldStartCrestodianForBareRoot(["node", "openclaw"]),
"bare openclaw invocation did not route to Crestodian",
);
process.exitCode = undefined;
await runCli(["node", "openclaw", "onboard", "--modern", "--non-interactive", "--json"]);
assert(
process.exitCode === undefined || process.exitCode === 0,
"modern onboard overview exited nonzero",
);
const overviewRuntime = createRuntime();
await runCrestodian({ message: "overview", interactive: false }, overviewRuntime.runtime);
const overviewOutput = overviewRuntime.lines.join("\n");
assert(
overviewOutput.includes("Config: missing"),
"fresh overview did not report missing config",
);
assert(
overviewOutput.includes('Next: say "setup" to create a starter config'),
"fresh overview did not include setup recommendation",
);
const setupRuntime = createRuntime();
await runCrestodian(
{
message: "setup workspace /tmp/openclaw-first-run model openai/gpt-5.2",
yes: true,
interactive: false,
},
setupRuntime.runtime,
);
const setupOutput = setupRuntime.lines.join("\n");
assert(
setupOutput.includes("[crestodian] done: crestodian.setup"),
"Crestodian setup did not apply",
);
clearConfigCache();
const validateRuntime = createRuntime();
await runCrestodian({ message: "validate config", interactive: false }, validateRuntime.runtime);
assert(
validateRuntime.lines.join("\n").includes("Config valid:"),
"post-setup config validation did not pass",
);
const config = JSON.parse(await fs.readFile(configPath, "utf8")) as OpenClawConfig;
assert(
config.agents?.defaults?.workspace === "/tmp/openclaw-first-run",
"first-run setup did not write default workspace",
);
assert(
config.agents?.defaults?.model &&
typeof config.agents.defaults.model === "object" &&
"primary" in config.agents.defaults.model &&
config.agents.defaults.model.primary === "openai/gpt-5.2",
"first-run setup did not write default model",
);
const auditPath = path.join(stateDir, "audit", "crestodian.jsonl");
const audit = (await fs.readFile(auditPath, "utf8")).trim();
assert(audit.includes('"operation":"crestodian.setup"'), "setup audit entry missing");
console.log("Crestodian first-run Docker E2E passed");
}
main().catch((err) => {
console.error(err);
process.exit(1);
});

View File

@@ -0,0 +1,38 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "$ROOT_DIR/scripts/lib/docker-e2e-image.sh"
IMAGE_NAME="$(docker_e2e_resolve_image "openclaw-crestodian-first-run-e2e" OPENCLAW_CRESTODIAN_FIRST_RUN_E2E_IMAGE)"
CONTAINER_NAME="openclaw-crestodian-first-run-e2e-$$"
RUN_LOG="$(mktemp -t openclaw-crestodian-first-run-log.XXXXXX)"
cleanup() {
docker rm -f "$CONTAINER_NAME" >/dev/null 2>&1 || true
rm -f "$RUN_LOG"
}
trap cleanup EXIT
docker_e2e_build_or_reuse "$IMAGE_NAME" crestodian-first-run
echo "Running in-container Crestodian first-run smoke..."
set +e
docker run --rm \
--name "$CONTAINER_NAME" \
-e "OPENCLAW_STATE_DIR=/tmp/openclaw-state" \
-e "OPENCLAW_CONFIG_PATH=/tmp/openclaw-state/openclaw.json" \
"$IMAGE_NAME" \
bash -lc "set -euo pipefail
node --import tsx scripts/e2e/crestodian-first-run-docker-client.ts
" >"$RUN_LOG" 2>&1
status=${PIPESTATUS[0]}
set -e
if [ "$status" -ne 0 ]; then
echo "Docker Crestodian first-run smoke failed"
cat "$RUN_LOG"
exit "$status"
fi
cat "$RUN_LOG"
echo "OK"

View File

@@ -0,0 +1,267 @@
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { handleCrestodianCommand } from "../../src/auto-reply/reply/commands-crestodian.js";
import { clearConfigCache } from "../../src/config/config.js";
import type { OpenClawConfig } from "../../src/config/types.openclaw.js";
import { runCrestodianRescueMessage } from "../../src/crestodian/rescue-message.js";
type CommandResult = Awaited<ReturnType<typeof handleCrestodianCommand>>;
function assert(condition: unknown, message: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}
function makeParams(commandBody: string, cfg: OpenClawConfig, isGroup = false) {
return {
cfg,
command: {
surface: "whatsapp",
channel: "whatsapp",
channelId: "whatsapp",
ownerList: ["user:owner"],
senderIsOwner: true,
isAuthorizedSender: true,
senderId: "user:owner",
rawBodyNormalized: commandBody,
commandBodyNormalized: commandBody,
from: "user:owner",
to: "account:default",
},
agentId: "default",
isGroup,
} as Parameters<typeof handleCrestodianCommand>[0];
}
async function invoke(commandBody: string, cfg: OpenClawConfig, isGroup = false): Promise<string> {
const result: CommandResult = await handleCrestodianCommand(
makeParams(commandBody, cfg, isGroup),
true,
);
assert(result, `Command was not handled: ${commandBody}`);
assert(!result.shouldContinue, `Command should stop normal agent dispatch: ${commandBody}`);
const text = result.reply?.text;
assert(typeof text === "string", `Command did not return text: ${commandBody}`);
return text;
}
async function main() {
const stateDir =
process.env.OPENCLAW_STATE_DIR ??
(await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-crestodian-")));
const configPath = process.env.OPENCLAW_CONFIG_PATH ?? path.join(stateDir, "openclaw.json");
process.env.OPENCLAW_STATE_DIR = stateDir;
process.env.OPENCLAW_CONFIG_PATH = configPath;
await fs.mkdir(stateDir, { recursive: true });
await fs.writeFile(
configPath,
JSON.stringify(
{
meta: { lastTouchedVersion: "docker-e2e", lastTouchedAt: new Date(0).toISOString() },
agents: { defaults: {} },
},
null,
2,
),
);
clearConfigCache();
const denied = await invoke("/crestodian status", {
crestodian: { rescue: { enabled: true } },
agents: { defaults: { sandbox: { mode: "all" } } },
});
assert(denied.includes("sandboxing is active"), "sandboxed rescue was not denied");
const cfg: OpenClawConfig = {};
const refusedTui = await invoke("/crestodian talk to agent", cfg);
assert(
refusedTui.includes("cannot open the local TUI"),
"remote rescue TUI handoff was not refused",
);
const plan = await invoke("/crestodian set default model openai/gpt-5.2", cfg);
assert(
plan.includes("Reply /crestodian yes to apply"),
"persistent change did not require approval",
);
const applied = await invoke("/crestodian yes", cfg);
assert(applied.includes("Default model: openai/gpt-5.2"), "approved change did not apply");
const configValid = await invoke("/crestodian validate config", cfg);
assert(configValid.includes("Config valid:"), "config validation did not report valid config");
const configSetPlan = await invoke("/crestodian config set gateway.port 19001", cfg);
assert(
configSetPlan.includes("Reply /crestodian yes to apply"),
"generic config set did not require approval",
);
const configSetApplied = await invoke("/crestodian yes", cfg);
assert(configSetApplied.includes("[crestodian] done: config.set"), "generic config set failed");
const refPlan = await invoke(
"/crestodian config set-ref gateway.auth.token env OPENCLAW_GATEWAY_TOKEN",
cfg,
);
assert(
refPlan.includes("Reply /crestodian yes to apply"),
"SecretRef set did not require approval",
);
const refApplied = await invoke("/crestodian yes", cfg);
assert(refApplied.includes("[crestodian] done: config.setRef"), "SecretRef set failed");
const agentPlan = await invoke("/crestodian create agent work workspace /tmp/openclaw-work", cfg);
assert(
agentPlan.includes("Reply /crestodian yes to apply"),
"agent creation did not require approval",
);
const agentApplied = await invoke("/crestodian yes", cfg);
assert(agentApplied.includes("[crestodian] done: agents.create"), "agent creation did not apply");
const setupPlan = await invoke(
"/crestodian setup workspace /tmp/openclaw-setup model openai/gpt-5.2",
cfg,
);
assert(setupPlan.includes("Reply /crestodian yes to apply"), "setup did not require approval");
const setupApplied = await invoke("/crestodian yes", cfg);
assert(setupApplied.includes("[crestodian] done: crestodian.setup"), "setup did not apply");
const gatewayRestarts: string[] = [];
const gatewayCommand = makeParams("/crestodian restart gateway", cfg).command;
const gatewayPlan = await runCrestodianRescueMessage({
cfg,
command: gatewayCommand,
commandBody: "/crestodian restart gateway",
agentId: "default",
isGroup: false,
deps: {
runGatewayRestart: async () => {
gatewayRestarts.push("restart");
},
},
});
assert(
gatewayPlan?.includes("Reply /crestodian yes to apply"),
"gateway restart did not require approval",
);
const gatewayApplied = await runCrestodianRescueMessage({
cfg,
command: gatewayCommand,
commandBody: "/crestodian yes",
agentId: "default",
isGroup: false,
deps: {
runGatewayRestart: async () => {
gatewayRestarts.push("restart");
},
},
});
assert(
gatewayApplied?.includes("[crestodian] done: gateway.restart"),
"gateway restart did not apply",
);
assert(gatewayRestarts.length === 1, "gateway restart dependency was not invoked once");
const doctorRuns: string[] = [];
const doctorCommand = makeParams("/crestodian doctor fix", cfg).command;
const doctorPlan = await runCrestodianRescueMessage({
cfg,
command: doctorCommand,
commandBody: "/crestodian doctor fix",
agentId: "default",
isGroup: false,
deps: {
runDoctor: async (_runtime, options) => {
doctorRuns.push(options.repair ? "repair" : "check");
},
},
});
assert(
doctorPlan?.includes("Reply /crestodian yes to apply"),
"doctor fix did not require approval",
);
const doctorApplied = await runCrestodianRescueMessage({
cfg,
command: doctorCommand,
commandBody: "/crestodian yes",
agentId: "default",
isGroup: false,
deps: {
runDoctor: async (_runtime, options) => {
doctorRuns.push(options.repair ? "repair" : "check");
},
},
});
assert(doctorApplied?.includes("[crestodian] done: doctor.fix"), "doctor fix did not apply");
assert(doctorRuns.join(",") === "repair", "doctor repair dependency was not invoked once");
const updatedConfig = JSON.parse(await fs.readFile(configPath, "utf8")) as OpenClawConfig;
assert(
updatedConfig.agents?.defaults?.model &&
typeof updatedConfig.agents.defaults.model === "object" &&
"primary" in updatedConfig.agents.defaults.model &&
updatedConfig.agents.defaults.model.primary === "openai/gpt-5.2",
"config default model was not updated",
);
assert(updatedConfig.gateway?.port === 19001, "generic config set did not update gateway.port");
assert(
updatedConfig.gateway?.auth?.token &&
typeof updatedConfig.gateway.auth.token === "object" &&
"id" in updatedConfig.gateway.auth.token &&
updatedConfig.gateway.auth.token.id === "OPENCLAW_GATEWAY_TOKEN",
"SecretRef set did not update gateway.auth.token",
);
assert(
updatedConfig.agents?.defaults?.workspace === "/tmp/openclaw-setup",
"setup did not update default workspace",
);
assert(
updatedConfig.agents?.list?.some(
(agent) => agent.id === "work" && agent.workspace === "/tmp/openclaw-work",
),
"agent config was not updated",
);
const auditPath = path.join(stateDir, "audit", "crestodian.jsonl");
const auditLines = (await fs.readFile(auditPath, "utf8")).trim().split("\n");
assert(auditLines.length >= 2, "audit log did not record both operations");
const audits = auditLines.map((line) => JSON.parse(line));
assert(
audits.some((audit) => audit.operation === "config.setDefaultModel"),
"model audit operation missing",
);
assert(
audits.some((audit) => audit.operation === "config.set"),
"config set audit missing",
);
assert(
audits.some((audit) => audit.operation === "config.setRef"),
"SecretRef config audit missing",
);
assert(
audits.some((audit) => audit.operation === "crestodian.setup"),
"setup audit missing",
);
const agentAudit = audits.find((audit) => audit.operation === "agents.create");
assert(agentAudit, "agent audit operation missing");
assert(agentAudit.details?.rescue === true, "audit rescue marker missing");
assert(agentAudit.details?.channel === "whatsapp", "audit channel missing");
assert(agentAudit.details?.senderId === "user:owner", "audit sender missing");
assert(agentAudit.details?.agentId === "work", "audit agent missing");
assert(
audits.some((audit) => audit.operation === "gateway.restart"),
"gateway restart audit operation missing",
);
assert(
audits.some((audit) => audit.operation === "doctor.fix"),
"doctor fix audit missing",
);
console.log("Crestodian rescue Docker E2E passed");
}
main().catch((err) => {
console.error(err);
process.exit(1);
});

View File

@@ -0,0 +1,38 @@
#!/usr/bin/env bash
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
source "$ROOT_DIR/scripts/lib/docker-e2e-image.sh"
IMAGE_NAME="$(docker_e2e_resolve_image "openclaw-crestodian-rescue-e2e" OPENCLAW_CRESTODIAN_RESCUE_E2E_IMAGE)"
CONTAINER_NAME="openclaw-crestodian-rescue-e2e-$$"
RUN_LOG="$(mktemp -t openclaw-crestodian-rescue-log.XXXXXX)"
cleanup() {
docker rm -f "$CONTAINER_NAME" >/dev/null 2>&1 || true
rm -f "$RUN_LOG"
}
trap cleanup EXIT
docker_e2e_build_or_reuse "$IMAGE_NAME" crestodian-rescue
echo "Running in-container Crestodian rescue smoke..."
set +e
docker run --rm \
--name "$CONTAINER_NAME" \
-e "OPENCLAW_STATE_DIR=/tmp/openclaw-state" \
-e "OPENCLAW_CONFIG_PATH=/tmp/openclaw-state/openclaw.json" \
"$IMAGE_NAME" \
bash -lc "set -euo pipefail
node --import tsx scripts/e2e/crestodian-rescue-docker-client.ts
" >"$RUN_LOG" 2>&1
status=${PIPESTATUS[0]}
set -e
if [ "$status" -ne 0 ]; then
echo "Docker Crestodian rescue smoke failed"
cat "$RUN_LOG"
exit "$status"
fi
cat "$RUN_LOG"
echo "OK"

View File

@@ -171,6 +171,7 @@ const lanes = [
weight: 3,
}),
lane("pi-bundle-mcp-tools", "OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:pi-bundle-mcp-tools"),
lane("crestodian-rescue", "OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:crestodian-rescue"),
serviceLane(
"cron-mcp-cleanup",
"OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:cron-mcp-cleanup",
@@ -184,6 +185,10 @@ const lanes = [
serviceLane("config-reload", "OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:config-reload"),
...bundledScenarioLanes,
lane("openai-image-auth", "OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:openai-image-auth"),
lane(
"crestodian-first-run",
"OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:crestodian-first-run",
),
lane("qr", "pnpm test:docker:qr"),
];