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