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