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

server.ts

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