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

wsServer.ts

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