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