Open History to see the last commit
1import * as NetService from "@t3tools/shared/Net";
2import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
3import { DesktopBackendBootstrap, PortSchema } from "@t3tools/contracts";
4import * as Config from "effect/Config";
5import * as Duration from "effect/Duration";
6import * as Effect from "effect/Effect";
7import * as FileSystem from "effect/FileSystem";
8import * as LogLevel from "effect/LogLevel";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Redacted from "effect/Redacted";
12import * as Schema from "effect/Schema";
13import * as SchemaIssue from "effect/SchemaIssue";
14import * as SchemaTransformation from "effect/SchemaTransformation";
15import { Argument, Flag } from "effect/unstable/cli";
16
17import { readBootstrapEnvelope } from "../bootstrap.ts";
18import * as ServerConfig from "../config.ts";
19import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
20
21const modeFlag = Flag.choice("mode", ServerConfig.RuntimeMode.literals).pipe(
22 Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
23 Flag.optional,
24);
25const portFlag = Flag.integer("port").pipe(
26 Flag.withSchema(PortSchema),
27 Flag.withDescription("Port for the HTTP/WebSocket server."),
28 Flag.optional,
29);
30const hostFlag = Flag.string("host").pipe(
31 Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
32 Flag.optional,
33);
34export const baseDirFlag = Flag.string("base-dir").pipe(
35 Flag.withDescription(
36 "Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).",
37 ),
38 Flag.optional,
39);
40const devUrlFlag = Flag.string("dev-url").pipe(
41 Flag.withSchema(Schema.URLFromString),
42 Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
43 Flag.optional,
44);
45const noBrowserFlag = Flag.boolean("no-browser").pipe(
46 Flag.withDescription("Disable automatic browser opening."),
47 Flag.optional,
48);
49const bootstrapFdFlag = Flag.integer("bootstrap-fd").pipe(
50 Flag.withSchema(Schema.Int),
51 Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
52 Flag.optional,
53);
54const autoBootstrapProjectFromCwdFlag = Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
55 Flag.withDescription(
56 "Create a project for the current working directory on startup when missing.",
57 ),
58 Flag.optional,
59);
60const logWebSocketEventsFlag = Flag.boolean("log-websocket-events").pipe(
61 Flag.withDescription(
62 "Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
63 ),
64 Flag.withAlias("log-ws-events"),
65 Flag.optional,
66);
67const tailscaleServeFlag = Flag.boolean("tailscale-serve").pipe(
68 Flag.withDescription(
69 "Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.",
70 ),
71 Flag.optional,
72);
73const tailscaleServePortFlag = Flag.integer("tailscale-serve-port").pipe(
74 Flag.withSchema(PortSchema),
75 Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
76 Flag.optional,
77);
78
79const EnvServerConfig = Config.all({
80 logLevel: Config.logLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
81 traceMinLevel: Config.logLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
82 traceTimingEnabled: Config.boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
83 traceFile: Config.string("T3CODE_TRACE_FILE").pipe(
84 Config.option,
85 Config.map(Option.getOrUndefined),
86 ),
87 traceMaxBytes: Config.int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
88 traceMaxFiles: Config.int("T3CODE_TRACE_MAX_FILES").pipe(Config.withDefault(10)),
89 traceBatchWindowMs: Config.int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(1_000)),
90 otlpTracesUrl: Config.string("T3CODE_OTLP_TRACES_URL").pipe(
91 Config.option,
92 Config.map(Option.getOrUndefined),
93 ),
94 otlpMetricsUrl: Config.string("T3CODE_OTLP_METRICS_URL").pipe(
95 Config.option,
96 Config.map(Option.getOrUndefined),
97 ),
98 otlpExportIntervalMs: Config.int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
99 Config.withDefault(10_000),
100 ),
101 otlpServiceName: Config.string("T3CODE_OTLP_SERVICE_NAME").pipe(Config.withDefault("t3-server")),
102 mode: Config.schema(ServerConfig.RuntimeMode, "T3CODE_MODE").pipe(
103 Config.option,
104 Config.map(Option.getOrUndefined),
105 ),
106 port: Config.port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
107 host: Config.string("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
108 t3Home: Config.string("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
109 devUrl: Config.url("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
110 devAllowedOrigins: Config.string("T3CODE_DEV_ALLOWED_ORIGINS").pipe(
111 Config.withDefault(""),
112 Config.map((value) =>
113 value
114 .split(",")
115 .map((entry) => entry.trim())
116 .filter((entry) => entry.length > 0),
117 ),
118 ),
119 noBrowser: Config.boolean("T3CODE_NO_BROWSER").pipe(
120 Config.option,
121 Config.map(Option.getOrUndefined),
122 ),
123 bootstrapFd: Config.int("T3CODE_BOOTSTRAP_FD").pipe(
124 Config.option,
125 Config.map(Option.getOrUndefined),
126 ),
127 autoBootstrapProjectFromCwd: Config.boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
128 Config.option,
129 Config.map(Option.getOrUndefined),
130 ),
131 logWebSocketEvents: Config.boolean("T3CODE_LOG_WS_EVENTS").pipe(
132 Config.option,
133 Config.map(Option.getOrUndefined),
134 ),
135 tailscaleServeEnabled: Config.boolean("T3CODE_TAILSCALE_SERVE").pipe(
136 Config.option,
137 Config.map(Option.getOrUndefined),
138 ),
139 tailscaleServePort: Config.port("T3CODE_TAILSCALE_SERVE_PORT").pipe(
140 Config.option,
141 Config.map(Option.getOrUndefined),
142 ),
143});
144
145const DevAuthTokenConfig = Config.redacted("T3CODE_DEV_AUTH_TOKEN").pipe(
146 Config.map((token) => Redacted.make(Redacted.value(token).trim())),
147 Config.mapOrFail((token) =>
148 Redacted.value(token).length === 0 || Redacted.value(token).length >= 32
149 ? Effect.succeed(token)
150 : Effect.fail(
151 new Config.ConfigError(
152 new Schema.SchemaError(
153 new SchemaIssue.InvalidValue({
154 message: "T3CODE_DEV_AUTH_TOKEN must contain at least 32 characters.",
155 }),
156 ),
157 ),
158 ),
159 ),
160 Config.option,
161 Config.map(Option.filter((token) => Redacted.value(token).length > 0)),
162 Config.map(Option.getOrUndefined),
163);
164
165export interface CliServerFlags {
166 readonly mode: Option.Option<ServerConfig.RuntimeMode>;
167 readonly port: Option.Option<number>;
168 readonly host: Option.Option<string>;
169 readonly baseDir: Option.Option<string>;
170 readonly cwd: Option.Option<string>;
171 readonly devUrl: Option.Option<URL>;
172 readonly noBrowser: Option.Option<boolean>;
173 readonly bootstrapFd: Option.Option<number>;
174 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
175 readonly logWebSocketEvents: Option.Option<boolean>;
176 readonly tailscaleServeEnabled: Option.Option<boolean>;
177 readonly tailscaleServePort: Option.Option<number>;
178}
179
180export interface CliAuthLocationFlags {
181 readonly baseDir: Option.Option<string>;
182 readonly devUrl?: Option.Option<URL>;
183}
184
185export const authLocationFlags = {
186 baseDir: baseDirFlag,
187 devUrl: devUrlFlag,
188} as const;
189
190export const projectLocationFlags = {
191 baseDir: baseDirFlag,
192} as const;
193
194export const sharedServerCommandFlags = {
195 mode: modeFlag,
196 port: portFlag,
197 host: hostFlag,
198 baseDir: baseDirFlag,
199 cwd: Argument.string("cwd").pipe(
200 Argument.withDescription(
201 "Working directory for provider sessions (defaults to the current directory).",
202 ),
203 Argument.optional,
204 ),
205 devUrl: devUrlFlag,
206 noBrowser: noBrowserFlag,
207 bootstrapFd: bootstrapFdFlag,
208 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
209 logWebSocketEvents: logWebSocketEventsFlag,
210 tailscaleServeEnabled: tailscaleServeFlag,
211 tailscaleServePort: tailscaleServePortFlag,
212} as const;
213
214const resolveOptionPrecedence = <Value>(
215 ...values: ReadonlyArray<Option.Option<Value>>
216): Option.Option<Value> => Option.firstSomeOf(values);
217
218const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
219 const fs = yield* FileSystem.FileSystem;
220 const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
221 if (!exists) {
222 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined };
223 }
224
225 const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
226 return parsePersistedServerObservabilitySettings(raw);
227});
228
229export const resolveServerConfig = (
230 flags: CliServerFlags,
231 cliLogLevel: Option.Option<LogLevel.LogLevel>,
232 options?: {
233 readonly startupPresentation?: ServerConfig.StartupPresentation;
234 readonly forceAutoBootstrapProjectFromCwd?: boolean;
235 },
236) =>
237 Effect.gen(function* () {
238 const { findAvailablePort } = yield* NetService.NetService;
239 const path = yield* Path.Path;
240 const fs = yield* FileSystem.FileSystem;
241 const env = yield* EnvServerConfig;
242 const normalizedFlags = {
243 mode: flags.mode ?? Option.none(),
244 port: flags.port ?? Option.none(),
245 host: flags.host ?? Option.none(),
246 baseDir: flags.baseDir ?? Option.none(),
247 cwd: flags.cwd ?? Option.none(),
248 devUrl: flags.devUrl ?? Option.none(),
249 noBrowser: flags.noBrowser ?? Option.none(),
250 bootstrapFd: flags.bootstrapFd ?? Option.none(),
251 autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
252 logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
253 tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
254 tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
255 } satisfies CliServerFlags;
256 const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
257 const bootstrapEnvelope =
258 bootstrapFd !== undefined
259 ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)
260 : Option.none();
261 const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
262
263 const mode: ServerConfig.RuntimeMode = Option.getOrElse(
264 resolveOptionPrecedence(
265 normalizedFlags.mode,
266 Option.fromUndefinedOr(env.mode),
267 Option.fromUndefinedOr(bootstrap?.mode),
268 ),
269 () => "web",
270 );
271
272 const port = yield* Option.match(
273 resolveOptionPrecedence(
274 normalizedFlags.port,
275 Option.fromUndefinedOr(env.port),
276 Option.fromUndefinedOr(bootstrap?.port),
277 ),
278 {
279 onSome: (value) => Effect.succeed(value),
280 onNone: () => {
281 if (mode === "desktop") {
282 return Effect.succeed(ServerConfig.DEFAULT_PORT);
283 }
284 return findAvailablePort(ServerConfig.DEFAULT_PORT);
285 },
286 },
287 );
288 const devUrl = Option.getOrElse(
289 resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
290 () => undefined,
291 );
292 const devAuthToken =
293 mode === "web" && devUrl !== undefined ? yield* DevAuthTokenConfig : undefined;
294 const explicitBaseDir = resolveOptionPrecedence(
295 normalizedFlags.baseDir,
296 Option.fromUndefinedOr(env.t3Home),
297 ).pipe(Option.filter((value) => value.trim().length > 0));
298 const baseDir = yield* resolveBaseDir(
299 Option.getOrUndefined(
300 resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),
301 ),
302 );
303 const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
304 const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
305 yield* fs.makeDirectory(cwd, { recursive: true });
306 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
307 baseDirIsExplicit: Option.isSome(explicitBaseDir),
308 });
309 yield* ServerConfig.ensureServerDirectories(derivedPaths);
310 const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
311 derivedPaths.settingsPath,
312 );
313 const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
314 yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
315 const startupPresentation = options?.startupPresentation ?? "browser";
316 const isHeadlessStartup = startupPresentation === "headless";
317 const noBrowser = Option.getOrElse(
318 resolveOptionPrecedence(
319 isHeadlessStartup ? Option.some(true) : Option.none(),
320 normalizedFlags.noBrowser,
321 Option.fromUndefinedOr(env.noBrowser),
322 Option.fromUndefinedOr(bootstrap?.noBrowser),
323 ),
324 () => mode === "desktop",
325 );
326 const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
327 const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
328 const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
329 const resourceMonitorPath = bootstrap?.resourceMonitorPath;
330 const autoBootstrapProjectFromCwd = Option.getOrElse(
331 resolveOptionPrecedence(
332 Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
333 isHeadlessStartup ? Option.some(false) : Option.none(),
334 normalizedFlags.autoBootstrapProjectFromCwd,
335 Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
336 ),
337 () => mode === "web",
338 );
339 const logWebSocketEvents = Option.getOrElse(
340 resolveOptionPrecedence(
341 normalizedFlags.logWebSocketEvents,
342 Option.fromUndefinedOr(env.logWebSocketEvents),
343 ),
344 () => Boolean(devUrl),
345 );
346 const tailscaleServeEnabled = Option.getOrElse(
347 resolveOptionPrecedence(
348 normalizedFlags.tailscaleServeEnabled,
349 Option.fromUndefinedOr(env.tailscaleServeEnabled),
350 Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
351 ),
352 () => false,
353 );
354 const tailscaleServePort = Option.getOrElse(
355 resolveOptionPrecedence(
356 normalizedFlags.tailscaleServePort,
357 Option.fromUndefinedOr(env.tailscaleServePort),
358 Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
359 ),
360 () => 443,
361 );
362 const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
363 const host = Option.getOrElse(
364 resolveOptionPrecedence(
365 normalizedFlags.host,
366 Option.fromUndefinedOr(env.host),
367 Option.fromUndefinedOr(bootstrap?.host),
368 ),
369 () => (mode === "desktop" ? "127.0.0.1" : undefined),
370 );
371 const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
372
373 const config: ServerConfig.ServerConfig["Service"] = {
374 logLevel,
375 traceMinLevel: env.traceMinLevel,
376 traceTimingEnabled: env.traceTimingEnabled,
377 traceBatchWindowMs: env.traceBatchWindowMs,
378 traceMaxBytes: env.traceMaxBytes,
379 traceMaxFiles: env.traceMaxFiles,
380 otlpTracesUrl:
381 env.otlpTracesUrl ??
382 bootstrap?.otlpTracesUrl ??
383 persistedObservabilitySettings.otlpTracesUrl,
384 otlpMetricsUrl:
385 env.otlpMetricsUrl ??
386 bootstrap?.otlpMetricsUrl ??
387 persistedObservabilitySettings.otlpMetricsUrl,
388 otlpExportIntervalMs: env.otlpExportIntervalMs,
389 otlpServiceName: env.otlpServiceName,
390 mode,
391 port,
392 cwd,
393 baseDir,
394 ...derivedPaths,
395 serverTracePath,
396 host,
397 staticDir,
398 devUrl,
399 ...(devAuthToken === undefined ? {} : { devAuthToken }),
400 devAllowedOrigins: env.devAllowedOrigins,
401 noBrowser,
402 startupPresentation,
403 desktopBootstrapToken,
404 desktopTelemetryFd,
405 desktopTelemetryControlFd,
406 resourceMonitorPath,
407 autoBootstrapProjectFromCwd,
408 logWebSocketEvents,
409 tailscaleServeEnabled,
410 tailscaleServePort,
411 };
412
413 return config;
414 });
415
416export const resolveCliAuthConfig = (
417 flags: CliAuthLocationFlags,
418 cliLogLevel: Option.Option<LogLevel.LogLevel>,
419) =>
420 resolveServerConfig(
421 {
422 mode: Option.none(),
423 port: Option.none(),
424 host: Option.none(),
425 baseDir: flags.baseDir,
426 cwd: Option.none(),
427 devUrl: flags.devUrl ?? Option.none(),
428 noBrowser: Option.none(),
429 bootstrapFd: Option.none(),
430 autoBootstrapProjectFromCwd: Option.none(),
431 logWebSocketEvents: Option.none(),
432 tailscaleServeEnabled: Option.none(),
433 tailscaleServePort: Option.none(),
434 },
435 cliLogLevel,
436 );
437
438const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
439
440const parseDurationInput = (value: string): Duration.Duration | null => {
441 const trimmed = value.trim();
442 if (trimmed.length === 0) return null;
443
444 const shorthand = DurationShorthandPattern.exec(trimmed);
445 const normalizedInput = shorthand?.groups
446 ? (() => {
447 const amountText = shorthand.groups.value;
448 const unitText = shorthand.groups.unit;
449 if (typeof amountText !== "string" || typeof unitText !== "string") {
450 return null;
451 }
452
453 const amount = Number.parseInt(amountText, 10);
454 if (!Number.isFinite(amount)) return null;
455
456 switch (unitText.toLowerCase()) {
457 case "ms":
458 return `${amount} millis`;
459 case "s":
460 return `${amount} seconds`;
461 case "m":
462 return `${amount} minutes`;
463 case "h":
464 return `${amount} hours`;
465 case "d":
466 return `${amount} days`;
467 case "w":
468 return `${amount} weeks`;
469 default:
470 return null;
471 }
472 })()
473 : (trimmed as Duration.Input);
474
475 if (normalizedInput === null) return null;
476
477 const decoded = Duration.fromInput(normalizedInput as Duration.Input);
478 return Option.isSome(decoded) ? decoded.value : null;
479};
480
481export const DurationFromString = Schema.String.pipe(
482 Schema.decodeTo(
483 Schema.Duration,
484 SchemaTransformation.transformOrFail({
485 decode: (value) => {
486 const duration = parseDurationInput(value);
487 if (duration !== null) {
488 return Effect.succeed(duration);
489 }
490 return Effect.fail(
491 new SchemaIssue.InvalidValue({
492 message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
493 }),
494 );
495 },
496 encode: (duration) => Effect.succeed(Duration.format(duration)),
497 }),
498 ),
499);