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