Open History to see the last commit
1/**
2 * Server - HTTP/WebSocket server service interface.
3 *
4 * Owns startup and shutdown lifecycle of the HTTP server, static asset serving,
5 * and WebSocket request routing.
6 *
7 * @module Server
8 */
9import http from "node:http";
10import type { Duplex } from "node:stream";
11
12import Mime from "@effect/platform-node/Mime";
13import {
14 CommandId,
15 type ClientOrchestrationCommand,
16 type OrchestrationCommand,
17 ORCHESTRATION_WS_CHANNELS,
18 ORCHESTRATION_WS_METHODS,
19 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
20 ProjectId,
21 ThreadId,
22 TerminalEvent,
23 WS_CHANNELS,
24 WS_METHODS,
25 WebSocketRequest,
26 WsPush,
27 WsResponse,
28} from "@t3tools/contracts";
29import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
30import {
31 Cause,
32 Effect,
33 Exit,
34 FileSystem,
35 Layer,
36 Path,
37 Ref,
38 Schema,
39 Scope,
40 ServiceMap,
41 Stream,
42 Struct,
43} from "effect";
44import { WebSocketServer, type WebSocket } from "ws";
45
46import { createLogger } from "./logger";
47import { GitManager } from "./git/Services/GitManager.ts";
48import { TerminalManager } from "./terminal/Services/Manager.ts";
49import { Keybindings } from "./keybindings";
50import { searchWorkspaceEntries } from "./workspaceEntries";
51import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
52import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
53import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
54import { ProviderService } from "./provider/Services/ProviderService";
55import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
56import { clamp } from "effect/Number";
57import { Open } from "./open";
58import { ServerConfig } from "./config";
59import { GitCore } from "./git/Services/GitCore.ts";
60import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
61import {
62 ATTACHMENTS_ROUTE_PREFIX,
63 normalizeAttachmentRelativePath,
64 resolveAttachmentRelativePath,
65} from "./attachmentPaths";
66import { createAttachmentId, resolveAttachmentPath, resolveAttachmentPathById } from "./attachmentStore.ts";
67import { parseBase64DataUrl } from "./imageMime.ts";
68
69/**
70 * ServerShape - Service API for server lifecycle control.
71 */
72export interface ServerShape {
73 /**
74 * Start HTTP and WebSocket listeners.
75 */
76 readonly start: Effect.Effect<
77 http.Server,
78 ServerLifecycleError,
79 Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
80 >;
81
82 /**
83 * Wait for process shutdown signals.
84 */
85 readonly stopSignal: Effect.Effect<void, never>;
86}
87
88/**
89 * Server - Service tag for HTTP/WebSocket lifecycle management.
90 */
91export class Server extends ServiceMap.Service<Server, ServerShape>()("t3/wsServer/Server") {}
92
93const isServerNotRunningError = (error: unknown): boolean => {
94 if (!(error instanceof Error)) return false;
95 const maybeCode = (error as NodeJS.ErrnoException).code;
96 return (
97 maybeCode === "ERR_SERVER_NOT_RUNNING" || error.message.toLowerCase().includes("not running")
98 );
99};
100
101function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
102 socket.end(
103 `HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
104 "Connection: close\r\n" +
105 "Content-Type: text/plain\r\n" +
106 `Content-Length: ${Buffer.byteLength(message)}\r\n` +
107 "\r\n" +
108 message,
109 );
110}
111
112function websocketRawToString(raw: unknown): string | null {
113 if (typeof raw === "string") {
114 return raw;
115 }
116 if (raw instanceof Uint8Array) {
117 return Buffer.from(raw).toString("utf8");
118 }
119 if (raw instanceof ArrayBuffer) {
120 return Buffer.from(new Uint8Array(raw)).toString("utf8");
121 }
122 if (Array.isArray(raw)) {
123 const chunks: string[] = [];
124 for (const chunk of raw) {
125 if (typeof chunk === "string") {
126 chunks.push(chunk);
127 continue;
128 }
129 if (chunk instanceof Uint8Array) {
130 chunks.push(Buffer.from(chunk).toString("utf8"));
131 continue;
132 }
133 if (chunk instanceof ArrayBuffer) {
134 chunks.push(Buffer.from(new Uint8Array(chunk)).toString("utf8"));
135 continue;
136 }
137 return null;
138 }
139 return chunks.join("");
140 }
141 return null;
142}
143
144function stripRequestTag<T extends { _tag: string }>(body: T) {
145 return Struct.omit(body, ["_tag"]);
146}
147
148export type ServerCoreRuntimeServices =
149 | OrchestrationEngineService
150 | ProjectionSnapshotQuery
151 | CheckpointDiffQuery
152 | OrchestrationReactor
153 | ProviderService;
154
155export type ServerRuntimeServices =
156 | ServerCoreRuntimeServices
157 | GitManager
158 | GitCore
159 | TerminalManager
160 | Keybindings
161 | Open;
162
163export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()(
164 "ServerLifecycleError",
165 {
166 operation: Schema.String,
167 cause: Schema.optional(Schema.Defect),
168 },
169) {}
170
171class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("RouteRequestError", {
172 message: Schema.String,
173}) {}
174
175export const createServer = Effect.fn(function* (): Effect.fn.Return<
176 http.Server,
177 ServerLifecycleError,
178 Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
179> {
180 const serverConfig = yield* ServerConfig;
181 const {
182 port,
183 cwd,
184 keybindingsConfigPath,
185 staticDir,
186 devUrl,
187 authToken,
188 host,
189 logWebSocketEvents,
190 autoBootstrapProjectFromCwd,
191 } = serverConfig;
192
193 const gitManager = yield* GitManager;
194 const terminalManager = yield* TerminalManager;
195 const keybindingsManager = yield* Keybindings;
196 const git = yield* GitCore;
197 const fileSystem = yield* FileSystem.FileSystem;
198 const path = yield* Path.Path;
199
200 yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe(
201 Effect.catch((error) =>
202 Effect.logWarning("failed to sync keybindings defaults on startup", {
203 path: error.configPath,
204 detail: error.detail,
205 cause: error.cause,
206 }),
207 ),
208 );
209
210 const clients = yield* Ref.make(new Set<WebSocket>());
211 const logger = createLogger("ws");
212
213 function logOutgoingPush(push: WsPush, recipients: number) {
214 if (!logWebSocketEvents) return;
215 logger.event("outgoing push", {
216 channel: push.channel,
217 recipients,
218 payload: push.data,
219 });
220 }
221
222 const encodePush = Schema.encodeEffect(Schema.fromJsonString(WsPush));
223 const broadcastPush = Effect.fnUntraced(function* (push: WsPush) {
224 const message = yield* encodePush(push);
225 let recipients = 0;
226 for (const client of yield* Ref.get(clients)) {
227 if (client.readyState === client.OPEN) {
228 client.send(message);
229 recipients += 1;
230 }
231 }
232 logOutgoingPush(push, recipients);
233 });
234
235 const onTerminalEvent = Effect.fnUntraced(function* (event: TerminalEvent) {
236 yield* broadcastPush({
237 type: "push",
238 channel: WS_CHANNELS.terminalEvent,
239 data: event,
240 });
241 });
242
243 const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
244 readonly command: ClientOrchestrationCommand;
245 }) {
246 if (input.command.type !== "thread.turn.start") {
247 return input.command as OrchestrationCommand;
248 }
249 const turnStartCommand = input.command;
250
251 const normalizedAttachments = yield* Effect.forEach(
252 turnStartCommand.message.attachments,
253 (attachment) =>
254 Effect.gen(function* () {
255 const parsed = parseBase64DataUrl(attachment.dataUrl);
256 if (!parsed || !parsed.mimeType.startsWith("image/")) {
257 return yield* new RouteRequestError({
258 message: `Invalid image attachment payload for '${attachment.name}'.`,
259 });
260 }
261
262 const bytes = Buffer.from(parsed.base64, "base64");
263 if (bytes.byteLength === 0 || bytes.byteLength > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
264 return yield* new RouteRequestError({
265 message: `Image attachment '${attachment.name}' is empty or too large.`,
266 });
267 }
268
269 const attachmentId = createAttachmentId(turnStartCommand.threadId);
270 if (!attachmentId) {
271 return yield* new RouteRequestError({
272 message: "Failed to create a safe attachment id.",
273 });
274 }
275
276 const persistedAttachment = {
277 type: "image" as const,
278 id: attachmentId,
279 name: attachment.name,
280 mimeType: parsed.mimeType.toLowerCase(),
281 sizeBytes: bytes.byteLength,
282 };
283
284 const attachmentPath = resolveAttachmentPath({
285 stateDir: serverConfig.stateDir,
286 attachment: persistedAttachment,
287 });
288 if (!attachmentPath) {
289 return yield* new RouteRequestError({
290 message: `Failed to resolve persisted path for '${attachment.name}'.`,
291 });
292 }
293
294 yield* fileSystem.makeDirectory(path.dirname(attachmentPath), { recursive: true }).pipe(
295 Effect.mapError(
296 () =>
297 new RouteRequestError({
298 message: `Failed to create attachment directory for '${attachment.name}'.`,
299 }),
300 ),
301 );
302 yield* fileSystem.writeFile(attachmentPath, bytes).pipe(
303 Effect.mapError(
304 () =>
305 new RouteRequestError({
306 message: `Failed to persist attachment '${attachment.name}'.`,
307 }),
308 ),
309 );
310
311 return persistedAttachment;
312 }),
313 { concurrency: 1 },
314 );
315
316 return {
317 ...turnStartCommand,
318 message: {
319 ...turnStartCommand.message,
320 attachments: normalizedAttachments,
321 },
322 } satisfies OrchestrationCommand;
323 });
324
325 // HTTP server — serves static files or redirects to Vite dev server
326 const httpServer = http.createServer((req, res) => {
327 const respond = (
328 statusCode: number,
329 headers: Record<string, string>,
330 body?: string | Uint8Array,
331 ) => {
332 res.writeHead(statusCode, headers);
333 res.end(body);
334 };
335
336 void Effect.runPromise(
337 Effect.gen(function* () {
338 const url = new URL(req.url ?? "/", `http://localhost:${port}`);
339 if (tryHandleProjectFaviconRequest(url, res)) {
340 return;
341 }
342
343 if (url.pathname.startsWith(ATTACHMENTS_ROUTE_PREFIX)) {
344 const rawRelativePath = url.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
345 const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
346 if (!normalizedRelativePath) {
347 respond(400, { "Content-Type": "text/plain" }, "Invalid attachment path");
348 return;
349 }
350
351 const isIdLookup =
352 !normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
353 const filePath = isIdLookup
354 ? resolveAttachmentPathById({
355 stateDir: serverConfig.stateDir,
356 attachmentId: normalizedRelativePath,
357 })
358 : resolveAttachmentRelativePath({
359 stateDir: serverConfig.stateDir,
360 relativePath: normalizedRelativePath,
361 });
362 if (!filePath) {
363 respond(
364 isIdLookup ? 404 : 400,
365 { "Content-Type": "text/plain" },
366 isIdLookup ? "Not Found" : "Invalid attachment path",
367 );
368 return;
369 }
370
371 const fileInfo = yield* fileSystem
372 .stat(filePath)
373 .pipe(Effect.catch(() => Effect.succeed(null)));
374 if (!fileInfo || fileInfo.type !== "File") {
375 respond(404, { "Content-Type": "text/plain" }, "Not Found");
376 return;
377 }
378
379 const contentType = Mime.getType(filePath) ?? "application/octet-stream";
380 res.writeHead(200, {
381 "Content-Type": contentType,
382 "Cache-Control": "public, max-age=31536000, immutable",
383 });
384 const streamExit = yield* Stream.runForEach(fileSystem.stream(filePath), (chunk) =>
385 Effect.sync(() => {
386 if (!res.destroyed) {
387 res.write(chunk);
388 }
389 }),
390 ).pipe(Effect.exit);
391 if (streamExit._tag === "Failure") {
392 if (!res.destroyed) {
393 res.destroy();
394 }
395 return;
396 }
397 if (!res.writableEnded) {
398 res.end();
399 }
400 return;
401 }
402
403 // In dev mode, redirect to Vite dev server
404 if (devUrl) {
405 respond(302, { Location: devUrl.href });
406 return;
407 }
408
409 // Serve static files from the web app build
410 if (!staticDir) {
411 respond(
412 503,
413 { "Content-Type": "text/plain" },
414 "No static directory configured and no dev URL set.",
415 );
416 return;
417 }
418
419 const staticRoot = path.resolve(staticDir);
420 const staticRequestPath = url.pathname === "/" ? "/index.html" : url.pathname;
421 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
422 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
423 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
424 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
425 if (
426 staticRelativePath.length === 0 ||
427 hasRawLeadingParentSegment ||
428 hasPathTraversalSegment ||
429 staticRelativePath.includes("\0")
430 ) {
431 respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
432 return;
433 }
434
435 const isWithinStaticRoot = (candidate: string) =>
436 candidate === staticRoot ||
437 candidate.startsWith(
438 staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`,
439 );
440
441 let filePath = path.resolve(staticRoot, staticRelativePath);
442 if (!isWithinStaticRoot(filePath)) {
443 respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
444 return;
445 }
446
447 const ext = path.extname(filePath);
448 if (!ext) {
449 filePath = path.resolve(filePath, "index.html");
450 if (!isWithinStaticRoot(filePath)) {
451 respond(400, { "Content-Type": "text/plain" }, "Invalid static file path");
452 return;
453 }
454 }
455
456 const fileInfo = yield* fileSystem
457 .stat(filePath)
458 .pipe(Effect.catch(() => Effect.succeed(null)));
459 if (!fileInfo || fileInfo.type !== "File") {
460 const indexPath = path.resolve(staticRoot, "index.html");
461 const indexData = yield* fileSystem
462 .readFile(indexPath)
463 .pipe(Effect.catch(() => Effect.succeed(null)));
464 if (!indexData) {
465 respond(404, { "Content-Type": "text/plain" }, "Not Found");
466 return;
467 }
468 respond(200, { "Content-Type": "text/html; charset=utf-8" }, indexData);
469 return;
470 }
471
472 const contentType = Mime.getType(filePath) ?? "application/octet-stream";
473 const data = yield* fileSystem
474 .readFile(filePath)
475 .pipe(Effect.catch(() => Effect.succeed(null)));
476 if (!data) {
477 respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
478 return;
479 }
480 respond(200, { "Content-Type": contentType }, data);
481 }),
482 ).catch(() => {
483 if (!res.headersSent) {
484 respond(500, { "Content-Type": "text/plain" }, "Internal Server Error");
485 }
486 });
487 });
488
489 // WebSocket server — upgrades from the HTTP server
490 const wss = new WebSocketServer({ noServer: true });
491
492 const closeWebSocketServer = Effect.callback<void, ServerLifecycleError>((resume) => {
493 wss.close((error) => {
494 if (error && !isServerNotRunningError(error)) {
495 resume(
496 Effect.fail(
497 new ServerLifecycleError({ operation: "closeWebSocketServer", cause: error }),
498 ),
499 );
500 } else {
501 resume(Effect.void);
502 }
503 });
504 });
505
506 const closeAllClients = Ref.get(clients).pipe(
507 Effect.flatMap(Effect.forEach((client) => Effect.sync(() => client.close()))),
508 Effect.flatMap(() => Ref.set(clients, new Set())),
509 );
510
511 const listenOptions = host ? { host, port } : { port };
512
513 const orchestrationEngine = yield* OrchestrationEngineService;
514 const projectionReadModelQuery = yield* ProjectionSnapshotQuery;
515 const checkpointDiffQuery = yield* CheckpointDiffQuery;
516 const liveProviderService = yield* ProviderService;
517 const orchestrationReactor = yield* OrchestrationReactor;
518 const { openInEditor } = yield* Open;
519
520 const subscriptionsScope = yield* Scope.make("sequential");
521 yield* Effect.addFinalizer(() => Scope.close(subscriptionsScope, Exit.void));
522
523 yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) =>
524 broadcastPush({
525 type: "push",
526 channel: ORCHESTRATION_WS_CHANNELS.domainEvent,
527 data: event,
528 }),
529 ).pipe(Effect.forkIn(subscriptionsScope));
530
531 yield* Stream.runForEach(keybindingsManager.changes, (event) =>
532 broadcastPush({
533 type: "push",
534 channel: WS_CHANNELS.serverConfigUpdated,
535 data: event,
536 }),
537 ).pipe(Effect.forkIn(subscriptionsScope));
538
539 yield* Scope.provide(orchestrationReactor.start, subscriptionsScope);
540
541 let welcomeBootstrapProjectId: ProjectId | undefined;
542 let welcomeBootstrapThreadId: ThreadId | undefined;
543
544 if (autoBootstrapProjectFromCwd) {
545 yield* Effect.gen(function* () {
546 const snapshot = yield* projectionReadModelQuery.getSnapshot();
547 const existingProject = snapshot.projects.find(
548 (project) => project.workspaceRoot === cwd && project.deletedAt === null,
549 );
550 let bootstrapProjectId: ProjectId;
551 let bootstrapProjectDefaultModel: string;
552
553 if (!existingProject) {
554 const createdAt = new Date().toISOString();
555 bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
556 const bootstrapProjectTitle = path.basename(cwd) || "project";
557 bootstrapProjectDefaultModel = "gpt-5-codex";
558 yield* orchestrationEngine.dispatch({
559 type: "project.create",
560 commandId: CommandId.makeUnsafe(crypto.randomUUID()),
561 projectId: bootstrapProjectId,
562 title: bootstrapProjectTitle,
563 workspaceRoot: cwd,
564 defaultModel: bootstrapProjectDefaultModel,
565 createdAt,
566 });
567 } else {
568 bootstrapProjectId = existingProject.id;
569 bootstrapProjectDefaultModel = existingProject.defaultModel ?? "gpt-5-codex";
570 }
571
572 const existingThread = snapshot.threads.find(
573 (thread) => thread.projectId === bootstrapProjectId && thread.deletedAt === null,
574 );
575 if (!existingThread) {
576 const createdAt = new Date().toISOString();
577 const threadId = ThreadId.makeUnsafe(crypto.randomUUID());
578 yield* orchestrationEngine.dispatch({
579 type: "thread.create",
580 commandId: CommandId.makeUnsafe(crypto.randomUUID()),
581 threadId,
582 projectId: bootstrapProjectId,
583 title: "New thread",
584 model: bootstrapProjectDefaultModel,
585 branch: null,
586 worktreePath: null,
587 createdAt,
588 });
589 welcomeBootstrapProjectId = bootstrapProjectId;
590 welcomeBootstrapThreadId = threadId;
591 } else {
592 welcomeBootstrapProjectId = bootstrapProjectId;
593 welcomeBootstrapThreadId = existingThread.id;
594 }
595 }).pipe(
596 Effect.mapError(
597 (cause) => new ServerLifecycleError({ operation: "autoBootstrapProject", cause }),
598 ),
599 );
600 }
601
602 const routeRequest = Effect.fnUntraced(function* (request: WebSocketRequest) {
603 switch (request.body._tag) {
604 case ORCHESTRATION_WS_METHODS.getSnapshot:
605 return yield* projectionReadModelQuery.getSnapshot();
606
607 case ORCHESTRATION_WS_METHODS.dispatchCommand: {
608 const { command } = request.body;
609 const normalizedCommand = yield* normalizeDispatchCommand({ command });
610 return yield* orchestrationEngine.dispatch(normalizedCommand);
611 }
612
613 case ORCHESTRATION_WS_METHODS.getTurnDiff: {
614 const body = stripRequestTag(request.body);
615 return yield* checkpointDiffQuery.getTurnDiff(body);
616 }
617
618 case ORCHESTRATION_WS_METHODS.getFullThreadDiff: {
619 const body = stripRequestTag(request.body);
620 return yield* checkpointDiffQuery.getFullThreadDiff(body);
621 }
622
623 case ORCHESTRATION_WS_METHODS.replayEvents: {
624 const { fromSequenceExclusive } = request.body;
625 return yield* Stream.runCollect(
626 orchestrationEngine.readEvents(
627 clamp(fromSequenceExclusive, {
628 maximum: Number.MAX_SAFE_INTEGER,
629 minimum: 0,
630 }),
631 ),
632 ).pipe(Effect.map((events) => Array.from(events)));
633 }
634
635 case WS_METHODS.projectsSearchEntries: {
636 const body = stripRequestTag(request.body);
637 return yield* Effect.tryPromise({
638 try: () => searchWorkspaceEntries(body),
639 catch: (cause) =>
640 new RouteRequestError({
641 message: `Failed to search workspace entries: ${String(cause)}`,
642 }),
643 });
644 }
645
646 case WS_METHODS.shellOpenInEditor: {
647 const body = stripRequestTag(request.body);
648 return yield* openInEditor(body);
649 }
650
651 case WS_METHODS.gitStatus: {
652 const body = stripRequestTag(request.body);
653 return yield* gitManager.status(body);
654 }
655
656 case WS_METHODS.gitPull: {
657 const body = stripRequestTag(request.body);
658 return yield* git.pullCurrentBranch(body.cwd);
659 }
660
661 case WS_METHODS.gitRunStackedAction: {
662 const body = stripRequestTag(request.body);
663 return yield* gitManager.runStackedAction(body);
664 }
665
666 case WS_METHODS.gitListBranches: {
667 const body = stripRequestTag(request.body);
668 return yield* git.listBranches(body);
669 }
670
671 case WS_METHODS.gitCreateWorktree: {
672 const body = stripRequestTag(request.body);
673 return yield* git.createWorktree(body);
674 }
675
676 case WS_METHODS.gitRemoveWorktree: {
677 const body = stripRequestTag(request.body);
678 return yield* git.removeWorktree(body);
679 }
680
681 case WS_METHODS.gitCreateBranch: {
682 const body = stripRequestTag(request.body);
683 return yield* git.createBranch(body);
684 }
685
686 case WS_METHODS.gitCheckout: {
687 const body = stripRequestTag(request.body);
688 return yield* git.checkoutBranch(body);
689 }
690
691 case WS_METHODS.gitInit: {
692 const body = stripRequestTag(request.body);
693 return yield* git.initRepo(body);
694 }
695
696 case WS_METHODS.terminalOpen: {
697 const body = stripRequestTag(request.body);
698 return yield* terminalManager.open(body);
699 }
700
701 case WS_METHODS.terminalWrite: {
702 const body = stripRequestTag(request.body);
703 return yield* terminalManager.write(body);
704 }
705
706 case WS_METHODS.terminalResize: {
707 const body = stripRequestTag(request.body);
708 return yield* terminalManager.resize(body);
709 }
710
711 case WS_METHODS.terminalClear: {
712 const body = stripRequestTag(request.body);
713 return yield* terminalManager.clear(body);
714 }
715
716 case WS_METHODS.terminalRestart: {
717 const body = stripRequestTag(request.body);
718 return yield* terminalManager.restart(body);
719 }
720
721 case WS_METHODS.terminalClose: {
722 const body = stripRequestTag(request.body);
723 return yield* terminalManager.close(body);
724 }
725
726 case WS_METHODS.serverGetConfig:
727 const keybindingsConfig = yield* keybindingsManager.loadConfigState;
728 return {
729 cwd,
730 keybindingsConfigPath,
731 keybindings: keybindingsConfig.keybindings,
732 issues: keybindingsConfig.issues,
733 };
734
735 case WS_METHODS.serverUpsertKeybinding: {
736 const body = stripRequestTag(request.body);
737 const keybindingsConfig = yield* keybindingsManager.upsertKeybindingRule(body);
738 return { keybindings: keybindingsConfig, issues: [] };
739 }
740
741 default: {
742 const _exhaustiveCheck: never = request.body;
743 return yield* new RouteRequestError({
744 message: `Unknown method: ${String(_exhaustiveCheck)}`,
745 });
746 }
747 }
748 });
749
750 const handleMessage = Effect.fnUntraced(function* (ws: WebSocket, raw: unknown) {
751 const encodeResponse = Schema.encodeEffect(Schema.fromJsonString(WsResponse));
752
753 const messageText = websocketRawToString(raw);
754 if (messageText === null) {
755 const errorResponse = yield* encodeResponse({
756 id: "unknown",
757 error: { message: "Invalid request format: Failed to read message" },
758 });
759 ws.send(errorResponse);
760 return;
761 }
762
763 const request = Schema.decodeExit(Schema.fromJsonString(WebSocketRequest))(messageText);
764 if (request._tag === "Failure") {
765 const errorResponse = yield* encodeResponse({
766 id: "unknown",
767 error: { message: `Invalid request format: ${Cause.pretty(request.cause)}` },
768 });
769 ws.send(errorResponse);
770 return;
771 }
772
773 const result = yield* Effect.exit(routeRequest(request.value));
774 if (result._tag === "Failure") {
775 const errorResponse = yield* encodeResponse({
776 id: request.value.id,
777 error: { message: Cause.pretty(result.cause) },
778 });
779 ws.send(errorResponse);
780 return;
781 }
782
783 const response = yield* encodeResponse({
784 id: request.value.id,
785 result: result.value,
786 });
787 ws.send(response);
788 });
789
790 httpServer.on("upgrade", (request, socket, head) => {
791 socket.on("error", () => {}); // Prevent unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake
792
793 if (authToken) {
794 let providedToken: string | null = null;
795 try {
796 const url = new URL(request.url ?? "/", `http://localhost:${port}`);
797 providedToken = url.searchParams.get("token");
798 } catch {
799 rejectUpgrade(socket, 400, "Invalid WebSocket URL");
800 return;
801 }
802
803 if (providedToken !== authToken) {
804 rejectUpgrade(socket, 401, "Unauthorized WebSocket connection");
805 return;
806 }
807 }
808
809 wss.handleUpgrade(request, socket, head, (ws) => {
810 wss.emit("connection", ws, request);
811 });
812 });
813
814 wss.on("connection", (ws) => {
815 void Effect.runPromise(Ref.update(clients, (clients) => clients.add(ws)));
816
817 const segments = cwd.split(/[/\\]/).filter(Boolean);
818 const projectName = segments[segments.length - 1] ?? "project";
819
820 const welcome: WsPush = {
821 type: "push",
822 channel: WS_CHANNELS.serverWelcome,
823 data: {
824 cwd,
825 projectName,
826 ...(welcomeBootstrapProjectId ? { bootstrapProjectId: welcomeBootstrapProjectId } : {}),
827 ...(welcomeBootstrapThreadId ? { bootstrapThreadId: welcomeBootstrapThreadId } : {}),
828 },
829 };
830 logOutgoingPush(welcome, 1);
831 ws.send(JSON.stringify(welcome));
832
833 ws.on("message", (raw) => {
834 void Effect.runPromise(
835 handleMessage(ws, raw).pipe(
836 Effect.catch((error) => Effect.logError("Error handling message", error)),
837 ),
838 );
839 });
840
841 ws.on("close", () => {
842 void Effect.runPromise(
843 Ref.update(clients, (clients) => {
844 clients.delete(ws);
845 return clients;
846 }),
847 );
848 });
849
850 ws.on("error", () => {
851 void Effect.runPromise(
852 Ref.update(clients, (clients) => {
853 clients.delete(ws);
854 return clients;
855 }),
856 );
857 });
858 });
859
860 yield* Effect.addFinalizer(() =>
861 Effect.catch(liveProviderService.stopAll(), (cause) =>
862 Effect.logWarning("failed to stop provider service", { cause }),
863 ),
864 );
865
866 const unsubscribeTerminalEvents = yield* terminalManager.subscribe(
867 (event) => void Effect.runPromise(onTerminalEvent(event)),
868 );
869 yield* Effect.addFinalizer(() => Effect.sync(() => unsubscribeTerminalEvents()));
870
871 yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
872 Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
873 );
874
875 yield* Effect.addFinalizer(() =>
876 Effect.all([
877 closeAllClients,
878 closeWebSocketServer.pipe(
879 Effect.catch((error) =>
880 Effect.logWarning("failed to close web socket server", { cause: error }),
881 ),
882 ),
883 ]),
884 );
885
886 return httpServer;
887});
888
889export const ServerLive = Layer.succeed(Server, {
890 start: createServer(),
891 stopSignal: Effect.never,
892} satisfies ServerShape);