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