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