将 roundtable-coordinator 改为内置单例避免重复创建;legacy sync 加 TTL 减少 runs/stream 延迟;前端仅当前发言者显示研讨中。 Co-authored-by: Cursor <cursoragent@cursor.com>
358 lines
12 KiB
TypeScript
358 lines
12 KiB
TypeScript
/**
|
|
* 圆桌规划共享常量与小工具函数。
|
|
*
|
|
* 这里只放与具体 React 状态无关的纯数据 / 纯函数。复杂的 dialogue 管理、
|
|
* 编排循环、API 状态等都在 `hooks/` 与 `components/` 里维护。
|
|
*/
|
|
import type { IntentSummary } from "@/roundtable-planning/api/intent";
|
|
|
|
/** 指挥员(人类)所在的固定 seat id。Agent 席位从 2 开始排。 */
|
|
export const COMMANDER_SEAT_ID = 1;
|
|
|
|
/** 编排循环最大轮次。超出后 toast 强停以防死循环。 */
|
|
export const MAX_CYCLES = 8;
|
|
|
|
/** Step 2 角色面板的一行。 */
|
|
export type RoleEntry = {
|
|
id: number;
|
|
name: string;
|
|
agentId?: string;
|
|
type: "human" | "agent";
|
|
status: string;
|
|
};
|
|
|
|
/** 用户在推荐弹窗选定的一个研讨席位。 */
|
|
export type SelectedAgent = { agent_id: string; name: string };
|
|
|
|
/**
|
|
* 6 个内置 roundtable 席位的展示元数据。用户保留默认席位时,
|
|
* 头像 / 配色 / 中文显示名都按这里走;非内置(用户自建)走 FALLBACK_AVATAR_TYPES。
|
|
*/
|
|
export const BUILTIN_AGENT_META: Record<
|
|
string,
|
|
{ avatarType: string; displayName: string }
|
|
> = {
|
|
"roundtable-intelligence": { avatarType: "purple", displayName: "情报收集" },
|
|
"roundtable-environment": { avatarType: "emerald", displayName: "环境评估" },
|
|
"roundtable-solution-design": { avatarType: "human", displayName: "方案设计" },
|
|
"roundtable-risk-review": { avatarType: "amber", displayName: "风险审查" },
|
|
"roundtable-execution-plan": { avatarType: "pink", displayName: "执行规划" },
|
|
"roundtable-summary": { avatarType: "blue", displayName: "总结陈述" },
|
|
};
|
|
|
|
/** 非内置 agent 的头像配色轮换池。 */
|
|
export const FALLBACK_AVATAR_TYPES = [
|
|
"blue",
|
|
"purple",
|
|
"emerald",
|
|
"amber",
|
|
"pink",
|
|
] as const;
|
|
|
|
/**
|
|
* 用户未确认推荐弹窗时,Step 2 默认使用的 6 个内置席位。
|
|
* 保留默认时页面与原硬编码行为完全一致。
|
|
*/
|
|
export const DEFAULT_SELECTED_AGENTS: SelectedAgent[] = [
|
|
{ agent_id: "roundtable-summary", name: "总结陈述" },
|
|
{ agent_id: "roundtable-intelligence", name: "情报收集" },
|
|
{ agent_id: "roundtable-environment", name: "环境评估" },
|
|
{ agent_id: "roundtable-solution-design", name: "方案设计" },
|
|
{ agent_id: "roundtable-risk-review", name: "风险审查" },
|
|
{ agent_id: "roundtable-execution-plan", name: "执行规划" },
|
|
];
|
|
|
|
export function getAvatarTypeFor(agentId: string, index: number): string {
|
|
return (
|
|
BUILTIN_AGENT_META[agentId]?.avatarType ??
|
|
FALLBACK_AVATAR_TYPES[index % FALLBACK_AVATAR_TYPES.length]
|
|
);
|
|
}
|
|
|
|
export function getDisplayNameFor(agent: SelectedAgent): string {
|
|
return BUILTIN_AGENT_META[agent.agent_id]?.displayName ?? agent.name;
|
|
}
|
|
|
|
/**
|
|
* 右侧角色面板的模板列表。指挥员固定 id=1,agents 按用户在推荐弹窗里的
|
|
* 选择顺序排 id=2..N+1,与可视化圆桌 + agentNameToRole 保持一致。
|
|
*/
|
|
export function buildRoleTemplates(
|
|
agents: SelectedAgent[],
|
|
): ReadonlyArray<Omit<RoleEntry, "status">> {
|
|
const out: Omit<RoleEntry, "status">[] = [
|
|
{ id: COMMANDER_SEAT_ID, name: "指挥员 / 主持人", type: "human" },
|
|
];
|
|
agents.forEach((a, i) => {
|
|
out.push({
|
|
id: i + 2,
|
|
name: getDisplayNameFor(a),
|
|
agentId: a.agent_id,
|
|
type: "agent",
|
|
});
|
|
});
|
|
return out;
|
|
}
|
|
|
|
export function makeRolesFromTemplates(
|
|
templates: ReadonlyArray<Omit<RoleEntry, "status">>,
|
|
defaultStatus: string,
|
|
overrides: Record<number, string> = {},
|
|
): RoleEntry[] {
|
|
return templates.map((t) => ({
|
|
...t,
|
|
status: overrides[t.id] ?? defaultStatus,
|
|
}));
|
|
}
|
|
|
|
/**
|
|
* `agent_name`(小写)→ bubble meta 映射。流式输出时根据它反查
|
|
* speakerId / 头像 / 中文名,保证可视化圆桌的高亮和气泡渲染对齐。
|
|
*/
|
|
export function buildAgentNameToRole(
|
|
agents: SelectedAgent[],
|
|
): Record<string, { speakerId: number; avatarType: string; displayName: string }> {
|
|
const out: Record<
|
|
string,
|
|
{ speakerId: number; avatarType: string; displayName: string }
|
|
> = {};
|
|
agents.forEach((a, i) => {
|
|
out[a.agent_id] = {
|
|
speakerId: i + 2,
|
|
avatarType: getAvatarTypeFor(a.agent_id, i),
|
|
displayName: getDisplayNameFor(a),
|
|
};
|
|
});
|
|
return out;
|
|
}
|
|
|
|
export function nowTime(): string {
|
|
return new Date().toLocaleTimeString("zh-CN", { hour12: false });
|
|
}
|
|
|
|
/**
|
|
* 圆桌总控协调智能体的**固定单例 id**。后端 `_roundtable_seed.COORDINATOR_AGENT_ID`
|
|
* 与本常量必须保持一致(2026-05 改造前是 `roundtable-coordinator-<ts36>` 形式,
|
|
* 每次会话生成新 id 导致 `.deer-flow/agents/` 累积大量壳目录)。
|
|
*
|
|
* 改造后:
|
|
* - 后端 ensure 机制保证磁盘上始终存在 `.deer-flow/agents/roundtable-coordinator/`;
|
|
* - 本次会话的「可调度席位列表」由后端 init 通过 human 消息注入 coordinator
|
|
* thread 历史,不再写入 SOUL,所以单例 SOUL 长期稳定;
|
|
* - 前端 `streamMultiAgent({ coordinatorName })` 等位置不需要任何改动,因为
|
|
* `coordinatorName` 仍然是一个**字符串**,只是值不再每次变化。
|
|
*/
|
|
export const COORDINATOR_AGENT_ID = "roundtable-coordinator";
|
|
|
|
/**
|
|
* 兼容性保留:历史上叫 `newCoordinatorName()`,意为"生成新的一次性 coordinator id"。
|
|
* 改造为单例后实际只返回常量;命名不再准确,但留下避免触发跨文件级联改名。
|
|
* 新代码请直接使用 {@link COORDINATOR_AGENT_ID}。
|
|
*/
|
|
export function newCoordinatorName(): string {
|
|
return COORDINATOR_AGENT_ID;
|
|
}
|
|
|
|
/**
|
|
* 后端 intent agent 输出的**标准** `[INTENT_READY]\n\`\`\`json {...}\`\`\`` 块形状。
|
|
* 仅作格式参考 / 快速匹配用;实际从气泡正文里抽摘要走 `splitIntentReadyBlock` 的
|
|
* 容错提取(marker 定位 + 括号配对 + 多级降级 parse),不再依赖这条严格正则。
|
|
*/
|
|
export const INTENT_READY_RE = /\[INTENT_READY\]\s*```json\s*(\{[\s\S]*?\})\s*```/;
|
|
|
|
/**
|
|
* 把 JSON 文本里**字符串值内部**的字面控制字符(换行 / 回车 / 制表符)转义成合法的
|
|
* `\n` / `\r` / `\t`。模型偶尔会在 summary 的字符串值里直接敲换行,产出的 JSON 不合法,
|
|
* `JSON.parse` 会抛 `Bad control character in string literal`。这里只在字符串内替换,
|
|
* 不动结构性空白,避免破坏本来就合法的 JSON。
|
|
*/
|
|
function sanitizeJsonControlChars(raw: string): string {
|
|
let out = "";
|
|
let inString = false;
|
|
let escaped = false;
|
|
for (const ch of raw) {
|
|
if (escaped) {
|
|
out += ch;
|
|
escaped = false;
|
|
continue;
|
|
}
|
|
if (ch === "\\") {
|
|
out += ch;
|
|
escaped = true;
|
|
continue;
|
|
}
|
|
if (ch === '"') {
|
|
inString = !inString;
|
|
out += ch;
|
|
continue;
|
|
}
|
|
if (inString) {
|
|
if (ch === "\n") {
|
|
out += "\\n";
|
|
continue;
|
|
}
|
|
if (ch === "\r") {
|
|
out += "\\r";
|
|
continue;
|
|
}
|
|
if (ch === "\t") {
|
|
out += "\\t";
|
|
continue;
|
|
}
|
|
}
|
|
out += ch;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/**
|
|
* 从 `fromIndex` 起找第一个 `{`,按花括号配对(跳过字符串内部的括号)找到匹配的 `}`,
|
|
* 返回 JSON 子串及其在原文里的起止下标。
|
|
*
|
|
* 比 `\{[\s\S]*?\}` 这种正则更抗模型跑偏:容忍 JSON 内嵌套对象、字符串里的裸换行 /
|
|
* 花括号,以及模型漏写 ```json 代码围栏(直接 `[INTENT_READY] {...}`)的情况。
|
|
*/
|
|
function extractBalancedJson(
|
|
text: string,
|
|
fromIndex: number,
|
|
): { json: string; end: number } | null {
|
|
const start = text.indexOf("{", fromIndex);
|
|
if (start < 0) return null;
|
|
let depth = 0;
|
|
let inString = false;
|
|
let escaped = false;
|
|
for (let i = start; i < text.length; i += 1) {
|
|
const ch = text[i];
|
|
if (escaped) {
|
|
escaped = false;
|
|
continue;
|
|
}
|
|
if (ch === "\\") {
|
|
escaped = true;
|
|
continue;
|
|
}
|
|
if (ch === '"') {
|
|
inString = !inString;
|
|
continue;
|
|
}
|
|
if (inString) continue;
|
|
if (ch === "{") depth += 1;
|
|
else if (ch === "}") {
|
|
depth -= 1;
|
|
if (depth === 0) return { json: text.slice(start, i + 1), end: i + 1 };
|
|
}
|
|
}
|
|
return null; // 括号未闭合(流式中段 / 模型截断)
|
|
}
|
|
|
|
/** 去掉对象 / 数组里 `}` `]` 之前的尾随逗号(只在字符串外处理)。 */
|
|
function stripTrailingCommas(raw: string): string {
|
|
let out = "";
|
|
let inString = false;
|
|
let escaped = false;
|
|
for (let i = 0; i < raw.length; i += 1) {
|
|
const ch = raw[i];
|
|
if (escaped) {
|
|
out += ch;
|
|
escaped = false;
|
|
continue;
|
|
}
|
|
if (ch === "\\") {
|
|
out += ch;
|
|
escaped = true;
|
|
continue;
|
|
}
|
|
if (ch === '"') {
|
|
inString = !inString;
|
|
out += ch;
|
|
continue;
|
|
}
|
|
if (!inString && ch === ",") {
|
|
let j = i + 1;
|
|
while (j < raw.length && /\s/.test(raw[j])) j += 1;
|
|
if (raw[j] === "}" || raw[j] === "]") continue; // 丢弃尾随逗号
|
|
}
|
|
out += ch;
|
|
}
|
|
return out;
|
|
}
|
|
|
|
/** 把任意值归一成 string[]:数组逐项转字符串、单个字符串包成单元素、其它视为空。 */
|
|
function toStringArray(value: unknown): string[] {
|
|
if (Array.isArray(value)) {
|
|
return value
|
|
.map((x) => (typeof x === "string" ? x : x == null ? "" : String(x)))
|
|
.filter((x) => x.trim().length > 0);
|
|
}
|
|
if (typeof value === "string" && value.trim().length > 0) return [value];
|
|
return [];
|
|
}
|
|
|
|
/**
|
|
* 把解析出的对象归一成 IntentSummary。只要 `objective` 是非空字符串就认。
|
|
* constraints / assumptions 容忍模型写成字符串 / null / 缺失,统一归到 string[]。
|
|
*/
|
|
function normalizeIntentSummary(parsed: unknown): IntentSummary | null {
|
|
if (!parsed || typeof parsed !== "object") return null;
|
|
const obj = parsed as Record<string, unknown>;
|
|
const objective =
|
|
typeof obj.objective === "string" ? obj.objective.trim() : "";
|
|
if (!objective) return null;
|
|
return {
|
|
objective,
|
|
constraints: toStringArray(obj.constraints),
|
|
assumptions: toStringArray(obj.assumptions),
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 解析 INTENT_READY 的 JSON 块。内网模型输出不可控,这里逐级降级重试:
|
|
* 1) 原文直接 parse
|
|
* 2) 转义字符串内的裸控制字符(换行 / 制表符)后再 parse
|
|
* 3) 再去掉尾随逗号后 parse
|
|
* 三次都失败才放弃。任一成功都过 `normalizeIntentSummary` 兜字段类型。
|
|
*/
|
|
function parseIntentSummary(raw: string): IntentSummary | null {
|
|
const sanitized = sanitizeJsonControlChars(raw);
|
|
const candidates = [raw, sanitized, stripTrailingCommas(sanitized)];
|
|
for (const candidate of candidates) {
|
|
try {
|
|
const summary = normalizeIntentSummary(JSON.parse(candidate));
|
|
if (summary) return summary;
|
|
} catch {
|
|
// 下一个候选
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
const INTENT_READY_MARKER_RE = /\[INTENT_READY\]/i;
|
|
|
|
/**
|
|
* 把含 [INTENT_READY] 标记的气泡正文拆成前 / 摘要 / 后三段。
|
|
* 摘要 JSON 格式异常时整体保留在 `before`,用户仍能看到原文。
|
|
*
|
|
* 提取不再依赖严格的 ```json 围栏正则:先定位 [INTENT_READY](大小写不敏感),
|
|
* 再用括号配对抓出后面的第一个完整 JSON 对象,最后多级降级 parse。这样模型漏写
|
|
* 代码围栏、JSON 里有裸换行 / 尾随逗号、字段类型写偏等情况都能尽量恢复。
|
|
*/
|
|
export function splitIntentReadyBlock(text: string): {
|
|
before: string;
|
|
summary: IntentSummary | null;
|
|
after: string;
|
|
} {
|
|
if (!text) return { before: text, summary: null, after: "" };
|
|
const marker = INTENT_READY_MARKER_RE.exec(text);
|
|
if (!marker) return { before: text, summary: null, after: "" };
|
|
const block = extractBalancedJson(text, marker.index + marker[0].length);
|
|
if (!block) return { before: text, summary: null, after: "" };
|
|
const summary = parseIntentSummary(block.json);
|
|
if (!summary) return { before: text, summary: null, after: "" };
|
|
return {
|
|
before: text.slice(0, marker.index).trimEnd(),
|
|
summary,
|
|
// 丢掉 JSON 块之后残留的代码围栏 ``` 与模型多说的话(SOUL 要求 READY 后即停)。
|
|
after: text.slice(block.end).replace(/^\s*```+/, "").trimStart(),
|
|
};
|
|
}
|