Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

server.ts

794 lines34.3 KB

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