import { registerSettings } from "./settings"; import { hostsPlugin } from "./hosts"; import Fastify, { type FastifyInstance } from "fastify"; import websocket from "@fastify/websocket"; import { loadConfig, type ServerConfig } from "./config"; import { workspacePlugin } from "./workspace"; import { runsPlugin, EventsHub } from "./runs"; import { terminalPlugin, type TerminalOptions } from "./terminal"; import { createNotebookWatcher } from "./watch"; import { registerAuth, type AuthOptions } from "./auth"; import { registerStatic } from "./static"; import { chatPlugin } from "./chat"; export interface AppOptions { logger?: boolean; config?: Partial; events?: EventsHub; /** * Login protection for all /api routes. Enabled by default with `config.dataDir`. * `false` exists only for tests that exercise other plugins in isolation. */ auth?: Partial | false; trustProxy?: string[]; /** Built web app (apps/web/dist); served only when it contains index.html. */ staticDir?: string; /** Watch workspace notebooks and publish file.changed/file.deleted on /api/events. */ watchNotebooks?: boolean; terminal?: Omit; } /** * Builds the Fastify app. Feature areas live in their own folders: * src/auth/ login, persistent session secret (registered first: its hook guards every /api route) * src/workspace/ notebooks, hosts.yaml; src/ssh/, src/runs/ queue, audit, artifacts, /api/events * src/terminal/ node-pty + tmux, /api/terminal; src/watch/ file.changed events into the events hub * src/static/ built web app with SPA fallback */ export async function buildApp(options: AppOptions = {}): Promise { const config = loadConfig(options.config); const hub = options.events ?? new EventsHub(); const app = Fastify({ logger: options.logger ?? false, trustProxy: options.trustProxy ?? false }); if (options.auth !== false) await registerAuth(app, { dataDir: config.dataDir, ...options.auth }); await registerSettings(app, config); await app.register(websocket); await app.register(workspacePlugin, { config }); await app.register(hostsPlugin, { config }); await app.register(runsPlugin, { config, hub }); await app.register(terminalPlugin, { ...options.terminal, workspaceDir: config.workspaceDir }); await app.register(chatPlugin, { config }); if (options.watchNotebooks) { const watcher = createNotebookWatcher(config.workspaceDir, { onError: error => app.log.error({ err: error }, "notebook watcher error"), }); watcher.on(event => hub.publish(event)); app.addHook("onClose", async () => { await watcher.close(); }); await watcher.ready; } app.get("/api/health", async () => ({ ok: true })); if (options.staticDir) await registerStatic(app, options.staticDir); return app; }