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 otlpExportIntervalMs: number;
76 readonly otlpServiceName: string;
77 readonly otlpHeaders: Readonly<Record<string, string>> | undefined;
78 readonly otlpProtocol: OtlpProtocol;
79 readonly mode: RuntimeMode;
80 readonly port: number;
81 readonly host: string | undefined;
82 readonly cwd: string;
83 readonly baseDir: string;
84 readonly staticDir: string | undefined;
85 readonly devUrl: URL | undefined;
86 readonly devAuthToken?: Redacted.Redacted<string> | undefined;
87 readonly devAllowedOrigins: ReadonlyArray<string>;
88 readonly noBrowser: boolean;
89 readonly startupPresentation: StartupPresentation;
90 readonly desktopBootstrapToken: string | undefined;
91 readonly desktopTelemetryFd?: number | undefined;
92 readonly desktopTelemetryControlFd?: number | undefined;
93 readonly resourceMonitorPath?: string | undefined;
94 readonly autoBootstrapProjectFromCwd: boolean;
95 readonly logWebSocketEvents: boolean;
96 readonly tailscaleServeEnabled: boolean;
97 readonly tailscaleServePort: number;
98 }
99>()("t3/config/ServerConfig") {
100 /** @deprecated Import and use `layerTest` from this module. */
101 static readonly layerTest = (
102 cwd: string,
103 baseDirOrPrefix: string | { readonly prefix: string },
104 ) => layerTest(cwd, baseDirOrPrefix);
105}
106
107export const make = (config: ServerConfig["Service"]) => ServerConfig.of(config);
108
109export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerConfig, make(config));
110
111export const deriveServerPaths = Effect.fn(function* (
112 baseDir: ServerConfig["Service"]["baseDir"],
113 devUrl: ServerConfig["Service"]["devUrl"],
114 options: DeriveServerPathsOptions = {},
115): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
116 const { join } = yield* Path.Path;
117 const stateDir = join(
118 baseDir,
119 devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
120 );
121 const dbPath = join(stateDir, "state.sqlite");
122 const attachmentsDir = join(stateDir, "attachments");
123 const logsDir = join(stateDir, "logs");
124 const providerLogsDir = join(logsDir, "provider");
125 const providerStatusCacheDir = join(baseDir, "caches");
126 return {
127 stateDir,
128 dbPath,
129 keybindingsConfigPath: join(stateDir, "keybindings.json"),
130 settingsPath: join(stateDir, "settings.json"),
131 environmentThemesDir: join(stateDir, "themes"),
132 providerStatusCacheDir,
133 worktreesDir: join(baseDir, "worktrees"),
134 attachmentsDir,
135 browserArtifactsDir: join(stateDir, "browser-artifacts"),
136 logsDir,
137 serverLogPath: join(logsDir, "server.log"),
138 serverTracePath: join(logsDir, "server.trace.ndjson"),
139 providerLogsDir,
140 providerEventLogPath: join(providerLogsDir, "events.log"),
141 terminalLogsDir: join(logsDir, "terminals"),
142 anonymousIdPath: join(stateDir, "anonymous-id"),
143 environmentIdPath: join(stateDir, "environment-id"),
144 serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
145 secretsDir: join(stateDir, "secrets"),
146 };
147});
148
149export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
150 const fs = yield* FileSystem.FileSystem;
151 const path = yield* Path.Path;
152
153 yield* Effect.all(
154 [
155 fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
156 fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
157 fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
158 fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
159 fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
160 fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
161 fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
162 fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
163 fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
164 fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
165 fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
166 ],
167 { concurrency: "unbounded" },
168 );
169
170 const swept = sweepStalePendingAttachments({
171 attachmentsDir: derivedPaths.attachmentsDir,
172 nowMs: yield* Clock.currentTimeMillis,
173 });
174 if (swept.deleted > 0) {
175 yield* Effect.logInfo("Removed expired attachment uploads.", { deleted: swept.deleted });
176 }
177});
178
179const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
180 cwd: string,
181 baseDirOrPrefix: string | { readonly prefix: string },
182) {
183 const devUrl = undefined;
184 const fs = yield* FileSystem.FileSystem;
185 const baseDir =
186 typeof baseDirOrPrefix === "string"
187 ? baseDirOrPrefix
188 : yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
189 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
190 yield* ensureServerDirectories(derivedPaths);
191
192 return ServerConfig.of({
193 logLevel: "Error",
194 traceMinLevel: "Info",
195 traceTimingEnabled: true,
196 traceBatchWindowMs: 200,
197 traceMaxBytes: 10 * 1024 * 1024,
198 traceMaxFiles: 10,
199 otlpTracesUrl: undefined,
200 otlpMetricsUrl: undefined,
201 otlpExportIntervalMs: 10_000,
202 otlpServiceName: "t3-server",
203 otlpHeaders: undefined,
204 otlpProtocol: "http/json",
205 cwd,
206 baseDir,
207 ...derivedPaths,
208 mode: "web",
209 autoBootstrapProjectFromCwd: false,
210 logWebSocketEvents: false,
211 tailscaleServeEnabled: false,
212 tailscaleServePort: 443,
213 port: 0,
214 host: undefined,
215 desktopBootstrapToken: undefined,
216 desktopTelemetryFd: undefined,
217 desktopTelemetryControlFd: undefined,
218 resourceMonitorPath: undefined,
219 staticDir: undefined,
220 devUrl,
221 devAllowedOrigins: [],
222 noBrowser: false,
223 startupPresentation: "browser",
224 });
225});
226
227export const layerTest = (cwd: string, baseDirOrPrefix: string | { readonly prefix: string }) =>
228 Layer.effect(ServerConfig, makeTest(cwd, baseDirOrPrefix));
229
230export const resolveStaticDir = Effect.fn(function* () {
231 const { join, resolve } = yield* Path.Path;
232 const { exists } = yield* FileSystem.FileSystem;
233 const bundledClient = resolve(join(import.meta.dirname, "client"));
234 const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe(
235 Effect.orElseSucceed(() => false),
236 );
237 if (bundledStat) {
238 return bundledClient;
239 }
240
241 const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist"));
242 const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe(
243 Effect.orElseSucceed(() => false),
244 );
245 if (monorepoStat) {
246 return monorepoClient;
247 }
248 return undefined;
249});