The best way to control Claude Code, Codex and more from any computer or phone
| 1 | #!/usr/bin/env node |
| 2 | |
| 3 | import * as NodeOS from "node:os"; |
| 4 | |
| 5 | import * as NodeRuntime from "@effect/platform-node/NodeRuntime"; |
| 6 | import * as NodeServices from "@effect/platform-node/NodeServices"; |
| 7 | import * as NetService from "@t3tools/shared/Net"; |
| 8 | import { resolveGitWorktreePath, resolveWorktreeT3Home } from "@t3tools/shared/devHome"; |
| 9 | import * as HostProcess from "@t3tools/shared/HostProcess"; |
| 10 | import { resolveSpawnCommand } from "@t3tools/shared/shell"; |
| 11 | import * as Config from "effect/Config"; |
| 12 | import * as Effect from "effect/Effect"; |
| 13 | import * as FileSystem from "effect/FileSystem"; |
| 14 | import * as Hash from "effect/Hash"; |
| 15 | import * as Layer from "effect/Layer"; |
| 16 | import * as Logger from "effect/Logger"; |
| 17 | import * as Option from "effect/Option"; |
| 18 | import * as Path from "effect/Path"; |
| 19 | import * as Schema from "effect/Schema"; |
| 20 | import { Argument, Command, Flag } from "effect/cli"; |
| 21 | import { ChildProcess } from "effect/process"; |
| 22 | |
| 23 | import { defaultDevMemoryLimitBytes, enforceDevMemoryLimit } from "./lib/dev-memory-limit.ts"; |
| 24 | import { type DevShareError, shareDevServer, unshareDevServer } from "./lib/dev-share.ts"; |
| 25 | import { loadRepoEnv } from "./lib/public-config.ts"; |
| 26 | |
| 27 | Object.assign(process.env, loadRepoEnv()); |
| 28 | |
| 29 | const BASE_SERVER_PORT = 13773; |
| 30 | const BASE_WEB_PORT = 5733; |
| 31 | const MAX_HASH_OFFSET = 3000; |
| 32 | const MAX_PORT = 65535; |
| 33 | const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1"; |
| 34 | // Browsers block these ports before networking even when curl accepts them. |
| 35 | // https://fetch.spec.whatwg.org/#port-blocking |
| 36 | const FETCH_BAD_PORTS = new Set([ |
| 37 | 0, 1, 7, 9, 11, 13, 15, 17, 19, 20, 21, 22, 23, 25, 37, 42, 43, 53, 69, 77, 79, 87, 95, 101, 102, |
| 38 | 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465, |
| 39 | 512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993, |
| 40 | 995, 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668, |
| 41 | 6669, 6679, 6697, 10080, |
| 42 | ]); |
| 43 | // Dev binds loopback; other interfaces cannot establish port availability. |
| 44 | const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "::1"] as const; |
| 45 | // Migration prunes after copying, so large sources also need an automatic-seeding limit. |
| 46 | const LARGE_DEV_DATABASE_BYTES = 500 * 1024 * 1024; |
| 47 | |
| 48 | /** Only loopback and wildcard binds keep the loopback proxy target reachable. */ |
| 49 | export function isProxiableBindHost(host: string): boolean { |
| 50 | const normalized = host.trim(); |
| 51 | return ( |
| 52 | normalized === "" || |
| 53 | normalized === "localhost" || |
| 54 | normalized === "127.0.0.1" || |
| 55 | normalized === "::1" || |
| 56 | normalized === "[::1]" || |
| 57 | normalized === "0.0.0.0" || |
| 58 | normalized === "::" || |
| 59 | normalized === "[::]" |
| 60 | ); |
| 61 | } |
| 62 | |
| 63 | function sharedBackendTargetHost(host: string | undefined): string { |
| 64 | const normalized = host?.trim() ?? ""; |
| 65 | if (normalized === "::1" || normalized === "[::1]") return "[::1]"; |
| 66 | if (normalized === "localhost") return "localhost"; |
| 67 | return "127.0.0.1"; |
| 68 | } |
| 69 | |
| 70 | export const DEFAULT_T3_HOME = Effect.map(Effect.service(Path.Path), (path) => |
| 71 | path.join(NodeOS.homedir(), ".t3"), |
| 72 | ); |
| 73 | |
| 74 | const MODE_ARGS = { |
| 75 | dev: [ |
| 76 | "run", |
| 77 | "--filter=@t3tools/contracts", |
| 78 | "--filter=@t3tools/web", |
| 79 | "--filter=t3", |
| 80 | "--parallel", |
| 81 | "dev", |
| 82 | ], |
| 83 | "dev:server": ["run", "--filter=t3", "dev"], |
| 84 | "dev:web": ["run", "--filter=@t3tools/web", "dev"], |
| 85 | "dev:desktop": ["run", "--filter=@t3tools/desktop", "--filter=@t3tools/web", "dev"], |
| 86 | } as const satisfies Record<string, ReadonlyArray<string>>; |
| 87 | |
| 88 | // `--built`: the web package rebuilds into apps/web/dist and the backend serves |
| 89 | // it, so no Vite dev server runs. |
| 90 | const BUILT_DEV_ARGS = [ |
| 91 | "run", |
| 92 | "--filter=@t3tools/web", |
| 93 | "--filter=t3", |
| 94 | "--parallel", |
| 95 | "dev:built", |
| 96 | ] as const; |
| 97 | |
| 98 | type DevMode = keyof typeof MODE_ARGS; |
| 99 | // Only backend ports honor --host/T3CODE_HOST; web ports stay loopback. |
| 100 | type PortAvailabilityCheck<R = never> = ( |
| 101 | port: number, |
| 102 | role?: "server" | "web", |
| 103 | ) => Effect.Effect<boolean, never, R>; |
| 104 | |
| 105 | const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>; |
| 106 | |
| 107 | export function isBrowserAllowedPort(port: number): boolean { |
| 108 | return !FETCH_BAD_PORTS.has(port); |
| 109 | } |
| 110 | |
| 111 | export class DevRunnerConfigurationError extends Schema.TaggedError<DevRunnerConfigurationError>()( |
| 112 | "DevRunnerConfigurationError", |
| 113 | { |
| 114 | configKeys: Schema.Array(Schema.String), |
| 115 | cause: Schema.Defect(), |
| 116 | }, |
| 117 | ) { |
| 118 | override get message(): string { |
| 119 | return `Failed to read dev-runner configuration: ${this.configKeys.join(", ")}.`; |
| 120 | } |
| 121 | } |
| 122 | |
| 123 | export class DevRunnerInvalidPortOffsetError extends Schema.TaggedError<DevRunnerInvalidPortOffsetError>()( |
| 124 | "DevRunnerInvalidPortOffsetError", |
| 125 | { |
| 126 | configKey: Schema.Literal("T3CODE_PORT_OFFSET"), |
| 127 | portOffset: Schema.Number, |
| 128 | minimum: Schema.Number, |
| 129 | }, |
| 130 | ) { |
| 131 | override get message(): string { |
| 132 | return `${this.configKey} must be at least ${this.minimum}; received ${this.portOffset}.`; |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | export class DevRunnerPortExhaustedError extends Schema.TaggedError<DevRunnerPortExhaustedError>()( |
| 137 | "DevRunnerPortExhaustedError", |
| 138 | { |
| 139 | startOffset: Schema.Number, |
| 140 | requireServerPort: Schema.Boolean, |
| 141 | requireWebPort: Schema.Boolean, |
| 142 | baseServerPort: Schema.Number, |
| 143 | baseWebPort: Schema.Number, |
| 144 | maximumPort: Schema.Number, |
| 145 | }, |
| 146 | ) { |
| 147 | override get message(): string { |
| 148 | return `No required dev ports were available from offset ${this.startOffset} through maximum port ${this.maximumPort}.`; |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | export class DevRunnerProcessError extends Schema.TaggedError<DevRunnerProcessError>()( |
| 153 | "DevRunnerProcessError", |
| 154 | { |
| 155 | operation: Schema.Literals(["spawn", "wait-for-exit"]), |
| 156 | mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]), |
| 157 | executable: Schema.Literal("vp"), |
| 158 | argumentCount: Schema.Number, |
| 159 | shell: Schema.Boolean, |
| 160 | cause: Schema.Defect(), |
| 161 | }, |
| 162 | ) { |
| 163 | override get message(): string { |
| 164 | return `Dev-runner process operation "${this.operation}" failed for mode "${this.mode}".`; |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | export class DevRunnerProcessExitError extends Schema.TaggedError<DevRunnerProcessExitError>()( |
| 169 | "DevRunnerProcessExitError", |
| 170 | { |
| 171 | mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]), |
| 172 | executable: Schema.Literal("vp"), |
| 173 | argumentCount: Schema.Number, |
| 174 | shell: Schema.Boolean, |
| 175 | exitCode: Schema.Number, |
| 176 | }, |
| 177 | ) { |
| 178 | override get message(): string { |
| 179 | return `Dev-runner process exited with code ${this.exitCode} in mode "${this.mode}".`; |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | export class DevRunnerHostNotProxiableError extends Schema.TaggedError<DevRunnerHostNotProxiableError>()( |
| 184 | "DevRunnerHostNotProxiableError", |
| 185 | { |
| 186 | mode: Schema.Literals(["dev", "dev:web"]), |
| 187 | host: Schema.String, |
| 188 | }, |
| 189 | ) { |
| 190 | override get message(): string { |
| 191 | return `--host ${this.host} cannot be combined with ${this.mode}: single-origin browser dev proxies the backend at localhost, and a backend bound only to ${this.host} leaves localhost unanswered, so every proxied request fails. Use a wildcard (0.0.0.0 or ::) to serve that interface and loopback together, or --share for remote access.`; |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | export class DevRunnerBuiltNeedsShareError extends Schema.TaggedError<DevRunnerBuiltNeedsShareError>()( |
| 196 | "DevRunnerBuiltNeedsShareError", |
| 197 | { |
| 198 | mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]), |
| 199 | }, |
| 200 | ) { |
| 201 | override get message(): string { |
| 202 | return `--built only works with \`dev --share\` (got ${this.mode}${this.mode === "dev" ? " without --share" : ""}): the backend serves the built client on the tailnet URL.`; |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | const optionalStringConfig = (name: string): Config.Config<string | undefined> => |
| 207 | Config.String(name).pipe( |
| 208 | Config.option, |
| 209 | Config.map((value) => Option.getOrUndefined(value)), |
| 210 | ); |
| 211 | const optionalBooleanConfig = (name: string): Config.Config<boolean | undefined> => |
| 212 | Config.Boolean(name).pipe( |
| 213 | Config.option, |
| 214 | Config.map((value) => Option.getOrUndefined(value)), |
| 215 | ); |
| 216 | const optionalIntegerConfig = (name: string): Config.Config<number | undefined> => |
| 217 | Config.Int(name).pipe( |
| 218 | Config.option, |
| 219 | Config.map((value) => Option.getOrUndefined(value)), |
| 220 | ); |
| 221 | const OffsetConfig = Config.all({ |
| 222 | portOffset: optionalIntegerConfig("T3CODE_PORT_OFFSET"), |
| 223 | devInstance: optionalStringConfig("T3CODE_DEV_INSTANCE"), |
| 224 | }); |
| 225 | |
| 226 | export function resolveOffset(config: { |
| 227 | readonly portOffset: number | undefined; |
| 228 | readonly devInstance: string | undefined; |
| 229 | readonly worktreePath?: string | undefined; |
| 230 | }): Effect.Effect< |
| 231 | { readonly offset: number; readonly source: string }, |
| 232 | DevRunnerInvalidPortOffsetError |
| 233 | > { |
| 234 | if (config.portOffset !== undefined) { |
| 235 | if (config.portOffset < 0) { |
| 236 | return Effect.fail( |
| 237 | new DevRunnerInvalidPortOffsetError({ |
| 238 | configKey: "T3CODE_PORT_OFFSET", |
| 239 | portOffset: config.portOffset, |
| 240 | minimum: 0, |
| 241 | }), |
| 242 | ); |
| 243 | } |
| 244 | return Effect.succeed({ |
| 245 | offset: config.portOffset, |
| 246 | source: `T3CODE_PORT_OFFSET=${config.portOffset}`, |
| 247 | }); |
| 248 | } |
| 249 | |
| 250 | const seed = config.devInstance?.trim(); |
| 251 | if (seed) { |
| 252 | if (/^\d+$/.test(seed)) { |
| 253 | return Effect.succeed({ |
| 254 | offset: Number(seed), |
| 255 | source: `numeric T3CODE_DEV_INSTANCE=${seed}`, |
| 256 | }); |
| 257 | } |
| 258 | |
| 259 | const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1; |
| 260 | return Effect.succeed({ offset, source: `hashed T3CODE_DEV_INSTANCE=${seed}` }); |
| 261 | } |
| 262 | |
| 263 | const worktreePath = config.worktreePath?.trim(); |
| 264 | if (worktreePath) { |
| 265 | const offset = ((Hash.string(worktreePath) >>> 0) % MAX_HASH_OFFSET) + 1; |
| 266 | return Effect.succeed({ offset, source: `worktree ${worktreePath}` }); |
| 267 | } |
| 268 | |
| 269 | return Effect.succeed({ offset: 0, source: "default ports" }); |
| 270 | } |
| 271 | |
| 272 | const resolveBaseDir = Effect.fn("dev-runner.resolveBaseDir")(function* ( |
| 273 | baseDir: string | undefined, |
| 274 | ): Effect.fn.Return<string, never, Path.Path> { |
| 275 | const path = yield* Path.Path; |
| 276 | const configured = baseDir?.trim(); |
| 277 | |
| 278 | if (configured === "~") { |
| 279 | return yield* HostProcess.HomeDirectory; |
| 280 | } |
| 281 | if (configured?.startsWith("~/") || configured?.startsWith("~\\")) { |
| 282 | return path.join(yield* HostProcess.HomeDirectory, configured.slice(2)); |
| 283 | } |
| 284 | if (configured) { |
| 285 | return path.resolve(configured); |
| 286 | } |
| 287 | |
| 288 | return yield* DEFAULT_T3_HOME; |
| 289 | }); |
| 290 | |
| 291 | interface CreateDevRunnerEnvInput { |
| 292 | readonly mode: DevMode; |
| 293 | readonly baseEnv: NodeJS.ProcessEnv; |
| 294 | readonly serverOffset: number; |
| 295 | readonly webOffset: number; |
| 296 | readonly t3Home: string | undefined; |
| 297 | readonly browser: boolean | undefined; |
| 298 | readonly autoBootstrapProjectFromCwd: boolean | undefined; |
| 299 | readonly logWebSocketEvents: boolean | undefined; |
| 300 | readonly host: string | undefined; |
| 301 | readonly port: number | undefined; |
| 302 | readonly devUrl: URL | undefined; |
| 303 | } |
| 304 | |
| 305 | export const createDevRunnerEnv = Effect.fn("dev-runner.createDevRunnerEnv")(function* ({ |
| 306 | mode, |
| 307 | baseEnv, |
| 308 | serverOffset, |
| 309 | webOffset, |
| 310 | t3Home, |
| 311 | browser, |
| 312 | autoBootstrapProjectFromCwd, |
| 313 | logWebSocketEvents, |
| 314 | host, |
| 315 | port, |
| 316 | devUrl, |
| 317 | }: CreateDevRunnerEnvInput): Effect.fn.Return<NodeJS.ProcessEnv, never, Path.Path> { |
| 318 | const serverPort = port ?? BASE_SERVER_PORT + serverOffset; |
| 319 | const webPort = BASE_WEB_PORT + webOffset; |
| 320 | const configuredBaseDir = t3Home?.trim() || undefined; |
| 321 | const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir); |
| 322 | const isDesktopMode = mode === "dev:desktop"; |
| 323 | |
| 324 | const output: NodeJS.ProcessEnv = { |
| 325 | ...baseEnv, |
| 326 | PORT: String(webPort), |
| 327 | VITE_DEV_SERVER_URL: |
| 328 | devUrl?.toString() ?? |
| 329 | `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`, |
| 330 | }; |
| 331 | |
| 332 | const path = yield* Path.Path; |
| 333 | // The server stores an explicit home's state in userdata, which for ~/.t3 is the live |
| 334 | // install. Left implicit, dev state goes to ~/.t3/dev. |
| 335 | const isLiveHome = resolvedBaseDir === path.join(yield* HostProcess.HomeDirectory, ".t3"); |
| 336 | if (configuredBaseDir !== undefined && !isLiveHome) { |
| 337 | output.T3CODE_HOME = resolvedBaseDir; |
| 338 | } else { |
| 339 | delete output.T3CODE_HOME; |
| 340 | } |
| 341 | |
| 342 | // Managed T3 service shells leak launcher variables that make dev servers fail version checks. |
| 343 | // Dev-runner servers are never launcher-managed (serviceLauncherClient.ts resolveStartup). |
| 344 | delete output.T3_SERVICE_LAUNCHER_CONTEXT; |
| 345 | delete output.T3_BOOT_SERVICE_UNIT; |
| 346 | |
| 347 | // Each worktree has its own state, so a dev server would count as a new |
| 348 | // install of the developer's real accounts. Set it explicitly to opt in. |
| 349 | output.T3CODE_TELEMETRY_ENABLED = baseEnv.T3CODE_TELEMETRY_ENABLED ?? "false"; |
| 350 | |
| 351 | if (!isDesktopMode) { |
| 352 | output.T3CODE_PORT = String(serverPort); |
| 353 | // An inherited HOST pins Vite's HMR socket via explicitHost in apps/web/vite.config.ts. |
| 354 | // Only desktop mode should set it. |
| 355 | delete output.HOST; |
| 356 | if (mode === "dev" || mode === "dev:web") { |
| 357 | // Browser dev is single-origin: everything (including /ws) is proxied |
| 358 | // through Vite, so the client must resolve its backend from |
| 359 | // window.location.origin rather than a baked-in localhost URL. |
| 360 | delete output.VITE_HTTP_URL; |
| 361 | delete output.VITE_WS_URL; |
| 362 | // Deleting is not enough on its own: vite.config.ts calls loadRepoEnv, |
| 363 | // which merges `.env`/`.env.local` *under* this env, so a developer |
| 364 | // with either URL in their `.env` would get it back and silently lose |
| 365 | // single-origin mode. |
| 366 | output.T3CODE_SINGLE_ORIGIN_DEV = "1"; |
| 367 | } else { |
| 368 | output.VITE_HTTP_URL = `http://localhost:${serverPort}`; |
| 369 | output.VITE_WS_URL = `ws://localhost:${serverPort}`; |
| 370 | delete output.T3CODE_SINGLE_ORIGIN_DEV; |
| 371 | } |
| 372 | } else { |
| 373 | output.T3CODE_PORT = String(serverPort); |
| 374 | output.VITE_HTTP_URL = `http://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`; |
| 375 | output.VITE_WS_URL = `ws://${DESKTOP_DEV_LOOPBACK_HOST}:${serverPort}`; |
| 376 | // Desktop pins the renderer to loopback on purpose; an ambient marker |
| 377 | // must not make Vite drop those URLs. |
| 378 | delete output.T3CODE_SINGLE_ORIGIN_DEV; |
| 379 | delete output.T3CODE_MODE; |
| 380 | delete output.T3CODE_NO_BROWSER; |
| 381 | delete output.T3CODE_DEV_AUTH_TOKEN; |
| 382 | } |
| 383 | |
| 384 | // Agent shells inherit the parent T3 server's bind settings; only --host widens the dev server. |
| 385 | delete output.T3CODE_LAN; |
| 386 | if (!isDesktopMode && host !== undefined) { |
| 387 | output.T3CODE_HOST = host; |
| 388 | } else { |
| 389 | delete output.T3CODE_HOST; |
| 390 | } |
| 391 | |
| 392 | if (!isDesktopMode) { |
| 393 | output.T3CODE_NO_BROWSER = browser === true ? "0" : "1"; |
| 394 | } |
| 395 | |
| 396 | if (autoBootstrapProjectFromCwd !== undefined) { |
| 397 | output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0"; |
| 398 | } else { |
| 399 | delete output.T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD; |
| 400 | } |
| 401 | |
| 402 | if (logWebSocketEvents !== undefined) { |
| 403 | output.T3CODE_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0"; |
| 404 | } else { |
| 405 | delete output.T3CODE_LOG_WS_EVENTS; |
| 406 | } |
| 407 | |
| 408 | if (mode === "dev") { |
| 409 | output.T3CODE_MODE = "web"; |
| 410 | delete output.T3CODE_DESKTOP_WS_URL; |
| 411 | } |
| 412 | |
| 413 | if (mode === "dev:server" || mode === "dev:web") { |
| 414 | output.T3CODE_MODE = "web"; |
| 415 | delete output.T3CODE_DESKTOP_WS_URL; |
| 416 | } |
| 417 | |
| 418 | if (isDesktopMode) { |
| 419 | output.HOST = DESKTOP_DEV_LOOPBACK_HOST; |
| 420 | delete output.T3CODE_DESKTOP_WS_URL; |
| 421 | } |
| 422 | |
| 423 | return output; |
| 424 | }); |
| 425 | |
| 426 | function portPairForOffset(offset: number): { |
| 427 | readonly serverPort: number; |
| 428 | readonly webPort: number; |
| 429 | } { |
| 430 | return { |
| 431 | serverPort: BASE_SERVER_PORT + offset, |
| 432 | webPort: BASE_WEB_PORT + offset, |
| 433 | }; |
| 434 | } |
| 435 | |
| 436 | export const checkPortAvailabilityOnHosts = Effect.fn("dev-runner.checkPortAvailabilityOnHosts")( |
| 437 | function* <R>( |
| 438 | port: number, |
| 439 | hosts: ReadonlyArray<string>, |
| 440 | canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>, |
| 441 | ): Effect.fn.Return<boolean, never, R> { |
| 442 | for (const host of hosts) { |
| 443 | if (!(yield* canListenOnHost(port, host))) { |
| 444 | return false; |
| 445 | } |
| 446 | } |
| 447 | |
| 448 | return true; |
| 449 | }, |
| 450 | ); |
| 451 | |
| 452 | export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> { |
| 453 | const host = configuredHost?.trim(); |
| 454 | if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) { |
| 455 | return DEV_PORT_PROBE_HOSTS; |
| 456 | } |
| 457 | return [...DEV_PORT_PROBE_HOSTS, host]; |
| 458 | } |
| 459 | |
| 460 | const makeDefaultCheckPortAvailability = |
| 461 | (configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> => |
| 462 | (port, role) => |
| 463 | Effect.gen(function* () { |
| 464 | const net = yield* NetService.NetService; |
| 465 | const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost); |
| 466 | return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) => |
| 467 | net.canListenOnHost(candidatePort, host), |
| 468 | ); |
| 469 | }); |
| 470 | |
| 471 | const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined); |
| 472 | |
| 473 | interface FindFirstAvailableOffsetInput<R = NetService.NetService> { |
| 474 | readonly startOffset: number; |
| 475 | readonly requireServerPort: boolean; |
| 476 | readonly requireWebPort: boolean; |
| 477 | readonly checkPortAvailability?: PortAvailabilityCheck<R>; |
| 478 | } |
| 479 | |
| 480 | export const findFirstAvailableOffset = Effect.fn("dev-runner.findFirstAvailableOffset")(function* < |
| 481 | R = NetService.NetService, |
| 482 | >({ |
| 483 | startOffset, |
| 484 | requireServerPort, |
| 485 | requireWebPort, |
| 486 | checkPortAvailability, |
| 487 | }: FindFirstAvailableOffsetInput<R>): Effect.fn.Return<number, DevRunnerPortExhaustedError, R> { |
| 488 | const checkPort = (checkPortAvailability ?? |
| 489 | defaultCheckPortAvailability) as PortAvailabilityCheck<R>; |
| 490 | |
| 491 | for (let candidate = startOffset; ; candidate += 1) { |
| 492 | const { serverPort, webPort } = portPairForOffset(candidate); |
| 493 | const serverPortOutOfRange = serverPort > MAX_PORT; |
| 494 | const webPortOutOfRange = webPort > MAX_PORT; |
| 495 | |
| 496 | if ( |
| 497 | (requireServerPort && serverPortOutOfRange) || |
| 498 | (requireWebPort && webPortOutOfRange) || |
| 499 | (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange)) |
| 500 | ) { |
| 501 | break; |
| 502 | } |
| 503 | |
| 504 | if (requireWebPort && !isBrowserAllowedPort(webPort)) { |
| 505 | continue; |
| 506 | } |
| 507 | |
| 508 | const checks: Array<Effect.Effect<boolean, never, R>> = []; |
| 509 | if (requireServerPort) { |
| 510 | checks.push(checkPort(serverPort, "server")); |
| 511 | } |
| 512 | if (requireWebPort) { |
| 513 | checks.push(checkPort(webPort, "web")); |
| 514 | } |
| 515 | |
| 516 | if (checks.length === 0) { |
| 517 | return candidate; |
| 518 | } |
| 519 | |
| 520 | const availability = yield* Effect.all(checks); |
| 521 | if (availability.every(Boolean)) { |
| 522 | return candidate; |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | return yield* new DevRunnerPortExhaustedError({ |
| 527 | startOffset, |
| 528 | requireServerPort, |
| 529 | requireWebPort, |
| 530 | baseServerPort: BASE_SERVER_PORT, |
| 531 | baseWebPort: BASE_WEB_PORT, |
| 532 | maximumPort: MAX_PORT, |
| 533 | }); |
| 534 | }); |
| 535 | |
| 536 | interface ResolveModePortOffsetsInput<R = NetService.NetService> { |
| 537 | readonly mode: DevMode; |
| 538 | readonly startOffset: number; |
| 539 | readonly hasExplicitServerPort: boolean; |
| 540 | readonly hasExplicitDevUrl: boolean; |
| 541 | readonly checkPortAvailability?: PortAvailabilityCheck<R>; |
| 542 | } |
| 543 | |
| 544 | export const resolveModePortOffsets = Effect.fn("dev-runner.resolveModePortOffsets")(function* < |
| 545 | R = NetService.NetService, |
| 546 | >({ |
| 547 | mode, |
| 548 | startOffset, |
| 549 | hasExplicitServerPort, |
| 550 | hasExplicitDevUrl, |
| 551 | checkPortAvailability, |
| 552 | }: ResolveModePortOffsetsInput<R>): Effect.fn.Return< |
| 553 | { readonly serverOffset: number; readonly webOffset: number }, |
| 554 | DevRunnerPortExhaustedError, |
| 555 | R |
| 556 | > { |
| 557 | const checkPort = (checkPortAvailability ?? |
| 558 | defaultCheckPortAvailability) as PortAvailabilityCheck<R>; |
| 559 | |
| 560 | if (mode === "dev:web") { |
| 561 | if (hasExplicitDevUrl) { |
| 562 | return { serverOffset: startOffset, webOffset: startOffset }; |
| 563 | } |
| 564 | |
| 565 | const webOffset = yield* findFirstAvailableOffset({ |
| 566 | startOffset, |
| 567 | requireServerPort: false, |
| 568 | requireWebPort: true, |
| 569 | checkPortAvailability: checkPort, |
| 570 | }); |
| 571 | return { serverOffset: startOffset, webOffset }; |
| 572 | } |
| 573 | |
| 574 | if (mode === "dev:server") { |
| 575 | if (hasExplicitServerPort) { |
| 576 | return { serverOffset: startOffset, webOffset: startOffset }; |
| 577 | } |
| 578 | |
| 579 | const serverOffset = yield* findFirstAvailableOffset({ |
| 580 | startOffset, |
| 581 | requireServerPort: true, |
| 582 | requireWebPort: false, |
| 583 | checkPortAvailability: checkPort, |
| 584 | }); |
| 585 | return { serverOffset, webOffset: serverOffset }; |
| 586 | } |
| 587 | |
| 588 | const sharedOffset = yield* findFirstAvailableOffset({ |
| 589 | startOffset, |
| 590 | requireServerPort: !hasExplicitServerPort, |
| 591 | requireWebPort: !hasExplicitDevUrl, |
| 592 | checkPortAvailability: checkPort, |
| 593 | }); |
| 594 | |
| 595 | return { serverOffset: sharedOffset, webOffset: sharedOffset }; |
| 596 | }); |
| 597 | |
| 598 | /** Best effort: a failed first-start step warns, and dev still starts. */ |
| 599 | const runRepoScript = Effect.fn("dev-runner.runRepoScript")(function* ( |
| 600 | script: string, |
| 601 | args: ReadonlyArray<string>, |
| 602 | env: NodeJS.ProcessEnv, |
| 603 | ) { |
| 604 | const path = yield* Path.Path; |
| 605 | const repoRoot = path.dirname(import.meta.dirname); |
| 606 | const exitCode = yield* ChildProcess.make( |
| 607 | yield* HostProcess.ExecutablePath, |
| 608 | [path.join(repoRoot, script), ...args], |
| 609 | { cwd: repoRoot, stdin: "ignore", stdout: "inherit", stderr: "inherit", env, extendEnv: false }, |
| 610 | ).pipe( |
| 611 | Effect.flatMap((child) => child.exitCode), |
| 612 | Effect.scoped, |
| 613 | Effect.orElseSucceed(() => -1), |
| 614 | ); |
| 615 | if (exitCode !== 0) { |
| 616 | yield* Effect.logWarning(`[dev-runner] ${script} failed; starting anyway.`); |
| 617 | } |
| 618 | }); |
| 619 | |
| 620 | /** |
| 621 | * The first start in a worktree seeds its empty database from a small live database, |
| 622 | * builds the native resource monitor, and warms the web dependency cache. Each step |
| 623 | * checks for its own output, so later starts skip it. |
| 624 | */ |
| 625 | const prepareFirstStart = Effect.fn("dev-runner.prepareFirstStart")(function* (input: { |
| 626 | readonly mode: DevMode; |
| 627 | readonly seed: boolean; |
| 628 | readonly worktreeHome: string | undefined; |
| 629 | readonly env: NodeJS.ProcessEnv; |
| 630 | }) { |
| 631 | const fs = yield* FileSystem.FileSystem; |
| 632 | const path = yield* Path.Path; |
| 633 | const exists = (file: string) => fs.exists(file).pipe(Effect.orElseSucceed(() => false)); |
| 634 | |
| 635 | if (input.worktreeHome !== undefined && input.mode !== "dev:web") { |
| 636 | const stateDir = path.join(input.worktreeHome, "userdata"); |
| 637 | for (const name of ["statev2.sqlite", "state.sqlite"]) { |
| 638 | const file = path.join(stateDir, name); |
| 639 | const info = yield* fs.stat(file).pipe(Effect.option); |
| 640 | if (Option.isSome(info) && Number(info.value.size) > LARGE_DEV_DATABASE_BYTES) { |
| 641 | yield* Effect.logWarning( |
| 642 | `[dev-runner] ${file} is ${Math.round(Number(info.value.size) / 1024 / 1024)} MB. With the dev server stopped, \`vp run migrate-dev-db\` rebuilds statev2.sqlite as a small copy of recent data.`, |
| 643 | ); |
| 644 | } |
| 645 | } |
| 646 | const source = path.join(yield* HostProcess.HomeDirectory, ".t3", "userdata", "statev2.sqlite"); |
| 647 | // A V1 state.sqlite counts as data too: the server imports it only while |
| 648 | // statev2.sqlite is missing, so seeding would hide it. |
| 649 | if ( |
| 650 | input.seed && |
| 651 | !(yield* exists(path.join(stateDir, "statev2.sqlite"))) && |
| 652 | !(yield* exists(path.join(stateDir, "state.sqlite"))) |
| 653 | ) { |
| 654 | const info = yield* fs.stat(source).pipe(Effect.option); |
| 655 | if (Option.isSome(info)) { |
| 656 | if (Number(info.value.size) > LARGE_DEV_DATABASE_BYTES) { |
| 657 | yield* Effect.logWarning( |
| 658 | `[dev-runner] ${source} exceeds 500 MiB; skipping automatic database seeding and starting with an empty database. Run \`vp run migrate-dev-db\` manually with dev stopped if needed; it may use substantial disk space before pruning.`, |
| 659 | ); |
| 660 | } else { |
| 661 | yield* Effect.logInfo( |
| 662 | `[dev-runner] seeding ${input.worktreeHome} from ${source} (read-only). --no-seed or T3CODE_DEV_SEED=0 skips this.`, |
| 663 | ); |
| 664 | yield* runRepoScript( |
| 665 | "apps/server/scripts/migrate-dev-db.ts", |
| 666 | ["--base-dir", input.worktreeHome, "--source", source], |
| 667 | input.env, |
| 668 | ); |
| 669 | } |
| 670 | } |
| 671 | } |
| 672 | } |
| 673 | |
| 674 | const repoRoot = path.dirname(import.meta.dirname); |
| 675 | // Dev backends load the monitor from its Cargo output, which a fresh |
| 676 | // checkout or worktree does not have yet. |
| 677 | if (input.mode !== "dev:web") { |
| 678 | const crate = path.join(repoRoot, "native/resource-monitor"); |
| 679 | const binary = |
| 680 | (yield* HostProcess.Platform) === "win32" ? "t3-resource-monitor.exe" : "t3-resource-monitor"; |
| 681 | if ( |
| 682 | !(yield* exists(path.join(crate, "target/release", binary))) && |
| 683 | !(yield* exists(path.join(crate, "target/debug", binary))) |
| 684 | ) { |
| 685 | yield* Effect.logInfo("[dev-runner] building the resource monitor (first start only)."); |
| 686 | const exitCode = yield* ChildProcess.make( |
| 687 | "cargo", |
| 688 | ["build", "--locked", "--release", "--manifest-path", path.join(crate, "Cargo.toml")], |
| 689 | { |
| 690 | cwd: repoRoot, |
| 691 | stdin: "ignore", |
| 692 | stdout: "inherit", |
| 693 | stderr: "inherit", |
| 694 | env: input.env, |
| 695 | extendEnv: false, |
| 696 | }, |
| 697 | ).pipe( |
| 698 | Effect.flatMap((child) => child.exitCode), |
| 699 | Effect.scoped, |
| 700 | Effect.orElseSucceed(() => -1), |
| 701 | ); |
| 702 | if (exitCode !== 0) { |
| 703 | yield* Effect.logWarning( |
| 704 | "[dev-runner] could not build the resource monitor; starting without process telemetry. Install Rust and run `vp run build:resource-monitor`.", |
| 705 | ); |
| 706 | } |
| 707 | } |
| 708 | } |
| 709 | |
| 710 | if ( |
| 711 | input.mode !== "dev:server" && |
| 712 | !(yield* exists(path.join(repoRoot, "apps/web/node_modules/.vite/deps/_metadata.json"))) |
| 713 | ) { |
| 714 | yield* runRepoScript("apps/web/scripts/warm-dep-cache.ts", [], input.env); |
| 715 | } |
| 716 | }); |
| 717 | |
| 718 | interface DevRunnerCliInput { |
| 719 | readonly mode: DevMode; |
| 720 | readonly t3Home: string | undefined; |
| 721 | readonly browser: boolean | undefined; |
| 722 | readonly autoBootstrapProjectFromCwd: boolean | undefined; |
| 723 | readonly logWebSocketEvents: boolean | undefined; |
| 724 | readonly host: string | undefined; |
| 725 | readonly port: number | undefined; |
| 726 | readonly devUrl: URL | undefined; |
| 727 | readonly dryRun: boolean; |
| 728 | readonly share: boolean; |
| 729 | readonly seed?: boolean | undefined; |
| 730 | readonly built: boolean; |
| 731 | readonly memoryLimitGb?: number | undefined; |
| 732 | readonly runArgs: ReadonlyArray<string>; |
| 733 | } |
| 734 | |
| 735 | export const runDevRunnerWithInput = Effect.fn("dev-runner.runDevRunnerWithInput")(function* ( |
| 736 | input: DevRunnerCliInput, |
| 737 | ) { |
| 738 | const { portOffset, devInstance } = yield* OffsetConfig.pipe( |
| 739 | Effect.mapError( |
| 740 | (cause) => |
| 741 | new DevRunnerConfigurationError({ |
| 742 | configKeys: ["T3CODE_PORT_OFFSET", "T3CODE_DEV_INSTANCE"], |
| 743 | cause, |
| 744 | }), |
| 745 | ), |
| 746 | ); |
| 747 | |
| 748 | if ( |
| 749 | (input.mode === "dev" || input.mode === "dev:web") && |
| 750 | input.host !== undefined && |
| 751 | !isProxiableBindHost(input.host) |
| 752 | ) { |
| 753 | return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host }); |
| 754 | } |
| 755 | |
| 756 | if (input.built && (input.mode !== "dev" || !input.share)) { |
| 757 | return yield* new DevRunnerBuiltNeedsShareError({ mode: input.mode }); |
| 758 | } |
| 759 | |
| 760 | const worktreePath = yield* resolveGitWorktreePath(yield* HostProcess.WorkingDirectory); |
| 761 | |
| 762 | const { offset, source } = yield* resolveOffset({ |
| 763 | portOffset, |
| 764 | devInstance, |
| 765 | worktreePath, |
| 766 | }); |
| 767 | |
| 768 | const { serverOffset, webOffset } = yield* resolveModePortOffsets({ |
| 769 | mode: input.mode, |
| 770 | startOffset: offset, |
| 771 | hasExplicitServerPort: input.port !== undefined, |
| 772 | hasExplicitDevUrl: input.devUrl !== undefined, |
| 773 | checkPortAvailability: makeDefaultCheckPortAvailability(input.host), |
| 774 | }); |
| 775 | |
| 776 | const hostEnvironment = yield* HostProcess.Environment; |
| 777 | // A dev server started inside a worktree defaults to that worktree's own |
| 778 | // (gitignored) `.t3` — see @t3tools/shared/devHome for why this must |
| 779 | // outrank an ambient T3CODE_HOME. `--home-dir` still wins. |
| 780 | const worktreeHome = yield* resolveWorktreeT3Home(yield* HostProcess.WorkingDirectory); |
| 781 | // Trim before choosing: `--home-dir ""` is not a selection, and treating it |
| 782 | // as one would skip the worktree default and land on the shared home — |
| 783 | // exactly the outcome this precedence exists to prevent. |
| 784 | const resolvedT3Home = |
| 785 | (input.t3Home?.trim() || undefined) ?? |
| 786 | worktreeHome ?? |
| 787 | (hostEnvironment.T3CODE_HOME?.trim() || undefined); |
| 788 | const env = yield* createDevRunnerEnv({ |
| 789 | mode: input.mode, |
| 790 | baseEnv: hostEnvironment, |
| 791 | serverOffset, |
| 792 | webOffset, |
| 793 | t3Home: resolvedT3Home, |
| 794 | browser: input.browser, |
| 795 | autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd, |
| 796 | logWebSocketEvents: input.logWebSocketEvents, |
| 797 | host: input.host, |
| 798 | port: input.port, |
| 799 | devUrl: input.devUrl, |
| 800 | }); |
| 801 | |
| 802 | const selectionSuffix = |
| 803 | serverOffset !== offset || webOffset !== offset |
| 804 | ? ` selectedOffset(server=${serverOffset},web=${webOffset})` |
| 805 | : ""; |
| 806 | const baseDir = env.T3CODE_HOME ?? (yield* DEFAULT_T3_HOME); |
| 807 | |
| 808 | yield* Effect.logInfo( |
| 809 | `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.T3CODE_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`, |
| 810 | ); |
| 811 | |
| 812 | // Before the share block: --dry-run only resolves and prints. Sharing would |
| 813 | // replace, then tear down, whatever mapping the port already had — a |
| 814 | // surprising side effect from a command documented as inert. |
| 815 | if (input.dryRun) { |
| 816 | return; |
| 817 | } |
| 818 | |
| 819 | const sharedWebPort = BASE_WEB_PORT + webOffset; |
| 820 | let built = false; |
| 821 | if (input.share) { |
| 822 | if (input.mode === "dev:server") { |
| 823 | yield* Effect.logInfo("[dev-runner] --share has no effect for dev:server (no web server)."); |
| 824 | } else if (input.mode === "dev:desktop") { |
| 825 | yield* Effect.logWarning( |
| 826 | "[dev-runner] --share is not supported for dev:desktop (the renderer is pinned to loopback). Use `dev`, which runs the whole browser stack.", |
| 827 | ); |
| 828 | } else { |
| 829 | // acquireRelease, not share-then-addFinalizer: the mapping outlives this |
| 830 | // process (and reboots), so the cleanup has to be registered atomically |
| 831 | // with creating it. An interrupt landing in between would otherwise |
| 832 | // leave a mapping pointing at a port nothing is listening on. |
| 833 | const shared = yield* Effect.acquireRelease( |
| 834 | shareDevServer({ |
| 835 | webPort: sharedWebPort, |
| 836 | // The backend binds 127.0.0.1 unless --host changes it. A wildcard |
| 837 | // still answers there; `--host ::1` binds only the IPv6 loopback, and |
| 838 | // `localhost` binds whichever loopback Node resolves first. |
| 839 | ...(input.built |
| 840 | ? { |
| 841 | localTarget: { |
| 842 | port: Number(env.T3CODE_PORT), |
| 843 | host: sharedBackendTargetHost(input.host), |
| 844 | }, |
| 845 | } |
| 846 | : {}), |
| 847 | }), |
| 848 | () => |
| 849 | unshareDevServer(sharedWebPort).pipe( |
| 850 | Effect.flatMap((result) => |
| 851 | result.cleared |
| 852 | ? Effect.void |
| 853 | : Effect.logWarning( |
| 854 | `[dev-runner] could not remove the tailnet mapping for port ${String(sharedWebPort)}${ |
| 855 | result.explanation ? `: ${result.explanation}` : "" |
| 856 | }. Remove it with \`tailscale serve --https=${String(sharedWebPort)} --set-path=/ off\`.`, |
| 857 | ), |
| 858 | ), |
| 859 | ), |
| 860 | ).pipe( |
| 861 | Effect.tapError((error: DevShareError) => |
| 862 | Effect.logWarning( |
| 863 | `[dev-runner] could not share on the tailnet: ${error.message}${ |
| 864 | error.hint ? ` — ${error.hint}` : "" |
| 865 | }`, |
| 866 | ), |
| 867 | ), |
| 868 | Effect.option, |
| 869 | Effect.map(Option.getOrUndefined), |
| 870 | ); |
| 871 | |
| 872 | if (shared) { |
| 873 | // The app is reached from the tailnet origin. Vite already allows |
| 874 | // *.ts.net hosts; the backend needs the origin for credentialed |
| 875 | // requests that bypass the proxy (desktop renderer, direct calls). |
| 876 | env.T3CODE_DEV_ALLOWED_ORIGINS = [ |
| 877 | env.T3CODE_DEV_ALLOWED_ORIGINS, |
| 878 | new URL(shared.url).origin, |
| 879 | ] |
| 880 | .filter((entry) => entry && entry.length > 0) |
| 881 | .join(","); |
| 882 | if (input.devUrl === undefined) { |
| 883 | env.VITE_DEV_SERVER_URL = shared.url; |
| 884 | } |
| 885 | if (input.built) { |
| 886 | built = true; |
| 887 | env.T3CODE_BUILT_DEV = "1"; |
| 888 | } else if (env.T3CODE_BUNDLED_DEV === undefined) { |
| 889 | // A shared origin serves a remote browser, where unbundled dev's |
| 890 | // per-module requests each pay a tailnet round trip — a cold module |
| 891 | // graph takes minutes to first paint. Bundled dev collapses that to a |
| 892 | // few chunk requests. |
| 893 | env.T3CODE_BUNDLED_DEV = "1"; |
| 894 | } |
| 895 | yield* Effect.logInfo(`[dev-runner] shared on tailnet: ${shared.url}`); |
| 896 | } else if (input.built) { |
| 897 | yield* Effect.logWarning( |
| 898 | "[dev-runner] --built needs the tailnet share; running the Vite dev server instead.", |
| 899 | ); |
| 900 | } |
| 901 | } |
| 902 | } |
| 903 | |
| 904 | // After sharing, so the warm step sees the same bundled-dev env as Vite. |
| 905 | yield* prepareFirstStart({ |
| 906 | mode: input.mode, |
| 907 | seed: input.seed !== false, |
| 908 | worktreeHome: baseDir === worktreeHome ? worktreeHome : undefined, |
| 909 | env, |
| 910 | }); |
| 911 | |
| 912 | const args = [...(built ? BUILT_DEV_ARGS : MODE_ARGS[input.mode]), ...input.runArgs]; |
| 913 | const spawnCommand = yield* resolveSpawnCommand("vp", args, { env }); |
| 914 | const processContext = { |
| 915 | mode: input.mode, |
| 916 | executable: "vp" as const, |
| 917 | argumentCount: args.length, |
| 918 | shell: spawnCommand.shell, |
| 919 | } as const; |
| 920 | const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, { |
| 921 | stdin: "inherit", |
| 922 | stdout: "inherit", |
| 923 | stderr: "inherit", |
| 924 | env, |
| 925 | extendEnv: false, |
| 926 | shell: spawnCommand.shell, |
| 927 | // Its own process group: teardown signals the whole group, because vp |
| 928 | // does not pass SIGTERM on to Vite and the server. Windows tears down with |
| 929 | // taskkill /T instead, and a detached shell there leaves vp to open a |
| 930 | // visible console of its own. |
| 931 | detached: (yield* HostProcess.Platform) !== "win32", |
| 932 | forceKillAfter: "1500 millis", |
| 933 | }).pipe( |
| 934 | Effect.mapError( |
| 935 | (cause) => |
| 936 | new DevRunnerProcessError({ |
| 937 | ...processContext, |
| 938 | operation: "spawn", |
| 939 | cause, |
| 940 | }), |
| 941 | ), |
| 942 | ); |
| 943 | |
| 944 | const memoryLimitBytes = |
| 945 | input.memoryLimitGb === undefined |
| 946 | ? defaultDevMemoryLimitBytes() |
| 947 | : input.memoryLimitGb * 1024 ** 3; |
| 948 | const exitCode = yield* child.exitCode.pipe( |
| 949 | Effect.mapError( |
| 950 | (cause) => |
| 951 | new DevRunnerProcessError({ |
| 952 | ...processContext, |
| 953 | operation: "wait-for-exit", |
| 954 | cause, |
| 955 | }), |
| 956 | ), |
| 957 | Effect.raceFirst(enforceDevMemoryLimit(memoryLimitBytes)), |
| 958 | ); |
| 959 | if (exitCode !== 0) { |
| 960 | return yield* new DevRunnerProcessExitError({ |
| 961 | ...processContext, |
| 962 | exitCode, |
| 963 | }); |
| 964 | } |
| 965 | }); |
| 966 | |
| 967 | const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0)); |
| 968 | |
| 969 | const devRunnerCli = Command.make("dev-runner", { |
| 970 | mode: Argument.Literals("mode", DEV_RUNNER_MODES).pipe( |
| 971 | Argument.withDescription("Development mode to run."), |
| 972 | ), |
| 973 | t3Home: Flag.String("home-dir").pipe( |
| 974 | Flag.withDescription( |
| 975 | "Explicit T3 Code data directory; runtime state is stored under userdata (equivalent to T3CODE_HOME). Inside a git worktree this defaults to that worktree's own .t3 so dev state stays off the shared home.", |
| 976 | ), |
| 977 | Flag.optional, |
| 978 | Flag.map(Option.getOrUndefined), |
| 979 | ), |
| 980 | browser: Flag.Boolean("browser").pipe( |
| 981 | Flag.withDescription("Open a browser automatically (disabled by default for web dev)."), |
| 982 | Flag.withDefault(false), |
| 983 | ), |
| 984 | autoBootstrapProjectFromCwd: Flag.Boolean("auto-bootstrap-project-from-cwd").pipe( |
| 985 | Flag.withDescription( |
| 986 | "Auto-bootstrap toggle (equivalent to T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).", |
| 987 | ), |
| 988 | Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")), |
| 989 | ), |
| 990 | logWebSocketEvents: Flag.Boolean("log-websocket-events").pipe( |
| 991 | Flag.withDescription("WebSocket event logging toggle (equivalent to T3CODE_LOG_WS_EVENTS)."), |
| 992 | Flag.withAlias("log-ws-events"), |
| 993 | Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_LOG_WS_EVENTS")), |
| 994 | ), |
| 995 | host: Flag.String("host").pipe( |
| 996 | Flag.withDescription( |
| 997 | "Server host/interface override (forwards to T3CODE_HOST). Ambient T3CODE_HOST is ignored: agent shells inherit it from the T3 server that spawned them.", |
| 998 | ), |
| 999 | Flag.optional, |
| 1000 | Flag.map(Option.getOrUndefined), |
| 1001 | ), |
| 1002 | port: Flag.Int("port").pipe( |
| 1003 | Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))), |
| 1004 | Flag.withDescription( |
| 1005 | "Server port override (forwards to T3CODE_PORT). Ambient T3CODE_PORT is ignored: agent shells inherit it from the T3 server that spawned them.", |
| 1006 | ), |
| 1007 | Flag.optional, |
| 1008 | Flag.map(Option.getOrUndefined), |
| 1009 | ), |
| 1010 | devUrl: Flag.String("dev-url").pipe( |
| 1011 | Flag.withSchema(Schema.URLFromString), |
| 1012 | Flag.withDescription( |
| 1013 | "Explicit web dev URL override (forwards to VITE_DEV_SERVER_URL). Ambient VITE_DEV_SERVER_URL values are ignored so a parent dev app cannot redirect the child runner.", |
| 1014 | ), |
| 1015 | Flag.optional, |
| 1016 | Flag.map(Option.getOrUndefined), |
| 1017 | ), |
| 1018 | dryRun: Flag.Boolean("dry-run").pipe( |
| 1019 | Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."), |
| 1020 | Flag.withDefault(false), |
| 1021 | ), |
| 1022 | share: Flag.Boolean("share").pipe( |
| 1023 | Flag.withDescription( |
| 1024 | "Publish the web dev server on this machine's tailnet over HTTPS (via `tailscale serve`) and print the pairing URL for it. Removed again on exit.", |
| 1025 | ), |
| 1026 | Flag.withDefault(false), |
| 1027 | ), |
| 1028 | seed: Flag.Boolean("seed").pipe( |
| 1029 | Flag.withDescription( |
| 1030 | "Seed an empty worktree database from ~/.t3 on first start (read-only, via migrate-dev-db) if the source is at most 500 MiB. On by default; --no-seed or T3CODE_DEV_SEED=0 skips it.", |
| 1031 | ), |
| 1032 | Flag.withFallbackConfig(optionalBooleanConfig("T3CODE_DEV_SEED")), |
| 1033 | ), |
| 1034 | built: Flag.Boolean("built").pipe( |
| 1035 | Flag.withDescription( |
| 1036 | "With --share: serve a production web build from the backend instead of the Vite dev server. Rebuilds on change, no HMR, much smaller remote loads.", |
| 1037 | ), |
| 1038 | Flag.withDefault(false), |
| 1039 | ), |
| 1040 | memoryLimitGb: Flag.Int("memory-limit-gb").pipe( |
| 1041 | Flag.withSchema(NonNegativeInt), |
| 1042 | Flag.withDescription( |
| 1043 | "Stop the dev server when it and its child processes use more than this many GiB of RAM plus swap (equivalent to T3CODE_DEV_MEMORY_LIMIT_GB). Defaults to half of RAM, at most 16. 0 turns it off. Linux only.", |
| 1044 | ), |
| 1045 | Flag.withFallbackConfig( |
| 1046 | Config.schema(NonNegativeInt, "T3CODE_DEV_MEMORY_LIMIT_GB").pipe( |
| 1047 | Config.option, |
| 1048 | Config.map(Option.getOrUndefined), |
| 1049 | ), |
| 1050 | ), |
| 1051 | ), |
| 1052 | runArgs: Argument.String("run-arg").pipe( |
| 1053 | Argument.withDescription("Additional Vite+ run args (pass after `--`)."), |
| 1054 | Argument.variadic(), |
| 1055 | ), |
| 1056 | }).pipe( |
| 1057 | Command.withDescription("Run monorepo development modes with deterministic port/env wiring."), |
| 1058 | Command.withHandler((input) => runDevRunnerWithInput(input)), |
| 1059 | ); |
| 1060 | |
| 1061 | const cliRuntimeLayer = Layer.mergeAll( |
| 1062 | Logger.layer([Logger.consolePretty()]), |
| 1063 | NodeServices.layer, |
| 1064 | NetService.layer, |
| 1065 | ); |
| 1066 | |
| 1067 | if (import.meta.main) { |
| 1068 | // runMain interrupts (running finalizers such as the --share unmapping) only |
| 1069 | // on SIGINT/SIGTERM; a closed terminal or dropped SSH session sends SIGHUP. |
| 1070 | process.on("SIGHUP", () => process.kill(process.pid, "SIGTERM")); |
| 1071 | Command.run(devRunnerCli, { version: "0.0.0" }).pipe( |
| 1072 | Effect.scoped, |
| 1073 | Effect.provide(cliRuntimeLayer), |
| 1074 | NodeRuntime.runMain, |
| 1075 | ); |
| 1076 | } |