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

server.ts

728 lines31.3 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 { 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);
307​
308const GitManagerLayerLive = GitManager.layer.pipe(
309 Layer.provideMerge(ProjectSetupScriptRunner.layer),
310 Layer.provideMerge(GitVcsDriver.layer),
311 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
312 Layer.provideMerge(TextGeneration.layer),
313);
314​
315const GitLayerLive = Layer.empty.pipe(
316 Layer.provideMerge(GitManagerLayerLive),
317 Layer.provideMerge(GitVcsDriver.layer),
318);
319​
320const GitWorkflowLayerLive = GitWorkflowService.layer.pipe(
321 Layer.provideMerge(VcsDriverRegistryLayerLive),
322 Layer.provideMerge(GitLayerLive),
323);
324​
325const SourceControlRepositoryServiceLayerLive = SourceControlRepositoryService.layer.pipe(
326 Layer.provideMerge(GitVcsDriver.layer),
327 Layer.provideMerge(SourceControlProviderRegistryLayerLive),
328);
329​
330const ReviewLayerLive = ReviewService.layer.pipe(
331 Layer.provideMerge(GitVcsDriver.layer),
332 Layer.provideMerge(VcsDriverRegistryLayerLive),
333);
334​
335const VcsLayerLive = Layer.empty.pipe(
336 Layer.provideMerge(VcsProjectConfig.layer),
337 Layer.provideMerge(VcsDriverRegistryLayerLive),
338 Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
339 Layer.provideMerge(GitWorkflowLayerLive),
340 Layer.provideMerge(ReviewLayerLive),
341 Layer.provideMerge(SourceControlRepositoryServiceLayerLive),
342 Layer.provideMerge(
343 VcsStatusBroadcaster.layer.pipe(
344 Layer.provide(GitWorkflowLayerLive),
345 Layer.provide(VcsStatusBroadcaster.autoPullPolicyLayer),
346 ),
347 ),
348);
349​
350const CheckpointingLayerLive = Layer.empty.pipe(
351 Layer.provideMerge(CheckpointDiffQuery.layer),
352 Layer.provideMerge(CheckpointStore.layer.pipe(Layer.provide(VcsDriverRegistryLayerLive))),
353);
354​
355const PortScannerLayerLive = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer));
356​
357const TerminalLayerLive = TerminalManager.layer.pipe(
358 Layer.provide(PtyAdapterLive),
359 Layer.provide(PortScannerLayerLive),
360);
361​
362const PreviewLayerLive = Layer.empty.pipe(
363 Layer.provideMerge(PreviewManager.layer),
364 Layer.provideMerge(PortScannerLayerLive),
365);
366​
367const WorkspaceEntriesLayerLive = WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer));
368​
369const WorkspaceFileSystemLayerLive = WorkspaceFileSystem.layer.pipe(
370 Layer.provide(WorkspacePaths.layer),
371 Layer.provide(WorkspaceEntriesLayerLive),
372);
373​
374const WorkspaceLayerLive = Layer.mergeAll(
375 WorkspacePaths.layer,
376 WorkspaceEntriesLayerLive,
377 WorkspaceFileSystemLayerLive,
378);
379​
380const ProjectFaviconResolverLayerLive = ProjectFaviconResolver.layer.pipe(
381 Layer.provide(WorkspacePaths.layer),
382 Layer.provide(T3ProjectFileLoader.layer),
383);
384​
385const ServerEnvironmentLayerLive = ServerEnvironment.layer.pipe(
386 Layer.provide(ServerSecretStore.layer),
387);
388​
389const AuthLayerLive = EnvironmentAuth.layer.pipe(
390 Layer.provideMerge(PersistenceLayerLive),
391 Layer.provide(ServerEnvironmentLayerLive),
392 Layer.provide(ServerSecretStore.layer),
393);
394​
395const CloudManagedEndpointRuntimeLive = Layer.mergeAll(
396 RelayClientLive,
397 CloudManagedEndpointRuntime.layer.pipe(
398 Layer.provide(ServerSecretStore.layer),
399 Layer.provide(RelayClientLive),
400 ),
401);
402​
403const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe(
404 Layer.provideMerge(ProviderLayerLive),
405 Layer.provideMerge(OrchestrationLayerLive),
406);
407​
408const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe(
409 // Core Services
410 Layer.provideMerge(ServerSettingsLayerLive),
411 Layer.provideMerge(CheckpointingLayerLive),
412 Layer.provideMerge(
413 Layer.mergeAll(SourceControlProviderRegistryLayerLive, PullRequestServiceLive),
414 ),
415 Layer.provideMerge(GitLayerLive),
416 Layer.provideMerge(VcsLayerLive),
417 Layer.provideMerge(ProviderRuntimeLayerLive),
418 Layer.provideMerge(Layer.mergeAll(TerminalLayerLive, PreviewLayerLive)),
419 Layer.provideMerge(PersistenceLayerLive),
420 // Both read a user-owned file out of the state directory and stream changes
421 // to clients; neither depends on the other.
422 Layer.provideMerge(Layer.mergeAll(Keybindings.layer, EnvironmentTheme.layer)),
423 Layer.provideMerge(ProviderRegistryLive),
424 // The instance registry is the new routing keystone — text generation,
425 // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
426 // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
427 // `providerInstances` hydration merges `settings.providers.<kind>`
428 // with explicit `providerInstances` entries on boot.
429 Layer.provideMerge(ProviderInstanceRegistryHydrationLive),
430 // Shared native/canonical NDJSON writers used by both the per-instance
431 // drivers (native stream, written from inside each `<X>Adapter`) and
432 // `ProviderService` (canonical stream, written after event normalization).
433 // Provided once at the runtime level so every consumer sees the same
434 // logger instances.
435 // `ModelManifest.layer` is the legacy-model classification data, refreshed
436 // from the repo's `model-manifest.json` on `main` and applied by the
437 // Codex/Claude drivers.
438 Layer.provideMerge(Layer.mergeAll(ProviderEventLoggers.layer, ModelManifest.layer)),
439 // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
440 // `ProviderRegistryLive` pulled `OpenCodeRuntimeLive` in for itself, but
441 // the rewritten registry reads snapshots off the instance registry and
442 // no longer transitively provides it. Exposing it at the runtime level
443 // keeps a single Live for all opencode consumers.
444 Layer.provideMerge(OpenCodeRuntime.OpenCodeRuntimeLive),
445 Layer.provideMerge(WorkspaceLayerLive),
446 Layer.provideMerge(ProjectFaviconResolverLayerLive),
447 Layer.provideMerge(RepositoryIdentityResolver.layer),
448 Layer.provideMerge(ServerEnvironmentLayerLive),
449 Layer.provideMerge(AuthLayerLive),
450 Layer.provideMerge(ServerSecretStore.layer),
451 Layer.provideMerge(
452 Layer.mergeAll(
453 CloudCliTokenManager.layer.pipe(
454 Layer.provide(ServerSecretStore.layer),
455 Layer.provide(ExternalLauncher.layer),
456 ),
457 CloudManagedEndpointRuntimeLive,
458 ),
459 ),
460);
461​
462const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe(
463 // Misc.
464 Layer.provideMerge(BackgroundLayerLive),
465 Layer.provideMerge(ResourceDiagnosticsLayerLive),
466 Layer.provideMerge(UsageLayerLive),
467 Layer.provideMerge(TraceDiagnostics.layer),
468 Layer.provideMerge(AnalyticsService.layer),
469 Layer.provideMerge(ExternalLauncher.layer),
470 Layer.provideMerge(RemoteOpenTargets.layer),
471 Layer.provideMerge(ServerLifecycleEvents.layer),
472 Layer.provide(NetService.layer),
473);
474​
475const commandReadinessLayer = HttpRouter.middleware(
476 (httpEffect) =>
477 Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>
478 startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),
479 ),
480 { global: true },
481);
482​
483export const makeRoutesLayer = Layer.mergeAll(
484 Layer.mergeAll(
485 HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
486 Layer.provide(authHttpApiLayer),
487 Layer.provide(connectHttpApiLayer),
488 Layer.provide(orchestrationHttpApiLayer),
489 Layer.provide(pullRequestHttpApiLayer),
490 Layer.provide(serverEnvironmentHttpApiLayer),
491 Layer.provide(environmentAuthenticatedAuthLayer),
492 ),
493 otlpTracesProxyRouteLayer,
494 assetRouteLayer,
495 attachmentUploadRouteLayer,
496 staticAndDevRouteLayer,
497 websocketRpcRouteLayer,
498 ),
499 McpHttpServer.layer.pipe(Layer.provide(McpSessionRegistry.layer)),
500).pipe(
501 // Both transports consume the same service instance, so caches single-flight across clients
502 // and mutations observed on WebSocket invalidate patches subsequently read over HTTP.
503 Layer.provide(PullRequestServiceLive),
504 Layer.provide(PreviewAutomationBroker.layer),
505 Layer.provide(ServerSelfUpdate.layer.pipe(Layer.provide(DesktopAppUpdateLayerLive))),
506 Layer.provide(commandReadinessLayer),
507 Layer.provide(browserApiCorsLayer),
508 Layer.provide(httpCompressionLayer),
509);
510​
511export const makeServerLayer = Layer.unwrap(
512 Effect.gen(function* () {
513 const config = yield* ServerConfig.ServerConfig;
514 const activation = yield* Deferred.make<void>();
515 const awaitActivation = Deferred.await(activation);
516 const activationLayer = Layer.succeed(ServerActivation, awaitActivation);
517 const runtimeStateParked = yield* Deferred.make<void>();
518 const tailscaleParked = yield* Deferred.make<void>();
519 const cloudLinkParked = yield* Deferred.make<void>();
520 const routesReady = yield* Deferred.make<void>();
521 const launcherLayer = ServiceLauncherClient.layer;
522​
523 yield* fixPath();
524​
525 const httpListeningLayer = Layer.effectDiscard(
526 Effect.gen(function* () {
527 yield* HttpServer.HttpServer;
528 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
529 yield* startup.markHttpListening;
530 }),
531 );
532 const runtimeStateLayer = Layer.effectDiscard(
533 Effect.acquireRelease(
534 Effect.gen(function* () {
535 yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);
536 yield* awaitActivation;
537 const server = yield* HttpServer.HttpServer;
538 const address = server.address;
539 if (typeof address === "string" || !("port" in address)) {
540 return;
541 }
542​
543 const state = yield* makePersistedServerRuntimeState({
544 config,
545 port: address.port,
546 });
547 yield* persistServerRuntimeState({
548 path: config.serverRuntimeStatePath,
549 state,
550 }).pipe(
551 Effect.catchCause((cause) =>
552 Effect.logWarning("Failed to persist server runtime state", { cause }),
553 ),
554 );
555 }),
556 () =>
557 clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(
558 Effect.catchCause((cause) =>
559 Effect.logWarning("Failed to clear server runtime state", { cause }),
560 ),
561 ),
562 ),
563 );
564 const tailscaleServeLayer = config.tailscaleServeEnabled
565 ? Layer.effectDiscard(
566 Effect.acquireRelease(
567 Effect.gen(function* () {
568 yield* Deferred.succeed(tailscaleParked, undefined).pipe(Effect.orDie);
569 yield* awaitActivation;
570 const server = yield* HttpServer.HttpServer;
571 const address = server.address;
572 if (typeof address === "string" || !("port" in address)) {
573 return null;
574 }
575​
576 const localPort = address.port;
577 return yield* ensureTailscaleServe({
578 localPort,
579 servePort: config.tailscaleServePort,
580 localHost: "127.0.0.1",
581 }).pipe(
582 Effect.as({ localPort, servePort: config.tailscaleServePort }),
583 Effect.tap(() =>
584 Effect.logInfo("Tailscale Serve configured", {
585 localPort,
586 servePort: config.tailscaleServePort,
587 }),
588 ),
589 Effect.catch((cause) =>
590 Effect.logWarning("Failed to configure Tailscale Serve", {
591 cause,
592 localPort,
593 servePort: config.tailscaleServePort,
594 }).pipe(Effect.as(null)),
595 ),
596 );
597 }),
598 (configured) =>
599 configured
600 ? disableTailscaleServe({ servePort: configured.servePort }).pipe(
601 Effect.tap(() =>
602 Effect.logInfo("Tailscale Serve disabled", {
603 servePort: configured.servePort,
604 }),
605 ),
606 Effect.catch((cause) =>
607 Effect.logWarning("Failed to disable Tailscale Serve", {
608 cause,
609 servePort: configured.servePort,
610 }),
611 ),
612 )
613 : Effect.void,
614 ),
615 )
616 : Layer.empty;
617 const cloudDesiredLinkReconcileLayer = Layer.effectDiscard(
618 Effect.gen(function* () {
619 if (!hasCloudPublicConfig) {
620 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
621 return;
622 }
623 const releaseManagedTunnel = releaseManagedTunnelOnShutdown().pipe(
624 Effect.timeout("10 seconds"),
625 Effect.tap((released) =>
626 released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
627 ),
628 Effect.catchCause((cause) =>
629 Effect.logWarning(
630 "Failed to release the managed tunnel on shutdown; the next link reuses it",
631 { cause },
632 ),
633 ),
634 Effect.asVoid,
635 );
636 // A launcher trial can be stopped before activation. The previous
637 // server is already gone, so the trial owns cleanup immediately; the
638 // pending-state check keeps the tunnel for normal commit or rollback,
639 // while the launcher's explicit-stop marker allows it to be released.
640 // Other runtimes wait for activation so a failed standby cannot tear
641 // down the active runtime's tunnel.
642 const cleanupBeforeActivation = yield* pendingServiceUpdateExists;
643 if (cleanupBeforeActivation) {
644 yield* Effect.addFinalizer(() => releaseManagedTunnel);
645 }
646 yield* forkParked(
647 Effect.gen(function* () {
648 if (!cleanupBeforeActivation) {
649 yield* Effect.addFinalizer(() => releaseManagedTunnel);
650 }
651 if (!(yield* CloudCliState.readCliDesiredCloudLink)) return;
652 const server = yield* HttpServer.HttpServer;
653 const address = server.address;
654 if (typeof address === "string" || !("port" in address)) return;
655 // No settling delay before the first attempt: routes are already
656 // serving by the time activation opens this gate (the startup
657 // sequence awaits routesReady), and the retry schedule below
658 // covers anything this sleep used to hedge against. Every
659 // millisecond here is dead time on the path to remote
660 // reachability after a restart.
661 yield* reconcileDesiredCloudLink(`http://127.0.0.1:${address.port}`).pipe(
662 Effect.retry({
663 while: (error) =>
664 error._tag !== "EnvironmentHttpBadRequestError" &&
665 error._tag !== "EnvironmentHttpUnauthorizedError" &&
666 error._tag !== "EnvironmentHttpConflictError",
667 schedule: Schedule.exponential("1 second").pipe(
668 Schedule.modifyDelay(({ duration }) =>
669 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
670 ),
671 Schedule.upTo({ duration: "10 minutes" }),
672 ),
673 }),
674 Effect.tap(() => Effect.logInfo("T3 Connect desired link reconciled on startup")),
675 Effect.catch((cause) =>
676 Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
677 cause,
678 }),
679 ),
680 );
681 }),
682 );
683 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
684 }),
685 );
686​
687 const runtimeServicesLive = ServerRuntimeStartup.layerWithOptions({
688 activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),
689 abort: (error) => Deferred.die(activation, error).pipe(Effect.asVoid),
690 awaitAuxiliaryParked: Effect.all(
691 [
692 Deferred.await(runtimeStateParked),
693 Deferred.await(cloudLinkParked),
694 Deferred.await(routesReady),
695 ...(config.tailscaleServeEnabled ? [Deferred.await(tailscaleParked)] : []),
696 ],
697 { concurrency: "unbounded" },
698 ).pipe(Effect.asVoid),
699 }).pipe(Layer.provideMerge(RuntimeDependenciesLive), Layer.provide(launcherLayer));
700​
701 const routesLayer = HttpRouter.serve(makeRoutesLayer.pipe(Layer.provide(launcherLayer)), {
702 disableLogger: !config.logWebSocketEvents,
703 routerConfig: HTTP_ROUTER_CONFIG,
704 }).pipe(Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)));
705 const serverApplicationLayer = Layer.mergeAll(
706 routesLayer,
707 httpListeningLayer,
708 runtimeStateLayer,
709 tailscaleServeLayer,
710 cloudDesiredLinkReconcileLayer,
711 );
712​
713 return serverApplicationLayer.pipe(
714 Layer.provideMerge(runtimeServicesLive),
715 Layer.provide(activationLayer),
716 Layer.provideMerge(serverRelayBrokerTracingLayer),
717 Layer.provideMerge(HttpServerLive),
718 Layer.provide(ApplicationObservabilityLive),
719 Layer.provideMerge(FetchHttpClient.layer),
720 // PR reads, Git operations, and WebSocket discovery share one process limiter.
721 Layer.provide(VcsProcess.layer),
722 Layer.provideMerge(PlatformServicesLive),
723 );
724 }),
725);
726​
727// The CLI supplies configuration.
728export const runServer = Layer.launch(makeServerLayer);