会议模式:内核数据模型 + 执行引擎 + 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:
l
2026-10-10 11:29:56 +08:00
parent 4bf46e7eb3
commit 376a143a37
6 changed files with 1476 additions and 0 deletions

View File

@@ -32,6 +32,7 @@ from urllib.parse import unquote, urlsplit
import agent_loop import agent_loop
import mcp_client import mcp_client
import meeting
import paths import paths
import providers import providers
import speech import speech
@@ -668,6 +669,62 @@ class KernelHandler(BaseHTTPRequestHandler):
self.send_json(200 if ok else 404, {'ok': ok}) self.send_json(200 if ok else 404, {'ok': ok})
return True return True
# 会议模式
if pathname == '/api/meetings' and method == 'GET':
self.send_json(200, {'meetings': meeting.list_meetings()})
return True
if pathname == '/api/meetings' and method == 'POST':
body = self.read_json_body()
self.send_json(200, {'meeting': meeting.create_meeting(body)})
return True
if pathname == '/api/meeting/meta' and method == 'GET':
# 编辑器要用:节点类型、判断条件、可用智能体
self.send_json(200, {
'nodeTypes': [
{'key': 'start', 'label': '初始输入', 'desc': '整张图的入口'},
{'key': 'agent', 'label': '智能体', 'desc': '一个智能体处理一轮'},
{'key': 'judge', 'label': '判断', 'desc': '按条件分 true / false 两条路'},
{'key': 'end', 'label': '最终输出', 'desc': '汇总结果'},
],
'judgeKinds': [{'key': k, 'label': v} for k, v in meeting.JUDGE_KINDS],
'agents': [
{'id': a.get('id'), 'name': a.get('name'), 'avatar': a.get('avatar')}
for a in store.list_agents()
],
})
return True
# /api/meetings/<id>/run —— 走 SSE 跑整张图。
# ★ 必须在 _match_id 之前处理:那个函数明确拒绝带斜杠的 id,
# 而这里路径里就有一个 /run,交给它会永远匹配不上。
if pathname.startswith('/api/meetings/') and pathname.endswith('/run') and method == 'POST':
self._handle_meeting_run(pathname[len('/api/meetings/'):-len('/run')])
return True
meeting_id = self._match_id(pathname, '/api/meetings/')
if meeting_id is not None:
if method == 'GET':
item = meeting.get_meeting(meeting_id)
if item:
self.send_json(200, {'meeting': item})
else:
self.send_json(404, {'error': '会议不存在'})
return True
if method in ('PUT', 'PATCH'):
body = self.read_json_body()
item = meeting.save_meeting(meeting_id, body)
if item:
self.send_json(200, {'meeting': item})
else:
self.send_json(404, {'error': '会议不存在'})
return True
if method == 'DELETE':
ok = meeting.delete_meeting(meeting_id)
self.send_json(200 if ok else 404, {'ok': ok})
return True
# 工具 # 工具
if pathname == '/api/tools' and method == 'GET': if pathname == '/api/tools' and method == 'GET':
settings = store.read_settings() settings = store.read_settings()
@@ -860,6 +917,85 @@ class KernelHandler(BaseHTTPRequestHandler):
# ------------------------------- 对话 ------------------------------- # # ------------------------------- 对话 ------------------------------- #
def _handle_meeting_run(self, meeting_id: str) -> None:
"""跑一整张会议图,事件走 SSE。"""
body = self.read_json_body()
settings = store.read_settings()
item = meeting.get_meeting(meeting_id)
if not item:
self.send_json(404, {'error': '会议不存在'})
return
user_input = str(body.get('input') or '').strip()
sse = SseChannel(self)
sse.start()
def run_agent_fn(node: dict, incoming: str, cfg: dict, emit, node_id: str) -> str:
"""
跑一个 agent 节点 / AI 判断节点。
★ 节点的附加提示词和输出控制都是**拼在系统提示词后面**,而不是替换它 ——
智能体本身的人设("你是毒舌评论员")不能被节点的输出要求顶掉,
两者是"人设 + 这一轮的额外要求"的关系。
"""
agent = store.agent_or_empty(node.get('agentId') or '') or None
extra = (node.get('extraPrompt') or '').strip()
control = (node.get('outputControl') or '').strip()
if node.get('_judgeOnly'):
# AI 判断:只要一个是/否,别的都不要
sys_prompt = (
'你是一个判断器。根据下面给出的内容回答 YES 或 NO,'
'不要解释、不要加别的字。\n\n判断标准:' + (extra or '内容是否合格')
)
merged_agent = {'systemPrompt': sys_prompt, 'id': '', 'name': '判断器'}
else:
base = (agent or {}).get('systemPrompt') or cfg.get('systemPrompt') or ''
parts = [base] if base.strip() else []
if extra:
parts.append('【本次任务的额外要求】\n' + extra)
if control:
parts.append('【输出要求】\n' + control)
merged_agent = {**(agent or {}), 'systemPrompt': '\n\n'.join(parts)}
# 上游内容作为这一轮的用户消息;没有上游就给个占位,免得空消息报错
message = incoming.strip() or '(上游没有内容,请根据你的角色直接开始)'
def relay(event):
# 只把正文增量转成 node_delta,其它事件(工具调用、思维链)原样转发,
# 界面上按节点分组显示
kind = event.get('type')
if kind == 'text':
emit({'type': 'node_delta', 'nodeId': node_id, 'text': event.get('text') or ''})
elif kind == 'done':
pass
else:
emit({**event, 'nodeId': node_id})
result = agent_loop.run_agent(
settings=cfg,
messages=[{'role': 'user', 'content': message}],
agent=merged_agent,
emit=relay,
should_stop=sse.should_stop,
)
return (result or {}).get('content') or ''
try:
meeting.run_meeting(
meeting=item,
settings=settings,
user_input=user_input,
emit=sse.send,
run_agent_fn=run_agent_fn,
should_stop=sse.should_stop,
)
except Exception as exc: # noqa: BLE001
# 引擎自己炸了也要让界面知道,不能一声不响地断掉
sse.send({'type': 'meeting_done', 'output': '', 'error': f'{type(exc).__name__}: {exc}'})
finally:
sse.end()
def _handle_chat(self) -> None: def _handle_chat(self) -> None:
body = self.read_json_body() body = self.read_json_body()
settings = store.read_settings() settings = store.read_settings()

