Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
1683 lines (1454 loc) · 62.1 KB
/
Copy pathserver.js
File metadata and controls
1683 lines (1454 loc) · 62.1 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
require("dotenv").config();
const express = require("express");
const multer = require("multer");
const pdfParse = require("pdf-parse");
const mammoth = require("mammoth");
const crypto = require("crypto");
const fs = require("fs/promises");
const path = require("path");
const mcpClient = require("./mcpClient");
const logger = require("./logger");
const app = express();
const PORT = process.env.PORT || 3000;
const ROOT = __dirname;
const STORAGE_DIR = path.join(ROOT, "storage");
const UPLOAD_DIR = path.join(STORAGE_DIR, "uploads");
const NOTES_PATH = path.join(STORAGE_DIR, "notes.json");
const SECRETS_PATH = path.join(STORAGE_DIR, "provider-secrets.json");
// In-memory cache to avoid repeated disk reads
let cachedNotes = [];
let cachedSecrets = {};
async function initInMemoryCache() {
await ensureStorage();
try {
const raw = await fs.readFile(NOTES_PATH, "utf8");
cachedNotes = JSON.parse(raw);
} catch (e) {
cachedNotes = [];
}
try {
const raw = await fs.readFile(SECRETS_PATH, "utf8");
cachedSecrets = JSON.parse(raw);
} catch (e) {
cachedSecrets = {};
}
}
const upload = multer({
storage: multer.memoryStorage(),
limits: {
files: 10,
fileSize: 20 * 1024 * 1024
}
});
const STOP_WORDS = new Set([
"about", "after", "again", "against", "all", "also", "an", "and", "any", "are", "because", "been",
"before", "being", "between", "both", "but", "can", "could", "did", "does", "doing", "during", "each",
"few", "for", "from", "further", "had", "has", "have", "having", "her", "here", "hers", "him", "himself",
"his", "how", "into", "its", "itself", "just", "more", "most", "not", "now", "off", "once", "only", "other",
"our", "ours", "ourselves", "out", "over", "same", "should", "some", "such", "than", "that", "the", "their",
"theirs", "them", "themselves", "then", "there", "these", "they", "this", "those", "through", "under", "until",
"very", "was", "were", "what", "when", "where", "which", "while", "who", "will", "with", "would", "your",
"yours", "yourself", "yourselves"
]);
app.use(express.json({ limit: "25mb" }));
app.use(express.urlencoded({ extended: true }));
// CORS & static serving
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
if (req.method === "OPTIONS") {
res.status(204).end();
return;
}
next();
});
app.use(express.static(ROOT));
// ─── Routes ────────────────────────────────────────────────────────────────────
app.get("/api/health", async (_req, res) => {
try {
await ensureStorage();
res.json({ ok: true, mcpOnline: mcpClient.isOnline() });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get("/api/system-accounts", async (req, res) => {
const fssync = require("fs");
const pathlib = require("path");
const { execSync } = require("child_process");
const accounts = [];
const osUser = process.env.USERNAME || "Google User";
// 1. Try Git global config
try {
const gitEmail = execSync("git config --global user.email", { encoding: "utf8" }).trim();
const gitName = execSync("git config --global user.name", { encoding: "utf8" }).trim();
let displayName = gitName;
if (!displayName || displayName === "mrpunithvenkatsain47139" || /\d/.test(displayName)) {
displayName = osUser;
}
if (gitEmail && gitEmail.includes("@")) {
accounts.push({ name: displayName || "Git User", email: gitEmail });
}
} catch (e) { /* ignore */ }
// 2. Scan Google Chrome profiles
const localAppData = process.env.LOCALAPPDATA;
if (localAppData) {
const chromeDir = pathlib.join(localAppData, "Google", "Chrome", "User Data");
if (fssync.existsSync(chromeDir)) {
const profiles = [
"Default", "Profile 1", "Profile 2", "Profile 3", "Profile 4",
"Profile 5", "Profile 6", "Profile 7", "Profile 8", "Profile 9",
"Profile 10", "Profile 11", "Profile 12", "Profile 13", "Profile 14"
];
profiles.forEach(p => {
const prefPath = pathlib.join(chromeDir, p, "Preferences");
if (fssync.existsSync(prefPath)) {
try {
const json = JSON.parse(fssync.readFileSync(prefPath, "utf8"));
let email = null;
let name = null;
if (json.google && json.google.services && json.google.services.username) {
email = json.google.services.username;
}
if (json.profile && json.profile.name) name = json.profile.name;
if (email && email.includes("@")) {
accounts.push({ name: name || osUser, email });
}
} catch (e) {}
}
});
const defaultPref = pathlib.join(chromeDir, "Default", "Preferences");
if (fssync.existsSync(defaultPref)) {
try {
const json = JSON.parse(fssync.readFileSync(defaultPref, "utf8"));
if (json.profile && json.profile.info_cache) {
Object.keys(json.profile.info_cache).forEach(key => {
const item = json.profile.info_cache[key];
if (item.user_name && item.user_name.includes("@")) {
accounts.push({
name: item.name || item.given_name || osUser,
email: item.user_name
});
}
});
}
} catch (e) {}
}
}
}
// De-duplicate case-insensitively
const uniqueMap = new Map();
accounts.forEach(acc => {
const key = acc.email.toLowerCase().trim();
if (!uniqueMap.has(key)) {
uniqueMap.set(key, acc);
}
});
res.json(Array.from(uniqueMap.values()));
});
app.get("/api/files", async (_req, res) => {
try {
const notes = await readNotes();
res.json({ notes: notes.map(stripNoteForClient) });
} catch (error) {
console.error("Get files error:", error);
res.status(500).json({ error: error.message });
}
});
app.post("/api/files/upload", upload.array("files", 10), async (req, res) => {
try {
await ensureStorage();
if (!req.files || req.files.length === 0) {
res.status(400).json({ error: "No files were uploaded." });
return;
}
const existingNotes = await readNotes();
const uploaded = [];
let apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
const secrets = await readSecrets();
apiKey = secrets.gemini;
}
for (const file of req.files) {
const id = crypto.randomUUID();
const extension = path.extname(file.originalname) || guessExtension(file.mimetype);
const savedName = `${id}${extension}`;
const absoluteFilePath = path.join(UPLOAD_DIR, savedName);
await fs.writeFile(absoluteFilePath, file.buffer);
const extractedText = await extractText(file);
const analysis = analyzeText(extractedText, file.originalname);
let quizzes = analysis.quizzes;
if (apiKey) {
try {
console.log(`Generating AI quizzes for note: ${file.originalname}`);
const aiQuizzes = await generateQuizzesWithAI(extractedText, file.originalname, apiKey);
if (aiQuizzes && aiQuizzes.length > 0) {
quizzes = aiQuizzes;
}
} catch (err) {
console.error(`Failed to generate AI quizzes for ${file.originalname}, falling back to local extractor:`, err);
}
}
const note = {
id,
name: file.originalname,
size: file.size,
mimeType: file.mimetype,
createdAt: new Date().toISOString(),
storedFile: savedName,
extractedText,
summary: analysis.summary,
topics: analysis.topics,
dates: analysis.dates,
snippets: analysis.snippets,
quizzes
};
// Index chunks to Elasticsearch via MCP if online
if (mcpClient.isOnline()) {
const notesIndex = getScopedIndexName("notes", req);
const chunks = note.snippets || splitIntoChunks(extractedText);
logger.logAgentDecision("Uploading document chunks to Elastic via MCP", {
filename: file.originalname,
chunksCount: chunks.length,
index: notesIndex
});
for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
const chunkText = chunks[chunkIndex];
const chunkDoc = {
filename: file.originalname,
uploadTimestamp: note.createdAt,
documentType: file.mimetype,
chunkId: `${id}-chunk-${chunkIndex}`,
content: chunkText,
topicLabels: note.topics || [],
userId: req.headers["x-user-uid"] || "global",
noteId: id
};
await indexDocumentMCP(notesIndex, chunkDoc, `${id}-chunk-${chunkIndex}`);
}
}
existingNotes.unshift(note);
uploaded.push(stripNoteForClient(note));
}
await writeNotes(existingNotes);
res.status(201).json({ notes: uploaded });
} catch (error) {
console.error("Upload error:", error);
res.status(500).json({ error: "Failed to upload files: " + error.message });
}
});
app.post("/api/notes/index", async (req, res) => {
try {
const note = req.body;
if (!note || !note.id) {
return res.status(400).json({ error: "Note object is required." });
}
// Index chunks to Elasticsearch via MCP if online
if (mcpClient.isOnline()) {
const notesIndex = getScopedIndexName("notes", req);
const chunks = note.snippets || splitIntoChunks(note.extractedText || "");
logger.logAgentDecision("Indexing document chunks to Elastic via MCP (Firebase bridge)", {
filename: note.name,
chunksCount: chunks.length,
index: notesIndex
});
for (let chunkIndex = 0; chunkIndex < chunks.length; chunkIndex++) {
const chunkText = chunks[chunkIndex];
const chunkDoc = {
filename: note.name,
uploadTimestamp: note.createdAt || new Date().toISOString(),
documentType: note.mimeType || "text/plain",
chunkId: `${note.id}-chunk-${chunkIndex}`,
content: chunkText,
topicLabels: note.topics || [],
userId: req.headers["x-user-uid"] || "global",
noteId: note.id
};
await indexDocumentMCP(notesIndex, chunkDoc, `${note.id}-chunk-${chunkIndex}`);
}
}
res.json({ ok: true });
} catch (error) {
logger.logError("Failed to index note via bridge", error);
res.status(500).json({ error: error.message });
}
});
app.delete("/api/files/:id", async (req, res) => {
try {
await ensureStorage();
const notes = await readNotes();
const noteIndex = notes.findIndex((note) => note.id === req.params.id);
if (noteIndex === -1) {
res.status(404).json({ error: "Note not found." });
return;
}
const [note] = notes.splice(noteIndex, 1);
const absoluteFilePath = path.join(UPLOAD_DIR, note.storedFile);
await fs.rm(absoluteFilePath, { force: true });
await writeNotes(notes);
// Delete note chunks from Elasticsearch via MCP
if (mcpClient.isOnline()) {
const notesIndex = getScopedIndexName("notes", req);
try {
await mcpClient.callTool("delete_by_query", {
index: notesIndex,
query: {
match: {
noteId: req.params.id
}
}
});
logger.logAgentDecision("Deleted note chunks from Elasticsearch", { noteId: req.params.id, index: notesIndex });
} catch (err) {
logger.logError(`Failed to delete note chunks from index ${notesIndex}`, err);
}
}
res.json({ ok: true });
} catch (error) {
console.error("Delete note error:", error);
res.status(500).json({ error: "Failed to delete note: " + error.message });
}
});
app.post("/api/ask", async (req, res) => {
try {
await ensureStorage();
const question = String(req.body.question || "").trim();
const noteIds = Array.isArray(req.body.noteIds) ? req.body.noteIds.map(String) : [];
const depth = String(req.body.depth || "balanced").trim();
if (!question) {
res.status(400).json({ error: "Question is required." });
return;
}
const notes = await readNotes();
const selectedNotes = noteIds.length > 0 ? notes.filter((note) => noteIds.includes(note.id)) : notes;
if (selectedNotes.length === 0) {
res.status(400).json({ error: "Upload and select at least one note first." });
return;
}
let relevantChunks = [];
let isMcpUsed = false;
if (mcpClient.isOnline()) {
const notesIndex = getScopedIndexName("notes", req);
const startTime = Date.now();
logger.logAgentDecision("Attempting Elastic MCP search for grounding context", { question, index: notesIndex });
const esResults = await searchDocumentsMCP(notesIndex, question, ["content"], 8);
if (esResults && esResults.length > 0) {
relevantChunks = esResults.map((doc) => ({
noteId: doc.noteId || "mcp-note",
noteName: doc.filename || "Note",
chunk: doc.content || doc.chunk || "",
score: 1
}));
isMcpUsed = true;
logger.logRetrievalPerformance("search_documents", Date.now() - startTime, esResults.length);
}
}
if (!isMcpUsed) {
logger.logAgentDecision("Falling back to local note chunk retrieval engine", { question });
relevantChunks = retrieveRelevantChunks(question, selectedNotes);
}
const citations = buildCitations(relevantChunks, selectedNotes);
let apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
const secrets = await readSecrets();
apiKey = secrets.gemini;
}
let answer = "";
let provider = "Local grounded mode";
let model = "local-grounded";
let mode = "local";
if (apiKey) {
provider = "Gemini Answering (AI Mode)";
mode = "gemini-api";
const eligibleModels = await getEligibleModels(apiKey);
let success = false;
let lastError = null;
for (const currentModel of eligibleModels) {
try {
console.log(`Attempting backend Gemini call with model: ${currentModel}`);
answer = await callGeminiBackend(question, relevantChunks, apiKey, depth, currentModel);
model = currentModel;
success = true;
break;
} catch (err) {
console.error(`Gemini call failed for model ${currentModel}: ${err.message}`);
lastError = err;
continue;
}
}
if (!success) {
console.error("All Gemini backend model attempts failed, falling back to local synthesis.");
model = "local-fallback";
answer = `[AI Answering failed for all models. Last error: ${lastError ? lastError.message : "Unknown error"}]. Falling back to local synthesis:\n\n` +
localGroundedAnswer(question, selectedNotes, relevantChunks, depth);
}
} else {
answer = localGroundedAnswer(question, selectedNotes, relevantChunks, depth);
}
res.json({ answer, citations, provider, model, mode });
} catch (error) {
console.error("Ask query error:", error);
res.status(500).json({ error: "Failed to process research query: " + error.message });
}
});
app.post("/api/plan/generate", async (req, res) => {
try {
await ensureStorage();
const prompt = String(req.body.prompt || "").trim();
const noteIds = Array.isArray(req.body.noteIds) ? req.body.noteIds.map(String) : [];
const calendarEvents = Array.isArray(req.body.calendarEvents) ? req.body.calendarEvents : [];
const isReplan = !!req.body.isReplan;
const todayStr = String(req.body.todayStr || "").trim();
if (!prompt) {
res.status(400).json({ error: "Planner prompt is required." });
return;
}
const notes = await readNotes();
const selectedNotes = noteIds.length > 0 ? notes.filter((note) => noteIds.includes(note.id)) : notes;
let notesSummary = "";
let isMcpUsed = false;
if (mcpClient.isOnline()) {
const notesIndex = getScopedIndexName("notes", req);
const searchQuery = prompt || selectedNotes.map(n => n.name).join(" ");
const startTime = Date.now();
logger.logAgentDecision("Attempting Elastic MCP search for planner grounding", { searchQuery, index: notesIndex });
const esResults = await searchDocumentsMCP(notesIndex, searchQuery, ["content"], 10);
if (esResults && esResults.length > 0) {
notesSummary = esResults.map(doc => {
return `Note Name: ${doc.filename || "Study Material"}\nContent Chunk: ${doc.content || ""}\nTopics: ${(doc.topicLabels || []).join(", ")}`;
}).join("\n\n");
isMcpUsed = true;
logger.logRetrievalPerformance("search_documents (planner)", Date.now() - startTime, esResults.length);
}
}
if (!isMcpUsed) {
logger.logAgentDecision("Falling back to local note configurations for study planner", { noteIds });
notesSummary = selectedNotes.map((note) => {
return `Note Name: ${note.name}\nSummary: ${note.summary || "No summary available."}\nTopics: ${(note.topics || []).join(", ") || "No topics extracted."}\nDates: ${(note.dates || []).join(", ") || "None"}`;
}).join("\n\n");
}
const calendarSummary = calendarEvents.map(e => `- ${e.title} on ${e.day} from ${e.start} to ${e.end}`).join("\n");
let apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
const secrets = await readSecrets();
apiKey = secrets.gemini;
}
let plan = [];
let provider = "Local planner fallback";
let model = "local-grounded";
if (apiKey) {
provider = "Gemini Planner (AI Mode)";
const eligibleModels = await getEligibleModels(apiKey);
let success = false;
let lastError = null;
for (const currentModel of eligibleModels) {
try {
console.log(`Attempting backend Gemini planner call with model: ${currentModel}`);
const rawResponse = await callGeminiPlannerBackend(prompt, notesSummary, calendarSummary, apiKey, currentModel, isReplan, todayStr);
let cleanedText = rawResponse.trim();
if (cleanedText.startsWith("```")) {
cleanedText = cleanedText.replace(/^```[a-zA-Z]*\n/, "").replace(/\n```$/, "");
}
cleanedText = cleanedText.trim();
plan = JSON.parse(cleanedText);
model = currentModel;
success = true;
break;
} catch (err) {
console.error(`Gemini planner call failed for model ${currentModel}: ${err.message}`);
lastError = err;
continue;
}
}
if (!success) {
throw lastError || new Error("Failed to generate plan with Gemini");
}
} else {
throw new Error("No Gemini API key configured on backend.");
}
res.json({ plan, provider, model });
} catch (error) {
console.error("Plan generate query error:", error);
res.status(500).json({ error: "Failed to generate study plan: " + error.message });
}
});
app.post("/api/calendar/parse", async (req, res) => {
try {
await ensureStorage();
const text = String(req.body.text || "").trim();
if (!text) {
res.status(400).json({ error: "Calendar text is required." });
return;
}
let apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
const secrets = await readSecrets();
apiKey = secrets.gemini;
}
let events = [];
if (apiKey) {
const eligibleModels = await getEligibleModels(apiKey);
let success = false;
let lastError = null;
const prompt = `Analyze the following schedule text and extract all planned events.
Format them as a JSON array of objects, where each object represents an event with the following fields:
- "title": Concise event title (e.g., "Chemistry Lab")
- "day": The day of the week (e.g., "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
- "start": Start time in 24-hour HH:MM format (e.g., "14:00")
- "end": End time in 24-hour HH:MM format (e.g., "16:00")
- "color": A hex color string for the event (use standard Google colors: "#1a73e8" for blue, "#ea4335" for red, "#fbbc05" for yellow, "#34a853" for green)
If no duration/end time is specified, assume the event lasts 1 hour.
Respond ONLY with the raw JSON array. Do not include markdown formatting or explanations.
Schedule Text:
"""
${text}
"""`;
for (const currentModel of eligibleModels) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 20000);
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${currentModel}:generateContent?key=${apiKey}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: { temperature: 0.1 }
}),
signal: controller.signal
});
clearTimeout(timeoutId);
const data = await response.json();
if (!response.ok) {
throw new Error(data.error?.message || "Gemini API call failed");
}
const rawResponse = data.candidates?.[0]?.content?.parts?.[0]?.text || "[]";
let cleanedText = rawResponse.trim();
if (cleanedText.startsWith("```")) {
cleanedText = cleanedText.replace(/^```[a-zA-Z]*\n/, "").replace(/\n```$/, "");
}
cleanedText = cleanedText.trim();
events = JSON.parse(cleanedText);
success = true;
break;
} catch (err) {
console.error(`Calendar parsing failed with model ${currentModel}: ${err.message}`);
lastError = err;
continue;
}
}
if (!success) throw lastError || new Error("Failed to parse calendar text with Gemini");
} else {
throw new Error("No Gemini API key configured on backend.");
}
res.json({ events });
} catch (error) {
console.error("Calendar parse error:", error);
res.status(500).json({ error: "Failed to parse calendar schedule: " + error.message });
}
});
app.post("/api/quiz", async (req, res) => {
try {
await ensureStorage();
const noteIds = Array.isArray(req.body.noteIds) ? req.body.noteIds.map(String) : [];
const notes = await readNotes();
const selectedNotes = noteIds.length > 0 ? notes.filter((note) => noteIds.includes(note.id)) : notes;
let allQuizzes = [];
for (const note of selectedNotes) {
if (note.quizzes && note.quizzes.length > 0) {
allQuizzes.push(...note.quizzes);
}
}
allQuizzes.sort(() => Math.random() - 0.5);
res.json({ quizzes: allQuizzes });
} catch (error) {
console.error("Quiz generation error:", error);
res.status(500).json({ error: "Failed to generate quiz: " + error.message });
}
});
app.post("/api/quiz/generate", async (req, res) => {
try {
await ensureStorage();
const noteIds = Array.isArray(req.body.noteIds) ? req.body.noteIds.map(String) : [];
const prompt = String(req.body.prompt || "").trim();
const notes = await readNotes();
const selectedNotes = noteIds.length > 0 ? notes.filter((note) => noteIds.includes(note.id)) : notes;
if (selectedNotes.length === 0) {
res.status(400).json({ error: "Select at least one note first." });
return;
}
let combinedText = "";
let isMcpUsed = false;
if (mcpClient.isOnline()) {
const notesIndex = getScopedIndexName("notes", req);
const searchQuery = prompt || selectedNotes.map(n => n.name).join(" ");
const startTime = Date.now();
logger.logAgentDecision("Attempting Elastic MCP search for quiz generation grounding", { searchQuery, index: notesIndex });
const esResults = await searchDocumentsMCP(notesIndex, searchQuery, ["content"], 15);
if (esResults && esResults.length > 0) {
combinedText = esResults.map(doc => `[Source Document: ${doc.filename}]\n${doc.content || ""}`).join("\n\n");
isMcpUsed = true;
logger.logRetrievalPerformance("search_documents (quiz generation)", Date.now() - startTime, esResults.length);
}
}
if (!isMcpUsed) {
logger.logAgentDecision("Falling back to local notes text consolidation for quiz generation", { noteIds });
combinedText = selectedNotes.map(n => `[Document: ${n.name}]\n${n.extractedText || ""}`).join("\n\n");
}
let apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
const secrets = await readSecrets();
apiKey = secrets.gemini;
}
let quizzes = [];
if (apiKey) {
console.log(`Generating custom AI quiz using ${isMcpUsed ? "Elastic MCP retrieved context" : "local text consolidation"}`);
quizzes = await generateQuizzesWithAIAndPrompt(combinedText, prompt, apiKey);
} else {
let allQuizzes = [];
for (const note of selectedNotes) {
if (note.quizzes && note.quizzes.length > 0) {
allQuizzes.push(...note.quizzes);
} else {
allQuizzes.push(...extractQuizzesFromText(note.extractedText || "", note.name));
}
}
if (prompt) {
const terms = prompt.toLowerCase().split(/\s+/).filter(t => t.length > 2);
if (terms.length > 0) {
allQuizzes = allQuizzes.filter(q => {
const text = (q.question + " " + q.answer).toLowerCase();
return terms.some(t => text.includes(t));
});
}
}
quizzes = allQuizzes;
}
quizzes.sort(() => Math.random() - 0.5);
res.json({ quizzes });
} catch (error) {
console.error("Custom quiz generation error:", error);
res.status(500).json({ error: "Failed to generate custom quiz: " + error.message });
}
});
app.get("/api/config/gemini", async (_req, res) => {
try {
let apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) {
const secrets = await readSecrets();
apiKey = secrets.gemini;
}
res.json({ configured: !!apiKey });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post("/api/config/gemini", async (req, res) => {
try {
const { apiKey } = req.body;
const secrets = await readSecrets();
secrets.gemini = String(apiKey || "").trim();
await writeSecrets(secrets);
res.json({ ok: true });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get("/api/memory", async (req, res) => {
try {
const memoryIndex = getScopedIndexName("memory", req);
if (mcpClient.isOnline()) {
try {
const response = await mcpClient.callTool("get_document", {
index: memoryIndex,
id: "agent_memory"
});
if (response && response.content && Array.isArray(response.content)) {
const textPart = response.content.find(c => c.type === "text");
if (textPart) {
const data = JSON.parse(textPart.text);
const source = data._source || data.document || data;
return res.json(source);
}
}
} catch (err) {
logger.logAgentDecision("No existing memory found in Elastic", { error: err.message });
}
}
res.json({});
} catch (error) {
logger.logError("Failed to get memory", error);
res.status(500).json({ error: error.message });
}
});
app.post("/api/memory", async (req, res) => {
try {
const memoryIndex = getScopedIndexName("memory", req);
const memoryData = req.body || {};
if (mcpClient.isOnline()) {
const success = await indexDocumentMCP(memoryIndex, memoryData, "agent_memory");
if (success) {
return res.json({ ok: true });
}
}
res.json({ ok: true, status: "Local storage only" });
} catch (error) {
logger.logError("Failed to save memory", error);
res.status(500).json({ error: error.message });
}
});
// ─── Server Start ───────────────────────────────────────────────────────────────
app.listen(PORT, async () => {
await initInMemoryCache();
console.log(`Cortexa listening on http://localhost:${PORT}`);
// Initialize Elastic MCP Client
mcpClient.init().catch(err => {
logger.logError("Failed to initialize Elastic MCP", err);
});
});
// ─── Storage Helpers ────────────────────────────────────────────────────────────
async function ensureStorage() {
await fs.mkdir(UPLOAD_DIR, { recursive: true });
try {
await fs.access(NOTES_PATH);
} catch {
await fs.writeFile(NOTES_PATH, "[]", "utf8");
}
try {
await fs.access(SECRETS_PATH);
} catch {
await fs.writeFile(SECRETS_PATH, "{}", "utf8");
}
}
async function readNotes() {
return cachedNotes;
}
async function writeNotes(notes) {
cachedNotes = notes;
fs.writeFile(NOTES_PATH, JSON.stringify(notes, null, 2), "utf8").catch(() => {});
}
async function readSecrets() {
const secrets = { ...cachedSecrets };
if (!secrets.gemini) {
secrets.gemini = "AIzaSyDyLMOIOr7gx8EKPZQOrKg4nKkVlNJC4QA";
}
return secrets;
}
async function writeSecrets(secrets) {
cachedSecrets = secrets;
fs.writeFile(SECRETS_PATH, JSON.stringify(secrets, null, 2), "utf8").catch(() => {});
}
// ─── Gemini Helpers ─────────────────────────────────────────────────────────────
async function getEligibleModels(apiKey) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models?key=${apiKey}`, {
signal: controller.signal
});
clearTimeout(timeoutId);
const fallbackList = ["gemini-1.5-flash", "gemini-1.5-pro"];
if (!response.ok) return fallbackList;
const data = await response.json();
if (!data.models || !Array.isArray(data.models)) return fallbackList;
const eligibleModels = data.models.filter(m =>
m.supportedGenerationMethods &&
m.supportedGenerationMethods.includes("generateContent")
);
if (eligibleModels.length === 0) return fallbackList;
const modelNames = eligibleModels.map(m => m.name.replace(/^models\//, ""));
const preferences = [
"gemini-2.5-flash",
"gemini-2.0-flash",
"gemini-1.5-flash",
"gemini-1.5-flash-8b",
"gemini-1.5-pro",
"gemini-2.0-pro"
];
const result = [];
for (const pref of preferences) {
if (modelNames.includes(pref)) result.push(pref);
}
for (const name of modelNames) {
if (!result.includes(name)) result.push(name);
}
return result.length > 0 ? result : fallbackList;
} catch (err) {
console.error("Failed to list models, using fallback list:", err);
return ["gemini-1.5-flash", "gemini-1.5-pro"];
}
}
async function callGeminiBackend(question, relevantChunks, apiKey, depth, model = "gemini-1.5-flash") {
const context = relevantChunks
.map((item, index) => `[Source ${index + 1}: ${item.noteName || "Note"}]\n${item.chunk || ""}`)
.join("\n\n");
const prompt = `You are Cortexa, an intelligent study assistant.
Your goal is to explain concepts clearly, analyze the user's notes, and spoon-feed the explanation to the user based on the selected response depth: "${depth}".
Please use the following grounding context from the user's notes to formulate your answer:
---
${context}
---
User Question: ${question}
Instructions:
1. Ground your answer in the provided notes.
2. If the notes do not have enough information, explain what is missing but still provide a helpful, accurate concept explanation.
3. Structure your response in a neat, clean format using Markdown.
4. Render all mathematical equations and formulas in LaTeX notation (using $ for inline and $$ for display blocks, e.g. $\\Delta G = \\Delta H - T\\Delta S$).
5. Format the depth of your explanation as follows:
- "brief": A short, direct 1-2 sentence definition or summary.
- "balanced": A clear, structured explanation with key points and formulas.
- "deep": An in-depth, comprehensive concept analysis explaining the core principles, detailing equations, and giving illustrative examples.
6. Make the tone encouraging, clear, and easy to understand (like spoon-feeding a student). Do not just copy-paste the context; analyze and explain it.`;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 15000);
try {
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
contents: [{ parts: [{ text: prompt }] }],
generationConfig: { temperature: 0.3 }
}),
signal: controller.signal
});
clearTimeout(timeoutId);
const data = await response.json();
if (!response.ok) throw new Error(data.error?.message || "Gemini API call failed");
return data.candidates?.[0]?.content?.parts?.[0]?.text || "No response returned.";
} catch (error) {
clearTimeout(timeoutId);
if (error.name === "AbortError") {
throw new Error("Request to Gemini API timed out after 15 seconds. Please try again.");
}
throw error;
}
}
async function callGeminiPlannerBackend(prompt, notesSummary, calendarSummary, apiKey, model = "gemini-1.5-flash", isReplan = false, todayStr = "") {
if (!todayStr) {
const today = new Date();
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
todayStr = today.toLocaleDateString('en-US', options);
}
let replanInstruction = "";
if (isReplan) {
replanInstruction = `\nCRITICAL REPLAN REQUIREMENT: The user has requested to REPLAN their week.
Please evaluate the user's prompt and note topics to generate a restructured, highly optimized, and comfortable study schedule.
Make it well-spaced across the days and completely resolve any calendar overlaps by moving study sessions to the most comfortable open slots (typically in the late afternoon/evening hours, e.g., 16:00 - 22:00).`;
}
const systemPrompt = `You are Cortexa, an intelligent study planning assistant.
Your goal is to parse the user's study planning query, analyze their notes, check their Google Calendar events, and generate a customized study schedule.
Here are the user's notes:
${notesSummary}
Here is the user's current Google Calendar schedule of events (avoid scheduling study blocks during these times):
${calendarSummary || "No calendar events scheduled."}
User Planning Request: "${prompt}"
${replanInstruction}
Instructions:
1. Generate a structured daily study plan that spans the appropriate days (e.g., next 7 days or matching the user's request).
2. Propose 3 to 7 study blocks depending on the user's request. Each block should have:
- "day": The calendar date formatted precisely as "Weekday, Month DD" (e.g., "Wednesday, Jun 10", "Thursday, Jun 11"). All planned study blocks must start from today (${todayStr}) or subsequent days sequentially.
- "start": The start time in 24-hour format (e.g. "18:30")
- "duration": The duration in minutes (e.g. 45)
- "title": A concise, descriptive study block title (e.g. "Thermodynamics Unit 3 review")
- "copy": A helpful description of what to focus on, referencing concepts from the notes (e.g. "Focus on entropy definitions and spontaneity rules.").
3. Do NOT schedule any block that overlaps with the user's Google Calendar events.
4. Try to distribute the study blocks realistically throughout the week (typically in the late afternoon or evening, e.g. between 15:00 and 22:00, unless the prompt asks for something else).
5. Respond ONLY with a valid JSON array of objects representing the study blocks. Do not add any markdown formatting (like \`\`\`json), explanations, or trailing text. Just return the raw JSON array.
Example Response:
[
{
"day": "Wednesday, Jun 10",
"start": "18:30",
"duration": 45,
"title": "Thermodynamics Unit 3 deep review",
"copy": "Focus on entropy definitions and spontaneity rules."
}
]`;