-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrender-chat-server.ts
More file actions
1280 lines (1132 loc) · 34.4 KB
/
render-chat-server.ts
File metadata and controls
1280 lines (1132 loc) · 34.4 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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
createServer,
type IncomingMessage,
type ServerResponse,
} from "node:http";
import {
type ChatAbortReason,
type ChatProvider,
type ChatRequestBody,
ensureChatRunCredits,
ensureChatModelAccess,
executeChatRunStream,
resolveRunSystemInstructions,
resolveChatRequest,
} from "@/lib/chat/server-core";
import { encodeChatStreamEvent } from "@/lib/chat/protocol";
import { isAdminUser } from "@/lib/auth/admin";
import { resolveUserLocation } from "@/lib/locale-preference";
import {
abortRegisteredChatRun,
registerChatRunAbortController,
unregisterChatRunAbortController,
} from "@/lib/chat/run-abort-registry";
import {
completeChatRun,
getChatRun,
getChatRunEvents,
getLatestChatRunForThread,
isRunStale,
requestChatRunCancel,
requestThreadRunCancel,
} from "@/lib/chat/runs-repository";
import {
forkThreadAtMessage,
getSpreadsheetAssistantRecentSessions,
getSpreadsheetAssistantThreadMessages,
} from "@/lib/chat/graph";
import {
deleteAssistantSession,
upsertAssistantSession,
} from "@/lib/chat/sessions-repository";
import { db } from "@/lib/db/postgres";
type AuthIdentity = {
userId: string;
email: string | null;
activeOrganizationId?: string | null;
};
type JwtPayloadLike = {
sub?: unknown;
email?: unknown;
[key: string]: unknown;
};
const CHAT_PATH = process.env.CHAT_RENDER_PATH?.trim() || "/chat";
const CHAT_RESUME_PATH = process.env.CHAT_RESUME_PATH?.trim() || "/chat/resume";
const CHAT_STOP_PATH = process.env.CHAT_STOP_PATH?.trim() || "/chat/stop";
const CHAT_HISTORY_PATH =
process.env.CHAT_HISTORY_PATH?.trim() || "/chat/history";
const HEALTH_PATH = process.env.CHAT_RENDER_HEALTH_PATH?.trim() || "/health";
const CHAT_RUNTIME_HEADER_NAME = "X-Chat-Runtime";
const CHAT_RUNTIME_HEADER_VALUE =
process.env.CHAT_RUNTIME_HEADER_VALUE?.trim() || "render-chat-server";
const DEFAULT_CHAT_SERVER_TIMEOUT_MS = 30 * 60_000; // 30 minutes
const MAX_CHAT_SERVER_TIMEOUT_MS = 95 * 60_000; // Keep below common 100-min gateway limits
const DEFAULT_CHAT_ALLOWED_ORIGINS = [
"https://rowsncolumns.ai",
"https://www.rowsncolumns.ai",
"http://localhost:3000",
"https://localhost:3000",
];
const CHAT_MODEL = process.env.CHAT_MODEL?.trim() || undefined;
const CHAT_PROVIDER = (() => {
const value = process.env.CHAT_PROVIDER?.trim().toLowerCase();
if (value === "openai" || value === "anthropic") {
return value as ChatProvider;
}
return undefined;
})();
const CHAT_REASONING_ENABLED = (() => {
const value = process.env.CHAT_REASONING_ENABLED?.trim().toLowerCase();
if (value === "true" || value === "1") return true;
if (value === "false" || value === "0") return false;
return undefined;
})();
const CHAT_SYSTEM_INSTRUCTIONS =
process.env.CHAT_SYSTEM_INSTRUCTIONS?.trim() || undefined;
const parsePositiveInt = (value: string | undefined, fallback: number) => {
if (!value) return fallback;
const parsed = Number.parseInt(value, 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
};
const resolveActiveOrganizationIdForUser = async (
userId: string,
): Promise<string | null> => {
const rows = await db<{ organization_id: string }[]>`
SELECT m."organizationId" AS organization_id
FROM public.member AS m
WHERE m."userId" = ${userId}
ORDER BY m."createdAt" ASC
LIMIT 1
`;
return rows[0]?.organization_id ?? null;
};
const CHAT_SSE_HEARTBEAT_INTERVAL_MS = Math.max(
0,
parsePositiveInt(process.env.CHAT_SSE_HEARTBEAT_INTERVAL_MS, 15000),
);
const normalizeAuthBaseUrl = () => {
const raw =
process.env.CHAT_AUTH_BASE_URL?.trim() ??
process.env.BETTER_AUTH_URL?.trim();
if (!raw) {
throw new Error(
"Missing CHAT_AUTH_BASE_URL or BETTER_AUTH_URL for Render chat server.",
);
}
return raw.replace(/\/+$/, "");
};
const AUTH_BASE_URL = normalizeAuthBaseUrl();
const AUTH_BASE_ORIGIN = new URL(AUTH_BASE_URL).origin;
const AUTH_BASE_PATH = (
process.env.CHAT_AUTH_BASE_PATH?.trim() || "/api/auth"
).replace(/\/+$/, "");
const AUTH_API_BASE = AUTH_BASE_PATH.startsWith("/")
? `${AUTH_BASE_URL}${AUTH_BASE_PATH}`
: `${AUTH_BASE_URL}/${AUTH_BASE_PATH}`;
const CHAT_AUTH_JWKS_URL = process.env.CHAT_AUTH_JWKS_URL?.trim() || undefined;
const CHAT_AUTH_EXPECTED_ISSUER =
process.env.CHAT_AUTH_EXPECTED_ISSUER?.trim() || AUTH_BASE_ORIGIN;
const CHAT_AUTH_EXPECTED_AUDIENCE =
process.env.CHAT_AUTH_EXPECTED_AUDIENCE?.trim() || AUTH_BASE_ORIGIN;
const CHAT_SERVER_TIMEOUT_MS = Math.min(
parsePositiveInt(
process.env.CHAT_SERVER_TIMEOUT_MS,
DEFAULT_CHAT_SERVER_TIMEOUT_MS,
),
MAX_CHAT_SERVER_TIMEOUT_MS,
);
const CHAT_RESUME_POLL_INTERVAL_MS = Math.max(
100,
parsePositiveInt(process.env.CHAT_RESUME_POLL_INTERVAL_MS, 500),
);
const CHAT_RESUME_MAX_STREAM_DURATION_MS = Math.max(
CHAT_RESUME_POLL_INTERVAL_MS,
parsePositiveInt(
process.env.CHAT_RESUME_MAX_STREAM_DURATION_MS,
CHAT_SERVER_TIMEOUT_MS,
),
);
const CHAT_RESUME_STALE_CHECK_NO_EVENTS_SECONDS = Math.max(
5,
parsePositiveInt(process.env.CHAT_RESUME_STALE_CHECK_NO_EVENTS_SECONDS, 15),
);
const CHAT_RESUME_STALE_CHECK_AFTER_IDLE_MS = Math.max(
CHAT_RESUME_POLL_INTERVAL_MS,
parsePositiveInt(process.env.CHAT_RESUME_STALE_CHECK_AFTER_IDLE_MS, 10_000),
);
const CHAT_ALLOWED_ORIGINS = new Set(
(process.env.CHAT_ALLOWED_ORIGINS ?? DEFAULT_CHAT_ALLOWED_ORIGINS.join(","))
.split(",")
.map((origin) => origin.trim())
.filter(Boolean),
);
const buildCorsHeaders = (origin: string | null) => {
const isAllowedOrigin = !!origin && CHAT_ALLOWED_ORIGINS.has(origin);
if (!isAllowedOrigin) {
return null;
}
return {
"Access-Control-Allow-Origin": origin,
"Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Credentials": "true",
"Access-Control-Max-Age": "86400",
Vary: "Origin",
} as const;
};
const resolveRequestOrigin = (req: IncomingMessage): string | null => {
const originHeader =
typeof req.headers.origin === "string" ? req.headers.origin.trim() : "";
if (originHeader) {
return originHeader;
}
const refererHeader =
typeof req.headers.referer === "string" ? req.headers.referer.trim() : "";
if (!refererHeader) {
return null;
}
try {
const refererOrigin = new URL(refererHeader).origin.trim();
return refererOrigin.length > 0 ? refererOrigin : null;
} catch {
return null;
}
};
const setCorsHeaders = (res: ServerResponse, origin: string | null) => {
const headers = buildCorsHeaders(origin);
if (!headers) {
return false;
}
for (const [key, value] of Object.entries(headers)) {
res.setHeader(key, value);
}
return true;
};
const setRuntimeHeader = (res: ServerResponse) => {
res.setHeader(CHAT_RUNTIME_HEADER_NAME, CHAT_RUNTIME_HEADER_VALUE);
};
const sendJson = (
req: IncomingMessage,
res: ServerResponse,
status: number,
payload: unknown,
) => {
setRuntimeHeader(res);
const origin = resolveRequestOrigin(req);
const hasCors = setCorsHeaders(res, origin);
if (origin && !hasCors) {
res.statusCode = 403;
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(JSON.stringify({ error: "Origin is not allowed." }));
return;
}
res.statusCode = status;
res.setHeader("Content-Type", "application/json; charset=utf-8");
res.end(JSON.stringify(payload));
};
const getRequestUrl = (req: IncomingMessage) => {
const host = req.headers.host ?? "localhost";
return new URL(req.url ?? "/", `http://${host}`);
};
const parseJsonBody = async <T>(req: IncomingMessage): Promise<T> => {
const chunks: Buffer[] = [];
let size = 0;
const maxBytes = 1024 * 1024; // 1MB
for await (const chunk of req) {
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
size += buffer.length;
if (size > maxBytes) {
throw new Error("Request body too large.");
}
chunks.push(buffer);
}
const body = Buffer.concat(chunks).toString("utf8");
return JSON.parse(body) as T;
};
const getHeaderValue = (
headers: IncomingMessage["headers"],
name: string,
): string | undefined => {
const raw = headers[name.toLowerCase()];
if (Array.isArray(raw)) {
return raw[0]?.trim() || undefined;
}
if (typeof raw === "string") {
const trimmed = raw.trim();
return trimmed.length > 0 ? trimmed : undefined;
}
return undefined;
};
const buildShareDbWsHeaders = (
headers: IncomingMessage["headers"],
): Record<string, string> => {
const out: Record<string, string> = {};
const cookie = getHeaderValue(headers, "cookie");
if (cookie) {
out.cookie = cookie;
}
const authorization = getHeaderValue(headers, "authorization");
if (authorization) {
out.authorization = authorization;
}
return out;
};
const getStringClaim = (payload: JwtPayloadLike, key: string) => {
const value = payload[key];
if (typeof value !== "string") return null;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
};
const isLikelyJwt = (token: string) => {
const parts = token.split(".");
return parts.length === 3 && parts.every((part) => part.length > 0);
};
const buildJwksUrls = () => {
const candidates = [
CHAT_AUTH_JWKS_URL,
`${AUTH_BASE_URL}/.well-known/jwks.json`,
`${AUTH_BASE_ORIGIN}/.well-known/jwks.json`,
];
const deduped = new Set<string>();
for (const candidate of candidates) {
if (!candidate) continue;
deduped.add(candidate.replace(/\/+$/, ""));
}
return [...deduped];
};
const verifyTokenViaVerifyJwtEndpoint = async (
token: string,
): Promise<JwtPayloadLike | null> => {
try {
const response = await fetch(`${AUTH_API_BASE}/verify-jwt`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ token }),
signal: AbortSignal.timeout(4000),
});
if (!response.ok) {
return null;
}
const payload = (await response.json().catch(() => null)) as {
payload?: JwtPayloadLike | null;
data?: { payload?: JwtPayloadLike | null };
} | null;
return payload?.payload ?? payload?.data?.payload ?? null;
} catch {
return null;
}
};
type SessionIntrospectionResult = {
user?: {
id?: string;
email?: string | null;
} | null;
session?: {
token?: string;
activeOrganizationId?: string | null;
} | null;
} | null;
type StopChatRunRequest = {
runId?: string;
threadId?: string;
};
const tryGetSessionFromCookieName = async (
cookieName: string,
token: string,
): Promise<SessionIntrospectionResult> => {
try {
const response = await fetch(`${AUTH_API_BASE}/get-session`, {
method: "GET",
headers: {
Cookie: `${cookieName}=${encodeURIComponent(token)}`,
},
signal: AbortSignal.timeout(4000),
});
if (!response.ok) {
return null;
}
const payload = (await response
.json()
.catch(() => null)) as SessionIntrospectionResult;
return payload;
} catch {
return null;
}
};
const verifyTokenViaSessionIntrospection = async (
token: string,
): Promise<AuthIdentity | null> => {
const cookieNames = [
"__Secure-better-auth.session_token",
"better-auth.session_token",
"__Secure-neon-auth.session_token",
"neon-auth.session_token",
"session_token",
] as const;
for (const cookieName of cookieNames) {
const sessionData = await tryGetSessionFromCookieName(cookieName, token);
const userId = sessionData?.user?.id?.trim();
if (!userId) {
continue;
}
const emailRaw = sessionData?.user?.email;
const email =
typeof emailRaw === "string" && emailRaw.trim().length > 0
? emailRaw.trim()
: null;
const activeOrganizationIdRaw = sessionData?.session?.activeOrganizationId;
const activeOrganizationId =
typeof activeOrganizationIdRaw === "string" &&
activeOrganizationIdRaw.trim().length > 0
? activeOrganizationIdRaw.trim()
: null;
return { userId, email, activeOrganizationId };
}
return null;
};
const verifyTokenViaJwks = async (
token: string,
): Promise<JwtPayloadLike | null> => {
const jose = await import("jose");
const jwksUrls = buildJwksUrls();
for (const jwksUrl of jwksUrls) {
try {
const jwkSet = jose.createRemoteJWKSet(new URL(jwksUrl));
const { payload } = await jose.jwtVerify(token, jwkSet, {
issuer: CHAT_AUTH_EXPECTED_ISSUER,
audience: CHAT_AUTH_EXPECTED_AUDIENCE,
});
return payload as JwtPayloadLike;
} catch {
continue;
}
}
return null;
};
const identityFromPayload = (payload: JwtPayloadLike): AuthIdentity | null => {
const userId =
getStringClaim(payload, "sub") ??
getStringClaim(payload, "userId") ??
getStringClaim(payload, "user_id") ??
getStringClaim(payload, "id");
if (!userId) return null;
const email =
getStringClaim(payload, "email") ??
getStringClaim(payload, "user_email") ??
null;
return { userId, email };
};
const verifyAuthToken = async (token: string): Promise<AuthIdentity | null> => {
const tokenLooksLikeJwt = isLikelyJwt(token);
if (tokenLooksLikeJwt) {
const payload =
(await verifyTokenViaJwks(token)) ??
(await verifyTokenViaVerifyJwtEndpoint(token));
if (payload) {
const identity = identityFromPayload(payload);
if (identity) {
return identity;
}
}
}
const sessionIdentity = await verifyTokenViaSessionIntrospection(token);
if (sessionIdentity) {
return sessionIdentity;
}
if (!tokenLooksLikeJwt) {
const payload = await verifyTokenViaVerifyJwtEndpoint(token);
if (!payload) {
return null;
}
return identityFromPayload(payload);
}
return null;
};
const getBearerToken = (authorizationHeader: string | undefined) => {
if (!authorizationHeader) return null;
const match = authorizationHeader.match(/^Bearer\s+(.+)$/i);
if (!match) return null;
const token = match[1]?.trim();
return token || null;
};
const parseCookies = (
cookieHeader: string | undefined,
): Map<string, string> => {
const cookies = new Map<string, string>();
if (!cookieHeader) return cookies;
for (const part of cookieHeader.split(";")) {
const [name, ...valueParts] = part.split("=");
const trimmedName = name?.trim();
if (!trimmedName) continue;
const value = valueParts.join("=").trim();
// Decode the cookie value (it may be URL-encoded)
try {
cookies.set(trimmedName, decodeURIComponent(value));
} catch {
cookies.set(trimmedName, value);
}
}
return cookies;
};
const getSessionTokenFromCookies = (
cookieHeader: string | undefined,
): string | null => {
const cookies = parseCookies(cookieHeader);
// Try different cookie names in order of preference
const cookieNames = [
"__Secure-better-auth.session_token",
"better-auth.session_token",
"__Secure-neon-auth.session_token",
"neon-auth.session_token",
"session_token",
];
for (const name of cookieNames) {
const value = cookies.get(name);
if (value && value.trim().length > 0) {
return value.trim();
}
}
return null;
};
const startSse = (req: IncomingMessage, res: ServerResponse) => {
setRuntimeHeader(res);
const origin = resolveRequestOrigin(req);
const hasCors = setCorsHeaders(res, origin);
if (origin && !hasCors) {
sendJson(req, res, 403, { error: "Origin is not allowed." });
return false;
}
res.statusCode = 200;
res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
res.setHeader("Cache-Control", "no-cache, no-transform");
res.setHeader("Connection", "keep-alive");
res.setHeader("Keep-Alive", "timeout=300");
res.setHeader("Content-Encoding", "identity");
res.setHeader("X-Accel-Buffering", "no");
res.flushHeaders?.();
return true;
};
const startSseHeartbeat = (res: ServerResponse) => {
if (CHAT_SSE_HEARTBEAT_INTERVAL_MS <= 0) {
return () => {};
}
const interval = setInterval(() => {
if (res.writableEnded || res.destroyed) {
return;
}
// SSE comment heartbeat to keep intermediaries from closing idle streams.
res.write(": keepalive\n\n");
}, CHAT_SSE_HEARTBEAT_INTERVAL_MS);
interval.unref?.();
return () => {
clearInterval(interval);
};
};
const writeSseEvent = (res: ServerResponse, event: unknown) => {
if (res.writableEnded || res.destroyed) {
return;
}
res.write(encodeChatStreamEvent(event as never));
};
const handleChatRequest = async (req: IncomingMessage, res: ServerResponse) => {
// Try Bearer token first, then fall back to session cookie
const bearerToken = getBearerToken(req.headers.authorization);
const sessionToken =
bearerToken ?? getSessionTokenFromCookies(req.headers.cookie);
if (!sessionToken) {
sendJson(req, res, 401, {
error: "Unauthorized. Bearer token or session cookie is required.",
});
return;
}
const identity = await verifyAuthToken(sessionToken);
if (!identity) {
sendJson(req, res, 401, {
error: "Unauthorized. Invalid or expired token.",
});
return;
}
let body: ChatRequestBody;
try {
body = await parseJsonBody<ChatRequestBody>(req);
} catch (error) {
sendJson(req, res, 400, {
error:
error instanceof Error ? error.message : "Invalid JSON request body.",
});
return;
}
// Mirror Vercel /api/chat behavior: enrich context with resolved user location.
const userLocation = resolveUserLocation({
acceptLanguage: getHeaderValue(req.headers, "accept-language"),
countryCode:
getHeaderValue(req.headers, "x-vercel-ip-country") ||
getHeaderValue(req.headers, "cf-ipcountry"),
timezone:
getHeaderValue(req.headers, "x-vercel-ip-timezone") ||
getHeaderValue(req.headers, "cf-timezone"),
});
const contextWithLocation = {
...(typeof body.context === "object" && body.context !== null
? body.context
: {}),
userLocation,
};
const resolved = resolveChatRequest(
{ ...body, context: contextWithLocation },
{
model: CHAT_MODEL,
provider: CHAT_PROVIDER,
reasoningEnabled: CHAT_REASONING_ENABLED,
},
);
if (!resolved.ok) {
sendJson(req, res, resolved.error.status, resolved.error.payload);
return;
}
const chatRequest = resolved.value;
const isAdmin = isAdminUser({ id: identity.userId, email: identity.email });
const organizationId =
identity.activeOrganizationId?.trim() ||
(await resolveActiveOrganizationIdForUser(identity.userId));
if (!organizationId) {
sendJson(req, res, 409, {
error: "No active organization. Create an organization first.",
onboardingUrl: "/onboarding/organization",
});
return;
}
const modelAccessCheck = await ensureChatModelAccess({
isAdmin,
organizationId,
model: chatRequest.model,
provider: chatRequest.provider,
});
if (!modelAccessCheck.ok) {
sendJson(req, res, modelAccessCheck.error.status, modelAccessCheck.error.payload);
return;
}
const creditCheck = await ensureChatRunCredits({
isAdmin,
userId: identity.userId,
organizationId,
threadId: chatRequest.threadId,
message: chatRequest.message,
});
if (!creditCheck.ok) {
sendJson(req, res, creditCheck.error.status, creditCheck.error.payload);
return;
}
const systemInstructions = await resolveRunSystemInstructions({
userId: identity.userId,
organizationId,
request: chatRequest,
defaultSystemInstructions: CHAT_SYSTEM_INSTRUCTIONS,
});
const runRequest = { ...chatRequest, systemInstructions };
if (!startSse(req, res)) {
return;
}
const stopHeartbeat = startSseHeartbeat(res);
const runAbortController = new AbortController();
let activeRunId: string | null = null;
const timeoutHandle = setTimeout(() => {
if (!runAbortController.signal.aborted) {
runAbortController.abort({
code: "SERVER_TIMEOUT",
timeoutMs: CHAT_SERVER_TIMEOUT_MS,
message: `Chat run exceeded server timeout (${Math.ceil(CHAT_SERVER_TIMEOUT_MS / 1000)}s).`,
} satisfies ChatAbortReason);
}
}, CHAT_SERVER_TIMEOUT_MS);
timeoutHandle.unref?.();
// Track if client disconnected - we'll stop writing but let the run complete
let clientDisconnected = false;
const onClientClose = () => {
clientDisconnected = true;
console.log(
"[render-chat-server] Client disconnected, run will continue in background",
);
};
req.on("close", onClientClose);
try {
await executeChatRunStream({
request: runRequest,
userId: identity.userId,
organizationId,
isAdmin,
shareDbWsHeaders: buildShareDbWsHeaders(req.headers),
persistEvents: true,
abortSignal: runAbortController.signal,
onRunCreated: (runId) => {
activeRunId = runId;
registerChatRunAbortController({
runId,
userId: identity.userId,
threadId: runRequest.threadId,
controller: runAbortController,
});
},
emitEvent: (event) => {
// Only write to response if client is still connected
if (!clientDisconnected && !res.writableEnded && !res.destroyed) {
writeSseEvent(res, event);
}
},
});
} finally {
stopHeartbeat();
clearTimeout(timeoutHandle);
if (activeRunId) {
unregisterChatRunAbortController({ runId: activeRunId });
}
req.off("close", onClientClose);
if (!res.writableEnded && !res.destroyed) {
res.end();
}
}
};
const handleStopRequest = async (req: IncomingMessage, res: ServerResponse) => {
// Try Bearer token first, then fall back to session cookie
const bearerToken = getBearerToken(req.headers.authorization);
const sessionToken =
bearerToken ?? getSessionTokenFromCookies(req.headers.cookie);
if (!sessionToken) {
sendJson(req, res, 401, {
error: "Unauthorized. Bearer token or session cookie is required.",
});
return;
}
const identity = await verifyAuthToken(sessionToken);
if (!identity) {
sendJson(req, res, 401, {
error: "Unauthorized. Invalid or expired token.",
});
return;
}
let body: StopChatRunRequest;
try {
body = await parseJsonBody<StopChatRunRequest>(req);
} catch (error) {
sendJson(req, res, 400, {
error:
error instanceof Error ? error.message : "Invalid JSON request body.",
});
return;
}
const runId = typeof body.runId === "string" ? body.runId.trim() : "";
const threadId =
typeof body.threadId === "string" ? body.threadId.trim() : "";
if (!runId && !threadId) {
sendJson(req, res, 400, {
error: "Either runId or threadId is required.",
});
return;
}
const reason = {
code: "CLIENT_ABORT" as const,
message: "Chat run stopped by user.",
};
const dbCancelResult = runId
? await requestChatRunCancel({
userId: identity.userId,
runId,
reason: reason.message,
})
: await requestThreadRunCancel({
userId: identity.userId,
threadId: threadId!,
reason: reason.message,
});
const abortRunId = dbCancelResult.runId || runId;
const abortThreadId = dbCancelResult.threadId || threadId;
const result = abortRunId
? abortRegisteredChatRun({
userId: identity.userId,
runId: abortRunId,
reason,
})
: abortThreadId
? abortRegisteredChatRun({
userId: identity.userId,
threadId: abortThreadId,
reason,
})
: { stopped: false as const };
sendJson(req, res, 200, {
success: true,
stopped: dbCancelResult.cancelled || result.stopped,
runId: dbCancelResult.runId ?? result.runId ?? null,
pending: false,
});
};
const handleResumeRequest = async (
req: IncomingMessage,
res: ServerResponse,
) => {
// Try Bearer token first, then fall back to session cookie
const bearerToken = getBearerToken(req.headers.authorization);
const sessionToken =
bearerToken ?? getSessionTokenFromCookies(req.headers.cookie);
if (!sessionToken) {
sendJson(req, res, 401, {
error: "Unauthorized. Bearer token or session cookie is required.",
});
return;
}
const identity = await verifyAuthToken(sessionToken);
if (!identity) {
sendJson(req, res, 401, {
error: "Unauthorized. Invalid or expired token.",
});
return;
}
const requestUrl = getRequestUrl(req);
const runId = requestUrl.searchParams.get("runId")?.trim();
const threadId = requestUrl.searchParams.get("threadId")?.trim();
const stream = requestUrl.searchParams.get("stream") === "true";
const lastEventIdParam = requestUrl.searchParams.get("lastEventId")?.trim();
const lastEventId = lastEventIdParam
? Number.parseInt(lastEventIdParam, 10)
: 0;
if (!runId && !threadId) {
sendJson(req, res, 400, {
error: "Either runId or threadId is required.",
});
return;
}
// Get the run record
let run = runId ? await getChatRun({ runId, userId: identity.userId }) : null;
// If no runId provided, get the latest run for the thread
if (!run && threadId) {
run = await getLatestChatRunForThread({
threadId,
userId: identity.userId,
});
}
if (!run) {
sendJson(req, res, 404, {
error: "Run not found.",
});
return;
}
// Non-streaming response (for initial check)
if (!stream) {
const events = await getChatRunEvents({
runId: run.runId,
afterEventId: lastEventId,
});
sendJson(req, res, 200, {
run: {
runId: run.runId,
threadId: run.threadId,
status: run.status,
startedAt: run.startedAt,
completedAt: run.completedAt,
errorMessage: run.errorMessage,
},
events: events.map((e) => ({
id: e.id,
type: e.eventType,
data: e.eventData,
})),
hasMore: run.status === "running",
});
return;
}
// Streaming response - replay events and continue streaming if still running
if (!startSse(req, res)) {
return;
}
const stopHeartbeat = startSseHeartbeat(res);
const currentRunId = run.runId;
const userId = identity.userId;
let currentLastEventId = lastEventId;
const maxIterations = Math.max(
1,
Math.ceil(CHAT_RESUME_MAX_STREAM_DURATION_MS / CHAT_RESUME_POLL_INTERVAL_MS),
);
const staleThresholdIterations = Math.max(
1,
Math.ceil(
CHAT_RESUME_STALE_CHECK_AFTER_IDLE_MS / CHAT_RESUME_POLL_INTERVAL_MS,
),
);
let iterations = 0;
let noNewEventsCount = 0;
let clientDisconnected = false;
req.on("close", () => {
clientDisconnected = true;
});
try {
while (iterations < maxIterations && !clientDisconnected) {
// Get new events
const events = await getChatRunEvents({
runId: currentRunId,
afterEventId: currentLastEventId,
});
// Stream each event
for (const event of events) {
if (clientDisconnected || res.writableEnded || res.destroyed) {
break;
}
res.write(encodeChatStreamEvent(event.eventData));
currentLastEventId = Math.max(currentLastEventId, event.id);
}
if (events.length > 0) {
noNewEventsCount = 0;
} else {
noNewEventsCount += 1;
}
// Check if run is complete
const updatedRun = await getChatRun({ runId: currentRunId, userId });
if (!updatedRun || updatedRun.status !== "running") {
break;
}
if (noNewEventsCount >= staleThresholdIterations) {
const stale = await isRunStale({