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