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