Open History to see the last commit
1import type { RelayManagedEndpointRuntimeConfig } from "@t3tools/contracts/relay";
2import * as Clock from "effect/Clock";
3import * as Random from "effect/Random";
4import * as Semaphore from "effect/Semaphore";
5import * as StorageCleanup from "./storageCleanup.ts";
6import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts";
7import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts";
8// @effect-diagnostics nodeBuiltinImport:off
9import * as NodeHttp from "node:http";
10
11import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
12import * as NodeServices from "@effect/platform-node/NodeServices";
13import { EnvironmentHttpApi, type RepositoryIdentity } from "@t3tools/contracts";
14import * as Cause from "effect/Cause";
15import * as Duration from "effect/Duration";
16import * as Deferred from "effect/Deferred";
17import * as Effect from "effect/Effect";
18import * as Option from "effect/Option";
19import * as Layer from "effect/Layer";
20import * as Stream from "effect/Stream";
21import * as Schedule from "effect/Schedule";
22import { FetchHttpClient, HttpRouter, HttpServer } from "effect/http";
23import * as HttpApiBuilder from "effect/http-api/HttpApiBuilder";
24
25import * as BackgroundPolicy from "./background/BackgroundPolicy.ts";
26import * as HostPowerMonitor from "./background/HostPowerMonitor.ts";
27import * as ServerConfig from "./config.ts";
28import { withUntracedRequests } from "./http.ts";
29import * as ServerHttp from "./http.ts";
30import { guardHttpResponseWriteErrors } from "./httpResponseErrorGuard.ts";
31import { fixPath } from "./os-jank.ts";
32import * as Ws from "./ws.ts";
33import * as ExternalLauncher from "./process/externalLauncher.ts";
34import * as NodePtyAdapter from "./terminal/NodePtyAdapter.ts";
35import * as PullRequestHttp from "./pullRequest/http.ts";
36import * as PullRequestProviderRegistry from "./pullRequest/PullRequestProviderRegistry.ts";
37import * as PullRequestService from "./pullRequest/PullRequestService.ts";
38import * as SqlitePersistence from "./persistence/Sqlite.ts";
39import * as PullRequestFilesViewed from "./persistence/PullRequestFilesViewed.ts";
40import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
41import * as AnalyticsService from "./telemetry/AnalyticsService.ts";
42import * as ProviderEventIngestor from "./orchestration-v2/ProviderEventIngestor.ts";
43import * as ModelManifest from "./provider/ModelManifest.ts";
44import * as ResetCreditCoordinator from "./provider/resetCreditCoordinator.ts";
45import * as ProviderEventLoggers from "./provider/ProviderEventLoggers.ts";
46import * as OpenCodeRuntime from "./provider/opencodeRuntime.ts";
47import * as OpenCodeServerLedger from "./provider/OpenCodeServerLedger.ts";
48import * as AcpRegistryCatalog from "./provider/AcpRegistryCatalog.ts";
49import * as CheckpointDiffQuery from "./checkpointing/CheckpointDiffQuery.ts";
50import * as CheckpointStore from "./checkpointing/CheckpointStore.ts";
51import * as AzureDevOpsCli from "./sourceControl/AzureDevOpsCli.ts";
52import * as BitbucketApi from "./sourceControl/BitbucketApi.ts";
53import * as GitHubCli from "./sourceControl/GitHubCli.ts";
54import * as GitLabCli from "./sourceControl/GitLabCli.ts";
55import * as ForgejoCli from "./sourceControl/ForgejoCli.ts";
56import * as TextGeneration from "./textGeneration/TextGeneration.ts";
57import * as ProviderInstanceRegistryHydration from "./provider/ProviderInstanceRegistryHydration.ts";
58import * as TerminalManager from "./terminal/Manager.ts";
59import * as McpHttpServer from "./mcp/McpHttpServer.ts";
60import * as McpSessionRegistry from "./mcp/McpSessionRegistry.ts";
61import * as PreviewAutomationBroker from "./mcp/PreviewAutomationBroker.ts";
62import * as DeviceService from "./device/DeviceService.ts";
63import * as DeviceHubProxy from "./device/DeviceHubProxy.ts";
64import * as PreviewManager from "./preview/Manager.ts";
65import * as PortScanner from "./preview/PortScanner.ts";
66import * as ProcessRunner from "./processRunner.ts";
67import * as GitManager from "./git/GitManager.ts";
68import * as EnvironmentTheme from "./environmentTheme.ts";
69import * as Keybindings from "./keybindings.ts";
70import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
71import * as AgentAwarenessRelay from "./relay/AgentAwarenessRelay.ts";
72import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
73import * as ServerSettings from "./serverSettings.ts";
74import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts";
75import * as NativeAppIconResolver from "./assets/NativeAppIconResolver.ts";
76import * as AntigravityInstallation from "./provider/AntigravityInstallation.ts";
77import * as CodexInstallation from "./provider/CodexInstallation.ts";
78import * as ProviderInstanceRegistry from "./provider/ProviderInstanceRegistry.ts";
79import * as ProviderAdapterRegistry from "./orchestration-v2/ProviderAdapterRegistry.ts";
80import * as ProviderRegistry from "./provider/ProviderRegistry.ts";
81import * as ProviderUsageLimitsIngestion from "./provider/ProviderUsageLimitsIngestion.ts";
82import * as UsageLimitSources from "./usage/UsageLimitSources.ts";
83import * as ProjectFaviconResolver from "./project/ProjectFaviconResolver.ts";
84import * as T3ProjectFileLoader from "./project/T3ProjectFileLoader.ts";
85import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
86import * as WorkspaceEntries from "./workspace/WorkspaceEntries.ts";
87import * as WorkspaceFileSystem from "./workspace/WorkspaceFileSystem.ts";
88import * as WorkspacePaths from "./workspace/WorkspacePaths.ts";
89import * as GitVcsDriver from "./vcs/GitVcsDriver.ts";
90import * as VcsDriverRegistry from "./vcs/VcsDriverRegistry.ts";
91import * as VcsProjectConfig from "./vcs/VcsProjectConfig.ts";
92import * as VcsProcess from "./vcs/VcsProcess.ts";
93import * as VcsProvisioningService from "./vcs/VcsProvisioningService.ts";
94import * as VcsStatusBroadcaster from "./vcs/VcsStatusBroadcaster.ts";
95import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts";
96import * as GitWorkflowService from "./git/GitWorkflowService.ts";
97import * as ReviewService from "./review/ReviewService.ts";
98import * as SourceControlProviderRegistry from "./sourceControl/SourceControlProviderRegistry.ts";
99import * as PullRequestReadCache from "./pullRequest/PullRequestReadCache.ts";
100import * as SourceControlRateLimit from "./sourceControl/SourceControlRateLimit.ts";
101import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
102import * as WorktreeSetupTracker from "./project/WorktreeSetupTracker.ts";
103import * as Observability from "./observability/Observability.ts";
104import * as HeapSnapshot from "./observability/HeapSnapshot.ts";
105import * as EventLoopMonitor from "./observability/EventLoopMonitor.ts";
106import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
107import * as DirectEndpoints from "./environment/DirectEndpoints.ts";
108import * as RemoteOpenTargets from "./environment/RemoteOpenTargets.ts";
109import * as AuthHttp from "./auth/http.ts";
110import * as ReplayMarkers from "./auth/replayMarkers.ts";
111import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
112import * as WebhookRoute from "./scheduledTasks/webhookRoute.ts";
113import * as RelayDeliveryProof from "./scheduledTasks/RelayDeliveryProof.ts";
114import * as HeldHooksWaker from "./relay/HeldHooksWaker.ts";
115import {
116 relayHookBaseUrl,
117 ScheduledTaskWebhookOrigin,
118} from "./scheduledTasks/ScheduledTaskService.ts";
119import {
120 CLOUD_ENDPOINT_RUNTIME_CONFIG,
121 decodeRuntimeConfig,
122 RELAY_URL_SECRET,
123} from "./cloud/config.ts";
124import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
125import * as CloudHttp from "./cloud/http.ts";
126import * as CloudLink from "./cloud/CloudLink.ts";
127import { pendingServiceUpdateExists } from "./cloud/updateHandoff.ts";
128import * as RelayTracing from "./cloud/relayTracing.ts";
129import * as CloudManagedEndpointRuntime from "./cloud/ManagedEndpointRuntime.ts";
130import {
131 MANAGED_TUNNEL_FIRST_REGISTRATION_JITTER,
132 MANAGED_TUNNEL_RECOVERY_COOLDOWN,
133 managedTunnelStartupAction,
134 retryManagedTunnelRegistration,
135} from "./cloud/managedTunnelStartup.ts";
136import * as CloudCliTokenManager from "./cloud/CliTokenManager.ts";
137import * as CloudCliState from "./cloud/CliState.ts";
138import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
139import * as DesktopAppUpdate from "./desktopUpdate/DesktopAppUpdate.ts";
140import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts";
141import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts";
142import * as HostResources from "./resourceTelemetry/HostResources.ts";
143import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts";
144import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts";
145import * as DesktopTelemetryReceiver from "./resourceTelemetry/DesktopTelemetryReceiver.ts";
146import * as NativeTelemetryClient from "./resourceTelemetry/NativeTelemetryClient.ts";
147import * as ResourceAttribution from "./resourceTelemetry/ResourceAttribution.ts";
148import * as ResourceMonitorBinary from "./resourceTelemetry/ResourceMonitorBinary.ts";
149import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts";
150import * as UsageService from "./usage/UsageService.ts";
151import * as RuntimeLayer from "./orchestration-v2/runtimeLayer.ts";
152import * as ProjectStore from "./orchestration-v2/ProjectStore.ts";
153import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts";
154import * as ResourceCleanupService from "./orchestration-v2/ResourceCleanupService.ts";
155import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts";
156import * as ThreadPullRequestService from "./orchestration-v2/ThreadPullRequestService.ts";
157import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts";
158import * as ProjectionStoreV2 from "./orchestration-v2/ProjectionStore.ts";
159import {
160 clearPersistedServerRuntimeState,
161 makePersistedServerRuntimeState,
162 persistServerRuntimeState,
163} from "./serverRuntimeState.ts";
164import * as OrchestrationHttp from "./orchestration-v2/http.ts";
165import * as ProjectHttp from "./project/http.ts";
166import * as NetService from "@t3tools/shared/Net";
167import * as RelayClient from "@t3tools/shared/relayClient";
168import { disableTailscaleServe, ensureTailscaleServe } from "@t3tools/tailscale";
169import * as ServerActivation from "./serverActivation.ts";
170
171// MCP handoff thread IDs include escaped provenance and can exceed find-my-way's
172// 100-character default for one path segment.
173const HTTP_ROUTER_CONFIG = {
174 maxParamLength: 512,
175} as const;
176
177// Effect's default preemptive shutdown waits 20s before finalizing request scopes.
178// T3's primary transport is long-lived WebSocket RPC, whose Effect scope finalizer
179// already closes the websocket gracefully. Do not add an artificial drain before
180// those finalizers get a chance to run.
181const HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS = 0;
182const layerResourceAttribution = ResourceAttribution.layer;
183const layerApplicationObservability = EventLoopMonitor.layer.pipe(
184 Layer.provideMerge(Observability.layer),
185 Layer.provideMerge(layerResourceAttribution),
186);
187
188const layerPtyAdapter = NodePtyAdapter.layer;
189
190const layerServerSettings = ServerSettings.layer.pipe(
191 Layer.provide(ServerSecretStore.layer),
192 Layer.provideMerge(SqlitePersistence.layerConfig),
193);
194
195const layerNativeTelemetry = NativeTelemetryClient.layer.pipe(
196 Layer.provide(ResourceMonitorBinary.layer),
197);
198const layerDesktopTelemetryReceiver = DesktopTelemetryReceiver.layer.pipe(
199 Layer.provideMerge(layerServerSettings),
200);
201
202const layerResourceTelemetry = ResourceTelemetry.layer.pipe(
203 Layer.provideMerge(layerNativeTelemetry),
204 Layer.provideMerge(layerDesktopTelemetryReceiver),
205);
206
207const layerHostPowerMonitor = HostPowerMonitor.layer.pipe(
208 Layer.provide(layerDesktopTelemetryReceiver),
209);
210
211// Reuses DesktopTelemetryReceiverLayerLive: a fresh receiver layer here
212// would open a second reader on the desktop telemetry fd.
213const layerDesktopAppUpdate = DesktopAppUpdate.layer.pipe(
214 Layer.provide(layerDesktopTelemetryReceiver),
215);
216
217const layerBackground = BackgroundPolicy.layer.pipe(
218 Layer.provide(layerHostPowerMonitor),
219 Layer.provideMerge(layerServerSettings),
220);
221
222const layerUsage = UsageService.layer.pipe(Layer.provide(layerServerSettings));
223
224const layerResourceDiagnostics = Layer.mergeAll(
225 HostResources.layer,
226 layerResourceTelemetry,
227 ProcessDiagnostics.layer.pipe(Layer.provide(layerResourceTelemetry)),
228 ProcessResourceMonitor.layer.pipe(Layer.provide(layerResourceTelemetry)),
229);
230
231const layerRelayClient = Layer.unwrap(
232 Effect.gen(function* () {
233 const config = yield* ServerConfig.ServerConfig;
234 return RelayClient.layerCloudflared({ baseDir: config.baseDir });
235 }),
236);
237
238const layerHttpServer = Layer.unwrap(
239 Effect.gen(function* () {
240 const config = yield* ServerConfig.ServerConfig;
241 return NodeHttpServer.layer(() => guardHttpResponseWriteErrors(NodeHttp.createServer()), {
242 host: config.host ?? "127.0.0.1",
243 port: config.port,
244 gracefulShutdownTimeout: HTTP_PREEMPTIVE_SHUTDOWN_GRACE_MS,
245 // Negotiate permessage-deflate with clients that offer it; clients
246 // that don't still get uncompressed frames on their connection.
247 // Context takeover stays enabled (ws default) so the compression
248 // window is shared across frames — that also makes small frames cheap
249 // to compress, so no size threshold is set (ws only honors
250 // `threshold` when context takeover is disabled).
251 websocket: { perMessageDeflate: true },
252 });
253 }),
254);
255
256const layerPlatformServices = NodeServices.layer;
257
258const layerPersistence = Layer.empty.pipe(Layer.provideMerge(SqlitePersistence.layerConfig));
259
260const layerVcsDriverRegistry = VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer));
261
262const layerSourceControlProviderRegistry = SourceControlProviderRegistry.layer.pipe(
263 Layer.provide(
264 Layer.mergeAll(
265 AzureDevOpsCli.layer,
266 BitbucketApi.layer,
267 GitHubCli.layer,
268 GitLabCli.layer,
269 ForgejoCli.layer,
270 ),
271 ),
272 Layer.provideMerge(GitVcsDriver.layer),
273 Layer.provideMerge(layerVcsDriverRegistry),
274);
275
276const layerRepositoryIdentityResolver = Layer.effect(
277 RepositoryIdentityResolver.RepositoryIdentityResolver,
278 Effect.gen(function* () {
279 const registry = yield* SourceControlProviderRegistry.SourceControlProviderRegistry;
280 return yield* RepositoryIdentityResolver.make({
281 refine: Effect.fn(function* (identity: RepositoryIdentity) {
282 const remote = ForgejoCli.parseForgejoRemote(identity.locator.remoteUrl);
283 if (
284 !remote ||
285 !identity.rootPath ||
286 (identity.provider !== undefined &&
287 identity.provider !== "unknown" &&
288 identity.provider !== "forgejo")
289 )
290 return identity;
291 const handle = yield* registry.resolveHandle({
292 cwd: identity.rootPath,
293 context: {
294 provider: { kind: "unknown", name: "Unknown", baseUrl: "" },
295 remoteName: identity.locator.remoteName,
296 remoteUrl: identity.locator.remoteUrl,
297 },
298 });
299 if (handle.context?.provider.kind !== "forgejo") return identity;
300 const baseUrl = handle.context.provider.baseUrl.replace(/\/+$/, "");
301 const basePath = new URL(baseUrl).pathname.replace(/^\/+|\/+$/g, "");
302 const path =
303 !remote.ssh && basePath && remote.path.startsWith(`${basePath}/`)
304 ? remote.path.slice(basePath.length + 1)
305 : remote.path;
306 return { ...identity, provider: "forgejo", webUrl: `${baseUrl}/${path}` };
307 }),
308 });
309 }),
310).pipe(Layer.provide(layerSourceControlProviderRegistry), Layer.provide(ProcessRunner.layer));
311
312const layerPullRequestService = PullRequestService.layer.pipe(
313 Layer.provide(PullRequestProviderRegistry.layer),
314 // Where the viewed-file marks live for a host that keeps none of its own.
315 Layer.provide(PullRequestFilesViewed.layer),
316 Layer.provide(PullRequestReadCache.layer),
317 Layer.provide(layerSourceControlProviderRegistry),
318 Layer.provide(SourceControlRateLimit.layer),
319);
320
321const layerGitManager = GitManager.layer.pipe(
322 // Per-project git settings resolve the acting thread's project.
323 Layer.provide(Layer.merge(ProjectionStoreV2.layer, ProjectStore.layer)),
324 Layer.provideMerge(RuntimeLayer.layerProjectSetupScriptRunner),
325 Layer.provideMerge(WorktreeSetupTracker.layer),
326 Layer.provideMerge(GitVcsDriver.layer),
327 Layer.provideMerge(layerSourceControlProviderRegistry),
328 Layer.provideMerge(TextGeneration.layer.pipe(Layer.provide(layerSourceControlProviderRegistry))),
329);
330
331const layerGit = Layer.empty.pipe(
332 Layer.provideMerge(layerGitManager),
333 Layer.provideMerge(GitVcsDriver.layer),
334);
335
336const layerGitWorkflow = GitWorkflowService.layer.pipe(
337 Layer.provideMerge(layerVcsDriverRegistry),
338 Layer.provideMerge(layerGit),
339);
340
341const layerSourceControlRepositoryService = SourceControlRepositoryService.layer.pipe(
342 Layer.provideMerge(GitVcsDriver.layer),
343 Layer.provideMerge(layerSourceControlProviderRegistry),
344);
345
346const layerProjectCloneTracker = ProjectCloneTracker.layer.pipe(
347 Layer.provide(layerSourceControlRepositoryService),
348);
349
350const layerReview = ReviewService.layer.pipe(
351 Layer.provideMerge(GitVcsDriver.layer),
352 Layer.provideMerge(layerVcsDriverRegistry),
353);
354
355const layerVcs = Layer.empty.pipe(
356 Layer.provideMerge(VcsProjectConfig.layer),
357 Layer.provideMerge(layerVcsDriverRegistry),
358 Layer.provideMerge(VcsProvisioningService.layer.pipe(Layer.provide(layerVcsDriverRegistry))),
359 Layer.provideMerge(layerGitWorkflow),
360 Layer.provideMerge(layerReview),
361 Layer.provideMerge(layerSourceControlRepositoryService),
362 Layer.provideMerge(layerProjectCloneTracker),
363 Layer.provideMerge(
364 VcsStatusBroadcaster.layer.pipe(
365 Layer.provide(layerGitWorkflow),
366 // Auto-pull reads the project row. The orchestration runtime also
367 // consumes the broadcaster (run finalization), so the policy cannot read
368 // the store from the runtime's output.
369 Layer.provide(
370 VcsStatusBroadcaster.layerAutoPullPolicy.pipe(Layer.provide(ProjectStore.layer)),
371 ),
372 ),
373 ),
374);
375
376const layerCheckpointStore = CheckpointStore.layer.pipe(Layer.provide(layerVcsDriverRegistry));
377
378const layerPortScanner = PortScanner.layer.pipe(Layer.provide(ProcessRunner.layer));
379
380const layerTerminal = TerminalManager.layer.pipe(
381 Layer.provide(layerPtyAdapter),
382 Layer.provide(layerPortScanner),
383 Layer.provide(layerNativeTelemetry),
384);
385
386const layerPreview = Layer.empty.pipe(
387 Layer.provideMerge(PreviewManager.layer),
388 Layer.provideMerge(layerPortScanner),
389);
390
391const layerDevice = DeviceService.layer.pipe(
392 Layer.provide(layerServerSettings),
393 Layer.provide(ProcessRunner.layer),
394 Layer.provide(NetService.layer),
395);
396
397const layerWorkspaceEntries = WorkspaceEntries.layer.pipe(Layer.provide(WorkspacePaths.layer));
398
399const layerWorkspaceFileSystem = WorkspaceFileSystem.layer.pipe(
400 Layer.provide(WorkspacePaths.layer),
401 Layer.provide(layerWorkspaceEntries),
402);
403
404const layerWorkspace = Layer.mergeAll(
405 WorkspacePaths.layer,
406 layerWorkspaceEntries,
407 layerWorkspaceFileSystem,
408);
409
410const layerProjectFaviconResolver = ProjectFaviconResolver.layer.pipe(
411 Layer.provide(WorkspacePaths.layer),
412 Layer.provide(T3ProjectFileLoader.layer),
413);
414
415const layerServerEnvironment = ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer));
416
417const layerAuth = EnvironmentAuth.layer.pipe(
418 Layer.provideMerge(layerPersistence),
419 Layer.provide(layerServerEnvironment),
420 Layer.provide(ServerSecretStore.layer),
421);
422
423const layerCloudManagedEndpointRuntime = Layer.mergeAll(
424 layerRelayClient,
425 CloudManagedEndpointRuntime.layer.pipe(
426 Layer.provide(ServerSecretStore.layer),
427 Layer.provide(layerRelayClient),
428 ),
429);
430
431// Webhook URLs go through the relay only when the managed tunnel it forwards
432// to is configured; otherwise clients show the environment-relative path.
433const layerScheduledTaskWebhookOrigin = Layer.effect(
434 ScheduledTaskWebhookOrigin,
435 Effect.gen(function* () {
436 const secrets = yield* ServerSecretStore.ServerSecretStore;
437 // The reference holds an effect so each read sees the current link state.
438 return Effect.gen(function* () {
439 const [relayUrl, tunnelConfig] = yield* Effect.all([
440 secrets.get(RELAY_URL_SECRET),
441 secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG),
442 ]).pipe(Effect.orElseSucceed(() => [Option.none(), Option.none()] as const));
443 if (Option.isNone(relayUrl) || Option.isNone(tunnelConfig)) {
444 return { relayHookBaseUrl: null };
445 }
446 const config = decodeRuntimeConfig(new TextDecoder().decode(tunnelConfig.value));
447 return {
448 relayHookBaseUrl: relayHookBaseUrl({
449 relayUrl: new TextDecoder().decode(relayUrl.value),
450 tunnelName: Option.isSome(config) ? config.value.tunnelName : undefined,
451 }),
452 };
453 });
454 }),
455);
456
457const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe(
458 Layer.provide(layerScheduledTaskWebhookOrigin),
459 Layer.provide(ProviderEventIngestor.layerAnalytics),
460 Layer.provide(layerCheckpointStore),
461 Layer.provide(layerGitWorkflow),
462 Layer.provide(ResourceCleanupService.layer),
463 Layer.provide(
464 RunFinalizationService.layerObserver.pipe(
465 Layer.provide(ProjectionStoreV2.layer),
466 Layer.provide(layerPullRequestService),
467 Layer.provide(RuntimeLayer.layerProjectService),
468 ),
469 ),
470);
471
472const layerOrchestrationApplication = CheckpointDiffQuery.layer.pipe(
473 Layer.provideMerge(layerCheckpointStore),
474 Layer.provideMerge(layerOrchestrationV2Runtime),
475);
476
477// Automatic thread settlement (#8600): a server-owned sweep evaluates
478// inactivity and merged pull requests, then settles through the orchestrator
479// so every client sees the same shelf.
480const layerThreadSettlementWorker = Layer.effectDiscard(
481 ThreadSettlementService.make.pipe(Effect.flatMap((service) => service.start())),
482).pipe(Layer.provide(layerPullRequestService), Layer.provide(ProjectionStoreV2.layer));
483
484const layerThreadPullRequestWorker = Layer.effectDiscard(
485 ThreadPullRequestService.make.pipe(Effect.flatMap((service) => service.start())),
486).pipe(Layer.provide(layerPullRequestService));
487
488const layerProviderInstallationRefresh = Layer.effectDiscard(
489 Effect.gen(function* () {
490 const antigravity = yield* AntigravityInstallation.AntigravityInstallation;
491 const codex = yield* CodexInstallation.CodexInstallation;
492 const instances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry;
493 const providers = yield* ProviderRegistry.ProviderRegistry;
494 yield* Stream.merge(
495 antigravity.changes.pipe(
496 Stream.changesWith((a, b) => a.installedVersion === b.installedVersion),
497 Stream.drop(1),
498 ),
499 codex.changes.pipe(
500 Stream.changesWith((a, b) => a.installedVersion === b.installedVersion),
501 Stream.drop(1),
502 ),
503 ).pipe(
504 Stream.runForEach((state) =>
505 instances.listInstances.pipe(
506 Effect.flatMap((entries) =>
507 Effect.forEach(
508 entries.filter((instance) => instance.driverKind === state.driver),
509 (instance) => providers.refreshInstance(instance.instanceId),
510 { discard: true },
511 ),
512 ),
513 ),
514 ),
515 Effect.forkScoped,
516 );
517 }),
518);
519
520const layerRuntimeCoreDependenciesBase = Layer.mergeAll(
521 AgentAwarenessRelay.layer,
522 // Asks T3 Connect to deliver webhooks it held while this environment was offline.
523 HeldHooksWaker.layer,
524 layerThreadSettlementWorker,
525 Layer.effectDiscard(StorageCleanup.make.pipe(Effect.flatMap((service) => service.start()))).pipe(
526 Layer.provide(ProjectionStoreV2.layer),
527 ),
528 layerThreadPullRequestWorker,
529 Layer.effectDiscard(
530 Effect.gen(function* () {
531 const service = yield* PullRequestSyncReactor.PullRequestSyncReactor;
532 yield* service.start();
533 }),
534 ).pipe(
535 Layer.provideMerge(PullRequestSyncReactor.layer),
536 Layer.provide(layerPullRequestService),
537 Layer.provide(ProjectionStoreV2.layer),
538 ),
539 Layer.effectDiscard(
540 Effect.gen(function* () {
541 const service = yield* PullRequestWatchReactor.PullRequestWatchReactor;
542 yield* service.start();
543 }),
544 ).pipe(
545 Layer.provide(PullRequestWatchReactor.layer),
546 Layer.provide(layerPullRequestService),
547 Layer.provide(ProjectionStoreV2.layer),
548 ),
549 // Subscribes to `account.rate-limits.updated` so usage bars track live
550 // telemetry instead of waiting for the next status probe.
551 ProviderUsageLimitsIngestion.layer,
552 layerProviderInstallationRefresh,
553 ReplayMarkers.layer,
554).pipe(
555 // Core Services
556 Layer.provideMerge(layerOrchestrationApplication),
557 Layer.provideMerge(RuntimeLayer.layerEventInfrastructure),
558 Layer.provideMerge(Layer.merge(ProjectStore.layer, ThreadSearch.layer)),
559 Layer.provideMerge(layerServerSettings),
560 // The asset route uses the registry's GitHub credential for private PR media.
561 Layer.provideMerge(layerSourceControlProviderRegistry),
562 Layer.provideMerge(GitHubCli.layer),
563 Layer.provideMerge(layerGit),
564 Layer.provideMerge(layerVcs),
565 Layer.provideMerge(Layer.mergeAll(layerTerminal, layerPreview, layerDevice)),
566 Layer.provideMerge(layerPersistence),
567 // Both read a user-owned file out of the state directory and stream changes
568 // to clients; neither depends on the other.
569 Layer.provideMerge(
570 Layer.mergeAll(Keybindings.layer, EnvironmentTheme.layer, UsageLimitSources.layer),
571 ),
572 Layer.provideMerge(ProviderRegistry.layer),
573 // The instance registry is the new routing keystone — text generation,
574 // adapter lookup, and runtime ingestion all resolve `ProviderInstanceId`
575 // through this layer. Built-in drivers come from `BUILT_IN_DRIVERS`;
576 // `providerInstances` hydration merges `settings.providers.<kind>`
577 // with explicit `providerInstances` entries on boot.
578 Layer.provideMerge(ProviderInstanceRegistryHydration.layer),
579 Layer.provideMerge(
580 Layer.mergeAll(
581 AntigravityInstallation.AntigravityInstallation.layer,
582 CodexInstallation.CodexInstallation.layer,
583 ),
584 ),
585);
586
587const layerRuntimeCoreDependencies = layerRuntimeCoreDependenciesBase.pipe(
588 Layer.provideMerge(layerPtyAdapter),
589 // Search, prepare, status inspection, and turn launch share one registry
590 // cache so every client and provider instance sees the same prepared agents.
591 Layer.provideMerge(AcpRegistryCatalog.layer.pipe(Layer.provide(layerServerSettings))),
592 // Shared native/canonical NDJSON writers used by both the per-instance
593 // V2 drivers and the orchestration runtime. Provide resource attribution so
594 // the rewritten telemetry pipeline can account for logical NDJSON writes.
595 // Provided once at the runtime level so every consumer sees the same
596 // logger instances.
597 // `ModelManifest.layer` is the legacy-model classification data, refreshed
598 // from the repo's `model-manifest.json` on `main` and applied by the
599 // Codex/Claude drivers.
600 Layer.provideMerge(
601 Layer.mergeAll(ProviderEventLoggers.layer, ModelManifest.layer, ResetCreditCoordinator.layer),
602 ),
603 // `OpenCodeDriver.create()` yields `OpenCodeRuntime`; previously the old
604 // `ProviderRegistry.layer` pulled `OpenCodeRuntimeLive` in for itself, but
605 // the rewritten registry reads snapshots off the instance registry and
606 // no longer transitively provides it. Exposing it at the runtime level
607 // keeps a single Live for all opencode consumers.
608 Layer.provideMerge(OpenCodeRuntime.layer.pipe(Layer.provide(OpenCodeServerLedger.layer))),
609 Layer.provideMerge(layerWorkspace),
610 Layer.provideMerge(ProjectEnrichmentService.layer),
611 Layer.provideMerge(Layer.mergeAll(NativeAppIconResolver.layer, layerProjectFaviconResolver)),
612 Layer.provideMerge(layerRepositoryIdentityResolver),
613 Layer.provideMerge(layerServerEnvironment),
614 Layer.provideMerge(layerAuth),
615 Layer.provideMerge(ServerSecretStore.layer),
616 Layer.provideMerge(
617 Layer.mergeAll(
618 CloudCliTokenManager.layer.pipe(
619 Layer.provide(ServerSecretStore.layer),
620 Layer.provide(ExternalLauncher.layer),
621 ),
622 layerCloudManagedEndpointRuntime,
623 ),
624 ),
625);
626
627const layerRuntimeDependencies = layerRuntimeCoreDependencies.pipe(
628 // Misc.
629 Layer.provideMerge(layerBackground),
630 Layer.provideMerge(layerResourceDiagnostics),
631 Layer.provideMerge(layerUsage),
632 Layer.provideMerge(TraceDiagnostics.layer),
633 Layer.provideMerge(AnalyticsService.layer),
634 Layer.provideMerge(ExternalLauncher.layer),
635 Layer.provideMerge(RemoteOpenTargets.layer),
636 Layer.provideMerge(DirectEndpoints.layer),
637 Layer.provideMerge(ServerLifecycleEvents.layer),
638 Layer.provide(NetService.layer),
639);
640
641const layerCommandReadiness = HttpRouter.middleware(
642 (httpEffect) =>
643 Effect.flatMap(ServerRuntimeStartup.ServerRuntimeStartup, (startup) =>
644 startup.awaitCommandReady.pipe(Effect.orDie, Effect.andThen(httpEffect)),
645 ),
646 { global: true },
647);
648
649const layerMakeRoutes = Layer.mergeAll(
650 Layer.mergeAll(
651 HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
652 Layer.provide(AuthHttp.layer),
653 Layer.provide(CloudHttp.layer),
654 Layer.provide(OrchestrationHttp.layer),
655 Layer.provide(PullRequestHttp.layer),
656 Layer.provide(ProjectHttp.layer),
657 Layer.provide(ServerHttp.layerServerEnvironmentHttpApi),
658 Layer.provide(WebhookRoute.layer.pipe(Layer.provide(RelayDeliveryProof.layer))),
659 Layer.provide(AuthHttp.layerAuthenticatedAuth),
660 ),
661 ServerHttp.layerOtlpTracesProxyRoute,
662 ServerHttp.layerAssetRoute,
663 ServerHttp.layerAttachmentUploadRoute,
664 DeviceHubProxy.layer,
665 ServerHttp.layerStaticAndDevRoute,
666 Ws.layer,
667 ),
668 // The MCP session registry is provided globally (shared with V2 provider
669 // sessions) rather than inline here. The orchestrator toolkit resolves
670 // delegation targets through the same live adapter facade the V2
671 // orchestrator uses, so MCP capability reporting can never drift from
672 // what dispatch can actually serve.
673 McpHttpServer.layer.pipe(
674 Layer.provide(ProviderAdapterRegistry.layerFromProviderInstanceRegistry),
675 ),
676).pipe(
677 // Both transports consume the same service instance, so caches single-flight across clients
678 // and mutations observed on WebSocket invalidate patches subsequently read over HTTP.
679 Layer.provide(layerPullRequestService),
680 Layer.provide(PreviewAutomationBroker.layer),
681 Layer.provide(ServerSelfUpdate.layer.pipe(Layer.provide(layerDesktopAppUpdate))),
682 Layer.provide(layerCommandReadiness),
683 Layer.provide(ServerHttp.layerBrowserApiCors),
684 Layer.provide(ServerHttp.layerHttpCompression),
685);
686
687const layerMakeServer = Layer.unwrap(
688 Effect.gen(function* () {
689 const config = yield* ServerConfig.ServerConfig;
690 const activation = yield* Deferred.make<void>();
691 const awaitActivation = Deferred.await(activation);
692 const layerActivation = Layer.succeed(ServerActivation.ServerActivation, awaitActivation);
693 const runtimeStateParked = yield* Deferred.make<void>();
694 const tailscaleParked = yield* Deferred.make<void>();
695 const cloudLinkParked = yield* Deferred.make<void>();
696 const routesReady = yield* Deferred.make<void>();
697 const layerLauncher = ServiceLauncherClient.layer;
698
699 yield* fixPath();
700
701 const layerHttpListening = Layer.effectDiscard(
702 Effect.gen(function* () {
703 yield* HttpServer.HttpServer;
704 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
705 yield* startup.markHttpListening;
706 }),
707 );
708 const layerRuntimeState = Layer.effectDiscard(
709 Effect.acquireRelease(
710 Effect.gen(function* () {
711 yield* Deferred.succeed(runtimeStateParked, undefined).pipe(Effect.orDie);
712 yield* awaitActivation;
713 const server = yield* HttpServer.HttpServer;
714 const address = server.address;
715 if (typeof address === "string" || !("port" in address)) {
716 return;
717 }
718
719 const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
720 const state = yield* makePersistedServerRuntimeState({
721 config,
722 port: address.port,
723 serviceManaged: launcher.managed,
724 });
725 yield* persistServerRuntimeState({
726 path: config.serverRuntimeStatePath,
727 state,
728 }).pipe(
729 Effect.catchCause((cause) =>
730 Effect.logWarning("Failed to persist server runtime state", { cause }),
731 ),
732 );
733 }),
734 () =>
735 clearPersistedServerRuntimeState(config.serverRuntimeStatePath).pipe(
736 Effect.catchCause((cause) =>
737 Effect.logWarning("Failed to clear server runtime state", { cause }),
738 ),
739 ),
740 ),
741 );
742 const layerTailscaleServe = config.tailscaleServeEnabled
743 ? Layer.effectDiscard(
744 Effect.acquireRelease(
745 Effect.gen(function* () {
746 yield* Deferred.succeed(tailscaleParked, undefined).pipe(Effect.orDie);
747 yield* awaitActivation;
748 const server = yield* HttpServer.HttpServer;
749 const address = server.address;
750 if (typeof address === "string" || !("port" in address)) {
751 return null;
752 }
753
754 const localPort = address.port;
755 return yield* ensureTailscaleServe({
756 localPort,
757 servePort: config.tailscaleServePort,
758 localHost: "127.0.0.1",
759 }).pipe(
760 Effect.as({ localPort, servePort: config.tailscaleServePort }),
761 Effect.tap(() =>
762 Effect.logInfo("Tailscale Serve configured", {
763 localPort,
764 servePort: config.tailscaleServePort,
765 }),
766 ),
767 Effect.catch((cause) =>
768 Effect.logWarning("Failed to configure Tailscale Serve", {
769 cause,
770 localPort,
771 servePort: config.tailscaleServePort,
772 }).pipe(Effect.as(null)),
773 ),
774 );
775 }),
776 (configured) =>
777 configured
778 ? disableTailscaleServe({ servePort: configured.servePort }).pipe(
779 Effect.tap(() =>
780 Effect.logInfo("Tailscale Serve disabled", {
781 servePort: configured.servePort,
782 }),
783 ),
784 Effect.catch((cause) =>
785 Effect.logWarning("Failed to disable Tailscale Serve", {
786 cause,
787 servePort: configured.servePort,
788 }),
789 ),
790 )
791 : Effect.void,
792 ),
793 )
794 : Layer.empty;
795 const layerCloudDesiredLinkReconcile = Layer.effectDiscard(
796 Effect.gen(function* () {
797 const cloudLink = yield* CloudLink.CloudLink;
798 const releaseManagedTunnel = cloudLink.releaseManagedTunnelOnShutdown().pipe(
799 Effect.timeout("10 seconds"),
800 Effect.tap((released) =>
801 released ? Effect.logInfo("Released the managed tunnel on shutdown") : Effect.void,
802 ),
803 Effect.catchCause((cause) =>
804 Effect.logWarning(
805 "Failed to release the managed tunnel on shutdown; the next link reuses it",
806 { errors: Cause.prettyErrors(cause).map((error) => error.message) },
807 ),
808 ),
809 Effect.asVoid,
810 );
811 // A launcher trial can be stopped before activation. The previous
812 // server is already gone, so the trial owns cleanup immediately; the
813 // pending-state check keeps the tunnel for normal commit or rollback,
814 // while the launcher's explicit-stop marker allows it to be released.
815 // Other runtimes wait for activation so a failed standby cannot tear
816 // down the active runtime's tunnel.
817 const cleanupBeforeActivation = yield* pendingServiceUpdateExists;
818 if (cleanupBeforeActivation) {
819 yield* Effect.addFinalizer(() => releaseManagedTunnel);
820 }
821 yield* ServerActivation.forkParked(
822 Effect.gen(function* () {
823 if (!cleanupBeforeActivation) {
824 yield* Effect.addFinalizer(() => releaseManagedTunnel);
825 }
826 const server = yield* HttpServer.HttpServer;
827 const address = server.address;
828 if (typeof address === "string" || !("port" in address)) return;
829 const localOrigin = `http://127.0.0.1:${address.port}`;
830 const endpointRuntime = yield* CloudManagedEndpointRuntime.CloudManagedEndpointRuntime;
831 const recoveryLock = yield* Semaphore.make(1);
832 let lastRecoveryAtMillis = 0;
833 const recoverManagedTunnel = (config: RelayManagedEndpointRuntimeConfig) =>
834 recoveryLock.withPermits(1)(
835 Effect.gen(function* () {
836 const elapsed = (yield* Clock.currentTimeMillis) - lastRecoveryAtMillis;
837 const wait = Duration.toMillis(MANAGED_TUNNEL_RECOVERY_COOLDOWN) - elapsed;
838 if (wait > 0) yield* Effect.sleep(Duration.millis(wait));
839 lastRecoveryAtMillis = yield* Clock.currentTimeMillis;
840 }).pipe(
841 Effect.andThen(
842 cloudLink.recoverManagedTunnel(localOrigin, config, {
843 retryRuntimeFailures: true,
844 }),
845 ),
846 Effect.retry({
847 while: (error) =>
848 CloudLink.shouldRetryCloudLink(error) &&
849 error._tag !== "CloudLinkEndpointUnavailableError",
850 schedule: Schedule.exponential("1 second").pipe(
851 Schedule.modifyDelay(({ duration }) =>
852 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
853 ),
854 Schedule.jittered,
855 ),
856 }),
857 Effect.tap((recovered) =>
858 recovered ? Effect.logInfo("T3 Connect managed tunnel recovered") : Effect.void,
859 ),
860 Effect.catchCause((cause) =>
861 Cause.hasInterrupts(cause)
862 ? Effect.interrupt
863 : Effect.logWarning("Failed to recover the T3 Connect managed tunnel", {
864 cause,
865 }),
866 ),
867 ),
868 );
869 yield* endpointRuntime.recoveryRequests.pipe(
870 Stream.runForEach(recoverManagedTunnel),
871 Effect.forkScoped,
872 );
873 // No settling delay before the first attempt: routes are already
874 // serving by the time activation opens this gate (the startup
875 // sequence awaits routesReady), and the retry schedule below
876 // covers anything this sleep used to hedge against. Every
877 // millisecond here is dead time on the path to remote
878 // reachability after a restart.
879 const wantsCliLink = hasCloudPublicConfig
880 ? yield* CloudCliState.readCliDesiredCloudLink.pipe(
881 Effect.catch((cause) =>
882 Effect.logWarning("Failed to read the desired T3 Connect link", { cause }).pipe(
883 Effect.as(false),
884 ),
885 ),
886 )
887 : false;
888 // A failed read must not end this fiber before it registers
889 // recovery and starts consuming recovery requests. "managed" is
890 // what a missing value means, so it is the safe fallback.
891 const desiredCliLinkMode = wantsCliLink
892 ? yield* CloudCliState.readCliDesiredLinkMode.pipe(
893 Effect.catch((cause) =>
894 Effect.logWarning("Failed to read the desired T3 Connect link mode", {
895 cause,
896 }).pipe(Effect.as("managed" as const)),
897 ),
898 )
899 : null;
900 // A publish-only link must not expose the host, even if a managed
901 // config from an earlier link is still stored.
902 const startedConfirmed =
903 desiredCliLinkMode === "publish_only"
904 ? false
905 : yield* cloudLink.startManagedTunnelIfOriginConfirmed(localOrigin).pipe(
906 Effect.catch((cause) =>
907 Effect.logWarning("Failed to start the confirmed T3 Connect tunnel", {
908 cause,
909 }).pipe(Effect.as(false)),
910 ),
911 );
912 const startStoredManagedTunnel = cloudLink
913 .startManagedTunnelIfOriginConfirmed(localOrigin, {
914 requireConfirmedOrigin: false,
915 })
916 .pipe(
917 Effect.tap((started) =>
918 started
919 ? Effect.logWarning(
920 "T3 Connect started the stored tunnel without relay confirmation",
921 )
922 : Effect.void,
923 ),
924 Effect.catch((cause) =>
925 Effect.logWarning("Failed to start the stored T3 Connect tunnel", { cause }),
926 ),
927 Effect.asVoid,
928 );
929 const registerManagedTunnel = retryManagedTunnelRegistration(
930 cloudLink.registerManagedTunnelRecovery(localOrigin, {
931 retryRuntimeFailures: true,
932 }),
933 (error) =>
934 CloudLink.shouldRetryCloudLink(error) &&
935 error._tag !== "CloudLinkEndpointUnavailableError",
936 startedConfirmed ? Effect.void : startStoredManagedTunnel,
937 ).pipe(
938 Effect.tap((result) =>
939 result.status === "ready"
940 ? Effect.logInfo("T3 Connect managed tunnel recovery registered")
941 : Effect.void,
942 ),
943 Effect.catchCause((cause) =>
944 Cause.hasInterrupts(cause)
945 ? Effect.interrupt
946 : Effect.logWarning("Failed to register T3 Connect managed tunnel recovery", {
947 cause,
948 }).pipe(Effect.as({ status: "unavailable" as const })),
949 ),
950 );
951 // A host without a confirmed marker is on its first boot after the
952 // upgrade. Spread those registrations so an auto-update wave does
953 // not hit the relay all at once.
954 if (!startedConfirmed && desiredCliLinkMode !== "publish_only") {
955 const jitter = yield* Random.nextIntBetween(
956 0,
957 Duration.toMillis(MANAGED_TUNNEL_FIRST_REGISTRATION_JITTER),
958 );
959 yield* Effect.sleep(Duration.millis(jitter));
960 }
961 const registration =
962 desiredCliLinkMode === "publish_only"
963 ? { status: "not_linked" as const }
964 : yield* registerManagedTunnel;
965 // A terminal registration failure also allows the stored config
966 // to start. Transient outages use the fallback above and keep
967 // registration retrying in this scoped startup fiber.
968 if (registration.status === "unavailable" && !startedConfirmed) {
969 yield* startStoredManagedTunnel;
970 }
971 const startupAction = managedTunnelStartupAction({ wantsCliLink, registration });
972 if (startupAction.action === "request_recovery") {
973 yield* endpointRuntime.requestRecovery(startupAction.config);
974 }
975 if (startupAction.action === "reconcile_link") {
976 const reconciledMode = yield* cloudLink
977 .reconcileDesiredLinkIfStillDesired(localOrigin)
978 .pipe(
979 Effect.retry({
980 while: CloudLink.shouldRetryCloudLink,
981 schedule: Schedule.exponential("1 second").pipe(
982 Schedule.modifyDelay(({ duration }) =>
983 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
984 ),
985 Schedule.upTo({ duration: "10 minutes" }),
986 ),
987 }),
988 Effect.tap((mode) =>
989 mode === null
990 ? Effect.void
991 : Effect.logInfo("T3 Connect desired link reconciled on startup"),
992 ),
993 Effect.catch((cause) =>
994 Effect.logWarning("Failed to reconcile T3 Connect desired link on startup", {
995 cause,
996 }).pipe(Effect.as(null)),
997 ),
998 );
999 if (reconciledMode === "managed") {
1000 const afterReconcile = yield* registerManagedTunnel;
1001 if (afterReconcile.status === "recovery_required") {
1002 yield* endpointRuntime.requestRecovery(afterReconcile.config);
1003 }
1004 }
1005 }
1006 }),
1007 );
1008 yield* Deferred.succeed(cloudLinkParked, undefined).pipe(Effect.orDie);
1009 }),
1010 );
1011
1012 const layerRuntimeServices = ServerRuntimeStartup.layerWithOptions({
1013 activate: Deferred.succeed(activation, undefined).pipe(Effect.asVoid),
1014 abort: (error) => Deferred.die(activation, error).pipe(Effect.asVoid),
1015 awaitAuxiliaryParked: Effect.all(
1016 [
1017 Deferred.await(runtimeStateParked),
1018 Deferred.await(cloudLinkParked),
1019 Deferred.await(routesReady),
1020 ...(config.tailscaleServeEnabled ? [Deferred.await(tailscaleParked)] : []),
1021 ],
1022 { concurrency: "unbounded" },
1023 ).pipe(Effect.asVoid),
1024 }).pipe(Layer.provideMerge(layerRuntimeDependencies), Layer.provide(layerLauncher));
1025
1026 const layerRoutes = HttpRouter.serve(layerMakeRoutes.pipe(Layer.provide(layerLauncher)), {
1027 disableLogger: !config.logWebSocketEvents,
1028 routerConfig: HTTP_ROUTER_CONFIG,
1029 }).pipe(
1030 withUntracedRequests,
1031 Layer.tap(() => Deferred.succeed(routesReady, undefined).pipe(Effect.orDie)),
1032 );
1033 const layerServerApplication = Layer.mergeAll(
1034 layerRoutes,
1035 layerHttpListening,
1036 layerRuntimeState.pipe(Layer.provide(layerLauncher)),
1037 layerTailscaleServe,
1038 layerCloudDesiredLinkReconcile,
1039 HeapSnapshot.layer,
1040 );
1041
1042 return layerServerApplication.pipe(
1043 // The connect routes and the startup/shutdown link work share one instance.
1044 Layer.provide(CloudLink.layer),
1045 Layer.provideMerge(layerRuntimeServices),
1046 Layer.provideMerge(
1047 McpSessionRegistry.layer.pipe(
1048 Layer.provide(ServerEnvironment.layer.pipe(Layer.provide(ServerSecretStore.layer))),
1049 ),
1050 ),
1051 Layer.provide(layerActivation),
1052 Layer.provideMerge(RelayTracing.layerServerRelayBroker),
1053 Layer.provideMerge(layerHttpServer),
1054 Layer.provide(layerApplicationObservability),
1055 Layer.provideMerge(FetchHttpClient.layer),
1056 // PR reads, Git operations, and WebSocket discovery share one process limiter.
1057 Layer.provide(VcsProcess.layer),
1058 Layer.provideMerge(layerPlatformServices),
1059 );
1060 }),
1061);
1062
1063// The CLI supplies configuration.
1064export const runServer = Layer.launch(layerMakeServer);