来源仓库: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 经哈希比对与线上同值), 整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。 供应商系统后续开发自本提交开始。
152 lines
5.1 KiB
TypeScript
152 lines
5.1 KiB
TypeScript
import { getRedisClient, isRedisConfigured } from './redisClient';
|
||
import { normalizePendingPick, type AssistantPendingPick } from '../mcp/requestPick';
|
||
import { normalizePendingBrowse, type AssistantPendingBrowse } from '../mcp/queryBrowse';
|
||
|
||
export type { AssistantPendingPick, AssistantPendingBrowse };
|
||
|
||
export type AssistantSessionTrace = { name: string; ok: boolean; summary: string };
|
||
|
||
export type AssistantPendingWrite = { capability: string; args: Record<string, unknown> };
|
||
|
||
export type AssistantSession = {
|
||
lastModule: string | null;
|
||
lastUser: string;
|
||
lastReply: string;
|
||
traces: AssistantSessionTrace[];
|
||
pendingWrite?: AssistantPendingWrite | null;
|
||
pendingPick?: AssistantPendingPick | null;
|
||
pendingBrowse?: AssistantPendingBrowse | null;
|
||
};
|
||
|
||
const TTL_SEC = 45 * 60;
|
||
const KEY_PREFIX = 'assistant:sess:';
|
||
const memory = new Map<string, { exp: number; value: AssistantSession }>();
|
||
|
||
export function assistantSessionKey(userId: string, sessionId: string): string {
|
||
return `${KEY_PREFIX}${String(userId || '').trim()}:${String(sessionId || '').trim()}`;
|
||
}
|
||
|
||
function clip(text: string, max = 200): string {
|
||
const value = String(text || '').trim();
|
||
return value.length <= max ? value : `${value.slice(0, max)}…`;
|
||
}
|
||
|
||
function normalizePendingWrite(raw: unknown): AssistantPendingWrite | null {
|
||
if (!raw || typeof raw !== 'object') return null;
|
||
const row = raw as { capability?: unknown; args?: unknown };
|
||
const capability = String(row.capability || '').trim();
|
||
if (!capability) return null;
|
||
const args =
|
||
row.args && typeof row.args === 'object' && !Array.isArray(row.args)
|
||
? { ...(row.args as Record<string, unknown>) }
|
||
: {};
|
||
delete args.confirm;
|
||
return { capability, args };
|
||
}
|
||
|
||
export function normalizeAssistantSession(raw: Partial<AssistantSession> | null | undefined): AssistantSession {
|
||
const traces = Array.isArray(raw?.traces)
|
||
? raw!.traces
|
||
.filter((row) => row && typeof row.name === 'string')
|
||
.slice(-5)
|
||
.map((row) => ({
|
||
name: String(row.name || '').trim(),
|
||
ok: row.ok !== false,
|
||
summary: clip(String(row.summary || ''), 240),
|
||
}))
|
||
.filter((row) => row.name)
|
||
: [];
|
||
return {
|
||
lastModule: String(raw?.lastModule || '').trim() || null,
|
||
lastUser: clip(String(raw?.lastUser || '')),
|
||
lastReply: clip(String(raw?.lastReply || '')),
|
||
traces,
|
||
pendingWrite: normalizePendingWrite(raw?.pendingWrite),
|
||
pendingPick: normalizePendingPick(raw?.pendingPick),
|
||
pendingBrowse: normalizePendingBrowse(raw?.pendingBrowse),
|
||
};
|
||
}
|
||
|
||
function sweepMemory(now = Date.now()) {
|
||
for (const [key, row] of memory) {
|
||
if (row.exp <= now) memory.delete(key);
|
||
}
|
||
}
|
||
|
||
export function resetAssistantSessionsForTests() {
|
||
memory.clear();
|
||
}
|
||
|
||
export async function readAssistantSession(userId: string, sessionId: string): Promise<AssistantSession | null> {
|
||
const id = String(sessionId || '').trim();
|
||
const uid = String(userId || '').trim();
|
||
if (!id || !uid) return null;
|
||
const key = assistantSessionKey(uid, id);
|
||
if (isRedisConfigured()) {
|
||
const redis = getRedisClient();
|
||
if (redis) {
|
||
try {
|
||
const raw = await redis.get(key);
|
||
if (raw) return normalizeAssistantSession(JSON.parse(raw) as AssistantSession);
|
||
} catch {
|
||
// 回退内存
|
||
}
|
||
}
|
||
}
|
||
sweepMemory();
|
||
const row = memory.get(key);
|
||
if (!row || row.exp <= Date.now()) {
|
||
if (row) memory.delete(key);
|
||
return null;
|
||
}
|
||
return normalizeAssistantSession(row.value);
|
||
}
|
||
|
||
export async function writeAssistantSession(
|
||
userId: string,
|
||
sessionId: string,
|
||
session: AssistantSession
|
||
): Promise<void> {
|
||
const id = String(sessionId || '').trim();
|
||
const uid = String(userId || '').trim();
|
||
if (!id || !uid) return;
|
||
const key = assistantSessionKey(uid, id);
|
||
const value = normalizeAssistantSession(session);
|
||
const payload = JSON.stringify(value);
|
||
if (isRedisConfigured()) {
|
||
const redis = getRedisClient();
|
||
if (redis) {
|
||
try {
|
||
await redis.set(key, payload, 'EX', TTL_SEC);
|
||
return;
|
||
} catch {
|
||
// 回退内存
|
||
}
|
||
}
|
||
}
|
||
memory.set(key, { exp: Date.now() + TTL_SEC * 1000, value });
|
||
}
|
||
|
||
export function resolveAssistantHintModule(
|
||
sessionLastModule: string | null | undefined,
|
||
requestHint: string | null | undefined
|
||
): string | null {
|
||
return String(sessionLastModule || '').trim() || String(requestHint || '').trim() || null;
|
||
}
|
||
|
||
export function formatSessionIndex(session: AssistantSession | null): string {
|
||
if (!session || (!session.lastModule && !session.traces.length && !session.lastUser)) return '';
|
||
const moduleLabel = session.lastModule || '无';
|
||
const traceText = session.traces.length
|
||
? session.traces.map((row) => `${row.name} → ${row.summary}`).join(';')
|
||
: '无';
|
||
const follow = session.lastUser ? `上一句用户:${session.lastUser}` : '';
|
||
return [
|
||
`会话索引(不是当前事实):上次模块=${moduleLabel};上次工具:${traceText}。`,
|
||
'跟进短句优先仍走该模块。需要数字/列表/页上筛选必须再调工具,禁止把索引里的数字当成最新结果。',
|
||
follow,
|
||
]
|
||
.filter(Boolean)
|
||
.join('');
|
||
}
|