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