51ec4598df
- digital.profile.ts: 未保存偏好时默认开启,原子合并 JSON 保留其他资料 - digital.controller.ts、digital.users.ts: 接入本人和管理员偏好读写、事务及审计 - digital.chat.ts、digital.prompt.ts、digital.suggestions.ts: 各生成入口读取服务端账号偏好,保留游客鉴权 - tests/digital-*.test.ts: 覆盖默认值、关闭保留、旧客户端兼容与越权拦截 - README.md: 同步模块职责和发布要求
474 lines
16 KiB
TypeScript
474 lines
16 KiB
TypeScript
/** 流式对话编排。租约防止并发双发;下架的预设或世界书跳过,不中断本轮。 */
|
|
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 { getDigitalProfile } from "./digital.profile";
|
|
import {
|
|
assemblePrompt,
|
|
continuationMessages,
|
|
type PromptMessage,
|
|
} from "./digital.prompt";
|
|
import {
|
|
contentSchema,
|
|
settingsSchema,
|
|
type ContentInput,
|
|
} from "./digital.schema";
|
|
import {
|
|
activeExperiment,
|
|
experiments,
|
|
resolveExperiment,
|
|
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 publishedOptional(
|
|
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) return null;
|
|
return { ...r, body: contentSchema.shape.body.parse(json(r.body)) };
|
|
}
|
|
/** 只允许读取已发布的同类型内容;后台编辑使用独立接口。 */
|
|
export async function published(id: string, kind: ContentInput["kind"]) {
|
|
const found = await publishedOptional(id, kind);
|
|
if (!found) throw notFound("内容尚未发布或已下架");
|
|
return found;
|
|
}
|
|
/** 会话指定预设优先,其次角色默认预设,都不可用时用内置写法。 */
|
|
export function choosePresetBody(
|
|
selected: ContentInput["body"] | null,
|
|
characterDefault: ContentInput["body"] | null,
|
|
base: ContentInput["body"],
|
|
) {
|
|
return selected ?? characterDefault ?? base;
|
|
}
|
|
/** 用户会话隔离边界,禁止仅凭 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 async function conversationStylePolicy(account: string, id: string) {
|
|
await ownConversation(id, account);
|
|
const plan = activeExperiment(await experiments(), "chat");
|
|
const decision = plan ? await resolveExperiment(plan, account, true) : null;
|
|
return {
|
|
managed: !!(decision && (decision.presetSnapshot || decision.presetId)),
|
|
};
|
|
}
|
|
/** 公开卡片剔除提示词、示例和内部来源编排。 */
|
|
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" | "continue";
|
|
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", { value: "" });
|
|
const presetId =
|
|
decision.presetId ?? conversation.settings.presetId ?? card.body.presetId;
|
|
const selectedPreset = decision.presetSnapshot
|
|
? decision.presetSnapshot
|
|
: presetId
|
|
? ((await publishedOptional(presetId, "preset"))?.body ?? null)
|
|
: null;
|
|
const characterPreset =
|
|
!selectedPreset && card.body.presetId && card.body.presetId !== presetId
|
|
? ((await publishedOptional(card.body.presetId, "preset"))?.body ?? null)
|
|
: null;
|
|
const preset = choosePresetBody(selectedPreset, characterPreset, basePreset);
|
|
const bookIds = [
|
|
...new Set([...card.body.bookIds, ...conversation.settings.bookIds]),
|
|
];
|
|
const books = (
|
|
await Promise.all(
|
|
bookIds.map((book) => publishedOptional(book, "worldbook")),
|
|
)
|
|
).filter((book) => book !== null);
|
|
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 if (input.mode === "regenerate") {
|
|
const [last] = await rows<{ role: string; sequence_id: number }>(
|
|
"SELECT role,sequence_id 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("请先发送一条消息");
|
|
// 只替换最近一条回答;角色连续说话时,不抹掉此前已经说过的段落。
|
|
if (last.role === "assistant")
|
|
await write(
|
|
"UPDATE dh_messages SET status='superseded' WHERE conversation_id=? AND role='assistant' AND sequence_id=? AND status IN ('complete','stopped','failed')",
|
|
[id, last.sequence_id],
|
|
c,
|
|
);
|
|
} else {
|
|
const [last] = await rows<{
|
|
role: string;
|
|
content: string;
|
|
status: string;
|
|
}>(
|
|
// 空的中止/失败尝试没有新台词,继续时沿用上一段已说出的内容;不能跳过真实用户消息。
|
|
"SELECT role,content,status FROM dh_messages WHERE conversation_id=? AND NOT (role='assistant' AND status IN ('stopped','failed') AND TRIM(content)='') ORDER BY sequence_id DESC LIMIT 1",
|
|
[id],
|
|
c,
|
|
);
|
|
if (
|
|
!last ||
|
|
last.role !== "assistant" ||
|
|
!["complete", "stopped"].includes(last.status) ||
|
|
!last.content.trim()
|
|
)
|
|
throw badRequest("角色还没有可继续的内容,请先开始一段对话");
|
|
}
|
|
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();
|
|
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),
|
|
(await getDigitalProfile(account)).nsfwEnabled,
|
|
);
|
|
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",
|
|
// 控制指令仅用于模型请求;数据库中“继续”只新增 assistant 消息。
|
|
messages:
|
|
input.mode === "continue" ||
|
|
(input.mode === "regenerate" && history.at(-1)?.role === "assistant")
|
|
? continuationMessages(prompt.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();
|
|
}
|
|
}
|