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

server.ts

1,090 lines47.3 KB

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