Study/server/main.ts
Elijah 5ea61c882c
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 51s
Add sandboxed Python for the assistant and a Python check of generated quizzes
- Pyodide (Python 3.14, WebAssembly) in a separate Node process under the permission
  model: read-only access to Pyodide's files, no writes, processes or network, empty
  environment, JS bridges removed, time limit with kill and restart.
- Assistant tool run_python, which can load a draft or quiz as Python data.
- After quiz generation the model checks question count, type mix, correct answers per
  type, duplicates and recomputed calculations with Python, then submits fixes that are
  applied only if the question still validates. Switch in the Generate dialog.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 13:03:24 -07:00

81 lines
3.1 KiB
TypeScript

import { serve } from '@hono/node-server';
import { tidyDrafts } from './ai/generate.ts';
import { createApp } from './app.ts';
import { initAuth } from './auth.ts';
import { loadConfig } from './config.ts';
import { openDatabase } from './db.ts';
import type { AppContext } from './http.ts';
import { APP_VERSION } from './routes/data.ts';
import { startBackupSchedule } from './services/backup.ts';
import { resumeQueue } from './services/documents.ts';
import { scheduleIndexing } from './services/semantic.ts';
import { seedTemplates } from './services/templates.ts';
import { stopPython } from './ai/sandbox.ts';
function log(level: 'info' | 'warn' | 'error', message: string, extra?: unknown): void {
const line = `${new Date().toISOString()} ${level.toUpperCase().padEnd(5)} ${message}`;
const detail = extra instanceof Error ? (extra.stack ?? extra.message) : extra !== undefined ? JSON.stringify(extra) : '';
(level === 'error' ? console.error : console.log)(detail ? `${line}\n${detail}` : line);
}
async function main(): Promise<void> {
// Optional .env file for running outside Docker. Real environment variables always win.
try {
process.loadEnvFile('.env');
} catch {
/* no .env file: that is the normal case in a container */
}
const config = loadConfig();
log('info', `Study Desk ${APP_VERSION} starting (data: ${config.dataDir})`);
const { db, report } = openDatabase(config.dbPath, config.backupsDir);
if (report.applied.length > 0) log('info', `Database migrated: ${report.applied.join(', ')}${report.backup ? ` (backup: ${report.backup})` : ''}`);
const app: AppContext = { db, config, log };
await initAuth(app);
seedTemplates(db);
tidyDrafts(db);
const resumed = resumeQueue(app);
if (resumed > 0) log('info', `Resuming processing of ${resumed} document(s)`);
scheduleIndexing(app);
const stopBackups = startBackupSchedule(app);
const server = serve({ fetch: createApp(app).fetch, port: config.port, hostname: config.host }, (info) => {
log('info', `Listening on http://${info.address === '::' || info.address === '0.0.0.0' ? 'localhost' : info.address}:${info.port}`);
if (!config.webDir) log('warn', 'No built web app found (dist/web). API only: use the Vite dev server for the UI.');
});
let closing = false;
const shutdown = (signal: string) => {
stopPython();
if (closing) return;
closing = true;
log('info', `${signal} received, shutting down`);
stopBackups();
server.close(() => {
try {
db.close();
} catch {
/* already closed */
}
process.exit(0);
});
// Do not let an open event stream hold the process forever.
setTimeout(() => {
try {
db.close();
} catch {
/* ignore */
}
process.exit(0);
}, 5000).unref();
};
process.on('SIGTERM', () => shutdown('SIGTERM'));
process.on('SIGINT', () => shutdown('SIGINT'));
process.on('unhandledRejection', (reason) => log('error', 'Unhandled promise rejection', reason));
}
main().catch((err) => {
log('error', 'Failed to start', err);
process.exit(1);
});