Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

config.ts

638 lines23.8 KB

1import * as NetService from "@t3tools/shared/Net";
2import { isWildcardHost, normalizeHostname } from "@t3tools/shared/hostClassification";
3import {
4 OtlpHeadersFromString,
5 OtlpProtocol,
6 type SignalExport,
7} from "@t3tools/shared/observability";
8import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
9import { parsePersistedServerObservabilitySettings } from "@t3tools/shared/serverSettings";
10import { DesktopBackendBootstrap, PortSchema } from "@t3tools/contracts";
11import * as Config from "effect/Config";
12import * as Duration from "effect/Duration";
13import * as Effect from "effect/Effect";
14import * as FileSystem from "effect/FileSystem";
15import * as LogLevel from "effect/LogLevel";
16import * as Option from "effect/Option";
17import * as Path from "effect/Path";
18import * as Redacted from "effect/Redacted";
19import * as References from "effect/References";
20import * as Schema from "effect/Schema";
21import * as SchemaIssue from "effect/SchemaIssue";
22import * as SchemaTransformation from "effect/SchemaTransformation";
23import { Argument, Flag } from "effect/cli";
24import * as CliError from "effect/cli/CliError";
25​
26import { readBootstrapEnvelope } from "../bootstrap.ts";
27import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
28import * as ServerConfig from "../config.ts";
29import { expandHomePath, resolveBaseDir } from "../os-jank.ts";
30import { isProcessAlive, readPersistedServerRuntimeState } from "../serverRuntimeState.ts";
31import { isServerOwnershipHeld } from "../serverOwnership.ts";
32import { resolveHostCliCommand } from "./invocation.ts";
33​
34const modeFlag = Flag.Literals("mode", ServerConfig.RuntimeMode.literals).pipe(
35 Flag.withDescription("Runtime mode. `desktop` keeps loopback defaults unless overridden."),
36 Flag.optional,
37);
38const portFlag = Flag.Int("port").pipe(
39 Flag.withSchema(PortSchema),
40 Flag.withDescription("Port for the HTTP/WebSocket server."),
41 Flag.optional,
42);
43const hostFlag = Flag.String("host").pipe(
44 Flag.withDescription("Host/interface to bind (for example 127.0.0.1, 0.0.0.0, or a Tailnet IP)."),
45 Flag.optional,
46);
47export const baseDirFlag = Flag.String("base-dir").pipe(
48 Flag.withDescription(
49 "Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME).",
50 ),
51 Flag.optional,
52);
53const devUrlFlag = Flag.String("dev-url").pipe(
54 Flag.withSchema(Schema.URLFromString),
55 Flag.withDescription("Dev web URL to proxy/redirect to (equivalent to VITE_DEV_SERVER_URL)."),
56 Flag.optional,
57);
58const noBrowserFlag = Flag.Boolean("no-browser").pipe(
59 Flag.withDescription("Disable automatic browser opening."),
60 Flag.optional,
61);
62const bootstrapFdFlag = Flag.Int("bootstrap-fd").pipe(
63 Flag.withSchema(Schema.Int),
64 Flag.withDescription("Read one-time bootstrap secrets from the given file descriptor."),
65 Flag.optional,
66);
67const autoBootstrapProjectFromCwdFlag = Flag.Boolean("auto-bootstrap-project-from-cwd").pipe(
68 Flag.withDescription(
69 "Create a project for the current working directory on startup when missing.",
70 ),
71 Flag.optional,
72);
73const logWebSocketEventsFlag = Flag.Boolean("log-websocket-events").pipe(
74 Flag.withDescription(
75 "Emit server-side logs for outbound WebSocket push traffic (equivalent to T3CODE_LOG_WS_EVENTS).",
76 ),
77 Flag.withAlias("log-ws-events"),
78 Flag.optional,
79);
80const tailscaleServeFlag = Flag.Boolean("tailscale-serve").pipe(
81 Flag.withDescription(
82 "Configure Tailscale Serve to expose this backend over HTTPS on the Tailnet.",
83 ),
84 Flag.optional,
85);
86const tailscaleServePortFlag = Flag.Int("tailscale-serve-port").pipe(
87 Flag.withSchema(PortSchema),
88 Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
89 Flag.optional,
90);
91const lanFlag = Flag.Boolean("lan").pipe(
92 Flag.withDescription(
93 "Accept connections from your local network and tailnet, not only this machine (equivalent to T3CODE_LAN).",
94 ),
95 Flag.optional,
96);
97​
98export const traceFileConfig = Config.String("T3CODE_TRACE_FILE").pipe(
99 Config.option,
100 Config.map(Option.getOrUndefined),
101);
102export const traceMaxFilesConfig = Config.Int("T3CODE_TRACE_MAX_FILES").pipe(
103 Config.withDefault(10),
104);
105​
106const EnvServerConfig = Config.all({
107 logLevel: Config.LogLevel("T3CODE_LOG_LEVEL").pipe(Config.withDefault("Info")),
108 traceMinLevel: Config.LogLevel("T3CODE_TRACE_MIN_LEVEL").pipe(Config.withDefault("Info")),
109 traceTimingEnabled: Config.Boolean("T3CODE_TRACE_TIMING_ENABLED").pipe(Config.withDefault(true)),
110 traceFile: traceFileConfig,
111 traceMaxBytes: Config.Int("T3CODE_TRACE_MAX_BYTES").pipe(Config.withDefault(10 * 1024 * 1024)),
112 traceMaxFiles: traceMaxFilesConfig,
113 traceBatchWindowMs: Config.Int("T3CODE_TRACE_BATCH_WINDOW_MS").pipe(Config.withDefault(1_000)),
114 otlpTracesUrl: Config.String("T3CODE_OTLP_TRACES_URL").pipe(
115 Config.option,
116 Config.map(Option.getOrUndefined),
117 ),
118 otlpMetricsUrl: Config.String("T3CODE_OTLP_METRICS_URL").pipe(
119 Config.option,
120 Config.map(Option.getOrUndefined),
121 ),
122 otlpLogsUrl: Config.String("T3CODE_OTLP_LOGS_URL").pipe(
123 Config.option,
124 Config.map(Option.getOrUndefined),
125 ),
126 otlpExportIntervalMs: Config.Int("T3CODE_OTLP_EXPORT_INTERVAL_MS").pipe(
127 Config.withDefault(10_000),
128 ),
129 otlpHeaders: Config.schema(OtlpHeadersFromString, "T3CODE_OTLP_HEADERS").pipe(
130 Config.option,
131 Config.map(Option.getOrUndefined),
132 ),
133 otlpProtocol: Config.schema(OtlpProtocol, "T3CODE_OTLP_PROTOCOL").pipe(
134 Config.withDefault("http/json"),
135 ),
136 mode: Config.schema(ServerConfig.RuntimeMode, "T3CODE_MODE").pipe(
137 Config.option,
138 Config.map(Option.getOrUndefined),
139 ),
140 port: Config.Port("T3CODE_PORT").pipe(Config.option, Config.map(Option.getOrUndefined)),
141 host: Config.String("T3CODE_HOST").pipe(Config.option, Config.map(Option.getOrUndefined)),
142 t3Home: Config.String("T3CODE_HOME").pipe(Config.option, Config.map(Option.getOrUndefined)),
143 devUrl: Config.URL("VITE_DEV_SERVER_URL").pipe(Config.option, Config.map(Option.getOrUndefined)),
144 devAllowedOrigins: Config.String("T3CODE_DEV_ALLOWED_ORIGINS").pipe(
145 Config.withDefault(""),
146 Config.map((value) =>
147 value
148 .split(",")
149 .map((entry) => entry.trim())
150 .filter((entry) => entry.length > 0),
151 ),
152 ),
153 noBrowser: Config.Boolean("T3CODE_NO_BROWSER").pipe(
154 Config.option,
155 Config.map(Option.getOrUndefined),
156 ),
157 bootstrapFd: Config.Int("T3CODE_BOOTSTRAP_FD").pipe(
158 Config.option,
159 Config.map(Option.getOrUndefined),
160 ),
161 autoBootstrapProjectFromCwd: Config.Boolean("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD").pipe(
162 Config.option,
163 Config.map(Option.getOrUndefined),
164 ),
165 logWebSocketEvents: Config.Boolean("T3CODE_LOG_WS_EVENTS").pipe(
166 Config.option,
167 Config.map(Option.getOrUndefined),
168 ),
169 tailscaleServeEnabled: Config.Boolean("T3CODE_TAILSCALE_SERVE").pipe(
170 Config.option,
171 Config.map(Option.getOrUndefined),
172 ),
173 tailscaleServePort: Config.Port("T3CODE_TAILSCALE_SERVE_PORT").pipe(
174 Config.option,
175 Config.map(Option.getOrUndefined),
176 ),
177 lan: Config.Boolean("T3CODE_LAN").pipe(Config.option, Config.map(Option.getOrUndefined)),
178});
179​
180const DevAuthTokenConfig = Config.Redacted("T3CODE_DEV_AUTH_TOKEN").pipe(
181 Config.map((token) => Redacted.make(Redacted.value(token).trim())),
182 Config.mapEffect((token) =>
183 Redacted.value(token).length === 0 || Redacted.value(token).length >= 32
184 ? Effect.succeed(token)
185 : Effect.fail(
186 new Config.ConfigError(
187 new Schema.SchemaError(
188 new SchemaIssue.InvalidValue({
189 message: "T3CODE_DEV_AUTH_TOKEN must contain at least 32 characters.",
190 }),
191 ),
192 ),
193 ),
194 ),
195 Config.option,
196 Config.map(Option.filter((token) => Redacted.value(token).length > 0)),
197 Config.map(Option.getOrUndefined),
198);
199​
200export interface CliServerFlags {
201 readonly mode: Option.Option<ServerConfig.RuntimeMode>;
202 readonly port: Option.Option<number>;
203 readonly host: Option.Option<string>;
204 readonly baseDir: Option.Option<string>;
205 readonly cwd: Option.Option<string>;
206 readonly devUrl: Option.Option<URL>;
207 readonly noBrowser: Option.Option<boolean>;
208 readonly bootstrapFd: Option.Option<number>;
209 readonly autoBootstrapProjectFromCwd: Option.Option<boolean>;
210 readonly logWebSocketEvents: Option.Option<boolean>;
211 readonly tailscaleServeEnabled: Option.Option<boolean>;
212 readonly tailscaleServePort: Option.Option<number>;
213 readonly lan: Option.Option<boolean>;
215​
216export interface CliAuthLocationFlags {
217 readonly baseDir: Option.Option<string>;
218 readonly devUrl?: Option.Option<URL>;
220​
221export const authLocationFlags = {
222 baseDir: baseDirFlag,
223 devUrl: devUrlFlag,
224} as const;
225​
226export const projectLocationFlags = {
227 baseDir: baseDirFlag,
228} as const;
229​
230export const sharedServerCommandFlags = {
231 mode: modeFlag,
232 port: portFlag,
233 host: hostFlag,
234 baseDir: baseDirFlag,
235 cwd: Argument.String("cwd").pipe(
236 Argument.withDescription(
237 "Working directory for provider sessions (defaults to the current directory).",
238 ),
239 Argument.optional,
240 ),
241 devUrl: devUrlFlag,
242 noBrowser: noBrowserFlag,
243 bootstrapFd: bootstrapFdFlag,
244 autoBootstrapProjectFromCwd: autoBootstrapProjectFromCwdFlag,
245 logWebSocketEvents: logWebSocketEventsFlag,
246 tailscaleServeEnabled: tailscaleServeFlag,
247 tailscaleServePort: tailscaleServePortFlag,
248 lan: lanFlag,
249} as const;
250​
251const resolveOptionPrecedence = <Value>(
252 ...values: ReadonlyArray<Option.Option<Value>>
253): Option.Option<Value> => Option.firstSomeOf(values);
254​
255const loadPersistedObservabilitySettings = Effect.fn(function* (settingsPath: string) {
256 const fs = yield* FileSystem.FileSystem;
257 const exists = yield* fs.exists(settingsPath).pipe(Effect.orElseSucceed(() => false));
258 if (!exists) {
259 return { otlpTracesUrl: undefined, otlpMetricsUrl: undefined, otlpLogsUrl: undefined };
260 }
261​
262 const raw = yield* fs.readFileString(settingsPath).pipe(Effect.orElseSucceed(() => ""));
263 return parsePersistedServerObservabilitySettings(raw);
264});
265​
266export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(function* (
267 flags: CliServerFlags,
268 cliLogLevel: Option.Option<LogLevel.LogLevel>,
269 options?: {
270 readonly startupPresentation?: ServerConfig.StartupPresentation;
271 readonly forceAutoBootstrapProjectFromCwd?: boolean;
272 readonly rejectRunningServer?: boolean;
273 readonly selectAutomaticPort?: (
274 preferred: number,
275 host: string | undefined,
276 ) => Effect.Effect<number, NetService.NetError | CliError.UserError>;
277 },
278) {
279 const { findAvailablePort } = yield* NetService.NetService;
280 const selectAutomaticPort = options?.selectAutomaticPort ?? findAvailablePort;
281 const path = yield* Path.Path;
282 const fs = yield* FileSystem.FileSystem;
283 const env = yield* EnvServerConfig;
284 const normalizedFlags = {
285 mode: flags.mode ?? Option.none(),
286 port: flags.port ?? Option.none(),
287 host: flags.host ?? Option.none(),
288 baseDir: flags.baseDir ?? Option.none(),
289 cwd: flags.cwd ?? Option.none(),
290 devUrl: flags.devUrl ?? Option.none(),
291 noBrowser: flags.noBrowser ?? Option.none(),
292 bootstrapFd: flags.bootstrapFd ?? Option.none(),
293 autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
294 logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
295 tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
296 tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
297 lan: flags.lan ?? Option.none(),
298 } satisfies CliServerFlags;
299 const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
300 const bootstrapEnvelope =
301 bootstrapFd !== undefined
302 ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)
303 : Option.none();
304 const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
305​
306 const mode: ServerConfig.RuntimeMode = Option.getOrElse(
307 resolveOptionPrecedence(
308 normalizedFlags.mode,
309 Option.fromUndefinedOr(env.mode),
310 Option.fromUndefinedOr(bootstrap?.mode),
311 ),
312 () => "web",
313 );
314​
315 const devUrl = Option.getOrElse(
316 resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
317 () => undefined,
318 );
319 const devAuthToken =
320 mode === "web" && devUrl !== undefined ? yield* DevAuthTokenConfig : undefined;
321 const explicitBaseDir = resolveOptionPrecedence(
322 normalizedFlags.baseDir,
323 Option.fromUndefinedOr(env.t3Home),
324 ).pipe(Option.filter((value) => value.trim().length > 0));
325 const baseDir = yield* resolveBaseDir(
326 Option.getOrUndefined(
327 resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),
328 ),
329 );
330 const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
331 const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
332 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
333 baseDirIsExplicit: Option.isSome(explicitBaseDir),
334 });
335 // An interactive CLI must not start over a discovered server. Lifetime locking
336 // and supervisor handoff are separate; this preflight cannot arbitrate two starts.
337 if (options?.rejectRunningServer && mode === "web") {
338 const runtime = yield* readPersistedServerRuntimeState(derivedPaths.serverRuntimeStatePath);
339 // A killed container can leave a record whose PID is now ours or an unrelated process's.
340 // Lock-aware records are live only while their owner still holds the lock.
341 if (
342 Option.isSome(runtime) &&
343 runtime.value.pid > 0 &&
344 runtime.value.pid !== process.pid &&
345 isProcessAlive(runtime.value.pid) &&
346 (runtime.value.ownerId === undefined ||
347 isServerOwnershipHeld(derivedPaths.serverRuntimeStatePath))
348 ) {
349 // Bare `t3 pair` prefers a linked worktree's `.t3`, so always name this home.
350 const { command: pairCommand } = yield* resolveHostCliCommand("pair", [
351 "--base-dir",
352 baseDir,
353 ]);
354 return yield* new CliError.UserError({
355 cause: `A T3 Code server is already running for ${baseDir} (pid ${runtime.value.pid}, ${runtime.value.origin}). To open it, run \`${pairCommand}\` and open the pairing URL it prints. To start another server, stop this one first or use a different --base-dir.`,
356 });
357 }
358 }
359 yield* fs.makeDirectory(cwd, { recursive: true });
360 yield* ServerConfig.ensureServerDirectories(derivedPaths);
361 const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
362 derivedPaths.settingsPath,
363 );
364 const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
365 yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
366 const startupPresentation = options?.startupPresentation ?? "browser";
367 const isHeadlessStartup = startupPresentation === "headless";
368 const noBrowser = Option.getOrElse(
369 resolveOptionPrecedence(
370 isHeadlessStartup ? Option.some(true) : Option.none(),
371 normalizedFlags.noBrowser,
372 Option.fromUndefinedOr(env.noBrowser),
373 Option.fromUndefinedOr(bootstrap?.noBrowser),
374 ),
375 () => mode === "desktop",
376 );
377 const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
378 const desktopBootstrapSecret = bootstrap?.desktopBootstrapSecret;
379 const desktopReadinessSecret = bootstrap?.desktopReadinessSecret;
380 const shellEnvironmentPrepared = bootstrap?.shellEnvironmentPrepared;
381 const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
382 const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
383 const desktopAppUpdate = bootstrap?.desktopAppUpdate;
384 const desktopBrowserFd = bootstrap?.desktopBrowserFd;
385 const desktopBrowserControlFd = bootstrap?.desktopBrowserControlFd;
386 const resourceMonitorPath = bootstrap?.resourceMonitorPath;
387 const autoBootstrapProjectFromCwd = Option.getOrElse(
388 resolveOptionPrecedence(
389 Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
390 isHeadlessStartup ? Option.some(false) : Option.none(),
391 normalizedFlags.autoBootstrapProjectFromCwd,
392 Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
393 ),
394 () => mode === "web",
395 );
396 const logWebSocketEvents = Option.getOrElse(
397 resolveOptionPrecedence(
398 normalizedFlags.logWebSocketEvents,
399 Option.fromUndefinedOr(env.logWebSocketEvents),
400 ),
401 () => Boolean(devUrl),
402 );
403 const tailscaleServeEnabled = Option.getOrElse(
404 resolveOptionPrecedence(
405 normalizedFlags.tailscaleServeEnabled,
406 Option.fromUndefinedOr(env.tailscaleServeEnabled),
407 Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
408 ),
409 () => false,
410 );
411 const tailscaleServePort = Option.getOrElse(
412 resolveOptionPrecedence(
413 normalizedFlags.tailscaleServePort,
414 Option.fromUndefinedOr(env.tailscaleServePort),
415 Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
416 ),
417 () => 443,
418 );
419 const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
420 const explicitHost = resolveOptionPrecedence(
421 normalizedFlags.host,
422 Option.fromUndefinedOr(env.host),
423 Option.fromUndefinedOr(bootstrap?.host),
424 ).pipe(Option.map((host) => (isWildcardHost(host) ? normalizeHostname(host) : host)));
425 // Private networks only, so clients learn a LAN address and prefer it over
426 // T3 Connect. `t3 service install` writes T3CODE_LAN=false for a new
427 // service; one installed before T3CODE_LAN existed keeps listening.
428 const lan = resolveOptionPrecedence(normalizedFlags.lan, Option.fromUndefinedOr(env.lan));
429 const privateNetworkOnly =
430 Option.isNone(explicitHost) &&
431 mode === "web" &&
432 (Option.isSome(lan)
433 ? lan.value
434 : yield* resolveServiceLauncherMode().pipe(
435 Effect.map((launcher) => launcher.managed),
436 Effect.orElseSucceed(() => false),
437 ));
438 const host = Option.getOrElse(explicitHost, () =>
439 privateNetworkOnly ? "0.0.0.0" : mode === "desktop" ? "127.0.0.1" : undefined,
440 );
441 const port = yield* Option.match(
442 resolveOptionPrecedence(
443 normalizedFlags.port,
444 Option.fromUndefinedOr(env.port),
445 Option.fromUndefinedOr(bootstrap?.port),
446 ),
447 {
448 onSome: (value) => Effect.succeed(value),
449 onNone: () => {
450 if (mode === "desktop") {
451 return Effect.succeed(ServerConfig.DEFAULT_PORT);
452 }
453 return selectAutomaticPort(ServerConfig.DEFAULT_PORT, host);
454 },
455 },
456 );
457 const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
458​
459 const otel = yield* OtelEnvironment.load;
460​
461 const signalExport: SignalExport = {
462 protocol: env.otlpProtocol,
463 headers: env.otlpHeaders,
464 exportIntervalMs: env.otlpExportIntervalMs,
465 };
466 const traces = OtelEnvironment.resolveSignalEndpoint(
467 otel,
468 "traces",
469 { url: env.otlpTracesUrl, export: signalExport },
470 {
471 bootstrapUrl: bootstrap?.otlpTracesUrl,
472 settingsUrl: persistedObservabilitySettings.otlpTracesUrl,
473 },
474 );
475 const metrics = OtelEnvironment.resolveSignalEndpoint(
476 otel,
477 "metrics",
478 { url: env.otlpMetricsUrl, export: signalExport },
479 {
480 bootstrapUrl: bootstrap?.otlpMetricsUrl,
481 settingsUrl: persistedObservabilitySettings.otlpMetricsUrl,
482 },
483 );
484 const logs = OtelEnvironment.resolveSignalEndpoint(
485 otel,
486 "logs",
487 { url: env.otlpLogsUrl, export: signalExport },
488 {
489 bootstrapUrl: bootstrap?.otlpLogsUrl,
490 settingsUrl: persistedObservabilitySettings.otlpLogsUrl,
491 },
492 );
493​
494 const config: ServerConfig.ServerConfig["Service"] = {
495 logLevel,
496 traceMinLevel: env.traceMinLevel,
497 traceTimingEnabled: env.traceTimingEnabled,
498 traceBatchWindowMs: env.traceBatchWindowMs,
499 traceMaxBytes: env.traceMaxBytes,
500 traceMaxFiles: env.traceMaxFiles,
501 otlpTracesUrl: traces?.url,
502 otlpMetricsUrl: metrics?.url,
503 otlpLogsUrl: logs?.url,
504 otlpTracesExport: traces?.export ?? signalExport,
505 otlpMetricsExport: metrics?.export ?? signalExport,
506 otlpLogsExport: logs?.export ?? signalExport,
507 ...(traces !== undefined ? { otlpTracesSource: traces.source } : {}),
508 ...(traces?.variable !== undefined ? { otlpTracesVariable: traces.variable } : {}),
509 ...(metrics !== undefined ? { otlpMetricsSource: metrics.source } : {}),
510 ...(metrics?.variable !== undefined ? { otlpMetricsVariable: metrics.variable } : {}),
511 ...(logs !== undefined ? { otlpLogsSource: logs.source } : {}),
512 ...(logs?.variable !== undefined ? { otlpLogsVariable: logs.variable } : {}),
513 otelEnvironment: otel,
514 mode,
515 port,
516 cwd,
517 baseDir,
518 ...derivedPaths,
519 serverTracePath,
520 host,
521 ...(privateNetworkOnly ? { privateNetworkOnly } : {}),
522 staticDir,
523 devUrl,
524 ...(devAuthToken === undefined ? {} : { devAuthToken }),
525 devAllowedOrigins: env.devAllowedOrigins,
526 noBrowser,
527 startupPresentation,
528 desktopBootstrapToken,
529 ...(desktopBootstrapSecret === undefined ? {} : { desktopBootstrapSecret }),
530 ...(desktopReadinessSecret === undefined ? {} : { desktopReadinessSecret }),
531 ...(shellEnvironmentPrepared === undefined ? {} : { shellEnvironmentPrepared }),
532 desktopTelemetryFd,
533 desktopTelemetryControlFd,
534 ...(desktopAppUpdate === undefined ? {} : { desktopAppUpdate }),
535 desktopBrowserFd,
536 desktopBrowserControlFd,
537 resourceMonitorPath,
538 autoBootstrapProjectFromCwd,
539 logWebSocketEvents,
540 tailscaleServeEnabled,
541 tailscaleServePort,
542 };
543​
544 return config;
545});
546​
547export const resolveCliAuthConfig = (
548 flags: CliAuthLocationFlags,
549 cliLogLevel: Option.Option<LogLevel.LogLevel>,
550 options?: { readonly quietLogs?: boolean },
551) => {
552 const resolved = resolveServerConfig(
553 {
554 mode: Option.none(),
555 port: Option.none(),
556 host: Option.none(),
557 baseDir: flags.baseDir,
558 cwd: Option.none(),
559 devUrl: flags.devUrl ?? Option.none(),
560 noBrowser: Option.none(),
561 bootstrapFd: Option.none(),
562 autoBootstrapProjectFromCwd: Option.none(),
563 logWebSocketEvents: Option.none(),
564 tailscaleServeEnabled: Option.none(),
565 tailscaleServePort: Option.none(),
566 lan: Option.none(),
567 },
568 cliLogLevel,
569 );
570 // Logs go to stdout, where --json and --token-only print, and resolving can
571 // log, for example when it sweeps abandoned attachment uploads.
572 return options?.quietLogs === true
573 ? resolved.pipe(Effect.provideService(References.MinimumLogLevel, "Error"))
574 : resolved;
575};
576​
577const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
578​
579const parseDurationInput = (value: string): Duration.Duration | null => {
580 const trimmed = value.trim();
581 if (trimmed.length === 0) return null;
582​
583 const shorthand = DurationShorthandPattern.exec(trimmed);
584 const normalizedInput = shorthand?.groups
585 ? (() => {
586 const amountText = shorthand.groups.value;
587 const unitText = shorthand.groups.unit;
588 if (typeof amountText !== "string" || typeof unitText !== "string") {
589 return null;
590 }
591​
592 const amount = Number.parseInt(amountText, 10);
593 if (!Number.isFinite(amount)) return null;
594​
595 switch (unitText.toLowerCase()) {
596 case "ms":
597 return `${amount} millis`;
598 case "s":
599 return `${amount} seconds`;
600 case "m":
601 return `${amount} minutes`;
602 case "h":
603 return `${amount} hours`;
604 case "d":
605 return `${amount} days`;
606 case "w":
607 return `${amount} weeks`;
608 default:
609 return null;
610 }
611 })()
612 : (trimmed as Duration.Input);
613​
614 if (normalizedInput === null) return null;
615​
616 const decoded = Duration.fromInput(normalizedInput as Duration.Input);
617 return Option.isSome(decoded) ? decoded.value : null;
618};
619​
620export const DurationFromString = Schema.String.pipe(
621 Schema.decodeTo(
622 Schema.Duration,
623 SchemaTransformation.transformEffect({
624 decode: (value) => {
625 const duration = parseDurationInput(value);
626 if (duration !== null) {
627 return Effect.succeed(duration);
628 }
629 return Effect.fail(
630 new SchemaIssue.InvalidValue({
631 message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
632 }),
633 );
634 },
635 encode: (duration) => Effect.succeed(Duration.format(duration)),
636 }),
637 ),
638);