Open History to see the last commit
1import { NetService } from "@t3tools/shared/Net";
2import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
3import { Config, Effect, FileSystem, LogLevel, Option, Path, Schema } from "effect";
4import { Argument, Command, Flag, GlobalFlag } from "effect/unstable/cli";
5
6import {
7 DEFAULT_PORT,
8 deriveServerPaths,
9 ensureServerDirectories,
10 resolveStaticDir,
11 ServerConfig,
12 RuntimeMode,
13 type ServerConfigShape,
14} from "./config";
15import { readBootstrapEnvelope } from "./bootstrap";
16import { expandHomePath, resolveBaseDir } from "./os-jank";
17import { runServer } from "./server";
18
19const PortSchema = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }));
20
21const BootstrapEnvelopeSchema = Schema.Struct({
22 mode: Schema.optional(RuntimeMode),
23 port: Schema.optional(PortSchema),
24 host: Schema.optional(Schema.String),
25 t3Home: Schema.optional(Schema.String),
26 devUrl: Schema.optional(Schema.URLFromString),
27 noBrowser: Schema.optional(Schema.Boolean),
28 authToken: Schema.optional(Schema.String),
29 autoBootstrapProjectFromCwd: Schema.optional(Schema.Boolean),
30 logWebSocketEvents: Schema.optional(Schema.Boolean),
31 otlpTracesUrl: Schema.optional(Schema.String),
32 otlpMetricsUrl: Schema.optional(Schema.String),
33});
34
35const modeFlag = Flag.choice("mode", RuntimeMode.literals).pipe(
36 Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
37 Flag.optional,
38);
39const portFlag = Flag.integer("port").pipe(
40 Flag.withSchema(PortSchema),
41 Flag.withDescription("Port for the HTTP/WebSocket server."),
42 Flag.optional,
43);
44const hostFlag = Flag.string("host").pipe(
45 Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
46 Flag.optional,
47);
48const baseDirFlag = Flag.string("base-dir").pipe(
49 Flag.withDescription("Base directory path (equivalent to T3CODE_HOME)."),
50 Flag.optional,
51);
52const devUrlFlag = Flag.string("dev-url").pipe(
53 Flag.withSchema(Schema.URLFromString),
54 Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
55 Flag.optional,
56);
57const noBrowserFlag = Flag.boolean("no-browser").pipe(
58 Flag.withDescription("Disable automatic browser opening."),
59 Flag.optional,
60);
61const authTokenFlag = Flag.string("auth-token").pipe(
62 Flag.withDescription("Auth token required for WebSocket connections."),
63 Flag.withAlias("token"),
64 Flag.optional,
65);
66const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
67 Flag.withSchema(Schema.Int),
68 Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
69 Flag.optional,
70);
71const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
72 Flag.withDescription(
73 "Create a project for the current working directory on startup when missing.",
74 ),
75 Flag.optional,
76);
77const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
78 Flag.withDescription(
79 "Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
80 ),
81 Flag.withAlias("log-ws-events"),
82 Flag.optional,
83);
84
85const EnvServerConfig = Config.all({
86 logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
87 traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
88 traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
89 traceFile: Config.string("T3CODE_TRACE_FILE").pipe(
90 Config.option,
91 Config.map(Option.getOrUndefined),
92 ),
93 traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
94 traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
95 traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(200)),
96 otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
97 Config.option,
98 Config.map(Option.getOrUndefined),
99 ),
100 otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe(
101 Config.option,
102 Config.map(Option.getOrUndefined),
103 ),
104 otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
105 Config.withDefault(10_000),
106 ),
107 otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")),
108 mode: Config.schema(RuntimeMode, "T3CODE_MODE").pipe(
109 Config.option,
110 Config.map(Option.getOrUndefined),
111 ),
112 port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
113 host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
114 t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
115 devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
116 noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
117 Config.option,
118 Config.map(Option.getOrUndefined),
119 ),
120 authToken: Config.string("T3CODE_AUTH_TOKEN").pipe(
121 Config.option,
122 Config.map(Option.getOrUndefined),
123 ),
124 bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
125 Config.option,
126 Config.map(Option.getOrUndefined),
127 ),
128 autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
129 Config.option,
130 Config.map(Option.getOrUndefined),
131 ),
132 logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
133 Config.option,
134 Config.map(Option.getOrUndefined),
135 ),
136});
137
138interface CliServerFlags {
139 readonly mode: Option.Option<RuntimeMode>;
140 readonly port: Option.Option<number>;
141 readonly host: Option.Option<string>;
142 readonly baseDir: Option.Option<string>;
143 readonly cwd: Option.Option<string>;
144 readonly devUrl: Option.Option<URL>;
145 readonly noBrowser: Option.Option<boolean>;
146 readonly authToken: Option.Option<string>;
147 readonly bootstrapFd: Option.Option<number>;
148 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
149 readonly logWebSocketEvents: Option.Option<boolean>;
150}
151
152const resolveBooleanFlag = (flag: Option.Option<boolean>, envValue: boolean) =>
153 Option.getOrElse(Option.filter(flag, Boolean), () => envValue);
154
155const resolveOptionPrecedence = <Value>(
156 ...values: ReadonlyArray<Option.Option<Value>>
157): Option.Option<Value> => Option.firstSomeOf(values);
158
159const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
160 const fs = yield* FileSystem.FileSystem;
161 const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
162 if (!exists) {
163 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
164 }
165
166 const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
167 return parsePersistedServerObservabilitySettings(raw);
168});
169
170export const resolveServerConfig = (
171 flags: CliServerFlags,
172 cliLogLevel: Option.Option<LogLevel.LogLevel>,
173) =>
174 Effect.gen(function* () {
175 const { findAvailablePort } = yield* NetService;
176 const path = yield* Path.Path;
177 const fs = yield* FileSystem.FileSystem;
178 const env = yield* EnvServerConfig;
179 const bootstrapFd = Option.getOrUndefined(flags.bootstrapFd) ?? env.bootstrapFd;
180 const bootstrapEnvelope =
181 bootstrapFd !== undefined
182 ? yield* readBootstrapEnvelope(BootstrapEnvelopeSchema, bootstrapFd)
183 : Option.none();
184
185 const mode: RuntimeMode = Option.getOrElse(
186 resolveOptionPrecedence(
187 flags.mode,
188 Option.fromUndefinedOr(env.mode),
189 Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.mode)),
190 ),
191 () => "web",
192 );
193
194 const port = yield* Option.match(
195 resolveOptionPrecedence(
196 flags.port,
197 Option.fromUndefinedOr(env.port),
198 Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.port)),
199 ),
200 {
201 onSome: (value) => Effect.succeed(value),
202 onNone: () => {
203 if (mode === "desktop") {
204 return Effect.succeed(DEFAULT_PORT);
205 }
206 return findAvailablePort(DEFAULT_PORT);
207 },
208 },
209 );
210 const devUrl = Option.getOrElse(
211 resolveOptionPrecedence(
212 flags.devUrl,
213 Option.fromUndefinedOr(env.devUrl),
214 Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.devUrl)),
215 ),
216 () => undefined,
217 );
218 const baseDir = yield* resolveBaseDir(
219 Option.getOrUndefined(
220 resolveOptionPrecedence(
221 flags.baseDir,
222 Option.fromUndefinedOr(env.t3Home),
223 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
224 Option.fromUndefinedOr(bootstrap.t3Home),
225 ),
226 ),
227 ),
228 );
229 const rawCwd = Option.getOrElse(flags.cwd, () => process.cwd());
230 const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
231 yield* fs.makeDirectory(cwd, { recursive: true });
232 const derivedPaths = yield* deriveServerPaths(baseDir, devUrl);
233 yield* ensureServerDirectories(derivedPaths);
234 const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
235 derivedPaths.settingsPath,
236 );
237 const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
238 yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
239 const noBrowser = resolveBooleanFlag(
240 flags.noBrowser,
241 Option.getOrElse(
242 resolveOptionPrecedence(
243 Option.fromUndefinedOr(env.noBrowser),
244 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
245 Option.fromUndefinedOr(bootstrap.noBrowser),
246 ),
247 ),
248 () => mode === "desktop",
249 ),
250 );
251 const authToken = Option.getOrUndefined(
252 resolveOptionPrecedence(
253 flags.authToken,
254 Option.fromUndefinedOr(env.authToken),
255 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
256 Option.fromUndefinedOr(bootstrap.authToken),
257 ),
258 ),
259 );
260 const autoBootstrapProjectFromCwd = resolveBooleanFlag(
261 flags.autoBootstrapProjectFromCwd,
262 Option.getOrElse(
263 resolveOptionPrecedence(
264 Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
265 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
266 Option.fromUndefinedOr(bootstrap.autoBootstrapProjectFromCwd),
267 ),
268 ),
269 () => mode === "web",
270 ),
271 );
272 const logWebSocketEvents = resolveBooleanFlag(
273 flags.logWebSocketEvents,
274 Option.getOrElse(
275 resolveOptionPrecedence(
276 Option.fromUndefinedOr(env.logWebSocketEvents),
277 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
278 Option.fromUndefinedOr(bootstrap.logWebSocketEvents),
279 ),
280 ),
281 () => Boolean(devUrl),
282 ),
283 );
284 const staticDir = devUrl ? undefined : yield* resolveStaticDir();
285 const host = Option.getOrElse(
286 resolveOptionPrecedence(
287 flags.host,
288 Option.fromUndefinedOr(env.host),
289 Option.flatMap(bootstrapEnvelope, (bootstrap) => Option.fromUndefinedOr(bootstrap.host)),
290 ),
291 () => (mode === "desktop" ? "127.0.0.1" : undefined),
292 );
293 const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
294
295 const config: ServerConfigShape = {
296 logLevel,
297 traceMinLevel: env.traceMinLevel,
298 traceTimingEnabled: env.traceTimingEnabled,
299 traceBatchWindowMs: env.traceBatchWindowMs,
300 traceMaxBytes: env.traceMaxBytes,
301 traceMaxFiles: env.traceMaxFiles,
302 otlpTracesUrl:
303 env.otlpTracesUrl ??
304 Option.getOrUndefined(
305 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
306 Option.fromUndefinedOr(bootstrap.otlpTracesUrl),
307 ),
308 ) ??
309 persistedObservabilitySettings.otlpTracesUrl,
310 otlpMetricsUrl:
311 env.otlpMetricsUrl ??
312 Option.getOrUndefined(
313 Option.flatMap(bootstrapEnvelope, (bootstrap) =>
314 Option.fromUndefinedOr(bootstrap.otlpMetricsUrl),
315 ),
316 ) ??
317 persistedObservabilitySettings.otlpMetricsUrl,
318 otlpExportIntervalMs: env.otlpExportIntervalMs,
319 otlpServiceName: env.otlpServiceName,
320 mode,
321 port,
322 cwd,
323 baseDir,
324 ...derivedPaths,
325 serverTracePath,
326 host,
327 staticDir,
328 devUrl,
329 noBrowser,
330 authToken,
331 autoBootstrapProjectFromCwd,
332 logWebSocketEvents,
333 };
334
335 return config;
336 });
337
338const commandFlags = {
339 mode: modeFlag,
340 port: portFlag,
341 host: hostFlag,
342 baseDir: baseDirFlag,
343 cwd: Argument.string("cwd").pipe(
344 Argument.withDescription(
345 "Working directory for provider sessions (defaults to the current directory).",
346 ),
347 Argument.optional,
348 ),
349 devUrl: devUrlFlag,
350 noBrowser: noBrowserFlag,
351 authToken: authTokenFlag,
352 bootstrapFd: bootstrapFdFlag,
353 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
354 logWebSocketEvents: logWebSocketEventsFlag,
355} as const;
356
357const rootCommand = Command.make("t3", commandFlags).pipe(
358 Command.withDescription("Run the T3 Code server."),
359 Command.withHandler((flags) =>
360 Effect.gen(function* () {
361 const logLevel = yield* GlobalFlag.LogLevel;
362 const config = yield* resolveServerConfig(flags, logLevel);
363 return yield* runServer.pipe(Effect.provideService(ServerConfig, config));
364 }),
365 ),
366);
367
368export const cli = rootCommand;