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

server.ts

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