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

wsServer.ts

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