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

server.ts

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