Open History to see the last commit
1/**
2 * CliConfig - CLI/runtime bootstrap service definitions.
3 *
4 * Defines startup-only service contracts used while resolving process config
5 * and constructing server runtime layers.
6 *
7 * @module CliConfig
8 */
9import { Config, Data, Effect, FileSystem, Layer, Option, Path, Schema, ServiceMap } from "effect";
10import { Command, Flag } from "effect/unstable/cli";
11import { NetService } from "@t3tools/shared/Net";
12import {
13 DEFAULT_PORT,
14 resolveStaticDir,
15 ServerConfig,
16 type RuntimeMode,
17 type ServerConfigShape,
18} from "./config";
19import { fixPath, resolveStateDir } from "./os-jank";
20import { Open } from "./open";
21import * as SqlitePersistence from "./persistence/Layers/Sqlite";
22import { makeServerProviderLayer, makeServerRuntimeServicesLayer } from "./serverLayers";
23import { ProjectionSnapshotQuery } from "./orchestration/Services/ProjectionSnapshotQuery";
24import { ProviderHealthLive } from "./provider/Layers/ProviderHealth";
25import { Server } from "./wsServer";
26import { ServerLoggerLive } from "./serverLogger";
27import { AnalyticsServiceLayerLive } from "./telemetry/Layers/AnalyticsService";
28import { AnalyticsService } from "./telemetry/Services/AnalyticsService";
29
30export class StartupError extends Data.TaggedError("StartupError")<{
31 readonly message: string;
32 readonly cause?: unknown;
33}> {}
34
35interface CliInput {
36 readonly mode: Option.Option<RuntimeMode>;
37 readonly port: Option.Option<number>;
38 readonly host: Option.Option<string>;
39 readonly stateDir: Option.Option<string>;
40 readonly devUrl: Option.Option<URL>;
41 readonly noBrowser: Option.Option<boolean>;
42 readonly authToken: Option.Option<string>;
43 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
44 readonly logWebSocketEvents: Option.Option<boolean>;
45}
46
47/**
48 * CliConfigShape - Startup helpers required while building server layers.
49 */
50export interface CliConfigShape {
51 /**
52 * Current process working directory.
53 */
54 readonly cwd: string;
55
56 /**
57 * Apply OS-specific PATH normalization.
58 */
59 readonly fixPath: Effect.Effect<void>;
60
61 /**
62 * Resolve static web asset directory for server mode.
63 */
64 readonly resolveStaticDir: Effect.Effect<string | undefined>;
65}
66
67/**
68 * CliConfig - Service tag for startup CLI/runtime helpers.
69 */
70export class CliConfig extends ServiceMap.Service<CliConfig, CliConfigShape>()(
71 "t3/main/CliConfig",
72) {
73 static readonly layer = Layer.effect(
74 CliConfig,
75 Effect.gen(function* () {
76 const fileSystem = yield* FileSystem.FileSystem;
77 const path = yield* Path.Path;
78 return {
79 cwd: process.cwd(),
80 fixPath: Effect.sync(fixPath),
81 resolveStaticDir: resolveStaticDir().pipe(
82 Effect.provideService(FileSystem.FileSystem, fileSystem),
83 Effect.provideService(Path.Path, path),
84 ),
85 } satisfies CliConfigShape;
86 }),
87 );
88}
89
90const CliEnvConfig = Config.all({
91 mode: Config.string("T3CODE_MODE").pipe(
92 Config.option,
93 Config.map(
94 Option.match<RuntimeMode, string>({
95 onNone: () => "web",
96 onSome: (value) => (value === "desktop" ? "desktop" : "web"),
97 }),
98 ),
99 ),
100 port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
101 host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
102 stateDir: Config.string("T3CODE_STATE_DIR").pipe(
103 Config.option,
104 Config.map(Option.getOrUndefined),
105 ),
106 devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
107 noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
108 Config.option,
109 Config.map(Option.getOrUndefined),
110 ),
111 authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
112 Config.option,
113 Config.map(Option.getOrUndefined),
114 ),
115 autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
116 Config.option,
117 Config.map(Option.getOrUndefined),
118 ),
119 logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
120 Config.option,
121 Config.map(Option.getOrUndefined),
122 ),
123});
124
125const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
126 Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
127
128const ServerConfigLive = (input: CliInput) =>
129 Layer.effect(
130 ServerConfig,
131 Effect.gen(function* () {
132 const cliConfig = yield* CliConfig;
133 const { findAvailablePort } = yield* NetService;
134 const env = yield* CliEnvConfig.asEffect().pipe(
135 Effect.mapError(
136 (cause) =>
137 new StartupError({ message: "Failed to read environment configuration", cause }),
138 ),
139 );
140
141 const mode = Option.getOrElse(input.mode, () => env.mode);
142
143 const port = yield* Option.match(input.port, {
144 onSome: (value) => Effect.succeed(value),
145 onNone: () => {
146 if (env.port) {
147 return Effect.succeed(env.port);
148 }
149 if (mode === "desktop") {
150 return Effect.succeed(DEFAULT_PORT);
151 }
152 return findAvailablePort(DEFAULT_PORT);
153 },
154 });
155 const stateDir = yield* resolveStateDir(
156 Option.getOrUndefined(input.stateDir) ?? env.stateDir,
157 );
158 const devUrl = Option.getOrElse(input.devUrl, () => env.devUrl);
159 const noBrowser = resolveBooleanFlag(input.noBrowser, env.noBrowser ?? mode === "desktop");
160 const authToken = Option.getOrUndefined(input.authToken) ?? env.authToken;
161 const autoBootstrapProjectFromCwd = resolveBooleanFlag(
162 input.autoBootstrapProjectFromCwd,
163 env.autoBootstrapProjectFromCwd ?? mode === "web",
164 );
165 const logWebSocketEvents = resolveBooleanFlag(
166 input.logWebSocketEvents,
167 env.logWebSocketEvents ?? Boolean(devUrl),
168 );
169 const staticDir = devUrl ? undefined : yield* cliConfig.resolveStaticDir;
170 const { join } = yield* Path.Path;
171 const keybindingsConfigPath = join(stateDir, "keybindings.json");
172 const appearanceConfigPath = join(stateDir, "appearance.json");
173 const host =
174 Option.getOrUndefined(input.host) ??
175 env.host ??
176 (mode === "desktop" ? "127.0.0.1" : undefined);
177
178 const config: ServerConfigShape = {
179 mode,
180 port,
181 cwd: cliConfig.cwd,
182 keybindingsConfigPath,
183 appearanceConfigPath,
184 host,
185 stateDir,
186 staticDir,
187 devUrl,
188 noBrowser,
189 authToken,
190 autoBootstrapProjectFromCwd,
191 logWebSocketEvents,
192 } satisfies ServerConfigShape;
193
194 return config;
195 }),
196 );
197
198const LayerLive = (input: CliInput) =>
199 Layer.empty.pipe(
200 Layer.provideMerge(makeServerRuntimeServicesLayer()),
201 Layer.provideMerge(makeServerProviderLayer()),
202 Layer.provideMerge(ProviderHealthLive),
203 Layer.provideMerge(SqlitePersistence.layerConfig),
204 Layer.provideMerge(ServerLoggerLive),
205 Layer.provideMerge(AnalyticsServiceLayerLive),
206 Layer.provideMerge(ServerConfigLive(input)),
207 );
208
209const isWildcardHost = (host: string | undefined): boolean =>
210 host === "0.0.0.0" || host === "::" || host === "[::]";
211
212const formatHostForUrl = (host: string): string =>
213 host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
214
215export const recordStartupHeartbeat = Effect.gen(function* () {
216 const analytics = yield* AnalyticsService;
217 const projectionSnapshotQuery = yield* ProjectionSnapshotQuery;
218
219 const { threadCount, projectCount } = yield* projectionSnapshotQuery.getSnapshot().pipe(
220 Effect.map((snapshot) => ({
221 threadCount: snapshot.threads.length,
222 projectCount: snapshot.projects.length,
223 })),
224 Effect.catch((cause) =>
225 Effect.logWarning("failed to gather startup snapshot for telemetry", { cause }).pipe(
226 Effect.as({
227 threadCount: 0,
228 projectCount: 0,
229 }),
230 ),
231 ),
232 );
233
234 yield* analytics.record("server.boot.heartbeat", {
235 threadCount,
236 projectCount,
237 });
238});
239
240const makeServerProgram = (input: CliInput) =>
241 Effect.gen(function* () {
242 const cliConfig = yield* CliConfig;
243 const { start, stopSignal } = yield* Server;
244 const openDeps = yield* Open;
245 yield* cliConfig.fixPath;
246
247 const config = yield* ServerConfig;
248
249 if (!config.devUrl && !config.staticDir) {
250 yield* Effect.logWarning(
251 "web bundle missing and no VITE_DEV_SERVER_URL; web UI unavailable",
252 {
253 hint: "Run `bun run --cwd apps/web build` or set VITE_DEV_SERVER_URL for dev mode.",
254 },
255 );
256 }
257
258 yield* start;
259 yield* Effect.forkChild(recordStartupHeartbeat);
260
261 const localUrl = `http://localhost:${config.port}`;
262 const bindUrl =
263 config.host && !isWildcardHost(config.host)
264 ? `http://${formatHostForUrl(config.host)}:${config.port}`
265 : localUrl;
266 const { authToken, devUrl, ...safeConfig } = config;
267 yield* Effect.logInfo("T3 Code running", {
268 ...safeConfig,
269 devUrl: devUrl?.toString(),
270 authEnabled: Boolean(authToken),
271 });
272
273 if (!config.noBrowser) {
274 const target = config.devUrl?.toString() ?? bindUrl;
275 yield* openDeps.openBrowser(target).pipe(
276 Effect.catch(() =>
277 Effect.logInfo("browser auto-open unavailable", {
278 hint: `Open ${target} in your browser.`,
279 }),
280 ),
281 );
282 }
283
284 return yield* stopSignal;
285 }).pipe(Effect.provide(LayerLive(input)));
286
287/**
288 * These flags mirrors the environment variables and the config shape.
289 */
290
291const modeFlag = Flag.choice("mode", ["web", "desktop"]).pipe(
292 Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
293 Flag.optional,
294);
295const portFlag = Flag.integer("port").pipe(
296 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
297 Flag.withDescription("Port for the HTTP/WebSocket server."),
298 Flag.optional,
299);
300const hostFlag = Flag.string("host").pipe(
301 Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
302 Flag.optional,
303);
304const stateDirFlag = Flag.string("state-dir").pipe(
305 Flag.withDescription("State directory path (equivalent to T3CODE_STATE_DIR)."),
306 Flag.optional,
307);
308const devUrlFlag = Flag.string("dev-url").pipe(
309 Flag.withSchema(Schema.URLFromString),
310 Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
311 Flag.optional,
312);
313const noBrowserFlag = Flag.boolean("no-browser").pipe(
314 Flag.withDescription("Disable automatic browser opening."),
315 Flag.optional,
316);
317const authTokenFlag = Flag.string("auth-token").pipe(
318 Flag.withDescription("Auth token required for WebSocket connections."),
319 Flag.withAlias("token"),
320 Flag.optional,
321);
322const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
323 Flag.withDescription(
324 "Create a project for the current working directory on startup when missing.",
325 ),
326 Flag.optional,
327);
328const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
329 Flag.withDescription(
330 "Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
331 ),
332 Flag.withAlias("log-ws-events"),
333 Flag.optional,
334);
335
336export const t3Cli = Command.make("t3", {
337 mode: modeFlag,
338 port: portFlag,
339 host: hostFlag,
340 stateDir: stateDirFlag,
341 devUrl: devUrlFlag,
342 noBrowser: noBrowserFlag,
343 authToken: authTokenFlag,
344 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
345 logWebSocketEvents: logWebSocketEventsFlag,
346}).pipe(
347 Command.withDescription("Run the T3 Code server."),
348 Command.withHandler((input) => Effect.scoped(makeServerProgram(input))),
349);