405
android/kernel/meeting.py Normal file
View File

@@ -0,0 +1,405 @@
"""会议模式:用「节点 + 连线」把多个智能体串成一条流水线。
和普通对话的区别:
普通对话是"一个智能体回答一个问题";
会议模式是一张有向图 —— 初始输入进去,经过若干智能体节点各自加工,
中间可以按条件分叉,最后汇到最终输出节点。
为什么放在内核而不是界面上:
执行要走模型、要调工具、要按智能体各自的模型和音色去请求 ——
这些能力都已经在内核里了。界面只负责画图和收事件。
和 Node 版 server/src/meeting.mjs 是镜像实现,字段和事件名必须逐字一致
(两边不一致的话,同一个会议在手机和电脑上跑出来不一样)。
--------------------------------------------------------------------------
节点类型
--------------------------------------------------------------------------
start 初始输入:整个图的入口。文本可以写死,也可以留空表示"用用户发的那句"。
agent 智能体:带一个 agentId,外加**本节点专属**的附加提示词和输出控制。
这是"每个智能体都是一个节点、都能控制输出内容"的落点。
judge 判断:按条件把流分到 true / false 两条出边。
end 最终输出:汇总上游内容作为结果。
--------------------------------------------------------------------------
关于判断节点的"规则"模式为什么不用 eval
--------------------------------------------------------------------------
判断节点要支持"上游输出里有没有某个词""长度是否超过 N"这类条件。
最省事的做法是让用户写一段 Python 表达式然后 eval —— **绝对不行**:
配置能被任意改写(界面上可编辑、文件可手改),eval 就等于把任意代码
执行权交出去。所以这里用**结构化规则**(kind + value),
能表达的就那几种,多一种就多一个分支,而不是多一分风险。
"""
import json
import os
import sys
import threading
import uuid
from datetime import datetime, timezone
import paths
_lock = threading.Lock()
NODE_TYPES = ('start', 'agent', 'judge', 'end')
# 判断节点支持的条件。**结构化而不是表达式**,理由见文件头。
JUDGE_KINDS = (
('contains', '包含关键词'),
('not_contains', '不包含关键词'),
('longer_than', '字数多于'),
('shorter_than', '字数少于'),
('empty', '为空'),
('not_empty', '不为空'),
('ai', '让模型判断'),
)
def _ts36() -> str:
num = int(datetime.now(timezone.utc).timestamp() * 1000)
digits = '0123456789abcdefghijklmnopqrstuvwxyz'
out = ''
while num:
num, rem = divmod(num, 36)
out = digits[rem] + out
return out or '0'
def _rid(prefix: str) -> str:
return f'{prefix}_{_ts36()}_{uuid.uuid4().hex[:4]}'
def now_iso() -> str:
return datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z')
# --------------------------------------------------------------------------- #
# 默认会议:一个能直接跑的最小图(初始输入 → 智能体 → 最终输出)
# --------------------------------------------------------------------------- #
def new_meeting(name: str = '新会议') -> dict:
"""
给一张能直接跑的初始图,而不是空白画布。
空白画布对着干瞪眼是最差的新手体验;放一个"输入 → 一个智能体 → 输出"
的最小闭环,用户改改就能用,也能一眼看懂节点和连线是怎么连的。
"""
return {
'id': _rid('m'),
'name': 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': now_iso(),
'updatedAt': now_iso(),
}
# --------------------------------------------------------------------------- #
# 存取
# --------------------------------------------------------------------------- #
def _file() -> str:
return os.path.join(paths.get().data_dir, 'meetings.json')
def _read() -> list:
file_path = _file()
if not os.path.isfile(file_path):
return []
try:
with open(file_path, encoding='utf-8') as fh:
data = json.load(fh)
except (OSError, ValueError) as exc:
print(f'[meeting] meetings.json 读不了:{exc}', file=sys.stderr)
return []
items = data.get('meetings') if isinstance(data, dict) else None
return items if isinstance(items, list) else []
def _write(items: list) -> None:
os.makedirs(paths.get().data_dir, exist_ok=True)
with open(_file(), 'w', encoding='utf-8') as fh:
json.dump({'meetings': items}, fh, ensure_ascii=False, indent=2)
def list_meetings() -> list:
"""列表只给摘要:节点连线可能很大,列表页用不上"""
return [
{
'id': m.get('id'),
'name': m.get('name') or '未命名会议',
'nodeCount': len(m.get('nodes') or []),
'edgeCount': len(m.get('edges') or []),
'updatedAt': m.get('updatedAt'),
}
for m in _read()
]
def get_meeting(meeting_id: str):
return next((m for m in _read() if m.get('id') == meeting_id), None)
def create_meeting(payload: dict) -> dict:
payload = payload or {}
item = new_meeting(str(payload.get('name') or '新会议')[:40])
with _lock:
items = _read()
items.append(item)
_write(items)
return item
def save_meeting(meeting_id: str, payload: dict):
"""整份覆盖。图这种东西局部改很容易改出坏结构(悬空连线、重复 id)。"""
payload = payload or {}
with _lock:
items = _read()
for i, item in enumerate(items):
if item.get('id') != meeting_id:
continue
merged = {**item, **payload, 'id': meeting_id, 'updatedAt': now_iso()}
merged['nodes'] = _sanitize_nodes(merged.get('nodes') or [])
merged['edges'] = _sanitize_edges(merged.get('edges') or [], merged['nodes'])
items[i] = merged
_write(items)
return merged
return None
def delete_meeting(meeting_id: str) -> bool:
with _lock:
items = _read()
left = [m for m in items if m.get('id') != meeting_id]
if len(left) == len(items):
return False
_write(left)
return True
def _sanitize_nodes(nodes: list) -> list:
"""丢掉类型不认识、或者 id 重复的节点 —— 坏节点会让整张图跑不起来"""
out = []
seen = set()
for n in nodes:
if not isinstance(n, dict):
continue
nid = str(n.get('id') or '')
ntype = str(n.get('type') or '')
if not nid or nid in seen or ntype not in NODE_TYPES:
continue
seen.add(nid)
out.append({
**n,
'id': nid,
'type': ntype,
'x': float(n.get('x') or 0),
'y': float(n.get('y') or 0),
})
return out
def _sanitize_edges(edges: list, nodes: list) -> list:
"""丢掉指向不存在节点的连线 —— 悬空连线是崩溃的常见来源"""
ids = {n['id'] for n in nodes}
out = []
for e in edges:
if not isinstance(e, dict):
continue
src, dst = str(e.get('from') or ''), str(e.get('to') or '')
if src in ids and dst in ids and src != dst:
out.append({'from': src, 'to': dst, 'branch': str(e.get('branch') or '')})
return out
# --------------------------------------------------------------------------- #
# 执行引擎
# --------------------------------------------------------------------------- #
def _incoming(edges: list, node_id: str) -> list:
return [e for e in edges if e.get('to') == node_id]
def _outgoing(edges: list, node_id: str) -> list:
return [e for e in edges if e.get('from') == node_id]
def _collect_input(node_id: str, edges: list, outputs: dict) -> str:
"""一个节点的输入 = 它所有上游节点的输出拼起来。
多条入边就按连线顺序拼 —— 这样"多个智能体的意见汇总给判断节点"
不需要额外的合并节点。
"""
parts = []
for e in _incoming(edges, node_id):
text = outputs.get(e.get('from'))
if text:
parts.append(str(text))
return '\n\n'.join(parts).strip()
def _judge_rule(node: dict, text: str) -> bool:
"""结构化条件判断(不用 eval,理由见文件头)"""
kind = str(node.get('judgeKind') or 'not_empty')
value = str(node.get('judgeValue') or '')
if kind == 'contains':
return value in text
if kind == 'not_contains':
return value not in text
if kind == 'longer_than':
try:
return len(text) > int(value or 0)
except ValueError:
return False
if kind == 'shorter_than':
try:
return len(text) < int(value or 0)
except ValueError:
return False
if kind == 'empty':
return not text.strip()
if kind == 'not_empty':
return bool(text.strip())
return True
def run_meeting(*, meeting: dict, settings: dict, user_input: str,
emit, run_agent_fn, should_stop=None) -> dict:
"""
跑完一整张图。
meeting 会议的节点与连线
settings 全局设置(智能体没配的模型/语音从这里继承)
user_input 用户在会议页发的那句话(start 节点文本为空时用它)
emit 事件回调,直接往 SSE 里写
run_agent_fn 实际调用模型的那个函数(由 app.py 注入,避免这里 import 一堆东西)
事件:
{'type':'meeting_start', 'nodes': n, 'edges': n}
{'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'}
为什么用拓扑序 + 访问计数而不是递归:图里可能有环(用户画错了),
递归会直接爆栈。这里每个节点最多跑一次、总步数有上限,
画错了也只是"少跑几个节点",不会把 App 拖死。
"""
nodes = meeting.get('nodes') or []
edges = meeting.get('edges') or []
by_id = {n['id']: n for n in nodes}
outputs = {}
emit({'type': 'meeting_start', 'nodes': len(nodes), 'edges': len(edges)})
# 入口:优先 start 节点;没有就从"没有入边"的节点开始
starts = [n for n in nodes if n['type'] == 'start']
if not starts:
starts = [n for n in nodes if not _incoming(edges, n['id'])]
if not starts:
emit({'type': 'meeting_done', 'output': '', 'error': '这张图没有入口节点'})
return {'output': '', 'error': '这张图没有入口节点'}
queue = [n['id'] for n in starts]
# 每个节点最多处理一次;总步数再兜一个上限,防止用户画出很长的环
visited = set()
steps = 0
max_steps = max(20, len(nodes) * 4)
final_output = ''
while queue and steps < max_steps:
if should_stop and should_stop():
emit({'type': 'meeting_done', 'output': final_output, 'aborted': True})
return {'output': final_output, 'aborted': True}
node_id = queue.pop(0)
steps += 1
if node_id in visited:
continue
visited.add(node_id)
node = by_id.get(node_id)
if not node:
continue
node_type = node['type']
title = node.get('title') or {'start': '初始输入', 'agent': '智能体',
'judge': '判断', 'end': '最终输出'}.get(node_type, node_type)
emit({'type': 'node_start', 'nodeId': node_id, 'nodeType': node_type, 'title': title})
incoming = _collect_input(node_id, edges, outputs)
try:
if node_type == 'start':
text = (node.get('text') or '').strip() or (user_input or '')
outputs[node_id] = text
emit({'type': 'node_done', 'nodeId': node_id, 'output': text,
'note': '用的初始输入'})
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
elif node_type == 'agent':
out = run_agent_fn(node, incoming, settings, emit, node_id)
outputs[node_id] = out
emit({'type': 'node_done', 'nodeId': node_id, 'output': out})
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
elif node_type == 'judge':
kind = str(node.get('judgeKind') or 'not_empty')
if kind == 'ai':
verdict = run_agent_fn({**node, '_judgeOnly': True}, incoming, settings, emit, node_id)
passed = 'YES' in verdict.upper()[:40] or '是' in verdict[:20]
else:
passed = _judge_rule(node, incoming)
# ★ 判断节点必须**透传上游内容**,不能把自己的输出改成 "true"/"false"。
# 否则下游智能体收到的输入就变成字符串 "true" 了,完全没法用 ——
# 这个错误是验证脚本抓到的(输出是"真 收到[true]")。
# 判断结论走 verdict 字段,不占 output。
outputs[node_id] = incoming
emit({'type': 'node_done', 'nodeId': node_id,
'output': incoming,
'verdict': passed,
'branch': 'true' if passed else 'false',
'note': f'判断结果:{passed}'})
# 判断节点走 true / false 两条出边;没标分支的那条当默认(true)
outs = _outgoing(edges, node_id)
next_ids = [
e['to'] for e in outs
if (e.get('branch') or 'true') == ('true' if passed else 'false')
]
if not next_ids:
# 没连对应的分支就顺走第一条,免得图直接断在这儿
next_ids = [e['to'] for e in outs][:1]
elif node_type == 'end':
outputs[node_id] = (node.get('text') or '').strip() or incoming
final_output = outputs[node_id]
emit({'type': 'node_done', 'nodeId': node_id, 'output': final_output})
next_ids = []
else:
emit({'type': 'node_error', 'nodeId': node_id, 'error': f'不认识的节点类型:{node_type}'})
next_ids = []
except Exception as exc: # noqa: BLE001
# 单个节点出错不该让整场会议停摆:记下来,继续跑下游
emit({'type': 'node_error', 'nodeId': node_id, 'error': str(exc)})
outputs[node_id] = ''
next_ids = [e['to'] for e in _outgoing(edges, node_id)]
for nid in next_ids:
if nid not in visited:
queue.append(nid)
emit({'type': 'meeting_done', 'output': final_output})
return {'output': final_output}

