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

server.ts

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