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