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