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