Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112// The WebSocket server the App connects to. It listens on 127.0.0.1 only and refuses a connection without the Daemon's token.// Each connection gets a snapshot first, then every event, in order.// Its plain pages (pages) answer on ::1 too, on the same port: a browser that opens localhost may try IPv6 first, as macOS gives ::1 first.import { timingSafeEqual } from "node:crypto";import { createServer, type IncomingMessage, type ServerResponse } from "node:http";import type { AddressInfo } from "node:net";import { type WebSocket, WebSocketServer } from "ws";import { type AppCommand, authorization, type DaemonEvent, type DaemonMessage, type Snapshot } from "../../packages/protocol/index.ts";
export type Server = { port: number; /** Sends an event to every connected App. */ broadcast(event: DaemonEvent): void; /** Closes every connection and stops listening. */ close(): Promise<void>;};
/** One connected App. A command can send it events of its own, as the Chat it follows. */export type Connection = { /** Sends an event to this App only, while it is connected. */ send(event: DaemonEvent): void; /** Resolves once the App is gone. */ closed: Promise<void>;};
/** How a command ended: why the Daemon refused it, in plain words, null when it is done, or the id of what it created. */export type CommandResult = string | null | { created: string };
/** port 0 picks a free port. onCommand runs each command of the App that sent it. * The events it sends while it runs reach the App before its reply. * pages: the plain pages a browser may open, by path, with no token, as the return from an MCP server's sign-in on localhost. Each gets * the query, and gives the text the page shows. */export async function startServer(options: { port: number; token: string; snapshot: () => Snapshot; onCommand: (command: AppCommand, from: Connection) => Promise<CommandResult>; pages?: Record<string, (query: URLSearchParams) => Promise<string>>;}): Promise<Server> { const expected = Buffer.from(authorization(options.token)); const allowed = (header: string | undefined) => { const given = Buffer.from(header ?? ""); return given.length === expected.length && timingSafeEqual(given, expected); }; const sockets = new WebSocketServer({ noServer: true }); const answer = (request: IncomingMessage, response: ServerResponse) => { const url = new URL(request.url ?? "/", "http://127.0.0.1"); const page = request.method === "GET" && Object.hasOwn(options.pages ?? {}, url.pathname) ? options.pages?.[url.pathname] : undefined; if (!page) return response.writeHead(426, { "content-type": "text/plain" }).end("Pilot's Daemon speaks WebSocket only."); void page(url.searchParams) .catch((failure: Error) => "Pilot's Daemon failed: " + failure.message) .then((text) => response.writeHead(200, { "content-type": "text/plain; charset=utf-8" }).end(text)); }; const http = createServer(answer); // Only the pages: it takes no WebSocket. const ipv6 = createServer(answer); http.on("upgrade", (request, socket, head) => { if (!allowed(request.headers.authorization)) { socket.end("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n"); return; } sockets.handleUpgrade(request, socket, head, (ws) => { const from: Connection = { send: (event) => ws.readyState === ws.OPEN && send(ws, event), closed: new Promise((resolve) => ws.once("close", () => resolve())), }; send(ws, { type: "snapshot", snapshot: options.snapshot() }); ws.on("message", async (data) => { let command: AppCommand; try { command = JSON.parse(String(data)) as AppCommand; } catch { return; } const result = await options.onCommand(command, from).catch((failure: Error) => "Pilot's Daemon failed: " + failure.message); const reply: DaemonMessage = result !== null && typeof result === "object" ? { type: "replied", id: command.id, error: null, created: result.created } : { type: "replied", id: command.id, error: result }; if (ws.readyState === ws.OPEN) send(ws, reply); }); }); }); const send = (ws: WebSocket, message: DaemonMessage) => ws.send(JSON.stringify(message)); await new Promise<void>((resolve, reject) => { http.once("error", reject); http.listen(options.port, "127.0.0.1", () => resolve()); }); const port = (http.address() as AddressInfo).port; // A Mac without IPv6, or with the port taken on ::1, still has the pages on 127.0.0.1. const onIpv6 = await new Promise<boolean>((resolve) => { ipv6.once("error", () => resolve(false)); ipv6.listen(port, "::1", () => resolve(true)); }); return { port, broadcast(event) { for (const ws of sockets.clients) send(ws, event); }, async close() { for (const ws of sockets.clients) ws.close(1001, "Pilot's Daemon stopped."); await new Promise<void>((resolve) => sockets.close(() => resolve())); http.closeAllConnections(); if (onIpv6) { ipv6.closeAllConnections(); await new Promise<void>((resolve) => ipv6.close(() => resolve())); } await new Promise<void>((resolve, reject) => http.close((error) => (error ? reject(error) : resolve()))); }, };}