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
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "agent-app",
"version": "1.0.0",
"version": "2.0.0",
"description": "自用通用 Agent 系统:多模型调度 + 任务目录 + 工具调用 + H5 Web UI",
"main": "server/server.js",
"scripts": {
+47 -8
View File
@@ -37,12 +37,9 @@ function deepMerge(base, extra) {
return out;
}
function loadConfig(configPath) {
const p = configPath || process.env.AGENT_CONFIG || path.join(__dirname, '..', 'config.yml');
let raw = {};
if (fs.existsSync(p)) {
raw = YAML.parse(fs.readFileSync(p, 'utf8')) || {};
}
// 校验原始配置文本(启动读文件与网页编辑共用)。configPath 仅记录来源,可为空。
function parseAndValidate(rawText, configPath) {
const raw = YAML.parse(rawText || '') || {};
const cfg = deepMerge(DEFAULTS, raw);
if (!Array.isArray(cfg.models) || cfg.models.length === 0) {
@@ -106,8 +103,50 @@ function loadConfig(configPath) {
s.headers = headers;
}
cfg.config_path = p;
cfg.config_path = configPath || '';
return cfg;
}
module.exports = { loadConfig };
function loadConfig(configPath) {
const p = configPath || process.env.AGENT_CONFIG || path.join(__dirname, '..', 'config.yml');
const text = fs.existsSync(p) ? fs.readFileSync(p, 'utf8') : '';
return parseAndValidate(text, p);
}
// 从文本校验一份配置(页面编辑试运行 / 写盘前校验),返回完整生效 cfg。
function loadConfigFromText(text, configPath) {
return parseAndValidate(text, configPath || '');
}
// ---------- 配置读写(2.0:设置页管理 config.yml;无热重载,写盘后重启生效) ----------
// 读当前配置文件原文(保留注释);文件不存在返回 null。
function readConfigText(cfg) {
const p = cfg && cfg.config_path;
if (!p || !fs.existsSync(p)) return null;
return fs.readFileSync(p, 'utf8');
}
// 单项编辑:[{path:[...], value}] 或 [{path:[...], delete:true}]。
// 用 YAML Document 写回,保留注释与排版;路径段为纯数字时按数组下标处理(如 ["models",0,"url"])。
function applyEditsToText(text, edits) {
const doc = YAML.parseDocument(text || '');
for (const e of edits || []) {
if (!e || !Array.isArray(e.path) || !e.path.length) throw new Error('配置项 path 必须是非空数组');
const docPath = e.path.map(s => (typeof s === 'string' && /^\d+$/.test(s)) ? Number(s) : s);
if (e.delete) doc.deleteIn(docPath);
else doc.setIn(docPath, e.value);
}
return doc.toString();
}
// 校验通过才写盘(不合法直接抛错、不动文件)。
// 注意:不用「临时文件 + rename」原子写:容器里 config.yml 是单文件 bind mount,
// rename 替换该路径会 EBUSY;写坏风险已由“先校验后写”兑底。
function writeConfigText(cfg, text) {
const p = cfg && cfg.config_path;
if (!p) throw Object.assign(new Error('配置文件路径未知(config.yml 可能不存在),无法写入'), { status_code: 409 });
parseAndValidate(text, p);
fs.writeFileSync(p, text, 'utf8');
}
module.exports = { loadConfig, loadConfigFromText, readConfigText, applyEditsToText, writeConfigText };
+9
View File
@@ -256,6 +256,14 @@ function getRun(sessionId, create) {
return run;
}
// 正在执行 AI 回合(looping)的会话 id 列表:供重启保护判断。
// 注意只算「回合执行中」;active 但空闲(等用户输入)与 held 都不算,重启无损失。
function activeRuns() {
const out = [];
for (const [id, run] of runs) if (run && run.looping) out.push(id);
return out;
}
function killRunProcs(run) {
for (const proc of run.procs) {
try { process.kill(-proc.pid, 'SIGKILL'); } catch (_) {
@@ -549,6 +557,7 @@ module.exports = {
getDb: () => db,
getBus: () => bus,
getConfig: () => cfg,
activeRuns,
createSession,
postUserMessage,
startExecution,
+1 -3
View File
@@ -35,11 +35,9 @@ body {
display: inline-flex;
align-items: center;
gap: 8px;
cursor: pointer;
/* 可选:增加内边距扩大点击热区,但不会扩展到空白区域 */
cursor: default;
padding: 4px 8px;
border-radius: 6px;
transition: background 0.2s;
}
.chat-title {
flex: 1; text-align: center; font-size: 16px; font-weight: 600;
+6 -6
View File
@@ -16,7 +16,7 @@
<!-- ================= Tab:任务(会话列表) ================= -->
<div id="tab-tasks" class="tab-page hidden">
<div class="header">
<div class="header-left"><div class="brand" onclick="ui.logout()">
<div class="header-left"><div class="brand">
<svg width="24" height="24" viewBox="0 0 24 24" stroke="#fff" fill="none" stroke-width="1.5">
<rect x="3" y="3" width="18" height="18" rx="3"/><line x1="9" y1="9" x2="15" y2="9"/><line x1="9" y1="13" x2="15" y2="13"/><line x1="9" y1="17" x2="12" y2="17"/>
</svg>
@@ -169,10 +169,10 @@
<div class="toast hidden" id="toast"></div>
<!-- 发版时更新 v 参数,避免移动端浏览器缓存旧 JS -->
<script src="/js/core.js?v=20260901c"></script>
<script src="/js/tasks.js?v=20260901c"></script>
<script src="/js/skills.js?v=20260901c"></script>
<script src="/js/models.js?v=20260901c"></script>
<script src="/js/settings.js?v=20260901c"></script>
<script src="/js/core.js?v=20260901d"></script>
<script src="/js/tasks.js?v=20260901d"></script>
<script src="/js/skills.js?v=20260901d"></script>
<script src="/js/models.js?v=20260901d"></script>
<script src="/js/settings.js?v=20260901d"></script>
</body>
</html>
+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;
+2
View File
@@ -34,6 +34,8 @@ app.use(express.static(path.join(__dirname, 'public')));
app.use('/api/sessions', require('./routes/sessions'));
app.use('/api/sessions', require('./routes/messages'));
app.use('/api/sessions', require('./routes/files'));
app.use('/api/config', require('./routes/config'));
app.use('/api/system', require('./routes/system'));
// 模型池状态(前端可展示空闲/占用)
app.get('/api/models', (req, res) => {
+34
View File
@@ -172,6 +172,40 @@ async function main() {
const esc = await executeTool(ctx, 'read_file', { path: '../outside.txt' }).catch(e => 'ERR:' + e.message);
ok(String(esc).includes('越界'), 'read_file 拒绝越界', String(esc));
// ---- 9. 配置读写 API(阶段 2)----
console.log('\n[8] 配置读写');
const cfgPath = path.join(ROOT, 'test/config.test.yml');
const origText = fs.readFileSync(cfgPath, 'utf8');
const got = await api('GET', '/api/config');
ok(got.exists && got.text.includes('models:'), 'GET /api/config 返回原文');
const patched = await api('PATCH', '/api/config', { path: 'agent.temperature', value: 0.5 });
ok(patched.ok && patched.changed.includes('agent'), 'PATCH 单项修改');
const afterPatch = await api('GET', '/api/config');
ok(/temperature:\s*0\.5/.test(afterPatch.text), 'PATCH 写盘生效');
ok(afterPatch.text.includes('冒烟测试用短租约'), 'PATCH 保留文件注释');
let bad400 = false;
try { await api('PUT', '/api/config', { text: 'models: [unclosed' }); } catch (e) { bad400 = /400/.test(e.message); }
ok(bad400, 'PUT 非法配置被 400 拒绝');
ok(fs.readFileSync(cfgPath, 'utf8') === afterPatch.text, '非法写入未动文件');
const restored = await api('PUT', '/api/config', { text: origText });
ok(restored.ok && fs.readFileSync(cfgPath, 'utf8') === origText, 'PUT 整文件恢复原配置');
// ---- 10. 系统状态与优雅重启(阶段 2;放在最后,服务进程将退出收尾)----
console.log('\n[9] 优雅重启');
const st = await api('GET', '/api/system/status');
ok(st.ok && st.started_at && st.port === 8099, 'GET /api/system/status');
s = await api('POST', '/api/sessions', { title: '冒烟-重启保护' });
await waitSession(s.id, x => x.session.status === 'active', 5000, '绑定');
await api('POST', '/api/sessions/' + s.id + '/messages', { content: '慢一点说' });
await sleep(400); // 进入慢速流式输出,looping=true
let guarded = false;
try { await api('POST', '/api/system/restart'); } catch (e) { guarded = /409/.test(e.message); }
ok(guarded, '回合执行中 restart 被 409 拦截');
const rj = await api('POST', '/api/system/restart?force=true');
ok(rj && rj.restarting, 'force 重启被接受');
await sleep(800); // 服务在响应后 300ms 退出
ok(server.exitCode === 0, '服务以退出码 0 结束(交由 Docker 拉起)', 'exitCode=' + server.exitCode);
console.log('\n========================');
console.log('通过 ' + pass + ' / 失败 ' + fail);
process.exit(fail === 0 ? 0 : 2);
+1 -1
View File
@@ -8,7 +8,7 @@ services:
volumes:
- ./data:/workspace/tasks # 持久化:任务目录 + SQLite(.agent.db 在此目录内)
- ./skills:/workspace/skills # 技能目录:所有任务/会话共享同一份技能
- ./config.yml:/app/config.yml:ro
- ./config.yml:/app/config.yml # 2.0:去掉 :ro,允许设置页写配置(写前服务端会校验)
- ./app/server:/app/server
environment:
- PORT=8080