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