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 Effect from "effect/Effect";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as LogLevel from "effect/LogLevel";
14import * as Path from "effect/Path";
15import * as Schema from "effect/Schema";
16import type { CuaDriverMcpConfiguration } from "@t3tools/contracts";
17
18export const DEFAULT_PORT = 3773;
19
20export const RuntimeMode = Schema.Literals(["web", "desktop"]);
21export type RuntimeMode = typeof RuntimeMode.Type;
22
23export const StartupPresentation = Schema.Literals(["browser", "headless"]);
24export type StartupPresentation = typeof StartupPresentation.Type;
25
26/**
27 * ServerDerivedPaths - Derived paths from the base directory.
28 */
29export interface ServerDerivedPaths {
30 readonly stateDir: string;
31 readonly dbPath: string;
32 readonly keybindingsConfigPath: string;
33 readonly settingsPath: string;
34 readonly providerStatusCacheDir: string;
35 readonly worktreesDir: string;
36 readonly attachmentsDir: string;
37 readonly logsDir: string;
38 readonly serverLogPath: string;
39 readonly serverTracePath: string;
40 readonly providerLogsDir: string;
41 readonly providerEventLogPath: string;
42 readonly terminalLogsDir: string;
43 readonly anonymousIdPath: string;
44 readonly environmentIdPath: string;
45 readonly serverRuntimeStatePath: string;
46 readonly secretsDir: string;
47}
48
49export interface DeriveServerPathsOptions {
50 readonly baseDirIsExplicit?: boolean;
51}
52
53/**
54 * ServerConfig - Service tag for server runtime configuration.
55 */
56export class ServerConfig extends Context.Service<
57 ServerConfig,
58 ServerDerivedPaths & {
59 readonly logLevel: LogLevel.LogLevel;
60 readonly traceMinLevel: LogLevel.LogLevel;
61 readonly traceTimingEnabled: boolean;
62 readonly traceBatchWindowMs: number;
63 readonly traceMaxBytes: number;
64 readonly traceMaxFiles: number;
65 readonly otlpTracesUrl: string | undefined;
66 readonly otlpMetricsUrl: string | undefined;
67 readonly otlpExportIntervalMs: number;
68 readonly otlpServiceName: string;
69 readonly mode: RuntimeMode;
70 readonly port: number;
71 readonly host: string | undefined;
72 readonly cwd: string;
73 readonly baseDir: string;
74 readonly staticDir: string | undefined;
75 readonly devUrl: URL | undefined;
76 readonly devAllowedOrigins: ReadonlyArray<string>;
77 readonly noBrowser: boolean;
78 readonly startupPresentation: StartupPresentation;
79 readonly desktopBootstrapToken: string | undefined;
80 readonly desktopTelemetryFd?: number | undefined;
81 readonly desktopTelemetryControlFd?: number | undefined;
82 readonly resourceMonitorPath?: string | undefined;
83 readonly cuaDriverMcp?: CuaDriverMcpConfiguration | undefined;
84 readonly autoBootstrapProjectFromCwd: boolean;
85 readonly logWebSocketEvents: boolean;
86 readonly tailscaleServeEnabled: boolean;
87 readonly tailscaleServePort: number;
88 }
89>()("t3/config/ServerConfig") {
90 /** @deprecated Import and use `layerTest` from this module. */
91 static readonly layerTest = (
92 cwd: string,
93 baseDirOrPrefix: string | { readonly prefix: string },
94 ) => layerTest(cwd, baseDirOrPrefix);
95}
96
97export const make = (config: ServerConfig["Service"]) => ServerConfig.of(config);
98
99export const layer = (config: ServerConfig["Service"]) => Layer.succeed(ServerConfig, make(config));
100
101export const deriveServerPaths = Effect.fn(function* (
102 baseDir: ServerConfig["Service"]["baseDir"],
103 devUrl: ServerConfig["Service"]["devUrl"],
104 options: DeriveServerPathsOptions = {},
105): Effect.fn.Return<ServerDerivedPaths, never, Path.Path> {
106 const { join } = yield* Path.Path;
107 const stateDir = join(
108 baseDir,
109 devUrl !== undefined && !options.baseDirIsExplicit ? "dev" : "userdata",
110 );
111 const dbPath = join(stateDir, "state.sqlite");
112 const attachmentsDir = join(stateDir, "attachments");
113 const logsDir = join(stateDir, "logs");
114 const providerLogsDir = join(logsDir, "provider");
115 const providerStatusCacheDir = join(baseDir, "caches");
116 return {
117 stateDir,
118 dbPath,
119 keybindingsConfigPath: join(stateDir, "keybindings.json"),
120 settingsPath: join(stateDir, "settings.json"),
121 providerStatusCacheDir,
122 worktreesDir: join(baseDir, "worktrees"),
123 attachmentsDir,
124 logsDir,
125 serverLogPath: join(logsDir, "server.log"),
126 serverTracePath: join(logsDir, "server.trace.ndjson"),
127 providerLogsDir,
128 providerEventLogPath: join(providerLogsDir, "events.log"),
129 terminalLogsDir: join(logsDir, "terminals"),
130 anonymousIdPath: join(stateDir, "anonymous-id"),
131 environmentIdPath: join(stateDir, "environment-id"),
132 serverRuntimeStatePath: join(stateDir, "server-runtime.json"),
133 secretsDir: join(stateDir, "secrets"),
134 };
135});
136
137export const ensureServerDirectories = Effect.fn(function* (derivedPaths: ServerDerivedPaths) {
138 const fs = yield* FileSystem.FileSystem;
139 const path = yield* Path.Path;
140
141 yield* Effect.all(
142 [
143 fs.makeDirectory(derivedPaths.stateDir, { recursive: true }),
144 fs.makeDirectory(derivedPaths.logsDir, { recursive: true }),
145 fs.makeDirectory(derivedPaths.providerLogsDir, { recursive: true }),
146 fs.makeDirectory(derivedPaths.terminalLogsDir, { recursive: true }),
147 fs.makeDirectory(derivedPaths.attachmentsDir, { recursive: true }),
148 fs.makeDirectory(derivedPaths.worktreesDir, { recursive: true }),
149 fs.makeDirectory(path.dirname(derivedPaths.keybindingsConfigPath), { recursive: true }),
150 fs.makeDirectory(path.dirname(derivedPaths.settingsPath), { recursive: true }),
151 fs.makeDirectory(derivedPaths.providerStatusCacheDir, { recursive: true }),
152 fs.makeDirectory(path.dirname(derivedPaths.anonymousIdPath), { recursive: true }),
153 fs.makeDirectory(path.dirname(derivedPaths.serverRuntimeStatePath), { recursive: true }),
154 ],
155 { concurrency: "unbounded" },
156 );
157});
158
159const makeTest = Effect.fn("ServerConfig.makeTest")(function* (
160 cwd: string,
161 baseDirOrPrefix: string | { readonly prefix: string },
162) {
163 const devUrl = undefined;
164 const fs = yield* FileSystem.FileSystem;
165 const baseDir =
166 typeof baseDirOrPrefix === "string"
167 ? baseDirOrPrefix
168 : yield* fs.makeTempDirectoryScoped({ prefix: baseDirOrPrefix.prefix });
169 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
170 yield* ensureServerDirectories(derivedPaths);
171
172 return ServerConfig.of({
173 logLevel: "Error",
174 traceMinLevel: "Info",
175 traceTimingEnabled: true,
176 traceBatchWindowMs: 200,
177 traceMaxBytes: 10 * 1024 * 1024,
178 traceMaxFiles: 10,
179 otlpTracesUrl: undefined,
180 otlpMetricsUrl: undefined,
181 otlpExportIntervalMs: 10_000,
182 otlpServiceName: "t3-server",
183 cwd,
184 baseDir,
185 ...derivedPaths,
186 mode: "web",
187 autoBootstrapProjectFromCwd: false,
188 logWebSocketEvents: false,
189 tailscaleServeEnabled: false,
190 tailscaleServePort: 443,
191 port: 0,
192 host: undefined,
193 desktopBootstrapToken: undefined,
194 desktopTelemetryFd: undefined,
195 desktopTelemetryControlFd: undefined,
196 resourceMonitorPath: undefined,
197 cuaDriverMcp: undefined,
198 staticDir: undefined,
199 devUrl,
200 devAllowedOrigins: [],
201 noBrowser: false,
202 startupPresentation: "browser",
203 });
204});
205
206export const layerTest = (cwd: string, baseDirOrPrefix: string | { readonly prefix: string }) =>
207 Layer.effect(ServerConfig, makeTest(cwd, baseDirOrPrefix));
208
209export const resolveStaticDir = Effect.fn(function* () {
210 const { join, resolve } = yield* Path.Path;
211 const { exists } = yield* FileSystem.FileSystem;
212 const bundledClient = resolve(join(import.meta.dirname, "client"));
213 const bundledStat = yield* exists(join(bundledClient, "index.html")).pipe(
214 Effect.orElseSucceed(() => false),
215 );
216 if (bundledStat) {
217 return bundledClient;
218 }
219
220 const monorepoClient = resolve(join(import.meta.dirname, "../../web/dist"));
221 const monorepoStat = yield* exists(join(monorepoClient, "index.html")).pipe(
222 Effect.orElseSucceed(() => false),
223 );
224 if (monorepoStat) {
225 return monorepoClient;
226 }
227 return undefined;
228});