Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 8x 8x 38x 23x 23x 38x 509x 508x 509x 38x 1x 1x 38x 355x 355x 38x 108x 108x 108x 38x 42x 291x 41x 41x 41x 41x 41x 41x 41x 250x 250x 250x 42x 38x 42x 42x 42x 42x 42x 42x 42x 1x 1x 42x 1x 1x 42x 42x 38x 42x 41x 41x 10x 10x 10x 10x 37x 36x 36x 5x 5x 36x 37x 41x 42x 38x 42x 23x 23x 22x 10x 10x 10x 7x 7x 10x 10x 10x 2x 22x 42x 42x 1x 1x 42x 42x 38x 43x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 41x 33x 33x 43x 3x 3x 43x 38x 41x 507x 507x 507x 507x 153x 507x 354x 507x 474x 468x 468x 41x 38x 12x 4x 4x 4x 3x 3x 4x 4x 8x 12x 38x 12x 11x 11x 12x 1x 12x 38x 17x 17x 3x 3x 3x 17x 5x 5x 5x 12x 12x 12x 12x 12x 12x 17x 2x 2x 12x 12x 12x 17x 38x 2x 2x 2x 2x 38x | import type { ChildProcess } from "child_process";
import type { ServerState } from "./types";
import { PLATFORM, SERVER_STATE } from "./types";
import { node } from "./binary-manager";
const SERVER_MANAGER_CONFIG = {
HEALTH_POLL_INTERVAL_MS: 1000,
HEALTH_POLL_MAX_ATTEMPTS: 120,
STOP_GRACE_MS: 5000,
CRASH_RESTART_DELAY_MS: 3000,
MAX_CRASH_RESTARTS: 3,
PORT_FILE_POLL_INTERVAL_MS: 500,
PORT_FILE_MAX_ATTEMPTS: 240,
} as const;
export interface ServerManagerOptions {
binaryPath: string;
dataDir: string;
/**
* HuggingFace cache and GGUF storage. Set via `LILBEE_MODELS_DIR` so the
* server uses the same path across all vaults — without it, lilbee would
* scope models to each per-vault data-dir and re-download per vault.
*/
modelsDir: string;
ragSystemPrompt: string;
generalSystemPrompt: string;
onStateChange?: (state: ServerState) => void;
onRestartsExhausted?: (stderr: string) => void;
onShutdownFailure?: (error: Error) => void;
}
export class ServerManager {
private opts: ServerManagerOptions;
private child: ChildProcess | null = null;
private _state: ServerState = SERVER_STATE.STOPPED;
private crashCount = 0;
private stopping = false;
private restartTimer: ReturnType<typeof setTimeout> | null = null;
private _actualPort: number | null = null;
private _stderrLines: string[] = [];
private static readonly MAX_STDERR_LINES = 20;
constructor(opts: ServerManagerOptions) {
this.opts = opts;
}
get lastStderr(): string {
return this._stderrLines.join("\n");
}
get state(): ServerState {
return this._state;
}
get serverUrl(): string {
if (this._actualPort === null) return "";
return `http://127.0.0.1:${this._actualPort}`;
}
get dataDir(): string {
return this.opts.dataDir;
}
private get portFilePath(): string {
return `${this.opts.dataDir}/data/server.port`;
}
private setState(s: ServerState): void {
this._state = s;
this.opts.onStateChange?.(s);
}
private async waitForPortFile(): Promise<void> {
for (let i = 0; i < SERVER_MANAGER_CONFIG.PORT_FILE_MAX_ATTEMPTS; i++) {
if (node.existsSync(this.portFilePath)) {
const content = node.readFileSync(this.portFilePath, "utf-8").trim();
const port = parseInt(content, 10);
if (!isNaN(port) && port > 0 && port <= 65535) {
this._actualPort = port;
return;
}
}
await new Promise((r) => setTimeout(r, SERVER_MANAGER_CONFIG.PORT_FILE_POLL_INTERVAL_MS));
}
throw new Error("Port file not found within timeout");
}
private buildSpawnEnv(): Record<string, string | undefined> {
const env: Record<string, string | undefined> = {
...process.env,
LILBEE_CORS_ORIGINS: "app://obsidian.md",
LILBEE_PARENT_PID: String(process.pid),
LILBEE_MODELS_DIR: this.opts.modelsDir,
};
if (this.opts.ragSystemPrompt) {
env.LILBEE_RAG_SYSTEM_PROMPT = this.opts.ragSystemPrompt;
}
if (this.opts.generalSystemPrompt) {
env.LILBEE_GENERAL_SYSTEM_PROMPT = this.opts.generalSystemPrompt;
}
return env;
}
private attachStderrCapture(child: ChildProcess): void {
if (!child.stderr) return;
let partial = "";
child.stderr.on("data", (chunk: Buffer) => {
partial += chunk.toString();
const lines = partial.split("\n");
partial = lines.pop()!;
for (const line of lines) {
if (line.length > 0) {
this._stderrLines.push(line);
if (this._stderrLines.length > ServerManager.MAX_STDERR_LINES) {
this._stderrLines.shift();
}
}
}
});
}
private attachLifecycleHandlers(child: ChildProcess): void {
child.on("exit", () => {
this.child = null;
if (this.stopping) return;
if (this.crashCount < SERVER_MANAGER_CONFIG.MAX_CRASH_RESTARTS) {
this.crashCount++;
this.setState(SERVER_STATE.ERROR);
this.restartTimer = setTimeout(() => {
this.restartTimer = null;
if (!this.stopping) void this.start();
}, SERVER_MANAGER_CONFIG.CRASH_RESTART_DELAY_MS);
return;
}
this.setState(SERVER_STATE.ERROR);
this.opts.onRestartsExhausted?.(this.lastStderr);
});
child.on("error", () => {
this.child = null;
this.setState(SERVER_STATE.ERROR);
});
}
async start(): Promise<void> {
if (this.child) return;
this.stopping = false;
this._actualPort = null;
this.setState(SERVER_STATE.STARTING);
this._stderrLines = [];
// No --port: the server binds 0, the kernel picks a free port, and
// the chosen value is written to data/server.port for us to read.
const args = ["serve", "--host", "127.0.0.1", "--data-dir", this.opts.dataDir];
this.child = node.spawn(this.opts.binaryPath, args, {
env: this.buildSpawnEnv(),
stdio: ["ignore", "ignore", "pipe"],
detached: false,
});
this.attachStderrCapture(this.child);
this.attachLifecycleHandlers(this.child);
try {
await this.waitForPortFile();
await this.waitForReady();
this.crashCount = 0;
this.setState(SERVER_STATE.READY);
} catch {
this.setState(SERVER_STATE.ERROR);
}
}
private async waitForReady(): Promise<void> {
for (let i = 0; i < SERVER_MANAGER_CONFIG.HEALTH_POLL_MAX_ATTEMPTS; i++) {
const url = this.serverUrl;
if (url) {
try {
const res = await node.fetch(`${url}/api/health`);
if (res.ok) return;
} catch {
// not ready yet
}
}
await new Promise((r) => setTimeout(r, SERVER_MANAGER_CONFIG.HEALTH_POLL_INTERVAL_MS));
}
throw new Error("Server did not become ready within timeout");
}
private async terminateChild(child: ChildProcess): Promise<void> {
if (process.platform === PLATFORM.WIN32) {
try {
await node.execFile("taskkill", ["/pid", String(child.pid), "/f", "/t"]);
} catch (err) {
this.opts.onShutdownFailure?.(err instanceof Error ? err : new Error(String(err)));
}
return;
}
child.kill("SIGTERM");
}
private cleanupPortFile(): void {
if (!node.existsSync(this.portFilePath)) return;
try {
node.unlinkSync(this.portFilePath);
} catch {
// ignore cleanup errors
}
}
async stop(): Promise<void> {
this.stopping = true;
if (this.restartTimer) {
clearTimeout(this.restartTimer);
this.restartTimer = null;
}
if (!this.child) {
this.setState(SERVER_STATE.STOPPED);
return;
}
const child = this.child;
await this.terminateChild(child);
const exited = await Promise.race([
new Promise<boolean>((resolve) => child.on("exit", () => resolve(true))),
new Promise<boolean>((resolve) => setTimeout(() => resolve(false), SERVER_MANAGER_CONFIG.STOP_GRACE_MS)),
]);
if (!exited && this.child) {
this.child.kill("SIGKILL");
}
this.child = null;
this.setState(SERVER_STATE.STOPPED);
this.cleanupPortFile();
}
async restart(): Promise<void> {
await this.stop();
this.crashCount = 0;
await this.start();
}
}
|