opencode/js/src/server/server.ts

66 lines
1.7 KiB
TypeScript
Raw Normal View History

2025-05-18 09:31:42 +08:00
import { Log } from "../util/log";
2025-05-19 02:13:04 +08:00
import { Bus } from "../bus";
2025-05-18 09:31:42 +08:00
2025-05-19 02:13:04 +08:00
import { Hono } from "hono";
import { streamSSE } from "hono/streaming";
import { Session } from "../session/session";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
export namespace Server {
const log = Log.create({ service: "server" });
2025-05-18 09:31:42 +08:00
const PORT = 16713;
2025-05-19 02:13:04 +08:00
2025-05-19 02:28:08 +08:00
export type App = ReturnType<typeof app>;
2025-05-19 02:13:04 +08:00
2025-05-19 02:28:08 +08:00
function app() {
return new Hono()
2025-05-19 02:13:04 +08:00
.get("/event", async (c) => {
log.info("event connected");
return streamSSE(c, async (stream) => {
const unsub = Bus.subscribeAll(async (event) => {
await stream.writeSSE({
data: JSON.stringify(event),
});
});
await new Promise<void>((resolve) => {
stream.onAbort(() => {
unsub();
resolve();
log.info("event disconnected");
});
});
});
})
.post("/session_create", async (c) => {
const session = await Session.create();
return c.json(session);
})
.post(
"/session_chat",
zValidator(
"json",
z.object({
sessionID: z.string(),
parts: z.custom<Session.Message["parts"]>(),
}),
),
async (c) => {
const body = c.req.valid("json");
const msg = await Session.chat(body.sessionID, ...body.parts);
return c.json(msg);
2025-05-18 09:31:42 +08:00
},
2025-05-19 02:13:04 +08:00
);
2025-05-19 02:28:08 +08:00
}
2025-05-19 02:13:04 +08:00
2025-05-19 02:28:08 +08:00
export function listen() {
const server = Bun.serve({
2025-05-19 02:13:04 +08:00
port: PORT,
hostname: "0.0.0.0",
idleTimeout: 0,
2025-05-19 02:28:08 +08:00
fetch: app().fetch,
2025-05-19 02:13:04 +08:00
});
2025-05-19 02:28:08 +08:00
return server;
2025-05-18 09:31:42 +08:00
}
}