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

server.ts

362 lines14.4 KB

1import { Effect, Layer } from "effect";
2import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
3​
4import { ServerConfig } from "./config.ts";
5import {
6 attachmentsRouteLayer,
7 otlpTracesProxyRouteLayer,
8 projectFaviconRouteLayer,
9 serverEnvironmentRouteLayer,
10 staticAndDevRouteLayer,
11 browserApiCorsLayer,
12} from "./http.ts";
13import { fixPath } from "./os-jank.ts";
14import { websocketRpcRouteLayer } from "./ws.ts";
15import { OpenLive } from "./open.ts";
16import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
17import { ServerLifecycleEventsLive } from "./serverLifecycleEvents.ts";
18import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService.ts";
19import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts";
20import { ProviderSessionRuntimeRepositoryLive } from "./persistence/Layers/ProviderSessionRuntime.ts";
21import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts";
22import { ProviderEventLoggersLive } from "./provider/Layers/ProviderEventLoggers.ts";
23import { ProviderServiceLive } from "./provider/Layers/ProviderService.ts";
24import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts";
25import { OpenCodeRuntimeLive } from "./provider/opencodeRuntime.ts";
26import { CheckpointDiffQueryLive } from "./checkpointing/Layers/CheckpointDiffQuery.ts";
27import { CheckpointStoreLive } from "./checkpointing/Layers/CheckpointStore.ts";
28import * as GitHubCli from "./sourceControl/GitHubCli.ts";
29import * as GitLabCli from "./sourceControl/GitLabCli.ts";
30import * as TextGeneration from "./textGeneration/TextGeneration.ts";
31import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
32import { TerminalManagerLive } from "./terminal/Layers/Manager.ts";
33import * as GitManager from "./git/GitManager.ts";
34import { KeybindingsLive } from "./keybindings.ts";
35import { ServerRuntimeStartup, ServerRuntimeStartupLive } from "./serverRuntimeStartup.ts";
36import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor.ts";
37import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus.ts";
38import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion.ts";
39import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts";
40import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";
41import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";
42import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
43import { ServerSettingsLive } from "./serverSettings.ts";
44import { ProjectFaviconResolverLive } from "./project/Layers/ProjectFaviconResolver.ts";
45import { RepositoryIdentityResolverLive } from "./project/Layers/RepositoryIdentityResolver.ts";
46import { WorkspaceEntriesLive } from "./workspace/Layers/WorkspaceEntries.ts";
47import { WorkspaceFileSystemLive } from "./workspace/Layers/WorkspaceFileSystem.ts";
48import { WorkspacePathsLive } from "./workspace/Layers/WorkspacePaths.ts";
49import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
50import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
51import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
52import * as VcsProcess from "./vcs/VcsProcess.ts";
53import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
54import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
55import * as GitWorkflowService from "./git/GitWorkflowService.ts";
56import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
57import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
58import { ProjectSetupScriptRunnerLive } from "./project/Layers/ProjectSetupScriptRunner.ts";
59import { ObservabilityLive } from "./observability/Layers/Observability.ts";
60import { ServerEnvironmentLive } from "./environment/Layers/ServerEnvironment.ts";
61import {
62 authBearerBootstrapRouteLayer,
63 authBootstrapRouteLayer,
64 authClientsRevokeOthersRouteLayer,
65 authClientsRevokeRouteLayer,
66 authClientsRouteLayer,
67 authPairingLinksRevokeRouteLayer,
68 authPairingLinksRouteLayer,
69 authPairingCredentialRouteLayer,
70 authSessionRouteLayer,
71 authWebSocketTokenRouteLayer,
72} from "./auth/http.ts";
73import { ServerSecretStoreLive } from "./auth/Layers/ServerSecretStore.ts";
74import { ServerAuthLive } from "./auth/Layers/ServerAuth.ts";
75import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
76import {
77 clearPersistedServerRuntimeState,
78 makePersistedServerRuntimeState,
79 persistServerRuntimeState,
80} from "./serverRuntimeState.ts";
81import {
82 orchestrationDispatchRouteLayer,
83 orchestrationSnapshotRouteLayer,
84} from "./orchestration/http.ts";
85import { NetService } from "@t3tools/shared/Net";
86​
87const PtyAdapterLive = Layer.unwrap(
88 Effect.gen(function* () {
89 if (typeof Bun !== "undefined") {
90 const BunPTY = yield* Effect.promise(() => import("./terminal/Layers/BunPTY.ts"));
91 return BunPTY.layer;
92 } else {
93 const NodePTY = yield* Effect.promise(() => import("./terminal/Layers/NodePTY.ts"));
94 return NodePTY.layer;
95 }
96 }),
97);
98​
99const HttpServerLive = Layer.unwrap(
100 Effect.gen(function* () {
101 const config = yield* ServerConfig;
102 if (typeof Bun !== "undefined") {
103 const BunHttpServer = yield* Effect.promise(
104 () => import("@effect/platform-bun/BunHttpServer"),
105 );
106 return BunHttpServer.layer({
107 port: config.port,
108 ...(config.host ? { hostname: config.host } : {}),
109 });
110 } else {
111 const [NodeHttpServer, NodeHttp] = yield* Effect.all([
112 Effect.promise(() => import("@effect/platform-node/NodeHttpServer")),
113 Effect.promise(() => import("node:http")),
114 ]);
115 return NodeHttpServer.layer(NodeHttp.createServer, {
116 host: config.host,
117 port: config.port,
118 });
119 }
120 }),
121);
122​
123const PlatformServicesLive = Layer.unwrap(
124 Effect.gen(function* () {
125 if (typeof Bun !== "undefined") {
126 const { layer } = yield* Effect.promise(() => import("@effect/platform-bun/BunServices"));
127 return layer;
128 } else {
129 const { layer } = yield* Effect.promise(() => import("@effect/platform-node/NodeServices"));
130 return layer;
131 }
132 }),
133);
134​
135const ReactorLayerLive = Layer.empty.pipe(
136 Layer.provideMerge(OrchestrationReactorLive),
137 Layer.provideMerge(ProviderRuntimeIngestionLive),
138 Layer.provideMerge(ProviderCommandReactorLive),
139 Layer.provideMerge(CheckpointReactorLive),
140 Layer.provideMerge(ThreadDeletionReactorLive),
141 Layer.provideMerge(RuntimeReceiptBusLive),
142);
143​
144const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(
145 Layer.provide(ProviderSessionRuntimeRepositoryLive),
146);
147​
148// `ProviderAdapterRegistryLive` is now a facade that resolves kind → adapter
149// by looking up the default `ProviderInstance` per driver in the instance
150// registry. Adapter construction itself moved inside each driver's
151// `create()`; `ProviderEventLoggersLive` owns the shared native/canonical
152// NDJSON writers and is provided at the outer runtime layer so both
153// `ProviderService` and the per-instance drivers read the same logger pair.
154const ProviderLayerLive = ProviderServiceLive.pipe(
155 Layer.provide(ProviderAdapterRegistryLive),
156 Layer.provideMerge(ProviderSessionDirectoryLayerLive),
157);
158​
159const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
160​
161const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
162 Layer.provide(VcsProjectConfig.layer),
163);
164​
165const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
166 Layer.provide(Layer.mergeAll(GitHubCli.layer, GitLabCli.layer)),
167 Layer.provideMerge(VcsDriverRegistryLayerLive),
168);
169​
170const GitManagerLayerLive = GitManager.layer.pipe(
171 Layer.provideMerge(ProjectSetupScriptRunnerLive),
172 Layer.provideMerge(GitVcsDriver.layer),
173 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
174 Layer.provideMerge(TextGeneration.layer),
175);
176​
177const GitLayerLive = Layer.empty.pipe(
178 Layer.provideMerge(GitManagerLayerLive),
179 Layer.provideMerge(GitVcsDriver.layer),
180);
181​
182const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
183 Layer.provideMerge(VcsDriverRegistryLayerLive),
184 Layer.provideMerge(GitLayerLive),
185);
186​
187const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
188 Layer.provideMerge(GitVcsDriver.layer),
189 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
190);
191​
192const VcsLayerLive = Layer.empty.pipe(
193 Layer.provideMerge(VcsProjectConfig.layer),
194 Layer.provideMerge(VcsDriverRegistryLayerLive),
195 Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
196 Layer.provideMerge(GitWorkflowLayerLive),
197 Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
198 Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
199);
200​
201const CheckpointingLayerLive = Layer.empty.pipe(
202 Layer.provideMerge(CheckpointDiffQueryLive),
203 Layer.provideMerge(CheckpointStoreLive.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
204);
205​
206const TerminalLayerLive = TerminalManagerLive.pipe(Layer.provide(PtyAdapterLive));
207​
208const WorkspaceEntriesLayerLive = WorkspaceEntriesLive.pipe(
209 Layer.provide(WorkspacePathsLive),
210 Layer.provideMerge(VcsDriverRegistryLayerLive),
211);
212​
213const WorkspaceFileSystemLayerLive = WorkspaceFileSystemLive.pipe(
214 Layer.provide(WorkspacePathsLive),
215 Layer.provide(WorkspaceEntriesLayerLive),
216);
217​
218const WorkspaceLayerLive = Layer.mergeAll(
219 WorkspacePathsLive,
220 WorkspaceEntriesLayerLive,
221 WorkspaceFileSystemLayerLive,
222);
223​
224const AuthLayerLive = ServerAuthLive.pipe(
225 Layer.provideMerge(PersistenceLayerLive),
226 Layer.provide(ServerSecretStoreLive),
227);
228​
229const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
230 Layer.provideMerge(ProviderLayerLive),
231 Layer.provideMerge(OrchestrationLayerLive),
232);
233​
234const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
235 // Core Services
236 Layer.provideMerge(CheckpointingLayerLive),
237 Layer.provideMerge(GitLayerLive),
238 Layer.provideMerge(VcsLayerLive),
239 Layer.provideMerge(ProviderRuntimeLayerLive),
240 Layer.provideMerge(TerminalLayerLive),
241 Layer.provideMerge(PersistenceLayerLive),
242 Layer.provideMerge(KeybindingsLive),
243 Layer.provideMerge(ProviderRegistryLive),
244 // The instance registry is the new routing keystone — text generation,
245 // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
246 // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
247 // `providerInstances` hydration merges `settings.providers.<kind>`
248 // with explicit `providerInstances` entries on boot.
249 Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
250 // Shared native/canonical NDJSON writers used by both the per-instance
251 // drivers (native stream, written from inside each `<X>Adapter`) and
252 // `ProviderService` (canonical stream, written after event normalization).
253 // Provided once at the runtime level so every consumer sees the same
254 // logger instances.
255 Layer.provideMerge(ProviderEventLoggersLive),
256 // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
257 // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
258 // the rewritten registry reads snapshots off the instance registry and
259 // no longer transitively provides it. Exposing it at the runtime level
260 // keeps a single Live for all opencode consumers.
261 Layer.provideMerge(OpenCodeRuntimeLive),
262 Layer.provideMerge(ServerSettingsLive),
263 Layer.provideMerge(WorkspaceLayerLive),
264 Layer.provideMerge(ProjectFaviconResolverLive),
265 Layer.provideMerge(RepositoryIdentityResolverLive),
266 Layer.provideMerge(ServerEnvironmentLive),
267 Layer.provideMerge(AuthLayerLive),
268);
269​
270const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
271 // Misc.
272 Layer.provideMerge(AnalyticsServiceLayerLive),
273 Layer.provideMerge(OpenLive),
274 Layer.provideMerge(ServerLifecycleEventsLive),
275 Layer.provide(NetService.layer),
276);
277​
278const RuntimeServicesLive = ServerRuntimeStartupLive.pipe(
279 Layer.provideMerge(RuntimeDependenciesLive),
280);
281​
282export const makeRoutesLayer = Layer.mergeAll(
283 authBearerBootstrapRouteLayer,
284 authBootstrapRouteLayer,
285 authClientsRevokeOthersRouteLayer,
286 authClientsRevokeRouteLayer,
287 authClientsRouteLayer,
288 authPairingLinksRevokeRouteLayer,
289 authPairingLinksRouteLayer,
290 authPairingCredentialRouteLayer,
291 authSessionRouteLayer,
292 authWebSocketTokenRouteLayer,
293 attachmentsRouteLayer,
294 orchestrationDispatchRouteLayer,
295 orchestrationSnapshotRouteLayer,
296 otlpTracesProxyRouteLayer,
297 projectFaviconRouteLayer,
298 serverEnvironmentRouteLayer,
299 staticAndDevRouteLayer,
300 websocketRpcRouteLayer,
301).pipe(Layer.provide(browserApiCorsLayer));
302​
303export const makeServerLayer = Layer.unwrap(
304 Effect.gen(function* () {
305 const config = yield* ServerConfig;
306​
307 fixPath();
308​
309 const httpListeningLayer = Layer.effectDiscard(
310 Effect.gen(function* () {
311 yield* HttpServer.HttpServer;
312 const startup = yield* ServerRuntimeStartup;
313 yield* startup.markHttpListening;
314 }),
315 );
316 const runtimeStateLayer = Layer.effectDiscard(
317 Effect.acquireRelease(
318 Effect.gen(function* () {
319 const server = yield* HttpServer.HttpServer;
320 const address = server.address;
321 if (typeof address === "string" || !("port" in address)) {
322 return;
323 }
324​
325 const state = makePersistedServerRuntimeState({
326 config,
327 port: address.port,
328 });
329 yield* persistServerRuntimeState({
330 path: config.serverRuntimeStatePath,
331 state,
332 });
333 }),
334 () => clearPersistedServerRuntimeState(config.serverRuntimeStatePath),
335 ),
336 );
337​
338 const serverApplicationLayer = Layer.mergeAll(
339 HttpRouter.serve(makeRoutesLayer, {
340 disableLogger: !config.logWebSocketEvents,
341 }),
342 httpListeningLayer,
343 runtimeStateLayer,
344 );
345​
346 return serverApplicationLayer.pipe(
347 Layer.provideMerge(RuntimeServicesLive),
348 Layer.provideMerge(HttpServerLive),
349 Layer.provide(ObservabilityLive),
350 Layer.provideMerge(FetchHttpClient.layer),
351 Layer.provideMerge(VcsProcess.layer),
352 Layer.provideMerge(PlatformServicesLive),
353 );
354 }),
355);
356​
357// Important: Only `ServerConfig` should be provided by the CLI layer!!! Don't let other requirements leak into the launch layer.
358export const runServer = Layer.launch(makeServerLayer) satisfies Effect.Effect<
359 never,
360 any,
361 ServerConfig
362>;