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