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