会议模式:内核数据模型 + 执行引擎 + SSE 路由
用户需求 C 的第一部分(引擎侧)。界面编辑器下一轮。
【数据模型】
meeting = { id, name, nodes[], edges[] }
节点四类:
start 初始输入(文本可写死,留空则用用户发的那句)
agent 智能体:agentId + **本节点专属**的附加提示词 + 输出控制
judge 判断:按条件分 true / false 两条出边
end 最终输出
★ 新增会议时给的是"输入 → 一个智能体 → 输出"的**最小可跑闭环**,
不是空白画布 —— 对着空白画布干瞪眼是最差的新手体验,
而且有个能跑的例子,节点和连线怎么连一眼就懂。
【安全决定:判断节点的规则不用 eval】
判断节点要支持"包含某词""字数多于 N"这类条件。最省事是让用户写表达式然后
eval —— **绝对不行**:配置能被任意改写(界面上可编辑、文件可手改),
eval 就等于把任意代码执行权交出去。
改用**结构化规则**(7 种 kind + value):能表达的就那几种,
多一种就多一个分支,而不是多一分风险。AI 判断也支持(让模型回 YES/NO)。
【执行引擎】
- 拓扑序 + 访问集合 + 步数上限,而不是递归:
用户画错画出环时递归会直接爆栈,这样最多"少跑几个节点"
- 一个节点的输入 = 所有上游输出拼接(多条入边不用额外的合并节点)
- 单个节点出错**不让整场会议停摆**:上报 node_error,继续跑下游
- 边和节点在保存时做消毒:丢掉类型不认识的节点、指向不存在节点的悬空连线
【测试抓到的一个真设计缺陷】
判断节点原先把输出**覆盖成了字符串 "true"/"false"**,
于是下游智能体收到的输入就是 "true",完全没法用 ——
验证脚本报出来的是"真 收到[true]"。
修成**透传上游内容**,判断结论单独走 verdict 字段。
这个错误要是等界面做完再发现,会以为是"连线没连对",白查半天。
【验证】
- scripts/verify-meeting.mjs:引擎逻辑,7 张图(直链 / true 分支 / false 分支 /
多入边拼接 / 环 / 节点报错 / 无入口),用**假智能体**不打真实模型。
Node 与 Python 逐用例对拍一致;判断规则 6/6。20/20。
- scripts/verify-meeting-http.mjs:HTTP 端到端(起内核 + mock LLM),
验路由、SSE 事件流、真调模型、判断分支、透传。两份内核各 12/12。
回归:语音 41/41 ×2、Markdown 19/19。
【还剩】会议模式的可视化编辑器(Compose 画布:拖节点、拉连线、点节点配参数)。
This commit is contained in:
320
server/src/meeting.mjs
Normal file
320
server/src/meeting.mjs
Normal file
@@ -0,0 +1,320 @@
|
||||
/**
|
||||
* 会议模式:用「节点 + 连线」把多个智能体串成一条流水线。
|
||||
*
|
||||
* 对应 Python 版 android/kernel/meeting.py —— 节点类型、判断条件、事件名
|
||||
* 必须逐字一致(两边不一致的话,同一个会议在手机和电脑上跑出来不一样)。
|
||||
*
|
||||
* 和普通对话的区别:
|
||||
* 普通对话是"一个智能体回答一个问题";
|
||||
* 会议模式是一张有向图 —— 初始输入进去,经过若干智能体节点各自加工,
|
||||
* 中间可以按条件分叉,最后汇到最终输出节点。
|
||||
*
|
||||
* ---------------------------------------------------------------------------
|
||||
* 关于判断节点的"规则"模式为什么不用 eval
|
||||
* ---------------------------------------------------------------------------
|
||||
* 判断节点要支持"上游输出里有没有某个词""长度是否超过 N"这类条件。
|
||||
* 最省事的做法是让用户写一段 JS 表达式然后 eval —— **绝对不行**:
|
||||
* 配置能被任意改写(界面上可编辑、文件可手改),eval 就等于把任意代码
|
||||
* 执行权交出去。所以这里用**结构化规则**(kind + value),
|
||||
* 能表达的就那几种,多一种就多一个分支,而不是多一分风险。
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { DATA_DIR } from './config.mjs';
|
||||
|
||||
export const NODE_TYPES = ['start', 'agent', 'judge', 'end'];
|
||||
|
||||
/** 判断节点支持的条件。**结构化而不是表达式**,理由见文件头。 */
|
||||
export const JUDGE_KINDS = [
|
||||
['contains', '包含关键词'],
|
||||
['not_contains', '不包含关键词'],
|
||||
['longer_than', '字数多于'],
|
||||
['shorter_than', '字数少于'],
|
||||
['empty', '为空'],
|
||||
['not_empty', '不为空'],
|
||||
['ai', '让模型判断'],
|
||||
];
|
||||
|
||||
const ts36 = () => Date.now().toString(36);
|
||||
const rid = (prefix) => `${prefix}_${ts36()}_${randomUUID().slice(0, 4)}`;
|
||||
const nowIso = () => new Date().toISOString();
|
||||
|
||||
function file() {
|
||||
return path.join(DATA_DIR, 'meetings.json');
|
||||
}
|
||||
|
||||
/**
|
||||
* 给一张能直接跑的初始图,而不是空白画布。
|
||||
*
|
||||
* 空白画布对着干瞪眼是最差的新手体验;放一个"输入 → 一个智能体 → 输出"
|
||||
* 的最小闭环,用户改改就能用,也能一眼看懂节点和连线是怎么连的。
|
||||
*/
|
||||
export function newMeeting(name = '新会议') {
|
||||
return {
|
||||
id: rid('m'),
|
||||
name,
|
||||
nodes: [
|
||||
{ id: 'n_start', type: 'start', x: 60, y: 200, title: '初始输入', text: '' },
|
||||
{ id: 'n_agent1', type: 'agent', x: 300, y: 200, title: '智能体', agentId: '', extraPrompt: '', outputControl: '' },
|
||||
{ id: 'n_end', type: 'end', x: 540, y: 200, title: '最终输出', text: '' },
|
||||
],
|
||||
edges: [
|
||||
{ from: 'n_start', to: 'n_agent1', branch: '' },
|
||||
{ from: 'n_agent1', to: 'n_end', branch: '' },
|
||||
],
|
||||
createdAt: nowIso(),
|
||||
updatedAt: nowIso(),
|
||||
};
|
||||
}
|
||||
|
||||
function read() {
|
||||
const f = file();
|
||||
if (!fs.existsSync(f)) return [];
|
||||
try {
|
||||
const data = JSON.parse(fs.readFileSync(f, 'utf8'));
|
||||
return Array.isArray(data?.meetings) ? data.meetings : [];
|
||||
} catch (err) {
|
||||
console.error(`[meeting] meetings.json 读不了:${err.message}`);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function write(items) {
|
||||
fs.mkdirSync(path.dirname(file()), { recursive: true });
|
||||
fs.writeFileSync(file(), JSON.stringify({ meetings: items }, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
/** 列表只给摘要:节点连线可能很大,列表页用不上 */
|
||||
export function listMeetings() {
|
||||
return read().map((m) => ({
|
||||
id: m.id,
|
||||
name: m.name || '未命名会议',
|
||||
nodeCount: (m.nodes || []).length,
|
||||
edgeCount: (m.edges || []).length,
|
||||
updatedAt: m.updatedAt,
|
||||
}));
|
||||
}
|
||||
|
||||
export function getMeeting(id) {
|
||||
return read().find((m) => m.id === id) || null;
|
||||
}
|
||||
|
||||
export function createMeeting(payload = {}) {
|
||||
const item = newMeeting(String(payload.name || '新会议').slice(0, 40));
|
||||
const items = read();
|
||||
items.push(item);
|
||||
write(items);
|
||||
return item;
|
||||
}
|
||||
|
||||
/** 整份覆盖。图这种东西局部改很容易改出坏结构(悬空连线、重复 id)。 */
|
||||
export function saveMeeting(id, payload = {}) {
|
||||
const items = read();
|
||||
const i = items.findIndex((m) => m.id === id);
|
||||
if (i < 0) return null;
|
||||
const merged = { ...items[i], ...payload, id, updatedAt: nowIso() };
|
||||
merged.nodes = sanitizeNodes(merged.nodes || []);
|
||||
merged.edges = sanitizeEdges(merged.edges || [], merged.nodes);
|
||||
items[i] = merged;
|
||||
write(items);
|
||||
return merged;
|
||||
}
|
||||
|
||||
export function deleteMeeting(id) {
|
||||
const items = read();
|
||||
const left = items.filter((m) => m.id !== id);
|
||||
if (left.length === items.length) return false;
|
||||
write(left);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** 丢掉类型不认识、或者 id 重复的节点 —— 坏节点会让整张图跑不起来 */
|
||||
function sanitizeNodes(nodes) {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
for (const n of nodes) {
|
||||
if (!n || typeof n !== 'object') continue;
|
||||
const nid = String(n.id || '');
|
||||
const ntype = String(n.type || '');
|
||||
if (!nid || seen.has(nid) || !NODE_TYPES.includes(ntype)) continue;
|
||||
seen.add(nid);
|
||||
out.push({ ...n, id: nid, type: ntype, x: Number(n.x) || 0, y: Number(n.y) || 0 });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 丢掉指向不存在节点的连线 —— 悬空连线是崩溃的常见来源 */
|
||||
function sanitizeEdges(edges, nodes) {
|
||||
const ids = new Set(nodes.map((n) => n.id));
|
||||
const out = [];
|
||||
for (const e of edges) {
|
||||
if (!e || typeof e !== 'object') continue;
|
||||
const src = String(e.from || '');
|
||||
const dst = String(e.to || '');
|
||||
if (ids.has(src) && ids.has(dst) && src !== dst) {
|
||||
out.push({ from: src, to: dst, branch: String(e.branch || '') });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------------------- */
|
||||
/* 执行引擎 */
|
||||
/* -------------------------------------------------------------------------- */
|
||||
|
||||
const incoming = (edges, id) => edges.filter((e) => e.to === id);
|
||||
const outgoing = (edges, id) => edges.filter((e) => e.from === id);
|
||||
|
||||
/**
|
||||
* 一个节点的输入 = 它所有上游节点的输出拼起来。
|
||||
*
|
||||
* 多条入边就按连线顺序拼 —— 这样"多个智能体的意见汇总给判断节点"
|
||||
* 不需要额外的合并节点。
|
||||
*/
|
||||
function collectInput(id, edges, outputs) {
|
||||
const parts = [];
|
||||
for (const e of incoming(edges, id)) {
|
||||
const text = outputs[e.from];
|
||||
if (text) parts.push(String(text));
|
||||
}
|
||||
return parts.join('\n\n').trim();
|
||||
}
|
||||
|
||||
/** 结构化条件判断(不用 eval,理由见文件头) */
|
||||
export function judgeRule(node, text) {
|
||||
const kind = String(node.judgeKind || 'not_empty');
|
||||
const value = String(node.judgeValue ?? '');
|
||||
switch (kind) {
|
||||
case 'contains': return text.includes(value);
|
||||
case 'not_contains': return !text.includes(value);
|
||||
case 'longer_than': return text.length > (Number(value) || 0);
|
||||
case 'shorter_than': return text.length < (Number(value) || 0);
|
||||
case 'empty': return !text.trim();
|
||||
case 'not_empty': return !!text.trim();
|
||||
default: return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 跑完一整张图。
|
||||
*
|
||||
* 事件:
|
||||
* {type:'meeting_start', nodes, edges}
|
||||
* {type:'node_start', nodeId, nodeType, title}
|
||||
* {type:'node_delta', nodeId, text} ← 流式增量
|
||||
* {type:'node_done', nodeId, output}
|
||||
* {type:'node_error', nodeId, error}
|
||||
* {type:'meeting_done', output}
|
||||
*
|
||||
* 为什么用队列 + 访问集合而不是递归:图里可能有环(用户画错了),
|
||||
* 递归会直接爆栈。这里每个节点最多跑一次、总步数还有上限,
|
||||
* 画错了也只是"少跑几个节点",不会把进程拖死。
|
||||
*/
|
||||
export async function runMeeting({ meeting, settings, userInput, emit, runAgentFn, shouldStop }) {
|
||||
const nodes = meeting.nodes || [];
|
||||
const edges = meeting.edges || [];
|
||||
const byId = new Map(nodes.map((n) => [n.id, n]));
|
||||
const outputs = {};
|
||||
|
||||
emit({ type: 'meeting_start', nodes: nodes.length, edges: edges.length });
|
||||
|
||||
// 入口:优先 start 节点;没有就从"没有入边"的节点开始
|
||||
let starts = nodes.filter((n) => n.type === 'start');
|
||||
if (!starts.length) starts = nodes.filter((n) => incoming(edges, n.id).length === 0);
|
||||
if (!starts.length) {
|
||||
emit({ type: 'meeting_done', output: '', error: '这张图没有入口节点' });
|
||||
return { output: '', error: '这张图没有入口节点' };
|
||||
}
|
||||
|
||||
const queue = starts.map((n) => n.id);
|
||||
const visited = new Set();
|
||||
let steps = 0;
|
||||
const maxSteps = Math.max(20, nodes.length * 4);
|
||||
let finalOutput = '';
|
||||
|
||||
while (queue.length && steps < maxSteps) {
|
||||
if (shouldStop && shouldStop()) {
|
||||
emit({ type: 'meeting_done', output: finalOutput, aborted: true });
|
||||
return { output: finalOutput, aborted: true };
|
||||
}
|
||||
|
||||
const nodeId = queue.shift();
|
||||
steps += 1;
|
||||
if (visited.has(nodeId)) continue;
|
||||
visited.add(nodeId);
|
||||
|
||||
const node = byId.get(nodeId);
|
||||
if (!node) continue;
|
||||
|
||||
const nodeType = node.type;
|
||||
const title = node.title
|
||||
|| { start: '初始输入', agent: '智能体', judge: '判断', end: '最终输出' }[nodeType]
|
||||
|| nodeType;
|
||||
emit({ type: 'node_start', nodeId, nodeType, title });
|
||||
|
||||
const input = collectInput(nodeId, edges, outputs);
|
||||
let nextIds = [];
|
||||
|
||||
try {
|
||||
if (nodeType === 'start') {
|
||||
const text = String(node.text || '').trim() || (userInput || '');
|
||||
outputs[nodeId] = text;
|
||||
emit({ type: 'node_done', nodeId, output: text, note: '用的初始输入' });
|
||||
nextIds = outgoing(edges, nodeId).map((e) => e.to);
|
||||
} else if (nodeType === 'agent') {
|
||||
const out = await runAgentFn(node, input, settings, emit, nodeId);
|
||||
outputs[nodeId] = out;
|
||||
emit({ type: 'node_done', nodeId, output: out });
|
||||
nextIds = outgoing(edges, nodeId).map((e) => e.to);
|
||||
} else if (nodeType === 'judge') {
|
||||
const kind = String(node.judgeKind || 'not_empty');
|
||||
let passed;
|
||||
if (kind === 'ai') {
|
||||
const verdict = await runAgentFn({ ...node, _judgeOnly: true }, input, settings, emit, nodeId);
|
||||
passed = /YES/i.test(verdict.slice(0, 40)) || verdict.slice(0, 20).includes('是');
|
||||
} else {
|
||||
passed = judgeRule(node, input);
|
||||
}
|
||||
// ★ 判断节点必须**透传上游内容**,不能把自己的输出改成 "true"/"false"。
|
||||
// 否则下游智能体收到的输入就变成字符串 "true" 了,完全没法用 ——
|
||||
// 这个错误是验证脚本抓到的(输出是"真 收到[true]")。
|
||||
// 判断结论走 verdict 字段,不占 output。
|
||||
outputs[nodeId] = input;
|
||||
emit({
|
||||
type: 'node_done',
|
||||
nodeId,
|
||||
output: input,
|
||||
verdict: passed,
|
||||
branch: passed ? 'true' : 'false',
|
||||
note: `判断结果:${passed}`,
|
||||
});
|
||||
// 判断节点走 true / false 两条出边;没标分支的那条当默认(true)
|
||||
const outs = outgoing(edges, nodeId);
|
||||
nextIds = outs.filter((e) => (e.branch || 'true') === (passed ? 'true' : 'false')).map((e) => e.to);
|
||||
// 没连对应的分支就顺走第一条,免得图直接断在这儿
|
||||
if (!nextIds.length) nextIds = outs.slice(0, 1).map((e) => e.to);
|
||||
} else if (nodeType === 'end') {
|
||||
outputs[nodeId] = String(node.text || '').trim() || input;
|
||||
finalOutput = outputs[nodeId];
|
||||
emit({ type: 'node_done', nodeId, output: finalOutput });
|
||||
nextIds = [];
|
||||
} else {
|
||||
emit({ type: 'node_error', nodeId, error: `不认识的节点类型:${nodeType}` });
|
||||
nextIds = [];
|
||||
}
|
||||
} catch (err) {
|
||||
// 单个节点出错不该让整场会议停摆:记下来,继续跑下游
|
||||
emit({ type: 'node_error', nodeId, error: err.message });
|
||||
outputs[nodeId] = '';
|
||||
nextIds = outgoing(edges, nodeId).map((e) => e.to);
|
||||
}
|
||||
|
||||
for (const nid of nextIds) {
|
||||
if (!visited.has(nid)) queue.push(nid);
|
||||
}
|
||||
}
|
||||
|
||||
emit({ type: 'meeting_done', output: finalOutput });
|
||||
return { output: finalOutput };
|
||||
}
|
||||
Reference in New Issue
Block a user