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

config.ts

624 lines22.9 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 readonly selectAutomaticPort?: (
271 preferred: number,
272 ) => Effect.Effect<number, NetService.NetError | CliError.UserError>;
273 },
274) {
275 const { findAvailablePort } = yield* NetService.NetService;
276 const selectAutomaticPort = options?.selectAutomaticPort ?? findAvailablePort;
277 const path = yield* Path.Path;
278 const fs = yield* FileSystem.FileSystem;
279 const env = yield* EnvServerConfig;
280 const normalizedFlags = {
281 mode: flags.mode ?? Option.none(),
282 port: flags.port ?? Option.none(),
283 host: flags.host ?? Option.none(),
284 baseDir: flags.baseDir ?? Option.none(),
285 cwd: flags.cwd ?? Option.none(),
286 devUrl: flags.devUrl ?? Option.none(),
287 noBrowser: flags.noBrowser ?? Option.none(),
288 bootstrapFd: flags.bootstrapFd ?? Option.none(),
289 autoBootstrapProjectFromCwd: flags.autoBootstrapProjectFromCwd ?? Option.none(),
290 logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
291 tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
292 tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
293 lan: flags.lan ?? Option.none(),
294 } satisfies CliServerFlags;
295 const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
296 const bootstrapEnvelope =
297 bootstrapFd !== undefined
298 ? yield* readBootstrapEnvelope(DesktopBackendBootstrap, bootstrapFd)
299 : Option.none();
300 const bootstrap = Option.getOrUndefined(bootstrapEnvelope);
301​
302 const mode: ServerConfig.RuntimeMode = Option.getOrElse(
303 resolveOptionPrecedence(
304 normalizedFlags.mode,
305 Option.fromUndefinedOr(env.mode),
306 Option.fromUndefinedOr(bootstrap?.mode),
307 ),
308 () => "web",
309 );
310​
311 const port = yield* Option.match(
312 resolveOptionPrecedence(
313 normalizedFlags.port,
314 Option.fromUndefinedOr(env.port),
315 Option.fromUndefinedOr(bootstrap?.port),
316 ),
317 {
318 onSome: (value) => Effect.succeed(value),
319 onNone: () => {
320 if (mode === "desktop") {
321 return Effect.succeed(ServerConfig.DEFAULT_PORT);
322 }
323 return selectAutomaticPort(ServerConfig.DEFAULT_PORT);
324 },
325 },
326 );
327 const devUrl = Option.getOrElse(
328 resolveOptionPrecedence(normalizedFlags.devUrl, Option.fromUndefinedOr(env.devUrl)),
329 () => undefined,
330 );
331 const devAuthToken =
332 mode === "web" && devUrl !== undefined ? yield* DevAuthTokenConfig : undefined;
333 const explicitBaseDir = resolveOptionPrecedence(
334 normalizedFlags.baseDir,
335 Option.fromUndefinedOr(env.t3Home),
336 ).pipe(Option.filter((value) => value.trim().length > 0));
337 const baseDir = yield* resolveBaseDir(
338 Option.getOrUndefined(
339 resolveOptionPrecedence(explicitBaseDir, Option.fromUndefinedOr(bootstrap?.t3Home)),
340 ),
341 );
342 const rawCwd = Option.getOrElse(normalizedFlags.cwd, () => process.cwd());
343 const cwd = path.resolve(yield* expandHomePath(rawCwd.trim()));
344 const derivedPaths = yield* ServerConfig.deriveServerPaths(baseDir, devUrl, {
345 baseDirIsExplicit: Option.isSome(explicitBaseDir),
346 });
347 // An interactive CLI must not start over a discovered server. Lifetime locking
348 // and supervisor handoff are separate; this preflight cannot arbitrate two starts.
349 if (options?.rejectRunningServer && mode === "web") {
350 const runtime = yield* readPersistedServerRuntimeState(derivedPaths.serverRuntimeStatePath);
351 // A killed container can leave a record with the new server's own PID.
352 if (
353 Option.isSome(runtime) &&
354 runtime.value.pid > 0 &&
355 runtime.value.pid !== process.pid &&
356 isProcessAlive(runtime.value.pid)
357 ) {
358 return yield* new CliError.UserError({
359 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.`,
360 });
361 }
362 }
363 yield* fs.makeDirectory(cwd, { recursive: true });
364 yield* ServerConfig.ensureServerDirectories(derivedPaths);
365 const persistedObservabilitySettings = yield* loadPersistedObservabilitySettings(
366 derivedPaths.settingsPath,
367 );
368 const serverTracePath = env.traceFile ?? derivedPaths.serverTracePath;
369 yield* fs.makeDirectory(path.dirname(serverTracePath), { recursive: true });
370 const startupPresentation = options?.startupPresentation ?? "browser";
371 const isHeadlessStartup = startupPresentation === "headless";
372 const noBrowser = Option.getOrElse(
373 resolveOptionPrecedence(
374 isHeadlessStartup ? Option.some(true) : Option.none(),
375 normalizedFlags.noBrowser,
376 Option.fromUndefinedOr(env.noBrowser),
377 Option.fromUndefinedOr(bootstrap?.noBrowser),
378 ),
379 () => mode === "desktop",
380 );
381 const desktopBootstrapToken = bootstrap?.desktopBootstrapToken;
382 const desktopBootstrapSecret = bootstrap?.desktopBootstrapSecret;
383 const shellEnvironmentPrepared = bootstrap?.shellEnvironmentPrepared;
384 const desktopTelemetryFd = bootstrap?.desktopTelemetryFd;
385 const desktopTelemetryControlFd = bootstrap?.desktopTelemetryControlFd;
386 const desktopAppUpdate = bootstrap?.desktopAppUpdate;
387 const desktopBrowserFd = bootstrap?.desktopBrowserFd;
388 const desktopBrowserControlFd = bootstrap?.desktopBrowserControlFd;
389 const resourceMonitorPath = bootstrap?.resourceMonitorPath;
390 const autoBootstrapProjectFromCwd = Option.getOrElse(
391 resolveOptionPrecedence(
392 Option.fromUndefinedOr(options?.forceAutoBootstrapProjectFromCwd),
393 isHeadlessStartup ? Option.some(false) : Option.none(),
394 normalizedFlags.autoBootstrapProjectFromCwd,
395 Option.fromUndefinedOr(env.autoBootstrapProjectFromCwd),
396 ),
397 () => mode === "web",
398 );
399 const logWebSocketEvents = Option.getOrElse(
400 resolveOptionPrecedence(
401 normalizedFlags.logWebSocketEvents,
402 Option.fromUndefinedOr(env.logWebSocketEvents),
403 ),
404 () => Boolean(devUrl),
405 );
406 const tailscaleServeEnabled = Option.getOrElse(
407 resolveOptionPrecedence(
408 normalizedFlags.tailscaleServeEnabled,
409 Option.fromUndefinedOr(env.tailscaleServeEnabled),
410 Option.fromUndefinedOr(bootstrap?.tailscaleServeEnabled),
411 ),
412 () => false,
413 );
414 const tailscaleServePort = Option.getOrElse(
415 resolveOptionPrecedence(
416 normalizedFlags.tailscaleServePort,
417 Option.fromUndefinedOr(env.tailscaleServePort),
418 Option.fromUndefinedOr(bootstrap?.tailscaleServePort),
419 ),
420 () => 443,
421 );
422 const staticDir = devUrl ? undefined : yield* ServerConfig.resolveStaticDir();
423 const explicitHost = resolveOptionPrecedence(
424 normalizedFlags.host,
425 Option.fromUndefinedOr(env.host),
426 Option.fromUndefinedOr(bootstrap?.host),
427 );
428 // Private networks only, so clients learn a LAN address and prefer it over
429 // T3 Connect. `t3 service install` writes T3CODE_LAN=false for a new
430 // service; one installed before T3CODE_LAN existed keeps listening.
431 const lan = resolveOptionPrecedence(normalizedFlags.lan, Option.fromUndefinedOr(env.lan));
432 const privateNetworkOnly =
433 Option.isNone(explicitHost) &&
434 mode === "web" &&
435 (Option.isSome(lan)
436 ? lan.value
437 : yield* resolveServiceLauncherMode().pipe(
438 Effect.map((launcher) => launcher.managed),
439 Effect.orElseSucceed(() => false),
440 ));
441 const host = Option.getOrElse(explicitHost, () =>
442 privateNetworkOnly ? "0.0.0.0" : mode === "desktop" ? "127.0.0.1" : undefined,
443 );
444 const logLevel = Option.getOrElse(cliLogLevel, () => env.logLevel);
445​
446 const otel = yield* OtelEnvironment.load;
447​
448 const signalExport: SignalExport = {
449 protocol: env.otlpProtocol,
450 headers: env.otlpHeaders,
451 exportIntervalMs: env.otlpExportIntervalMs,
452 };
453 const traces = OtelEnvironment.resolveSignalEndpoint(
454 otel,
455 "traces",
456 { url: env.otlpTracesUrl, export: signalExport },
457 {
458 bootstrapUrl: bootstrap?.otlpTracesUrl,
459 settingsUrl: persistedObservabilitySettings.otlpTracesUrl,
460 },
461 );
462 const metrics = OtelEnvironment.resolveSignalEndpoint(
463 otel,
464 "metrics",
465 { url: env.otlpMetricsUrl, export: signalExport },
466 {
467 bootstrapUrl: bootstrap?.otlpMetricsUrl,
468 settingsUrl: persistedObservabilitySettings.otlpMetricsUrl,
469 },
470 );
471 const logs = OtelEnvironment.resolveSignalEndpoint(
472 otel,
473 "logs",
474 { url: env.otlpLogsUrl, export: signalExport },
475 {
476 bootstrapUrl: bootstrap?.otlpLogsUrl,
477 settingsUrl: persistedObservabilitySettings.otlpLogsUrl,
478 },
479 );
480​
481 const config: ServerConfig.ServerConfig["Service"] = {
482 logLevel,
483 traceMinLevel: env.traceMinLevel,
484 traceTimingEnabled: env.traceTimingEnabled,
485 traceBatchWindowMs: env.traceBatchWindowMs,
486 traceMaxBytes: env.traceMaxBytes,
487 traceMaxFiles: env.traceMaxFiles,
488 otlpTracesUrl: traces?.url,
489 otlpMetricsUrl: metrics?.url,
490 otlpLogsUrl: logs?.url,
491 otlpTracesExport: traces?.export ?? signalExport,
492 otlpMetricsExport: metrics?.export ?? signalExport,
493 otlpLogsExport: logs?.export ?? signalExport,
494 ...(traces !== undefined ? { otlpTracesSource: traces.source } : {}),
495 ...(traces?.variable !== undefined ? { otlpTracesVariable: traces.variable } : {}),
496 ...(metrics !== undefined ? { otlpMetricsSource: metrics.source } : {}),
497 ...(metrics?.variable !== undefined ? { otlpMetricsVariable: metrics.variable } : {}),
498 ...(logs !== undefined ? { otlpLogsSource: logs.source } : {}),
499 ...(logs?.variable !== undefined ? { otlpLogsVariable: logs.variable } : {}),
500 otelEnvironment: otel,
501 mode,
502 port,
503 cwd,
504 baseDir,
505 ...derivedPaths,
506 serverTracePath,
507 host,
508 ...(privateNetworkOnly ? { privateNetworkOnly } : {}),
509 staticDir,
510 devUrl,
511 ...(devAuthToken === undefined ? {} : { devAuthToken }),
512 devAllowedOrigins: env.devAllowedOrigins,
513 noBrowser,
514 startupPresentation,
515 desktopBootstrapToken,
516 ...(desktopBootstrapSecret === undefined ? {} : { desktopBootstrapSecret }),
517 ...(shellEnvironmentPrepared === undefined ? {} : { shellEnvironmentPrepared }),
518 desktopTelemetryFd,
519 desktopTelemetryControlFd,
520 ...(desktopAppUpdate === undefined ? {} : { desktopAppUpdate }),
521 desktopBrowserFd,
522 desktopBrowserControlFd,
523 resourceMonitorPath,
524 autoBootstrapProjectFromCwd,
525 logWebSocketEvents,
526 tailscaleServeEnabled,
527 tailscaleServePort,
528 };
529​
530 return config;
531});
532​
533export const resolveCliAuthConfig = (
534 flags: CliAuthLocationFlags,
535 cliLogLevel: Option.Option<LogLevel.LogLevel>,
536 options?: { readonly quietLogs?: boolean },
537) => {
538 const resolved = resolveServerConfig(
539 {
540 mode: Option.none(),
541 port: Option.none(),
542 host: Option.none(),
543 baseDir: flags.baseDir,
544 cwd: Option.none(),
545 devUrl: flags.devUrl ?? Option.none(),
546 noBrowser: Option.none(),
547 bootstrapFd: Option.none(),
548 autoBootstrapProjectFromCwd: Option.none(),
549 logWebSocketEvents: Option.none(),
550 tailscaleServeEnabled: Option.none(),
551 tailscaleServePort: Option.none(),
552 lan: Option.none(),
553 },
554 cliLogLevel,
555 );
556 // Logs go to stdout, where --json and --token-only print, and resolving can
557 // log, for example when it sweeps abandoned attachment uploads.
558 return options?.quietLogs === true
559 ? resolved.pipe(Effect.provideService(References.MinimumLogLevel, "Error"))
560 : resolved;
561};
562​
563const DurationShorthandPattern = /^(?<value>\d+)(?<unit>ms|s|m|h|d|w)$/i;
564​
565const parseDurationInput = (value: string): Duration.Duration | null => {
566 const trimmed = value.trim();
567 if (trimmed.length === 0) return null;
568​
569 const shorthand = DurationShorthandPattern.exec(trimmed);
570 const normalizedInput = shorthand?.groups
571 ? (() => {
572 const amountText = shorthand.groups.value;
573 const unitText = shorthand.groups.unit;
574 if (typeof amountText !== "string" || typeof unitText !== "string") {
575 return null;
576 }
577​
578 const amount = Number.parseInt(amountText, 10);
579 if (!Number.isFinite(amount)) return null;
580​
581 switch (unitText.toLowerCase()) {
582 case "ms":
583 return `${amount} millis`;
584 case "s":
585 return `${amount} seconds`;
586 case "m":
587 return `${amount} minutes`;
588 case "h":
589 return `${amount} hours`;
590 case "d":
591 return `${amount} days`;
592 case "w":
593 return `${amount} weeks`;
594 default:
595 return null;
596 }
597 })()
598 : (trimmed as Duration.Input);
599​
600 if (normalizedInput === null) return null;
601​
602 const decoded = Duration.fromInput(normalizedInput as Duration.Input);
603 return Option.isSome(decoded) ? decoded.value : null;
604};
605​
606export const DurationFromString = Schema.String.pipe(
607 Schema.decodeTo(
608 Schema.Duration,
609 SchemaTransformation.transformEffect({
610 decode: (value) => {
611 const duration = parseDurationInput(value);
612 if (duration !== null) {
613 return Effect.succeed(duration);
614 }
615 return Effect.fail(
616 new SchemaIssue.InvalidValue({
617 message: "Invalid duration. Use values like 5m, 1h, 30d, or 15 minutes.",
618 }),
619 );
620 },
621 encode: (duration) => Effect.succeed(Duration.format(duration)),
622 }),
623 ),
624);