Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

wsServer.ts

1,065 lines33.4 KB

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