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

server.ts

686 lines29.5 KB

1import { EnvironmentHttpApi } from "@t3tools/contracts";
2import * as Duration from "effect/Duration";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Schedule from "effect/Schedule";
7import { FetchHttpClient, HttpRouter, HttpServer } from "effect/unstable/http";
8import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
9​
10import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
11import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
12import * as ServerConfig from "./config.ts";
13import {
14 otlpTracesProxyRouteLayer,
15 assetRouteLayer,
16 serverEnvironmentHttpApiLayer,
17 staticAndDevRouteLayer,
18 browserApiCorsLayer,
19 httpCompressionLayer,
20} from "./http.ts";
21import { fixPath } from "./os-jank.ts";
22import { websocketRpcRouteLayer } from "./ws.ts";
23import * as ExternalLauncher from "./process/externalLauncher.ts";
24import { pullRequestHttpApiLayer } from "./pullRequest/http.ts";
25import * as PullRequestProviderRegistry from "./pullRequest/PullRequestProviderRegistry.ts";
26import * as PullRequestService from "./pullRequest/PullRequestService.ts";
27import { layerConfig as SqlitePersistenceLayerLive } from "./persistence/Layers/Sqlite.ts";
28import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
29import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
30import { ProviderSessionDirectoryLive } from "./provider/Layers/ProviderSessionDirectory.ts";
31import * as ProviderSessionRuntime from "./persistence/ProviderSessionRuntime.ts";
32import { ProviderAdapterRegistryLive } from "./provider/Layers/ProviderAdapterRegistry.ts";
33import * as ProviderEventLoggers from "./provider/Layers/ProviderEventLoggers.ts";
34import { ProviderServiceLive } from "./provider/Layers/ProviderService.ts";
35import { ProviderSessionReaperLive } from "./provider/Layers/ProviderSessionReaper.ts";
36import * as OpenCodeRuntime from "./provider/opencodeRuntime.ts";
37import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
38import * as CheckpointStore from "./checkpointing/CheckpointStore.ts";
39import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
40import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
41import * as GitHubCli from "./sourceControl/GitHubCli.ts";
42import * as GitLabCli from "./sourceControl/GitLabCli.ts";
43import * as TextGeneration from "./textGeneration/TextGeneration.ts";
44import { ProviderInstanceRegistryHydrationLive } from "./provider/Layers/ProviderInstanceRegistryHydration.ts";
45import * as TerminalManager from "./terminal/Manager.ts";
46import * as McpHttpServer from "./mcp/McpHttpServer.ts";
47import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
48import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
49import * as PreviewManager from "./preview/Manager.ts";
50import * as PortScanner from "./preview/PortScanner.ts";
51import * as ProcessRunner from "./processRunner.ts";
52import * as GitManager from "./git/GitManager.ts";
53import * as Keybindings from "./keybindings.ts";
54import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
55import { OrchestrationReactorLive } from "./orchestration/Layers/OrchestrationReactor.ts";
56import { RuntimeReceiptBusLive } from "./orchestration/Layers/RuntimeReceiptBus.ts";
57import { ProviderRuntimeIngestionLive } from "./orchestration/Layers/ProviderRuntimeIngestion.ts";
58import { ProviderCommandReactorLive } from "./orchestration/Layers/ProviderCommandReactor.ts";
59import { CheckpointReactorLive } from "./orchestration/Layers/CheckpointReactor.ts";
60import { ThreadDeletionReactorLive } from "./orchestration/Layers/ThreadDeletionReactor.ts";
61import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
62import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
63import { ProviderRegistryLive } from "./provider/Layers/ProviderRegistry.ts";
64import * as ServerSettings from "./serverSettings.ts";
65import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
66import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
67import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
68import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
69import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
70import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
71import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
72import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
73import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
74import * as VcsProcess from "./vcs/VcsProcess.ts";
75import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
76import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
77import * as GitWorkflowService from "./git/GitWorkflowService.ts";
78import * as ReviewService from "./review/ReviewService.ts";
79import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
80import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
81import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
82import { ObservabilityLive } from "./observability/Layers/Observability.ts";
83import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
84import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
85import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
86import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
87import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
88import {
89 connectHttpApiLayer,
90 pendingServiceUpdateExists,
91 reconcileDesiredCloudLink,
92 releaseManagedTunnelOnShutdown,
93} from "./cloud/http.ts";
94import { serverRelayBrokerTracingLayer } from "./cloud/relayTracing.ts";
95import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
96import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
97import * as CloudCliState from "./cloud/CliState.ts";
98import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
99import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
100import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
101import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
102import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
103import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts";
104import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";
105import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
106import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts";
107import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
108import * as UsageService from "./usage/UsageService.ts";
109import { OrchestrationLayerLive } from "./orchestration/runtimeLayer.ts";
110import {
111 clearPersistedServerRuntimeState,
112 makePersistedServerRuntimeState,
113 persistServerRuntimeState,
114} from "./serverRuntimeState.ts";
115import { orchestrationHttpApiLayer } from "./orchestration/http.ts";
116import * as NetService from "@t3tools/shared/Net";
117import * as RelayClient from "@t3tools/shared/relayClient";
118import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
119import { forkParked, ServerActivation } from "./serverActivation.ts";
120​
121// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
122// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
123// already closes the websocket gracefully. Do not add an artificial drain before
124// those finalizers get a chance to run.
125const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;
126const ResourceAttributionLayerLive = ResourceAttribution.layer;
127const ApplicationObservabilityLive = ObservabilityLive.pipe(
128 Layer.provideMerge(ResourceAttributionLayerLive),
129);
130​
131const PtyAdapterLive = Layer.unwrap(
132 Effect.gen(function* () {
133 if (typeof Bun !== "undefined") {
134 const BunPtyAdapter = yield* Effect.promise(() => import("./terminal/BunPtyAdapter.ts"));
135 return BunPtyAdapter.layer;
136 } else {
137 const NodePtyAdapter = yield* Effect.promise(() => import("./terminal/NodePtyAdapter.ts"));
138 return NodePtyAdapter.layer;
139 }
140 }),
141);
142​
143const ServerSettingsLayerLive = ServerSettings.layer.pipe(Layer.provide(ServerSecretStore.layer));
144​
145const NativeTelemetryLayerLive = NativeTelemetryClient.layer.pipe(
146 Layer.provide(ResourceMonitorBinary.layer),
147);
148const DesktopTelemetryReceiverLayerLive = DesktopTelemetryReceiver.layer.pipe(
149 Layer.provideMerge(ServerSettingsLayerLive),
150);
151​
152const ResourceTelemetryLayerLive = ResourceTelemetry.layer.pipe(
153 Layer.provideMerge(NativeTelemetryLayerLive),
154 Layer.provideMerge(DesktopTelemetryReceiverLayerLive),
155);
156​
157const HostPowerMonitorLayerLive = HostPowerMonitor.layer.pipe(
158 Layer.provide(DesktopTelemetryReceiverLayerLive),
159);
160​
161const BackgroundLayerLive = BackgroundPolicy.layer.pipe(
162 Layer.provide(HostPowerMonitorLayerLive),
163 Layer.provideMerge(ServerSettingsLayerLive),
164);
165​
166const UsageLayerLive = UsageService.layer.pipe(Layer.provide(ServerSettingsLayerLive));
167​
168const ResourceDiagnosticsLayerLive = Layer.mergeAll(
169 ResourceTelemetryLayerLive,
170 ProcessDiagnostics.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
171 ProcessResourceMonitor.layer.pipe(Layer.provide(ResourceTelemetryLayerLive)),
172);
173​
174const RelayClientLive = Layer.unwrap(
175 Effect.gen(function* () {
176 const config = yield* ServerConfig.ServerConfig;
177 return RelayClient.layerCloudflared({ baseDir: config.baseDir });
178 }),
179);
180​
181const HttpServerLive = Layer.unwrap(
182 Effect.gen(function* () {
183 const config = yield* ServerConfig.ServerConfig;
184 if (typeof Bun !== "undefined") {
185 const BunHttpServer = yield* Effect.promise(
186 () => import("@effect/platform-bun/BunHttpServer"),
187 );
188 return BunHttpServer.layer({
189 port: config.port,
190 hostname: config.host ?? "127.0.0.1",
191 gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
192 websocket: {
193 // Negotiate permessage-deflate with clients that offer it; clients
194 // that don't still get uncompressed frames on their connection. A
195 // dedicated compressor keeps a per-connection sliding window
196 // (context takeover) so the compression dictionary is shared across
197 // server-to-client frames. Decompression uses the shared
198 // decompressor: uWebSockets' dedicated decompressor path can abort
199 // connections (close 1006) on valid DEFLATE input — see
200 // https://github.com/uNetworking/uWebSockets.js/issues/633.
201 perMessageDeflate: {
202 compress: "dedicated",
203 decompress: "shared",
204 },
205 },
206 });
207 } else {
208 const [NodeHttpServer, NodeHttp] = yield* Effect.all([
209 Effect.promise(() => import("@effect/platform-node/NodeHttpServer")),
210 Effect.promise(() => import("node:http")),
211 ]);
212 return NodeHttpServer.layer(NodeHttp.createServer, {
213 host: config.host ?? "127.0.0.1",
214 port: config.port,
215 gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
216 // Negotiate permessage-deflate with clients that offer it; clients
217 // that don't still get uncompressed frames on their connection.
218 // Context takeover stays enabled (ws default) so the compression
219 // window is shared across frames — that also makes small frames cheap
220 // to compress, so no size threshold is set (ws only honors
221 // `threshold` when context takeover is disabled).
222 websocket: { perMessageDeflate: true },
223 });
224 }
225 }),
226);
227​
228const PlatformServicesLive = Layer.unwrap(
229 Effect.gen(function* () {
230 if (typeof Bun !== "undefined") {
231 const { layer } = yield* Effect.promise(() => import("@effect/platform-bun/BunServices"));
232 return layer;
233 } else {
234 const { layer } = yield* Effect.promise(() => import("@effect/platform-node/NodeServices"));
235 return layer;
236 }
237 }),
238);
239​
240const ReactorLayerLive = Layer.empty.pipe(
241 Layer.provideMerge(OrchestrationReactorLive),
242 Layer.provideMerge(ProviderRuntimeIngestionLive),
243 Layer.provideMerge(ProviderCommandReactorLive),
244 Layer.provideMerge(CheckpointReactorLive),
245 Layer.provideMerge(ThreadDeletionReactorLive),
246 Layer.provideMerge(AgentAwarenessRelay.layer.pipe(Layer.provide(ServerSecretStore.layer))),
247 Layer.provideMerge(RuntimeReceiptBusLive),
248);
249​
250const ProviderSessionDirectoryLayerLive = ProviderSessionDirectoryLive.pipe(
251 Layer.provide(ProviderSessionRuntime.layer),
252);
253​
254// `ProviderAdapterRegistryLive` is now a facade that resolves kind → adapter
255// by looking up the default `ProviderInstance` per driver in the instance
256// registry. Adapter construction itself moved inside each driver's
257// `create()`; `ProviderEventLoggers.layer` owns the shared native/canonical
258// NDJSON writers and is provided at the outer runtime layer so both
259// `ProviderService` and the per-instance drivers read the same logger pair.
260const ProviderLayerLive = ProviderServiceLive.pipe(
261 Layer.provide(ProviderAdapterRegistryLive),
262 Layer.provideMerge(ProviderSessionDirectoryLayerLive),
263);
264​
265const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive));
266​
267const VcsDriverRegistryLayerLive = VcsDriverRegistry.layer.pipe(
268 Layer.provide(VcsProjectConfig.layer),
269);
270​
271const SourceControlProviderRegistryLayerLive = SourceControlProviderRegistry.layer.pipe(
272 Layer.provide(
273 Layer.mergeAll(AzureDevOpsCli.layer, BitbucketApi.layer, GitHubCli.layer, GitLabCli.layer),
274 ),
275 Layer.provideMerge(GitVcsDriver.layer),
276 Layer.provideMerge(VcsDriverRegistryLayerLive),
277);
278​
279const GitManagerLayerLive = GitManager.layer.pipe(
280 Layer.provideMerge(ProjectSetupScriptRunner.layer),
281 Layer.provideMerge(GitVcsDriver.layer),
282 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
283 Layer.provideMerge(TextGeneration.layer),
284);
285​
286const GitLayerLive = Layer.empty.pipe(
287 Layer.provideMerge(GitManagerLayerLive),
288 Layer.provideMerge(GitVcsDriver.layer),
289);
290​
291const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
292 Layer.provideMerge(VcsDriverRegistryLayerLive),
293 Layer.provideMerge(GitLayerLive),
294);
295​
296const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
297 Layer.provideMerge(GitVcsDriver.layer),
298 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
299);
300​
301const ReviewLayerLive = ReviewService.layer.pipe(
302 Layer.provideMerge(GitVcsDriver.layer),
303 Layer.provideMerge(VcsDriverRegistryLayerLive),
304);
305​
306const VcsLayerLive = Layer.empty.pipe(
307 Layer.provideMerge(VcsProjectConfig.layer),
308 Layer.provideMerge(VcsDriverRegistryLayerLive),
309 Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
310 Layer.provideMerge(GitWorkflowLayerLive),
311 Layer.provideMerge(ReviewLayerLive),
312 Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
313 Layer.provideMerge(VcsStatusBroadcaster.layer.pipe(Layer.provide(GitWorkflowLayerLive))),
314);
315​
316const CheckpointingLayerLive = Layer.empty.pipe(
317 Layer.provideMerge(CheckpointDiffQuery.layer),
318 Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
319);
320​
321const PortScannerLayerLive = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer));
322​
323const TerminalLayerLive = TerminalManager.layer.pipe(
324 Layer.provide(PtyAdapterLive),
325 Layer.provide(PortScannerLayerLive),
326);
327​
328const PreviewLayerLive = Layer.empty.pipe(
329 Layer.provideMerge(PreviewManager.layer),
330 Layer.provideMerge(PortScannerLayerLive),
331);
332​
333const WorkspaceEntriesLayerLive = WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer));
334​
335const WorkspaceFileSystemLayerLive = WorkspaceFileSystem.layer.pipe(
336 Layer.provide(WorkspacePaths.layer),
337 Layer.provide(WorkspaceEntriesLayerLive),
338);
339​
340const WorkspaceLayerLive = Layer.mergeAll(
341 WorkspacePaths.layer,
342 WorkspaceEntriesLayerLive,
343 WorkspaceFileSystemLayerLive,
344);
345​
346const ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe(
347 Layer.provide(WorkspacePaths.layer),
348 Layer.provide(T3ProjectFileLoader.layer),
349);
350​
351const AuthLayerLive = EnvironmentAuth.layer.pipe(
352 Layer.provideMerge(PersistenceLayerLive),
353 Layer.provide(ServerSecretStore.layer),
354);
355​
356const CloudManagedEndpointRuntimeLive = Layer.mergeAll(
357 RelayClientLive,
358 CloudManagedEndpointRuntime.layer.pipe(
359 Layer.provide(ServerSecretStore.layer),
360 Layer.provide(RelayClientLive),
361 ),
362);
363​
364const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
365 Layer.provideMerge(ProviderLayerLive),
366 Layer.provideMerge(OrchestrationLayerLive),
367);
368​
369const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
370 // Core Services
371 Layer.provideMerge(ServerSettingsLayerLive),
372 Layer.provideMerge(CheckpointingLayerLive),
373 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
374 Layer.provideMerge(GitLayerLive),
375 Layer.provideMerge(VcsLayerLive),
376 Layer.provideMerge(ProviderRuntimeLayerLive),
377 Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)),
378 Layer.provideMerge(PersistenceLayerLive),
379 Layer.provideMerge(Keybindings.layer),
380 Layer.provideMerge(ProviderRegistryLive),
381 // The instance registry is the new routing keystone — text generation,
382 // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
383 // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
384 // `providerInstances` hydration merges `settings.providers.<kind>`
385 // with explicit `providerInstances` entries on boot.
386 Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
387 // Shared native/canonical NDJSON writers used by both the per-instance
388 // drivers (native stream, written from inside each `<X>Adapter`) and
389 // `ProviderService` (canonical stream, written after event normalization).
390 // Provided once at the runtime level so every consumer sees the same
391 // logger instances.
392 Layer.provideMerge(ProviderEventLoggers.layer),
393 // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
394 // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
395 // the rewritten registry reads snapshots off the instance registry and
396 // no longer transitively provides it. Exposing it at the runtime level
397 // keeps a single Live for all opencode consumers.
398 Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
399 Layer.provideMerge(WorkspaceLayerLive),
400 Layer.provideMerge(ProjectFaviconResolverLayerLive),
401 Layer.provideMerge(RepositoryIdentityResolver.layer),
402 Layer.provideMerge(ServerEnvironment.layer),
403 Layer.provideMerge(AuthLayerLive),
404 Layer.provideMerge(ServerSecretStore.layer),
405 Layer.provideMerge(
406 Layer.mergeAll(
407 CloudCliTokenManager.layer.pipe(
408 Layer.provide(ServerSecretStore.layer),
409 Layer.provide(ExternalLauncher.layer),
410 ),
411 CloudManagedEndpointRuntimeLive,
412 ),
413 ),
414);
415​
416const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
417 // Misc.
418 Layer.provideMerge(BackgroundLayerLive),
419 Layer.provideMerge(ResourceDiagnosticsLayerLive),
420 Layer.provideMerge(UsageLayerLive),
421 Layer.provideMerge(TraceDiagnostics.layer),
422 Layer.provideMerge(AnalyticsService.layer),
423 Layer.provideMerge(ExternalLauncher.layer),
424 Layer.provideMerge(RemoteOpenTargets.layer),
425 Layer.provideMerge(ServerLifecycleEvents.layer),
426 Layer.provide(NetService.layer),
427);
428​
429const commandReadinessLayer = HttpRouter.middleware(
430 (httpEffect) =>
431 Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>
432 startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),
433 ),
434 { global: true },
435);
436​
437const PullRequestServiceLive = PullRequestService.layer.pipe(
438 // One registry entry per supported host; the service only knows the registry.
439 Layer.provide(PullRequestProviderRegistry.layer),
440 Layer.provide(SourceControlProviderRegistryLayerLive),
441 Layer.provide(VcsProcess.layer),
442);
443​
444export const makeRoutesLayer = Layer.mergeAll(
445 Layer.mergeAll(
446 HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
447 Layer.provide(authHttpApiLayer),
448 Layer.provide(connectHttpApiLayer),
449 Layer.provide(orchestrationHttpApiLayer),
450 Layer.provide(pullRequestHttpApiLayer),
451 Layer.provide(serverEnvironmentHttpApiLayer),
452 Layer.provide(environmentAuthenticatedAuthLayer),
453 ),
454 otlpTracesProxyRouteLayer,
455 assetRouteLayer,
456 staticAndDevRouteLayer,
457 websocketRpcRouteLayer,
458 ),
459 McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
460).pipe(
461 // Both transports consume the same service instance, so caches single-flight across clients
462 // and mutations observed on WebSocket invalidate patches subsequently read over HTTP.
463 Layer.provide(PullRequestServiceLive),
464 Layer.provide(PreviewAutomationBroker.layer),
465 Layer.provide(ServerSelfUpdate.layer),
466 Layer.provide(commandReadinessLayer),
467 Layer.provide(browserApiCorsLayer),
468 Layer.provide(httpCompressionLayer),
469);
470​
471export const makeServerLayer = Layer.unwrap(
472 Effect.gen(function* () {
473 const config = yield* ServerConfig.ServerConfig;
474 const activation = yield* Deferred.make<void>();
475 const awaitActivation = Deferred.await(activation);
476 const activationLayer = Layer.succeed(ServerActivation, awaitActivation);
477 const runtimeStateParked = yield* Deferred.make<void>();
478 const tailscaleParked = yield* Deferred.make<void>();
479 const cloudLinkParked = yield* Deferred.make<void>();
480 const routesReady = yield* Deferred.make<void>();
481 const launcherLayer = ServiceLauncherClient.layer;
482​
483 yield* fixPath();
484​
485 const httpListeningLayer = Layer.effectDiscard(
486 Effect.gen(function* () {
487 yield* HttpServer.HttpServer;
488 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
489 yield* startup.markHttpListening;
490 }),
491 );
492 const runtimeStateLayer = Layer.effectDiscard(
493 Effect.acquireRelease(
494 Effect.gen(function* () {
495 yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);
496 yield* awaitActivation;
497 const server = yield* HttpServer.HttpServer;
498 const address = server.address;
499 if (typeof address === "string" || !("port" in address)) {
500 return;
501 }
502​
503 const state = yield* makePersistedServerRuntimeState({
504 config,
505 port: address.port,
506 });
507 yield* persistServerRuntimeState({
508 path: config.serverRuntimeStatePath,
509 state,
510 }).pipe(
511 Effect.catchCause((cause) =>
512 Effect.logWarning("Failed to persist server runtime state", { cause }),
513 ),
514 );
515 }),
516 () =>
517 clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(
518 Effect.catchCause((cause) =>
519 Effect.logWarning("Failed to clear server runtime state", { cause }),
520 ),
521 ),
522 ),
523 );
524 const tailscaleServeLayer = config.tailscaleServeEnabled
525 ? Layer.effectDiscard(
526 Effect.acquireRelease(
527 Effect.gen(function* () {
528 yield* Deferred.succeed(tailscaleParked, undefined).pipe(Effect.orDie);
529 yield* awaitActivation;
530 const server = yield* HttpServer.HttpServer;
531 const address = server.address;
532 if (typeof address === "string" || !("port" in address)) {
533 return null;
534 }
535​
536 const localPort = address.port;
537 return yield* ensureTailscaleServe({
538 localPort,
539 servePort: config.tailscaleServePort,
540 localHost: "127.0.0.1",
541 }).pipe(
542 Effect.as({ localPort, servePort: config.tailscaleServePort }),
543 Effect.tap(() =>
544 Effect.logInfo("Tailscale Serve configured", {
545 localPort,
546 servePort: config.tailscaleServePort,
547 }),
548 ),
549 Effect.catch((cause) =>
550 Effect.logWarning("Failed to configure Tailscale Serve", {
551 cause,
552 localPort,
553 servePort: config.tailscaleServePort,
554 }).pipe(Effect.as(null)),
555 ),
556 );
557 }),
558 (configured) =>
559 configured
560 ? disableTailscaleServe({ servePort: configured.servePort }).pipe(
561 Effect.tap(() =>
562 Effect.logInfo("Tailscale Serve disabled", {
563 servePort: configured.servePort,
564 }),
565 ),
566 Effect.catch((cause) =>
567 Effect.logWarning("Failed to disable Tailscale Serve", {
568 cause,
569 servePort: configured.servePort,
570 }),
571 ),
572 )
573 : Effect.void,
574 ),
575 )
576 : Layer.empty;
577 const cloudDesiredLinkReconcileLayer = Layer.effectDiscard(
578 Effect.gen(function* () {
579 if (!hasCloudPublicConfig) {
580 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
581 return;
582 }
583 const releaseManagedTunnel = releaseManagedTunnelOnShutdown().pipe(
584 Effect.timeout("10 seconds"),
585 Effect.tap((released) =>
586 released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
587 ),
588 Effect.catchCause((cause) =>
589 Effect.logWarning(
590 "Failed to release the managed tunnel on shutdown; the next link reuses it",
591 { cause },
592 ),
593 ),
594 Effect.asVoid,
595 );
596 // A launcher trial can be stopped before activation. The previous
597 // server is already gone, so the trial owns cleanup immediately; the
598 // pending-state check keeps the tunnel for normal commit or rollback,
599 // while the launcher's explicit-stop marker allows it to be released.
600 // Other runtimes wait for activation so a failed standby cannot tear
601 // down the active runtime's tunnel.
602 const cleanupBeforeActivation = yield* pendingServiceUpdateExists;
603 if (cleanupBeforeActivation) {
604 yield* Effect.addFinalizer(() => releaseManagedTunnel);
605 }
606 yield* forkParked(
607 Effect.gen(function* () {
608 if (!cleanupBeforeActivation) {
609 yield* Effect.addFinalizer(() => releaseManagedTunnel);
610 }
611 if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
612 const server = yield* HttpServer.HttpServer;
613 const address = server.address;
614 if (typeof address === "string" || !("port" in address)) return;
615 // No settling delay before the first attempt: routes are already
616 // serving by the time activation opens this gate (the startup
617 // sequence awaits routesReady), and the retry schedule below
618 // covers anything this sleep used to hedge against. Every
619 // millisecond here is dead time on the path to remote
620 // reachability after a restart.
621 yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(
622 Effect.retry({
623 while: (error) =>
624 error._tag !== "EnvironmentHttpBadRequestError" &&
625 error._tag !== "EnvironmentHttpUnauthorizedError" &&
626 error._tag !== "EnvironmentHttpConflictError",
627 schedule: Schedule.exponential("1 second").pipe(
628 Schedule.modifyDelay(({ duration }) =>
629 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
630 ),
631 Schedule.upTo({ duration: "10 minutes" }),
632 ),
633 }),
634 Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
635 Effect.catch((cause) =>
636 Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
637 cause,
638 }),
639 ),
640 );
641 }),
642 );
643 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
644 }),
645 );
646​
647 const runtimeServicesLive = ServerRuntimeStartup.layerWithOptions({
648 activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),
649 abort: (error) => Deferred.die(activation, error).pipe(Effect.asVoid),
650 awaitAuxiliaryParked: Effect.all(
651 [
652 Deferred.await(runtimeStateParked),
653 Deferred.await(cloudLinkParked),
654 Deferred.await(routesReady),
655 ...(config.tailscaleServeEnabled ? [Deferred.await(tailscaleParked)] : []),
656 ],
657 { concurrency: "unbounded" },
658 ).pipe(Effect.asVoid),
659 }).pipe(Layer.provideMerge(RuntimeDependenciesLive), Layer.provide(launcherLayer));
660​
661 const routesLayer = HttpRouter.serve(makeRoutesLayer.pipe(Layer.provide(launcherLayer)), {
662 disableLogger: !config.logWebSocketEvents,
663 }).pipe(Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)));
664 const serverApplicationLayer = Layer.mergeAll(
665 routesLayer,
666 httpListeningLayer,
667 runtimeStateLayer,
668 tailscaleServeLayer,
669 cloudDesiredLinkReconcileLayer,
670 );
671​
672 return serverApplicationLayer.pipe(
673 Layer.provideMerge(runtimeServicesLive),
674 Layer.provide(activationLayer),
675 Layer.provideMerge(serverRelayBrokerTracingLayer),
676 Layer.provideMerge(HttpServerLive),
677 Layer.provide(ApplicationObservabilityLive),
678 Layer.provideMerge(FetchHttpClient.layer),
679 Layer.provideMerge(VcsProcess.layer),
680 Layer.provideMerge(PlatformServicesLive),
681 );
682 }),
683);
684​
685// The CLI supplies configuration.
686export const runServer = Layer.launch(makeServerLayer);