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

config.ts

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