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