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