-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
854 lines (780 loc) · 34.4 KB
/
server.js
File metadata and controls
854 lines (780 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
const express = require('express');
const { spawn } = require('child_process');
const fs = require('fs');
const path = require('path');
const os = require('os');
const { validatePythonSyntax, validateJavaSyntax } = require('./framework-validation');
const app = express();
const port = Number(process.env.PORT || 3000);
const OLLAMA_URL = process.env.OLLAMA_URL || 'http://localhost:11434';
const LMSTUDIO_URL = process.env.LMSTUDIO_URL || 'http://127.0.0.1:1234';
const LMSTUDIO_API_KEY = process.env.LMSTUDIO_API_KEY || '';
// Allow overriding the temporary working directory (useful when root FS is read-only)
const BASE_TMP_DIR = (process.env.RUN_TMP_DIR && process.env.RUN_TMP_DIR.trim()) || os.tmpdir();
// Utility: best-effort Python executable resolution across OSes
function resolvePythonCmd() {
// Allow override
if (process.env.PYTHON_BIN) {
const bin = process.env.PYTHON_BIN.trim();
if (bin.length > 0) return { cmd: bin, args: [] };
}
if (process.platform === 'win32') {
// Prefer Python launcher for Windows
return { cmd: 'py', args: ['-3'] };
}
// Linux/macOS commonly have python3; fallback to python
return { cmd: 'python3', args: [] };
}
// Safety limits
const MAX_CODE_SIZE_BYTES = 100 * 1024; // 100KB per request body
const MAX_EXECUTION_MS = 10_000; // 10 seconds per run
// Middleware to parse JSON
// Limit request body to reduce risk of memory abuse
app.use(express.json({ limit: '100kb' }));
// ----------------------
// Small helpers (DRY up chat endpoints, streaming headers, etc.)
// ----------------------
function toText(parts) {
return Array.isArray(parts) ? parts.map(p => (p && (p.text || ''))).join('\n') : '';
}
function normalizeChatHistory(history) {
return (history || [])
.map(m => ({
role: m.role === 'model' ? 'assistant' : (m.role || 'user'),
content: toText(m.parts)
}))
.filter(m => m.content && m.content.trim().length > 0);
}
function setStreamHeaders(res) {
res.setHeader('Content-Type', 'text/plain; charset=utf-8');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
}
// ----------------------
// Lessons storage (SQLite with JSON fallback)
// ----------------------
const { openDb, ensureSchema, seedFromJsonIfEmpty, seedFromJsonFiles, replaceFromJsonFiles, getLessons, countLessons, getLessonsPage, getLessonById } = require('./db');
const DATA_DIR = process.env.DATA_DIR || process.env.DB_DIR || (process.platform === 'win32' ? path.join(process.cwd(), 'data') : '/data');
const DB_FILE = process.env.DB_FILE || path.join(DATA_DIR, 'app.db');
const LESSONS_MODE = (process.env.LESSONS_MODE || 'replace');
const LESSONS_UPSERT_ON_START = (() => {
const v = String(process.env.LESSONS_UPSERT_ON_START || '').trim().toLowerCase();
return v === '1' || v === 'true' || v === 'yes';
})();
const LESSONS_REPLACE_ON_START = (() => {
const v = String(process.env.LESSONS_REPLACE_ON_START || '').trim().toLowerCase();
return v === '1' || v === 'true' || v === 'yes';
})();
let lessonsDb = null;
try {
lessonsDb = openDb(DB_FILE);
if (lessonsDb) {
ensureSchema(lessonsDb);
// Safe, idempotent seed from JSON if empty
seedFromJsonIfEmpty(lessonsDb, { publicDir: path.join(process.cwd(), 'public') });
// Optional: reflect JSON on boot either by replace (wipe+seed) or upsert
if (LESSONS_REPLACE_ON_START) {
try {
console.log('[lessons] Replacing lessons from JSON files...');
const result = replaceFromJsonFiles(lessonsDb, { publicDir: path.join(process.cwd(), 'public') });
console.log('[lessons] Replaced', result.count, 'lessons');
} catch (e) {
console.error('[lessons] Failed to replace from JSON:', e.message);
}
} else if (LESSONS_UPSERT_ON_START) {
try { seedFromJsonFiles(lessonsDb, { publicDir: path.join(process.cwd(), 'public') }); } catch (_) {}
}
}
} catch (e) {
console.error('[lessons] Database initialization failed:', e.message);
lessonsDb = null;
}
function lessonsStorageInfo() {
return {
storage: lessonsDb ? 'sqlite' : 'json',
dbFile: lessonsDb ? DB_FILE : null,
dataDir: DATA_DIR,
mode: LESSONS_MODE,
upsertOnStart: LESSONS_UPSERT_ON_START,
replaceOnStart: LESSONS_REPLACE_ON_START,
};
}
// Startup visibility so users can tell which storage is active
try {
const info = lessonsStorageInfo();
if (info.storage === 'sqlite') {
console.log(`[lessons] storage=sqlite db=${info.dbFile} mode=${info.mode} replaceOnStart=${info.replaceOnStart} upsertOnStart=${info.upsertOnStart}`);
} else {
console.log(`[lessons] storage=json (fallback to public/*.json) mode=${info.mode} replaceOnStart=${info.replaceOnStart} upsertOnStart=${info.upsertOnStart}`);
}
} catch (_) { /* ignore logging errors */ }
function readJsonSafe(absPath) {
try {
return JSON.parse(fs.readFileSync(absPath, 'utf8'));
} catch (_) {
return null;
}
}
function clampInt(n, min, max, dflt) {
const x = Number(n);
if (!Number.isFinite(x)) return dflt;
return Math.max(min, Math.min(max, x | 0));
}
// Serve lessons from DB if available; otherwise fall back to public JSON files
app.get('/lessons-java.json', (req, res) => {
try {
if (lessonsDb) {
const items = getLessons(lessonsDb, 'java');
if (items && items.length > 0) {
return res.json({ mode: LESSONS_MODE, lessons: items });
}
}
const fallback = readJsonSafe(path.join(__dirname, 'public', 'lessons-java.json'));
if (fallback) return res.json(fallback);
res.status(404).json({ error: 'No Java lessons found' });
} catch (err) {
res.status(500).json({ error: 'Failed to load Java lessons', details: err.message });
}
});
app.get('/lessons-python.json', (req, res) => {
try {
if (lessonsDb) {
const items = getLessons(lessonsDb, 'python');
if (items && items.length > 0) {
return res.json({ mode: LESSONS_MODE, lessons: items });
}
}
const fallback = readJsonSafe(path.join(__dirname, 'public', 'lessons-python.json'));
if (fallback) return res.json(fallback);
res.status(404).json({ error: 'No Python lessons found' });
} catch (err) {
res.status(500).json({ error: 'Failed to load Python lessons', details: err.message });
}
});
// Inspect active lessons storage mode (sqlite vs json) and paths
app.get('/lessons/storage', (req, res) => {
try {
return res.json(lessonsStorageInfo());
} catch (err) {
return res.status(500).json({ error: 'Failed to get storage info', details: err && err.message });
}
});
// Combined lessons endpoint removed to avoid accidental duplication on the client.
// ----------------------
// Scalable Lessons API (pagination + detail)
// ----------------------
app.get('/api/lessons', (req, res) => {
try {
const lang = String(req.query.lang || '').toLowerCase();
if (!['java', 'python'].includes(lang)) {
return res.status(400).json({ error: 'Invalid lang. Use java or python' });
}
const offset = clampInt(req.query.offset, 0, 1_000_000, 0);
const limit = clampInt(req.query.limit, 1, 5000, 200);
const fields = (String(req.query.fields || 'summary').toLowerCase() === 'full') ? 'full' : 'summary';
const q = String(req.query.q || '').trim();
if (lessonsDb) {
const total = countLessons(lessonsDb, lang, q);
const items = getLessonsPage(lessonsDb, lang, { offset, limit, fields, q });
return res.json({ meta: { total, offset, limit, fields, lang }, items });
}
// JSON fallback
const fallback = readJsonSafe(path.join(__dirname, 'public', `lessons-${lang}.json`));
const all = Array.isArray(fallback) ? fallback : (fallback && Array.isArray(fallback.lessons) ? fallback.lessons : []);
if (!all || all.length === 0) {
return res.json({ meta: { total: 0, offset, limit, fields, lang }, items: [] });
}
const filtered = q ? all.filter(l => {
try {
const hay = `${l.title || ''} ${l.description || ''}`.toLowerCase();
return hay.includes(q.toLowerCase());
} catch { return true; }
}) : all;
const total = filtered.length;
const slice = filtered.slice(offset, offset + limit);
const items = (fields === 'summary')
? slice.map(l => ({ id: l.id, language: (l.language || lang), title: l.title, description: l.description || '' }))
: slice;
return res.json({ meta: { total, offset, limit, fields, lang }, items });
} catch (err) {
return res.status(500).json({ error: 'Failed to list lessons', details: err && err.message });
}
});
app.get('/api/lessons/:lang/:id', (req, res) => {
try {
const lang = String(req.params.lang || '').toLowerCase();
const id = Number(req.params.id);
if (!['java', 'python'].includes(lang) || !Number.isFinite(id)) {
return res.status(400).json({ error: 'Invalid lang or id' });
}
if (lessonsDb) {
const item = getLessonById(lessonsDb, lang, id);
if (!item) return res.status(404).json({ error: 'Lesson not found' });
return res.json({ item });
}
// JSON fallback
const fallback = readJsonSafe(path.join(__dirname, 'public', `lessons-${lang}.json`));
const all = Array.isArray(fallback) ? fallback : (fallback && Array.isArray(fallback.lessons) ? fallback.lessons : []);
const item = (all || []).find(l => Number(l.id) === id);
if (!item) return res.status(404).json({ error: 'Lesson not found' });
return res.json({ item });
} catch (err) {
return res.status(500).json({ error: 'Failed to get lesson', details: err && err.message });
}
});
// ----------------------
// Ollama integration
// ----------------------
// List available local Ollama models
app.get('/ollama/models', async (req, res) => {
try {
const resp = await fetch(`${OLLAMA_URL}/api/tags`);
if (!resp.ok) {
return res.status(resp.status).json({ error: `Ollama responded with ${resp.status}` });
}
const data = await resp.json();
const models = (data.models || []).map(m => ({
name: m.name,
modified_at: m.modified_at,
size: m.size,
digest: m.digest,
details: m.details || {}
}));
res.json({ models });
} catch (err) {
res.status(500).json({ error: 'Failed to contact Ollama', details: err.message });
}
});
// ----------------------
// LM Studio integration (OpenAI-compatible)
// ----------------------
// List available LM Studio models (maps to OpenAI /v1/models)
app.get('/lmstudio/models', async (req, res) => {
try {
const resp = await fetch(`${LMSTUDIO_URL}/v1/models`, {
headers: LMSTUDIO_API_KEY ? { Authorization: `Bearer ${LMSTUDIO_API_KEY}` } : undefined,
});
if (!resp.ok) {
return res.status(resp.status).json({ error: `LM Studio responded with ${resp.status}` });
}
const data = await resp.json();
const models = (data.data || []).map(m => ({ name: m.id }));
res.json({ models });
} catch (err) {
res.status(500).json({ error: 'Failed to contact LM Studio', details: err.message });
}
});
// Chat with a selected LM Studio model (OpenAI chat.completions)
app.post('/lmstudio/chat', async (req, res) => {
const { model, history } = req.body || {};
if (!model) return res.status(400).json({ error: 'Missing model' });
const messages = normalizeChatHistory(history);
try {
const headers = { 'Content-Type': 'application/json' };
if (LMSTUDIO_API_KEY) headers['Authorization'] = `Bearer ${LMSTUDIO_API_KEY}`;
const resp = await fetch(`${LMSTUDIO_URL}/v1/chat/completions`, {
method: 'POST',
headers,
body: JSON.stringify({
model,
messages,
stream: false
})
});
if (!resp.ok) {
const text = await resp.text().catch(() => '');
return res.status(resp.status).json({ error: `LM Studio chat error ${resp.status}`, details: text });
}
const data = await resp.json();
const choice = data && data.choices && data.choices[0];
const msg = choice && choice.message;
const reasoning = (msg && (msg.reasoning || msg.thinking)) || (choice && (choice.reasoning || choice.thinking)) || '';
const content = (msg && msg.content) || '';
const text = (reasoning ? `<think>${reasoning}</think>` : '') + content;
res.json({ text });
} catch (err) {
res.status(500).json({ error: 'Failed to reach LM Studio chat', details: err.message });
}
});
// Streaming chat proxy for LM Studio (sends raw text chunks)
app.post('/lmstudio/chat/stream', async (req, res) => {
const { model, history } = req.body || {};
if (!model) return res.status(400).json({ error: 'Missing model' });
const messages = normalizeChatHistory(history);
const headers = { 'Content-Type': 'application/json' };
if (LMSTUDIO_API_KEY) headers['Authorization'] = `Bearer ${LMSTUDIO_API_KEY}`;
let controller;
try {
controller = new AbortController();
const upstream = await fetch(`${LMSTUDIO_URL}/v1/chat/completions`, {
method: 'POST',
headers,
body: JSON.stringify({ model, messages, stream: true }),
signal: controller.signal,
});
if (!upstream.ok || !upstream.body) {
const text = await upstream.text().catch(() => '');
return res.status(upstream.status || 500).json({ error: `LM Studio chat error ${upstream.status}`, details: text });
}
setStreamHeaders(res);
const decoder = new TextDecoder();
let buffer = '';
let thinkOpen = false;
let clientAborted = false;
req.on('close', () => {
clientAborted = true;
try { controller.abort(); } catch (_) {}
});
const reader = upstream.body.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) break;
if (clientAborted) break;
buffer += decoder.decode(value, { stream: true });
// Parse SSE lines like: "data: {json}\n\n" or partial lines
let idx;
while ((idx = buffer.indexOf('\n')) !== -1) {
const lineRaw = buffer.slice(0, idx);
buffer = buffer.slice(idx + 1);
const line = lineRaw.trimEnd();
if (!line) continue;
if (line.startsWith('data: ')) {
const dataStr = line.slice(6).trim();
if (dataStr === '[DONE]') {
if (thinkOpen) { try { controller.abort(); } catch (_) {} try { res.write('</think>'); } catch (_) {} }
res.end();
return;
}
try {
const obj = JSON.parse(dataStr);
const choice = obj && obj.choices && obj.choices[0];
const delta = choice && choice.delta;
const reasonChunk = delta && (delta.reasoning || delta.reasoning_content || delta.thinking);
const textChunk = (delta && delta.content) || (choice && choice.text) || '';
if (reasonChunk && String(reasonChunk).length > 0) {
if (!thinkOpen) { try { res.write('<think>'); } catch (_) {} thinkOpen = true; }
try { res.write(String(reasonChunk)); } catch (_) {}
}
if (textChunk && String(textChunk).length > 0) {
if (thinkOpen) { try { res.write('</think>'); } catch (_) {} thinkOpen = false; }
try { res.write(String(textChunk)); } catch (_) {}
}
} catch (_) {
// ignore JSON parse errors on partial lines
}
}
}
}
// Flush any remaining content if present
if (buffer.trim().length > 0) {
// Try to parse last line
const line = buffer.trim();
if (line.startsWith('data: ')) {
const dataStr = line.slice(6).trim();
if (dataStr !== '[DONE]') {
try {
const obj = JSON.parse(dataStr);
const choice = obj && obj.choices && obj.choices[0];
const delta = choice && choice.delta;
const reasonChunk = delta && (delta.reasoning || delta.reasoning_content || delta.thinking);
const textChunk = (delta && delta.content) || (choice && choice.text) || '';
if (reasonChunk && String(reasonChunk).length > 0) {
if (!thinkOpen) { try { res.write('<think>'); } catch (_) {} thinkOpen = true; }
try { res.write(String(reasonChunk)); } catch (_) {}
}
if (textChunk && String(textChunk).length > 0) {
if (thinkOpen) { try { res.write('</think>'); } catch (_) {} thinkOpen = false; }
try { res.write(String(textChunk)); } catch (_) {}
}
} catch (_) { /* ignore */ }
}
}
}
if (thinkOpen) { try { res.write('</think>'); } catch (_) {} }
res.end();
} catch (err) {
if (!res.headersSent) {
res.status(500).json({ error: 'Failed to stream from LM Studio', details: err.message });
} else {
try { res.end(); } catch (_) {}
}
}
});
// Streaming chat proxy for Ollama (NDJSON lines)
app.post('/ollama/chat/stream', async (req, res) => {
const { model, history } = req.body || {};
if (!model) return res.status(400).json({ error: 'Missing model' });
const messages = normalizeChatHistory(history);
let controller;
try {
controller = new AbortController();
const upstream = await fetch(`${OLLAMA_URL}/api/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model, messages, stream: true }),
signal: controller.signal,
});
if (!upstream.ok || !upstream.body) {
const text = await upstream.text().catch(() => '');
return res.status(upstream.status || 500).json({ error: `Ollama chat error ${upstream.status}`, details: text });
}
setStreamHeaders(res);
const decoder = new TextDecoder();
let buffer = '';
let thinkOpen = false;
let clientAborted = false;
req.on('close', () => {
clientAborted = true;
try { controller.abort(); } catch (_) {}
});
const reader = upstream.body.getReader();
while (true) {
const { value, done } = await reader.read();
if (done) break;
if (clientAborted) break;
buffer += decoder.decode(value, { stream: true });
let idx;
while ((idx = buffer.indexOf('\n')) !== -1) {
const line = buffer.slice(0, idx).trim();
buffer = buffer.slice(idx + 1);
if (!line) continue;
try {
const obj = JSON.parse(line);
if (obj && obj.done) {
if (thinkOpen) { try { res.write('</think>'); } catch (_) {} }
res.end();
return;
}
const msg = obj && obj.message;
const reasonChunk = (msg && (msg.reasoning || msg.thinking)) || obj.reasoning || obj.thinking || '';
const textChunk = (msg && msg.content) || obj.response || '';
if (reasonChunk && String(reasonChunk).length > 0) {
if (!thinkOpen) { try { res.write('<think>'); } catch (_) {} thinkOpen = true; }
try { res.write(String(reasonChunk)); } catch (_) {}
}
if (textChunk && String(textChunk).length > 0) {
if (thinkOpen) { try { res.write('</think>'); } catch (_) {} thinkOpen = false; }
try { res.write(String(textChunk)); } catch (_) {}
}
} catch (_) {
// ignore partial JSON
}
}
}
// Try to parse any leftover content
const rem = buffer.trim();
if (rem) {
try {
const obj = JSON.parse(rem);
const msg = obj && obj.message;
const reasonChunk = (msg && (msg.reasoning || msg.thinking)) || obj.reasoning || obj.thinking || '';
const textChunk = (msg && msg.content) || obj.response || '';
if (reasonChunk && String(reasonChunk).length > 0) {
if (!thinkOpen) { try { res.write('<think>'); } catch (_) {} thinkOpen = true; }
try { res.write(String(reasonChunk)); } catch (_) {}
}
if (textChunk && String(textChunk).length > 0) {
if (thinkOpen) { try { res.write('</think>'); } catch (_) {} thinkOpen = false; }
try { res.write(String(textChunk)); } catch (_) {}
}
} catch (_) { /* ignore */ }
}
if (thinkOpen) { try { res.write('</think>'); } catch (_) {} }
res.end();
} catch (err) {
if (!res.headersSent) {
res.status(500).json({ error: 'Failed to stream from Ollama', details: err.message });
} else {
try { res.end(); } catch (_) {}
}
}
});
// Simple health endpoint to check runtime availability
app.get('/health', async (req, res) => {
const checks = {
node: process.version,
platform: process.platform,
baseTmpDir: BASE_TMP_DIR,
ollama_url: OLLAMA_URL,
lmstudio_url: LMSTUDIO_URL,
};
// Report lessons storage status
try { checks.lessons = lessonsStorageInfo(); } catch { checks.lessons = { storage: lessonsDb ? 'sqlite' : 'json' }; }
const runVersion = (cmd, args) => new Promise((resolve) => {
try {
const p = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'] });
let out = '';
let err = '';
p.stdout.on('data', d => out += d.toString());
p.stderr.on('data', d => err += d.toString());
p.on('close', () => {
const v = (out || err || '').trim();
resolve(v || null);
});
p.on('error', () => resolve(null));
} catch {
resolve(null);
}
});
const py = resolvePythonCmd();
const [javacV, javaV, pythonV] = await Promise.all([
runVersion('javac', ['-version']).then(v => v || null),
runVersion('java', ['-version']).then(v => v || null),
runVersion(py.cmd, [...py.args, '--version']).then(v => v || null),
]);
checks.javac = javacV;
checks.java = javaV;
checks.python = pythonV;
// Try contacting Ollama and LM Studio quickly (ignore failures)
try {
const controller = new AbortController();
const t = setTimeout(() => controller.abort(), 1000);
const r = await fetch(`${OLLAMA_URL}/api/tags`, { signal: controller.signal });
clearTimeout(t);
checks.ollamaReachable = r.ok;
} catch {
checks.ollamaReachable = false;
}
try {
const controller2 = new AbortController();
const t2 = setTimeout(() => controller2.abort(), 1000);
const r2 = await fetch(`${LMSTUDIO_URL}/v1/models`, { signal: controller2.signal });
clearTimeout(t2);
checks.lmstudioReachable = r2.ok;
} catch {
checks.lmstudioReachable = false;
}
res.json(checks);
});
// Chat with a selected Ollama model
app.post('/ollama/chat', async (req, res) => {
const { model, history } = req.body || {};
if (!model) return res.status(400).json({ error: 'Missing model' });
// Convert existing chatHistory format to Ollama messages
const messages = normalizeChatHistory(history);
try {
const resp = await fetch(`${OLLAMA_URL}/api/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model, stream: false, messages })
});
if (!resp.ok) {
const text = await resp.text().catch(() => '');
return res.status(resp.status).json({ error: `Ollama chat error ${resp.status}`, details: text });
}
const data = await resp.json();
const reasoning = (data && data.message && (data.message.reasoning || data.message.thinking)) || data.reasoning || data.thinking || '';
const content = (data && data.message && data.message.content) || data.response || '';
const text = (reasoning ? `<think>${reasoning}</think>` : '') + content;
res.json({ text });
} catch (err) {
res.status(500).json({ error: 'Failed to reach Ollama chat', details: err.message });
}
});
// Endpoint to execute Java code
app.post('/run/java', (req, res) => {
console.log('Received Java execution request');
const { code, input, isFramework, frameworkName } = req.body;
if (typeof code !== 'string' || code.length === 0) {
console.error('No code provided in request');
return res.status(400).json({ error: 'No code provided.' });
}
if (Buffer.byteLength(code, 'utf8') > MAX_CODE_SIZE_BYTES) {
console.error('Code size exceeds limit');
return res.status(413).json({ error: 'Code too large (max 100KB).' });
}
// If this is a framework lesson, use syntax-only validation
if (isFramework) {
console.log(`Framework lesson detected: ${frameworkName || 'Unknown framework'}`);
return validateJavaSyntax(code, frameworkName, (err, result) => {
if (err) {
console.error('Framework validation error:', err);
return res.status(500).json({ error: err.message });
}
return res.json(result);
});
}
console.log('Creating temporary directory...');
const tempDir = fs.mkdtempSync(path.join(BASE_TMP_DIR, 'java-run-'));
const filePath = path.join(tempDir, 'Main.java');
console.log(`Temporary directory created at: ${tempDir}`);
// Save the user's code to a .java file
fs.writeFile(filePath, code, (err) => {
if (err) {
console.error('File write error:', err);
return res.status(500).json({ error: 'Failed to write code to file.' });
}
console.log('Code written to file, compiling...');
// Response guard to prevent double-send (timeouts vs close event)
let responded = false;
const safeRespond = (statusCode, payload) => {
if (responded) return;
responded = true;
try {
if (statusCode) {
res.status(statusCode).json(payload);
} else {
res.json(payload);
}
} catch (_) { /* ignore */ }
};
// Step 1: Compile the Java code (run inside the temp dir)
const compile = spawn('javac', [filePath], { cwd: tempDir });
let compileError = '';
compile.stderr.on('data', (data) => {
const error = data.toString();
console.error('Compilation error:', error);
compileError += error;
});
compile.on('error', (err) => {
console.error('Failed to start javac:', err);
cleanup();
return safeRespond(500, { output: `Failed to start javac: ${err.message}` , error: true, type: 'startup' });
});
compile.on('close', (code) => {
if (code !== 0) {
console.error(`Compilation failed with code ${code}`);
cleanup();
return safeRespond(200, { output: compileError, error: true, type: 'compilation' });
}
console.log('Compilation successful, running code...');
// Step 2: Run the compiled Java code with a small heap to limit memory
// Also set cwd so any relative file I/O happens inside the sandboxed temp dir
const run = spawn('java', ['-Xmx64m', '-cp', tempDir, 'Main'], { cwd: tempDir });
let output = '';
let runError = '';
// Handle input if provided
if (input) {
console.log('Providing input to Java process:', JSON.stringify(input));
run.stdin.write(input);
run.stdin.end();
} else {
console.log('No input provided for this execution');
}
// Set a timeout to prevent hanging
const timeout = setTimeout(() => {
console.error('Execution timed out');
try { run.kill(); } catch (_) {}
cleanup();
safeRespond(200, { output: 'Execution timed out after 10 seconds', error: true, type: 'timeout' });
}, MAX_EXECUTION_MS);
run.stdout.on('data', (data) => {
const dataStr = data.toString();
console.log('Java stdout:', dataStr);
output += dataStr;
});
run.stderr.on('data', (data) => {
const error = data.toString();
console.error('Java stderr:', error);
runError += error;
});
run.on('close', (code) => {
clearTimeout(timeout);
console.log(`Java process exited with code ${code}`);
cleanup();
if (responded) return;
if (runError) {
console.error('Runtime error occurred:', runError);
return safeRespond(200, { output: runError, error: true, type: 'runtime' });
}
console.log('Execution successful, output length:', output.length);
safeRespond(200, { output: output, error: false });
});
run.on('error', (err) => {
console.error('Failed to start Java process:', err);
clearTimeout(timeout);
cleanup();
safeRespond(500, { output: `Failed to start Java process: ${err.message}`, error: true, type: 'startup' });
});
});
function cleanup() {
console.log('Cleaning up temporary files...');
try {
// Remove temp dir recursively; ignore errors
if (fs.existsSync(tempDir)) {
fs.rmSync(tempDir, { recursive: true, force: true });
}
console.log('Cleanup complete');
} catch (cleanupErr) {
console.error('Error during cleanup:', cleanupErr);
}
}
});
});
// Endpoint to execute Python code
app.post('/run/python', (req, res) => {
const { code, isFramework, frameworkName } = req.body;
if (typeof code !== 'string' || code.length === 0) {
return res.status(400).json({ error: 'No code provided.' });
}
if (Buffer.byteLength(code, 'utf8') > MAX_CODE_SIZE_BYTES) {
return res.status(413).json({ error: 'Code too large (max 100KB).' });
}
// If this is a framework lesson, use syntax-only validation
if (isFramework) {
console.log(`Framework lesson detected: ${frameworkName || 'Unknown framework'}`);
return validatePythonSyntax(code, frameworkName, (err, result) => {
if (err) {
console.error('Framework validation error:', err);
return res.status(500).json({ error: err.message });
}
return res.json(result);
});
}
const tempDir = fs.mkdtempSync(path.join(BASE_TMP_DIR, 'python-run-'));
const filePath = path.join(tempDir, 'script.py');
fs.writeFile(filePath, code, (err) => {
if (err) {
return res.status(500).json({ error: 'Failed to write code to file.' });
}
// Response guard
let responded = false;
const safeRespond = (statusCode, payload) => {
if (responded) return;
responded = true;
try {
if (statusCode) {
res.status(statusCode).json(payload);
} else {
res.json(payload);
}
} catch (_) { /* ignore */ }
};
// Use resolved python executable
const py = resolvePythonCmd();
// Run Python with the temp directory as CWD so relative file I/O works
const run = spawn(py.cmd, [...py.args, filePath], { cwd: tempDir });
let output = '';
let runError = '';
let timedOut = false;
// Timeout to prevent hanging processes
const timeout = setTimeout(() => {
timedOut = true;
try { run.kill(); } catch (_) {}
}, MAX_EXECUTION_MS);
run.stdout.on('data', (data) => {
output += data.toString();
});
run.stderr.on('data', (data) => {
runError += data.toString();
});
run.on('close', (code) => {
clearTimeout(timeout);
try { fs.rmSync(filePath, { force: true }); } catch (_) {}
try { fs.rmSync(tempDir, { recursive: true, force: true }); } catch (_) {}
if (responded) return;
if (timedOut) {
return safeRespond(200, { output: 'Execution timed out after 10 seconds', error: true, type: 'timeout' });
}
if (runError) {
return safeRespond(200, { output: runError, error: true, type: 'runtime' });
}
safeRespond(200, { output: output, error: false });
});
});
});
// Serve static assets after dynamic JSON endpoints so DB can override JSON files
app.use(express.static('public'));
app.listen(port, () => {
console.log(`devbootLLM server listening at http://localhost:${port}`);
});