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