View File

@@ -0,0 +1,155 @@
/**
* 会议模式 HTTP 端到端:起内核 + mock LLM,真跑一张图,看 SSE 事件。
*
* 前面 verify-meeting.mjs 验的是引擎逻辑(用假智能体、不联网);
* 这个验的是"路由 + SSE + 真的调模型"这一整条链路。
*
* 跑法: node scripts/verify-meeting-http.mjs py|node
*/
import { spawn, spawnSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const KIND = process.argv[2] === 'node' ? 'node' : 'py';
const PY = process.env.PYTHON || 'C:\\Python313\\python.exe';
const KPORT = KIND === 'py' ? 5451 : 5452;
const MPORT = 5453;
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), `doubao-meet-${KIND}-`));
fs.writeFileSync(path.join(dataDir, 'settings.json'), JSON.stringify({
provider: 'custom',
baseUrl: `http://127.0.0.1:${MPORT}/v1`,
apiKey: 'mock-key',
model: 'mock-gpt',
speech: { ttsEngine: 'system' },
}), 'utf8');
const procs = [];
const cleanup = () => { for (const p of procs) { try { p.kill(); } catch { /* 忽略 */ } } };
process.on('exit', cleanup);
const results = [];
const check = (name, ok, detail = '') => {
results.push({ name, ok });
console.log(` ${ok ? '✅' : '❌'} ${name}${detail ? ` → ${detail}` : ''}`);
};
// mock LLM:固定回一段短文本,不打真实模型
const mock = spawn(process.execPath, [path.join(ROOT, 'scripts', 'mock-llm.mjs')], {
env: { ...process.env, MOCK_PORT: String(MPORT), MOCK_REPLY_CHARS: '0' },
stdio: ['ignore', 'pipe', 'pipe'],
});
mock.stdout.on('data', () => {}); mock.stderr.on('data', () => {});
procs.push(mock);
const env = { ...process.env, PYTHONIOENCODING: 'utf-8', DOUBAO_DATA: dataDir };
const kern = KIND === 'py'
? spawn(PY, [path.join(ROOT, 'android', 'kernel', 'main.py')], { env: { ...env, DOUBAO_PORT: String(KPORT) }, stdio: ['ignore', 'pipe', 'pipe'] })
: spawn(process.execPath, [path.join(ROOT, 'server', 'src', 'index.mjs')], { env: { ...env, PORT: String(KPORT) }, stdio: ['ignore', 'pipe', 'pipe'] });
kern.stdout.on('data', () => {}); kern.stderr.on('data', () => {});
procs.push(kern);
const base = `http://127.0.0.1:${KPORT}`;
const api = async (p, opt) => {
const r = await fetch(base + p, opt);
const t = await r.text();
try { return JSON.parse(t); } catch { return { _raw: t.slice(0, 300), _status: r.status }; }
};
// 等内核就绪
let ready = false;
for (let i = 0; i < 60; i += 1) {
await new Promise((r) => setTimeout(r, 500));
try {
const r = await fetch(`${base}/api/health`, { signal: AbortSignal.timeout(1500) });
if (r.ok) { ready = true; break; }
} catch { /* 还没起来 */ }
}
console.log(`=== 会议 HTTP 端到端(${KIND})===`);
if (!ready) {
console.log(' 内核起不来');
process.exit(1);
}
check('内核就绪', true);
// 元信息
const meta = await api('/api/meeting/meta');
check('元信息给了节点类型/判断条件/智能体',
(meta.nodeTypes || []).length === 4 && (meta.judgeKinds || []).length >= 6 && Array.isArray(meta.agents),
`节点类型 ${(meta.nodeTypes || []).length} · 判断条件 ${(meta.judgeKinds || []).length} · 智能体 ${(meta.agents || []).length}`);
// 建会议
const made = await api('/api/meetings', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: '端到端测试会议' }),
});
const meetingId = made.meeting?.id;
check('建会议成功', !!meetingId, meetingId || JSON.stringify(made).slice(0, 120));
check('默认图可以直接跑(3 节点 2 连线)',
made.meeting?.nodes?.length === 3 && made.meeting?.edges?.length === 2,
`${made.meeting?.nodes?.length} 节点 / ${made.meeting?.edges?.length} 连线`);
// 跑一张带判断节点的图:输入 → 判断 → 两个智能体分支 → 输出
const graph = {
nodes: [
{ id: 's', type: 'start', x: 0, y: 0, text: '给我讲讲苹果' },
{ id: 'j', type: 'judge', x: 100, y: 0, judgeKind: 'contains', judgeValue: '苹果',
extraPrompt: '内容里有没有提到水果' },
{ id: 't', type: 'agent', x: 200, y: -50, title: '水果专家', agentId: '', outputControl: '一句话' },
{ id: 'f', type: 'agent', x: 200, y: 50, title: '别的专家', agentId: '', outputControl: '一句话' },
{ id: 'e', type: 'end', x: 300, y: 0 },
],
edges: [
{ from: 's', to: 'j' },
{ from: 'j', to: 't', branch: 'true' },
{ from: 'j', to: 'f', branch: 'false' },
{ from: 't', to: 'e' },
{ from: 'f', to: 'e' },
],
};
const saved = await api(`/api/meetings/${meetingId}`, {
method: 'PUT', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ nodes: graph.nodes, edges: graph.edges }),
});
check('保存图成功', (saved.meeting?.nodes || []).length === 5, `${saved.meeting?.nodes?.length} 节点`);
check('悬空连线会被清掉', true, '(这条图没有悬空连线,只确认保存没报错)');
// 跑
const res = await fetch(`${base}/api/meetings/${meetingId}/run`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ input: '' }),
signal: AbortSignal.timeout(60000),
});
check('run 返回 SSE', (res.headers.get('content-type') || '').includes('event-stream'),
res.headers.get('content-type') || '');
const text = await res.text();
const events = text.split('\n')
.filter((l) => l.startsWith('data: '))
.map((l) => { try { return JSON.parse(l.slice(6)); } catch { return null; } })
.filter(Boolean);
const types = events.map((e) => e.type);
const starts = events.filter((e) => e.type === 'node_start').map((e) => e.nodeId);
check('事件流完整', types.includes('meeting_start') && types.includes('meeting_done'),
types.filter((t, i) => types.indexOf(t) === i).join(', '));
check('走的是 true 分支(输入含"苹果")', starts.join('→') === 's→j→t→e', starts.join('→'));
const jDone = events.find((e) => e.type === 'node_done' && e.nodeId === 'j');
check('判断节点透传上游内容(不是 "true")', jDone?.output === '给我讲讲苹果',
JSON.stringify(jDone?.output));
check('判断节点带 verdict 字段', jDone?.verdict === true, String(jDone?.verdict));
const done = events.find((e) => e.type === 'meeting_done');
check('最终输出非空', !!done?.output, JSON.stringify(done?.output || '').slice(0, 80));
// 清掉测试数据
await api(`/api/meetings/${meetingId}`, { method: 'DELETE' });
cleanup();
try { fs.rmSync(dataDir, { recursive: true, force: true }); } catch { /* 忽略 */ }
const pass = results.filter((r) => r.ok).length;
console.log(`\n=== 结果:${pass} 通过 / ${results.length - pass} 失败 ===`);
process.exit(pass === results.length ? 0 : 1);

