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