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

config.ts

634 lines23.5 KB

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