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

wsServer.ts

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