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