apps/web/src/lib/aiFlowSessions.ts

1import type { Flow, FlowSession } from './flowSelector'
2
3// Routing state is intentionally process-local. It contains no contact details,
4// does not authorize a handoff, and expires quickly.
5const flowMemory = new Map<string, FlowSession>()
6const FLOW_TTL = 60 * 60 * 1000
7
8export async function loadFlowSession(
9	chatId: string,
10	event: string,
11): Promise<FlowSession | null> {
12	const cached = flowMemory.get(chatId)
13	return cached &&
14		cached.event === event &&
15		Date.now() - cached.updatedAt < FLOW_TTL
16		? cached
17		: null
18}
19
20export async function saveFlowSession(
21	chatId: string,
22	workflow: Flow | null,
23	event: string,
24): Promise<void> {
25	if (flowMemory.size >= 5000)
26		flowMemory.delete(flowMemory.keys().next().value ?? '')
27	flowMemory.set(chatId, { workflow, event, updatedAt: Date.now() })
28}
29