Files
wonder 922e1c3be2 Initial commit: pi-lens session observability for pi
- collector, classify, prompt-parser, server (TypeScript)
- web panel (app.js, index.html, style.css)
- smoke and load-test scripts
- DESIGN.md and README.md
2026-10-04 19:54:34 +08:00

183 lines
5.6 KiB
TypeScript

/**
* server.ts — local read-only web service for pi-lens.
*
* node:http only (runs under node and bun), binds 127.0.0.1, no auth by design
* (local developer tool). Serves the embedded-free static web/ directory plus a
* small JSON API and SSE for append-only live updates.
*/
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import type { TraceStore } from "./collector.ts";
export interface LensServer {
port: number;
url: string;
attachStore(store: TraceStore): void;
stop(): Promise<void>;
}
const MIME: Record<string, string> = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json; charset=utf-8",
".svg": "image/svg+xml",
};
function resolveWebDir(): string {
const candidates: string[] = [];
try {
candidates.push(join(dirname(fileURLToPath(import.meta.url)), "web"));
} catch {
/* import.meta.url may be unavailable in some loaders */
}
candidates.push(
join(homedir(), ".pi", "agent", "extensions", "pi-lens", "web"),
join(process.cwd(), "pi-lens", "web"),
join(process.cwd(), "web"),
);
for (const dir of candidates) {
try {
readFileSync(join(dir, "index.html"));
return dir;
} catch {
/* try next */
}
}
throw new Error("pi-lens: web directory not found; looked in " + candidates.join(", "));
}
function sendJson(res: ServerResponse, data: unknown, status = 200): void {
const body = JSON.stringify(data);
res.writeHead(status, {
"content-type": "application/json; charset=utf-8",
"cache-control": "no-store",
"access-control-allow-origin": "*",
});
res.end(body);
}
export async function startServer(store: TraceStore, preferredPort = 7777): Promise<LensServer> {
const webDir = resolveWebDir();
let current: TraceStore = store;
const sseClients = new Set<ServerResponse>();
let unsubscribe: (() => void) | undefined;
const attachStore = (next: TraceStore): void => {
unsubscribe?.();
current = next;
unsubscribe = current.subscribe((event) => {
const payload = `event: trace\ndata: ${JSON.stringify(event)}\n\n`;
for (const client of sseClients) {
try {
client.write(payload);
} catch {
sseClients.delete(client);
}
}
});
};
attachStore(store);
const handler = (req: IncomingMessage, res: ServerResponse): void => {
const url = new URL(req.url ?? "/", "http://127.0.0.1");
const path = url.pathname;
try {
if (path === "/api/events") {
res.writeHead(200, {
"content-type": "text/event-stream; charset=utf-8",
"cache-control": "no-cache",
connection: "keep-alive",
});
res.write("retry: 2000\n\n");
sseClients.add(res);
const heartbeat = setInterval(() => {
try {
res.write(": ping\n\n");
} catch {
/* closed */
}
}, 15000);
req.on("close", () => {
clearInterval(heartbeat);
sseClients.delete(res);
});
return;
}
if (path === "/api/state") return sendJson(res, current.getState());
if (path === "/api/prompt-builds") return sendJson(res, current.getPromptBuilds());
if (path === "/api/skills") return sendJson(res, current.getSkills());
if (path === "/api/timeline") {
const before = url.searchParams.get("before");
const limit = Math.min(1000, Number(url.searchParams.get("limit") ?? 200) || 200);
return sendJson(res, current.getTimeline(before ? Number(before) : undefined, limit));
}
const contentMatch = path.match(/^\/api\/content\/(c\d+)$/);
if (contentMatch) {
const text = current.getContent(contentMatch[1]);
if (text === undefined) return sendJson(res, { error: "not found" }, 404);
return sendJson(res, { id: contentMatch[1], text });
}
if (path === "/api/export") return sendJson(res, current.exportAll());
// static files
const file = path === "/" ? "index.html" : path.replace(/^\/+/, "");
if (/^(index\.html|app\.js|style\.css)$/.test(file)) {
const data = readFileSync(join(webDir, file));
const ext = file.slice(file.lastIndexOf("."));
res.writeHead(200, { "content-type": MIME[ext] ?? "application/octet-stream", "cache-control": "no-cache" });
res.end(data);
return;
}
sendJson(res, { error: "not found" }, 404);
} catch (err) {
sendJson(res, { error: String(err) }, 500);
}
};
const server: Server = createServer(handler);
const port = await new Promise<number>((resolve, reject) => {
let attempt = preferredPort;
const tryListen = (): void => {
server.once("error", (err: NodeJS.ErrnoException) => {
if (err.code === "EADDRINUSE" && attempt < preferredPort + 100) {
attempt += 1;
tryListen();
} else {
reject(err);
}
});
server.listen(attempt, "127.0.0.1", () => resolve(attempt));
};
tryListen();
});
return {
port,
url: `http://127.0.0.1:${port}/`,
attachStore,
stop: () =>
new Promise<void>((resolve) => {
unsubscribe?.();
for (const client of sseClients) {
try {
client.end();
} catch {
/* already closed */
}
}
sseClients.clear();
server.close(() => resolve());
}),
};
}