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