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