-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathroute.ts
More file actions
1594 lines (1430 loc) · 61.6 KB
/
Copy pathroute.ts
File metadata and controls
1594 lines (1430 loc) · 61.6 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 { NextResponse } from 'next/server';
import {
streamText,
convertToModelMessages,
UIMessage,
stepCountIs,
createUIMessageStream,
createUIMessageStreamResponse,
type LanguageModelUsage,
type TextUIPart,
type ToolSet,
} from 'ai';
import { getPageSpaceModelTier } from '@/lib/ai/core/ai-providers-config';
import { mergeToolSets } from '@/lib/ai/core/tool-utils';
import { incrementUsage, getCurrentUsage, getUserUsageSummary } from '@/lib/subscription/usage-service';
import { requiresProSubscription, createRateLimitResponse } from '@/lib/subscription/rate-limit-middleware';
import { broadcastUsageEvent } from '@/lib/websocket';
import { authenticateRequestWithOptions, isAuthError, checkMCPPageScope } from '@/lib/auth';
const AUTH_OPTIONS_READ = { allow: ['session', 'mcp'] as const, requireCSRF: false };
const AUTH_OPTIONS_WRITE = { allow: ['session', 'mcp'] as const, requireCSRF: true };
import { canUserViewPage, canUserEditPage, getActorInfo } from '@pagespace/lib/server';
import {
createAIProvider,
updateUserProviderSettings,
createProviderErrorResponse,
isProviderError,
type ProviderRequest,
getUserOpenRouterSettings,
getUserGoogleSettings,
getDefaultPageSpaceSettings,
getUserOpenAISettings,
getUserAnthropicSettings,
getUserXAISettings,
getUserOllamaSettings,
getUserLMStudioSettings,
getUserGLMSettings,
pageSpaceTools,
extractMessageContent,
extractToolCalls,
extractToolResults,
saveMessageToDatabase,
sanitizeMessagesForModel,
convertDbMessageToUIMessage,
processMentionsInMessage,
buildTimestampSystemPrompt,
buildSystemPrompt,
buildPersonalizationPrompt,
filterToolsForReadOnly,
filterToolsForWebSearch,
getPageTreeContext,
getModelCapabilities,
convertMCPToolsToAISDKSchemas,
parseMCPToolName,
sanitizeToolNamesForProvider,
getUserPersonalization,
} from '@/lib/ai/core';
import { db, users, chatMessages, pages, drives, eq, and } from '@pagespace/db';
import { createId } from '@paralleldrive/cuid2';
import { loggers, conversationCache, type CachedMessage } from '@pagespace/lib/server';
import { maskIdentifier } from '@/lib/logging/mask';
import { trackFeature } from '@pagespace/lib/activity-tracker';
import { AIMonitoring } from '@pagespace/lib/ai-monitoring';
import type { MCPTool } from '@/types/mcp';
import { getMCPBridge } from '@/lib/mcp';
import { applyPageMutation, PageRevisionMismatchError } from '@/services/api/page-mutation-service';
import {
createStreamAbortController,
removeStream,
STREAM_ID_HEADER,
} from '@/lib/ai/core/stream-abort-registry';
import { validateUserMessageFileParts, hasFileParts } from '@/lib/ai/core/validate-image-parts';
import { hasVisionCapability } from '@/lib/ai/core/model-capabilities';
import {
determineMessagesToInclude,
getContextWindowSize,
estimateSystemPromptTokens,
estimateToolDefinitionTokens,
} from '@pagespace/lib/ai-context-calculator';
import { isContextLengthError } from '@/lib/ai/shared/error-messages';
// Allow streaming responses up to 5 minutes for complex AI agent interactions
export const maxDuration = 300;
/**
* Next.js 15 compatible API route for AI chat
* Implements reliable persistence by saving user messages immediately
* Supports multi-provider architecture: OpenRouter and Google AI
*/
export async function POST(request: Request) {
const startTime = Date.now();
let userId: string | undefined;
let chatId: string | undefined;
let conversationId: string | undefined;
let selectedProvider: string | undefined;
let selectedModel: string | undefined;
let usagePromise: Promise<LanguageModelUsage | undefined> | undefined;
let wasTruncated = false;
const usageLogger = loggers.ai.child({ module: 'page-ai-usage' });
const permissionLogger = loggers.ai.child({ module: 'page-ai-permissions' });
try {
loggers.ai.info('AI Chat API: Starting request processing');
// Authenticate the request
const authResult = await authenticateRequestWithOptions(request, AUTH_OPTIONS_WRITE);
if (isAuthError(authResult)) {
loggers.ai.warn('AI Chat API: Authentication failed');
return authResult.error;
}
userId = authResult.userId;
loggers.ai.debug('AI Chat API: Authentication successful', { userId });
// Body size guard — reject payloads over 25MB before parsing
const contentLength = parseInt(request.headers.get('content-length') || '0', 10);
if (contentLength > 25 * 1024 * 1024) {
loggers.ai.warn('AI Chat API: Request body too large', { contentLength });
return NextResponse.json({ error: 'Request body too large (max 25MB)' }, { status: 413 });
}
// Parse request body for AI SDK v5 pattern
const requestBody = await request.json();
loggers.ai.debug('AI Chat API: Request body received', {
messageCount: requestBody.messages?.length || 0,
chatId: requestBody.chatId,
selectedProvider: requestBody.selectedProvider,
selectedModel: requestBody.selectedModel,
hasOpenRouterKey: !!requestBody.openRouterApiKey,
hasGoogleKey: !!requestBody.googleApiKey
});
const {
messages, // Used ONLY to extract new user message, NOT for conversation history
chatId: requestChatId, // chat ID (page ID) - standard AI SDK pattern
conversationId: requestConversationId, // Conversation session ID (auto-generated if not provided)
selectedProvider: requestSelectedProvider,
selectedModel: requestSelectedModel,
openRouterApiKey,
googleApiKey,
openAIApiKey,
anthropicApiKey,
xaiApiKey,
ollamaBaseUrl,
glmApiKey,
pageContext,
mcpTools, // MCP tool schemas from desktop client (optional)
isReadOnly, // Optional read-only mode toggle
webSearchEnabled, // Optional web search toggle (defaults to false)
}: {
messages: UIMessage[],
chatId?: string,
conversationId?: string, // Optional - will be auto-generated if not provided
selectedProvider?: string,
selectedModel?: string,
openRouterApiKey?: string,
googleApiKey?: string,
openAIApiKey?: string,
anthropicApiKey?: string,
xaiApiKey?: string,
ollamaBaseUrl?: string,
glmApiKey?: string,
mcpTools?: MCPTool[], // MCP tool schemas from desktop (client-side execution)
isReadOnly?: boolean, // Optional read-only mode toggle
webSearchEnabled?: boolean, // Optional web search toggle (defaults to false)
pageContext?: {
pageId: string,
pageTitle: string,
pageType: string,
pagePath: string,
parentPath: string,
breadcrumbs: string[],
driveId?: string,
driveName: string,
driveSlug: string,
}
} = requestBody;
// Assign to outer scope variables for error handling
chatId = requestChatId;
selectedProvider = requestSelectedProvider;
selectedModel = requestSelectedModel;
// For Page AI, we'll use custom agent configuration instead of fixed roles
// Global assistant will continue to use the role system
loggers.ai.debug('AI Page Chat API: Page AI using custom agent configuration');
// Validate required parameters
if (!messages || messages.length === 0) {
loggers.ai.warn('AI Chat API: No messages provided');
return NextResponse.json({ error: 'messages are required' }, { status: 400 });
}
if (!chatId) {
loggers.ai.warn('AI Chat API: No chatId provided');
return NextResponse.json({ error: 'chatId is required' }, { status: 400 });
}
const mcpScopeError = await checkMCPPageScope(authResult, chatId);
if (mcpScopeError) return mcpScopeError;
// Ensure userId and chatId are defined
if (!userId) {
loggers.ai.warn('AI Chat API: No userId after authentication');
return NextResponse.json({ error: 'Authentication failed' }, { status: 401 });
}
// Image security validation — validate file parts in the user message
const userMessageForValidation = messages[messages.length - 1];
const messageHasImages = userMessageForValidation?.role === 'user' && hasFileParts(userMessageForValidation);
if (messageHasImages) {
const imageValidation = validateUserMessageFileParts(userMessageForValidation);
if (!imageValidation.valid) {
loggers.ai.warn('AI Chat API: Image validation failed', { error: imageValidation.error });
return NextResponse.json({ error: imageValidation.error }, { status: 400 });
}
}
// Check if user has permission to view and edit this AI chat page
const maskedUserId = maskIdentifier(userId);
const maskedChatId = maskIdentifier(chatId);
permissionLogger.debug('Evaluating Page AI permissions', {
userId: maskedUserId,
chatId: maskedChatId,
});
const canView = await canUserViewPage(userId, chatId);
permissionLogger.debug('Page AI view permission evaluated', {
userId: maskedUserId,
chatId: maskedChatId,
allowed: canView,
});
if (!canView) {
loggers.ai.warn('AI Chat API: User lacks view permission', { userId: maskedUserId, chatId: maskedChatId });
permissionLogger.warn('Page AI view permission denied', {
userId: maskedUserId,
chatId: maskedChatId,
});
return NextResponse.json({ error: 'You do not have permission to view this AI chat' }, { status: 403 });
}
const canEdit = await canUserEditPage(userId, chatId);
permissionLogger.debug('Page AI edit permission evaluated', {
userId: maskedUserId,
chatId: maskedChatId,
allowed: canEdit,
});
if (!canEdit) {
loggers.ai.warn('AI Chat API: User lacks edit permission', { userId: maskedUserId, chatId: maskedChatId });
permissionLogger.warn('Page AI edit permission denied', {
userId: maskedUserId,
chatId: maskedChatId,
});
return NextResponse.json({ error: 'You do not have permission to send messages in this AI chat' }, { status: 403 });
}
permissionLogger.info('Page AI permissions granted', {
userId: maskedUserId,
chatId: maskedChatId,
});
loggers.ai.info('AI Chat API: Validation passed', {
messageCount: messages.length,
chatId
});
// Get page configuration for custom agent settings (needed early for message saving)
const [page] = await db.select().from(pages).where(eq(pages.id, chatId));
if (!page) {
loggers.ai.warn('AI Chat API: Page not found', { chatId });
return NextResponse.json({ error: 'Page not found' }, { status: 404 });
}
// Vision capability gate — reject images sent to non-vision models
if (messageHasImages) {
const effectiveModel = selectedModel || page.aiModel;
if (effectiveModel && !hasVisionCapability(effectiveModel)) {
loggers.ai.warn('AI Chat API: Images sent to non-vision model', { model: effectiveModel });
return NextResponse.json(
{ error: `The selected model "${effectiveModel}" does not support image attachments. Please choose a vision-capable model.` },
{ status: 400 }
);
}
}
// Extract custom agent configuration from page
const customSystemPrompt = page.systemPrompt;
const enabledTools = page.enabledTools as string[] | null;
// Fetch drive prompt if page has includeDrivePrompt enabled
let drivePromptPrefix = '';
if (page.includeDrivePrompt) {
try {
const [drive] = await db
.select({ drivePrompt: drives.drivePrompt })
.from(drives)
.where(eq(drives.id, page.driveId))
.limit(1);
if (drive?.drivePrompt?.trim()) {
drivePromptPrefix = `## DRIVE INSTRUCTIONS\n\n${drive.drivePrompt}\n\n---\n\n`;
loggers.ai.debug('AI Page Chat API: Including drive prompt', {
driveId: page.driveId,
promptLength: drive.drivePrompt.length
});
}
} catch (error) {
loggers.ai.error('AI Page Chat API: Failed to fetch drive prompt', error as Error);
// Continue without drive prompt on error
}
}
loggers.ai.debug('AI Page Chat API: Using custom agent configuration', {
hasCustomSystemPrompt: !!customSystemPrompt,
enabledToolsCount: enabledTools?.length || 0,
pageName: page.title,
includeDrivePrompt: page.includeDrivePrompt,
hasDrivePrompt: !!drivePromptPrefix
});
// Auto-generate conversationId if not provided (seamless UX)
conversationId = requestConversationId || createId();
loggers.ai.debug('AI Chat API: Conversation session', {
conversationId,
isNewConversation: !requestConversationId
});
// Process @mentions in the user's message
let mentionedPageIds: string[] = [];
// Save user's message immediately to database (database-first approach)
const userMessage = messages[messages.length - 1]; // Last message is the new user message
let userPromptContent: string | undefined;
if (userMessage && userMessage.role === 'user') {
try {
const messageId = userMessage.id || createId();
const messageContent = extractMessageContent(userMessage);
userPromptContent = messageContent;
// Process @mentions in the user message
const processedMessage = processMentionsInMessage(messageContent);
mentionedPageIds = processedMessage.pageIds;
if (processedMessage.mentions.length > 0) {
loggers.ai.info('AI Chat API: Found @mentions in user message', {
mentionCount: processedMessage.mentions.length,
pageIds: mentionedPageIds
});
}
loggers.ai.debug('AI Chat API: Saving user message immediately', { id: messageId, contentLength: messageContent.length });
await saveMessageToDatabase({
messageId,
pageId: chatId,
conversationId,
userId,
role: 'user',
content: messageContent,
toolCalls: undefined,
toolResults: undefined,
uiMessage: userMessage,
});
loggers.ai.debug('AI Chat API: User message saved to database');
} catch (error) {
loggers.ai.error('AI Chat API: Failed to save user message', error as Error);
return NextResponse.json({
error: 'Failed to save message to database',
details: error instanceof Error ? error.message : 'Unknown database error',
userMessage: userMessage // Preserve user input for retry
}, { status: 500 });
}
}
// Get user's current AI provider settings
const [user] = await db.select().from(users).where(eq(users.id, userId));
const currentProvider = selectedProvider || user?.currentAiProvider || 'pagespace';
const currentModel = selectedModel || user?.currentAiModel || 'glm-4.5-air';
// Pro subscription check for special providers
const { requiresProSubscription, createSubscriptionRequiredResponse } = await import('@/lib/subscription/rate-limit-middleware');
// Check if provider requires Pro subscription
if (requiresProSubscription(currentProvider, currentModel, user?.subscriptionTier)) {
loggers.ai.warn('AI Chat API: Pro subscription required', {
userId,
provider: currentProvider,
model: currentModel,
subscriptionTier: user?.subscriptionTier
});
return createSubscriptionRequiredResponse();
}
// Usage tracking will be handled in onFinish callback for PageSpace providers only
loggers.ai.debug('AI Chat API: Will track usage in onFinish for PageSpace providers', {
userId,
provider: currentProvider,
isPageSpaceProvider: currentProvider === 'pagespace'
});
// Update page's AI provider/model if changed
if (selectedProvider && selectedModel && chatId) {
if (selectedProvider !== page.aiProvider || selectedModel !== page.aiModel) {
try {
const actorInfo = await getActorInfo(userId);
await applyPageMutation({
pageId: chatId,
operation: 'agent_config_update',
updates: {
aiProvider: selectedProvider,
aiModel: selectedModel,
},
updatedFields: ['aiProvider', 'aiModel'],
expectedRevision: typeof page.revision === 'number' ? page.revision : undefined,
context: {
userId,
actorEmail: actorInfo.actorEmail,
actorDisplayName: actorInfo.actorDisplayName,
resourceType: 'agent',
},
});
} catch (error) {
if (error instanceof PageRevisionMismatchError) {
return NextResponse.json(
{
error: error.message,
currentRevision: error.currentRevision,
expectedRevision: error.expectedRevision,
},
{ status: error.expectedRevision === undefined ? 428 : 409 }
);
}
throw error;
}
}
}
// Create AI provider using factory service
const providerRequest: ProviderRequest = {
selectedProvider,
selectedModel,
googleApiKey,
openRouterApiKey,
openAIApiKey,
anthropicApiKey,
xaiApiKey,
ollamaBaseUrl,
glmApiKey,
};
const providerResult = await createAIProvider(userId, providerRequest);
if (isProviderError(providerResult)) {
return createProviderErrorResponse(providerResult);
}
const { model } = providerResult;
// Update user's current provider/model if changed
await updateUserProviderSettings(userId, selectedProvider, selectedModel);
// RATE LIMIT CHECK: Verify user has remaining quota BEFORE streaming
// This prevents users from exceeding their daily AI call limits
if (currentProvider === 'pagespace') {
const providerType = getPageSpaceModelTier(currentModel) ?? 'standard';
loggers.ai.debug('AI Chat API: Checking rate limit before streaming', {
userId: maskIdentifier(userId),
provider: currentProvider,
model: currentModel,
providerType,
pageId: chatId
});
const currentUsage = await getCurrentUsage(userId, providerType);
if (!currentUsage.success || currentUsage.remainingCalls <= 0) {
loggers.ai.warn('AI Chat API: Rate limit exceeded', {
userId: maskIdentifier(userId),
providerType,
currentCount: currentUsage.currentCount,
limit: currentUsage.limit,
remaining: currentUsage.remainingCalls,
pageId: chatId
});
return createRateLimitResponse(providerType, currentUsage.limit);
}
loggers.ai.debug('AI Chat API: Rate limit check passed', {
userId: maskIdentifier(userId),
providerType,
remaining: currentUsage.remainingCalls,
limit: currentUsage.limit,
pageId: chatId
});
}
// Parse read-only mode (defaults to false for full access)
const readOnlyMode = isReadOnly === true;
// Parse web search mode (defaults to false - disabled)
const webSearchMode = webSearchEnabled === true;
loggers.ai.debug('AI Page Chat API: Tool modes', { isReadOnly: readOnlyMode, webSearchEnabled: webSearchMode });
// Filter tools based on custom enabled tools configuration
// - null or [] = no tools enabled (default behavior)
// - ['tool1', 'tool2'] = specific tools → use only those
let filteredTools: ToolSet;
if (enabledTools === null || enabledTools.length === 0) {
// No tools configured - default to no tools
filteredTools = {};
loggers.ai.debug('AI Page Chat API: No tools enabled', {
totalTools: Object.keys(pageSpaceTools).length,
enabledTools: 0,
filteredTools: 0,
isReadOnly: readOnlyMode
});
} else {
// Filter tools based on the page's enabled tools configuration
// Simple object filtering approach to avoid complex TypeScript issues
const filtered: Record<string, (typeof pageSpaceTools)[keyof typeof pageSpaceTools]> = {};
for (const toolName of enabledTools) {
if (toolName in pageSpaceTools) {
filtered[toolName] = pageSpaceTools[toolName as keyof typeof pageSpaceTools];
}
}
// Apply read-only filtering on top of enabled tools
const postReadOnlyFiltered = filterToolsForReadOnly(filtered, readOnlyMode);
// Apply web search filtering (exclude web_search if disabled)
filteredTools = filterToolsForWebSearch(postReadOnlyFiltered, webSearchMode);
loggers.ai.debug('AI Page Chat API: Filtered tools based on page configuration', {
totalTools: Object.keys(pageSpaceTools).length,
enabledTools: enabledTools.length,
filteredTools: Object.keys(filteredTools).length,
isReadOnly: readOnlyMode,
webSearchEnabled: webSearchMode
});
}
// INTEGRATION TOOLS: Resolve and merge integration tools for this agent
try {
const { resolvePageAgentIntegrationTools } = await import('@/lib/ai/core/integration-tool-resolver');
const integrationTools = await resolvePageAgentIntegrationTools({
agentId: chatId,
userId,
driveId: page.driveId,
});
if (Object.keys(integrationTools).length > 0) {
filteredTools = mergeToolSets(filteredTools, integrationTools);
loggers.ai.info('AI Chat API: Merged integration tools', {
integrationToolCount: Object.keys(integrationTools).length,
totalTools: Object.keys(filteredTools).length,
});
}
} catch (error) {
loggers.ai.error('AI Chat API: Failed to resolve integration tools', error as Error);
}
// DESKTOP MCP INTEGRATION: Merge MCP tools from client if provided
if (mcpTools && mcpTools.length > 0) {
try {
loggers.ai.info('AI Chat API: Integrating MCP tools from desktop', {
mcpToolCount: mcpTools.length,
toolNames: mcpTools.map(t => `mcp:${t.serverName}:${t.name}`),
userId: maskIdentifier(userId),
chatId: maskIdentifier(chatId)
});
// Convert MCP tools to AI SDK format (schemas only, no execute functions)
const mcpToolSchemas = convertMCPToolsToAISDKSchemas(mcpTools);
// Create execute functions that signal client-side execution
// The AI SDK will call these, but we throw a special error that the client intercepts
const mcpToolsWithExecute: Record<string, unknown> = {};
for (const [toolName, toolSchema] of Object.entries(mcpToolSchemas)) {
mcpToolsWithExecute[toolName] = {
...toolSchema,
execute: async (args: Record<string, unknown>) => {
// Ensure userId is defined (it should be from authentication)
if (!userId) {
throw new Error('User ID not available for MCP tool execution');
}
// Parse tool name using shared parser (supports both mcp:server:tool and legacy mcp__server__tool)
const parsed = parseMCPToolName(toolName);
if (!parsed) {
loggers.ai.error('AI Chat API: Invalid MCP tool name format', {
toolName,
userId: maskIdentifier(userId)
});
throw new Error(`Invalid MCP tool name format: ${toolName}`);
}
const { serverName, toolName: actualToolName } = parsed;
loggers.ai.debug('AI Chat API: Executing MCP tool via WebSocket bridge', {
toolName: actualToolName,
serverName,
userId: maskIdentifier(userId),
hasArgs: !!args
});
try {
const mcpBridge = getMCPBridge();
// Check if user is connected
if (!mcpBridge.isUserConnected(userId)) {
const errorMsg = 'Desktop app not connected. Please ensure PageSpace Desktop is running.';
loggers.ai.warn('AI Chat API: User not connected to desktop', {
userId: maskIdentifier(userId),
toolName: actualToolName,
serverName
});
throw new Error(errorMsg);
}
// Execute tool via WebSocket bridge
const result = await mcpBridge.executeTool(
userId,
serverName,
actualToolName,
args
);
loggers.ai.info('AI Chat API: MCP tool execution succeeded', {
toolName: actualToolName,
serverName,
userId: maskIdentifier(userId)
});
return result;
} catch (error) {
loggers.ai.error('AI Chat API: MCP tool execution failed', error as Error, {
toolName: actualToolName,
serverName,
userId: maskIdentifier(userId)
});
throw error;
}
}
};
}
// Merge MCP tools with PageSpace tools, then sanitize for provider compatibility
// (many providers reject colons in tool names - sanitization converts mcp:server:tool to mcp__server__tool)
filteredTools = sanitizeToolNamesForProvider({ ...filteredTools, ...mcpToolsWithExecute } as Record<string, ToolSet[string]>) as ToolSet;
loggers.ai.info('AI Chat API: Successfully merged MCP tools', {
totalTools: Object.keys(filteredTools).length,
mcpTools: Object.keys(mcpToolSchemas).length,
pageSpaceTools: Object.keys(filteredTools).length - Object.keys(mcpToolSchemas).length
});
} catch (error) {
loggers.ai.error('AI Chat API: Failed to integrate MCP tools', error as Error, {
userId: maskIdentifier(userId),
chatId: maskIdentifier(chatId)
});
// Continue without MCP tools rather than failing the entire request
}
} else {
loggers.ai.debug('AI Chat API: No MCP tools provided in request', {
userId: maskIdentifier(userId),
chatId: maskIdentifier(chatId)
});
}
// DATABASE-FIRST ARCHITECTURE WITH CACHING:
// PageSpace uses database as the single source of truth for all messages.
// Cache provides fast reads while invalidation ensures consistency on edits/deletes.
loggers.ai.debug('AI Chat API: Loading conversation history', {
pageId: chatId
});
// Try cache first (L1 memory -> L2 Redis -> DB fallback)
// Note: chatId is guaranteed to be defined here due to earlier validation
const pageId = chatId as string;
let conversationHistory: UIMessage[];
const cachedConversation = await conversationCache.getConversation(pageId, conversationId);
if (cachedConversation) {
// Cache hit - convert cached messages to UI format
conversationHistory = cachedConversation.messages.map(msg =>
convertDbMessageToUIMessage({
id: msg.id,
pageId,
userId: null,
role: msg.role,
content: msg.content,
toolCalls: msg.toolCalls,
toolResults: msg.toolResults,
createdAt: new Date(msg.createdAt),
isActive: true,
editedAt: msg.editedAt ? new Date(msg.editedAt) : null,
})
);
loggers.ai.debug('AI Chat API: Loaded conversation from cache', {
messageCount: conversationHistory.length,
pageId
});
} else {
// Cache miss - read from database
const dbMessages = await db
.select()
.from(chatMessages)
.where(and(
eq(chatMessages.pageId, pageId),
eq(chatMessages.conversationId, conversationId),
eq(chatMessages.isActive, true)
))
.orderBy(chatMessages.createdAt);
// Convert database messages to UI format
conversationHistory = dbMessages.map(msg =>
convertDbMessageToUIMessage({
id: msg.id,
pageId: msg.pageId,
userId: msg.userId,
role: msg.role,
content: msg.content,
toolCalls: msg.toolCalls,
toolResults: msg.toolResults,
createdAt: msg.createdAt,
isActive: msg.isActive,
editedAt: msg.editedAt,
})
);
// Populate cache with DB results (fire-and-forget)
const messagesToCache: CachedMessage[] = dbMessages.map(msg => ({
id: msg.id,
role: msg.role as 'user' | 'assistant' | 'system',
content: msg.content ?? '',
toolCalls: (msg.toolCalls as string | null) ?? null,
toolResults: (msg.toolResults as string | null) ?? null,
createdAt: msg.createdAt.getTime(),
editedAt: msg.editedAt?.getTime() ?? null,
messageType: (msg.messageType as 'standard' | 'todo_list') ?? 'standard',
}));
conversationCache.setConversation(pageId, conversationId, messagesToCache).catch(err => {
loggers.ai.warn('Failed to populate conversation cache', { error: err });
});
loggers.ai.debug('AI Chat API: Loaded conversation from database', {
messageCount: conversationHistory.length,
pageId
});
}
// Sanitize messages to remove tool parts without results (prevents "input-available" state errors)
// NOTE: We use database-loaded messages, NOT messages from client
// modelMessages is computed after system prompt is built so we can apply context truncation
const sanitizedMessages = sanitizeMessagesForModel(conversationHistory);
// Fetch user personalization for AI system prompt injection
const personalization = await getUserPersonalization(userId);
if (personalization) {
loggers.ai.debug('AI Chat API: User personalization loaded', {
hasPersonalization: true,
hasBio: !!personalization.bio,
hasWritingStyle: !!personalization.writingStyle,
hasRules: !!personalization.rules,
});
}
// Build system prompt for Page AI - use custom system prompt if available, otherwise use default
let systemPrompt: string;
if (customSystemPrompt) {
// Use custom system prompt with page context injected
// Prepend drive prompt if enabled and available
systemPrompt = drivePromptPrefix + customSystemPrompt;
if (pageContext) {
systemPrompt += `\n\nYou are operating within the page "${pageContext.pageTitle}" in the "${pageContext.driveName}" drive. Your current location: ${pageContext.pagePath}`;
}
// Add user personalization if enabled
const personalizationPrompt = buildPersonalizationPrompt(personalization ?? undefined);
if (personalizationPrompt) {
systemPrompt += `\n\n${personalizationPrompt}`;
}
// Add read-only constraint if applicable
if (readOnlyMode) {
systemPrompt += `\n\nREAD-ONLY MODE:\n• You cannot modify, create, or delete any content\n• Focus on exploring, analyzing, and planning\n• Create actionable plans for the user to execute later`;
}
} else {
// Fallback to default PageSpace system prompt with read-only mode and personalization
systemPrompt = buildSystemPrompt(
'page',
pageContext ? {
driveName: pageContext.driveName,
driveSlug: pageContext.driveSlug,
driveId: pageContext.driveId,
pagePath: pageContext.pagePath,
pageType: pageContext.pageType,
breadcrumbs: pageContext.breadcrumbs,
} : undefined,
readOnlyMode,
personalization ?? undefined
);
}
// Build timestamp system prompt for temporal awareness
const userTimezone = user?.timezone ?? undefined;
const timestampSystemPrompt = buildTimestampSystemPrompt(userTimezone);
// Build page tree context if enabled
let pageTreePrompt = '';
if (page.includePageTree && page.driveId) {
const pageTreeContext = await getPageTreeContext(userId, {
scope: (page.pageTreeScope as 'children' | 'drive') || 'children',
pageId: chatId,
driveId: page.driveId,
});
if (pageTreeContext) {
pageTreePrompt = `\n\n## WORKSPACE STRUCTURE\n\nHere is the ${page.pageTreeScope === 'drive' ? 'complete workspace' : 'page subtree'} structure:\n\n${pageTreeContext}`;
loggers.ai.debug('AI Chat API: Page tree context included', {
pageId: chatId,
scope: page.pageTreeScope,
contextLength: pageTreeContext.length
});
}
}
loggers.ai.debug('AI Chat API: Tools configured for Page AI', { toolCount: Object.keys(filteredTools).length });
// Context-length guard: proactively truncate oldest messages to fit within the model's context window.
// This prevents AI_APICallError from providers when a conversation grows too long.
// We build modelMessages here (after system prompt) so we have accurate token budgeting.
const fullSystemPrompt = systemPrompt + timestampSystemPrompt + pageTreePrompt;
const contextWindow = getContextWindowSize(currentModel, currentProvider);
const systemPromptTokens = estimateSystemPromptTokens(fullSystemPrompt);
// Cast needed because filteredTools is a ToolSet (Vercel AI SDK type) but calculator expects plain object
const toolTokens = estimateToolDefinitionTokens(filteredTools as Record<string, unknown>);
// Reserve 25% headroom for output tokens and tokenizer inaccuracies
const inputBudget = Math.floor(contextWindow * 0.75);
const truncationResult = determineMessagesToInclude(
sanitizedMessages,
inputBudget,
systemPromptTokens,
toolTokens
);
const { includedMessages } = truncationResult;
wasTruncated = truncationResult.wasTruncated;
if (wasTruncated) {
loggers.ai.warn('AI Chat API: Conversation truncated to fit context window', {
originalMessageCount: sanitizedMessages.length,
includedMessageCount: includedMessages.length,
model: currentModel,
provider: currentProvider,
contextWindow,
inputBudget,
systemPromptTokens,
toolTokens,
});
}
// Guard: if truncation left zero messages, the system prompt + tools alone exceed the budget.
// Sending an empty conversation to the model would produce a meaningless response or error.
if (includedMessages.length === 0) {
loggers.ai.error('AI Chat API: Context budget exhausted by system prompt and tools alone', {
model: currentModel,
provider: currentProvider,
contextWindow,
inputBudget,
systemPromptTokens,
toolTokens,
});
return NextResponse.json(
{
error: 'context_length_exceeded',
message: 'The system configuration (prompts and tools) exceeds this model\'s context window. Please switch to a model with a larger context window.',
details: 'context_length_exceeded',
},
{ status: 413 }
);
}
const modelMessages = convertToModelMessages(includedMessages as UIMessage[], {
tools: filteredTools // Use original tools - no wrapping needed
});
loggers.ai.info('AI Chat API: Starting streamText for Page AI', { model: currentModel, pageName: page.title });
// Create UI message stream with visual content injection support
// This handles the case where tools return visual content that needs to be injected into the stream
let result;
// Generate server-side message ID for the AI response
// This ensures client and server use the same ID, fixing the undo-after-streaming issue
// See: https://ai-sdk.dev/docs/ai-sdk-ui/chatbot-message-persistence
const serverAssistantMessageId = createId();
// Create abort controller for explicit user-initiated stop (via /api/ai/abort endpoint)
// This is separate from request.signal which fires on any client disconnect
const { streamId, signal: abortSignal } = createStreamAbortController({ userId });
try {
const stream = createUIMessageStream({
originalMessages: sanitizedMessages,
execute: async ({ writer }) => {
let startChunkSent = false;
// Send the server-generated message ID to the client at stream start
// streamId is passed via X-Stream-Id header (see result.toUIMessageStreamResponse below)
// Wrapped in try/catch to handle early disconnect - continue processing anyway
try {
writer.write({
type: 'start',
messageId: serverAssistantMessageId,
});
startChunkSent = true;
} catch {
// Client disconnected before first write - continue processing
// to ensure onFinish fires and the message is saved
}
// Start the AI response
const aiResult = streamText({
model,
system: systemPrompt + timestampSystemPrompt + pageTreePrompt,
messages: modelMessages,
tools: filteredTools, // Use original tools directly
stopWhen: stepCountIs(100), // Allow up to 100 tool calls per conversation turn
abortSignal, // From registry - only aborts on explicit user stop, not client disconnect
experimental_context: {
userId,
timezone: userTimezone,
aiProvider: currentProvider,
aiModel: currentModel,
conversationId,
locationContext: pageContext ? {
currentPage: {
id: pageContext.pageId,
title: pageContext.pageTitle,
type: pageContext.pageType,
path: pageContext.pagePath,
},
currentDrive: pageContext.driveId ? {
id: pageContext.driveId,
name: pageContext.driveName,
slug: pageContext.driveSlug,
} : undefined,
breadcrumbs: pageContext.breadcrumbs,
} : undefined,
modelCapabilities: await getModelCapabilities(currentModel, currentProvider),
chatSource: {
type: 'page' as const,
agentPageId: chatId,
agentTitle: page.title,
},
}, // Pass userId, timezone, AI context, location context, model capabilities, and chat source to tools
maxRetries: 20, // Increase from default 2 to 20 for better handling of rate limits
onAbort: () => {
loggers.ai.info('AI Chat API: Stream aborted by user', {
userId: maskIdentifier(userId!),
pageId: chatId,
streamId,
model: currentModel,
provider: currentProvider,
});
},
});
usagePromise = aiResult.totalUsage
.then((usage) => usage)
.catch((error) => {
loggers.ai.debug('AI Chat API: Failed to retrieve token usage from stream', {
error: error instanceof Error ? error.message : 'Unknown error',
});
return undefined;
});
// Stream the AI response directly to the client
// Wrap in try-catch to handle client disconnection gracefully - the AI stream
// will continue processing server-side even if writes fail
for await (const chunk of aiResult.toUIMessageStream()) {
try {
// We already emitted a start chunk with a server-controlled message ID.
// Skip any additional start chunks so client/server message IDs stay aligned.
if (chunk.type === 'start') {
if (startChunkSent) {
continue;
}
writer.write({
type: 'start',
messageId: serverAssistantMessageId,
});
startChunkSent = true;
continue;
}
writer.write(chunk);
} catch {
// Client disconnected - continue processing to ensure onFinish fires
// and the message is saved to the database
}
}