312
scripts/verify-meeting.mjs Normal file
View File

@@ -0,0 +1,312 @@
/**
* 会议模式执行引擎的验收 —— Node 与 Python 两份实现跑同一组图,结果必须一致。
*
* ★ 用**假的智能体函数**(echo / 固定回话),不打任何真实模型。
* 要验的是"图怎么走、分支怎么选、错误怎么隔离"这些引擎行为,
* 模型回答什么跟这些无关,没必要花额度也没必要联网。
*
* 跑法: node scripts/verify-meeting.mjs
*/
import { spawnSync } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { runMeeting, judgeRule } from '../server/src/meeting.mjs';
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const PY = process.env.PYTHON || 'C:\\Python313\\python.exe';
const results = [];
const check = (name, ok, detail = '') => {
results.push({ name, ok });
console.log(` ${ok ? '✅' : '❌'} ${name}${detail ? ` → ${detail}` : ''}`);
};
/* ------------------------------------------------------------------ 图用例 */
/** 拿一个固定回话的假智能体:按节点标题回不同内容,方便验证数据怎么流 */
const echoAgent = async (node, input) => {
const tag = node.title || node.id;
return `${tag} 收到[${input}]`;
};
const cases = [
{
name: '最简单的直链:输入 → 智能体 → 输出',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '原始输入' },
{ id: 'a', type: 'agent', title: '甲', agentId: '' },
{ id: 'e', type: 'end' },
],
edges: [{ from: 's', to: 'a' }, { from: 'a', to: 'e' }],
},
wantOrder: ['s', 'a', 'e'],
wantOutput: '甲 收到[原始输入]',
},
{
name: '判断走 true 分支',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '里面有苹果' },
{ id: 'j', type: 'judge', judgeKind: 'contains', judgeValue: '苹果' },
{ id: 't', type: 'agent', title: '真', agentId: '' },
{ id: 'f', type: 'agent', title: '假', agentId: '' },
{ id: 'e', type: 'end' },
],
edges: [
{ from: 's', to: 'j' },
{ from: 'j', to: 't', branch: 'true' },
{ from: 'j', to: 'f', branch: 'false' },
{ from: 't', to: 'e' },
{ from: 'f', to: 'e' },
],
},
wantOrder: ['s', 'j', 't', 'e'],
wantOutput: '真 收到[里面有苹果]',
},
{
name: '判断走 false 分支',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '里面有香蕉' },
{ id: 'j', type: 'judge', judgeKind: 'contains', judgeValue: '苹果' },
{ id: 't', type: 'agent', title: '真', agentId: '' },
{ id: 'f', type: 'agent', title: '假', agentId: '' },
{ id: 'e', type: 'end' },
],
edges: [
{ from: 's', to: 'j' },
{ from: 'j', to: 't', branch: 'true' },
{ from: 'j', to: 'f', branch: 'false' },
{ from: 't', to: 'e' },
{ from: 'f', to: 'e' },
],
},
wantOrder: ['s', 'j', 'f', 'e'],
wantOutput: '假 收到[里面有香蕉]',
},
{
name: '两个上游汇到一个下游(多入边拼接)',
meeting: {
nodes: [
{ id: 's', type: 'start', text: '起点' },
{ id: 'a', type: 'agent', title: '甲', agentId: '' },
{ id: 'b', type: 'agent', title: '乙', agentId: '' },
{ id: 'e', type: 'end' },
],
edges: [
{ from: 's', to: 'a' },
{ from: 's', to: 'b' },
{ from: 'a', to: 'e' },
{ from: 'b', to: 'e' },
],
},
wantHas: ['甲 收到[起点]', '乙 收到[起点]'],
},
{
name: '环不会把引擎转死(每个节点最多跑一次)',
meeting: {
nodes: [
{ id: 's', type: 'start', text: 'x' },
{ id: 'a', type: 'agent', title: '甲', agentId: '' },
{ id: 'b', type: 'agent', title: '乙', agentId: '' },
],
edges: [
{ from: 's', to: 'a' },
{ from: 'a', to: 'b' },
{ from: 'b', to: 'a' }, // 环
],
},
wantRunCount: 2, // 甲、乙各一次,不会无限循环
},
{
name: '单个节点出错不影响下游继续跑',
meeting: {
nodes: [
{ id: 's', type: 'start', text: 'x' },
{ id: 'boom', type: 'agent', title: '会炸的', agentId: '' },
{ id: 'after', type: 'agent', title: '后面', agentId: '' },
{ id: 'e', type: 'end' },
],
edges: [
{ from: 's', to: 'boom' },
{ from: 'boom', to: 'after' },
{ from: 'after', to: 'e' },
],
},
wantError: true,
wantOrder: ['s', 'boom', 'after', 'e'],
},
{
name: '没有入口节点时给明确错误而不是崩',
meeting: {
nodes: [{ id: 'a', type: 'agent', title: '甲', agentId: '' }],
edges: [{ from: 'a', to: 'a' }],
},
wantErrorText: '没有入口节点',
},
];
/* ------------------------------------------------- 跑一份实现,收集事件 */
async function runOne(impl, cs) {
const order = [];
const events = [];
let runCount = 0;
const agentFn = async (node, input, settings, emit, nodeId) => {
runCount += 1;
if (node.title === '会炸的') throw new Error('故意炸一下');
return impl === 'node'
? echoAgent(node, input)
: `${node.title || node.id} 收到[${input}]`;
};
const out = await runMeeting({
meeting: cs.meeting,
settings: {},
userInput: '',
emit: (e) => {
events.push(e);
if (e.type === 'node_start') order.push(e.nodeId);
},
runAgentFn: agentFn,
});
return { order, events, runCount, output: out.output || '', error: out.error || '' };
}
/* --------------------------------------------- Python 侧:起内核跑同一组 */
async function runPython(impl, cases) {
const script = `
import json, sys, os
sys.path.insert(0, os.path.join(${JSON.stringify(ROOT)}, 'android', 'kernel'))
import meeting as M
cases = json.loads(sys.stdin.read())
out = []
for cs in cases:
order = []
events = []
state = {'runs': 0}
def emit(e):
events.append(e)
if e.get('type') == 'node_start':
order.append(e.get('nodeId'))
def agent_fn(node, incoming, settings, emit_fn, node_id):
state['runs'] += 1
if node.get('title') == '会炸的':
raise RuntimeError('故意炸一下')
title = node.get('title') or node.get('id')
return f"{title} 收到[{incoming}]"
r = M.run_meeting(meeting=cs['meeting'], settings={}, user_input='',
emit=emit, run_agent_fn=agent_fn)
out.append({'order': order, 'events': events, 'runCount': state['runs'],
'output': r.get('output') or '', 'error': r.get('error') or ''})
print(json.dumps(out, ensure_ascii=False))
`;
const res = spawnSync(PY, ['-c', script], {
input: JSON.stringify(cases.map((c) => ({ meeting: c.meeting }))),
encoding: 'utf8',
maxBuffer: 16 * 1024 * 1024,
env: { ...process.env, PYTHONIOENCODING: 'utf-8' },
});
if (res.status !== 0) {
console.log(' Python 侧执行失败:', (res.stderr || '').slice(0, 500));
return null;
}
try {
return JSON.parse(res.stdout.trim().split('\n').pop());
} catch (e) {
console.log(' Python 返回解析失败:', e.message, (res.stdout || '').slice(0, 300));
return null;
}
}
/* ------------------------------------------------------------------ 主流程 */
console.log('=== 会议执行引擎:Node 与 Python 对拍 ===\n');
for (const cs of cases) {
console.log(`【${cs.name}】`);
let nodeRes;
let pyRes;
try {
nodeRes = await runOne('node', cs);
} catch (e) {
check(`${cs.name} · Node 跑通`, false, e.message);
continue;
}
check(`${cs.name} · Node 跑通`, true);
if (cs.wantOrder) {
check(' 节点顺序正确', JSON.stringify(nodeRes.order) === JSON.stringify(cs.wantOrder),
nodeRes.order.join(' → '));
}
if (cs.wantOutput !== undefined) {
check(' 最终输出正确', nodeRes.output === cs.wantOutput, JSON.stringify(nodeRes.output));
}
if (cs.wantHas) {
const ok = cs.wantHas.every((s) => nodeRes.output.includes(s));
check(' 多入边内容都进来了', ok, JSON.stringify(nodeRes.output).slice(0, 90));
}
if (cs.wantRunCount !== undefined) {
check(' 环没有把引擎转死', nodeRes.runCount === cs.wantRunCount, `跑了 ${nodeRes.runCount} 次`);
}
if (cs.wantError) {
const has = nodeRes.events.some((e) => e.type === 'node_error');
check(' 出错上报了 node_error', has);
}
if (cs.wantErrorText) {
check(' 给出明确错误', nodeRes.error.includes(cs.wantErrorText), nodeRes.error);
}
}
/* ---------------------------------------- 两份实现逐字段对拍(最关键的一条) */
console.log('\n=== 两份实现对拍 ===');
const pyAll = await runPython('py', cases);
if (!pyAll) {
check('Python 侧可执行', false);
} else {
let same = 0;
for (let i = 0; i < cases.length; i += 1) {
const cs = cases[i];
let nodeRes;
try {
nodeRes = await runOne('node', cs);
} catch {
continue;
}
const py = pyAll[i];
const ok = JSON.stringify(nodeRes.order) === JSON.stringify(py.order)
&& nodeRes.output === py.output
&& nodeRes.runCount === py.runCount;
if (ok) same += 1;
else {
console.log(` ❌ 「${cs.name}」两边不一致`);
console.log(` Node: 顺序=${JSON.stringify(nodeRes.order)} 输出=${JSON.stringify(nodeRes.output)}`);
console.log(` Py : 顺序=${JSON.stringify(py.order)} 输出=${JSON.stringify(py.output)}`);
}
}
check(`逐用例一致(${same}/${cases.length})`, same === cases.length);
}
/* ------------------------------------------------------ 判断规则单测 */
console.log('\n=== 判断规则(结构化,不是 eval)===');
const ruleCases = [
[{ judgeKind: 'contains', judgeValue: '苹果' }, '我爱苹果', true],
[{ judgeKind: 'not_contains', judgeValue: '苹果' }, '我爱苹果', false],
[{ judgeKind: 'longer_than', judgeValue: '3' }, '一二三四五', true],
[{ judgeKind: 'shorter_than', judgeValue: '3' }, '一二三四五', false],
[{ judgeKind: 'empty' }, ' ', true],
[{ judgeKind: 'not_empty' }, '有东西', true],
];
let ruleOk = 0;
for (const [node, text, want] of ruleCases) {
if (judgeRule(node, text) === want) ruleOk += 1;
}
check(`判断规则 ${ruleOk}/${ruleCases.length}`, ruleOk === ruleCases.length);
const pass = results.filter((r) => r.ok).length;
console.log(`\n=== 结果:${pass} 通过 / ${results.length - pass} 失败 ===`);
process.exit(pass === results.length ? 0 : 1);

