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 { DEFAULT_SIGNAL_EXPORT, type SignalExport } from "@t3tools/shared/observability";
21import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
22
23export const DEFAULT_PORT = 3773;
24
25export const RuntimeMode = Schema.Literals(["web", "desktop"]);
26export type RuntimeMode = typeof RuntimeMode.Type;
27
28export const StartupPresentation = Schema.Literals(["browser", "headless"]);
29export type StartupPresentation = typeof StartupPresentation.Type;
30
31/**
32 * ServerDerivedPaths - Derived paths from the base directory.
33 */
34export interface ServerDerivedPaths {
35 readonly stateDir: string;
36 readonly dbPath: string;
37 readonly keybindingsConfigPath: string;
38 readonly settingsPath: string;
39 /** Palettes this machine publishes for clients to follow, one file per theme. */
40 readonly environmentThemesDir: string;
41 readonly providerStatusCacheDir: string;
42 readonly worktreesDir: string;
43 readonly attachmentsDir: string;
44 /** Screenshots the agent asks the collaborative browser to keep for the user. */
45 readonly browserArtifactsDir: string;
46 readonly logsDir: 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 /**
77 * How each signal is exported. Read instead of a process-wide setting so
78 * the wire format, credential, and schedule travel with the endpoint they
79 * were configured beside.
80 */
81 readonly otlpTracesExport: SignalExport;
82 readonly otlpMetricsExport: SignalExport;
83 readonly otlpLogsExport: SignalExport;
84 readonly otelEnvironment: OtelEnvironment.OtelEnvironment;
85 readonly mode: RuntimeMode;
86 readonly port: number;
87 readonly host: string | undefined;
88 readonly cwd: string;
89 readonly baseDir: string;
90 readonly staticDir: string | undefined;
91 readonly devUrl: URL | undefined;
92 readonly devAuthToken?: Redacted.Redacted<string> | undefined;
93 readonly devAllowedOrigins: ReadonlyArray<string>;
94 readonly noBrowser: boolean;
95 readonly startupPresentation: StartupPresentation;
96 readonly desktopBootstrapToken: string | undefined;
97 readonly desktopTelemetryFd?: number | undefined;
98 readonly desktopTelemetryControlFd?: number | undefined;
99 readonly resourceMonitorPath?: string | undefined;
100 readonly autoBootstrapProjectFromCwd: boolean;
101 readonly logWebSocketEvents: boolean;
102 readonly tailscaleServeEnabled: boolean;
103 readonly tailscaleServePort: number;
104 }
105>()("t3/config/ServerConfig") {
106 /** @deprecated Import and use `layerTest` from this module. */
107 static readonly layerTest = (
108 cwd: string,
109 baseDirOrPrefix: string | { readonly prefix: string },
110 ) => layerTest(cwd, baseDirOrPrefix);
111}
112
113export const make = (config: ServerConfig["Service"]) => ServerConfig.of(config);
114
115/**
116 * Resource attributes shared by every OTLP exporter, so traces, metrics, and
117 * logs report the same service identity to the collector.
118 */
119export const otlpResource = (config: ServerConfig["Service"]) => ({
120 serviceName: "t3code-server",
121 attributes: {
122 "service.namespace": "t3code",
123 "service.runtime": "t3-server",
124 "service.mode": config.mode,
125 },
126});
127
128export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerConfig, make(config));
129
130export const deriveServerPaths = Effect.fn(function* (
131 baseDir: ServerConfig["Service"]["baseDir"],
132 devUrl: ServerConfig["Service"]["devUrl"],
133 options: DeriveServerPathsOptions = {},
134): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
135 const { join } = yield* Path.Path;
136 const stateDir = join(
137 baseDir,
138 devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
139 );
140 const dbPath = join(stateDir, "state.sqlite");
141 const attachmentsDir = join(stateDir, "attachments");
142 const logsDir = join(stateDir, "logs");
143 const providerLogsDir = join(logsDir, "provider");
144 const providerStatusCacheDir = join(baseDir, "caches");
145 return {
146 stateDir,
147 dbPath,
148 keybindingsConfigPath: join(stateDir, "keybindings.json"),
149 settingsPath: join(stateDir, "settings.json"),
150 environmentThemesDir: join(stateDir, "themes"),
151 providerStatusCacheDir,
152 worktreesDir: join(baseDir, "worktrees"),
153 attachmentsDir,
154 browserArtifactsDir: join(stateDir, "browser-artifacts"),
155 logsDir,
156 serverTracePath: join(logsDir, "server.trace.ndjson"),
157 providerLogsDir,
158 providerEventLogPath: join(providerLogsDir, "events.log"),
159 terminalLogsDir: join(logsDir, "terminals"),
160 anonymousIdPath: join(stateDir, "anonymous-id"),
161 environmentIdPath: join(stateDir, "environment-id"),
162 serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
163 secretsDir: join(stateDir, "secrets"),
164 };
165});
166
167export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
168 const fs = yield* FileSystem.FileSystem;
169 const path = yield* Path.Path;
170
171 yield* Effect.all(
172 [
173 fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
174 fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
175 fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
176 fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
177 fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
178 fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
179 fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
180 fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
181 fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
182 fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
183 fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
184 ],
185 { concurrency: "unbounded" },
186 );
187
188 const swept = sweepStalePendingAttachments({
189 attachmentsDir: derivedPaths.attachmentsDir,
190 nowMs: yield* Clock.currentTimeMillis,
191 });
192 if (swept.deleted > 0) {
193 yield* Effect.logInfo("Removed expired attachment uploads.", { deleted: swept.deleted });
194 }
195});
196
197const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
198 cwd: string,
199 baseDirOrPrefix: string | { readonly prefix: string },
200) {
201 const devUrl = undefined;
202 const fs = yield* FileSystem.FileSystem;
203 const baseDir =
204 typeof baseDirOrPrefix === "string"
205 ? baseDirOrPrefix
206 : yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
207 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
208 yield* ensureServerDirectories(derivedPaths);
209
210 return ServerConfig.of({
211 logLevel: "Error",
212 traceMinLevel: "Info",
213 traceTimingEnabled: true,
214 traceBatchWindowMs: 200,
215 traceMaxBytes: 10 * 1024 * 1024,
216 traceMaxFiles: 10,
217 otlpTracesUrl: undefined,
218 otlpMetricsUrl: undefined,
219 otlpLogsUrl: undefined,
220 otlpTracesExport: DEFAULT_SIGNAL_EXPORT,
221 otlpMetricsExport: DEFAULT_SIGNAL_EXPORT,
222 otlpLogsExport: DEFAULT_SIGNAL_EXPORT,
223 otelEnvironment: OtelEnvironment.none,
224 cwd,
225 baseDir,
226 ...derivedPaths,
227 mode: "web",
228 autoBootstrapProjectFromCwd: false,
229 logWebSocketEvents: false,
230 tailscaleServeEnabled: false,
231 tailscaleServePort: 443,
232 port: 0,
233 host: undefined,
234 desktopBootstrapToken: undefined,
235 desktopTelemetryFd: undefined,
236 desktopTelemetryControlFd: undefined,
237 resourceMonitorPath: undefined,
238 staticDir: undefined,
239 devUrl,
240 devAllowedOrigins: [],
241 noBrowser: false,
242 startupPresentation: "browser",
243 });
244});
245
246export const layerTest = (cwd: string, baseDirOrPrefix: string | { readonly prefix: string }) =>
247 Layer.effect(ServerConfig, makeTest(cwd, baseDirOrPrefix));
248
249export const resolveStaticDir = Effect.fn(function* () {
250 const { join, resolve } = yield* Path.Path;
251 const { exists } = yield* FileSystem.FileSystem;
252 const bundledClient = resolve(join(import.meta.dirname, "client"));
253 const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe(
254 Effect.orElseSucceed(() => false),
255 );
256 if (bundledStat) {
257 return bundledClient;
258 }
259
260 const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist"));
261 const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe(
262 Effect.orElseSucceed(() => false),
263 );
264 if (monorepoStat) {
265 return monorepoClient;
266 }
267 return undefined;
268});