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

wsServer.ts

1,060 lines34.4 KB

1/**
2 * Server - HTTP/WebSocket server service interface.
3 *
4 * Owns startup and shutdown lifecycle of the HTTP server, static asset serving,
5 * and WebSocket request routing.
6 *
7 * @module Server
8 */
9import http from "node:http";
10import type { Duplex } from "node:stream";
11​
12import Mime from "@effect/platform-node/Mime";
13import {
14 CommandId,
15 DEFAULT_PROVIDER_INTERACTION_MODE,
16 type ClientOrchestrationCommand,
17 type OrchestrationCommand,
18 ORCHESTRATION_WS_CHANNELS,
19 ORCHESTRATION_WS_METHODS,
20 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
21 ProjectId,
22 ThreadId,
23 WS_CHANNELS,
24 WS_METHODS,
25 WebSocketRequest,
26 type WsResponse as WsResponseMessage,
27 WsResponse,
28 type WsPushEnvelopeBase,
29} from "@t3tools/contracts";
30import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
31import {
32 Cause,
33 Effect,
34 Exit,
35 FileSystem,
36 Layer,
37 Path,
38 Ref,
39 Result,
40 Schema,
41 Scope,
42 ServiceMap,
43 Stream,
44 Struct,
45} from "effect";
46import { WebSocketServer, type WebSocket } from "ws";
47​
48import { createLogger } from "./logger";
49import { GitManager } from "./git/Services/GitManager.ts";
50import { TerminalManager } from "./terminal/Services/Manager.ts";
51import { Keybindings } from "./keybindings";
52import { ServerSettingsService } from "./serverSettings";
53import { searchWorkspaceEntries } from "./workspaceEntries";
54import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine";
55import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
56import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor";
57import { ProviderService } from "./provider/Services/ProviderService";
58import { ProviderRegistry } from "./provider/Services/ProviderRegistry";
59import { CheckpointDiffQuery } from "./checkpointing/Services/CheckpointDiffQuery";
60import { clamp } from "effect/Number";
61import { Open, resolveAvailableEditors } from "./open";
62import { ServerConfig } from "./config";
63import { GitCore } from "./git/Services/GitCore.ts";
64import { tryHandleProjectFaviconRequest } from "./projectFaviconRoute";
65import {
66 ATTACHMENTS_ROUTE_PREFIX,
67 normalizeAttachmentRelativePath,
68 resolveAttachmentRelativePath,
69} from "./attachmentPaths";
70​
71import {
72 createAttachmentId,
73 resolveAttachmentPath,
74 resolveAttachmentPathById,
75} from "./attachmentStore.ts";
76import { parseBase64DataUrl } from "./imageMime.ts";
77import { AnalyticsService } from "./telemetry/Services/AnalyticsService.ts";
78import { expandHomePath } from "./os-jank.ts";
79import { makeServerPushBus } from "./wsServer/pushBus.ts";
80import { makeServerReadiness } from "./wsServer/readiness.ts";
81import { decodeJsonResult, formatSchemaError } from "@t3tools/shared/schemaJson";
82​
83/**
84 * ServerShape - Service API for server lifecycle control.
85 */
86export interface ServerShape {
87 /**
88 * Start HTTP and WebSocket listeners.
89 */
90 readonly start: Effect.Effect<
91 http.Server,
92 ServerLifecycleError,
93 Scope.Scope | ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
94 >;
95​
96 /**
97 * Wait for process shutdown signals.
98 */
99 readonly stopSignal: Effect.Effect<void, never>;
101​
102/**
103 * Server - Service tag for HTTP/WebSocket lifecycle management.
104 */
105export class Server extends ServiceMap.Service<Server, ServerShape>()("t3/wsServer/Server") {}
106​
107const isServerNotRunningError = (error: Error): boolean => {
108 const maybeCode = (error as NodeJS.ErrnoException).code;
109 return (
110 maybeCode === "ERR_SERVER_NOT_RUNNING" || error.message.toLowerCase().includes("not running")
111 );
112};
113​
114function rejectUpgrade(socket: Duplex, statusCode: number, message: string): void {
115 socket.end(
116 `HTTP/1.1 ${statusCode} ${statusCode === 401 ? "Unauthorized" : "Bad Request"}\r\n` +
117 "Connection: close\r\n" +
118 "Content-Type: text/plain\r\n" +
119 `Content-Length: ${Buffer.byteLength(message)}\r\n` +
120 "\r\n" +
121 message,
122 );
124​
125function websocketRawToString(raw: unknown): string | null {
126 if (typeof raw === "string") {
127 return raw;
128 }
129 if (raw instanceof Uint8Array) {
130 return Buffer.from(raw).toString("utf8");
131 }
132 if (raw instanceof ArrayBuffer) {
133 return Buffer.from(new Uint8Array(raw)).toString("utf8");
134 }
135 if (Array.isArray(raw)) {
136 const chunks: string[] = [];
137 for (const chunk of raw) {
138 if (typeof chunk === "string") {
139 chunks.push(chunk);
140 continue;
141 }
142 if (chunk instanceof Uint8Array) {
143 chunks.push(Buffer.from(chunk).toString("utf8"));
144 continue;
145 }
146 if (chunk instanceof ArrayBuffer) {
147 chunks.push(Buffer.from(new Uint8Array(chunk)).toString("utf8"));
148 continue;
149 }
150 return null;
151 }
152 return chunks.join("");
153 }
154 return null;
156​
157function toPosixRelativePath(input: string): string {
158 return input.replaceAll("\\", "/");
160​
161function resolveWorkspaceWritePath(params: {
162 workspaceRoot: string;
163 relativePath: string;
164 path: Path.Path;
165}): Effect.Effect<{ absolutePath: string; relativePath: string }, RouteRequestError> {
166 const normalizedInputPath = params.relativePath.trim();
167 if (params.path.isAbsolute(normalizedInputPath)) {
168 return Effect.fail(
169 new RouteRequestError({
170 message: "Workspace file path must be relative to the project root.",
171 }),
172 );
173 }
174​
175 const absolutePath = params.path.resolve(params.workspaceRoot, normalizedInputPath);
176 const relativeToRoot = toPosixRelativePath(
177 params.path.relative(params.workspaceRoot, absolutePath),
178 );
179 if (
180 relativeToRoot.length === 0 ||
181 relativeToRoot === "." ||
182 relativeToRoot.startsWith("../") ||
183 relativeToRoot === ".." ||
184 params.path.isAbsolute(relativeToRoot)
185 ) {
186 return Effect.fail(
187 new RouteRequestError({
188 message: "Workspace file path must stay within the project root.",
189 }),
190 );
191 }
192​
193 return Effect.succeed({
194 absolutePath,
195 relativePath: relativeToRoot,
196 });
198​
199function stripRequestTag<T extends { _tag: string }>(body: T) {
200 return Struct.omit(body, ["_tag"]);
202​
203const encodeWsResponse = Schema.encodeEffect(Schema.fromJsonString(WsResponse));
204const decodeWebSocketRequest = decodeJsonResult(WebSocketRequest);
205​
206export type ServerCoreRuntimeServices =
207 | OrchestrationEngineService
208 | ProjectionSnapshotQuery
209 | CheckpointDiffQuery
210 | OrchestrationReactor
211 | ProviderService
212 | ProviderRegistry;
213​
214export type ServerRuntimeServices =
215 | ServerCoreRuntimeServices
216 | GitManager
217 | GitCore
218 | TerminalManager
219 | Keybindings
220 | ServerSettingsService
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 runtimeServices = yield* Effect.services<
256 ServerRuntimeServices | ServerConfig | FileSystem.FileSystem | Path.Path
257 >();
258 const runPromise = Effect.runPromiseWith(runtimeServices);
259​
260 const gitManager = yield* GitManager;
261 const terminalManager = yield* TerminalManager;
262 const keybindingsManager = yield* Keybindings;
263 const serverSettingsManager = yield* ServerSettingsService;
264 const providerRegistry = yield* ProviderRegistry;
265 const git = yield* GitCore;
266 const fileSystem = yield* FileSystem.FileSystem;
267 const path = yield* Path.Path;
268​
269 yield* keybindingsManager.syncDefaultKeybindingsOnStartup.pipe(
270 Effect.catch((error) =>
271 Effect.logWarning("failed to sync keybindings defaults on startup", {
272 path: error.configPath,
273 detail: error.detail,
274 cause: error.cause,
275 }),
276 ),
277 );
278​
279 const providersRef = yield* Ref.make(yield* providerRegistry.getProviders);
280​
281 const clients = yield* Ref.make(new Set<WebSocket>());
282 const logger = createLogger("ws");
283 const readiness = yield* makeServerReadiness;
284​
285 function logOutgoingPush(push: WsPushEnvelopeBase, recipients: number) {
286 if (!logWebSocketEvents) return;
287 logger.event("outgoing push", {
288 channel: push.channel,
289 sequence: push.sequence,
290 recipients,
291 payload: push.data,
292 });
293 }
294​
295 const pushBus = yield* makeServerPushBus({
296 clients,
297 logOutgoingPush,
298 });
299 yield* readiness.markPushBusReady;
300 yield* keybindingsManager.start.pipe(
301 Effect.mapError(
302 (cause) => new ServerLifecycleError({ operation: "keybindingsRuntimeStart", cause }),
303 ),
304 );
305 yield* readiness.markKeybindingsReady;
306 yield* serverSettingsManager.start.pipe(
307 Effect.mapError(
308 (cause) => new ServerLifecycleError({ operation: "serverSettingsRuntimeStart", cause }),
309 ),
310 );
311​
312 const normalizeDispatchCommand = Effect.fnUntraced(function* (input: {
313 readonly command: ClientOrchestrationCommand;
314 }) {
315 const normalizeProjectWorkspaceRoot = Effect.fnUntraced(function* (workspaceRoot: string) {
316 const normalizedWorkspaceRoot = path.resolve(yield* expandHomePath(workspaceRoot.trim()));
317 const workspaceStat = yield* fileSystem
318 .stat(normalizedWorkspaceRoot)
319 .pipe(Effect.catch(() => Effect.succeed(null)));
320 if (!workspaceStat) {
321 return yield* new RouteRequestError({
322 message: `Project directory does not exist: ${normalizedWorkspaceRoot}`,
323 });
324 }
325 if (workspaceStat.type !== "Directory") {
326 return yield* new RouteRequestError({
327 message: `Project path is not a directory: ${normalizedWorkspaceRoot}`,
328 });
329 }
330 return normalizedWorkspaceRoot;
331 });
332​
333 if (input.command.type === "project.create") {
334 return {
335 ...input.command,
336 workspaceRoot: yield* normalizeProjectWorkspaceRoot(input.command.workspaceRoot),
337 } satisfies OrchestrationCommand;
338 }
339​
340 if (input.command.type === "project.meta.update" && input.command.workspaceRoot !== undefined) {
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 attachmentsDir: serverConfig.attachmentsDir,
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 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 attachmentsDir: serverConfig.attachmentsDir,
457 attachmentId: normalizedRelativePath,
458 })
459 : resolveAttachmentRelativePath({
460 attachmentsDir: serverConfig.attachmentsDir,
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 (Exit.isFailure(streamExit)) {
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 pushBus.publishAll(ORCHESTRATION_WS_CHANNELS.domainEvent, event),
625 ).pipe(Effect.forkIn(subscriptionsScope));
626​
627 yield* Stream.runForEach(keybindingsManager.streamChanges, (event) =>
628 pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
629 issues: event.issues,
630 }),
631 ).pipe(Effect.forkIn(subscriptionsScope));
632​
633 yield* Stream.runForEach(serverSettingsManager.streamChanges, (settings) =>
634 pushBus.publishAll(WS_CHANNELS.serverConfigUpdated, {
635 issues: [],
636 settings,
637 }),
638 ).pipe(Effect.forkIn(subscriptionsScope));
639​
640 yield* Stream.runForEach(providerRegistry.streamChanges, (providers) =>
641 Effect.gen(function* () {
642 yield* Ref.set(providersRef, providers);
643 yield* pushBus.publishAll(WS_CHANNELS.serverProvidersUpdated, {
644 providers,
645 });
646 }),
647 ).pipe(Effect.forkIn(subscriptionsScope));
648​
649 yield* Scope.provide(orchestrationReactor.start(), subscriptionsScope);
650 yield* readiness.markOrchestrationSubscriptionsReady;
651​
652 let welcomeBootstrapProjectId: ProjectId | undefined;
653 let welcomeBootstrapThreadId: ThreadId | undefined;
654​
655 if (autoBootstrapProjectFromCwd) {
656 yield* Effect.gen(function* () {
657 const snapshot = yield* projectionReadModelQuery.getSnapshot();
658 const existingProject = snapshot.projects.find(
659 (project) => project.workspaceRoot === cwd && project.deletedAt === null,
660 );
661 let bootstrapProjectId: ProjectId;
662 let bootstrapProjectDefaultModelSelection;
663​
664 if (!existingProject) {
665 const createdAt = new Date().toISOString();
666 bootstrapProjectId = ProjectId.makeUnsafe(crypto.randomUUID());
667 const bootstrapProjectTitle = path.basename(cwd) || "project";
668 bootstrapProjectDefaultModelSelection = {
669 provider: "codex" as const,
670 model: "gpt-5-codex",
671 };
672 yield* orchestrationEngine.dispatch({
673 type: "project.create",
674 commandId: CommandId.makeUnsafe(crypto.randomUUID()),
675 projectId: bootstrapProjectId,
676 title: bootstrapProjectTitle,
677 workspaceRoot: cwd,
678 defaultModelSelection: bootstrapProjectDefaultModelSelection,
679 createdAt,
680 });
681 } else {
682 bootstrapProjectId = existingProject.id;
683 bootstrapProjectDefaultModelSelection = existingProject.defaultModelSelection ?? {
684 provider: "codex" as const,
685 model: "gpt-5-codex",
686 };
687 }
688​
689 const existingThread = snapshot.threads.find(
690 (thread) => thread.projectId === bootstrapProjectId && thread.deletedAt === null,
691 );
692 if (!existingThread) {
693 const createdAt = new Date().toISOString();
694 const threadId = ThreadId.makeUnsafe(crypto.randomUUID());
695 yield* orchestrationEngine.dispatch({
696 type: "thread.create",
697 commandId: CommandId.makeUnsafe(crypto.randomUUID()),
698 threadId,
699 projectId: bootstrapProjectId,
700 title: "New thread",
701 modelSelection: bootstrapProjectDefaultModelSelection,
702 interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
703 runtimeMode: "full-access",
704 branch: null,
705 worktreePath: null,
706 createdAt,
707 });
708 welcomeBootstrapProjectId = bootstrapProjectId;
709 welcomeBootstrapThreadId = threadId;
710 } else {
711 welcomeBootstrapProjectId = bootstrapProjectId;
712 welcomeBootstrapThreadId = existingThread.id;
713 }
714 }).pipe(
715 Effect.mapError(
716 (cause) => new ServerLifecycleError({ operation: "autoBootstrapProject", cause }),
717 ),
718 );
719 }
720​
721 const unsubscribeTerminalEvents = yield* terminalManager.subscribe((event) =>
722 pushBus.publishAll(WS_CHANNELS.terminalEvent, event),
723 );
724 yield* Scope.addFinalizer(subscriptionsScope, Effect.sync(unsubscribeTerminalEvents));
725 yield* readiness.markTerminalSubscriptionsReady;
726​
727 yield* NodeHttpServer.make(() => httpServer, listenOptions).pipe(
728 Effect.mapError((cause) => new ServerLifecycleError({ operation: "httpServerListen", cause })),
729 );
730 yield* readiness.markHttpListening;
731​
732 yield* Effect.addFinalizer(() =>
733 Effect.all([closeAllClients, closeWebSocketServer.pipe(Effect.ignoreCause({ log: true }))]),
734 );
735​
736 const routeRequest = Effect.fnUntraced(function* (ws: WebSocket, request: WebSocketRequest) {
737 switch (request.body._tag) {
738 case ORCHESTRATION_WS_METHODS.getSnapshot:
739 return yield* projectionReadModelQuery.getSnapshot();
740​
741 case ORCHESTRATION_WS_METHODS.dispatchCommand: {
742 const { command } = request.body;
743 const normalizedCommand = yield* normalizeDispatchCommand({ command });
744 return yield* orchestrationEngine.dispatch(normalizedCommand);
745 }
746​
747 case ORCHESTRATION_WS_METHODS.getTurnDiff: {
748 const body = stripRequestTag(request.body);
749 return yield* checkpointDiffQuery.getTurnDiff(body);
750 }
751​
752 case ORCHESTRATION_WS_METHODS.getFullThreadDiff: {
753 const body = stripRequestTag(request.body);
754 return yield* checkpointDiffQuery.getFullThreadDiff(body);
755 }
756​
757 case ORCHESTRATION_WS_METHODS.replayEvents: {
758 const { fromSequenceExclusive } = request.body;
759 return yield* Stream.runCollect(
760 orchestrationEngine.readEvents(
761 clamp(fromSequenceExclusive, {
762 maximum: Number.MAX_SAFE_INTEGER,
763 minimum: 0,
764 }),
765 ),
766 ).pipe(Effect.map((events) => Array.from(events)));
767 }
768​
769 case WS_METHODS.projectsSearchEntries: {
770 const body = stripRequestTag(request.body);
771 return yield* Effect.tryPromise({
772 try: () => searchWorkspaceEntries(body),
773 catch: (cause) =>
774 new RouteRequestError({
775 message: `Failed to search workspace entries: ${String(cause)}`,
776 }),
777 });
778 }
779​
780 case WS_METHODS.projectsWriteFile: {
781 const body = stripRequestTag(request.body);
782 const target = yield* resolveWorkspaceWritePath({
783 workspaceRoot: body.cwd,
784 relativePath: body.relativePath,
785 path,
786 });
787 yield* fileSystem
788 .makeDirectory(path.dirname(target.absolutePath), { recursive: true })
789 .pipe(
790 Effect.mapError(
791 (cause) =>
792 new RouteRequestError({
793 message: `Failed to prepare workspace path: ${String(cause)}`,
794 }),
795 ),
796 );
797 yield* fileSystem.writeFileString(target.absolutePath, body.contents).pipe(
798 Effect.mapError(
799 (cause) =>
800 new RouteRequestError({
801 message: `Failed to write workspace file: ${String(cause)}`,
802 }),
803 ),
804 );
805 return { relativePath: target.relativePath };
806 }
807​
808 case WS_METHODS.shellOpenInEditor: {
809 const body = stripRequestTag(request.body);
810 return yield* openInEditor(body);
811 }
812​
813 case WS_METHODS.gitStatus: {
814 const body = stripRequestTag(request.body);
815 return yield* gitManager.status(body);
816 }
817​
818 case WS_METHODS.gitPull: {
819 const body = stripRequestTag(request.body);
820 return yield* git.pullCurrentBranch(body.cwd);
821 }
822​
823 case WS_METHODS.gitRunStackedAction: {
824 const body = stripRequestTag(request.body);
825 return yield* gitManager.runStackedAction(body, {
826 actionId: body.actionId,
827 progressReporter: {
828 publish: (event) =>
829 pushBus.publishClient(ws, WS_CHANNELS.gitActionProgress, event).pipe(Effect.asVoid),
830 },
831 });
832 }
833​
834 case WS_METHODS.gitResolvePullRequest: {
835 const body = stripRequestTag(request.body);
836 return yield* gitManager.resolvePullRequest(body);
837 }
838​
839 case WS_METHODS.gitPreparePullRequestThread: {
840 const body = stripRequestTag(request.body);
841 return yield* gitManager.preparePullRequestThread(body);
842 }
843​
844 case WS_METHODS.gitListBranches: {
845 const body = stripRequestTag(request.body);
846 return yield* git.listBranches(body);
847 }
848​
849 case WS_METHODS.gitCreateWorktree: {
850 const body = stripRequestTag(request.body);
851 return yield* git.createWorktree(body);
852 }
853​
854 case WS_METHODS.gitRemoveWorktree: {
855 const body = stripRequestTag(request.body);
856 return yield* git.removeWorktree(body);
857 }
858​
859 case WS_METHODS.gitCreateBranch: {
860 const body = stripRequestTag(request.body);
861 return yield* git.createBranch(body);
862 }
863​
864 case WS_METHODS.gitCheckout: {
865 const body = stripRequestTag(request.body);
866 return yield* Effect.scoped(git.checkoutBranch(body));
867 }
868​
869 case WS_METHODS.gitInit: {
870 const body = stripRequestTag(request.body);
871 return yield* git.initRepo(body);
872 }
873​
874 case WS_METHODS.terminalOpen: {
875 const body = stripRequestTag(request.body);
876 return yield* terminalManager.open(body);
877 }
878​
879 case WS_METHODS.terminalWrite: {
880 const body = stripRequestTag(request.body);
881 return yield* terminalManager.write(body);
882 }
883​
884 case WS_METHODS.terminalResize: {
885 const body = stripRequestTag(request.body);
886 return yield* terminalManager.resize(body);
887 }
888​
889 case WS_METHODS.terminalClear: {
890 const body = stripRequestTag(request.body);
891 return yield* terminalManager.clear(body);
892 }
893​
894 case WS_METHODS.terminalRestart: {
895 const body = stripRequestTag(request.body);
896 return yield* terminalManager.restart(body);
897 }
898​
899 case WS_METHODS.terminalClose: {
900 const body = stripRequestTag(request.body);
901 return yield* terminalManager.close(body);
902 }
903​
904 case WS_METHODS.serverGetConfig: {
905 const keybindingsConfig = yield* keybindingsManager.loadConfigState;
906 const settings = yield* serverSettingsManager.getSettings;
907 const providers = yield* Ref.get(providersRef);
908 return {
909 cwd,
910 keybindingsConfigPath,
911 keybindings: keybindingsConfig.keybindings,
912 issues: keybindingsConfig.issues,
913 providers,
914 availableEditors,
915 settings,
916 };
917 }
918​
919 case WS_METHODS.serverRefreshProviders: {
920 const providers = yield* providerRegistry.refresh();
921 yield* Ref.set(providersRef, providers);
922 return { providers };
923 }
924​
925 case WS_METHODS.serverUpsertKeybinding: {
926 const body = stripRequestTag(request.body);
927 const keybindingsConfig = yield* keybindingsManager.upsertKeybindingRule(body);
928 return { keybindings: keybindingsConfig, issues: [] };
929 }
930​
931 case WS_METHODS.serverGetSettings: {
932 return yield* serverSettingsManager.getSettings;
933 }
934​
935 case WS_METHODS.serverUpdateSettings: {
936 const body = stripRequestTag(request.body);
937 return yield* serverSettingsManager.updateSettings(body.patch);
938 }
939​
940 default: {
941 const _exhaustiveCheck: never = request.body;
942 return yield* new RouteRequestError({
943 message: `Unknown method: ${String(_exhaustiveCheck)}`,
944 });
945 }
946 }
947 });
948​
949 const handleMessage = Effect.fnUntraced(function* (ws: WebSocket, raw: unknown) {
950 const sendWsResponse = (response: WsResponseMessage) =>
951 encodeWsResponse(response).pipe(
952 Effect.tap((encodedResponse) => Effect.sync(() => ws.send(encodedResponse))),
953 Effect.asVoid,
954 );
955​
956 const messageText = websocketRawToString(raw);
957 if (messageText === null) {
958 return yield* sendWsResponse({
959 id: "unknown",
960 error: { message: "Invalid request format: Failed to read message" },
961 });
962 }
963​
964 const request = decodeWebSocketRequest(messageText);
965 if (Result.isFailure(request)) {
966 return yield* sendWsResponse({
967 id: "unknown",
968 error: { message: `Invalid request format: ${formatSchemaError(request.failure)}` },
969 });
970 }
971​
972 const result = yield* Effect.exit(routeRequest(ws, request.success));
973 if (Exit.isFailure(result)) {
974 return yield* sendWsResponse({
975 id: request.success.id,
976 error: { message: Cause.pretty(result.cause) },
977 });
978 }
979​
980 return yield* sendWsResponse({
981 id: request.success.id,
982 result: result.value,
983 });
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 const segments = cwd.split(/[/\\]/).filter(Boolean);
1012 const projectName = segments[segments.length - 1] ?? "project";
1013​
1014 const welcomeData = {
1015 cwd,
1016 projectName,
1017 ...(welcomeBootstrapProjectId ? { bootstrapProjectId: welcomeBootstrapProjectId } : {}),
1018 ...(welcomeBootstrapThreadId ? { bootstrapThreadId: welcomeBootstrapThreadId } : {}),
1019 };
1020 // Send welcome before adding to broadcast set so publishAll calls
1021 // cannot reach this client before the welcome arrives.
1022 void runPromise(
1023 readiness.awaitServerReady.pipe(
1024 Effect.flatMap(() => pushBus.publishClient(ws, WS_CHANNELS.serverWelcome, welcomeData)),
1025 Effect.flatMap((delivered) =>
1026 delivered ? Ref.update(clients, (clients) => clients.add(ws)) : Effect.void,
1027 ),
1028 ),
1029 );
1030​
1031 ws.on("message", (raw) => {
1032 void runPromise(handleMessage(ws, raw).pipe(Effect.ignoreCause({ log: true })));
1033 });
1034​
1035 ws.on("close", () => {
1036 void runPromise(
1037 Ref.update(clients, (clients) => {
1038 clients.delete(ws);
1039 return clients;
1040 }),
1041 );
1042 });
1043​
1044 ws.on("error", () => {
1045 void runPromise(
1046 Ref.update(clients, (clients) => {
1047 clients.delete(ws);
1048 return clients;
1049 }),
1050 );
1051 });
1052 });
1053​
1054 return httpServer;
1055});
1056​
1057export const ServerLive = Layer.succeed(Server, {
1058 start: createServer(),
1059 stopSignal: Effect.never,
1060} satisfies ServerShape);