Open History to see the last commit
1/**
2 * ServerConfig - Runtime configuration services.
3 *
4 * Defines process-level server configuration and networking helpers used by
5 * startup and runtime layers.
6 *
7 * @module ServerConfig
8 */
9import * as Context from "effect/Context";
10import * as Clock from "effect/Clock";
11import * as Effect from "effect/Effect";
12import * as FileSystem from "effect/FileSystem";
13import * as Layer from "effect/Layer";
14import * as LogLevel from "effect/LogLevel";
15import * as Path from "effect/Path";
16import type * as Redacted from "effect/Redacted";
17import * as Schema from "effect/Schema";
18
19import { sweepStalePendingAttachments } from "./attachmentStore.ts";
20import { OtlpProtocol } from "@t3tools/shared/observability";
21
22export const DEFAULT_PORT = 3773;
23
24export const RuntimeMode = Schema.Literals(["web", "desktop"]);
25export type RuntimeMode = typeof RuntimeMode.Type;
26
27export const StartupPresentation = Schema.Literals(["browser", "headless"]);
28export type StartupPresentation = typeof StartupPresentation.Type;
29
30/**
31 * ServerDerivedPaths - Derived paths from the base directory.
32 */
33export interface ServerDerivedPaths {
34 readonly stateDir: string;
35 readonly dbPath: string;
36 readonly keybindingsConfigPath: string;
37 readonly settingsPath: string;
38 /** Palettes this machine publishes for clients to follow, one file per theme. */
39 readonly environmentThemesDir: string;
40 readonly providerStatusCacheDir: string;
41 readonly worktreesDir: string;
42 readonly attachmentsDir: string;
43 /** Screenshots the agent asks the collaborative browser to keep for the user. */
44 readonly browserArtifactsDir: string;
45 readonly logsDir: string;
46 readonly serverLogPath: string;
47 readonly serverTracePath: string;
48 readonly providerLogsDir: string;
49 readonly providerEventLogPath: string;
50 readonly terminalLogsDir: string;
51 readonly anonymousIdPath: string;
52 readonly environmentIdPath: string;
53 readonly serverRuntimeStatePath: string;
54 readonly secretsDir: string;
55}
56
57export interface DeriveServerPathsOptions {
58 readonly baseDirIsExplicit?: boolean;
59}
60
61/**
62 * ServerConfig - Service tag for server runtime configuration.
63 */
64export class ServerConfig extends Context.Service<
65 ServerConfig,
66 ServerDerivedPaths & {
67 readonly logLevel: LogLevel.LogLevel;
68 readonly traceMinLevel: LogLevel.LogLevel;
69 readonly traceTimingEnabled: boolean;
70 readonly traceBatchWindowMs: number;
71 readonly traceMaxBytes: number;
72 readonly traceMaxFiles: number;
73 readonly otlpTracesUrl: string | undefined;
74 readonly otlpMetricsUrl: string | undefined;
75 readonly otlpLogsUrl: string | undefined;
76 readonly otlpExportIntervalMs: number;
77 readonly otlpServiceName: string;
78 readonly otlpHeaders: Readonly<Record<string, string>> | undefined;
79 readonly otlpProtocol: OtlpProtocol;
80 readonly mode: RuntimeMode;
81 readonly port: number;
82 readonly host: string | undefined;
83 readonly cwd: string;
84 readonly baseDir: string;
85 readonly staticDir: string | undefined;
86 readonly devUrl: URL | undefined;
87 readonly devAuthToken?: Redacted.Redacted<string> | undefined;
88 readonly devAllowedOrigins: ReadonlyArray<string>;
89 readonly noBrowser: boolean;
90 readonly startupPresentation: StartupPresentation;
91 readonly desktopBootstrapToken: string | undefined;
92 readonly desktopTelemetryFd?: number | undefined;
93 readonly desktopTelemetryControlFd?: number | undefined;
94 readonly resourceMonitorPath?: string | undefined;
95 readonly autoBootstrapProjectFromCwd: boolean;
96 readonly logWebSocketEvents: boolean;
97 readonly tailscaleServeEnabled: boolean;
98 readonly tailscaleServePort: number;
99 }
100>()("t3/config/ServerConfig") {
101 /** @deprecated Import and use `layerTest` from this module. */
102 static readonly layerTest = (
103 cwd: string,
104 baseDirOrPrefix: string | { readonly prefix: string },
105 ) => layerTest(cwd, baseDirOrPrefix);
106}
107
108export const make = (config: ServerConfig["Service"]) => ServerConfig.of(config);
109
110/**
111 * Resource attributes shared by every OTLP exporter, so traces, metrics, and
112 * logs report the same service identity to the collector.
113 */
114export const otlpResource = (config: ServerConfig["Service"]) => ({
115 serviceName: config.otlpServiceName,
116 attributes: {
117 "service.runtime": "t3-server",
118 "service.mode": config.mode,
119 },
120});
121
122export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerConfig, make(config));
123
124export const deriveServerPaths = Effect.fn(function* (
125 baseDir: ServerConfig["Service"]["baseDir"],
126 devUrl: ServerConfig["Service"]["devUrl"],
127 options: DeriveServerPathsOptions = {},
128): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
129 const { join } = yield* Path.Path;
130 const stateDir = join(
131 baseDir,
132 devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
133 );
134 const dbPath = join(stateDir, "state.sqlite");
135 const attachmentsDir = join(stateDir, "attachments");
136 const logsDir = join(stateDir, "logs");
137 const providerLogsDir = join(logsDir, "provider");
138 const providerStatusCacheDir = join(baseDir, "caches");
139 return {
140 stateDir,
141 dbPath,
142 keybindingsConfigPath: join(stateDir, "keybindings.json"),
143 settingsPath: join(stateDir, "settings.json"),
144 environmentThemesDir: join(stateDir, "themes"),
145 providerStatusCacheDir,
146 worktreesDir: join(baseDir, "worktrees"),
147 attachmentsDir,
148 browserArtifactsDir: join(stateDir, "browser-artifacts"),
149 logsDir,
150 serverLogPath: join(logsDir, "server.log"),
151 serverTracePath: join(logsDir, "server.trace.ndjson"),
152 providerLogsDir,
153 providerEventLogPath: join(providerLogsDir, "events.log"),
154 terminalLogsDir: join(logsDir, "terminals"),
155 anonymousIdPath: join(stateDir, "anonymous-id"),
156 environmentIdPath: join(stateDir, "environment-id"),
157 serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
158 secretsDir: join(stateDir, "secrets"),
159 };
160});
161
162export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
163 const fs = yield* FileSystem.FileSystem;
164 const path = yield* Path.Path;
165
166 yield* Effect.all(
167 [
168 fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
169 fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
170 fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
171 fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
172 fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
173 fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
174 fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
175 fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
176 fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
177 fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
178 fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
179 ],
180 { concurrency: "unbounded" },
181 );
182
183 const swept = sweepStalePendingAttachments({
184 attachmentsDir: derivedPaths.attachmentsDir,
185 nowMs: yield* Clock.currentTimeMillis,
186 });
187 if (swept.deleted > 0) {
188 yield* Effect.logInfo("Removed expired attachment uploads.", { deleted: swept.deleted });
189 }
190});
191
192const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
193 cwd: string,
194 baseDirOrPrefix: string | { readonly prefix: string },
195) {
196 const devUrl = undefined;
197 const fs = yield* FileSystem.FileSystem;
198 const baseDir =
199 typeof baseDirOrPrefix === "string"
200 ? baseDirOrPrefix
201 : yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
202 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
203 yield* ensureServerDirectories(derivedPaths);
204
205 return ServerConfig.of({
206 logLevel: "Error",
207 traceMinLevel: "Info",
208 traceTimingEnabled: true,
209 traceBatchWindowMs: 200,
210 traceMaxBytes: 10 * 1024 * 1024,
211 traceMaxFiles: 10,
212 otlpTracesUrl: undefined,
213 otlpMetricsUrl: undefined,
214 otlpLogsUrl: undefined,
215 otlpExportIntervalMs: 10_000,
216 otlpServiceName: "t3-server",
217 otlpHeaders: undefined,
218 otlpProtocol: "http/json",
219 cwd,
220 baseDir,
221 ...derivedPaths,
222 mode: "web",
223 autoBootstrapProjectFromCwd: false,
224 logWebSocketEvents: false,
225 tailscaleServeEnabled: false,
226 tailscaleServePort: 443,
227 port: 0,
228 host: undefined,
229 desktopBootstrapToken: undefined,
230 desktopTelemetryFd: undefined,
231 desktopTelemetryControlFd: undefined,
232 resourceMonitorPath: undefined,
233 staticDir: undefined,
234 devUrl,
235 devAllowedOrigins: [],
236 noBrowser: false,
237 startupPresentation: "browser",
238 });
239});
240
241export const layerTest = (cwd: string, baseDirOrPrefix: string | { readonly prefix: string }) =>
242 Layer.effect(ServerConfig, makeTest(cwd, baseDirOrPrefix));
243
244export const resolveStaticDir = Effect.fn(function* () {
245 const { join, resolve } = yield* Path.Path;
246 const { exists } = yield* FileSystem.FileSystem;
247 const bundledClient = resolve(join(import.meta.dirname, "client"));
248 const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe(
249 Effect.orElseSucceed(() => false),
250 );
251 if (bundledStat) {
252 return bundledClient;
253 }
254
255 const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist"));
256 const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe(
257 Effect.orElseSucceed(() => false),
258 );
259 if (monorepoStat) {
260 return monorepoClient;
261 }
262 return undefined;
263});