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

server.ts

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