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