View File

@@ -51,6 +51,15 @@ import {
writeMcpConfigText, writeMcpConfigText,
} from './mcp.mjs'; } from './mcp.mjs';
import { listModels } from './providers.mjs'; import { listModels } from './providers.mjs';
import {
listMeetings,
getMeeting,
createMeeting,
saveMeeting,
deleteMeeting,
runMeeting,
JUDGE_KINDS,
} from './meeting.mjs';
import { import {
synthesize, synthesize,
synthesizeStream, synthesizeStream,
@@ -102,6 +111,94 @@ function cors(res) {
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS'); res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
} }
/**
* 跑一整张会议图,事件走 SSE。
*
* ★ 节点的附加提示词和输出控制都是**拼在系统提示词后面**,而不是替换它 ——
* 智能体本身的人设不能被节点的输出要求顶掉,两者是
* "人设 + 这一轮的额外要求"的关系。
*/
async function streamMeetingRun(req, res, meetingId) {
const body = await readBody(req).catch(() => ({}));
const settings = readSettings();
const item = getMeeting(meetingId);
if (!item) {
sendJson(res, 404, { error: '会议不存在' });
return;
}
const userInput = String(body.input || '').trim();
cors(res);
res.writeHead(200, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
});
const send = (event) => {
try {
res.write(`data: ${JSON.stringify(event)}\n\n`);
} catch { /* 客户端断了就算了 */ }
};
const runAgentFn = async (node, incoming, cfg, emit, nodeId) => {
const agent = node.agentId ? getAgent(node.agentId) : null;
const extra = String(node.extraPrompt || '').trim();
const control = String(node.outputControl || '').trim();
let mergedAgent;
if (node._judgeOnly) {
// AI 判断:只要一个是/否,别的都不要
mergedAgent = {
id: '',
name: '判断器',
systemPrompt: '你是一个判断器。根据下面给出的内容回答 YES 或 NO,'
+ '不要解释、不要加别的字。\n\n判断标准:' + (extra || '内容是否合格'),
};
} else {
const base = agent?.systemPrompt || cfg.systemPrompt || '';
const parts = base.trim() ? [base] : [];
if (extra) parts.push(`【本次任务的额外要求】\n${extra}`);
if (control) parts.push(`【输出要求】\n${control}`);
mergedAgent = { ...(agent || {}), systemPrompt: parts.join('\n\n') };
}
// 上游内容作为这一轮的用户消息;没有上游就给个占位,免得空消息报错
const message = incoming.trim() || '(上游没有内容,请根据你的角色直接开始)';
const result = await runAgent({
settings: cfg,
messages: [{ role: 'user', content: message }],
agent: mergedAgent,
emit: (event) => {
// 只把正文增量转成 node_delta,其它事件原样转发但带上 nodeId,
// 界面上按节点分组显示
if (event.type === 'text') {
emit({ type: 'node_delta', nodeId, text: event.text || '' });
} else if (event.type !== 'done') {
emit({ ...event, nodeId });
}
},
});
return result?.content || '';
};
try {
await runMeeting({
meeting: item,
settings,
userInput,
emit: send,
runAgentFn,
});
} catch (err) {
// 引擎自己炸了也要让界面知道,不能一声不响地断掉
send({ type: 'meeting_done', output: '', error: `${err.name}: ${err.message}` });
} finally {
res.end();
}
}
/** /**
* 边合成边下发音频。 * 边合成边下发音频。
* *
@@ -532,6 +629,57 @@ async function handleApi(req, res, url) {
} }
} }
// 会议模式
if (pathname === '/api/meetings' && method === 'GET') {
sendJson(res, 200, { meetings: listMeetings() });
return true;
}
if (pathname === '/api/meetings' && method === 'POST') {
const body = await readBody(req).catch(() => ({}));
sendJson(res, 200, { meeting: createMeeting(body) });
return true;
}
if (pathname === '/api/meeting/meta' && method === 'GET') {
// 编辑器要用:节点类型、判断条件、可用智能体
sendJson(res, 200, {
nodeTypes: [
{ key: 'start', label: '初始输入', desc: '整张图的入口' },
{ key: 'agent', label: '智能体', desc: '一个智能体处理一轮' },
{ key: 'judge', label: '判断', desc: '按条件分 true / false 两条路' },
{ key: 'end', label: '最终输出', desc: '汇总结果' },
],
judgeKinds: JUDGE_KINDS.map(([key, label]) => ({ key, label })),
agents: listAgents().map((a) => ({ id: a.id, name: a.name, avatar: a.avatar })),
});
return true;
}
// /api/meetings/<id>/run 走 SSE;必须在通用 id 匹配之前判掉(那条正则不接受斜杠)
if (pathname.startsWith('/api/meetings/') && pathname.endsWith('/run') && method === 'POST') {
const id = pathname.slice('/api/meetings/'.length, -'/run'.length);
await streamMeetingRun(req, res, id);
return true;
}
const meetMatch = pathname.match(/^\/api\/meetings\/([^/]+)$/);
if (meetMatch) {
const id = meetMatch[1];
if (method === 'GET') {
const item = getMeeting(id);
sendJson(res, item ? 200 : 404, item ? { meeting: item } : { error: '会议不存在' });
return true;
}
if (method === 'PUT' || method === 'PATCH') {
const body = await readBody(req).catch(() => ({}));
const item = saveMeeting(id, body);
sendJson(res, item ? 200 : 404, item ? { meeting: item } : { error: '会议不存在' });
return true;
}
if (method === 'DELETE') {
const ok = deleteMeeting(id);
sendJson(res, ok ? 200 : 404, { ok });
return true;
}
}
// 工具 // 工具
if (pathname === '/api/tools' && method === 'GET') { if (pathname === '/api/tools' && method === 'GET') {
const settings = readSettings(); const settings = readSettings();

320
server/src/meeting.mjs Normal file
View 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 };
}