summaryrefslogtreecommitdiffhomepage
path: root/packages/api/src/index.ts
blob: 02b04b6cf6ca53650f435f2a3180adcf2584d585 (plain)
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
import { createBunWebSocket } from "hono/bun";
import { agentManager, app } from "./app.js";

const { upgradeWebSocket, websocket } = createBunWebSocket();

app.get(
	"/ws",
	upgradeWebSocket((_c) => {
		return {
			onOpen(_event, ws) {
				// Send current status immediately
				ws.send(JSON.stringify({ type: "status", status: agentManager.getStatus() }));

				const unsubscribe = agentManager.onEvent((event) => {
					ws.send(JSON.stringify(event));
				});

				// Store unsubscribe fn on the raw socket for cleanup
				(ws as unknown as { _unsub?: () => void })._unsub = unsubscribe;
			},
			onClose(_event, ws) {
				const unsub = (ws as unknown as { _unsub?: () => void })._unsub;
				if (unsub) {
					unsub();
				}
			},
		};
	}),
);

export { app };

export default {
	port: 3000,
	fetch: app.fetch,
	websocket,
};