Files
openclaw-backend/mcp/openclaw-self-edit.js
T

238 lines
15 KiB
JavaScript

#!/usr/bin/env node
// Session-gated OpenClaw configuration editor. No arbitrary shell or target paths.
"use strict";
const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");
const { execFileSync } = require("node:child_process");
const HOME = process.env.OPENCLAW_STATE_DIR || "/home/node/.openclaw";
const CONFIG = path.join(HOME, "openclaw.json");
const LEASE = process.env.JARVIS_SELF_EDIT_LEASE || "/run/jarvis-self-edit/self-edit-lease.json";
const PROJECTS = "/home/node/.openclaw/workspaces/jarvis/projects";
const GENERATED_MCP = path.join(HOME, "mcp", "generated");
const BACKUPS = path.join(HOME, "self-edit", "backups");
const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
const MODEL = /^[a-z0-9_-]+\/[A-Za-z0-9._:/-]{1,160}$/i;
function result(text, error = false) { return { text, error }; }
function revision(raw) { return crypto.createHash("sha256").update(raw).digest("hex"); }
function load() {
const raw = fs.readFileSync(CONFIG, "utf8");
return { raw, config: JSON.parse(raw), revision: revision(raw) };
}
function activeLease(token) {
try {
const lease = JSON.parse(fs.readFileSync(LEASE, "utf8"));
if (lease.mode !== "self-edit" || lease.expiresAt <= Date.now()) return null;
const left = Buffer.from(String(lease.token || ""));
const right = Buffer.from(String(token || ""));
if (left.length !== right.length || !crypto.timingSafeEqual(left, right)) return null;
return lease;
} catch { return null; }
}
function mutationGuard(args, current) {
if (args.confirm !== true) return "Aenderung benoetigt confirm=true.";
if (!activeLease(args.lease)) return "Self-Edit-Lease fehlt, ist ungueltig oder abgelaufen.";
if (args.expected_revision !== current.revision) return "Konfiguration wurde zwischenzeitlich geaendert. Bitte neu auflisten und mit der aktuellen Revision erneut versuchen.";
return null;
}
function validateCandidate(file) {
try {
return execFileSync("openclaw", ["config", "validate"], {
env: { ...process.env, OPENCLAW_CONFIG_PATH: file },
timeout: 120_000,
stdio: ["ignore", "pipe", "pipe"],
}).toString("utf8").trim();
} catch (error) {
throw new Error(String(error.stderr || error.message || error).slice(0, 2000));
}
}
function applyConfig(args, mutate, summary) {
const current = load();
const blocked = mutationGuard(args, current);
if (blocked) return result(blocked, true);
const next = structuredClone(current.config);
mutate(next);
const text = JSON.stringify(next, null, 2) + "\n";
const dir = path.dirname(CONFIG);
const candidate = path.join(dir, `.openclaw.self-edit-${crypto.randomUUID()}.json`);
fs.mkdirSync(BACKUPS, { recursive: true, mode: 0o700 });
fs.writeFileSync(candidate, text, { mode: 0o600, flag: "wx" });
try {
validateCandidate(candidate);
const latest = fs.readFileSync(CONFIG, "utf8");
if (revision(latest) !== current.revision) throw new Error("Konfiguration wurde waehrend der Validierung geaendert.");
const stamp = new Date().toISOString().replace(/[:.]/g, "-");
fs.writeFileSync(path.join(BACKUPS, `${stamp}-${current.revision.slice(0, 12)}.json`), current.raw, { mode: 0o600, flag: "wx" });
fs.renameSync(candidate, CONFIG);
return result(`${summary}\nNeue Revision: ${revision(text)}\nBackup wurde erstellt; OpenClaw kann die validierte Konfiguration neu laden.`);
} catch (error) {
try { fs.rmSync(candidate, { force: true }); } catch {}
return result(`Aenderung nicht angewendet: ${String(error.message || error)}`, true);
}
}
function modelValue(primary, fallbacks) {
if (!MODEL.test(String(primary || ""))) throw new Error("Ungueltige Modell-ID. Erwartet wird provider/model.");
const list = Array.isArray(fallbacks) ? fallbacks.map(String) : [];
if (list.length > 5 || list.some((x) => !MODEL.test(x))) throw new Error("Ungueltige Fallback-Modellliste.");
return { primary: String(primary), fallbacks: [...new Set(list)] };
}
function listAgents() {
try {
const current = load();
const entries = current.config.agents?.entries || {};
const agents = Object.entries(entries).map(([id, a]) => ({ id, name: a.name || id, model: a.model || current.config.agents?.defaults?.model, toolProfile: a.tools?.profile || "inherit" }));
return result(JSON.stringify({ revision: current.revision, agents }, null, 2));
} catch (error) { return result(`Agenten konnten nicht gelesen werden: ${error.message}`, true); }
}
function addAgent(args) {
if (!ID.test(String(args.id || ""))) return result("Ungueltige Agent-ID.", true);
const name = String(args.name || "").trim().slice(0, 80);
const purpose = String(args.purpose || "").trim().slice(0, 2000);
if (!name || !purpose) return result("Name und Aufgabe sind erforderlich.", true);
const profile = ["minimal", "coding", "messaging"].includes(args.tool_profile) ? args.tool_profile : "minimal";
const workspace = path.join(HOME, "workspaces", args.id);
if (fs.existsSync(workspace)) return result("Der Agent-Workspace existiert bereits; er wird nicht ueberschrieben.", true);
try {
const model = args.primary_model ? modelValue(args.primary_model, args.fallback_models) : undefined;
const applied = applyConfig(args, (cfg) => {
cfg.agents ||= {};
cfg.agents.entries ||= {};
if (cfg.agents.entries[args.id]) throw new Error("Agent existiert bereits.");
cfg.agents.entries[args.id] = {
name,
workspace: `/home/node/.openclaw/workspaces/${args.id}`,
agentDir: `/home/node/.openclaw/agents/${args.id}/agent`,
...(model ? { model } : {}),
tools: { profile },
};
}, `Agent ${args.id} wurde angelegt.`);
if (!applied.error) {
fs.mkdirSync(workspace, { recursive: true, mode: 0o700 });
const guide = `# ${name}\n\n## Aufgabe\n\n${purpose}\n\n## Grenzen\n\n- Arbeite nur an explizit delegierten Aufgaben.\n- Gib keine Zugangsdaten aus.\n- Produktive oder destruktive Aenderungen benoetigen eine ausdrueckliche Freigabe.\n`;
fs.writeFileSync(path.join(workspace, "AGENTS.md"), guide, { mode: 0o600, flag: "wx" });
}
return applied;
} catch (error) { return result(String(error.message || error), true); }
}
function changeModel(args) {
if (!ID.test(String(args.id || ""))) return result("Ungueltige Agent-ID.", true);
try {
const model = modelValue(args.primary_model, args.fallback_models);
return applyConfig(args, (cfg) => {
const agent = cfg.agents?.entries?.[args.id];
if (!agent) throw new Error("Agent nicht gefunden.");
agent.model = model;
}, `Modell fuer ${args.id} wurde auf ${model.primary} gesetzt.`);
} catch (error) { return result(String(error.message || error), true); }
}
function listMcp() {
try {
const current = load();
const servers = Object.entries(current.config.mcp?.servers || {}).map(([id, s]) => ({ id, enabled: s.enabled !== false, transport: s.transport || "stdio", tools: s.toolFilter?.include || [] }));
return result(JSON.stringify({ revision: current.revision, servers }, null, 2));
} catch (error) { return result(`MCP-Server konnten nicht gelesen werden: ${error.message}`, true); }
}
function installMcp(args) {
if (!ID.test(String(args.id || ""))) return result("Ungueltige MCP-ID.", true);
let source;
try {
const projectsReal = fs.realpathSync(PROJECTS);
source = fs.realpathSync(path.resolve(PROJECTS, String(args.source_file || "")));
if (!source.startsWith(`${projectsReal}${path.sep}`)) return result("Quelle muss unter projects/ liegen.", true);
} catch { return result("MCP-Quelldatei nicht gefunden.", true); }
if (path.extname(source) !== ".js") return result("Quelle muss eine .js-Datei unter projects/ sein.", true);
let stat;
try { stat = fs.lstatSync(source); } catch { return result("MCP-Quelldatei nicht gefunden.", true); }
if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 512 * 1024) return result("MCP-Quelle muss eine regulaere Datei bis 512 KiB sein.", true);
const tools = Array.isArray(args.tools) ? [...new Set(args.tools.map(String))] : [];
if (!tools.length || tools.length > 100 || tools.some((x) => !/^[a-z][a-z0-9_-]{0,127}$/.test(x))) return result("Mindestens ein gueltiger Tool-Name ist erforderlich.", true);
const target = path.join(GENERATED_MCP, `${args.id}.js`);
if (fs.existsSync(target)) return result("Ein generierter MCP-Server mit dieser ID existiert bereits.", true);
const current = load();
const blocked = mutationGuard(args, current);
if (blocked) return result(blocked, true);
fs.mkdirSync(GENERATED_MCP, { recursive: true, mode: 0o700 });
fs.copyFileSync(source, target, fs.constants.COPYFILE_EXCL);
fs.chmodSync(target, 0o700);
const applied = applyConfig(args, (cfg) => {
cfg.mcp ||= {};
cfg.mcp.servers ||= {};
if (cfg.mcp.servers[args.id]) throw new Error("MCP-Server existiert bereits in der Konfiguration.");
cfg.mcp.servers[args.id] = { enabled: true, command: "node", args: [target], transport: "stdio", toolFilter: { include: tools }, connectionTimeoutMs: 30000, requestTimeoutMs: 120000, supportsParallelToolCalls: false };
}, `MCP-Server ${args.id} wurde installiert und registriert.`);
if (applied.error) try { fs.rmSync(target, { force: true }); } catch {}
return applied;
}
function editConfig(args) {
const allowed = {
"agents.defaults.userTimezone": (v) => typeof v === "string" && /^[A-Za-z_]+\/[A-Za-z_+-]+$/.test(v),
"agents.defaults.timeoutSeconds": (v) => Number.isInteger(v) && v >= 30 && v <= 1800,
"agents.defaults.maxConcurrent": (v) => Number.isInteger(v) && v >= 1 && v <= 8,
"tools.web.search.enabled": (v) => typeof v === "boolean",
"tools.web.search.maxResults": (v) => Number.isInteger(v) && v >= 1 && v <= 20,
"gateway.reload.mode": (v) => ["off", "hot", "restart", "hybrid"].includes(v),
};
const changes = Array.isArray(args.changes) ? args.changes : [];
if (!changes.length || changes.length > 20) return result("Zwischen 1 und 20 Aenderungen sind erforderlich.", true);
for (const change of changes) if (!allowed[change.field]?.(change.value)) return result(`Nicht erlaubtes oder ungueltiges Feld: ${change.field}`, true);
return applyConfig(args, (cfg) => {
for (const change of changes) {
const parts = change.field.split(".");
let node = cfg;
for (const part of parts.slice(0, -1)) node = node[part] ||= {};
node[parts.at(-1)] = change.value;
}
}, `${changes.length} freigegebene Konfigurationsaenderung(en) wurden angewendet.`);
}
function validateCurrent() {
try { return result(`${validateCandidate(CONFIG)}\nRevision: ${load().revision}`); }
catch (error) { return result(`Konfiguration ist ungueltig: ${error.message}`, true); }
}
const commonMutation = {
lease: { type: "string" }, expected_revision: { type: "string", pattern: "^[a-f0-9]{64}$" }, confirm: { type: "boolean" },
};
const TOOLS = [
{ name: "list_agents", description: "Listet OpenClaw-Agenten und die aktuelle Konfigurationsrevision. Lesend.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
{ name: "add_agent", description: "Legt im aktiven Self-Edit-Modus nach Bestaetigung einen neuen Spezialagenten mit eigenem Workspace an.", inputSchema: { type: "object", properties: { ...commonMutation, id: { type: "string" }, name: { type: "string" }, purpose: { type: "string" }, tool_profile: { type: "string", enum: ["minimal", "coding", "messaging"] }, primary_model: { type: "string" }, fallback_models: { type: "array", items: { type: "string" } } }, required: ["lease", "expected_revision", "confirm", "id", "name", "purpose"], additionalProperties: false } },
{ name: "change_agent_model", description: "Aendert nach Bestaetigung das Modell eines vorhandenen Agenten.", inputSchema: { type: "object", properties: { ...commonMutation, id: { type: "string" }, primary_model: { type: "string" }, fallback_models: { type: "array", items: { type: "string" } } }, required: ["lease", "expected_revision", "confirm", "id", "primary_model"], additionalProperties: false } },
{ name: "list_mcp_servers", description: "Listet registrierte MCP-Server ohne Secrets und die aktuelle Revision. Lesend.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
{ name: "install_mcp_server", description: "Installiert nach Bestaetigung eine gepruefte JavaScript-MCP-Datei aus dem Jarvis-Projektbereich und registriert nur angegebene Tools.", inputSchema: { type: "object", properties: { ...commonMutation, id: { type: "string" }, source_file: { type: "string" }, tools: { type: "array", items: { type: "string" } } }, required: ["lease", "expected_revision", "confirm", "id", "source_file", "tools"], additionalProperties: false } },
{ name: "edit_config", description: "Aendert nach Bestaetigung ausschliesslich freigegebene, begrenzte OpenClaw-Konfigurationsfelder.", inputSchema: { type: "object", properties: { ...commonMutation, changes: { type: "array", items: { type: "object", properties: { field: { type: "string" }, value: {} }, required: ["field", "value"], additionalProperties: false } } }, required: ["lease", "expected_revision", "confirm", "changes"], additionalProperties: false } },
{ name: "validate_config", description: "Validiert die aktuelle OpenClaw-Konfiguration. Lesend.", inputSchema: { type: "object", properties: {}, additionalProperties: false } },
];
function call(name, args) {
try {
if (name === "list_agents") return listAgents();
if (name === "add_agent") return addAgent(args);
if (name === "change_agent_model") return changeModel(args);
if (name === "list_mcp_servers") return listMcp();
if (name === "install_mcp_server") return installMcp(args);
if (name === "edit_config") return editConfig(args);
if (name === "validate_config") return validateCurrent();
return result("Unbekanntes Werkzeug.", true);
} catch (error) { return result(String(error.message || error).slice(0, 2000), true); }
}
function send(id, value) { process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, result: value }) + "\n"); }
function reply(id, value) { send(id, { content: [{ type: "text", text: value.text }], isError: value.error }); }
let buffer = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
buffer += chunk;
let end;
while ((end = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, end).trim();
buffer = buffer.slice(end + 1);
if (!line) continue;
let message;
try { message = JSON.parse(line); } catch { continue; }
if (message.method === "initialize") send(message.id, { protocolVersion: message.params?.protocolVersion || "2024-11-05", capabilities: { tools: {} }, serverInfo: { name: "openclaw-self-edit", version: "1.0.0" } });
else if (message.method === "tools/list") send(message.id, { tools: TOOLS });
else if (message.method === "tools/call") reply(message.id, call(message.params?.name, message.params?.arguments || {}));
}
});