Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

server.ts

979 lines43.0 KB

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