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