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

wsServer.ts

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