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