Skip to content

Commit 9056d4f

Browse files
committed
feat: add crestodian local planner fallback
1 parent 388270f commit 9056d4f

16 files changed

Lines changed: 851 additions & 39 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ Docs: https://docs.openclaw.ai
5252

5353
### Changes
5454

55-
- CLI/Crestodian: add a configless setup and repair helper for bare `openclaw`, typed config operations, agent handoff, audit logging, docs/source discovery, and guarded message-channel rescue.
55+
- CLI/Crestodian: add a configless setup and repair helper for bare `openclaw`, typed config operations, local Claude/Codex planner fallback, agent handoff, audit logging, docs/source discovery, and guarded message-channel rescue.
5656
- Gateway/nodes: add disabled-by-default `gateway.nodes.pairing.autoApproveCidrs` for first-time node pairing from explicit trusted CIDRs, while keeping operator/browser pairing and all upgrade flows manual. Fixes #60800. Thanks @sahilsatralkar.
5757
- Browser: add viewport coordinate clicks for managed and existing-session automation, plus `openclaw browser click-coords` for CLI use. (#54452) Thanks @dluttz.
5858
- Browser: add `browser.actionTimeoutMs` and use a 60s default action budget so healthy long browser waits do not fail at the client transport boundary. (#62589) Thanks @andyylin.

‎docs/cli/crestodian.md‎

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ Read-only operations can run immediately:
105105
- show the audit-log path
106106

107107
Persistent operations require conversational approval in interactive mode unless
108-
you pass `--yes` for a one-shot command:
108+
you pass `--yes` for a direct command:
109109

110110
- write config
111111
- run `config set`
@@ -153,14 +153,22 @@ model unset. Install or log into Codex/Claude Code, or expose
153153

154154
## Model-Assisted Planner
155155

156-
Crestodian always starts in deterministic mode. Once a valid OpenClaw model is
157-
configured, local Crestodian can make one bounded model call for fuzzy commands
158-
that the deterministic parser does not understand.
156+
Crestodian always starts in deterministic mode. For fuzzy commands that the
157+
deterministic parser does not understand, local Crestodian can make one bounded
158+
planner turn through OpenClaw's normal runtime paths. It first uses the
159+
configured OpenClaw model. If no configured model is usable yet, it can fall
160+
back to local runtimes already present on the machine:
161+
162+
- Claude Code CLI: `claude-cli/claude-opus-4-7`
163+
- Codex app-server harness: `openai/gpt-5.5` with `embeddedHarness.runtime: "codex"`
164+
- Codex CLI: `codex-cli/gpt-5.5`
159165

160166
The model-assisted planner cannot mutate config directly. It must translate the
161167
request into one of Crestodian's typed commands, then the normal approval and
162168
audit rules apply. Crestodian prints the model it used and the interpreted
163-
command before it runs anything.
169+
command before it runs anything. Configless fallback planner turns are
170+
temporary, tool-disabled where the runtime supports it, and use a temporary
171+
workspace/session.
164172

165173
Message-channel rescue mode does not use the model-assisted planner. Remote
166174
rescue stays deterministic so a broken or compromised normal agent path cannot
@@ -275,6 +283,19 @@ Remote rescue is covered by the Docker lane:
275283
pnpm test:docker:crestodian-rescue
276284
```
277285

286+
Configless local planner fallback is covered by:
287+
288+
```bash
289+
pnpm test:docker:crestodian-planner
290+
```
291+
292+
An opt-in live channel command-surface smoke checks `/crestodian status` plus a
293+
persistent approval roundtrip through the rescue handler:
294+
295+
```bash
296+
pnpm test:live:crestodian-rescue-channel
297+
```
298+
278299
Fresh configless setup through Crestodian is covered by:
279300

280301
```bash

‎docs/help/testing.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,14 @@ When debugging real providers/models (requires real creds):
5555
Slack DM with `/codex bind`, exercises `/codex fast` and
5656
`/codex permissions`, then verifies a plain reply and an image attachment
5757
route through the native plugin binding instead of ACP.
58+
- Crestodian rescue command smoke: `pnpm test:live:crestodian-rescue-channel`
59+
- Opt-in belt-and-suspenders check for the message-channel rescue command
60+
surface. It exercises `/crestodian status`, queues a persistent model
61+
change, replies `/crestodian yes`, and verifies the audit/config write path.
62+
- Crestodian planner Docker smoke: `pnpm test:docker:crestodian-planner`
63+
- Runs Crestodian in a configless container with a fake Claude CLI on `PATH`
64+
and verifies the fuzzy planner fallback translates into an audited typed
65+
config write.
5866
- Moonshot/Kimi cost smoke: with `MOONSHOT_API_KEY` set, run
5967
`openclaw models list --provider moonshot --json`, then run an isolated
6068
`openclaw agent --local --session-id live-kimi-cost --message 'Reply exactly: KIMI_LIVE_OK' --thinking off --json`

‎package.json‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1479,6 +1479,7 @@
14791479
"test:docker:cleanup": "bash scripts/test-cleanup-docker.sh",
14801480
"test:docker:config-reload": "bash scripts/e2e/config-reload-source-docker.sh",
14811481
"test:docker:crestodian-first-run": "bash scripts/e2e/crestodian-first-run-docker.sh",
1482+
"test:docker:crestodian-planner": "bash scripts/e2e/crestodian-planner-docker.sh",
14821483
"test:docker:crestodian-rescue": "bash scripts/e2e/crestodian-rescue-docker.sh",
14831484
"test:docker:cron-mcp-cleanup": "bash scripts/e2e/cron-mcp-cleanup-docker.sh",
14841485
"test:docker:doctor-switch": "bash scripts/e2e/doctor-install-switch-docker.sh",
@@ -1543,6 +1544,7 @@
15431544
"test:live": "node scripts/test-live.mjs",
15441545
"test:live:cache": "bun scripts/check-live-cache.ts",
15451546
"test:live:codex-harness": "OPENCLAW_LIVE_CODEX_HARNESS=1 node scripts/test-live.mjs -- src/gateway/gateway-codex-harness.live.test.ts",
1547+
"test:live:crestodian-rescue-channel": "OPENCLAW_LIVE_CRESTODIAN_RESCUE_CHANNEL=1 node scripts/test-live.mjs -- src/crestodian/rescue-channel.live.test.ts",
15461548
"test:live:gateway-profiles": "node scripts/test-live.mjs -- src/gateway/gateway-models.profiles.live.test.ts",
15471549
"test:live:media": "node --import tsx scripts/test-live-media.ts",
15481550
"test:live:media:image": "node --import tsx scripts/test-live-media.ts image",
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
import fs from "node:fs/promises";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { clearConfigCache } from "../../src/config/config.js";
5+
import type { OpenClawConfig } from "../../src/config/types.openclaw.js";
6+
import { runCrestodian } from "../../src/crestodian/crestodian.js";
7+
import type { RuntimeEnv } from "../../src/runtime.js";
8+
9+
function assert(condition: unknown, message: string): asserts condition {
10+
if (!condition) {
11+
throw new Error(message);
12+
}
13+
}
14+
15+
function createRuntime(): { runtime: RuntimeEnv; lines: string[] } {
16+
const lines: string[] = [];
17+
return {
18+
lines,
19+
runtime: {
20+
log: (...args) => lines.push(args.join(" ")),
21+
error: (...args) => lines.push(args.join(" ")),
22+
exit: (code) => {
23+
throw new Error(`exit ${code}`);
24+
},
25+
},
26+
};
27+
}
28+
29+
async function installFakeClaudeCli(fakeBinDir: string, promptLogPath: string): Promise<void> {
30+
await fs.mkdir(fakeBinDir, { recursive: true });
31+
const scriptPath = path.join(fakeBinDir, "claude");
32+
await fs.writeFile(
33+
scriptPath,
34+
[
35+
"#!/usr/bin/env bash",
36+
"set -euo pipefail",
37+
'if [[ "${1:-}" == "--version" ]]; then',
38+
' echo "claude 99.0.0"',
39+
" exit 0",
40+
"fi",
41+
"IFS= read -r prompt_line || true",
42+
`printf '%s\\n' "$prompt_line" > ${JSON.stringify(promptLogPath)}`,
43+
'node -e \'console.log(JSON.stringify({ type: "result", session_id: "fake-claude-session", result: JSON.stringify({ reply: "Fake Claude planner selected a typed model update.", command: "set default model openai/gpt-5.2" }), usage: { input_tokens: 1, output_tokens: 1 } }))\'',
44+
].join("\n"),
45+
{ mode: 0o755 },
46+
);
47+
await fs.chmod(scriptPath, 0o755);
48+
}
49+
50+
async function main() {
51+
const stateDir =
52+
process.env.OPENCLAW_STATE_DIR ??
53+
(await fs.mkdtemp(path.join(os.tmpdir(), "openclaw-crestodian-planner-")));
54+
const configPath = process.env.OPENCLAW_CONFIG_PATH ?? path.join(stateDir, "openclaw.json");
55+
const fakeBinDir = path.join(stateDir, "fake-bin");
56+
const promptLogPath = path.join(stateDir, "fake-claude-prompt.jsonl");
57+
process.env.OPENCLAW_STATE_DIR = stateDir;
58+
process.env.OPENCLAW_CONFIG_PATH = configPath;
59+
process.env.PATH = `${fakeBinDir}:${process.env.PATH ?? ""}`;
60+
await fs.rm(stateDir, { recursive: true, force: true });
61+
await fs.mkdir(stateDir, { recursive: true });
62+
await installFakeClaudeCli(fakeBinDir, promptLogPath);
63+
clearConfigCache();
64+
65+
const runtime = createRuntime();
66+
await runCrestodian(
67+
{
68+
message: "please make the default brain gpt five two",
69+
yes: true,
70+
interactive: false,
71+
},
72+
runtime.runtime,
73+
);
74+
const output = runtime.lines.join("\n");
75+
assert(
76+
output.includes("[crestodian] planner: claude-cli/claude-opus-4-7"),
77+
"configless planner did not use Claude CLI fallback",
78+
);
79+
assert(
80+
output.includes("Fake Claude planner selected a typed model update."),
81+
"planner reply was not surfaced",
82+
);
83+
assert(
84+
output.includes("[crestodian] interpreted: set default model openai/gpt-5.2"),
85+
"planner command was not interpreted",
86+
);
87+
assert(
88+
output.includes("[crestodian] done: config.setDefaultModel"),
89+
"planned model update did not apply",
90+
);
91+
92+
const promptLine = await fs.readFile(promptLogPath, "utf8");
93+
assert(promptLine.includes("User request:"), "fake Claude CLI did not receive planner prompt");
94+
assert(
95+
promptLine.includes("OpenClaw docs:"),
96+
"planner prompt did not include docs reference context",
97+
);
98+
99+
const config = JSON.parse(await fs.readFile(configPath, "utf8")) as OpenClawConfig;
100+
assert(
101+
config.agents?.defaults?.model &&
102+
typeof config.agents.defaults.model === "object" &&
103+
"primary" in config.agents.defaults.model &&
104+
config.agents.defaults.model.primary === "openai/gpt-5.2",
105+
"planned default model was not written",
106+
);
107+
108+
const auditPath = path.join(stateDir, "audit", "crestodian.jsonl");
109+
const audit = (await fs.readFile(auditPath, "utf8")).trim();
110+
assert(
111+
audit.includes('"operation":"config.setDefaultModel"'),
112+
"planned model update audit entry missing",
113+
);
114+
115+
console.log("Crestodian planner Docker E2E passed");
116+
process.exit(0);
117+
}
118+
119+
main().catch((err) => {
120+
console.error(err);
121+
process.exit(1);
122+
});
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#!/usr/bin/env bash
2+
set -euo pipefail
3+
4+
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
5+
source "$ROOT_DIR/scripts/lib/docker-e2e-image.sh"
6+
IMAGE_NAME="$(docker_e2e_resolve_image "openclaw-crestodian-planner-e2e" OPENCLAW_CRESTODIAN_PLANNER_E2E_IMAGE)"
7+
CONTAINER_NAME="openclaw-crestodian-planner-e2e-$$"
8+
RUN_LOG="$(mktemp -t openclaw-crestodian-planner-log.XXXXXX)"
9+
10+
cleanup() {
11+
docker rm -f "$CONTAINER_NAME" >/dev/null 2>&1 || true
12+
rm -f "$RUN_LOG"
13+
}
14+
trap cleanup EXIT
15+
16+
docker_e2e_build_or_reuse "$IMAGE_NAME" crestodian-planner
17+
18+
echo "Running in-container Crestodian planner fallback smoke..."
19+
set +e
20+
docker run --rm \
21+
--name "$CONTAINER_NAME" \
22+
-e "OPENCLAW_STATE_DIR=/tmp/openclaw-state" \
23+
-e "OPENCLAW_CONFIG_PATH=/tmp/openclaw-state/openclaw.json" \
24+
"$IMAGE_NAME" \
25+
bash -lc "set -euo pipefail
26+
node --import tsx scripts/e2e/crestodian-planner-docker-client.ts
27+
" >"$RUN_LOG" 2>&1
28+
status=${PIPESTATUS[0]}
29+
set -e
30+
31+
if [ "$status" -ne 0 ]; then
32+
echo "Docker Crestodian planner fallback smoke failed"
33+
cat "$RUN_LOG"
34+
exit "$status"
35+
fi
36+
37+
cat "$RUN_LOG"
38+
echo "OK"

‎scripts/test-docker-all.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,7 @@ const lanes = [
229229
}),
230230
lane("pi-bundle-mcp-tools", "OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:pi-bundle-mcp-tools"),
231231
lane("crestodian-rescue", "OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:crestodian-rescue"),
232+
lane("crestodian-planner", "OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:crestodian-planner"),
232233
serviceLane(
233234
"cron-mcp-cleanup",
234235
"OPENCLAW_SKIP_DOCKER_BUILD=1 pnpm test:docker:cron-mcp-cleanup",

‎src/agents/cli-runner.before-agent-reply-cron.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const {
1919
runBeforeAgentReplyMock,
2020
executePreparedCliRunMock,
2121
prepareCliRunContextMock,
22+
closeClaudeLiveSessionForContextMock,
2223
} = vi.hoisted(() => ({
2324
hasHooksMock: vi.fn<(hookName: string) => boolean>(() => false),
2425
runBeforeAgentReplyMock: vi.fn<(event: unknown, ctx: unknown) => Promise<BeforeAgentReplyResult>>(
@@ -28,6 +29,7 @@ const {
2829
text: "",
2930
})),
3031
prepareCliRunContextMock: vi.fn(),
32+
closeClaudeLiveSessionForContextMock: vi.fn(),
3133
}));
3234

3335
vi.mock("../plugins/hook-runner-global.js", () => ({
@@ -45,6 +47,10 @@ vi.mock("./cli-runner/execute.runtime.js", () => ({
4547
executePreparedCliRun: executePreparedCliRunMock,
4648
}));
4749

50+
vi.mock("./cli-runner/claude-live-session.js", () => ({
51+
closeClaudeLiveSessionForContext: closeClaudeLiveSessionForContextMock,
52+
}));
53+
4854
const baseRunParams = {
4955
sessionId: "test-session",
5056
sessionKey: "test-session-key",
@@ -86,6 +92,7 @@ beforeEach(() => {
8692
prepareCliRunContextMock.mockImplementation(async (params) =>
8793
makeStubContext(params as typeof baseRunParams & { trigger?: string }),
8894
);
95+
closeClaudeLiveSessionForContextMock.mockReset();
8996
});
9097

9198
afterEach(() => {
@@ -164,4 +171,17 @@ describe("runCliAgent cron before_agent_reply seam", () => {
164171
expect(runBeforeAgentReplyMock).not.toHaveBeenCalled();
165172
expect(executePreparedCliRunMock).toHaveBeenCalled();
166173
});
174+
175+
it("can close temporary CLI live sessions after a run", async () => {
176+
const { runCliAgent } = await import("./cli-runner.js");
177+
executePreparedCliRunMock.mockResolvedValue({ text: "real reply" });
178+
179+
await runCliAgent({ ...baseRunParams, cleanupCliLiveSessionOnRunEnd: true });
180+
181+
expect(executePreparedCliRunMock).toHaveBeenCalledTimes(1);
182+
expect(closeClaudeLiveSessionForContextMock).toHaveBeenCalledTimes(1);
183+
expect(closeClaudeLiveSessionForContextMock).toHaveBeenCalledWith(
184+
await prepareCliRunContextMock.mock.results[0].value,
185+
);
186+
});
167187
});

‎src/agents/cli-runner.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,15 @@ export async function runCliAgent(params: RunCliAgentParams): Promise<EmbeddedPi
101101
}
102102
const { prepareCliRunContext } = await import("./cli-runner/prepare.runtime.js");
103103
const context = await prepareCliRunContext(params);
104-
return runPreparedCliAgent(context);
104+
try {
105+
return await runPreparedCliAgent(context);
106+
} finally {
107+
if (params.cleanupCliLiveSessionOnRunEnd === true) {
108+
const { closeClaudeLiveSessionForContext } =
109+
await import("./cli-runner/claude-live-session.js");
110+
closeClaudeLiveSessionForContext(context);
111+
}
112+
}
105113
}
106114

107115
export async function runPreparedCliAgent(

‎src/agents/cli-runner/claude-live-session.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,15 @@ export function resetClaudeLiveSessionsForTest(): void {
7272
liveSessionCreates.clear();
7373
}
7474

75+
export function closeClaudeLiveSessionForContext(context: PreparedCliRunContext): void {
76+
const key = buildClaudeLiveKey(context);
77+
const session = liveSessions.get(key);
78+
if (session) {
79+
closeLiveSession(session, "restart");
80+
}
81+
liveSessionCreates.delete(key);
82+
}
83+
7584
export function shouldUseClaudeLiveSession(context: PreparedCliRunContext): boolean {
7685
return (
7786
context.backendResolved.id === "claude-cli" &&

0 commit comments

Comments
 (0)