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