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

config.ts

654 lines24.4 KB

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