| @@ -12,11 +12,12 @@ import { · 11 unmodified lines |
| 12 | 12 | WS_CHANNELS, |
| 13 | 13 | WS_METHODS, |
| 14 | 14 | WebSocketRequest, |
| 15 | + WebSocketResponse, |
| 15 | 16 | WsPush, |
| 16 | 17 | WsResponse, |
| 17 | 18 | } from "@t3tools/contracts"; |
| 18 | | −import { NodeServices } from "@effect/platform-node"; |
| 19 | | −import { Effect, Exit, Layer, ManagedRuntime, Schema, Scope, ServiceMap, Stream } from "effect"; |
| 19 | +import { NodeHttpServer, NodeServices } from "@effect/platform-node"; |
| 20 | +import { Cause, Effect, Exit, Layer, Schema, Scope, ServiceMap, Stream } from "effect"; |
| 20 | 21 | import { WebSocketServer, type WebSocket } from "ws"; |
| 21 | 22 | |
| 22 | 23 | import { createLogger } from "./logger"; |
| @@ -40,34 +41,21 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderComma · 17 unmodified lines |
| 40 | 41 | import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline"; |
| 41 | 42 | import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery"; |
| 42 | 43 | import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion"; |
| 43 | | −import { |
| 44 | | − OrchestrationEngineService, |
| 45 | | − type OrchestrationEngineShape, |
| 46 | | −} from "./orchestration/Services/OrchestrationEngine"; |
| 47 | | −import { |
| 48 | | − ProjectionSnapshotQuery, |
| 49 | | − type ProjectionSnapshotQueryShape, |
| 50 | | −} from "./orchestration/Services/ProjectionSnapshotQuery"; |
| 44 | +import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine"; |
| 45 | +import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; |
| 51 | 46 | import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor"; |
| 52 | 47 | import { makeSqlitePersistenceLive } from "./persistence/Layers/Sqlite"; |
| 53 | | −import assert from "node:assert"; |
| 54 | 48 | import { OrchestrationEventStoreLive } from "./persistence/Layers/OrchestrationEventStore"; |
| 55 | 49 | import { OrchestrationCommandReceiptRepositoryLive } from "./persistence/Layers/OrchestrationCommandReceipts"; |
| 56 | 50 | import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter"; |
| 57 | 51 | import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry"; |
| 58 | 52 | import { makeProviderServiceLive } from "./provider/Layers/ProviderService"; |
| 59 | 53 | import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory"; |
| 60 | | −import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService"; |
| 54 | +import { ProviderService } from "./provider/Services/ProviderService"; |
| 61 | 55 | import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore"; |
| 62 | 56 | import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime"; |
| 63 | | −import { |
| 64 | | − CheckpointStore, |
| 65 | | − type CheckpointStoreShape, |
| 66 | | −} from "./checkpointing/Services/CheckpointStore"; |
| 67 | | −import { makeEventNdjsonLogger, type EventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger"; |
| 57 | +import { CheckpointStore } from "./checkpointing/Services/CheckpointStore"; |
| 68 | 58 | import * as SqlClient from "effect/unstable/sql/SqlClient"; |
| 69 | | −import * as SqlError from "effect/unstable/sql/SqlError"; |
| 70 | | −import * as Migrator from "effect/unstable/sql/Migrator"; |
| 71 | 59 | import { clamp } from "effect/Number"; |
| 72 | 60 | import { OpenDefaultService, type OpenShape } from "./open"; |
| 73 | 61 | |
| @@ -92,37 +80,24 @@ export interface ServerOptions { · 18 unmodified lines |
| 92 | 80 | cwd: string; |
| 93 | 81 | autoBootstrapProjectFromCwd?: boolean | undefined; |
| 94 | 82 | stateDir?: string | undefined; |
| 95 | | − persistenceLayer?: |
| 96 | | − | Layer.Layer<SqlClient.SqlClient, SqlError.SqlError | Migrator.MigrationError> |
| 97 | | − | undefined; |
| 98 | 83 | staticDir?: string | undefined; |
| 99 | 84 | devUrl?: string | undefined; |
| 100 | 85 | logWebSocketEvents?: boolean | undefined; |
| 101 | 86 | gitManager?: GitManager | undefined; |
| 102 | 87 | terminalManager?: TerminalManager | undefined; |
| 103 | | − providerLayer?: Layer.Layer<ProviderService, unknown> | undefined; |
| 104 | 88 | authToken?: string | undefined; |
| 105 | 89 | open?: OpenShape | undefined; |
| 106 | 90 | } |
| 107 | 91 | |
| 108 | | −export interface ServerRuntime { |
| 109 | | − readonly start: () => Promise<void>; |
| 110 | | − readonly stop: () => Promise<void>; |
| 111 | | − readonly httpServer: http.Server; |
| 112 | | −} |
| 113 | | − |
| 114 | 92 | export interface ServerShape { |
| 115 | | − readonly createServer: (options: ServerOptions) => ServerRuntime; |
| 93 | + readonly createServer: ( |
| 94 | + options: ServerOptions, |
| 95 | + ) => Effect.Effect<http.Server, unknown, Scope.Scope | ServerRuntimeServices>; |
| 116 | 96 | readonly stopSignal: Effect.Effect<unknown, never>; |
| 117 | 97 | } |
| 118 | 98 | |
| 119 | 99 | export class Server extends ServiceMap.Service<Server, ServerShape>()("server/Server") {} |
| 120 | 100 | |
| 121 | | −export const ServerLive = Layer.succeed(Server, { |
| 122 | | − createServer, |
| 123 | | − stopSignal: Effect.never, |
| 124 | | −} satisfies ServerShape); |
| 125 | | − |
| 126 | 101 | const isServerNotRunningError = (error: unknown): boolean => { |
| 127 | 102 | if (!(error instanceof Error)) return false; |
| 128 | 103 | const maybeCode = (error as NodeJS.ErrnoException).code; |
| @@ -195,47 +170,104 @@ function checkpointRefForThreadTurn(threadId: string, turnCount: number): Checkp · 66 unmodified lines |
| 195 | 170 | return CheckpointRef.makeUnsafe(`${CHECKPOINT_REFS_PREFIX}/${encodedThreadId}/turn/${turnCount}`); |
| 196 | 171 | } |
| 197 | 172 | |
| 198 | | −type EffectRuntime = ManagedRuntime.ManagedRuntime< |
| 173 | +export type ServerCoreRuntimeServices = |
| 199 | 174 | | OrchestrationEngineService |
| 200 | 175 | | ProjectionSnapshotQuery |
| 201 | | − | ProviderService |
| 202 | 176 | | CheckpointStore |
| 203 | | − | OrchestrationReactor, |
| 204 | | − unknown |
| 205 | | −>; |
| 177 | + | OrchestrationReactor; |
| 178 | + |
| 179 | +export type ServerRuntimeServices = ServerCoreRuntimeServices | ProviderService; |
| 206 | 180 | |
| 207 | | −export function createServer(options: ServerOptions): ServerRuntime { |
| 181 | +export function makeServerPersistenceLayer(stateDir: string) { |
| 182 | + const dbPath = path.join(stateDir, "orchestration.sqlite"); |
| 183 | + return makeSqlitePersistenceLive(dbPath); |
| 184 | +} |
| 185 | + |
| 186 | +export function makeServerProviderLayer( |
| 187 | + stateDir: string, |
| 188 | +): Layer.Layer<ProviderService, unknown, SqlClient.SqlClient> { |
| 189 | + const providerLogsDir = path.join(stateDir, "logs", "providers"); |
| 190 | + const codexAdapterLayer = makeCodexAdapterLive({ |
| 191 | + nativeEventLogPath: path.join(providerLogsDir, "provider-native.ndjson"), |
| 192 | + }); |
| 193 | + const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe(Layer.provide(codexAdapterLayer)); |
| 194 | + const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe( |
| 195 | + Layer.provide(ProviderSessionRuntimeRepositoryLive), |
| 196 | + ); |
| 197 | + return makeProviderServiceLive({ |
| 198 | + canonicalEventLogPath: path.join(providerLogsDir, "provider-canonical.ndjson"), |
| 199 | + }).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer)); |
| 200 | +} |
| 201 | + |
| 202 | +export function makeServerRuntimeServicesLayer(): Layer.Layer< |
| 203 | + ServerCoreRuntimeServices, |
| 204 | + unknown, |
| 205 | + SqlClient.SqlClient | ProviderService |
| 206 | +> { |
| 207 | + const orchestrationLayer = OrchestrationEngineLive.pipe( |
| 208 | + Layer.provide(OrchestrationProjectionPipelineLive), |
| 209 | + Layer.provide(OrchestrationEventStoreLive), |
| 210 | + Layer.provide(OrchestrationCommandReceiptRepositoryLive), |
| 211 | + ); |
| 212 | + const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer)); |
| 213 | + |
| 214 | + const runtimeServicesLayer = Layer.mergeAll( |
| 215 | + orchestrationLayer, |
| 216 | + OrchestrationProjectionSnapshotQueryLive, |
| 217 | + checkpointStoreLayer, |
| 218 | + ); |
| 219 | + const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe( |
| 220 | + Layer.provideMerge(runtimeServicesLayer), |
| 221 | + ); |
| 222 | + const providerCommandReactorLayer = ProviderCommandReactorLive.pipe( |
| 223 | + Layer.provideMerge(runtimeServicesLayer), |
| 224 | + ); |
| 225 | + const checkpointReactorLayer = CheckpointReactorLive.pipe( |
| 226 | + Layer.provideMerge(runtimeServicesLayer), |
| 227 | + ); |
| 228 | + const orchestrationReactorLayer = OrchestrationReactorLive.pipe( |
| 229 | + Layer.provideMerge(runtimeIngestionLayer), |
| 230 | + Layer.provideMerge(providerCommandReactorLayer), |
| 231 | + Layer.provideMerge(checkpointReactorLayer), |
| 232 | + ); |
| 233 | + |
| 234 | + return orchestrationReactorLayer; |
| 235 | +} |
| 236 | + |
| 237 | +export class ServerLifecycleError extends Schema.TaggedErrorClass<ServerLifecycleError>()( |
| 238 | + "ServerLifecycleError", |
| 239 | + { |
| 240 | + operation: Schema.String, |
| 241 | + cause: Schema.optional(Schema.Defect), |
| 242 | + }, |
| 243 | +) {} |
| 244 | + |
| 245 | +class RouteRequestError extends Schema.TaggedErrorClass<RouteRequestError>()("RouteRequestError", { |
| 246 | + message: Schema.String, |
| 247 | +}) {} |
| 248 | + |
| 249 | +export const createServer = Effect.fn(function* ( |
| 250 | + options: ServerOptions, |
| 251 | +): Effect.fn.Return<http.Server, unknown, Scope.Scope | ServerRuntimeServices> { |
| 208 | 252 | const { |
| 209 | 253 | port, |
| 210 | 254 | host, |
| 211 | 255 | cwd, |
| 212 | 256 | autoBootstrapProjectFromCwd = false, |
| 213 | | − stateDir, |
| 214 | | − persistenceLayer: customPersistenceLayer, |
| 215 | 257 | staticDir, |
| 216 | 258 | devUrl, |
| 217 | 259 | logWebSocketEvents: explicitLogWsEvents, |
| 218 | 260 | gitManager = new GitManager(), |
| 219 | 261 | terminalManager = new TerminalManager(), |
| 220 | | − providerLayer: customProviderLayer, |
| 221 | 262 | authToken, |
| 222 | 263 | open: openService = OpenDefaultService, |
| 223 | 264 | } = options; |
| 224 | 265 | |
| 225 | | − const resolvedStateDir = stateDir ?? path.join(os.homedir(), ".t3", "userdata"); |
| 226 | | − let effectRuntime: EffectRuntime | null = null; |
| 227 | | − let orchestrationEngine: OrchestrationEngineShape | null = null; |
| 228 | | − let projectionSnapshotQuery: ProjectionSnapshotQueryShape | null = null; |
| 229 | | − let providerService: ProviderServiceShape | null = null; |
| 230 | | − let checkpointStore: CheckpointStoreShape | null = null; |
| 231 | 266 | const clients = new Set<WebSocket>(); |
| 232 | 267 | const logger = createLogger("ws"); |
| 233 | 268 | const logWebSocketEvents = |
| 234 | 269 | explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl); |
| 235 | 270 | let keybindingsConfig = loadResolvedKeybindingsConfig(logger); |
| 236 | | − let orchestrationDomainEventLogger: EventNdjsonLogger | undefined; |
| 237 | | − let orchestrationCommandLogger: EventNdjsonLogger | undefined; |
| 238 | | − let subscriptionsScope: Scope.Closeable | null = null; |
| 239 | 271 | |
| 240 | 272 | function logOutgoingPush(push: WsPush, recipients: number) { |
| 241 | 273 | if (!logWebSocketEvents) return; |
| @@ -246,86 +278,6 @@ export function createServer(options: ServerOptions): ServerRuntime { · 4 unmodified lines |
| 246 | 278 | }); |
| 247 | 279 | } |
| 248 | 280 | |
| 249 | | − const getOrchestrationEngine = () => { |
| 250 | | − assert(orchestrationEngine, "Orchestration engine is not started"); |
| 251 | | − return orchestrationEngine; |
| 252 | | − }; |
| 253 | | − |
| 254 | | − const getEffectRuntime = () => { |
| 255 | | − assert(effectRuntime, "Effect runtime is not started"); |
| 256 | | − return effectRuntime; |
| 257 | | − }; |
| 258 | | − |
| 259 | | − const getProjectionSnapshotQuery = () => { |
| 260 | | − assert(projectionSnapshotQuery, "Projection snapshot query is not started"); |
| 261 | | − return projectionSnapshotQuery; |
| 262 | | − }; |
| 263 | | − |
| 264 | | − const getCheckpointStore = () => { |
| 265 | | − assert(checkpointStore, "Checkpoint store is not started"); |
| 266 | | − return checkpointStore; |
| 267 | | − }; |
| 268 | | − |
| 269 | | − async function bootstrapProjectForCwd() { |
| 270 | | − if (!autoBootstrapProjectFromCwd) { |
| 271 | | − return; |
| 272 | | − } |
| 273 | | − |
| 274 | | − const runtime = getEffectRuntime(); |
| 275 | | − const snapshotQuery = getProjectionSnapshotQuery(); |
| 276 | | − const engine = getOrchestrationEngine(); |
| 277 | | − const snapshot = await runtime.runPromise(snapshotQuery.getSnapshot()); |
| 278 | | − const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd); |
| 279 | | − if (existing) { |
| 280 | | − return; |
| 281 | | − } |
| 282 | | − |
| 283 | | − const createdAt = new Date().toISOString(); |
| 284 | | − const projectName = path.basename(cwd) || "project"; |
| 285 | | − await runtime.runPromise( |
| 286 | | − engine.dispatchUnknownCommand({ |
| 287 | | − type: "project.create", |
| 288 | | − commandId: crypto.randomUUID(), |
| 289 | | − projectId: crypto.randomUUID(), |
| 290 | | − title: projectName, |
| 291 | | − workspaceRoot: cwd, |
| 292 | | − defaultModel: "gpt-5-codex", |
| 293 | | − createdAt, |
| 294 | | − }), |
| 295 | | − ); |
| 296 | | − } |
| 297 | | − |
| 298 | | − const attachSubscriptionss = Effect.gen(function* () { |
| 299 | | − const orchestrationEngine = yield* OrchestrationEngineService; |
| 300 | | − const orchestrationReactor = yield* OrchestrationReactor; |
| 301 | | − subscriptionsScope = yield* Scope.make("sequential"); |
| 302 | | − |
| 303 | | − yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => |
| 304 | | − Effect.sync(() => { |
| 305 | | − orchestrationDomainEventLogger?.write({ |
| 306 | | − observedAt: new Date().toISOString(), |
| 307 | | − event, |
| 308 | | − }); |
| 309 | | − const push: WsPush = { |
| 310 | | − type: "push", |
| 311 | | − channel: ORCHESTRATION_WS_CHANNELS.domainEvent, |
| 312 | | − data: event, |
| 313 | | − }; |
| 314 | | − const message = JSON.stringify(push); |
| 315 | | − let recipients = 0; |
| 316 | | − for (const client of clients) { |
| 317 | | − if (client.readyState === client.OPEN) { |
| 318 | | − client.send(message); |
| 319 | | − recipients += 1; |
| 320 | | − } |
| 321 | | − } |
| 322 | | − logOutgoingPush(push, recipients); |
| 323 | | − }), |
| 324 | | − ).pipe(Effect.forkIn(subscriptionsScope)); |
| 325 | | − |
| 326 | | − yield* orchestrationReactor.start.pipe(Scope.provide(subscriptionsScope)); |
| 327 | | − }); |
| 328 | | − |
| 329 | 281 | const onTerminalEvent = (event: TerminalEvent) => { |
| 330 | 282 | const push: WsPush = { |
| 331 | 283 | type: "push", |
| @@ -342,7 +294,6 @@ export function createServer(options: ServerOptions): ServerRuntime { · 10 unmodified lines |
| 342 | 294 | } |
| 343 | 295 | logOutgoingPush(push, recipients); |
| 344 | 296 | }; |
| 345 | | − terminalManager.on("event", onTerminalEvent); |
| 346 | 297 | |
| 347 | 298 | // HTTP server — serves static files or redirects to Vite dev server |
| 348 | 299 | const httpServer = http.createServer((req, res) => { |
| @@ -403,104 +354,85 @@ export function createServer(options: ServerOptions): ServerRuntime { · 54 unmodified lines |
| 403 | 354 | // WebSocket server — upgrades from the HTTP server |
| 404 | 355 | const wss = new WebSocketServer({ noServer: true }); |
| 405 | 356 | |
| 406 | | − httpServer.on("upgrade", (request, socket, head) => { |
| 407 | | − if (authToken) { |
| 408 | | − let providedToken: string | null = null; |
| 409 | | − try { |
| 410 | | − const url = new URL(request.url ?? "/", `http://localhost:${port}`); |
| 411 | | − providedToken = url.searchParams.get("token"); |
| 412 | | − } catch { |
| 413 | | − rejectUpgrade(socket, 400, "Invalid WebSocket URL"); |
| 414 | | − return; |
| 415 | | − } |
| 416 | | − |
| 417 | | − if (providedToken !== authToken) { |
| 418 | | − rejectUpgrade(socket, 401, "Unauthorized WebSocket connection"); |
| 419 | | − return; |
| 357 | + const closeWebSocketServer = Effect.callback<void, ServerLifecycleError>((resume) => { |
| 358 | + wss.close((error) => { |
| 359 | + if (error && !isServerNotRunningError(error)) { |
| 360 | + resume( |
| 361 | + Effect.fail( |
| 362 | + new ServerLifecycleError({ operation: "closeWebSocketServer", cause: error }), |
| 363 | + ), |
| 364 | + ); |
| 365 | + } else { |
| 366 | + resume(Effect.void); |
| 420 | 367 | } |
| 421 | | − } |
| 422 | | − |
| 423 | | − wss.handleUpgrade(request, socket, head, (ws) => { |
| 424 | | − wss.emit("connection", ws, request); |
| 425 | 368 | }); |
| 426 | 369 | }); |
| 427 | 370 | |
| 428 | | − wss.on("connection", (ws) => { |
| 429 | | − clients.add(ws); |
| 430 | | − |
| 431 | | − // Send welcome message with project info |
| 432 | | − const segments = cwd.split(/[/\\]/).filter(Boolean); |
| 433 | | − const projectName = segments[segments.length - 1] ?? "project"; |
| 434 | | − |
| 435 | | − const welcome: WsPush = { |
| 436 | | − type: "push", |
| 437 | | − channel: WS_CHANNELS.serverWelcome, |
| 438 | | − data: { cwd, projectName }, |
| 439 | | − }; |
| 440 | | − logOutgoingPush(welcome, 1); |
| 441 | | − ws.send(JSON.stringify(welcome)); |
| 371 | + const closeAllClients = () => { |
| 372 | + for (const client of clients) { |
| 373 | + client.close(); |
| 374 | + } |
| 375 | + clients.clear(); |
| 376 | + }; |
| 442 | 377 | |
| 443 | | − ws.on("message", (raw) => { |
| 444 | | − void handleMessage(ws, raw); |
| 445 | | − }); |
| 378 | + const listenOptions = host ? { host, port } : { port }; |
| 446 | 379 | |
| 447 | | − ws.on("close", () => { |
| 448 | | − clients.delete(ws); |
| 449 | | − }); |
| 380 | + const orchestrationEngine = yield* OrchestrationEngineService; |
| 381 | + const projectionReadModelQuery = yield* ProjectionSnapshotQuery; |
| 382 | + const liveCheckpointStore = yield* CheckpointStore; |
| 383 | + const liveProviderService = yield* ProviderService; |
| 384 | + const orchestrationReactor = yield* OrchestrationReactor; |
| 450 | 385 | |
| 451 | | − ws.on("error", () => { |
| 452 | | − clients.delete(ws); |
| 453 | | − }); |
| 454 | | − }); |
| 386 | + const subscriptionsScope = yield* Scope.make("sequential"); |
| 387 | + yield* Effect.addFinalizer(() => |
| 388 | + Scope.close(subscriptionsScope, Exit.void).pipe(Effect.orElseSucceed(() => undefined)), |
| 389 | + ); |
| 455 | 390 | |
| 456 | | − async function handleMessage(ws: WebSocket, raw: unknown) { |
| 457 | | − const messageText = websocketRawToString(raw); |
| 458 | | − if (messageText === null) { |
| 459 | | − const errorResponse: WsResponse = { |
| 460 | | − id: "unknown", |
| 461 | | − error: { message: "Invalid request format" }, |
| 391 | + yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => |
| 392 | + Effect.sync(() => { |
| 393 | + const push: WsPush = { |
| 394 | + type: "push", |
| 395 | + channel: ORCHESTRATION_WS_CHANNELS.domainEvent, |
| 396 | + data: event, |
| 462 | 397 | }; |
| 463 | | − ws.send(JSON.stringify(errorResponse)); |
| 464 | | − return; |
| 465 | | − } |
| 398 | + const message = JSON.stringify(push); |
| 399 | + let recipients = 0; |
| 400 | + for (const client of clients) { |
| 401 | + if (client.readyState === client.OPEN) { |
| 402 | + client.send(message); |
| 403 | + recipients += 1; |
| 404 | + } |
| 405 | + } |
| 406 | + logOutgoingPush(push, recipients); |
| 407 | + }), |
| 408 | + ).pipe(Effect.forkIn(subscriptionsScope)); |
| 466 | 409 | |
| 467 | | − let request: WebSocketRequest; |
| 468 | | − try { |
| 469 | | − request = Schema.decodeUnknownSync(Schema.fromJsonString(WebSocketRequest))(messageText); |
| 470 | | − } catch { |
| 471 | | − const errorResponse: WsResponse = { |
| 472 | | − id: "unknown", |
| 473 | | − error: { message: "Invalid request format" }, |
| 474 | | − }; |
| 475 | | − ws.send(JSON.stringify(errorResponse)); |
| 476 | | − return; |
| 477 | | − } |
| 410 | + yield* orchestrationReactor.start.pipe(Scope.provide(subscriptionsScope)); |
| 478 | 411 | |
| 479 | | − try { |
| 480 | | − const result = await routeRequest(request); |
| 481 | | − const response: WsResponse = { id: request.id, result }; |
| 482 | | − ws.send(JSON.stringify(response)); |
| 483 | | − } catch (err) { |
| 484 | | − const message = err instanceof Error ? err.message : "Unknown server error"; |
| 485 | | − const response: WsResponse = { |
| 486 | | − id: request.id, |
| 487 | | − error: { message }, |
| 488 | | − }; |
| 489 | | − ws.send(JSON.stringify(response)); |
| 412 | + if (autoBootstrapProjectFromCwd) { |
| 413 | + const snapshot = yield* projectionReadModelQuery.getSnapshot(); |
| 414 | + const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd); |
| 415 | + if (!existing) { |
| 416 | + const createdAt = new Date().toISOString(); |
| 417 | + const projectName = path.basename(cwd) || "project"; |
| 418 | + yield* orchestrationEngine.dispatchUnknownCommand({ |
| 419 | + type: "project.create", |
| 420 | + commandId: crypto.randomUUID(), |
| 421 | + projectId: crypto.randomUUID(), |
| 422 | + title: projectName, |
| 423 | + workspaceRoot: cwd, |
| 424 | + defaultModel: "gpt-5-codex", |
| 425 | + createdAt, |
| 426 | + }); |
| 490 | 427 | } |
| 491 | 428 | } |
| 492 | 429 | |
| 493 | | − async function routeRequest(request: WebSocketRequest): Promise<unknown> { |
| 494 | | − const orchestrationEngine = getOrchestrationEngine(); |
| 495 | | − const projectionReadModelQuery = getProjectionSnapshotQuery(); |
| 496 | | − const effectRuntime = getEffectRuntime(); |
| 497 | | − const liveCheckpointStore = getCheckpointStore(); |
| 498 | | − |
| 499 | | − const computeTurnDiff = async (input: { |
| 430 | + const routeRequest = Effect.fn(function* (request: WebSocketRequest) { |
| 431 | + const computeTurnDiff = Effect.fn(function* (input: { |
| 500 | 432 | readonly threadId: string; |
| 501 | 433 | readonly fromTurnCount: number; |
| 502 | 434 | readonly toTurnCount: number; |
| 503 | | − }) => { |
| 435 | + }) { |
| 504 | 436 | if (input.fromTurnCount > input.toTurnCount) { |
| 505 | 437 | throw new Error( |
| 506 | 438 | `Invalid turn diff range for thread '${input.threadId}': from ${input.fromTurnCount} exceeds to ${input.toTurnCount}.`, |
| @@ -516,7 +448,7 @@ export function createServer(options: ServerOptions): ServerRuntime { · 9 unmodified lines |
| 516 | 448 | }; |
| 517 | 449 | } |
| 518 | 450 | |
| 519 | | − const snapshot = await effectRuntime.runPromise(projectionReadModelQuery.getSnapshot()); |
| 451 | + const snapshot = yield* projectionReadModelQuery.getSnapshot(); |
| 520 | 452 | const thread = snapshot.threads.find((entry) => entry.id === input.threadId); |
| 521 | 453 | if (!thread) { |
| 522 | 454 | throw new Error(`Thread '${input.threadId}' not found.`); |
| @@ -562,20 +494,19 @@ export function createServer(options: ServerOptions): ServerRuntime { · 39 unmodified lines |
| 562 | 494 | ); |
| 563 | 495 | } |
| 564 | 496 | |
| 565 | | − const [fromExists, toExists] = await Promise.all([ |
| 566 | | − effectRuntime.runPromise( |
| 497 | + const [fromExists, toExists] = yield* Effect.all( |
| 498 | + [ |
| 567 | 499 | liveCheckpointStore.hasCheckpointRef({ |
| 568 | 500 | cwd: workspaceCwd, |
| 569 | 501 | checkpointRef: fromCheckpointRef, |
| 570 | 502 | }), |
| 571 | | − ), |
| 572 | | − effectRuntime.runPromise( |
| 573 | 503 | liveCheckpointStore.hasCheckpointRef({ |
| 574 | 504 | cwd: workspaceCwd, |
| 575 | 505 | checkpointRef: toCheckpointRef, |
| 576 | 506 | }), |
| 577 | | − ), |
| 578 | | − ]); |
| 507 | + ], |
| 508 | + { concurrency: "unbounded" }, |
| 509 | + ); |
| 579 | 510 | if (!fromExists) { |
| 580 | 511 | throw new Error( |
| 581 | 512 | `Filesystem checkpoint is unavailable for turn ${input.fromTurnCount} in thread ${input.threadId}.`, |
| @@ -587,304 +518,282 @@ export function createServer(options: ServerOptions): ServerRuntime { · 5 unmodified lines |
| 587 | 518 | ); |
| 588 | 519 | } |
| 589 | 520 | |
| 590 | | − const diff = await effectRuntime.runPromise( |
| 591 | | − liveCheckpointStore.diffCheckpoints({ |
| 592 | | − cwd: workspaceCwd, |
| 593 | | − fromCheckpointRef, |
| 594 | | − toCheckpointRef, |
| 595 | | − fallbackFromToHead: false, |
| 596 | | − }), |
| 597 | | − ); |
| 521 | + const diff = yield* liveCheckpointStore.diffCheckpoints({ |
| 522 | + cwd: workspaceCwd, |
| 523 | + fromCheckpointRef, |
| 524 | + toCheckpointRef, |
| 525 | + fallbackFromToHead: false, |
| 526 | + }); |
| 598 | 527 | return { |
| 599 | 528 | threadId: input.threadId, |
| 600 | 529 | fromTurnCount: input.fromTurnCount, |
| 601 | 530 | toTurnCount: input.toTurnCount, |
| 602 | 531 | diff, |
| 603 | 532 | }; |
| 604 | | − }; |
| 533 | + }); |
| 605 | 534 | |
| 606 | 535 | switch (request.body._tag) { |
| 607 | | − case ORCHESTRATION_WS_METHODS.getSnapshot: { |
| 608 | | − return effectRuntime.runPromise(projectionReadModelQuery.getSnapshot()); |
| 609 | | − } |
| 536 | + case ORCHESTRATION_WS_METHODS.getSnapshot: |
| 537 | + return yield* projectionReadModelQuery.getSnapshot(); |
| 610 | 538 | |
| 611 | 539 | case ORCHESTRATION_WS_METHODS.dispatchCommand: { |
| 612 | | − orchestrationCommandLogger?.write({ |
| 613 | | − observedAt: new Date().toISOString(), |
| 614 | | − command: request.body.command, |
| 615 | | − }); |
| 616 | | − return effectRuntime.runPromise(orchestrationEngine.dispatch(request.body.command)); |
| 540 | + const { command } = request.body; |
| 541 | + return yield* orchestrationEngine.dispatch(command); |
| 617 | 542 | } |
| 618 | 543 | |
| 619 | 544 | case ORCHESTRATION_WS_METHODS.getTurnDiff: { |
| 620 | 545 | const body = stripRequestTag(request.body); |
| 621 | | − return computeTurnDiff(body); |
| 546 | + return yield* computeTurnDiff(body); |
| 622 | 547 | } |
| 623 | 548 | |
| 624 | 549 | case ORCHESTRATION_WS_METHODS.getFullThreadDiff: { |
| 625 | 550 | const body = stripRequestTag(request.body); |
| 626 | | − return computeTurnDiff({ |
| 551 | + return yield* computeTurnDiff({ |
| 627 | 552 | threadId: body.threadId, |
| 628 | 553 | fromTurnCount: 0, |
| 629 | 554 | toTurnCount: body.toTurnCount, |
| 630 | 555 | }); |
| 631 | 556 | } |
| 632 | 557 | |
| 633 | | − case ORCHESTRATION_WS_METHODS.replayEvents: |
| 634 | | − return effectRuntime.runPromise( |
| 635 | | − Stream.runCollect( |
| 636 | | − orchestrationEngine.readEvents( |
| 637 | | − clamp(request.body.fromSequenceExclusive, { |
| 638 | | − maximum: Number.MAX_SAFE_INTEGER, |
| 639 | | − minimum: 0, |
| 640 | | − }), |
| 641 | | − ), |
| 642 | | − ).pipe(Effect.map((events) => Array.from(events))), |
| 643 | | − ); |
| 558 | + case ORCHESTRATION_WS_METHODS.replayEvents: { |
| 559 | + const { fromSequenceExclusive } = request.body; |
| 560 | + return yield* Stream.runCollect( |
| 561 | + orchestrationEngine.readEvents( |
| 562 | + clamp(fromSequenceExclusive, { |
| 563 | + maximum: Number.MAX_SAFE_INTEGER, |
| 564 | + minimum: 0, |
| 565 | + }), |
| 566 | + ), |
| 567 | + ).pipe(Effect.map((events) => Array.from(events))); |
| 568 | + } |
| 644 | 569 | |
| 645 | | − case WS_METHODS.projectsSearchEntries: |
| 646 | | − return searchWorkspaceEntries(stripRequestTag(request.body)); |
| 570 | + case WS_METHODS.projectsSearchEntries: { |
| 571 | + const body = stripRequestTag(request.body); |
| 572 | + return yield* Effect.promise(() => searchWorkspaceEntries(body)); |
| 573 | + } |
| 647 | 574 | |
| 648 | 575 | case WS_METHODS.shellOpenInEditor: { |
| 649 | | − await Effect.runPromise(openService.openInEditor(stripRequestTag(request.body))); |
| 650 | | − return undefined; |
| 576 | + const body = stripRequestTag(request.body); |
| 577 | + return yield* openService.openInEditor(body); |
| 651 | 578 | } |
| 652 | 579 | |
| 653 | | − case WS_METHODS.gitStatus: |
| 654 | | − return gitManager.status(stripRequestTag(request.body)); |
| 580 | + case WS_METHODS.gitStatus: { |
| 581 | + const body = stripRequestTag(request.body); |
| 582 | + return yield* Effect.promise(() => gitManager.status(body)); |
| 583 | + } |
| 655 | 584 | |
| 656 | | − case WS_METHODS.gitPull: |
| 657 | | − return pullGitBranch(stripRequestTag(request.body)); |
| 585 | + case WS_METHODS.gitPull: { |
| 586 | + const body = stripRequestTag(request.body); |
| 587 | + return yield* Effect.promise(() => pullGitBranch(body)); |
| 588 | + } |
| 658 | 589 | |
| 659 | | − case WS_METHODS.gitRunStackedAction: |
| 660 | | − return gitManager.runStackedAction(stripRequestTag(request.body)); |
| 661 | | − case WS_METHODS.gitListBranches: |
| 662 | | − return listGitBranches(stripRequestTag(request.body)); |
| 590 | + case WS_METHODS.gitRunStackedAction: { |
| 591 | + const body = stripRequestTag(request.body); |
| 592 | + return yield* Effect.promise(() => gitManager.runStackedAction(body)); |
| 593 | + } |
| 663 | 594 | |
| 664 | | − case WS_METHODS.gitCreateWorktree: |
| 665 | | − return createGitWorktree(stripRequestTag(request.body)); |
| 595 | + case WS_METHODS.gitListBranches: { |
| 596 | + const body = stripRequestTag(request.body); |
| 597 | + return yield* Effect.promise(() => listGitBranches(body)); |
| 598 | + } |
| 666 | 599 | |
| 667 | | − case WS_METHODS.gitRemoveWorktree: |
| 668 | | − return removeGitWorktree(stripRequestTag(request.body)); |
| 600 | + case WS_METHODS.gitCreateWorktree: { |
| 601 | + const body = stripRequestTag(request.body); |
| 602 | + return yield* Effect.promise(() => createGitWorktree(body)); |
| 603 | + } |
| 669 | 604 | |
| 670 | | − case WS_METHODS.gitCreateBranch: |
| 671 | | − return createGitBranch(stripRequestTag(request.body)); |
| 605 | + case WS_METHODS.gitRemoveWorktree: { |
| 606 | + const body = stripRequestTag(request.body); |
| 607 | + return yield* Effect.promise(() => removeGitWorktree(body)); |
| 608 | + } |
| 672 | 609 | |
| 673 | | − case WS_METHODS.gitCheckout: |
| 674 | | − return checkoutGitBranch(stripRequestTag(request.body)); |
| 610 | + case WS_METHODS.gitCreateBranch: { |
| 611 | + const body = stripRequestTag(request.body); |
| 612 | + return yield* Effect.promise(() => createGitBranch(body)); |
| 613 | + } |
| 675 | 614 | |
| 676 | | − case WS_METHODS.gitInit: |
| 677 | | − return initGitRepo(stripRequestTag(request.body)); |
| 615 | + case WS_METHODS.gitCheckout: { |
| 616 | + const body = stripRequestTag(request.body); |
| 617 | + return yield* Effect.promise(() => checkoutGitBranch(body)); |
| 618 | + } |
| 678 | 619 | |
| 679 | | − case WS_METHODS.terminalOpen: |
| 680 | | − return terminalManager.open(stripRequestTag(request.body)); |
| 620 | + case WS_METHODS.gitInit: { |
| 621 | + const body = stripRequestTag(request.body); |
| 622 | + return yield* Effect.promise(() => initGitRepo(body)); |
| 623 | + } |
| 681 | 624 | |
| 682 | | − case WS_METHODS.terminalWrite: |
| 683 | | − await terminalManager.write(stripRequestTag(request.body)); |
| 684 | | − return undefined; |
| 625 | + case WS_METHODS.terminalOpen: { |
| 626 | + const body = stripRequestTag(request.body); |
| 627 | + return yield* Effect.promise(() => terminalManager.open(body)); |
| 628 | + } |
| 685 | 629 | |
| 686 | | − case WS_METHODS.terminalResize: |
| 687 | | − await terminalManager.resize(stripRequestTag(request.body)); |
| 688 | | − return undefined; |
| 630 | + case WS_METHODS.terminalWrite: { |
| 631 | + const body = stripRequestTag(request.body); |
| 632 | + return yield* Effect.promise(() => terminalManager.write(body)); |
| 633 | + } |
| 689 | 634 | |
| 690 | | − case WS_METHODS.terminalClear: |
| 691 | | − await terminalManager.clear(stripRequestTag(request.body)); |
| 692 | | − return undefined; |
| 635 | + case WS_METHODS.terminalResize: { |
| 636 | + const body = stripRequestTag(request.body); |
| 637 | + return yield* Effect.promise(() => terminalManager.resize(body)); |
| 638 | + } |
| 639 | + |
| 640 | + case WS_METHODS.terminalClear: { |
| 641 | + const body = stripRequestTag(request.body); |
| 642 | + return yield* Effect.promise(() => terminalManager.clear(body)); |
| 643 | + } |
| 693 | 644 | |
| 694 | | − case WS_METHODS.terminalRestart: |
| 695 | | − return terminalManager.restart(stripRequestTag(request.body)); |
| 645 | + case WS_METHODS.terminalRestart: { |
| 646 | + const body = stripRequestTag(request.body); |
| 647 | + return yield* Effect.promise(() => terminalManager.restart(body)); |
| 648 | + } |
| 696 | 649 | |
| 697 | | − case WS_METHODS.terminalClose: |
| 698 | | − await terminalManager.close(stripRequestTag(request.body)); |
| 699 | | − return undefined; |
| 650 | + case WS_METHODS.terminalClose: { |
| 651 | + const body = stripRequestTag(request.body); |
| 652 | + return yield* Effect.promise(() => terminalManager.close(body)); |
| 653 | + } |
| 700 | 654 | |
| 701 | 655 | case WS_METHODS.serverGetConfig: |
| 702 | | − return { |
| 703 | | − cwd, |
| 704 | | − keybindings: keybindingsConfig, |
| 705 | | − }; |
| 656 | + return { cwd, keybindings: keybindingsConfig }; |
| 706 | 657 | |
| 707 | | − case WS_METHODS.serverUpsertKeybinding: |
| 708 | | − keybindingsConfig = upsertKeybindingRule(logger, stripRequestTag(request.body)); |
| 709 | | − return { |
| 710 | | − keybindings: keybindingsConfig, |
| 711 | | − }; |
| 658 | + case WS_METHODS.serverUpsertKeybinding: { |
| 659 | + const body = stripRequestTag(request.body); |
| 660 | + keybindingsConfig = upsertKeybindingRule(logger, body); |
| 661 | + return { keybindings: keybindingsConfig }; |
| 662 | + } |
| 712 | 663 | |
| 713 | 664 | default: { |
| 714 | 665 | const _exhaustiveCheck: never = request.body; |
| 715 | | − throw new Error(`Unknown method: ${String(_exhaustiveCheck)}`); |
| 716 | | − } |
| 717 | | − } |
| 718 | | − } |
| 719 | | − |
| 720 | | − async function createEffectRuntime() { |
| 721 | | − const dbPath = path.join(resolvedStateDir, "orchestration.sqlite"); |
| 722 | | − const providerLogsDir = path.join(resolvedStateDir, "logs", "providers"); |
| 723 | | − const orchestrationLogsDir = path.join(resolvedStateDir, "logs", "orchestration"); |
| 724 | | − orchestrationDomainEventLogger = makeEventNdjsonLogger( |
| 725 | | − path.join(orchestrationLogsDir, "orchestration-domain.ndjson"), |
| 726 | | − ); |
| 727 | | − orchestrationCommandLogger = makeEventNdjsonLogger( |
| 728 | | − path.join(orchestrationLogsDir, "orchestration-command.ndjson"), |
| 729 | | − ); |
| 730 | | − const persistenceLayer = customPersistenceLayer ?? makeSqlitePersistenceLive(dbPath); |
| 731 | | − const orchestrationLayer = OrchestrationEngineLive.pipe( |
| 732 | | − Layer.provide(OrchestrationProjectionPipelineLive), |
| 733 | | − Layer.provide(OrchestrationEventStoreLive), |
| 734 | | − Layer.provide(OrchestrationCommandReceiptRepositoryLive), |
| 735 | | − ); |
| 736 | | − const checkpointStoreLayer = CheckpointStoreLive.pipe(Layer.provide(NodeServices.layer)); |
| 737 | | − const providerLayer = |
| 738 | | − customProviderLayer ?? |
| 739 | | − (() => { |
| 740 | | − const codexAdapterLayer = makeCodexAdapterLive({ |
| 741 | | − nativeEventLogPath: path.join(providerLogsDir, "provider-native.ndjson"), |
| 666 | + return yield* new RouteRequestError({ |
| 667 | + message: `Unknown method: ${String(_exhaustiveCheck)}`, |
| 742 | 668 | }); |
| 743 | | − const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe( |
| 744 | | − Layer.provide(codexAdapterLayer), |
| 745 | | − ); |
| 746 | | − const providerSessionDirectoryLayer = ProviderSessionDirectoryLive.pipe( |
| 747 | | − Layer.provide(ProviderSessionRuntimeRepositoryLive), |
| 748 | | − ); |
| 749 | | − return makeProviderServiceLive({ |
| 750 | | − canonicalEventLogPath: path.join(providerLogsDir, "provider-canonical.ndjson"), |
| 751 | | − }).pipe(Layer.provide(adapterRegistryLayer), Layer.provide(providerSessionDirectoryLayer)); |
| 752 | | − })(); |
| 753 | | − |
| 754 | | − const runtimeServicesLayer = Layer.mergeAll( |
| 755 | | − orchestrationLayer, |
| 756 | | − OrchestrationProjectionSnapshotQueryLive, |
| 757 | | − checkpointStoreLayer, |
| 758 | | − providerLayer, |
| 759 | | − ); |
| 760 | | − const runtimeIngestionLayer = ProviderRuntimeIngestionLive.pipe( |
| 761 | | − Layer.provideMerge(runtimeServicesLayer), |
| 762 | | − ); |
| 763 | | − const providerCommandReactorLayer = ProviderCommandReactorLive.pipe( |
| 764 | | − Layer.provideMerge(runtimeServicesLayer), |
| 765 | | − ); |
| 766 | | − const checkpointReactorLayer = CheckpointReactorLive.pipe( |
| 767 | | − Layer.provideMerge(runtimeServicesLayer), |
| 768 | | − ); |
| 769 | | − const orchestrationReactorLayer = OrchestrationReactorLive.pipe( |
| 770 | | − Layer.provideMerge(runtimeIngestionLayer), |
| 771 | | − Layer.provideMerge(providerCommandReactorLayer), |
| 772 | | − Layer.provideMerge(checkpointReactorLayer), |
| 773 | | − ); |
| 774 | | − const layer = orchestrationReactorLayer.pipe( |
| 775 | | − Layer.provide(persistenceLayer), |
| 776 | | − Layer.provideMerge(NodeServices.layer), |
| 777 | | − ); |
| 778 | | − const runtime = ManagedRuntime.make(layer); |
| 779 | | − |
| 780 | | − try { |
| 781 | | − const [ |
| 782 | | − nextOrchestrationEngine, |
| 783 | | − nextProjectionSnapshotQuery, |
| 784 | | − nextCheckpointStore, |
| 785 | | − nextProviderService, |
| 786 | | − ] = await Promise.all([ |
| 787 | | − runtime.runPromise(Effect.service(OrchestrationEngineService)), |
| 788 | | − runtime.runPromise(Effect.service(ProjectionSnapshotQuery)), |
| 789 | | − runtime.runPromise(Effect.service(CheckpointStore)), |
| 790 | | − runtime.runPromise(Effect.service(ProviderService)), |
| 791 | | − ]); |
| 792 | | − orchestrationEngine = nextOrchestrationEngine; |
| 793 | | − projectionSnapshotQuery = nextProjectionSnapshotQuery; |
| 794 | | − checkpointStore = nextCheckpointStore; |
| 795 | | − providerService = nextProviderService; |
| 796 | | − await runtime.runPromise(attachSubscriptionss); |
| 797 | | − } catch (error) { |
| 798 | | − await runtime.dispose().catch(() => undefined); |
| 799 | | − throw error; |
| 669 | + } |
| 800 | 670 | } |
| 671 | + }); |
| 801 | 672 | |
| 802 | | − return runtime; |
| 803 | | − } |
| 673 | + const handleMessage = Effect.fnUntraced(function* (ws: WebSocket, raw: unknown) { |
| 674 | + const encodeResponse = Schema.encodeEffect(Schema.fromJsonString(WsResponse)); |
| 804 | 675 | |
| 805 | | − async function disposeEffectRuntime() { |
| 806 | | − if (subscriptionsScope && effectRuntime) { |
| 807 | | − await effectRuntime.runPromise(Scope.close(subscriptionsScope, Exit.void)); |
| 808 | | − subscriptionsScope = null; |
| 676 | + const messageText = websocketRawToString(raw); |
| 677 | + if (messageText === null) { |
| 678 | + const errorResponse = yield* encodeResponse( |
| 679 | + new WebSocketResponse({ |
| 680 | + id: "unknown", |
| 681 | + error: { message: "Invalid request format: Failed to read message" }, |
| 682 | + }), |
| 683 | + ); |
| 684 | + ws.send(errorResponse); |
| 685 | + return; |
| 809 | 686 | } |
| 810 | | − orchestrationDomainEventLogger?.close(); |
| 811 | | − orchestrationDomainEventLogger = undefined; |
| 812 | | − orchestrationCommandLogger?.close(); |
| 813 | | − orchestrationCommandLogger = undefined; |
| 814 | | − |
| 815 | | − const runtime = effectRuntime; |
| 816 | | − const liveProviderService = providerService; |
| 817 | | − effectRuntime = null; |
| 818 | | − orchestrationEngine = null; |
| 819 | | − projectionSnapshotQuery = null; |
| 820 | | − checkpointStore = null; |
| 821 | | − providerService = null; |
| 822 | | − |
| 823 | | − if (!runtime) { |
| 687 | + |
| 688 | + const request = Schema.decodeExit(Schema.fromJsonString(WebSocketRequest))(messageText); |
| 689 | + if (request._tag === "Failure") { |
| 690 | + const errorResponse = yield* encodeResponse( |
| 691 | + new WebSocketResponse({ |
| 692 | + id: "unknown", |
| 693 | + error: { message: `Invalid request format: ${Cause.pretty(request.cause)}` }, |
| 694 | + }), |
| 695 | + ); |
| 696 | + ws.send(errorResponse); |
| 824 | 697 | return; |
| 825 | 698 | } |
| 826 | 699 | |
| 827 | | − if (liveProviderService) { |
| 828 | | − await runtime.runPromise(liveProviderService.stopAll()).catch(() => undefined); |
| 700 | + const result = yield* Effect.exit(routeRequest(request.value)); |
| 701 | + if (result._tag === "Failure") { |
| 702 | + const errorResponse = yield* encodeResponse( |
| 703 | + new WebSocketResponse({ |
| 704 | + id: request.value.id, |
| 705 | + error: { message: Cause.pretty(result.cause) }, |
| 706 | + }), |
| 707 | + ); |
| 708 | + ws.send(errorResponse); |
| 709 | + return; |
| 829 | 710 | } |
| 830 | 711 | |
| 831 | | − await runtime.dispose(); |
| 832 | | − } |
| 712 | + const response = yield* encodeResponse( |
| 713 | + new WebSocketResponse({ |
| 714 | + id: request.value.id, |
| 715 | + result: result.value, |
| 716 | + }), |
| 717 | + ); |
| 718 | + ws.send(response); |
| 719 | + }); |
| 833 | 720 | |
| 834 | | − async function start() { |
| 835 | | − effectRuntime = await createEffectRuntime(); |
| 836 | | − await bootstrapProjectForCwd(); |
| 721 | + httpServer.on("upgrade", (request, socket, head) => { |
| 722 | + if (authToken) { |
| 723 | + let providedToken: string | null = null; |
| 724 | + try { |
| 725 | + const url = new URL(request.url ?? "/", `http://localhost:${port}`); |
| 726 | + providedToken = url.searchParams.get("token"); |
| 727 | + } catch { |
| 728 | + rejectUpgrade(socket, 400, "Invalid WebSocket URL"); |
| 729 | + return; |
| 730 | + } |
| 837 | 731 | |
| 838 | | − return new Promise<void>((resolve, reject) => { |
| 839 | | − const onError = (error: Error) => { |
| 840 | | − httpServer.off("error", onError); |
| 841 | | − void disposeEffectRuntime().finally(() => reject(error)); |
| 842 | | − }; |
| 843 | | − httpServer.once("error", onError); |
| 844 | | − const onListening = () => { |
| 845 | | − httpServer.off("error", onError); |
| 846 | | − resolve(); |
| 847 | | − }; |
| 848 | | − if (host) { |
| 849 | | − httpServer.listen(port, host, onListening); |
| 732 | + if (providedToken !== authToken) { |
| 733 | + rejectUpgrade(socket, 401, "Unauthorized WebSocket connection"); |
| 850 | 734 | return; |
| 851 | 735 | } |
| 852 | | − httpServer.listen(port, onListening); |
| 736 | + } |
| 737 | + |
| 738 | + wss.handleUpgrade(request, socket, head, (ws) => { |
| 739 | + wss.emit("connection", ws, request); |
| 853 | 740 | }); |
| 854 | | − } |
| 741 | + }); |
| 855 | 742 | |
| 856 | | − async function stop(): Promise<void> { |
| 857 | | − await disposeEffectRuntime(); |
| 858 | | − terminalManager.off("event", onTerminalEvent); |
| 859 | | − terminalManager.dispose(); |
| 743 | + wss.on("connection", (ws) => { |
| 744 | + clients.add(ws); |
| 860 | 745 | |
| 861 | | − for (const client of clients) { |
| 862 | | − client.close(); |
| 863 | | − } |
| 864 | | − clients.clear(); |
| 746 | + const segments = cwd.split(/[/\\]/).filter(Boolean); |
| 747 | + const projectName = segments[segments.length - 1] ?? "project"; |
| 865 | 748 | |
| 866 | | − const closeWebSocketServer = new Promise<void>((resolve, reject) => { |
| 867 | | − wss.close((error) => { |
| 868 | | − if (error && !isServerNotRunningError(error)) { |
| 869 | | − reject(error); |
| 870 | | − return; |
| 871 | | − } |
| 872 | | − resolve(); |
| 873 | | − }); |
| 749 | + const welcome: WsPush = { |
| 750 | + type: "push", |
| 751 | + channel: WS_CHANNELS.serverWelcome, |
| 752 | + data: { cwd, projectName }, |
| 753 | + }; |
| 754 | + logOutgoingPush(welcome, 1); |
| 755 | + ws.send(JSON.stringify(welcome)); |
| 756 | + |
| 757 | + ws.on("message", (raw) => { |
| 758 | + void Effect.runPromise(handleMessage(ws, raw)); |
| 874 | 759 | }); |
| 875 | 760 | |
| 876 | | − const closeHttpServer = new Promise<void>((resolve, reject) => { |
| 877 | | − httpServer.close((error) => { |
| 878 | | − if (error && !isServerNotRunningError(error)) { |
| 879 | | − reject(error); |
| 880 | | − return; |
| 881 | | − } |
| 882 | | − resolve(); |
| 883 | | − }); |
| 761 | + ws.on("close", () => { |
| 762 | + clients.delete(ws); |
| 884 | 763 | }); |
| 885 | 764 | |
| 886 | | − await Promise.all([closeWebSocketServer, closeHttpServer]); |
| 887 | | − } |
| 765 | + ws.on("error", () => { |
| 766 | + clients.delete(ws); |
| 767 | + }); |
| 768 | + }); |
| 888 | 769 | |
| 889 | | − return { start, stop, httpServer }; |
| 890 | | −} |
| 770 | + yield* Effect.addFinalizer(() => |
| 771 | + Effect.catch(liveProviderService.stopAll(), (cause) => |
| 772 | + Effect.logWarning("failed to stop provider service", { cause }), |
| 773 | + ), |
| 774 | + ); |
| 775 | + |
| 776 | + terminalManager.on("event", onTerminalEvent); |
| 777 | + yield* Effect.addFinalizer(() => |
| 778 | + Effect.sync(() => { |
| 779 | + terminalManager.off("event", onTerminalEvent); |
| 780 | + terminalManager.dispose(); |
| 781 | + }), |
| 782 | + ); |
| 783 | + |
| 784 | + yield* NodeHttpServer.make(() => httpServer, listenOptions); |
| 785 | + |
| 786 | + yield* Effect.addFinalizer(() => |
| 787 | + Effect.all([ |
| 788 | + Effect.sync(() => closeAllClients()), |
| 789 | + closeWebSocketServer.pipe(Effect.orElseSucceed(() => undefined)), |
| 790 | + ]), |
| 791 | + ); |
| 792 | + |
| 793 | + return httpServer; |
| 794 | +}); |
| 795 | + |
| 796 | +export const ServerLive = Layer.succeed(Server, { |
| 797 | + createServer, |
| 798 | + stopSignal: Effect.never, |
| 799 | +} satisfies ServerShape); |