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