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