2.0阶段2: 配置读写API(GET/PATCH保留注释/PUT整文件/validate干跑)+系统状态+优雅重启(exit+Docker拉起,运行中回合409保护);去掉logo退出登录;config.yml挂载放开:ro

This commit is contained in:
2026-09-01 16:50:00 +08:00
parent 4968241951
commit e9a1331557
10 changed files with 256 additions and 19 deletions
+89
View File
@@ -0,0 +1,89 @@
// 配置读写 API(2.0 阶段 2):设置页管理 config.yml。
// 语义:写 = 校验 → 覆盖文件(无热重载);POST /api/system/restart 后生效。
// 注意:GET 返回的原文含密钥,接口与设置页同受 auth 中间件保护(自用场景)。
const express = require('express');
const engine = require('../engine');
const { loadConfigFromText, readConfigText, applyEditsToText, writeConfigText } = require('../config');
const router = express.Router();
function sendErr(res, err) {
const code = err && err.status_code || 500;
res.status(code).json({ error: String(err && err.message || err) });
}
function badRequest(res, err) {
res.status(400).json({ error: String(err && err.message || err) });
}
function wrap(fn) {
return function (req, res) {
try { fn(req, res); } catch (err) { sendErr(res, err); }
};
}
// 对比运行配置与新配置的顶层差异键(前端提示「这些段重启后生效」)
function diffTop(oldCfg, newCfg) {
const skip = new Set(['config_path']);
const keys = new Set(Object.keys(oldCfg || {}).concat(Object.keys(newCfg || {})));
const changed = [];
for (const k of keys) {
if (skip.has(k)) continue;
if (JSON.stringify(oldCfg && oldCfg[k]) !== JSON.stringify(newCfg && newCfg[k])) changed.push(k);
}
return changed;
}
function cfgOf() { return engine.getConfig(); }
// 配置原文 + 路径(页面编辑器用;注释原样保留)
router.get('/', wrap((req, res) => {
const cfg = cfgOf();
const text = readConfigText(cfg);
res.json({ config_path: cfg.config_path || '', exists: text !== null, text: text === null ? '' : text });
}));
// 干跑校验(编辑器保存前预检):body { text }
router.post('/validate', wrap((req, res) => {
const text = req.body && req.body.text;
if (typeof text !== 'string') return badRequest(res, new Error('body.text 必须是字符串'));
try {
const next = loadConfigFromText(text, '');
res.json({ ok: true, changed: diffTop(cfgOf(), next) });
} catch (e) {
res.status(400).json({ ok: false, error: String(e && e.message || e) });
}
}));
// 整文件编辑:body { text }
router.put('/', wrap((req, res) => {
const cfg = cfgOf();
const text = req.body && req.body.text;
if (typeof text !== 'string') return badRequest(res, new Error('body.text 必须是字符串'));
let next;
try { next = loadConfigFromText(text, cfg.config_path); } catch (e) { return badRequest(res, e); }
writeConfigText(cfg, text);
res.json({ ok: true, changed: diffTop(cfg, next), restart_required: true });
}));
// 单项修改:body { path: "agent.temperature" | ["models",0,"url"], value, op?: "delete" }
// 用 YAML Document 写回,保留文件注释与排版;数组可整体替换,也可按数字下标改元素。
router.patch('/', wrap((req, res) => {
const cfg = cfgOf();
const text = readConfigText(cfg);
if (text === null) return sendErr(res, Object.assign(new Error('配置文件不存在:' + (cfg.config_path || '(未知路径)')), { status_code: 409 }));
const body = req.body || {};
let pathArr;
if (Array.isArray(body.path)) pathArr = body.path;
else if (typeof body.path === 'string' && body.path.trim()) pathArr = body.path.split('.').map(s => s.trim()).filter(Boolean);
else return badRequest(res, new Error('body.path 必填,如 agent.temperature 或 ["models",0,"display_name"]'));
if (!pathArr.length) return badRequest(res, new Error('body.path 为空'));
let nextText;
try {
nextText = applyEditsToText(text, [{ path: pathArr, value: body.value, delete: body.op === 'delete' }]);
} catch (e) { return badRequest(res, e); }
let next;
try { next = loadConfigFromText(nextText, cfg.config_path); } catch (e) { return badRequest(res, e); }
writeConfigText(cfg, nextText);
res.json({ ok: true, changed: diffTop(cfg, next), restart_required: true });
}));
module.exports = router;
+66
View File
@@ -0,0 +1,66 @@
// 系统状态与优雅重启(2.0 阶段 2)。
// 重启机制:确认 config.yml 仍能通过启动校验 → process.exit(0) → Docker 按
// restart 策略(unless-stopped)自动拉起。不依赖 docker.sock、无需提权。
// 非 docker 运行(如 npm start)时进程直接退出,不会自动重启,需自行启动。
const express = require('express');
const engine = require('../engine');
const { loadConfig } = require('../config');
const router = express.Router();
const STARTED_AT = Date.now();
let VERSION = '2.0.0';
try { VERSION = require('../../package.json').version || VERSION; } catch (_) {}
function sendErr(res, err) {
const code = err && err.status_code || 500;
res.status(code).json({ error: String(err && err.message || err) });
}
function wrap(fn) {
return function (req, res) {
try { fn(req, res); } catch (err) { sendErr(res, err); }
};
}
// 运行状态:设置页展示 + 前端重启后轮询等待恢复
router.get('/status', wrap((req, res) => {
const cfg = engine.getConfig();
res.json({
ok: true,
version: VERSION,
pid: process.pid,
node: process.version,
started_at: STARTED_AT,
uptime_ms: Date.now() - STARTED_AT,
config_path: cfg.config_path || '',
workspace_root: cfg.workspace_root,
skills_root: cfg.skills_root,
db_path: cfg.db_path,
port: cfg.port,
auth_enabled: !!(cfg.auth && cfg.auth.users && cfg.auth.users.length),
running_sessions: engine.activeRuns(),
});
}));
// 优雅重启:有 AI 回合执行中时默认 409 拒绝(force=true 才打断)。
router.post('/restart', wrap((req, res) => {
const cfg = engine.getConfig();
const force = req.query.force === 'true' || !!(req.body && req.body.force);
const running = engine.activeRuns();
if (running.length && !force) {
return res.status(409).json({
error: '有 ' + running.length + ' 个任务回合执行中,重启将打断它们',
running_sessions: running,
});
}
// 防重启崩溃循环:文件可能被容器外改成不合法,那样新进程将起不来,先拒绝重启
try { loadConfig(cfg.config_path); } catch (e) {
return res.status(409).json({ error: '配置文件当前内容不合法,重启将无法启动:' + String(e && e.message || e) });
}
console.log('[system] 收到重启请求(force=' + force + ',打断 ' + running.length + ' 个回合),进程退出,等待 Docker 拉起');
res.json({ ok: true, restarting: true });
// 稍候再退出,确保响应已发出;容器由 Docker restart 策略自动重启
setTimeout(() => process.exit(0), 300);
}));
module.exports = router;