Open History to see the last commit
1#!/usr/bin/env node
2
3import * as NodeOS from "node:os";
4
5import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
6import * as NodeServices from "@effect/platform-node/NodeServices";
7import * as NetService from "@piku/shared/Net";
8import { resolveGitWorktreePath, resolveWorktreePikuHome } from "@piku/shared/devHome";
9import { HostProcessEnvironment, HostProcessWorkingDirectory } from "@piku/shared/hostProcess";
10import { resolveSpawnCommand } from "@piku/shared/shell";
11import * as Config from "effect/Config";
12import * as Effect from "effect/Effect";
13import * as Hash from "effect/Hash";
14import * as Layer from "effect/Layer";
15import * as Logger from "effect/Logger";
16import * as Option from "effect/Option";
17import * as Path from "effect/Path";
18import * as Schema from "effect/Schema";
19import { Argument, Command, Flag } from "effect/unstable/cli";
20import { ChildProcess } from "effect/unstable/process";
21
22import { loadRepoEnv } from "./lib/public-config.ts";
23
24Object.assign(process.env, loadRepoEnv());
25
26const BASE_SERVER_PORT = 13773;
27const BASE_WEB_PORT = 5733;
28const MAX_HASH_OFFSET = 3000;
29const MAX_PORT = 65535;
30const DESKTOP_DEV_LOOPBACK_HOST = "127.0.0.1";
31// HTTP(S) requests to these ports are blocked by the Fetch standard before a
32// browser reaches the network. Keep the complete list here so explicit or
33// future wider offsets cannot produce a URL that curl accepts but browsers
34// reject. https://fetch.spec.whatwg.org/#port-blocking
35const FETCH_BAD_PORTS = new Set([
36 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,
37 103, 104, 109, 110, 111, 113, 115, 117, 119, 123, 135, 137, 139, 143, 161, 179, 389, 427, 465,
38 512, 513, 514, 515, 526, 530, 531, 532, 540, 548, 554, 556, 563, 587, 601, 636, 989, 990, 993,
39 995, 1719, 1720, 1723, 2049, 3659, 4045, 4190, 5060, 5061, 6000, 6566, 6665, 6666, 6667, 6668,
40 6669, 6679, 6697, 10080,
41]);
42// Dev servers bind loopback, so loopback is the only interface whose
43// availability decides whether we can use a port. Probing wildcards too made
44// the runner walk away from a perfectly free port whenever something else held
45// the same number on another interface, which silently moved the ports out
46// from under a URL that had just been handed out.
47const DEV_PORT_PROBE_HOSTS = ["127.0.0.1", "::1"] as const;
48
49/**
50 * Bind hosts on which a backend still answers `http://localhost:<port>`, which
51 * is where single-origin browser dev proxies to. Loopback and the wildcards
52 * qualify; a specific interface (e.g. a LAN IP) does not — the OS binds only
53 * that address and the proxy target goes dark.
54 */
55export function isProxiableBindHost(host: string): boolean {
56 const normalized = host.trim();
57 return (
58 normalized === "" ||
59 normalized === "localhost" ||
60 normalized === "127.0.0.1" ||
61 normalized === "::1" ||
62 normalized === "[::1]" ||
63 normalized === "0.0.0.0" ||
64 normalized === "::" ||
65 normalized === "[::]"
66 );
67}
68
69export const DEFAULT_PIKU_HOME = Effect.map(Effect.service(Path.Path), (path) =>
70 path.join(NodeOS.homedir(), ".pikucode"),
71);
72
73const MODE_ARGS = {
74 dev: [
75 "run",
76 "--filter=@piku/contracts",
77 "--filter=@piku/web",
78 "--filter=piku",
79 "--parallel",
80 "dev",
81 ],
82 "dev:server": ["run", "--filter=piku", "dev"],
83 "dev:web": ["run", "--filter=@piku/web", "dev"],
84 "dev:desktop": ["run", "--filter=@piku/desktop", "--filter=@piku/web", "dev"],
85} as const satisfies Record<string, ReadonlyArray<string>>;
86
87type DevMode = keyof typeof MODE_ARGS;
88/**
89 * `role` matters because only the backend honours `--host`/`PIKU_HOST`; the
90 * web port is always loopback. Passed explicitly rather than inferred from the
91 * port number, which stops distinguishing them under a large port offset.
92 */
93type PortAvailabilityCheck<R = never> = (
94 port: number,
95 role?: "server" | "web",
96) => Effect.Effect<boolean, never, R>;
97
98const DEV_RUNNER_MODES = Object.keys(MODE_ARGS) as Array<DevMode>;
99
100export function getDevRunnerModeArgs(mode: DevMode): ReadonlyArray<string> {
101 return MODE_ARGS[mode];
102}
103
104export function isBrowserAllowedPort(port: number): boolean {
105 return !FETCH_BAD_PORTS.has(port);
106}
107
108export class DevRunnerConfigurationError extends Schema.TaggedErrorClass<DevRunnerConfigurationError>()(
109 "DevRunnerConfigurationError",
110 {
111 configKeys: Schema.Array(Schema.String),
112 cause: Schema.Defect(),
113 },
114) {
115 override get message(): string {
116 return `Failed to read dev-runner configuration: ${this.configKeys.join(", ")}.`;
117 }
118}
119
120export class DevRunnerInvalidPortOffsetError extends Schema.TaggedErrorClass<DevRunnerInvalidPortOffsetError>()(
121 "DevRunnerInvalidPortOffsetError",
122 {
123 configKey: Schema.Literal("PIKU_PORT_OFFSET"),
124 portOffset: Schema.Number,
125 minimum: Schema.Number,
126 },
127) {
128 override get message(): string {
129 return `${this.configKey} must be at least ${this.minimum}; received ${this.portOffset}.`;
130 }
131}
132
133export class DevRunnerPortExhaustedError extends Schema.TaggedErrorClass<DevRunnerPortExhaustedError>()(
134 "DevRunnerPortExhaustedError",
135 {
136 startOffset: Schema.Number,
137 requireServerPort: Schema.Boolean,
138 requireWebPort: Schema.Boolean,
139 baseServerPort: Schema.Number,
140 baseWebPort: Schema.Number,
141 maximumPort: Schema.Number,
142 },
143) {
144 override get message(): string {
145 return `No required dev ports were available from offset ${this.startOffset} through maximum port ${this.maximumPort}.`;
146 }
147}
148
149export class DevRunnerProcessError extends Schema.TaggedErrorClass<DevRunnerProcessError>()(
150 "DevRunnerProcessError",
151 {
152 operation: Schema.Literals(["spawn", "wait-for-exit"]),
153 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
154 executable: Schema.Literal("vp"),
155 argumentCount: Schema.Number,
156 shell: Schema.Boolean,
157 cause: Schema.Defect(),
158 },
159) {
160 override get message(): string {
161 return `Dev-runner process operation "${this.operation}" failed for mode "${this.mode}".`;
162 }
163}
164
165export class DevRunnerProcessExitError extends Schema.TaggedErrorClass<DevRunnerProcessExitError>()(
166 "DevRunnerProcessExitError",
167 {
168 mode: Schema.Literals(["dev", "dev:server", "dev:web", "dev:desktop"]),
169 executable: Schema.Literal("vp"),
170 argumentCount: Schema.Number,
171 shell: Schema.Boolean,
172 exitCode: Schema.Number,
173 },
174) {
175 override get message(): string {
176 return `Dev-runner process exited with code ${this.exitCode} in mode "${this.mode}".`;
177 }
178}
179
180export class DevRunnerHostNotProxiableError extends Schema.TaggedErrorClass<DevRunnerHostNotProxiableError>()(
181 "DevRunnerHostNotProxiableError",
182 {
183 mode: Schema.Literals(["dev", "dev:web"]),
184 host: Schema.String,
185 },
186) {
187 override get message(): string {
188 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.`;
189 }
190}
191
192export const DevRunnerError = Schema.Union([
193 DevRunnerConfigurationError,
194 DevRunnerHostNotProxiableError,
195 DevRunnerInvalidPortOffsetError,
196 DevRunnerPortExhaustedError,
197 DevRunnerProcessError,
198 DevRunnerProcessExitError,
199]);
200export type DevRunnerError = typeof DevRunnerError.Type;
201export const isDevRunnerError = Schema.is(DevRunnerError);
202
203const optionalStringConfig = (name: string): Config.Config<string | undefined> =>
204 Config.string(name).pipe(
205 Config.option,
206 Config.map((value) => Option.getOrUndefined(value)),
207 );
208const optionalBooleanConfig = (name: string): Config.Config<boolean | undefined> =>
209 Config.boolean(name).pipe(
210 Config.option,
211 Config.map((value) => Option.getOrUndefined(value)),
212 );
213const optionalPortConfig = (name: string): Config.Config<number | undefined> =>
214 Config.port(name).pipe(
215 Config.option,
216 Config.map((value) => Option.getOrUndefined(value)),
217 );
218const optionalIntegerConfig = (name: string): Config.Config<number | undefined> =>
219 Config.int(name).pipe(
220 Config.option,
221 Config.map((value) => Option.getOrUndefined(value)),
222 );
223const OffsetConfig = Config.all({
224 portOffset: optionalIntegerConfig("PIKU_PORT_OFFSET"),
225 devInstance: optionalStringConfig("PIKU_DEV_INSTANCE"),
226});
227
228export function resolveOffset(config: {
229 readonly portOffset: number | undefined;
230 readonly devInstance: string | undefined;
231 readonly worktreePath?: string | undefined;
232}): Effect.Effect<
233 { readonly offset: number; readonly source: string },
234 DevRunnerInvalidPortOffsetError
235> {
236 if (config.portOffset !== undefined) {
237 if (config.portOffset < 0) {
238 return Effect.fail(
239 new DevRunnerInvalidPortOffsetError({
240 configKey: "PIKU_PORT_OFFSET",
241 portOffset: config.portOffset,
242 minimum: 0,
243 }),
244 );
245 }
246 return Effect.succeed({
247 offset: config.portOffset,
248 source: `PIKU_PORT_OFFSET=${config.portOffset}`,
249 });
250 }
251
252 const seed = config.devInstance?.trim();
253 if (seed) {
254 if (/^\d+$/.test(seed)) {
255 return Effect.succeed({
256 offset: Number(seed),
257 source: `numeric PIKU_DEV_INSTANCE=${seed}`,
258 });
259 }
260
261 const offset = ((Hash.string(seed) >>> 0) % MAX_HASH_OFFSET) + 1;
262 return Effect.succeed({ offset, source: `hashed PIKU_DEV_INSTANCE=${seed}` });
263 }
264
265 // Worktrees get ports derived from their path so each one is stable across
266 // restarts and distinct from its siblings. Without this every worktree starts
267 // at offset 0 and scan-collides onto whatever happens to be free that minute,
268 // so ports move under you between runs — which breaks any URL you already
269 // shared. The main checkout keeps the documented 5733/13773.
270 const worktreePath = config.worktreePath?.trim();
271 if (worktreePath) {
272 const offset = ((Hash.string(worktreePath) >>> 0) % MAX_HASH_OFFSET) + 1;
273 return Effect.succeed({ offset, source: `worktree ${worktreePath}` });
274 }
275
276 return Effect.succeed({ offset: 0, source: "default ports" });
277}
278
279function resolveBaseDir(baseDir: string | undefined): Effect.Effect<string, never, Path.Path> {
280 return Effect.gen(function* () {
281 const path = yield* Path.Path;
282 const configured = baseDir?.trim();
283
284 if (configured) {
285 return path.resolve(configured);
286 }
287
288 return yield* DEFAULT_PIKU_HOME;
289 });
290}
291
292interface CreateDevRunnerEnvInput {
293 readonly mode: DevMode;
294 readonly baseEnv: NodeJS.ProcessEnv;
295 readonly serverOffset: number;
296 readonly webOffset: number;
297 readonly pikuHome: string | undefined;
298 readonly browser: boolean | undefined;
299 readonly autoBootstrapProjectFromCwd: boolean | undefined;
300 readonly logWebSocketEvents: boolean | undefined;
301 readonly host: string | undefined;
302 readonly port: number | undefined;
303 readonly devUrl: URL | undefined;
304}
305
306export function createDevRunnerEnv({
307 mode,
308 baseEnv,
309 serverOffset,
310 webOffset,
311 pikuHome,
312 browser,
313 autoBootstrapProjectFromCwd,
314 logWebSocketEvents,
315 host,
316 port,
317 devUrl,
318}: CreateDevRunnerEnvInput): Effect.Effect<NodeJS.ProcessEnv, never, Path.Path> {
319 return Effect.gen(function* () {
320 const serverPort = port ?? BASE_SERVER_PORT + serverOffset;
321 const webPort = BASE_WEB_PORT + webOffset;
322 // Precedence (--home-dir > worktree .pikucode > ambient PIKU_HOME) is resolved
323 // by the caller; an unset pikuHome here genuinely means "use the default".
324 const configuredBaseDir = pikuHome?.trim() || undefined;
325 const resolvedBaseDir = yield* resolveBaseDir(configuredBaseDir);
326 const isDesktopMode = mode === "dev:desktop";
327
328 const output: NodeJS.ProcessEnv = {
329 ...baseEnv,
330 PORT: String(webPort),
331 VITE_DEV_SERVER_URL:
332 devUrl?.toString() ??
333 `http://${isDesktopMode ? DESKTOP_DEV_LOOPBACK_HOST : "localhost"}:${webPort}`,
334 };
335
336 if (configuredBaseDir !== undefined) {
337 output.PIKU_HOME = resolvedBaseDir;
338 } else {
339 delete output.PIKU_HOME;
340 }
341
342 if (!isDesktopMode) {
343 output.PIKU_PORT = String(serverPort);
344 // HOST is Vite's own bind address, and the desktop branch below is the
345 // only place we set it. An inherited one (an exported HOST, a container,
346 // a `HOST=0.0.0.0 npm start` habit) would otherwise reach Vite and pin
347 // its HMR socket to that address — see the `explicitHost` gate in
348 // apps/web/vite.config.ts. Over a shared origin that is invisible: the
349 // page loads and only HMR quietly dials the wrong machine.
350 delete output.HOST;
351 if (mode === "dev" || mode === "dev:web") {
352 // Browser dev is single-origin: everything (including /ws) is proxied
353 // through Vite, so the client must resolve its backend from
354 // window.location.origin rather than a baked-in localhost URL. See
355 // resolveConfiguredPrimaryTarget in apps/web/src/environments/primary/target.ts
356 // — it only defers to the origin when both of these are absent. Baking
357 // localhost here is what breaks any non-localhost origin (LAN,
358 // phone): the remote browser dials its own machine.
359 delete output.VITE_HTTP_URL;
360 delete output.VITE_WS_URL;
361 // Deleting is not enough on its own: vite.config.ts calls loadRepoEnv,
362 // which merges `.env`/`.env.local` *under* this env, so a developer
363 // with either URL in their `.env` would get it back and silently lose
364 // single-origin mode. This states the intent positively so Vite can
365 // ignore those values rather than infer from their absence.
366 output.PIKU_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.PIKU_SINGLE_ORIGIN_DEV;
371 }
372 } else {
373 output.PIKU_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.PIKU_SINGLE_ORIGIN_DEV;
379 delete output.PIKU_MODE;
380 delete output.PIKU_NO_BROWSER;
381 delete output.PIKU_HOST;
382 }
383
384 if (!isDesktopMode && host !== undefined) {
385 output.PIKU_HOST = host;
386 }
387
388 if (!isDesktopMode) {
389 output.PIKU_NO_BROWSER = browser === true ? "0" : "1";
390 }
391
392 if (autoBootstrapProjectFromCwd !== undefined) {
393 output.PIKU_AUTO_BOOTSTRAP_PROJECT_FROM_CWD = autoBootstrapProjectFromCwd ? "1" : "0";
394 } else {
395 delete output.PIKU_AUTO_BOOTSTRAP_PROJECT_FROM_CWD;
396 }
397
398 if (logWebSocketEvents !== undefined) {
399 output.PIKU_LOG_WS_EVENTS = logWebSocketEvents ? "1" : "0";
400 } else {
401 delete output.PIKU_LOG_WS_EVENTS;
402 }
403
404 if (mode === "dev") {
405 output.PIKU_MODE = "web";
406 delete output.PIKU_DESKTOP_WS_URL;
407 }
408
409 if (mode === "dev:server" || mode === "dev:web") {
410 output.PIKU_MODE = "web";
411 delete output.PIKU_DESKTOP_WS_URL;
412 }
413
414 if (isDesktopMode) {
415 output.HOST = DESKTOP_DEV_LOOPBACK_HOST;
416 delete output.PIKU_DESKTOP_WS_URL;
417 }
418
419 return output;
420 });
421}
422
423function portPairForOffset(offset: number): {
424 readonly serverPort: number;
425 readonly webPort: number;
426} {
427 return {
428 serverPort: BASE_SERVER_PORT + offset,
429 webPort: BASE_WEB_PORT + offset,
430 };
431}
432
433export function checkPortAvailabilityOnHosts<R>(
434 port: number,
435 hosts: ReadonlyArray<string>,
436 canListenOnHost: (port: number, host: string) => Effect.Effect<boolean, never, R>,
437): Effect.Effect<boolean, never, R> {
438 return Effect.gen(function* () {
439 for (const host of hosts) {
440 if (!(yield* canListenOnHost(port, host))) {
441 return false;
442 }
443 }
444
445 return true;
446 });
447}
448
449/**
450 * Hosts to probe for a dev server bound to `configuredHost`.
451 *
452 * Loopback is always checked because the web server and the desktop renderer
453 * target reach it there. When `--host`/`PIKU_HOST` moves the backend onto
454 * another interface, that interface decides whether the bind actually
455 * succeeds — probing only loopback would hand back a port that is free here
456 * and taken there, and the server would fail to start.
457 *
458 * `configuredHost` applies to the *backend* only. Vite takes its bind address
459 * from `HOST`, which the runner sets for desktop alone, so the web port stays
460 * on loopback and must not be judged against the backend's interface —
461 * a port free on loopback but busy on that interface would otherwise be
462 * rejected for a server that was never going to bind there.
463 */
464export function devPortProbeHosts(configuredHost: string | undefined): ReadonlyArray<string> {
465 const host = configuredHost?.trim();
466 if (!host || DEV_PORT_PROBE_HOSTS.includes(host as (typeof DEV_PORT_PROBE_HOSTS)[number])) {
467 return DEV_PORT_PROBE_HOSTS;
468 }
469 return [...DEV_PORT_PROBE_HOSTS, host];
470}
471
472const makeDefaultCheckPortAvailability =
473 (configuredHost: string | undefined): PortAvailabilityCheck<NetService.NetService> =>
474 (port, role) =>
475 Effect.gen(function* () {
476 const net = yield* NetService.NetService;
477 const hosts = role === "web" ? DEV_PORT_PROBE_HOSTS : devPortProbeHosts(configuredHost);
478 return yield* checkPortAvailabilityOnHosts(port, hosts, (candidatePort, host) =>
479 net.canListenOnHost(candidatePort, host),
480 );
481 });
482
483const defaultCheckPortAvailability = makeDefaultCheckPortAvailability(undefined);
484
485interface FindFirstAvailableOffsetInput<R = NetService.NetService> {
486 readonly startOffset: number;
487 readonly requireServerPort: boolean;
488 readonly requireWebPort: boolean;
489 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
490}
491
492export function findFirstAvailableOffset<R = NetService.NetService>({
493 startOffset,
494 requireServerPort,
495 requireWebPort,
496 checkPortAvailability,
497}: FindFirstAvailableOffsetInput<R>): Effect.Effect<number, DevRunnerPortExhaustedError, R> {
498 return Effect.gen(function* () {
499 const checkPort = (checkPortAvailability ??
500 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
501
502 for (let candidate = startOffset; ; candidate += 1) {
503 const { serverPort, webPort } = portPairForOffset(candidate);
504 const serverPortOutOfRange = serverPort > MAX_PORT;
505 const webPortOutOfRange = webPort > MAX_PORT;
506
507 if (
508 (requireServerPort && serverPortOutOfRange) ||
509 (requireWebPort && webPortOutOfRange) ||
510 (!requireServerPort && !requireWebPort && (serverPortOutOfRange || webPortOutOfRange))
511 ) {
512 break;
513 }
514
515 if (requireWebPort && !isBrowserAllowedPort(webPort)) {
516 continue;
517 }
518
519 const checks: Array<Effect.Effect<boolean, never, R>> = [];
520 if (requireServerPort) {
521 checks.push(checkPort(serverPort, "server"));
522 }
523 if (requireWebPort) {
524 checks.push(checkPort(webPort, "web"));
525 }
526
527 if (checks.length === 0) {
528 return candidate;
529 }
530
531 const availability = yield* Effect.all(checks);
532 if (availability.every(Boolean)) {
533 return candidate;
534 }
535 }
536
537 return yield* new DevRunnerPortExhaustedError({
538 startOffset,
539 requireServerPort,
540 requireWebPort,
541 baseServerPort: BASE_SERVER_PORT,
542 baseWebPort: BASE_WEB_PORT,
543 maximumPort: MAX_PORT,
544 });
545 });
546}
547
548interface ResolveModePortOffsetsInput<R = NetService.NetService> {
549 readonly mode: DevMode;
550 readonly startOffset: number;
551 readonly hasExplicitServerPort: boolean;
552 readonly hasExplicitDevUrl: boolean;
553 readonly checkPortAvailability?: PortAvailabilityCheck<R>;
554}
555
556export function resolveModePortOffsets<R = NetService.NetService>({
557 mode,
558 startOffset,
559 hasExplicitServerPort,
560 hasExplicitDevUrl,
561 checkPortAvailability,
562}: ResolveModePortOffsetsInput<R>): Effect.Effect<
563 { readonly serverOffset: number; readonly webOffset: number },
564 DevRunnerPortExhaustedError,
565 R
566> {
567 return Effect.gen(function* () {
568 const checkPort = (checkPortAvailability ??
569 defaultCheckPortAvailability) as PortAvailabilityCheck<R>;
570
571 if (mode === "dev:web") {
572 if (hasExplicitDevUrl) {
573 return { serverOffset: startOffset, webOffset: startOffset };
574 }
575
576 const webOffset = yield* findFirstAvailableOffset({
577 startOffset,
578 requireServerPort: false,
579 requireWebPort: true,
580 checkPortAvailability: checkPort,
581 });
582 return { serverOffset: startOffset, webOffset };
583 }
584
585 if (mode === "dev:server") {
586 if (hasExplicitServerPort) {
587 return { serverOffset: startOffset, webOffset: startOffset };
588 }
589
590 const serverOffset = yield* findFirstAvailableOffset({
591 startOffset,
592 requireServerPort: true,
593 requireWebPort: false,
594 checkPortAvailability: checkPort,
595 });
596 return { serverOffset, webOffset: serverOffset };
597 }
598
599 const sharedOffset = yield* findFirstAvailableOffset({
600 startOffset,
601 requireServerPort: !hasExplicitServerPort,
602 requireWebPort: !hasExplicitDevUrl,
603 checkPortAvailability: checkPort,
604 });
605
606 return { serverOffset: sharedOffset, webOffset: sharedOffset };
607 });
608}
609
610interface DevRunnerCliInput {
611 readonly mode: DevMode;
612 readonly pikuHome: string | undefined;
613 readonly browser: boolean | undefined;
614 readonly autoBootstrapProjectFromCwd: boolean | undefined;
615 readonly logWebSocketEvents: boolean | undefined;
616 readonly host: string | undefined;
617 readonly port: number | undefined;
618 readonly devUrl: URL | undefined;
619 readonly dryRun: boolean;
620 readonly runArgs: ReadonlyArray<string>;
621}
622
623export function runDevRunnerWithInput(input: DevRunnerCliInput) {
624 return Effect.gen(function* () {
625 const { portOffset, devInstance } = yield* OffsetConfig.pipe(
626 Effect.mapError(
627 (cause) =>
628 new DevRunnerConfigurationError({
629 configKeys: ["PIKU_PORT_OFFSET", "PIKU_DEV_INSTANCE"],
630 cause,
631 }),
632 ),
633 );
634
635 // Single-origin browser dev proxies the backend at localhost. A wildcard
636 // bind still answers there; a specific non-loopback interface does not,
637 // which breaks every proxied request in a way that reads as "server is
638 // broken" rather than "flag combination is unsupported". Reject it up
639 // front instead. (dev:server and dev:desktop don't proxy — untouched.)
640 if (
641 (input.mode === "dev" || input.mode === "dev:web") &&
642 input.host !== undefined &&
643 !isProxiableBindHost(input.host)
644 ) {
645 return yield* new DevRunnerHostNotProxiableError({ mode: input.mode, host: input.host });
646 }
647
648 const worktreePath = yield* resolveGitWorktreePath(yield* HostProcessWorkingDirectory);
649
650 const { offset, source } = yield* resolveOffset({
651 portOffset,
652 devInstance,
653 worktreePath,
654 });
655
656 const { serverOffset, webOffset } = yield* resolveModePortOffsets({
657 mode: input.mode,
658 startOffset: offset,
659 hasExplicitServerPort: input.port !== undefined,
660 hasExplicitDevUrl: input.devUrl !== undefined,
661 // A non-loopback bind host decides whether the backend can actually take
662 // the port, so it has to be probed alongside loopback.
663 checkPortAvailability: makeDefaultCheckPortAvailability(input.host),
664 });
665
666 const hostEnvironment = yield* HostProcessEnvironment;
667 // A dev server started inside a worktree defaults to that worktree's own
668 // (gitignored) `.pikucode` — see @piku/shared/devHome for why this must
669 // outrank an ambient PIKU_HOME. `--home-dir` still wins.
670 const worktreeHome = yield* resolveWorktreePikuHome(yield* HostProcessWorkingDirectory);
671 // Trim before choosing: `--home-dir ""` is not a selection, and treating it
672 // as one would skip the worktree default and land on the shared home —
673 // exactly the outcome this precedence exists to prevent.
674 const resolvedPikuHome =
675 (input.pikuHome?.trim() || undefined) ??
676 worktreeHome ??
677 (hostEnvironment.PIKU_HOME?.trim() || undefined);
678 const env = yield* createDevRunnerEnv({
679 mode: input.mode,
680 baseEnv: hostEnvironment,
681 serverOffset,
682 webOffset,
683 pikuHome: resolvedPikuHome,
684 browser: input.browser,
685 autoBootstrapProjectFromCwd: input.autoBootstrapProjectFromCwd,
686 logWebSocketEvents: input.logWebSocketEvents,
687 host: input.host,
688 port: input.port,
689 devUrl: input.devUrl,
690 });
691
692 const selectionSuffix =
693 serverOffset !== offset || webOffset !== offset
694 ? ` selectedOffset(server=${serverOffset},web=${webOffset})`
695 : "";
696 const baseDir = env.PIKU_HOME ?? (yield* DEFAULT_PIKU_HOME);
697
698 yield* Effect.logInfo(
699 `[dev-runner] mode=${input.mode} source=${source}${selectionSuffix} serverPort=${String(env.PIKU_PORT)} webPort=${String(env.PORT)} baseDir=${baseDir}`,
700 );
701
702 if (input.dryRun) {
703 return;
704 }
705
706 const spawnCommand = yield* resolveSpawnCommand(
707 "vp",
708 [...MODE_ARGS[input.mode], ...input.runArgs],
709 { env },
710 );
711 const processContext = {
712 mode: input.mode,
713 executable: "vp" as const,
714 argumentCount: spawnCommand.args.length,
715 shell: spawnCommand.shell,
716 } as const;
717 const child = yield* ChildProcess.make(spawnCommand.command, spawnCommand.args, {
718 stdin: "inherit",
719 stdout: "inherit",
720 stderr: "inherit",
721 env,
722 extendEnv: false,
723 shell: spawnCommand.shell,
724 // Keep Vite+ in the same process group so terminal signals (Ctrl+C)
725 // reach it directly. Effect defaults to detached: true on non-Windows,
726 // which would put the runner in a new group and require manual forwarding.
727 detached: false,
728 forceKillAfter: "1500 millis",
729 }).pipe(
730 Effect.mapError(
731 (cause) =>
732 new DevRunnerProcessError({
733 ...processContext,
734 operation: "spawn",
735 cause,
736 }),
737 ),
738 );
739
740 const exitCode = yield* child.exitCode.pipe(
741 Effect.mapError(
742 (cause) =>
743 new DevRunnerProcessError({
744 ...processContext,
745 operation: "wait-for-exit",
746 cause,
747 }),
748 ),
749 );
750 if (exitCode !== 0) {
751 return yield* new DevRunnerProcessExitError({
752 ...processContext,
753 exitCode,
754 });
755 }
756 });
757}
758
759const devRunnerCli = Command.make("dev-runner", {
760 mode: Argument.choice("mode", DEV_RUNNER_MODES).pipe(
761 Argument.withDescription("Development mode to run."),
762 ),
763 pikuHome: Flag.string("home-dir").pipe(
764 Flag.withDescription(
765 "Explicit Piku Code data directory; runtime state is stored under userdata (equivalent to PIKU_HOME). Inside a git worktree this defaults to that worktree's own .pikucode so dev state stays off the shared home.",
766 ),
767 Flag.optional,
768 Flag.map(Option.getOrUndefined),
769 ),
770 browser: Flag.boolean("browser").pipe(
771 Flag.withDescription("Open a browser automatically (disabled by default for web dev)."),
772 ),
773 autoBootstrapProjectFromCwd: Flag.boolean("auto-bootstrap-project-from-cwd").pipe(
774 Flag.withDescription(
775 "Auto-bootstrap toggle (equivalent to PIKU_AUTO_BOOTSTRAP_PROJECT_FROM_CWD).",
776 ),
777 Flag.withFallbackConfig(optionalBooleanConfig("PIKU_AUTO_BOOTSTRAP_PROJECT_FROM_CWD")),
778 ),
779 logWebSocketEvents: Flag.boolean("log-websocket-events").pipe(
780 Flag.withDescription("WebSocket event logging toggle (equivalent to PIKU_LOG_WS_EVENTS)."),
781 Flag.withAlias("log-ws-events"),
782 Flag.withFallbackConfig(optionalBooleanConfig("PIKU_LOG_WS_EVENTS")),
783 ),
784 host: Flag.string("host").pipe(
785 Flag.withDescription("Server host/interface override (forwards to PIKU_HOST)."),
786 Flag.withFallbackConfig(optionalStringConfig("PIKU_HOST")),
787 ),
788 port: Flag.integer("port").pipe(
789 Flag.withSchema(Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 }))),
790 Flag.withDescription("Server port override (forwards to PIKU_PORT)."),
791 Flag.withFallbackConfig(optionalPortConfig("PIKU_PORT")),
792 ),
793 devUrl: Flag.string("dev-url").pipe(
794 Flag.withSchema(Schema.URLFromString),
795 Flag.withDescription(
796 "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.",
797 ),
798 Flag.optional,
799 Flag.map(Option.getOrUndefined),
800 ),
801 dryRun: Flag.boolean("dry-run").pipe(
802 Flag.withDescription("Resolve mode/ports/env and print, but do not spawn Vite+."),
803 Flag.withDefault(false),
804 ),
805 runArgs: Argument.string("run-arg").pipe(
806 Argument.withDescription("Additional Vite+ run args (pass after `--`)."),
807 Argument.variadic(),
808 ),
809}).pipe(
810 Command.withDescription("Run monorepo development modes with deterministic port/env wiring."),
811 Command.withHandler((input) => runDevRunnerWithInput(input)),
812);
813
814const cliRuntimeLayer = Layer.mergeAll(
815 Logger.layer([Logger.consolePretty()]),
816 NodeServices.layer,
817 NetService.layer,
818);
819
820if (import.meta.main) {
821 Command.run(devRunnerCli, { version: "0.0.0" }).pipe(
822 Effect.scoped,
823 Effect.provide(cliRuntimeLayer),
824 NodeRuntime.runMain,
825 );
826}