-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathchat.ts
More file actions
678 lines (616 loc) · 23.5 KB
/
Copy pathchat.ts
File metadata and controls
678 lines (616 loc) · 23.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
import { Router } from "express";
import { requireAuth } from "../middleware/auth";
import { createServerSupabase } from "../lib/supabase";
import {
buildDocContext,
buildMessages,
enrichWithPriorEvents,
buildWorkflowStore,
extractAnnotations,
groundingSummary,
runLLMStream,
type ChatMessage,
} from "../lib/chatTools";
import { completeText } from "../lib/llm";
import { getUserApiKeys, getUserModelSettings } from "../lib/userSettings";
import { checkProjectAccess } from "../lib/access";
import { appendAuditEvent } from "../lib/audit";
import { enforceEgressGuard } from "../lib/routing";
export const chatRouter = Router();
type Db = ReturnType<typeof createServerSupabase>;
const isDev = process.env.NODE_ENV !== "production";
const devLog = (...args: Parameters<typeof console.log>) => {
if (isDev) console.log(...args);
};
type AccessibleChat = {
id: string;
title: string | null;
user_id: string;
project_id: string | null;
} & Record<string, unknown>;
function parseOptionalProjectId(value: unknown):
| { ok: true; provided: boolean; projectId: string | null }
| { ok: false; detail: string } {
if (value === undefined)
return { ok: true, provided: false, projectId: null };
if (value === null) return { ok: true, provided: true, projectId: null };
if (typeof value !== "string" || !value.trim()) {
return {
ok: false,
detail: "project_id must be a non-empty string or null",
};
}
return { ok: true, provided: true, projectId: value.trim() };
}
function parseOptionalChatId(value: unknown):
| { ok: true; chatId: string | null }
| { ok: false; detail: string } {
if (value === undefined || value === null) return { ok: true, chatId: null };
if (typeof value !== "string" || !value.trim()) {
return { ok: false, detail: "chat_id must be a non-empty string" };
}
return { ok: true, chatId: value.trim() };
}
function parseChatMessages(value: unknown):
| { ok: true; messages: ChatMessage[] }
| { ok: false; detail: string } {
if (!Array.isArray(value) || value.length === 0) {
return { ok: false, detail: "messages must be a non-empty array" };
}
for (const message of value) {
if (!message || typeof message !== "object" || Array.isArray(message)) {
return { ok: false, detail: "messages must contain objects" };
}
const row = message as Record<string, unknown>;
if (typeof row.role !== "string") {
return { ok: false, detail: "message.role must be a string" };
}
if (row.content !== null && typeof row.content !== "string") {
return {
ok: false,
detail: "message.content must be a string or null",
};
}
}
return { ok: true, messages: value as ChatMessage[] };
}
function parseOptionalModel(value: unknown):
| { ok: true; model: string | undefined }
| { ok: false; detail: string } {
if (value === undefined) return { ok: true, model: undefined };
if (typeof value !== "string" || !value.trim()) {
return { ok: false, detail: "model must be a non-empty string" };
}
return { ok: true, model: value.trim() };
}
async function validateAccessibleProjectId(
projectId: string | null,
userId: string,
userEmail: string | null | undefined,
db: Db,
): Promise<{ ok: true } | { ok: false; status: number; detail: string }> {
if (!projectId) return { ok: true };
const access = await checkProjectAccess(projectId, userId, userEmail, db);
if (!access.ok)
return { ok: false, status: 404, detail: "Project not found" };
return { ok: true };
}
async function getAccessibleChat(
chatId: string,
userId: string,
userEmail: string | null | undefined,
db: Db,
): Promise<AccessibleChat | null> {
const { data: chat, error } = await db
.from("chats")
.select("*")
.eq("id", chatId)
.maybeSingle();
if (error || !chat) return null;
const row = chat as AccessibleChat;
if (row.user_id === userId) return row;
if (row.project_id) {
const access = await checkProjectAccess(
row.project_id,
userId,
userEmail,
db,
);
if (access.ok) return row;
}
return null;
}
// GET /chat
// Visible chats = the user's own chats + every chat under a project the
// user owns (so a project owner sees all collaborator chats in their
// own projects in the global recent-chats list). Chats in projects that
// are merely *shared with* the user are NOT included here — those are
// listed per-project via GET /projects/:projectId/chats.
chatRouter.get("/", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const db = createServerSupabase();
const requestedLimit = Number.parseInt(String(req.query.limit ?? ""), 10);
const limit = Number.isFinite(requestedLimit)
? Math.min(Math.max(requestedLimit, 1), 100)
: null;
const { data: ownProjects, error: projErr } = await db
.from("projects")
.select("id")
.eq("user_id", userId);
if (projErr) return void res.status(500).json({ detail: projErr.message });
const ownProjectIds = ((ownProjects ?? []) as { id: string }[]).map(
(p) => p.id,
);
const filter =
ownProjectIds.length > 0
? `user_id.eq.${userId},project_id.in.(${ownProjectIds.join(",")})`
: `user_id.eq.${userId}`;
let query = db
.from("chats")
.select("*")
.or(filter)
.order("created_at", { ascending: false });
if (limit) query = query.limit(limit);
const { data, error } = await query;
if (error) return void res.status(500).json({ detail: error.message });
res.json(data ?? []);
});
// POST /chat/create
chatRouter.post("/create", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const parsedProjectId = parseOptionalProjectId(req.body?.project_id);
if (!parsedProjectId.ok) {
return void res.status(400).json({ detail: parsedProjectId.detail });
}
const projectId = parsedProjectId.projectId;
const db = createServerSupabase();
const projectAccess = await validateAccessibleProjectId(
projectId,
userId,
userEmail,
db,
);
if (!projectAccess.ok)
return void res
.status(projectAccess.status)
.json({ detail: projectAccess.detail });
const { data, error } = await db
.from("chats")
.insert({ user_id: userId, project_id: projectId ?? null })
.select("id")
.single();
if (error) return void res.status(500).json({ detail: error.message });
res.json({ id: data.id });
});
// GET /chat/:chatId
chatRouter.get("/:chatId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { chatId } = req.params;
const db = createServerSupabase();
const chat = await getAccessibleChat(chatId, userId, userEmail, db);
if (!chat)
return void res.status(404).json({ detail: "Chat not found" });
const { data: messages } = await db
.from("chat_messages")
.select("*")
.eq("chat_id", chatId)
.order("created_at", { ascending: true });
const hydrated = await hydrateEditStatuses(messages ?? [], db);
res.json({ chat, messages: hydrated });
});
// Stored message annotations/events capture the `status` at the time the
// assistant produced the edit (always "pending"). If the user later accepts
// or rejects, `document_edits.status` is updated but the stored message
// annotation is not. On chat load we merge the current DB status in so
// EditCards render with the real state.
async function hydrateEditStatuses(
messages: Record<string, unknown>[],
db: ReturnType<typeof createServerSupabase>,
): Promise<Record<string, unknown>[]> {
const editIds = new Set<string>();
const versionIds = new Set<string>();
const collectFromAnnList = (list: unknown) => {
if (!Array.isArray(list)) return;
for (const a of list as Record<string, unknown>[]) {
if (typeof a?.edit_id === "string") editIds.add(a.edit_id);
if (typeof a?.version_id === "string")
versionIds.add(a.version_id);
}
};
for (const m of messages) {
collectFromAnnList(m.annotations);
const content = m.content;
if (Array.isArray(content)) {
for (const ev of content as Record<string, unknown>[]) {
if (ev?.type === "doc_edited") {
collectFromAnnList(ev.annotations);
if (typeof ev.version_id === "string")
versionIds.add(ev.version_id);
}
}
}
}
if (editIds.size === 0 && versionIds.size === 0) return messages;
// Edit status patch.
const statusById = new Map<string, "pending" | "accepted" | "rejected">();
if (editIds.size > 0) {
const { data: rows } = await db
.from("document_edits")
.select("id, status")
.in("id", Array.from(editIds));
for (const r of (rows ?? []) as { id: string; status: string }[]) {
if (
r.status === "pending" ||
r.status === "accepted" ||
r.status === "rejected"
) {
statusById.set(r.id, r.status);
}
}
}
// Version-number patch — old stored events don't carry `version_number`
// because they predate the schema change. Look it up from
// document_versions so the UI can render "V3" chips + download filenames.
const versionNumberById = new Map<string, number | null>();
if (versionIds.size > 0) {
const { data: vrows } = await db
.from("document_versions")
.select("id, version_number")
.in("id", Array.from(versionIds));
for (const r of (vrows ?? []) as {
id: string;
version_number: number | null;
}[]) {
versionNumberById.set(r.id, r.version_number ?? null);
}
}
const patchAnnList = (list: unknown): unknown => {
if (!Array.isArray(list)) return list;
return (list as Record<string, unknown>[]).map((a) => {
let next = a;
if (typeof a?.edit_id === "string" && statusById.has(a.edit_id)) {
next = { ...next, status: statusById.get(a.edit_id) };
}
if (
typeof a?.version_id === "string" &&
versionNumberById.has(a.version_id)
) {
next = {
...next,
version_number: versionNumberById.get(a.version_id) ?? null,
};
}
return next;
});
};
return messages.map((m) => {
const next: Record<string, unknown> = { ...m };
next.annotations = patchAnnList(m.annotations);
if (Array.isArray(m.content)) {
next.content = (m.content as Record<string, unknown>[]).map(
(ev) => {
if (ev?.type !== "doc_edited") return ev;
let patched: Record<string, unknown> = {
...ev,
annotations: patchAnnList(ev.annotations),
};
if (
typeof ev.version_id === "string" &&
versionNumberById.has(ev.version_id)
) {
patched = {
...patched,
version_number:
versionNumberById.get(ev.version_id) ?? null,
};
}
return patched;
},
);
}
return next;
});
}
// PATCH /chat/:chatId
chatRouter.patch("/:chatId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { chatId } = req.params;
const title = (req.body.title ?? "").trim();
if (!title)
return void res.status(400).json({ detail: "title is required" });
const db = createServerSupabase();
const { data, error } = await db
.from("chats")
.update({ title })
.eq("id", chatId)
.eq("user_id", userId)
.select("id, title")
.single();
if (error || !data)
return void res.status(404).json({ detail: "Chat not found" });
res.json(data);
});
// DELETE /chat/:chatId
chatRouter.delete("/:chatId", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const { chatId } = req.params;
const db = createServerSupabase();
const { error } = await db
.from("chats")
.delete()
.eq("id", chatId)
.eq("user_id", userId);
if (error) return void res.status(500).json({ detail: error.message });
res.status(204).send();
});
// POST /chat/:chatId/generate-title
chatRouter.post("/:chatId/generate-title", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const userEmail = res.locals.userEmail as string | undefined;
const { chatId } = req.params;
const message =
typeof req.body?.message === "string" ? req.body.message.trim() : "";
if (!message)
return void res.status(400).json({ detail: "message is required" });
const db = createServerSupabase();
const chat = await getAccessibleChat(chatId, userId, userEmail, db);
if (!chat)
return void res.status(404).json({ detail: "Chat not found" });
try {
const { title_model, api_keys } = await getUserModelSettings(
userId,
db,
);
// ADR-0067/0095: generate-title wysyla pierwsze 500 znakow wiadomosci
// uzytkownika do LLM (title_model domyslnie chmurowy) - musi przejsc
// przez TEN SAM straznik data-residency. Dla sprawy objetej tajemnica
// blok = nie generujemy tytulu w chmurze (fallback do skrotu wiadomosci).
const titleGuard = await enforceEgressGuard({
db,
model: title_model,
projectId: chat.project_id ?? null,
actorUserId: userId,
chatId,
});
if (!titleGuard.allowed) {
const fallback = message.slice(0, 60);
await db.from("chats").update({ title: fallback }).eq("id", chatId);
return void res.json({ title: fallback });
}
const titleText = await completeText({
model: title_model,
user: `Generate a concise title (3–6 words) for a chat in an AI Legal Platform that starts with this message. The title should describe the topic or document — do NOT include words like "Legal Assistant", "AI", "Chat", or any similar prefix. Return only the title, no quotes or punctuation.\n\nMessage: ${message.slice(0, 500)}`,
maxTokens: 64,
apiKeys: api_keys,
});
const title = titleText.trim() || message.slice(0, 60);
await db
.from("chats")
.update({ title })
.eq("id", chatId);
res.json({ title });
} catch (err) {
console.error("[generate-title]", err);
res.status(500).json({ detail: "Failed to generate title" });
}
});
// POST /chat — streaming
chatRouter.post("/", requireAuth, async (req, res) => {
const userId = res.locals.userId as string;
const body =
req.body && typeof req.body === "object" && !Array.isArray(req.body)
? (req.body as Record<string, unknown>)
: {};
const parsedMessages = parseChatMessages(body.messages);
if (!parsedMessages.ok) {
return void res.status(400).json({ detail: parsedMessages.detail });
}
const parsedChatId = parseOptionalChatId(body.chat_id);
if (!parsedChatId.ok) {
return void res.status(400).json({ detail: parsedChatId.detail });
}
const parsedProjectId = parseOptionalProjectId(body.project_id);
if (!parsedProjectId.ok) {
return void res.status(400).json({ detail: parsedProjectId.detail });
}
const parsedModel = parseOptionalModel(body.model);
if (!parsedModel.ok) {
return void res.status(400).json({ detail: parsedModel.detail });
}
const messages = parsedMessages.messages;
const chat_id = parsedChatId.chatId;
const project_id = parsedProjectId.projectId;
const model = parsedModel.model;
devLog("[chat/stream] incoming request", {
userId,
chat_id,
project_id,
model,
messageCount: messages?.length,
});
const userEmail = res.locals.userEmail as string | undefined;
const db = createServerSupabase();
let chatId = chat_id ?? null;
let chatTitle: string | null = null;
let resolvedProjectId: string | null = parsedProjectId.projectId;
if (chatId) {
const existing = await getAccessibleChat(chatId, userId, userEmail, db);
if (!existing)
return void res.status(404).json({ detail: "Chat not found" });
const existingProjectId = existing.project_id ?? null;
if (
parsedProjectId.provided &&
parsedProjectId.projectId !== existingProjectId
) {
return void res
.status(400)
.json({ detail: "project_id does not match chat" });
}
resolvedProjectId = existingProjectId;
chatTitle = existing.title;
}
if (!chatId) {
// If creating a chat tied to a project, the user must have access
// to the project (own or shared).
const projectAccess = await validateAccessibleProjectId(
resolvedProjectId,
userId,
userEmail,
db,
);
if (!projectAccess.ok)
return void res
.status(projectAccess.status)
.json({ detail: projectAccess.detail });
const { data: newChat, error } = await db
.from("chats")
.insert({ user_id: userId, project_id: resolvedProjectId })
.select("id, title")
.single();
if (error || !newChat) {
console.error("[chat/stream] failed to create chat", error);
return void res
.status(500)
.json({ detail: "Failed to create chat" });
}
chatId = newChat.id as string;
chatTitle = newChat.title;
}
devLog("[chat/stream] resolved chatId", chatId);
const lastUser = [...messages].reverse().find((m) => m.role === "user");
if (lastUser) {
await db.from("chat_messages").insert({
chat_id: chatId,
role: "user",
content: lastUser.content,
files: lastUser.files ?? null,
workflow: lastUser.workflow ?? null,
});
// Audit trail (AI Act art. 12): zapis zdarzenia user-input. Bez tresci
// (long PII) - tylko skrot (dlugosc, liczba plikow, workflow id).
void appendAuditEvent(db, {
event_type: "chat.message.user",
actor_user_id: userId,
chat_id: chatId,
payload: {
content_len: (lastUser.content ?? "").length,
file_count: lastUser.files?.length ?? 0,
workflow_id: lastUser.workflow?.id ?? null,
},
});
}
const { docIndex, docStore } = await buildDocContext(
messages,
userId,
db,
chatId,
);
const docAvailability = Object.entries(docIndex).map(([doc_id, info]) => ({
doc_id,
filename: info.filename,
}));
const enrichedMessages = await enrichWithPriorEvents(
messages,
chatId,
db,
docIndex,
);
const apiMessages = buildMessages(enrichedMessages, docAvailability);
const workflowStore = await buildWorkflowStore(userId, userEmail, db);
devLog("[chat/stream] starting LLM stream", {
apiMessageCount: apiMessages.length,
docCount: Object.keys(docIndex).length,
workflowCount: Object.keys(workflowStore).length,
});
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
res.setHeader("X-Accel-Buffering", "no");
res.flushHeaders();
const write = (line: string) => res.write(line);
const apiKeys = await getUserApiKeys(userId, db);
try {
write(`data: ${JSON.stringify({ type: "chat_id", chatId })}\n\n`);
const { fullText, events, mcpCitations, grounding } =
await runLLMStream({
apiMessages,
docStore,
docIndex,
userId,
db,
write,
workflowStore,
model,
apiKeys,
projectId: resolvedProjectId,
});
devLog("[chat/stream] LLM stream finished", {
fullTextLen: fullText?.length ?? 0,
eventCount: events?.length ?? 0,
});
const annotations = extractAnnotations(
fullText,
docIndex,
events,
mcpCitations,
grounding,
);
await db.from("chat_messages").insert({
chat_id: chatId,
role: "assistant",
content: events.length ? events : null,
annotations: annotations.length ? annotations : null,
});
// Audit trail (AI Act art. 12): zapis zdarzenia assistant-output.
// Bez pelnej tresci - tylko liczby + lista narzedzi MCP wywolanych
// w tej turze (po nazwie konektora i toola).
const mcpToolsCalled = Array.from(
new Set(mcpCitations.map((c) => `${c.server}__${c.tool}`)),
);
void appendAuditEvent(db, {
event_type: "chat.message.assistant",
actor_user_id: userId,
chat_id: chatId,
payload: {
model: model ?? null,
full_text_len: fullText.length,
event_count: events.length,
citation_count: annotations.filter(
(a) =>
(a as Record<string, unknown>).type ===
"citation_data",
).length,
mcp_citation_count: mcpCitations.length,
mcp_tools_called: mcpToolsCalled,
// ADR-0005: wynik mechanicznej weryfikacji cytatow w tej turze.
grounding: groundingSummary(grounding),
},
});
if (!chatTitle && lastUser?.content) {
await db
.from("chats")
.update({ title: lastUser.content.slice(0, 120) })
.eq("id", chatId);
}
} catch (err) {
console.error("[chat/stream] error:", err);
// Odslon realny powod zamiast gluchego "Stream error" - mecenas (i my)
// widzimy DLACZEGO padlo (brak klucza, model not found, 401, timeout...).
// To infrastrukturalny komunikat providera, nie tresc akt; tniemy do 240
// znakow na wszelki wypadek. Frontend renderuje pole `message`.
const reason =
err instanceof Error && err.message ? err.message : String(err);
try {
write(
`data: ${JSON.stringify({ type: "error", message: `Blad generowania: ${reason}`.slice(0, 240) })}\n\n`,
);
write("data: [DONE]\n\n");
} catch {
/* ignore */
}
} finally {
res.end();
}
});