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

wsServer.ts

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