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: 同步模块职责和发布要求
586 lines
21 KiB
TypeScript
586 lines
21 KiB
TypeScript
/** 数字人 API:前台私有会话与后台内容/实验严格分权。 */
|
|
import {
|
|
experimentTypes,
|
|
saveExperimentType,
|
|
typeInputSchema,
|
|
confirmTypeIntegration,
|
|
} from "./digital.experiment-types";
|
|
import {
|
|
experimentUsers,
|
|
assertActiveExperimentAccount,
|
|
} from "./digital.experiment-users";
|
|
import { suggestReplies } from "./digital.suggestions";
|
|
import { env } from "../../config/env";
|
|
import { scenes, saveScene, sceneSchema } from "./digital.scenes";
|
|
import { randomUUID } from "node:crypto";
|
|
import type { FastifyInstance, FastifyRequest } from "fastify";
|
|
import { z } from "zod";
|
|
import { authGuard } from "../auth/auth.guard";
|
|
import { authService } from "../auth/auth.service";
|
|
import { ok } from "../../shared/response";
|
|
import {
|
|
badRequest,
|
|
conflict,
|
|
forbidden,
|
|
notFound,
|
|
unauthorized,
|
|
} from "../../shared/http-error";
|
|
import { rows, write, json, audit, transaction } from "./digital.repository";
|
|
import { getDigitalProfile, mergeDigitalProfile } from "./digital.profile";
|
|
import {
|
|
contentSchema,
|
|
experimentSchema,
|
|
idSchema,
|
|
groupKeySchema,
|
|
settingsSchema,
|
|
} from "./digital.schema";
|
|
import {
|
|
decodeExperimentConfig,
|
|
hasExperimentGroup,
|
|
} from "./digital.experiment-groups";
|
|
import {
|
|
experiments,
|
|
saveExperiment,
|
|
transition,
|
|
resolveExperiment,
|
|
decide,
|
|
} from "./digital.experiments";
|
|
import {
|
|
createConversation,
|
|
conversationStylePolicy,
|
|
ownConversation,
|
|
publicContent,
|
|
streamChat,
|
|
stopConversation,
|
|
type ContentRow,
|
|
} from "./digital.chat";
|
|
const params = z.object({ id: idSchema });
|
|
const accountSchema = z.string().regex(/^user:[0-9]+$/);
|
|
const adminGuard = async (r: FastifyRequest) => {
|
|
await authGuard(r);
|
|
const u = await authService.getCurrentUser(r.user);
|
|
if (u.accountType !== "SUPER_ADMIN") throw forbidden("数字人运营仅限管理员");
|
|
};
|
|
const userGuard = async (r: FastifyRequest) => {
|
|
await authGuard(r);
|
|
// 旧管理员/员工前台 Cookie 失效时走正常退出流程,不能继续读取迁移后的聊天。
|
|
if (r.user.accountType !== "DIGITAL_USER" || r.user.scene !== "DIGITAL_APP")
|
|
throw unauthorized("请使用独立 C 端账号重新登录");
|
|
await authService.getCurrentUser(r.user);
|
|
};
|
|
/** 独立 C 端令牌是唯一用户身份来源,忽略请求体中的用户标识。 */
|
|
export async function digitalRoutes(app: FastifyInstance) {
|
|
app.register(
|
|
async (front) => {
|
|
front.addHook("preHandler", userGuard);
|
|
front.get("/decisions/:key", async (r) => {
|
|
const { key } = z.object({ key: idSchema }).parse(r.params);
|
|
const d = await decide(r.user.sub, key);
|
|
// 通用消费者不接收服务端预设正文或账号创建信息。
|
|
return ok({
|
|
variant: d.variant,
|
|
reason: d.reason,
|
|
experimentId: d.experimentId,
|
|
decisionId: d.decisionId,
|
|
value: d.value,
|
|
fallbackValue: d.fallbackValue,
|
|
typeKey: d.typeKey,
|
|
typeRevision: d.typeRevision,
|
|
expiresAt: d.expiresAt,
|
|
fallbackVariant: d.fallbackVariant,
|
|
});
|
|
});
|
|
front.get("/bootstrap", async (r) => {
|
|
const [catalog, profile, decision] = await Promise.all([
|
|
rows<ContentRow>(
|
|
"SELECT * FROM dh_content WHERE status='published' ORDER BY created_at ASC LIMIT 500",
|
|
),
|
|
getDigitalProfile(r.user.sub),
|
|
decide(r.user.sub, env.DIGITAL_UI_TYPE_KEY, { value: "old" }),
|
|
]);
|
|
const publicDecision = {
|
|
typeKey: decision.typeKey,
|
|
reason: decision.reason,
|
|
variant: decision.variant,
|
|
value: decision.value,
|
|
fallbackValue: decision.fallbackValue,
|
|
decisionId: decision.decisionId,
|
|
experimentId: decision.experimentId,
|
|
expiresAt: decision.expiresAt,
|
|
fallbackVariant: decision.fallbackVariant,
|
|
};
|
|
return ok({
|
|
catalog: catalog.map(publicContent),
|
|
profile,
|
|
decision: publicDecision,
|
|
serverNow: Date.now(),
|
|
});
|
|
});
|
|
front.put("/profile", async (r) => {
|
|
const body = z
|
|
.object({
|
|
favorites: z.array(idSchema).max(200),
|
|
persona: z.string().max(2000),
|
|
userName: z.string().min(1).max(60),
|
|
nsfwEnabled: z.boolean().optional(),
|
|
})
|
|
.parse(r.body);
|
|
await mergeDigitalProfile(r.user.sub, body);
|
|
return ok(await getDigitalProfile(r.user.sub));
|
|
});
|
|
front.post("/exposure", async (r) => {
|
|
const { decisionId } = z.object({ decisionId: z.uuid() }).parse(r.body);
|
|
await write(
|
|
"UPDATE dh_decisions d JOIN dh_experiments e ON e.id=d.experiment_id SET d.exposed_at=COALESCE(d.exposed_at,NOW(3)) WHERE d.id=? AND d.account=? AND d.created_at>DATE_SUB(NOW(3),INTERVAL 60 SECOND) AND d.revision=e.revision AND e.state='running' AND d.reason IN ('allocated','sticky','override')",
|
|
[decisionId, r.user.sub],
|
|
);
|
|
return ok({ received: true });
|
|
});
|
|
front.get("/conversations", async (r) =>
|
|
ok(
|
|
await rows(
|
|
"SELECT id,character_id AS characterId,title,updated_at AS updatedAt FROM dh_conversations WHERE account=? ORDER BY updated_at DESC LIMIT 100",
|
|
[r.user.sub],
|
|
),
|
|
),
|
|
);
|
|
front.post("/conversations", async (r) => {
|
|
const b = z
|
|
.object({
|
|
characterId: idSchema,
|
|
greetingIndex: z.number().int().min(0).max(8).default(0),
|
|
uiDecisionId: z.uuid().optional(),
|
|
})
|
|
.parse(r.body);
|
|
return ok(
|
|
await createConversation(
|
|
r.user.sub,
|
|
b.characterId,
|
|
b.greetingIndex,
|
|
b.uiDecisionId,
|
|
),
|
|
);
|
|
});
|
|
front.get("/conversations/:id/style-policy", async (r) => {
|
|
const { id } = params.parse(r.params);
|
|
return ok(await conversationStylePolicy(r.user.sub, id));
|
|
});
|
|
front.get("/conversations/:id", async (r) => {
|
|
const { id } = params.parse(r.params);
|
|
const c = await ownConversation(id, r.user.sub);
|
|
const messages = await rows<{
|
|
id: string;
|
|
role: string;
|
|
content: string;
|
|
status: string;
|
|
pinned: number;
|
|
sequenceId: number;
|
|
createdAt: Date;
|
|
}>(
|
|
"SELECT id,role,content,status,pinned,sequence_id AS sequenceId,created_at AS createdAt FROM dh_messages WHERE conversation_id=? ORDER BY sequence_id DESC LIMIT 300",
|
|
[id],
|
|
);
|
|
// 生成态租约过期后显示为中断,避免进程重启留下永久打字状态。
|
|
const busy =
|
|
!!c.lease_until && new Date(c.lease_until).getTime() > Date.now();
|
|
return ok({
|
|
id: c.id,
|
|
characterId: c.character_id,
|
|
title: c.title,
|
|
settings: c.settings,
|
|
busy,
|
|
messages: messages
|
|
.reverse()
|
|
.map((m) =>
|
|
!busy && m.status === "generating"
|
|
? { ...m, status: "stopped" }
|
|
: m,
|
|
),
|
|
});
|
|
});
|
|
front.patch("/conversations/:id", async (r) => {
|
|
const { id } = params.parse(r.params);
|
|
await ownConversation(id, r.user.sub);
|
|
const b = z
|
|
.object({
|
|
title: z.string().min(1).max(120).optional(),
|
|
settings: settingsSchema.optional(),
|
|
})
|
|
.parse(r.body);
|
|
if (b.title)
|
|
await write(
|
|
"UPDATE dh_conversations SET title=? WHERE id=? AND account=?",
|
|
[b.title, id, r.user.sub],
|
|
);
|
|
if (b.settings)
|
|
await write(
|
|
"UPDATE dh_conversations SET settings=? WHERE id=? AND account=?",
|
|
[JSON.stringify(b.settings), id, r.user.sub],
|
|
);
|
|
return ok({ saved: true });
|
|
});
|
|
front.delete("/conversations/:id", async (r) => {
|
|
const { id } = params.parse(r.params);
|
|
await transaction(async (c) => {
|
|
const conversation = await ownConversation(id, r.user.sub, c);
|
|
if (
|
|
conversation.lease_until &&
|
|
new Date(conversation.lease_until).getTime() > Date.now()
|
|
)
|
|
throw conflict("请先停止生成");
|
|
await write(
|
|
"DELETE FROM dh_messages WHERE conversation_id=?",
|
|
[id],
|
|
c,
|
|
);
|
|
await write(
|
|
"DELETE FROM dh_conversations WHERE id=? AND account=?",
|
|
[id, r.user.sub],
|
|
c,
|
|
);
|
|
});
|
|
return ok({ deleted: true });
|
|
});
|
|
front.post("/conversations/:id/branch", async (r) => {
|
|
const { id } = params.parse(r.params),
|
|
b = z.object({ messageId: z.uuid() }).parse(r.body);
|
|
const source = await ownConversation(id, r.user.sub);
|
|
const fork = randomUUID();
|
|
await transaction(async (c) => {
|
|
const [anchor] = await rows<{ sequence_id: number; status: string }>(
|
|
"SELECT sequence_id,status FROM dh_messages WHERE id=? AND conversation_id=?",
|
|
[b.messageId, id],
|
|
c,
|
|
);
|
|
if (!anchor || anchor.status === "generating")
|
|
throw badRequest("请选择已结束的消息");
|
|
await write(
|
|
"INSERT INTO dh_conversations(id,account,character_id,title,settings) VALUES (?,?,?,?,?)",
|
|
[
|
|
fork,
|
|
r.user.sub,
|
|
source.character_id,
|
|
`${source.title.slice(0, 100)} · 分支`,
|
|
JSON.stringify(source.settings),
|
|
],
|
|
c,
|
|
);
|
|
const copied = await rows<{
|
|
role: string;
|
|
content: string;
|
|
status: string;
|
|
pinned: number;
|
|
}>(
|
|
"SELECT role,content,status,pinned FROM dh_messages WHERE conversation_id=? AND sequence_id<=? ORDER BY sequence_id",
|
|
[id, anchor.sequence_id],
|
|
c,
|
|
);
|
|
for (const m of copied)
|
|
await write(
|
|
"INSERT INTO dh_messages(id,conversation_id,role,content,status,pinned) VALUES (?,?,?,?,?,?)",
|
|
[
|
|
randomUUID(),
|
|
fork,
|
|
m.role,
|
|
m.content,
|
|
m.status === "complete" ? "complete" : "stopped",
|
|
m.pinned,
|
|
],
|
|
c,
|
|
);
|
|
});
|
|
return ok({ id: fork });
|
|
});
|
|
front.patch("/conversations/:id/messages/:messageId", async (r) => {
|
|
const { id, messageId } = z
|
|
.object({ id: idSchema, messageId: z.uuid() })
|
|
.parse(r.params);
|
|
const c = await ownConversation(id, r.user.sub);
|
|
if (c.lease_until && new Date(c.lease_until).getTime() > Date.now())
|
|
throw conflict("请先停止生成");
|
|
const { pinned } = z.object({ pinned: z.boolean() }).parse(r.body);
|
|
const result = await write(
|
|
"UPDATE dh_messages SET pinned=? WHERE id=? AND conversation_id=?",
|
|
[pinned, messageId, id],
|
|
);
|
|
if (!result.affectedRows) throw notFound("消息不存在");
|
|
return ok({ pinned });
|
|
});
|
|
front.post("/conversations/:id/stop", async (r) => {
|
|
const { id } = params.parse(r.params);
|
|
await stopConversation(id, r.user.sub);
|
|
return ok({ stopped: true });
|
|
});
|
|
front.post("/conversations/:id/suggestions", async (r, reply) => {
|
|
const { id } = params.parse(r.params),
|
|
{ draft } = z
|
|
.object({ draft: z.string().max(1000).default("") })
|
|
.parse(r.body ?? {});
|
|
const controller = new AbortController(),
|
|
disconnect = () => {
|
|
if (!reply.raw.writableEnded) controller.abort();
|
|
};
|
|
reply.raw.on("close", disconnect);
|
|
try {
|
|
return ok(
|
|
await suggestReplies(r.user.sub, id, draft, controller.signal),
|
|
);
|
|
} finally {
|
|
reply.raw.off("close", disconnect);
|
|
}
|
|
});
|
|
front.post("/conversations/:id/stream", async (r, reply) => {
|
|
const { id } = params.parse(r.params);
|
|
const b = z
|
|
.object({
|
|
requestId: z.uuid(),
|
|
content: z.string().max(4000).default(""),
|
|
mode: z.enum(["send", "regenerate", "continue"]).default("send"),
|
|
uiDecisionId: z.uuid().optional(),
|
|
})
|
|
.parse(r.body);
|
|
await streamChat(r.user.sub, id, b, reply);
|
|
});
|
|
},
|
|
{ prefix: "/digital" },
|
|
);
|
|
app.register(
|
|
async (admin) => {
|
|
admin.addHook("preHandler", adminGuard);
|
|
admin.get("/overview", async () =>
|
|
ok({
|
|
content: await rows(
|
|
"SELECT kind,status,COUNT(*) count FROM dh_content GROUP BY kind,status",
|
|
),
|
|
conversations: await rows(
|
|
"SELECT COUNT(*) count FROM dh_conversations",
|
|
),
|
|
messages: await rows(
|
|
"SELECT role,status,COUNT(*) count FROM dh_messages GROUP BY role,status",
|
|
),
|
|
modelConfigured: !!env.DEEPSEEK_API_KEY,
|
|
}),
|
|
);
|
|
admin.get("/content", async () =>
|
|
ok(
|
|
(
|
|
await rows<ContentRow>(
|
|
"SELECT * FROM dh_content ORDER BY updated_at DESC LIMIT 500",
|
|
)
|
|
).map((v) => ({ ...v, body: json(v.body) })),
|
|
),
|
|
);
|
|
admin.put("/content/:id", async (r) => {
|
|
const { id } = params.parse(r.params),
|
|
b = contentSchema.parse(r.body);
|
|
const expected = z
|
|
.object({ version: z.number().int().positive().optional() })
|
|
.parse(r.body).version;
|
|
await transaction(async (c) => {
|
|
const [old] = await rows<ContentRow>(
|
|
"SELECT * FROM dh_content WHERE id=? FOR UPDATE",
|
|
[id],
|
|
c,
|
|
);
|
|
if (old) {
|
|
if (old.version !== expected)
|
|
throw conflict("内容已被修改,请刷新");
|
|
if (old.kind !== b.kind) throw badRequest("不能变更内容类型");
|
|
await write(
|
|
"UPDATE dh_content SET name=?,status=?,body=?,version=version+1 WHERE id=?",
|
|
[b.name, b.status, JSON.stringify(b.body), id],
|
|
c,
|
|
);
|
|
} else
|
|
await write(
|
|
"INSERT INTO dh_content(id,kind,name,status,body) VALUES (?,?,?,?,?)",
|
|
[id, b.kind, b.name, b.status, JSON.stringify(b.body)],
|
|
c,
|
|
);
|
|
await audit(
|
|
r.user.sub,
|
|
"content.save",
|
|
id,
|
|
{
|
|
name: b.name,
|
|
kind: b.kind,
|
|
status: b.status,
|
|
version: (old?.version ?? 0) + 1,
|
|
},
|
|
c,
|
|
);
|
|
});
|
|
return ok({ saved: true });
|
|
});
|
|
admin.get("/experiment-types", async () => ok(await experimentTypes()));
|
|
admin.put("/experiment-types/:id", async (r) => {
|
|
const { id } = params.parse(r.params);
|
|
await saveExperimentType(r.user.sub, id, typeInputSchema.parse(r.body));
|
|
return ok({ saved: true });
|
|
});
|
|
admin.post("/experiment-types/:id/integration", async (r) => {
|
|
const { id } = params.parse(r.params);
|
|
const input = z
|
|
.object({
|
|
revision: z.number().int().positive(),
|
|
contractRevision: z.number().int().positive(),
|
|
verified: z.boolean(),
|
|
notes: z.string().max(2000),
|
|
})
|
|
.parse(r.body);
|
|
await confirmTypeIntegration(r.user.sub, id, input);
|
|
return ok({ saved: true });
|
|
});
|
|
admin.get("/experiment-users", async (r) => {
|
|
const input = z
|
|
.object({
|
|
q: z.string().max(100).default(""),
|
|
page: z.coerce.number().int().min(1).default(1),
|
|
size: z.coerce.number().int().min(1).max(50).default(20),
|
|
experiment: idSchema.optional(),
|
|
})
|
|
.parse(r.query);
|
|
return ok(await experimentUsers(input));
|
|
});
|
|
admin.get("/scenes", async () => ok(await scenes()));
|
|
admin.put("/scenes/:id", async (r) => {
|
|
const { id } = params.parse(r.params);
|
|
await saveScene(r.user.sub, id, sceneSchema.parse(r.body));
|
|
return ok({ saved: true });
|
|
});
|
|
admin.get("/experiments", async () => ok(await experiments()));
|
|
admin.put("/experiments/:id", async (r) => {
|
|
const { id } = params.parse(r.params);
|
|
await saveExperiment(
|
|
r.user.sub,
|
|
id,
|
|
experimentSchema.parse(r.body),
|
|
z.object({ revision: z.number().int().optional() }).parse(r.body)
|
|
.revision,
|
|
);
|
|
return ok({ saved: true });
|
|
});
|
|
admin.post("/experiments/:id/transition", async (r) => {
|
|
const { id } = params.parse(r.params),
|
|
b = z
|
|
.object({
|
|
state: z.enum(["running", "paused", "finished"]),
|
|
revision: z.number().int().positive(),
|
|
winner: groupKeySchema.optional(),
|
|
})
|
|
.parse(r.body);
|
|
await transition(r.user.sub, id, b.state, b.revision, b.winner);
|
|
return ok({ saved: true });
|
|
});
|
|
admin.get("/accounts", async () =>
|
|
ok(
|
|
await rows(
|
|
"SELECT CONCAT('user:',id) account,display_name name,created_at AS createdAt FROM dh_users WHERE status='ACTIVE' ORDER BY id LIMIT 500",
|
|
),
|
|
),
|
|
);
|
|
admin.post("/experiments/:id/explain", async (r) => {
|
|
const { id } = params.parse(r.params),
|
|
{ account } = z.object({ account: accountSchema }).parse(r.body);
|
|
const e = (await experiments()).find((v) => v.id === id);
|
|
if (!e) throw notFound("实验不存在");
|
|
return ok(await resolveExperiment(e, account, true));
|
|
});
|
|
admin.get("/experiments/:id/details", async (r) => {
|
|
const { id } = params.parse(r.params);
|
|
return ok({
|
|
assignments: await rows(
|
|
"SELECT account,variant,reason,created_at AS createdAt FROM dh_assignments WHERE experiment_id=? ORDER BY created_at DESC LIMIT 300",
|
|
[id],
|
|
),
|
|
overrides: await rows(
|
|
"SELECT account,variant,reason,bypass_audience AS bypassAudience,expires_at AS expiresAt FROM dh_overrides WHERE experiment_id=? ORDER BY expires_at DESC LIMIT 300",
|
|
[id],
|
|
),
|
|
metrics: await rows(
|
|
`SELECT variant,IF(reason='override','manual','random') cohort,COUNT(*) decisions,COUNT(DISTINCT account) assignedUsers,COUNT(exposed_at) exposures,COUNT(DISTINCT IF(exposed_at IS NOT NULL,account,NULL)) exposedUsers FROM dh_decisions WHERE experiment_id=? AND reason IN ('allocated','sticky','override') GROUP BY variant,cohort`,
|
|
[id],
|
|
),
|
|
funnel: await rows(
|
|
"SELECT variant,cohort,event_name AS eventName,COUNT(*) events,COUNT(DISTINCT account) users FROM dh_events WHERE experiment_id=? GROUP BY variant,cohort,event_name",
|
|
[id],
|
|
),
|
|
audits: await rows(
|
|
"SELECT actor,action,detail,created_at AS createdAt FROM dh_audits WHERE target=? ORDER BY id DESC LIMIT 100",
|
|
[id],
|
|
),
|
|
});
|
|
});
|
|
admin.put("/experiments/:id/override", async (r) => {
|
|
const { id } = params.parse(r.params),
|
|
b = z
|
|
.object({
|
|
account: accountSchema,
|
|
variant: groupKeySchema,
|
|
reason: z.string().min(2).max(500),
|
|
bypassAudience: z.boolean().default(false),
|
|
expiresAt: z.iso.datetime(),
|
|
})
|
|
.parse(r.body);
|
|
if (
|
|
Date.parse(b.expiresAt) <= Date.now() ||
|
|
Date.parse(b.expiresAt) > Date.now() + 30 * 86400000
|
|
)
|
|
throw badRequest("指定用户有效期须在未来30天内");
|
|
await assertActiveExperimentAccount(b.account);
|
|
await transaction(async (c) => {
|
|
const [e] = await rows<{ state: string; config: unknown }>(
|
|
"SELECT state,config FROM dh_experiments WHERE id=? FOR UPDATE",
|
|
[id],
|
|
c,
|
|
);
|
|
if (!e || e.state === "finished")
|
|
throw conflict("实验不存在或已结束");
|
|
if (
|
|
!hasExperimentGroup(
|
|
decodeExperimentConfig(json(e.config)),
|
|
b.variant,
|
|
)
|
|
)
|
|
throw badRequest("指定组不属于该测试方案");
|
|
await write(
|
|
"INSERT INTO dh_overrides(experiment_id,account,variant,reason,bypass_audience,expires_at) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE variant=VALUES(variant),reason=VALUES(reason),bypass_audience=VALUES(bypass_audience),expires_at=VALUES(expires_at)",
|
|
[
|
|
id,
|
|
b.account,
|
|
b.variant,
|
|
b.reason,
|
|
b.bypassAudience,
|
|
new Date(b.expiresAt),
|
|
],
|
|
c,
|
|
);
|
|
await audit(r.user.sub, "experiment.override", id, b, c);
|
|
});
|
|
return ok({ saved: true });
|
|
});
|
|
admin.delete("/experiments/:id/override/:account", async (r) => {
|
|
const { id, account } = z
|
|
.object({ id: idSchema, account: accountSchema })
|
|
.parse(r.params);
|
|
await transaction(async (c) => {
|
|
await write(
|
|
"DELETE FROM dh_overrides WHERE experiment_id=? AND account=?",
|
|
[id, account],
|
|
c,
|
|
);
|
|
await audit(
|
|
r.user.sub,
|
|
"experiment.override.remove",
|
|
id,
|
|
{ account },
|
|
c,
|
|
);
|
|
});
|
|
return ok({ deleted: true });
|
|
});
|
|
},
|
|
{ prefix: "/digital-admin" },
|
|
);
|
|
}
|