| ... | @@ -12,11 +12,12 @@ import { | ... | @@ -12,11 +12,12 @@ import { |
| 12 | WS_CHANNELS, | 12 | WS_CHANNELS, |
| 13 | WS_METHODS, | 13 | WS_METHODS, |
| 14 | WebSocketRequest, | 14 | WebSocketRequest, |
| | 15 | WebSocketResponse, |
| 15 | WsPush, | 16 | WsPush, |
| 16 | WsResponse, | 17 | WsResponse, |
| 17 | } from "@t3tools/contracts"; | 18 | } from "@t3tools/contracts"; |
| 18 | import { NodeServices } from "@effect/platform-node"; | 19 | import { NodeHttpServer, NodeServices } from "@effect/platform-node"; |
| 19 | import { Effect, Exit, Layer, ManagedRuntime, Schema, Scope, ServiceMap, Stream } from "effect"; | 20 | import { Cause, Effect, Exit, Layer, Schema, Scope, ServiceMap, Stream } from "effect"; |
| 20 | import { WebSocketServer, type WebSocket } from "ws"; | 21 | import { WebSocketServer, type WebSocket } from "ws"; |
| 21 | | 22 | |
| 22 | import { createLogger } from "./logger"; | 23 | import { createLogger } from "./logger"; |
| ... | @@ -40,34 +41,21 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderComma | ... | @@ -40,34 +41,21 @@ import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderComma |
| 40 | import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline"; | 41 | import { OrchestrationProjectionPipelineLive } from "./orchestration/Layers/ProjectionPipeline"; |
| 41 | import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery"; | 42 | import { OrchestrationProjectionSnapshotQueryLive } from "./orchestration/Layers/ProjectionSnapshotQuery"; |
| 42 | import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion"; | 43 | import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion"; |
| 43 | import { | 44 | import { OrchestrationEngineService } from "./orchestration/Services/OrchestrationEngine"; |
| 44 | OrchestrationEngineService, | 45 | import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery"; |
| 45 | type OrchestrationEngineShape, | | |
| 46 | } from "./orchestration/Services/OrchestrationEngine"; | | |
| 47 | import { | | |
| 48 | ProjectionSnapshotQuery, | | |
| 49 | type ProjectionSnapshotQueryShape, | | |
| 50 | } from "./orchestration/Services/ProjectionSnapshotQuery"; | | |
| 51 | import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor"; | 46 | import { OrchestrationReactor } from "./orchestration/Services/OrchestrationReactor"; |
| 52 | import { makeSqlitePersistenceLive } from "./persistence/Layers/Sqlite"; | 47 | import { makeSqlitePersistenceLive } from "./persistence/Layers/Sqlite"; |
| 53 | import assert from "node:assert"; | | |
| 54 | import { OrchestrationEventStoreLive } from "./persistence/Layers/OrchestrationEventStore"; | 48 | import { OrchestrationEventStoreLive } from "./persistence/Layers/OrchestrationEventStore"; |
| 55 | import { OrchestrationCommandReceiptRepositoryLive } from "./persistence/Layers/OrchestrationCommandReceipts"; | 49 | import { OrchestrationCommandReceiptRepositoryLive } from "./persistence/Layers/OrchestrationCommandReceipts"; |
| 56 | import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter"; | 50 | import { makeCodexAdapterLive } from "./provider/Layers/CodexAdapter"; |
| 57 | import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry"; | 51 | import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry"; |
| 58 | import { makeProviderServiceLive } from "./provider/Layers/ProviderService"; | 52 | import { makeProviderServiceLive } from "./provider/Layers/ProviderService"; |
| 59 | import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory"; | 53 | import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory"; |
| 60 | import { ProviderService, type ProviderServiceShape } from "./provider/Services/ProviderService"; | 54 | import { ProviderService } from "./provider/Services/ProviderService"; |
| 61 | import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore"; | 55 | import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore"; |
| 62 | import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime"; | 56 | import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime"; |
| 63 | import { | 57 | import { CheckpointStore } from "./checkpointing/Services/CheckpointStore"; |
| 64 | CheckpointStore, | | |
| 65 | type CheckpointStoreShape, | | |
| 66 | } from "./checkpointing/Services/CheckpointStore"; | | |
| 67 | import { makeEventNdjsonLogger, type EventNdjsonLogger } from "./provider/Layers/EventNdjsonLogger"; | | |
| 68 | import * as SqlClient from "effect/unstable/sql/SqlClient"; | 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 | import { clamp } from "effect/Number"; | 59 | import { clamp } from "effect/Number"; |
| 72 | import { OpenDefaultService, type OpenShape } from "./open"; | 60 | import { OpenDefaultService, type OpenShape } from "./open"; |
| 73 | | 61 | |
| ... | @@ -92,37 +80,24 @@ export interface ServerOptions { | ... | @@ -92,37 +80,24 @@ export interface ServerOptions { |
| 92 | cwd: string; | 80 | cwd: string; |
| 93 | autoBootstrapProjectFromCwd?: boolean | undefined; | 81 | autoBootstrapProjectFromCwd?: boolean | undefined; |
| 94 | stateDir?: string | undefined; | 82 | stateDir?: string | undefined; |
| 95 | persistenceLayer?: | | |
| 96 | | Layer.Layer<SqlClient.SqlClient, SqlError.SqlError | Migrator.MigrationError> | | |
| 97 | | undefined; | | |
| 98 | staticDir?: string | undefined; | 83 | staticDir?: string | undefined; |
| 99 | devUrl?: string | undefined; | 84 | devUrl?: string | undefined; |
| 100 | logWebSocketEvents?: boolean | undefined; | 85 | logWebSocketEvents?: boolean | undefined; |
| 101 | gitManager?: GitManager | undefined; | 86 | gitManager?: GitManager | undefined; |
| 102 | terminalManager?: TerminalManager | undefined; | 87 | terminalManager?: TerminalManager | undefined; |
| 103 | providerLayer?: Layer.Layer<ProviderService, unknown> | undefined; | | |
| 104 | authToken?: string | undefined; | 88 | authToken?: string | undefined; |
| 105 | open?: OpenShape | undefined; | 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 | export interface ServerShape { | 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 | readonly stopSignal: Effect.Effect<unknown, never>; | 96 | readonly stopSignal: Effect.Effect<unknown, never>; |
| 117 | } | 97 | } |
| 118 | | 98 | |
| 119 | export class Server extends ServiceMap.Service<Server, ServerShape>()("server/Server") {} | 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 | const isServerNotRunningError = (error: unknown): boolean => { | 101 | const isServerNotRunningError = (error: unknown): boolean => { |
| 127 | if (!(error instanceof Error)) return false; | 102 | if (!(error instanceof Error)) return false; |
| 128 | const maybeCode = (error as NodeJS.ErrnoException).code; | 103 | const maybeCode = (error as NodeJS.ErrnoException).code; |
| ... | @@ -195,47 +170,104 @@ function checkpointRefForThreadTurn(threadId: string, turnCount: number): Checkp | ... | @@ -195,47 +170,104 @@ function checkpointRefForThreadTurn(threadId: string, turnCount: number): Checkp |
| 195 | return CheckpointRef.makeUnsafe(`${CHECKPOINT_REFS_PREFIX}/${encodedThreadId}/turn/${turnCount}`); | 170 | return CheckpointRef.makeUnsafe(`${CHECKPOINT_REFS_PREFIX}/${encodedThreadId}/turn/${turnCount}`); |
| 196 | } | 171 | } |
| 197 | | 172 | |
| 198 | type EffectRuntime = ManagedRuntime.ManagedRuntime< | 173 | export type ServerCoreRuntimeServices = |
| 199 | | OrchestrationEngineService | 174 | | OrchestrationEngineService |
| 200 | | ProjectionSnapshotQuery | 175 | | ProjectionSnapshotQuery |
| 201 | | ProviderService | | |
| 202 | | CheckpointStore | 176 | | CheckpointStore |
| 203 | | OrchestrationReactor, | 177 | | OrchestrationReactor; |
| 204 | unknown | 178 | |
| 205 | >; | 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 | const { | 252 | const { |
| 209 | port, | 253 | port, |
| 210 | host, | 254 | host, |
| 211 | cwd, | 255 | cwd, |
| 212 | autoBootstrapProjectFromCwd = false, | 256 | autoBootstrapProjectFromCwd = false, |
| 213 | stateDir, | | |
| 214 | persistenceLayer: customPersistenceLayer, | | |
| 215 | staticDir, | 257 | staticDir, |
| 216 | devUrl, | 258 | devUrl, |
| 217 | logWebSocketEvents: explicitLogWsEvents, | 259 | logWebSocketEvents: explicitLogWsEvents, |
| 218 | gitManager = new GitManager(), | 260 | gitManager = new GitManager(), |
| 219 | terminalManager = new TerminalManager(), | 261 | terminalManager = new TerminalManager(), |
| 220 | providerLayer: customProviderLayer, | | |
| 221 | authToken, | 262 | authToken, |
| 222 | open: openService = OpenDefaultService, | 263 | open: openService = OpenDefaultService, |
| 223 | } = options; | 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 | const clients = new Set<WebSocket>(); | 266 | const clients = new Set<WebSocket>(); |
| 232 | const logger = createLogger("ws"); | 267 | const logger = createLogger("ws"); |
| 233 | const logWebSocketEvents = | 268 | const logWebSocketEvents = |
| 234 | explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl); | 269 | explicitLogWsEvents ?? parseBooleanEnv(process.env.T3CODE_LOG_WS_EVENTS) ?? Boolean(devUrl); |
| 235 | let keybindingsConfig = loadResolvedKeybindingsConfig(logger); | 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 | function logOutgoingPush(push: WsPush, recipients: number) { | 272 | function logOutgoingPush(push: WsPush, recipients: number) { |
| 241 | if (!logWebSocketEvents) return; | 273 | if (!logWebSocketEvents) return; |
| ... | @@ -246,86 +278,6 @@ export function createServer(options: ServerOptions): ServerRuntime { | ... | @@ -246,86 +278,6 @@ export function createServer(options: ServerOptions): ServerRuntime { |
| 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 | const onTerminalEvent = (event: TerminalEvent) => { | 281 | const onTerminalEvent = (event: TerminalEvent) => { |
| 330 | const push: WsPush = { | 282 | const push: WsPush = { |
| 331 | type: "push", | 283 | type: "push", |
| ... | @@ -342,7 +294,6 @@ export function createServer(options: ServerOptions): ServerRuntime { | ... | @@ -342,7 +294,6 @@ export function createServer(options: ServerOptions): ServerRuntime { |
| 342 | } | 294 | } |
| 343 | logOutgoingPush(push, recipients); | 295 | logOutgoingPush(push, recipients); |
| 344 | }; | 296 | }; |
| 345 | terminalManager.on("event", onTerminalEvent); | | |
| 346 | | 297 | |
| 347 | // HTTP server — serves static files or redirects to Vite dev server | 298 | // HTTP server — serves static files or redirects to Vite dev server |
| 348 | const httpServer = http.createServer((req, res) => { | 299 | const httpServer = http.createServer((req, res) => { |
| ... | @@ -403,104 +354,85 @@ export function createServer(options: ServerOptions): ServerRuntime { | ... | @@ -403,104 +354,85 @@ export function createServer(options: ServerOptions): ServerRuntime { |
| 403 | // WebSocket server — upgrades from the HTTP server | 354 | // WebSocket server — upgrades from the HTTP server |
| 404 | const wss = new WebSocketServer({ noServer: true }); | 355 | const wss = new WebSocketServer({ noServer: true }); |
| 405 | | 356 | |
| 406 | httpServer.on("upgrade", (request, socket, head) => { | 357 | const closeWebSocketServer = Effect.callback<void, ServerLifecycleError>((resume) => { |
| 407 | if (authToken) { | 358 | wss.close((error) => { |
| 408 | let providedToken: string | null = null; | 359 | if (error && !isServerNotRunningError(error)) { |
| 409 | try { | 360 | resume( |
| 410 | const url = new URL(request.url ?? "/", `http://localhost:${port}`); | 361 | Effect.fail( |
| 411 | providedToken = url.searchParams.get("token"); | 362 | new ServerLifecycleError({ operation: "closeWebSocketServer", cause: error }), |
| 412 | } catch { | 363 | ), |
| 413 | rejectUpgrade(socket, 400, "Invalid WebSocket URL"); | 364 | ); |
| 414 | return; | 365 | } else { |
| 415 | } | 366 | resume(Effect.void); |
| 416 | | | |
| 417 | if (providedToken !== authToken) { | | |
| 418 | rejectUpgrade(socket, 401, "Unauthorized WebSocket connection"); | | |
| 419 | return; | | |
| 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) => { | 371 | const closeAllClients = () => { |
| 429 | clients.add(ws); | 372 | for (const client of clients) { |
| 430 | | 373 | client.close(); |
| 431 | // Send welcome message with project info | 374 | } |
| 432 | const segments = cwd.split(/[/\\]/).filter(Boolean); | 375 | clients.clear(); |
| 433 | const projectName = segments[segments.length - 1] ?? "project"; | 376 | }; |
| 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)); | | |
| 442 | | 377 | |
| 443 | ws.on("message", (raw) => { | 378 | const listenOptions = host ? { host, port } : { port }; |
| 444 | void handleMessage(ws, raw); | | |
| 445 | }); | | |
| 446 | | 379 | |
| 447 | ws.on("close", () => { | 380 | const orchestrationEngine = yield* OrchestrationEngineService; |
| 448 | clients.delete(ws); | 381 | const projectionReadModelQuery = yield* ProjectionSnapshotQuery; |
| 449 | }); | 382 | const liveCheckpointStore = yield* CheckpointStore; |
| | 383 | const liveProviderService = yield* ProviderService; |
| | 384 | const orchestrationReactor = yield* OrchestrationReactor; |
| 450 | | 385 | |
| 451 | ws.on("error", () => { | 386 | const subscriptionsScope = yield* Scope.make("sequential"); |
| 452 | clients.delete(ws); | 387 | yield* Effect.addFinalizer(() => |
| 453 | }); | 388 | Scope.close(subscriptionsScope, Exit.void).pipe(Effect.orElseSucceed(() => undefined)), |
| 454 | }); | 389 | ); |
| 455 | | 390 | |
| 456 | async function handleMessage(ws: WebSocket, raw: unknown) { | 391 | yield* Stream.runForEach(orchestrationEngine.streamDomainEvents, (event) => |
| 457 | const messageText = websocketRawToString(raw); | 392 | Effect.sync(() => { |
| 458 | if (messageText === null) { | 393 | const push: WsPush = { |
| 459 | const errorResponse: WsResponse = { | 394 | type: "push", |
| 460 | id: "unknown", | 395 | channel: ORCHESTRATION_WS_CHANNELS.domainEvent, |
| 461 | error: { message: "Invalid request format" }, | 396 | data: event, |
| 462 | }; | 397 | }; |
| 463 | ws.send(JSON.stringify(errorResponse)); | 398 | const message = JSON.stringify(push); |
| 464 | return; | 399 | let recipients = 0; |
| 465 | } | 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; | 410 | yield* orchestrationReactor.start.pipe(Scope.provide(subscriptionsScope)); |
| 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 | } | | |
| 478 | | 411 | |
| 479 | try { | 412 | if (autoBootstrapProjectFromCwd) { |
| 480 | const result = await routeRequest(request); | 413 | const snapshot = yield* projectionReadModelQuery.getSnapshot(); |
| 481 | const response: WsResponse = { id: request.id, result }; | 414 | const existing = snapshot.projects.find((project) => project.workspaceRoot === cwd); |
| 482 | ws.send(JSON.stringify(response)); | 415 | if (!existing) { |
| 483 | } catch (err) { | 416 | const createdAt = new Date().toISOString(); |
| 484 | const message = err instanceof Error ? err.message : "Unknown server error"; | 417 | const projectName = path.basename(cwd) || "project"; |
| 485 | const response: WsResponse = { | 418 | yield* orchestrationEngine.dispatchUnknownCommand({ |
| 486 | id: request.id, | 419 | type: "project.create", |
| 487 | error: { message }, | 420 | commandId: crypto.randomUUID(), |
| 488 | }; | 421 | projectId: crypto.randomUUID(), |
| 489 | ws.send(JSON.stringify(response)); | 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> { | 430 | const routeRequest = Effect.fn(function* (request: WebSocketRequest) { |
| 494 | const orchestrationEngine = getOrchestrationEngine(); | 431 | const computeTurnDiff = Effect.fn(function* (input: { |
| 495 | const projectionReadModelQuery = getProjectionSnapshotQuery(); | | |
| 496 | const effectRuntime = getEffectRuntime(); | | |
| 497 | const liveCheckpointStore = getCheckpointStore(); | | |
| 498 | | | |
| 499 | const computeTurnDiff = async (input: { | | |
| 500 | readonly threadId: string; | 432 | readonly threadId: string; |
| 501 | readonly fromTurnCount: number; | 433 | readonly fromTurnCount: number; |
| 502 | readonly toTurnCount: number; | 434 | readonly toTurnCount: number; |
| 503 | }) => { | 435 | }) { |
| 504 | if (input.fromTurnCount > input.toTurnCount) { | 436 | if (input.fromTurnCount > input.toTurnCount) { |
| 505 | throw new Error( | 437 | throw new Error( |
| 506 | `Invalid turn diff range for thread '${input.threadId}': from ${input.fromTurnCount} exceeds to ${input.toTurnCount}.`, | 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 { | ... | @@ -516,7 +448,7 @@ export function createServer(options: ServerOptions): ServerRuntime { |
| 516 | }; | 448 | }; |
| 517 | } | 449 | } |
| 518 | | 450 | |
| 519 | const snapshot = await effectRuntime.runPromise(projectionReadModelQuery.getSnapshot()); | 451 | const snapshot = yield* projectionReadModelQuery.getSnapshot(); |
| 520 | const thread = snapshot.threads.find((entry) => entry.id === input.threadId); | 452 | const thread = snapshot.threads.find((entry) => entry.id === input.threadId); |
| 521 | if (!thread) { | 453 | if (!thread) { |
| 522 | throw new Error(`Thread '${input.threadId}' not found.`); | 454 | throw new Error(`Thread '${input.threadId}' not found.`); |
| ... | @@ -562,20 +494,19 @@ export function createServer(options: ServerOptions): ServerRuntime { | ... | @@ -562,20 +494,19 @@ export function createServer(options: ServerOptions): ServerRuntime { |
| 562 | ); | 494 | ); |
| 563 | } | 495 | } |
| 564 | | 496 | |
| 565 | const [fromExists, toExists] = await Promise.all([ | 497 | const [fromExists, toExists] = yield* Effect.all( |
| 566 | effectRuntime.runPromise( | 498 | [ |
| 567 | liveCheckpointStore.hasCheckpointRef({ | 499 | liveCheckpointStore.hasCheckpointRef({ |
| 568 | cwd: workspaceCwd, | 500 | cwd: workspaceCwd, |
| 569 | checkpointRef: fromCheckpointRef, | 501 | checkpointRef: fromCheckpointRef, |
| 570 | }), | 502 | }), |
| 571 | ), | | |
| 572 | effectRuntime.runPromise( | | |
| 573 | liveCheckpointStore.hasCheckpointRef({ | 503 | liveCheckpointStore.hasCheckpointRef({ |
| 574 | cwd: workspaceCwd, | 504 | cwd: workspaceCwd, |
| 575 | checkpointRef: toCheckpointRef, | 505 | checkpointRef: toCheckpointRef, |
| 576 | }), | 506 | }), |
| 577 | ), | 507 | ], |
| 578 | ]); | 508 | { concurrency: "unbounded" }, |
| | 509 | ); |
| 579 | if (!fromExists) { | 510 | if (!fromExists) { |
| 580 | throw new Error( | 511 | throw new Error( |
| 581 | `Filesystem checkpoint is unavailable for turn ${input.fromTurnCount} in thread ${input.threadId}.`, | 512 | `Filesystem checkpoint is unavailable for turn ${input.fromTurnCount} in thread ${input.threadId}.`, |
| ... | @@ -587,304 +518,282 @@ export function createServer(options: ServerOptions): ServerRuntime { | ... | @@ -587,304 +518,282 @@ export function createServer(options: ServerOptions): ServerRuntime { |
| 587 | ); | 518 | ); |
| 588 | } | 519 | } |
| 589 | | 520 | |
| 590 | const diff = await effectRuntime.runPromise( | 521 | const diff = yield* liveCheckpointStore.diffCheckpoints({ |
| 591 | liveCheckpointStore.diffCheckpoints({ | 522 | cwd: workspaceCwd, |
| 592 | cwd: workspaceCwd, | 523 | fromCheckpointRef, |
| 593 | fromCheckpointRef, | 524 | toCheckpointRef, |
| 594 | toCheckpointRef, | 525 | fallbackFromToHead: false, |
| 595 | fallbackFromToHead: false, | 526 | }); |
| 596 | }), | | |
| 597 | ); | | |
| 598 | return { | 527 | return { |
| 599 | threadId: input.threadId, | 528 | threadId: input.threadId, |
| 600 | fromTurnCount: input.fromTurnCount, | 529 | fromTurnCount: input.fromTurnCount, |
| 601 | toTurnCount: input.toTurnCount, | 530 | toTurnCount: input.toTurnCount, |
| 602 | diff, | 531 | diff, |
| 603 | }; | 532 | }; |
| 604 | }; | 533 | }); |
| 605 | | 534 | |
| 606 | switch (request.body._tag) { | 535 | switch (request.body._tag) { |
| 607 | case ORCHESTRATION_WS_METHODS.getSnapshot: { | 536 | case ORCHESTRATION_WS_METHODS.getSnapshot: |
| 608 | return effectRuntime.runPromise(projectionReadModelQuery.getSnapshot()); | 537 | return yield* projectionReadModelQuery.getSnapshot(); |
| 609 | } | | |
| 610 | | 538 | |
| 611 | case ORCHESTRATION_WS_METHODS.dispatchCommand: { | 539 | case ORCHESTRATION_WS_METHODS.dispatchCommand: { |
| 612 | orchestrationCommandLogger?.write({ | 540 | const { command } = request.body; |
| 613 | observedAt: new Date().toISOString(), | 541 | return yield* orchestrationEngine.dispatch(command); |
| 614 | command: request.body.command, | | |
| 615 | }); | | |
| 616 | return effectRuntime.runPromise(orchestrationEngine.dispatch(request.body.command)); | | |
| 617 | } | 542 | } |
| 618 | | 543 | |
| 619 | case ORCHESTRATION_WS_METHODS.getTurnDiff: { | 544 | case ORCHESTRATION_WS_METHODS.getTurnDiff: { |
| 620 | const body = stripRequestTag(request.body); | 545 | const body = stripRequestTag(request.body); |
| 621 | return computeTurnDiff(body); | 546 | return yield* computeTurnDiff(body); |
| 622 | } | 547 | } |
| 623 | | 548 | |
| 624 | case ORCHESTRATION_WS_METHODS.getFullThreadDiff: { | 549 | case ORCHESTRATION_WS_METHODS.getFullThreadDiff: { |
| 625 | const body = stripRequestTag(request.body); | 550 | const body = stripRequestTag(request.body); |
| 626 | return computeTurnDiff({ | 551 | return yield* computeTurnDiff({ |
| 627 | threadId: body.threadId, | 552 | threadId: body.threadId, |
| 628 | fromTurnCount: 0, | 553 | fromTurnCount: 0, |
| 629 | toTurnCount: body.toTurnCount, | 554 | toTurnCount: body.toTurnCount, |
| 630 | }); | 555 | }); |
| 631 | } | 556 | } |
| 632 | | 557 | |
| 633 | case ORCHESTRATION_WS_METHODS.replayEvents: | 558 | case ORCHESTRATION_WS_METHODS.replayEvents: { |
| 634 | return effectRuntime.runPromise( | 559 | const { fromSequenceExclusive } = request.body; |
| 635 | Stream.runCollect( | 560 | return yield* Stream.runCollect( |
| 636 | orchestrationEngine.readEvents( | 561 | orchestrationEngine.readEvents( |
| 637 | clamp(request.body.fromSequenceExclusive, { | 562 | clamp(fromSequenceExclusive, { |
| 638 | maximum: Number.MAX_SAFE_INTEGER, | 563 | maximum: Number.MAX_SAFE_INTEGER, |
| 639 | minimum: 0, | 564 | minimum: 0, |
| 640 | }), | 565 | }), |
| 641 | ), | 566 | ), |
| 642 | ).pipe(Effect.map((events) => Array.from(events))), | 567 | ).pipe(Effect.map((events) => Array.from(events))); |
| 643 | ); | 568 | } |
| 644 | | 569 | |
| 645 | case WS_METHODS.projectsSearchEntries: | 570 | case WS_METHODS.projectsSearchEntries: { |
| 646 | return searchWorkspaceEntries(stripRequestTag(request.body)); | 571 | const body = stripRequestTag(request.body); |
| | 572 | return yield* Effect.promise(() => searchWorkspaceEntries(body)); |
| | 573 | } |
| 647 | | 574 | |
| 648 | case WS_METHODS.shellOpenInEditor: { | 575 | case WS_METHODS.shellOpenInEditor: { |
| 649 | await Effect.runPromise(openService.openInEditor(stripRequestTag(request.body))); | 576 | const body = stripRequestTag(request.body); |
| 650 | return undefined; | 577 | return yield* openService.openInEditor(body); |
| 651 | } | 578 | } |
| 652 | | 579 | |
| 653 | case WS_METHODS.gitStatus: | 580 | case WS_METHODS.gitStatus: { |
| 654 | return gitManager.status(stripRequestTag(request.body)); | 581 | const body = stripRequestTag(request.body); |
| | 582 | return yield* Effect.promise(() => gitManager.status(body)); |
| | 583 | } |
| 655 | | 584 | |
| 656 | case WS_METHODS.gitPull: | 585 | case WS_METHODS.gitPull: { |
| 657 | return pullGitBranch(stripRequestTag(request.body)); | 586 | const body = stripRequestTag(request.body); |
| | 587 | return yield* Effect.promise(() => pullGitBranch(body)); |
| | 588 | } |
| 658 | | 589 | |
| 659 | case WS_METHODS.gitRunStackedAction: | 590 | case WS_METHODS.gitRunStackedAction: { |
| 660 | return gitManager.runStackedAction(stripRequestTag(request.body)); | 591 | const body = stripRequestTag(request.body); |
| 661 | case WS_METHODS.gitListBranches: | 592 | return yield* Effect.promise(() => gitManager.runStackedAction(body)); |
| 662 | return listGitBranches(stripRequestTag(request.body)); | 593 | } |
| 663 | | 594 | |
| 664 | case WS_METHODS.gitCreateWorktree: | 595 | case WS_METHODS.gitListBranches: { |
| 665 | return createGitWorktree(stripRequestTag(request.body)); | 596 | const body = stripRequestTag(request.body); |
| | 597 | return yield* Effect.promise(() => listGitBranches(body)); |
| | 598 | } |
| 666 | | 599 | |
| 667 | case WS_METHODS.gitRemoveWorktree: | 600 | case WS_METHODS.gitCreateWorktree: { |
| 668 | return removeGitWorktree(stripRequestTag(request.body)); | 601 | const body = stripRequestTag(request.body); |
| | 602 | return yield* Effect.promise(() => createGitWorktree(body)); |
| | 603 | } |
| 669 | | 604 | |
| 670 | case WS_METHODS.gitCreateBranch: | 605 | case WS_METHODS.gitRemoveWorktree: { |
| 671 | return createGitBranch(stripRequestTag(request.body)); | 606 | const body = stripRequestTag(request.body); |
| | 607 | return yield* Effect.promise(() => removeGitWorktree(body)); |
| | 608 | } |
| 672 | | 609 | |
| 673 | case WS_METHODS.gitCheckout: | 610 | case WS_METHODS.gitCreateBranch: { |
| 674 | return checkoutGitBranch(stripRequestTag(request.body)); | 611 | const body = stripRequestTag(request.body); |
| | 612 | return yield* Effect.promise(() => createGitBranch(body)); |
| | 613 | } |
| 675 | | 614 | |
| 676 | case WS_METHODS.gitInit: | 615 | case WS_METHODS.gitCheckout: { |
| 677 | return initGitRepo(stripRequestTag(request.body)); | 616 | const body = stripRequestTag(request.body); |
| | 617 | return yield* Effect.promise(() => checkoutGitBranch(body)); |
| | 618 | } |
| 678 | | 619 | |
| 679 | case WS_METHODS.terminalOpen: | 620 | case WS_METHODS.gitInit: { |
| 680 | return terminalManager.open(stripRequestTag(request.body)); | 621 | const body = stripRequestTag(request.body); |
| | 622 | return yield* Effect.promise(() => initGitRepo(body)); |
| | 623 | } |
| 681 | | 624 | |
| 682 | case WS_METHODS.terminalWrite: | 625 | case WS_METHODS.terminalOpen: { |
| 683 | await terminalManager.write(stripRequestTag(request.body)); | 626 | const body = stripRequestTag(request.body); |
| 684 | return undefined; | 627 | return yield* Effect.promise(() => terminalManager.open(body)); |
| | 628 | } |
| 685 | | 629 | |
| 686 | case WS_METHODS.terminalResize: | 630 | case WS_METHODS.terminalWrite: { |
| 687 | await terminalManager.resize(stripRequestTag(request.body)); | 631 | const body = stripRequestTag(request.body); |
| 688 | return undefined; | 632 | return yield* Effect.promise(() => terminalManager.write(body)); |
| | 633 | } |
| 689 | | 634 | |
| 690 | case WS_METHODS.terminalClear: | 635 | case WS_METHODS.terminalResize: { |
| 691 | await terminalManager.clear(stripRequestTag(request.body)); | 636 | const body = stripRequestTag(request.body); |
| 692 | return undefined; | 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: | 645 | case WS_METHODS.terminalRestart: { |
| 695 | return terminalManager.restart(stripRequestTag(request.body)); | 646 | const body = stripRequestTag(request.body); |
| | 647 | return yield* Effect.promise(() => terminalManager.restart(body)); |
| | 648 | } |
| 696 | | 649 | |
| 697 | case WS_METHODS.terminalClose: | 650 | case WS_METHODS.terminalClose: { |
| 698 | await terminalManager.close(stripRequestTag(request.body)); | 651 | const body = stripRequestTag(request.body); |
| 699 | return undefined; | 652 | return yield* Effect.promise(() => terminalManager.close(body)); |
| | 653 | } |
| 700 | | 654 | |
| 701 | case WS_METHODS.serverGetConfig: | 655 | case WS_METHODS.serverGetConfig: |
| 702 | return { | 656 | return { cwd, keybindings: keybindingsConfig }; |
| 703 | cwd, | | |
| 704 | keybindings: keybindingsConfig, | | |
| 705 | }; | | |
| 706 | | 657 | |
| 707 | case WS_METHODS.serverUpsertKeybinding: | 658 | case WS_METHODS.serverUpsertKeybinding: { |
| 708 | keybindingsConfig = upsertKeybindingRule(logger, stripRequestTag(request.body)); | 659 | const body = stripRequestTag(request.body); |
| 709 | return { | 660 | keybindingsConfig = upsertKeybindingRule(logger, body); |
| 710 | keybindings: keybindingsConfig, | 661 | return { keybindings: keybindingsConfig }; |
| 711 | }; | 662 | } |
| 712 | | 663 | |
| 713 | default: { | 664 | default: { |
| 714 | const _exhaustiveCheck: never = request.body; | 665 | const _exhaustiveCheck: never = request.body; |
| 715 | throw new Error(`Unknown method: ${String(_exhaustiveCheck)}`); | 666 | return yield* new RouteRequestError({ |
| 716 | } | 667 | message: `Unknown method: ${String(_exhaustiveCheck)}`, |
| 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"), | | |
| 742 | }); | 668 | }); |
| 743 | const adapterRegistryLayer = ProviderAdapterRegistryLive.pipe( | 669 | } |
| 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; | | |
| 800 | } | 670 | } |
| | 671 | }); |
| 801 | | 672 | |
| 802 | return runtime; | 673 | const handleMessage = Effect.fnUntraced(function* (ws: WebSocket, raw: unknown) { |
| 803 | } | 674 | const encodeResponse = Schema.encodeEffect(Schema.fromJsonString(WsResponse)); |
| 804 | | 675 | |
| 805 | async function disposeEffectRuntime() { | 676 | const messageText = websocketRawToString(raw); |
| 806 | if (subscriptionsScope && effectRuntime) { | 677 | if (messageText === null) { |
| 807 | await effectRuntime.runPromise(Scope.close(subscriptionsScope, Exit.void)); | 678 | const errorResponse = yield* encodeResponse( |
| 808 | subscriptionsScope = null; | 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(); | 687 | |
| 811 | orchestrationDomainEventLogger = undefined; | 688 | const request = Schema.decodeExit(Schema.fromJsonString(WebSocketRequest))(messageText); |
| 812 | orchestrationCommandLogger?.close(); | 689 | if (request._tag === "Failure") { |
| 813 | orchestrationCommandLogger = undefined; | 690 | const errorResponse = yield* encodeResponse( |
| 814 | | 691 | new WebSocketResponse({ |
| 815 | const runtime = effectRuntime; | 692 | id: "unknown", |
| 816 | const liveProviderService = providerService; | 693 | error: { message: `Invalid request format: ${Cause.pretty(request.cause)}` }, |
| 817 | effectRuntime = null; | 694 | }), |
| 818 | orchestrationEngine = null; | 695 | ); |
| 819 | projectionSnapshotQuery = null; | 696 | ws.send(errorResponse); |
| 820 | checkpointStore = null; | | |
| 821 | providerService = null; | | |
| 822 | | | |
| 823 | if (!runtime) { | | |
| 824 | return; | 697 | return; |
| 825 | } | 698 | } |
| 826 | | 699 | |
| 827 | if (liveProviderService) { | 700 | const result = yield* Effect.exit(routeRequest(request.value)); |
| 828 | await runtime.runPromise(liveProviderService.stopAll()).catch(() => undefined); | 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(); | 712 | const response = yield* encodeResponse( |
| 832 | } | 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() { | 721 | httpServer.on("upgrade", (request, socket, head) => { |
| 835 | effectRuntime = await createEffectRuntime(); | 722 | if (authToken) { |
| 836 | await bootstrapProjectForCwd(); | 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) => { | 732 | if (providedToken !== authToken) { |
| 839 | const onError = (error: Error) => { | 733 | rejectUpgrade(socket, 401, "Unauthorized WebSocket connection"); |
| 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); | | |
| 850 | return; | 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> { | 743 | wss.on("connection", (ws) => { |
| 857 | await disposeEffectRuntime(); | 744 | clients.add(ws); |
| 858 | terminalManager.off("event", onTerminalEvent); | | |
| 859 | terminalManager.dispose(); | | |
| 860 | | 745 | |
| 861 | for (const client of clients) { | 746 | const segments = cwd.split(/[/\\]/).filter(Boolean); |
| 862 | client.close(); | 747 | const projectName = segments[segments.length - 1] ?? "project"; |
| 863 | } | | |
| 864 | clients.clear(); | | |
| 865 | | 748 | |
| 866 | const closeWebSocketServer = new Promise<void>((resolve, reject) => { | 749 | const welcome: WsPush = { |
| 867 | wss.close((error) => { | 750 | type: "push", |
| 868 | if (error && !isServerNotRunningError(error)) { | 751 | channel: WS_CHANNELS.serverWelcome, |
| 869 | reject(error); | 752 | data: { cwd, projectName }, |
| 870 | return; | 753 | }; |
| 871 | } | 754 | logOutgoingPush(welcome, 1); |
| 872 | resolve(); | 755 | ws.send(JSON.stringify(welcome)); |
| 873 | }); | 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) => { | 761 | ws.on("close", () => { |
| 877 | httpServer.close((error) => { | 762 | clients.delete(ws); |
| 878 | if (error && !isServerNotRunningError(error)) { | | |
| 879 | reject(error); | | |
| 880 | return; | | |
| 881 | } | | |
| 882 | resolve(); | | |
| 883 | }); | | |
| 884 | }); | 763 | }); |
| 885 | | 764 | |
| 886 | await Promise.all([closeWebSocketServer, closeHttpServer]); | 765 | ws.on("error", () => { |
| 887 | } | 766 | clients.delete(ws); |
| | 767 | }); |
| | 768 | }); |
| 888 | | 769 | |
| 889 | return { start, stop, httpServer }; | 770 | yield* Effect.addFinalizer(() => |
| 890 | } | 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); |