Webchat: run agent in-process for RPC

This commit is contained in:
Peter Steinberger
2025-12-08 14:14:00 +00:00
parent ff3337feed
commit 52453eaeff

View File

@@ -13,7 +13,8 @@ import {
} from "../config/sessions.js"; } from "../config/sessions.js";
import { danger, info } from "../globals.js"; import { danger, info } from "../globals.js";
import { logDebug } from "../logger.js"; import { logDebug } from "../logger.js";
import { runCommandWithTimeout } from "../process/exec.js"; import { agentCommand } from "../commands/agent.js";
import type { RuntimeEnv } from "../runtime.js";
const WEBCHAT_DEFAULT_PORT = 18788; const WEBCHAT_DEFAULT_PORT = 18788;
@@ -100,24 +101,40 @@ async function handleRpc(body: any, sessionKey: string): Promise<{ ok: boolean;
const store = loadSessionStore(storePath); const store = loadSessionStore(storePath);
const sessionId = pickSessionId(sessionKey, store) ?? crypto.randomUUID(); const sessionId = pickSessionId(sessionKey, store) ?? crypto.randomUUID();
const cmd = ["clawdis", "agent", "--message", text, "--json", "--session-id", sessionId]; // Run the agent in-process and capture JSON output instead of spawning the CLI.
if (body?.thinking) cmd.push("--thinking", String(body.thinking)); const logs: string[] = [];
if (body?.deliver) cmd.push("--deliver"); const runtime: RuntimeEnv = {
if (body?.to) cmd.push("--to", String(body.to)); log: (msg: string) => void logs.push(String(msg)),
error: (_msg: string) => {},
exit: (code: number) => {
throw new Error(`agent exited ${code}`);
},
};
try { try {
const { stdout, stderr, code } = await runCommandWithTimeout(cmd, { await agentCommand(
timeoutMs: 120_000, {
cwd: path.dirname(storePath), message: text,
}); sessionId,
if (code !== 0) { thinking: body?.thinking,
return { ok: false, error: stderr.trim() || `agent exited ${code}` }; deliver: Boolean(body?.deliver),
} to: body?.to,
const parsed = JSON.parse(stdout || "{}"); json: true,
return { ok: true, payloads: parsed.payloads ?? [] }; },
runtime,
);
} catch (err) { } catch (err) {
return { ok: false, error: String(err) }; return { ok: false, error: String(err) };
} }
const jsonLine = logs.find((l) => l.trim().startsWith("{"));
if (!jsonLine) return { ok: false, error: "no agent output" };
try {
const parsed = JSON.parse(jsonLine);
return { ok: true, payloads: parsed.payloads ?? [] };
} catch (err) {
return { ok: false, error: `parse error: ${String(err)}` };
}
} }
function notFound(res: http.ServerResponse) { function notFound(res: http.ServerResponse) {