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