来源仓库:jxc/ai-fresh-delivery 来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d 快照树: 09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件) 按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据 (生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、 deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
421 lines
16 KiB
TypeScript
421 lines
16 KiB
TypeScript
import { randomUUID } from 'crypto';
|
|
import { pool } from '../db';
|
|
import type { CapabilitySurface } from '../capabilities/types';
|
|
|
|
export type AssistantChatSurface = 'web' | 'miniprogram';
|
|
export type AssistantChatTurn = { role: 'user' | 'assistant'; content: string };
|
|
|
|
const UUID_RE =
|
|
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
const TITLE_MAX = 80;
|
|
const CONTENT_MAX = 8000;
|
|
const LIST_LIMIT = 20;
|
|
|
|
export function parseAssistantChatSurface(raw: unknown): AssistantChatSurface {
|
|
return String(raw || '').trim() === 'miniprogram' ? 'miniprogram' : 'web';
|
|
}
|
|
|
|
export function capabilitySurfaceToChat(surface: CapabilitySurface | string): AssistantChatSurface {
|
|
return surface === 'miniprogram' ? 'miniprogram' : 'web';
|
|
}
|
|
|
|
export function isAssistantConversationId(raw: unknown): boolean {
|
|
return UUID_RE.test(String(raw || '').trim());
|
|
}
|
|
|
|
export function resolveConversationId(raw: unknown): string {
|
|
const value = String(raw || '').trim();
|
|
if (UUID_RE.test(value)) return value;
|
|
return randomUUID();
|
|
}
|
|
|
|
function clip(text: string, max: number): string {
|
|
const value = String(text || '').trim();
|
|
if (value.length <= max) return value;
|
|
return `${value.slice(0, max)}…`;
|
|
}
|
|
|
|
function titleFromTurns(turns: AssistantChatTurn[]): string {
|
|
const firstUser = turns.find((row) => row.role === 'user' && row.content.trim());
|
|
return clip(firstUser?.content || '', TITLE_MAX);
|
|
}
|
|
|
|
export async function listAssistantConversations(input: {
|
|
userId: string;
|
|
branchCode: string;
|
|
surface: AssistantChatSurface;
|
|
limit?: number;
|
|
}): Promise<Array<{ id: string; title: string; surface: string; updated_at: string }>> {
|
|
const userId = String(input.userId || '').trim();
|
|
const branchCode = String(input.branchCode || '').trim();
|
|
if (!userId || !branchCode) return [];
|
|
const limit = Math.min(LIST_LIMIT, Math.max(1, Number(input.limit) || LIST_LIMIT));
|
|
const result = await pool.query(
|
|
`SELECT id::text AS id, title, surface, updated_at
|
|
FROM assistant_conversations
|
|
WHERE user_id = $1
|
|
AND branch_code = $2
|
|
AND surface = $3
|
|
ORDER BY updated_at DESC
|
|
LIMIT $4`,
|
|
[userId, branchCode, input.surface, limit]
|
|
);
|
|
return (result.rows || []).map((row) => ({
|
|
id: String(row.id),
|
|
title: String(row.title || ''),
|
|
surface: String(row.surface || ''),
|
|
updated_at: row.updated_at instanceof Date ? row.updated_at.toISOString() : String(row.updated_at || ''),
|
|
}));
|
|
}
|
|
|
|
export async function listAssistantMessages(input: {
|
|
userId: string;
|
|
branchCode: string;
|
|
conversationId: string;
|
|
}): Promise<AssistantChatTurn[]> {
|
|
const userId = String(input.userId || '').trim();
|
|
const branchCode = String(input.branchCode || '').trim();
|
|
const conversationId = String(input.conversationId || '').trim();
|
|
if (!userId || !branchCode || !UUID_RE.test(conversationId)) return [];
|
|
const result = await pool.query(
|
|
`SELECT m.role, m.content
|
|
FROM assistant_messages m
|
|
JOIN assistant_conversations c ON c.id = m.conversation_id
|
|
WHERE c.id = $1::uuid
|
|
AND c.user_id = $2
|
|
AND c.branch_code = $3
|
|
ORDER BY m.created_at ASC, m.id ASC`,
|
|
[conversationId, userId, branchCode]
|
|
);
|
|
return (result.rows || [])
|
|
.map((row) => ({
|
|
role: row.role === 'assistant' ? ('assistant' as const) : ('user' as const),
|
|
content: String(row.content || ''),
|
|
}))
|
|
.filter((row) => row.content);
|
|
}
|
|
|
|
async function ensureOwnedConversation(input: {
|
|
conversationId: string;
|
|
userId: string;
|
|
branchCode: string;
|
|
surface: AssistantChatSurface;
|
|
title: string;
|
|
}): Promise<string | null> {
|
|
const owned = await pool.query(
|
|
`SELECT id::text AS id
|
|
FROM assistant_conversations
|
|
WHERE id = $1::uuid
|
|
AND user_id = $2
|
|
AND branch_code = $3
|
|
LIMIT 1`,
|
|
[input.conversationId, input.userId, input.branchCode]
|
|
);
|
|
if (owned.rowCount) {
|
|
await pool.query(
|
|
`UPDATE assistant_conversations
|
|
SET updated_at = NOW(),
|
|
title = CASE WHEN COALESCE(title, '') = '' THEN $2 ELSE title END
|
|
WHERE id = $1::uuid
|
|
AND user_id = $3
|
|
AND branch_code = $4`,
|
|
[input.conversationId, input.title, input.userId, input.branchCode]
|
|
);
|
|
return input.conversationId;
|
|
}
|
|
|
|
const taken = await pool.query(
|
|
`SELECT 1 FROM assistant_conversations WHERE id = $1::uuid LIMIT 1`,
|
|
[input.conversationId]
|
|
);
|
|
if (taken.rowCount) return null;
|
|
|
|
await pool.query(
|
|
`INSERT INTO assistant_conversations (id, user_id, branch_code, surface, title)
|
|
VALUES ($1::uuid, $2, $3, $4, $5)`,
|
|
[input.conversationId, input.userId, input.branchCode, input.surface, input.title]
|
|
);
|
|
return input.conversationId;
|
|
}
|
|
|
|
export async function appendAssistantChatTurns(input: {
|
|
conversationId: string;
|
|
userId: string;
|
|
branchCode: string;
|
|
surface: AssistantChatSurface;
|
|
turns: AssistantChatTurn[];
|
|
}): Promise<string | null> {
|
|
const userId = String(input.userId || '').trim();
|
|
const branchCode = String(input.branchCode || '').trim();
|
|
const turns = (input.turns || [])
|
|
.map((row) => ({
|
|
role: row.role === 'assistant' ? ('assistant' as const) : ('user' as const),
|
|
content: clip(row.content, CONTENT_MAX),
|
|
}))
|
|
.filter((row) => row.content);
|
|
if (!userId || !branchCode || !turns.length) return null;
|
|
const conversationId = resolveConversationId(input.conversationId);
|
|
const id = await ensureOwnedConversation({
|
|
conversationId,
|
|
userId,
|
|
branchCode,
|
|
surface: input.surface,
|
|
title: titleFromTurns(turns),
|
|
});
|
|
if (!id) return null;
|
|
for (const turn of turns) {
|
|
await pool.query(
|
|
`INSERT INTO assistant_messages (conversation_id, role, content)
|
|
SELECT $1::uuid, $2, $3
|
|
WHERE EXISTS (
|
|
SELECT 1 FROM assistant_conversations
|
|
WHERE id = $1::uuid AND user_id = $4 AND branch_code = $5
|
|
)`,
|
|
[id, turn.role, turn.content, userId, branchCode]
|
|
);
|
|
}
|
|
return id;
|
|
}
|
|
|
|
/**
|
|
* 会话记忆检索(P2b):只在**自己的会话**内检索(user_id + branch_code + conversation_id 三重限定)。
|
|
* 支持关键词(content ILIKE)与时间区间;返回最近 limit 条 + 总数,供模型按需读取更早的对话。
|
|
*/
|
|
export async function searchAssistantMessages(input: {
|
|
userId: string;
|
|
branchCode: string;
|
|
conversationId: string;
|
|
keyword?: string | null;
|
|
since?: string | null;
|
|
before?: string | null;
|
|
limit?: number;
|
|
/** 从最新往旧跳过的条数(分页:看更早的)。 */
|
|
offset?: number;
|
|
}): Promise<{ rows: Array<AssistantChatTurn & { created_at: string }>; total: number; truncated: boolean }> {
|
|
const userId = String(input.userId || '').trim();
|
|
const branchCode = String(input.branchCode || '').trim();
|
|
const conversationId = String(input.conversationId || '').trim();
|
|
if (!userId || !branchCode || !UUID_RE.test(conversationId)) return { rows: [], total: 0, truncated: false };
|
|
|
|
const limit = Math.min(60, Math.max(1, Number(input.limit) || 12));
|
|
const offset = Math.min(2000, Math.max(0, Number(input.offset) || 0));
|
|
const keyword = String(input.keyword || '').trim().slice(0, 60);
|
|
const ymd = (raw: unknown) => {
|
|
const v = String(raw || '').trim().slice(0, 10);
|
|
return /^\d{4}-\d{2}-\d{2}$/.test(v) ? v : null;
|
|
};
|
|
const since = ymd(input.since);
|
|
const before = ymd(input.before);
|
|
|
|
const filters: string[] = ['c.id = $1::uuid', 'c.user_id = $2', 'c.branch_code = $3'];
|
|
const params: unknown[] = [conversationId, userId, branchCode];
|
|
if (keyword) {
|
|
params.push(`%${keyword}%`);
|
|
filters.push(`m.content ILIKE $${params.length}`);
|
|
}
|
|
if (since) {
|
|
params.push(since);
|
|
filters.push(`m.created_at >= $${params.length}::date`);
|
|
}
|
|
if (before) {
|
|
params.push(before);
|
|
filters.push(`m.created_at < ($${params.length}::date + INTERVAL '1 day')`);
|
|
}
|
|
const where = filters.join(' AND ');
|
|
|
|
const totalResult = await pool.query(
|
|
`SELECT COUNT(*)::int AS cnt FROM assistant_messages m
|
|
JOIN assistant_conversations c ON c.id = m.conversation_id
|
|
WHERE ${where}`,
|
|
params
|
|
);
|
|
const total = Number(totalResult.rows[0]?.cnt) || 0;
|
|
|
|
const listParams = [...params, limit, offset];
|
|
const result = await pool.query(
|
|
`SELECT m.role, m.content, m.created_at
|
|
FROM assistant_messages m
|
|
JOIN assistant_conversations c ON c.id = m.conversation_id
|
|
WHERE ${where}
|
|
ORDER BY m.created_at DESC, m.id DESC
|
|
LIMIT $${listParams.length - 1} OFFSET $${listParams.length}`,
|
|
listParams
|
|
);
|
|
const rows = (result.rows || []).map((row) => ({
|
|
role: row.role === 'assistant' ? ('assistant' as const) : ('user' as const),
|
|
content: String(row.content || ''),
|
|
created_at: row.created_at instanceof Date ? row.created_at.toISOString() : String(row.created_at || ''),
|
|
}));
|
|
return { rows, total, truncated: total > offset + rows.length };
|
|
}
|
|
|
|
/** 会话消息总量与时间范围(记忆地图:告诉模型"本会话有多少历史、可检索")。 */
|
|
export async function describeAssistantHistory(input: {
|
|
userId: string;
|
|
branchCode: string;
|
|
conversationId: string;
|
|
}): Promise<{ total: number; from: string | null; to: string | null }> {
|
|
const userId = String(input.userId || '').trim();
|
|
const branchCode = String(input.branchCode || '').trim();
|
|
const conversationId = String(input.conversationId || '').trim();
|
|
if (!userId || !branchCode || !UUID_RE.test(conversationId)) return { total: 0, from: null, to: null };
|
|
const result = await pool.query(
|
|
`SELECT COUNT(*)::int AS cnt, MIN(m.created_at) AS from_at, MAX(m.created_at) AS to_at
|
|
FROM assistant_messages m
|
|
JOIN assistant_conversations c ON c.id = m.conversation_id
|
|
WHERE c.id = $1::uuid AND c.user_id = $2 AND c.branch_code = $3`,
|
|
[conversationId, userId, branchCode]
|
|
);
|
|
const row = result.rows[0] || {};
|
|
const iso = (v: unknown) => (v ? (v instanceof Date ? v.toISOString().slice(0, 10) : String(v).slice(0, 10)) : null);
|
|
return { total: Number(row.cnt) || 0, from: iso(row.from_at), to: iso(row.to_at) };
|
|
}
|
|
|
|
/** 会话的滚动摘要状态(P2b-5):摘要文本 + 已覆盖的消息条数。 */
|
|
export type AssistantConversationSummaryState = {
|
|
summary: string;
|
|
covered: number;
|
|
updated_at: string | null;
|
|
};
|
|
|
|
/** 读取会话摘要状态(无摘要时返回空态,不抛错)。 */
|
|
export async function loadAssistantConversationSummary(input: {
|
|
userId: string;
|
|
branchCode: string;
|
|
conversationId: string;
|
|
}): Promise<AssistantConversationSummaryState> {
|
|
const userId = String(input.userId || '').trim();
|
|
const branchCode = String(input.branchCode || '').trim();
|
|
const conversationId = String(input.conversationId || '').trim();
|
|
const empty: AssistantConversationSummaryState = { summary: '', covered: 0, updated_at: null };
|
|
if (!userId || !branchCode || !UUID_RE.test(conversationId)) return empty;
|
|
const result = await pool.query(
|
|
`SELECT summary, summary_message_count, summary_updated_at
|
|
FROM assistant_conversations
|
|
WHERE id = $1::uuid AND user_id = $2 AND branch_code = $3
|
|
LIMIT 1`,
|
|
[conversationId, userId, branchCode]
|
|
);
|
|
const row = result.rows[0];
|
|
if (!row) return empty;
|
|
return {
|
|
summary: String(row.summary || ''),
|
|
covered: Math.max(0, Number(row.summary_message_count) || 0),
|
|
updated_at: row.summary_updated_at
|
|
? row.summary_updated_at instanceof Date
|
|
? row.summary_updated_at.toISOString()
|
|
: String(row.summary_updated_at)
|
|
: null,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* 抢摘要生成锁(双活 CLB 下两实例同时触发也只跑一次):
|
|
* 仅当"从未生成"或"上次生成已过 staleMinutes"才能抢到。
|
|
*/
|
|
export async function claimAssistantConversationSummary(input: {
|
|
userId: string;
|
|
branchCode: string;
|
|
conversationId: string;
|
|
staleMinutes?: number;
|
|
}): Promise<boolean> {
|
|
const userId = String(input.userId || '').trim();
|
|
const branchCode = String(input.branchCode || '').trim();
|
|
const conversationId = String(input.conversationId || '').trim();
|
|
if (!userId || !branchCode || !UUID_RE.test(conversationId)) return false;
|
|
const stale = Math.max(1, Number(input.staleMinutes) || 2);
|
|
const result = await pool.query(
|
|
`UPDATE assistant_conversations
|
|
SET summary_updated_at = NOW()
|
|
WHERE id = $1::uuid
|
|
AND user_id = $2
|
|
AND branch_code = $3
|
|
AND (summary_updated_at IS NULL OR summary_updated_at < NOW() - ($4::int * INTERVAL '1 minute'))`,
|
|
[conversationId, userId, branchCode, stale]
|
|
);
|
|
return (result.rowCount ?? 0) > 0;
|
|
}
|
|
|
|
/** 写入摘要(归属三重校验;覆盖条数只增不减,避免并发回退)。 */
|
|
export async function saveAssistantConversationSummary(input: {
|
|
userId: string;
|
|
branchCode: string;
|
|
conversationId: string;
|
|
summary: string;
|
|
covered: number;
|
|
model?: string | null;
|
|
}): Promise<boolean> {
|
|
const userId = String(input.userId || '').trim();
|
|
const branchCode = String(input.branchCode || '').trim();
|
|
const conversationId = String(input.conversationId || '').trim();
|
|
if (!userId || !branchCode || !UUID_RE.test(conversationId)) return false;
|
|
const covered = Math.max(0, Number(input.covered) || 0);
|
|
const result = await pool.query(
|
|
`UPDATE assistant_conversations
|
|
SET summary = $4,
|
|
summary_message_count = GREATEST(summary_message_count, $5::int),
|
|
summary_updated_at = NOW(),
|
|
summary_model = $6
|
|
WHERE id = $1::uuid AND user_id = $2 AND branch_code = $3`,
|
|
[conversationId, userId, branchCode, String(input.summary || ''), covered, input.model || null]
|
|
);
|
|
return (result.rowCount ?? 0) > 0;
|
|
}
|
|
|
|
/** 按时间正序取一段消息(用于生成摘要:从 covered 起、到"保留最近 keep 条"前止)。 */
|
|
export async function listAssistantMessageSegment(input: {
|
|
userId: string;
|
|
branchCode: string;
|
|
conversationId: string;
|
|
offset: number;
|
|
limit: number;
|
|
}): Promise<AssistantChatTurn[]> {
|
|
const userId = String(input.userId || '').trim();
|
|
const branchCode = String(input.branchCode || '').trim();
|
|
const conversationId = String(input.conversationId || '').trim();
|
|
const offset = Math.max(0, Number(input.offset) || 0);
|
|
const limit = Math.min(400, Math.max(0, Number(input.limit) || 0));
|
|
if (!userId || !branchCode || !UUID_RE.test(conversationId) || !limit) return [];
|
|
const result = await pool.query(
|
|
`SELECT m.role, m.content
|
|
FROM assistant_messages m
|
|
JOIN assistant_conversations c ON c.id = m.conversation_id
|
|
WHERE c.id = $1::uuid AND c.user_id = $2 AND c.branch_code = $3
|
|
ORDER BY m.created_at ASC, m.id ASC
|
|
LIMIT $4 OFFSET $5`,
|
|
[conversationId, userId, branchCode, limit, offset]
|
|
);
|
|
return (result.rows || [])
|
|
.map((row) => ({
|
|
role: row.role === 'assistant' ? ('assistant' as const) : ('user' as const),
|
|
content: String(row.content || ''),
|
|
}))
|
|
.filter((row) => row.content);
|
|
}
|
|
|
|
/** 删除自己的某条会话(消息随外键级联删除)。返回是否删除成功。 */
|
|
export async function deleteAssistantConversation(input: {
|
|
userId: string;
|
|
conversationId: string;
|
|
}): Promise<boolean> {
|
|
const userId = String(input.userId || '').trim();
|
|
const conversationId = String(input.conversationId || '').trim();
|
|
if (!userId || !UUID_RE.test(conversationId)) return false;
|
|
const result = await pool.query(
|
|
`DELETE FROM assistant_conversations WHERE id = $1::uuid AND user_id = $2`,
|
|
[conversationId, userId]
|
|
);
|
|
return (result.rowCount ?? 0) > 0;
|
|
}
|
|
|
|
export async function safeAppendAssistantChatTurns(
|
|
input: Parameters<typeof appendAssistantChatTurns>[0]
|
|
): Promise<string | null> {
|
|
try {
|
|
return await appendAssistantChatTurns(input);
|
|
} catch (error) {
|
|
console.error('[assistant-chat-log] append failed', error);
|
|
return null;
|
|
}
|
|
}
|