feat(digital): 接入角色世界书与账号实验服务
- digital: 新增私有会话、DeepSeek流式生成、停止与分支、世界书和预设编排 - experiments: 新增账号稳定分组、人工指定、生命周期、预设快照及实验漏斗审计 - migrations/data: 初始化20位成年角色、4本世界书与3种叙事预设 - tests/docs: 补充11项核心回归、市场参考和部署说明
This commit is contained in:
@@ -0,0 +1,405 @@
|
||||
/** 流式对话编排,数据库租约防止并发双发,断线后保存已生成部分。 */
|
||||
import { env } from "../../config/env";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { FastifyReply } from "fastify";
|
||||
import type { PoolConnection } from "mysql2/promise";
|
||||
import { rows, write, json, transaction } from "./digital.repository";
|
||||
import { assemblePrompt, type PromptMessage } from "./digital.prompt";
|
||||
import {
|
||||
contentSchema,
|
||||
settingsSchema,
|
||||
type ContentInput,
|
||||
} from "./digital.schema";
|
||||
import { decide, trackUiEvent } from "./digital.experiments";
|
||||
import {
|
||||
badRequest,
|
||||
conflict,
|
||||
notFound,
|
||||
HttpError,
|
||||
} from "../../shared/http-error";
|
||||
/** 公开内容数据库行。 */
|
||||
export type ContentRow = {
|
||||
id: string;
|
||||
name: string;
|
||||
kind: ContentInput["kind"];
|
||||
status: string;
|
||||
body: ContentInput["body"];
|
||||
version: number;
|
||||
};
|
||||
/** 会话的所有操作都必须先按所属账号读取。 */
|
||||
export type Conversation = {
|
||||
id: string;
|
||||
account: string;
|
||||
character_id: string;
|
||||
title: string;
|
||||
settings: ReturnType<typeof settingsSchema.parse>;
|
||||
lease_id: string | null;
|
||||
lease_until: Date | null;
|
||||
};
|
||||
/** 只允许读取已发布的同类型内容;后台编辑使用独立接口。 */
|
||||
export async function published(id: string, kind: ContentInput["kind"]) {
|
||||
const [r] = await rows<ContentRow>(
|
||||
"SELECT * FROM dh_content WHERE id=? AND kind=? AND status='published'",
|
||||
[id, kind],
|
||||
);
|
||||
if (!r) throw notFound("内容尚未发布或已下架");
|
||||
return { ...r, body: contentSchema.shape.body.parse(json(r.body)) };
|
||||
}
|
||||
/** 用户会话隔离边界,禁止仅凭 conversation id 操作。 */
|
||||
export async function ownConversation(
|
||||
id: string,
|
||||
account: string,
|
||||
c?: PoolConnection,
|
||||
) {
|
||||
const [v] = await rows<Conversation>(
|
||||
`SELECT * FROM dh_conversations WHERE id=? AND account=?${c ? " FOR UPDATE" : ""}`,
|
||||
[id, account],
|
||||
c,
|
||||
);
|
||||
if (!v) throw notFound("会话不存在");
|
||||
return { ...v, settings: settingsSchema.parse(json(v.settings)) };
|
||||
}
|
||||
/** 公开卡片剔除提示词、示例和内部来源编排。 */
|
||||
export function publicContent(r: ContentRow) {
|
||||
const b = contentSchema.shape.body.parse(json(r.body));
|
||||
return {
|
||||
id: r.id,
|
||||
name: r.name,
|
||||
kind: r.kind,
|
||||
version: r.version,
|
||||
description: b.description,
|
||||
greeting: b.greeting,
|
||||
alternateGreetings: b.alternateGreetings,
|
||||
gender: b.gender,
|
||||
age: b.age,
|
||||
cover: b.cover,
|
||||
tags: b.tags,
|
||||
source: b.source,
|
||||
entriesCount: b.entries.length,
|
||||
};
|
||||
}
|
||||
/** 会话第一条问候也写入存储,刷新和分支后保持一致。 */
|
||||
export async function createConversation(
|
||||
account: string,
|
||||
cardId: string,
|
||||
greetingIndex: number,
|
||||
uiDecisionId?: string,
|
||||
) {
|
||||
const card = await published(cardId, "character");
|
||||
const [profile] = await rows<{ body: unknown }>(
|
||||
"SELECT body FROM dh_profiles WHERE account=?",
|
||||
[account],
|
||||
);
|
||||
const id = randomUUID(),
|
||||
settings = settingsSchema.parse(profile ? json(profile.body) : {});
|
||||
const greeting =
|
||||
[card.body.greeting, ...card.body.alternateGreetings][greetingIndex] ??
|
||||
card.body.greeting;
|
||||
await transaction(async (c) => {
|
||||
await write(
|
||||
"INSERT INTO dh_conversations(id,account,character_id,title,settings) VALUES (?,?,?,?,?)",
|
||||
[id, account, cardId, card.name, JSON.stringify(settings)],
|
||||
c,
|
||||
);
|
||||
if (greeting)
|
||||
await write(
|
||||
"INSERT INTO dh_messages(id,conversation_id,role,content) VALUES (?,?,'assistant',?)",
|
||||
[
|
||||
randomUUID(),
|
||||
id,
|
||||
greeting
|
||||
.replaceAll("{{char}}", card.name)
|
||||
.replaceAll("{{user}}", settings.userName),
|
||||
],
|
||||
c,
|
||||
);
|
||||
});
|
||||
await trackUiEvent(account, uiDecisionId, "conversation_started", id, id);
|
||||
return { id };
|
||||
}
|
||||
const basePreset = contentSchema.shape.body.parse({
|
||||
cover: "",
|
||||
systemPrompt:
|
||||
"每次回应以 2–4 段为主。避免重复上轮句式,给用户自然的接话空间。",
|
||||
});
|
||||
const running = new Map<string, AbortController>();
|
||||
let inFlight = 0;
|
||||
/** 显式停止只对会话拥有者开放;单业务实例中即时中断上游。 */
|
||||
export async function stopConversation(id: string, account: string) {
|
||||
await ownConversation(id, account);
|
||||
running.get(id)?.abort();
|
||||
}
|
||||
/** 有界 SSE 解码器支持网络帧分片,拒绝无限长上游事件。 */
|
||||
export async function* completionDeltas(body: ReadableStream<Uint8Array>) {
|
||||
const reader = body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = "";
|
||||
try {
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read();
|
||||
buffer += done
|
||||
? decoder.decode()
|
||||
: decoder.decode(value, { stream: true });
|
||||
if (buffer.length > 1048576) throw new Error("provider frame too large");
|
||||
let end: number;
|
||||
while ((end = buffer.indexOf("\n")) >= 0) {
|
||||
const line = buffer.slice(0, end).trim();
|
||||
buffer = buffer.slice(end + 1);
|
||||
if (!line.startsWith("data:")) continue;
|
||||
const data = line.slice(5).trim();
|
||||
if (data === "[DONE]") return;
|
||||
if (data) {
|
||||
const event = JSON.parse(data);
|
||||
if (event.error) throw new Error("provider stream error");
|
||||
const delta = event.choices?.[0]?.delta?.content;
|
||||
if (typeof delta === "string" && delta.length > 0) yield delta;
|
||||
}
|
||||
}
|
||||
if (done) throw new Error("provider ended before completion");
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
/** 每轮限制总时长、并发和输出;异常不泄露 DeepSeek 原始响应。 */
|
||||
export async function streamChat(
|
||||
account: string,
|
||||
id: string,
|
||||
input: {
|
||||
requestId: string;
|
||||
content: string;
|
||||
mode: "send" | "regenerate";
|
||||
uiDecisionId?: string;
|
||||
},
|
||||
reply: FastifyReply,
|
||||
) {
|
||||
if (!env.DEEPSEEK_API_KEY)
|
||||
throw new HttpError(503, "MODEL_UNAVAILABLE", "模型暂未配置,请联系管理员");
|
||||
const conversation = await ownConversation(id, account);
|
||||
const card = await published(conversation.character_id, "character");
|
||||
const decision = await decide(account, "chat");
|
||||
const presetId =
|
||||
decision.presetId ?? conversation.settings.presetId ?? card.body.presetId;
|
||||
const preset =
|
||||
decision.presetSnapshot ??
|
||||
(presetId ? (await published(presetId, "preset")).body : basePreset);
|
||||
const bookIds = [
|
||||
...new Set([...card.body.bookIds, ...conversation.settings.bookIds]),
|
||||
];
|
||||
const books = await Promise.all(
|
||||
bookIds.map((book) => published(book, "worldbook")),
|
||||
);
|
||||
if (inFlight >= 4)
|
||||
throw new HttpError(429, "MODEL_BUSY", "当前对话较多,请稍后再试");
|
||||
const lease = randomUUID();
|
||||
const assistantId = randomUUID();
|
||||
const controller = new AbortController();
|
||||
inFlight++;
|
||||
try {
|
||||
await transaction(async (c) => {
|
||||
// 条件写入获取租约;超时租约允许进程异常后恢复。租约长于上游硬超时。
|
||||
const result = await write(
|
||||
"UPDATE dh_conversations SET lease_id=?,lease_until=DATE_ADD(NOW(3),INTERVAL 150 SECOND) WHERE id=? AND account=? AND (lease_until IS NULL OR lease_until<NOW(3))",
|
||||
[lease, id, account],
|
||||
c,
|
||||
);
|
||||
if (!result.affectedRows)
|
||||
throw conflict("上一条回复仍在生成,请先停止或稍后重试");
|
||||
await write("UPDATE dh_messages SET status='stopped' WHERE conversation_id=? AND status='generating'",[id],c);
|
||||
const duplicate = await rows(
|
||||
"SELECT id FROM dh_messages WHERE conversation_id=? AND request_id=? LIMIT 1",
|
||||
[id, input.requestId],
|
||||
c,
|
||||
);
|
||||
if (duplicate.length) throw conflict("此请求已提交,请刷新会话查看结果");
|
||||
const count = await rows<{ n: number }>(
|
||||
"SELECT COUNT(*) n FROM dh_messages WHERE conversation_id IN (SELECT id FROM dh_conversations WHERE account=?) AND role='assistant' AND request_id IS NOT NULL AND created_at>DATE_SUB(NOW(3),INTERVAL 1 MINUTE)",
|
||||
[account],
|
||||
c,
|
||||
);
|
||||
if (Number(count[0].n) >= 12)
|
||||
throw new HttpError(429, "RATE_LIMIT", "发送太快,请稍后再试");
|
||||
if (input.mode === "send") {
|
||||
if (!input.content.trim()) throw badRequest("请输入消息");
|
||||
await write(
|
||||
"INSERT INTO dh_messages(id,conversation_id,role,content,request_id) VALUES (?,?,'user',?,?)",
|
||||
[randomUUID(), id, input.content, input.requestId],
|
||||
c,
|
||||
);
|
||||
} else {
|
||||
const [last] = await rows<{ role: string }>(
|
||||
"SELECT role FROM dh_messages WHERE conversation_id=? ORDER BY sequence_id DESC LIMIT 1",
|
||||
[id],
|
||||
c,
|
||||
);
|
||||
if (!last) throw badRequest("还没有可重新生成的对话");
|
||||
const users = await rows(
|
||||
"SELECT id FROM dh_messages WHERE conversation_id=? AND role='user' LIMIT 1",
|
||||
[id],
|
||||
c,
|
||||
);
|
||||
if (!users.length) throw badRequest("请先发送一条消息");
|
||||
const [anchor] = await rows<{ sequence_id: number }>(
|
||||
"SELECT sequence_id FROM dh_messages WHERE conversation_id=? AND role='user' ORDER BY sequence_id DESC LIMIT 1",
|
||||
[id],
|
||||
c,
|
||||
);
|
||||
await write(
|
||||
"UPDATE dh_messages SET status='superseded' WHERE conversation_id=? AND role='assistant' AND sequence_id>? AND status IN ('complete','stopped','failed')",
|
||||
[id, anchor.sequence_id],
|
||||
c,
|
||||
);
|
||||
}
|
||||
await write(
|
||||
"INSERT INTO dh_messages(id,conversation_id,role,content,status,request_id) VALUES (?,?,'assistant','','generating',?)",
|
||||
[assistantId, id, input.requestId],
|
||||
c,
|
||||
);
|
||||
if (input.mode === "send")
|
||||
await trackUiEvent(
|
||||
account,
|
||||
input.uiDecisionId,
|
||||
"message_sent",
|
||||
id,
|
||||
input.requestId,
|
||||
c,
|
||||
);
|
||||
});
|
||||
} catch (error) {
|
||||
inFlight--;
|
||||
throw error;
|
||||
}
|
||||
running.set(id, controller);
|
||||
let output = "",
|
||||
status: "complete" | "stopped" | "failed" = "complete",
|
||||
fail = false;
|
||||
const timeout = setTimeout(
|
||||
() => controller.abort(new Error("timeout")),
|
||||
120000,
|
||||
);
|
||||
const onClose = () => {
|
||||
if (!reply.raw.writableEnded) controller.abort();
|
||||
};
|
||||
reply.hijack();
|
||||
reply.raw.writeHead(200, {
|
||||
"Content-Type": "text/event-stream; charset=utf-8",
|
||||
"Cache-Control": "no-cache, no-transform",
|
||||
"X-Accel-Buffering": "no",
|
||||
});
|
||||
reply.raw.on("close", onClose);
|
||||
const send = (event: string, data: unknown) => {
|
||||
if (!reply.raw.destroyed)
|
||||
reply.raw.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
||||
};
|
||||
const heartbeat = setInterval(() => {
|
||||
if (!reply.raw.destroyed) reply.raw.write(": keepalive\n\n");
|
||||
}, 10000);
|
||||
send("start", { messageId: assistantId, requestId: input.requestId });
|
||||
try {
|
||||
// 重新生成只取最近用户消息及其以前的历史,不把旧答案喂回模型。
|
||||
const history = await rows<{
|
||||
role: "user" | "assistant";
|
||||
content: string;
|
||||
pinned: number;
|
||||
sequence_id: number;
|
||||
}>(
|
||||
"SELECT role,content,pinned,sequence_id FROM dh_messages WHERE conversation_id=? AND id<>? AND status IN ('complete','stopped') ORDER BY sequence_id DESC LIMIT 60",
|
||||
[id, assistantId],
|
||||
);
|
||||
history.reverse();
|
||||
if (input.mode === "regenerate") {
|
||||
while (history.length && history.at(-1)?.role !== "user") history.pop();
|
||||
}
|
||||
const pinned = await rows<{ content: string }>(
|
||||
"SELECT content FROM dh_messages WHERE conversation_id=? AND pinned=TRUE AND content<>'' ORDER BY sequence_id DESC LIMIT 20",
|
||||
[id],
|
||||
);
|
||||
const prompt = assemblePrompt(
|
||||
{ ...card.body, name: card.name },
|
||||
preset,
|
||||
books.flatMap((b) => b.body.entries),
|
||||
history,
|
||||
conversation.settings,
|
||||
pinned.map((m) => m.content),
|
||||
);
|
||||
const upstream = await fetch("https://api.deepseek.com/chat/completions", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${env.DEEPSEEK_API_KEY}`,
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model: "deepseek-flash",
|
||||
messages: prompt.messages,
|
||||
stream: true,
|
||||
thinking: { type: "disabled" },
|
||||
temperature: preset.temperature,
|
||||
max_tokens: preset.maxTokens,
|
||||
}),
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (decision.decisionId)
|
||||
await write("UPDATE dh_decisions SET exposed_at=NOW(3) WHERE id=?", [
|
||||
decision.decisionId,
|
||||
]);
|
||||
if (!upstream.ok || !upstream.body) {
|
||||
await upstream.body?.cancel();
|
||||
throw new Error("provider unavailable");
|
||||
}
|
||||
for await (const delta of completionDeltas(upstream.body)) {
|
||||
output += delta;
|
||||
if (output.length > 20000) {
|
||||
controller.abort();
|
||||
break;
|
||||
}
|
||||
send("delta", { text: delta });
|
||||
}
|
||||
if (!output.trim()) throw new Error("empty response");
|
||||
} catch {
|
||||
status = controller.signal.aborted ? "stopped" : "failed";
|
||||
fail = true;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
clearInterval(heartbeat);
|
||||
inFlight--;
|
||||
running.delete(id);
|
||||
reply.raw.off("close", onClose);
|
||||
try {
|
||||
await transaction(async (c) => {
|
||||
await write(
|
||||
"UPDATE dh_messages SET content=?,status=? WHERE id=?",
|
||||
[output, status, assistantId],
|
||||
c,
|
||||
);
|
||||
await write(
|
||||
"UPDATE dh_conversations SET lease_id=NULL,lease_until=NULL,updated_at=NOW(3) WHERE id=? AND lease_id=?",
|
||||
[id, lease],
|
||||
c,
|
||||
);
|
||||
});
|
||||
await trackUiEvent(
|
||||
account,
|
||||
input.uiDecisionId,
|
||||
status === "complete"
|
||||
? "reply_complete"
|
||||
: status === "stopped"
|
||||
? "reply_stopped"
|
||||
: "reply_failed",
|
||||
id,
|
||||
input.requestId,
|
||||
);
|
||||
if (fail)
|
||||
send("notice", {
|
||||
status,
|
||||
message:
|
||||
status === "stopped"
|
||||
? "已停止,已保存生成内容"
|
||||
: "生成暂时失败,可重新生成",
|
||||
});
|
||||
send("done", { messageId: assistantId, status });
|
||||
} catch {
|
||||
send("error", { message: "保存失败,请刷新确认会话状态" });
|
||||
}
|
||||
reply.raw.end();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user