The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { fileURLToPath } from "node:url"; |
| 2 | import * as Command from "effect/cli/Command"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Fiber from "effect/Fiber"; |
| 5 | import * as Logger from "effect/Logger"; |
| 6 | import * as Option from "effect/Option"; |
| 7 | import * as ChildProcess from "effect/process/ChildProcess"; |
| 8 | import * as Schema from "effect/Schema"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { resolveStackEntrypoint } from "../../Alchemist/Entrypoint.ts"; |
| 11 | import * as Contributions from "../../Contributions.ts"; |
| 12 | import { SPAWNER_URL_ENV_KEY } from "../../Local/RpcProviderProxy.ts"; |
| 13 | import * as RpcSpawner from "../../Local/RpcSpawner.ts"; |
| 14 | import { LOG_FD_ENV, parseRecord, replayRecord } from "../../Util/LogRecord.ts"; |
| 15 | import { nodeLoaderArgs } from "../../Util/Node.ts"; |
| 16 | import { timedShutdownStep } from "../../Util/Shutdown.ts"; |
| 17 | import { traceParentEnv } from "../../Util/TraceParent.ts"; |
| 18 | import { DEV_RELOAD_EXIT_CODE, DevOptions } from "../DevOptions.ts"; |
| 19 | import { consoleSettingsEnv, currentConsoleSettings, RunLog } from "../GlobalLog.ts"; |
| 20 | import { suppressInterruptMessages } from "./errors.ts"; |
| 21 | import { |
| 22 | configPath, |
| 23 | envFile, |
| 24 | force, |
| 25 | include, |
| 26 | exclude, |
| 27 | devStage, |
| 28 | optionalConfig, |
| 29 | profile, |
| 30 | resolveStackArgs, |
| 31 | } from "./flags.ts"; |
| 32 | import { logCommandFailure, VersionCheck } from "./instrument.ts"; |
| 33 | |
| 34 | /** |
| 35 | * Trust the Floci emulator CA in `alchemy dev` so cross-cloud data planes |
| 36 | * terminated by the emulator's self-signed cert (e.g. an AWS Lambda MicroVM |
| 37 | * bound to a local Cloudflare Worker) are reachable from local workerd. workerd |
| 38 | * reads its trusted certificates from `NODE_EXTRA_CA_CERTS` at runtime init, so |
| 39 | * this must be present in the env of every spawned child (the exec worker, the |
| 40 | * RPC sidecar, and the workerd instances they start). `ensureFloci` refreshes |
| 41 | * the bundle at this stable path (and sets the variable itself once written); |
| 42 | * never clobber a value the caller set, and don't point at a missing file — |
| 43 | * Node/Bun warn about it on every startup. |
| 44 | */ |
| 45 | |
| 46 | export const devCommand = Command.make( |
| 47 | "dev", |
| 48 | { |
| 49 | force, |
| 50 | include, |
| 51 | exclude, |
| 52 | config: optionalConfig, |
| 53 | configPath, |
| 54 | envFile, |
| 55 | stage: devStage, |
| 56 | profile, |
| 57 | }, |
| 58 | Effect.fn( |
| 59 | function* (rawArgs) { |
| 60 | const args = yield* resolveStackArgs("dev")(rawArgs); |
| 61 | // This process is only the exec child's supervisor; the child owns the |
| 62 | // terminal and announces the Ctrl+C shutdown. Without this, a SIGINT |
| 63 | // hits both processes and the interrupt message prints twice. |
| 64 | yield* suppressInterruptMessages; |
| 65 | const options = yield* Schema.encodeEffect(DevOptions)(args); |
| 66 | // A missing entry is this process's error to report, not a stack |
| 67 | // trace out of the exec child. |
| 68 | yield* resolveStackEntrypoint(options.main); |
| 69 | // Providers' dev environment (e.g. a local emulator's CA bundle). Set on |
| 70 | // THIS process, so the RPC spawner's sidecars (and the workerd they |
| 71 | // launch) inherit it — they are forked from here, not from the exec |
| 72 | // child below. |
| 73 | const env = yield* Contributions.devEnv().pipe( |
| 74 | Effect.catchTag("ContributionError", (error) => |
| 75 | Effect.logWarning(error.message).pipe(Effect.as({})), |
| 76 | ), |
| 77 | ); |
| 78 | for (const [key, value] of Object.entries(env)) { |
| 79 | process.env[key] ??= value; |
| 80 | } |
| 81 | const spawner = yield* RpcSpawner.RpcSpawner; |
| 82 | // Neither runtime uses its native `--watch`: those hard-restart the exec |
| 83 | // child with no teardown, leaving the previous generation's widget in |
| 84 | // scrollback and never saying what changed. exec.ts watches the user's |
| 85 | // stack graph itself. Under Node it reloads the graph in-process; under |
| 86 | // Bun (which cannot evict evaluated modules) it tears down and exits |
| 87 | // with DEV_RELOAD_EXIT_CODE, and this supervisor starts a fresh child. |
| 88 | let command: [string, ...string[]]; |
| 89 | const entry = fileURLToPath(import.meta.resolve("alchemy/bin/exec.js")); |
| 90 | if (typeof globalThis.Bun !== "undefined") { |
| 91 | command = ["bun", "run", ...process.execArgv, entry]; |
| 92 | } else { |
| 93 | // Node: the exec entry runs with alchemy's Oxc loader hooks, |
| 94 | // exactly as bin/cli.js started this process. Select the loader from |
| 95 | // this module's source or compiled location; the entry is always JS. |
| 96 | // Node's own TypeScript support is never relied on. `process.execPath`, |
| 97 | // not "node": the hooks are gated on THIS node's version. A |
| 98 | // duplicate --import inherited via execArgv is harmless — the |
| 99 | // second import of the same URL hits the module cache. |
| 100 | command = [ |
| 101 | process.execPath, |
| 102 | ...process.execArgv, |
| 103 | ...nodeLoaderArgs(import.meta.url), |
| 104 | entry, |
| 105 | ]; |
| 106 | } |
| 107 | const runLog = yield* RunLog; |
| 108 | const consoleSettings = yield* currentConsoleSettings; |
| 109 | // The child's records and spans join this command's trace. |
| 110 | const traceEnv = yield* traceParentEnv; |
| 111 | const runChild = ChildProcess.make(command[0], command.slice(1), { |
| 112 | stdin: "inherit", |
| 113 | stdout: "inherit", |
| 114 | stderr: "inherit", |
| 115 | env: { |
| 116 | ALCHEMY_EXEC_OPTIONS: JSON.stringify(options), |
| 117 | ALCHEMY_DEV: "true", |
| 118 | [LOG_FD_ENV]: "3", |
| 119 | // The exec child renders the run's logs but never sees this argv. |
| 120 | ...consoleSettingsEnv(consoleSettings), |
| 121 | ...(process.env.NODE_EXTRA_CA_CERTS |
| 122 | ? { NODE_EXTRA_CA_CERTS: process.env.NODE_EXTRA_CA_CERTS } |
| 123 | : {}), |
| 124 | [SPAWNER_URL_ENV_KEY]: spawner.url, |
| 125 | ...traceEnv, |
| 126 | }, |
| 127 | extendEnv: true, |
| 128 | // Same process group as this supervisor: the exec child owns the |
| 129 | // terminal (TUI stdin), so the tty's Ctrl+C must reach it directly. |
| 130 | detached: false, |
| 131 | // The child's log records, for the run log this process writes. |
| 132 | additionalFds: { fd3: { type: "output" } }, |
| 133 | }).pipe( |
| 134 | Effect.flatMap((child) => |
| 135 | Effect.gen(function* () { |
| 136 | const records = yield* child.getOutputFd(3).pipe( |
| 137 | Stream.decodeText(), |
| 138 | Stream.splitLines, |
| 139 | // Already rendered by the child: into the run log only. A line |
| 140 | // that doesn't decode is skipped, never ends the reader. |
| 141 | Stream.runForEach((line) => { |
| 142 | const record = parseRecord(line); |
| 143 | return record === undefined |
| 144 | ? Effect.void |
| 145 | : replayRecord(record).pipe( |
| 146 | Effect.provideService(Logger.CurrentLoggers, new Set([runLog])), |
| 147 | ); |
| 148 | }), |
| 149 | Effect.ignore, |
| 150 | Effect.forkScoped, |
| 151 | ); |
| 152 | // The pipe closes with the child: take its last records before |
| 153 | // this scope (and the reader with it) closes. |
| 154 | const drain = Fiber.join(records).pipe(Effect.timeout("2 seconds"), Effect.ignore); |
| 155 | const code = yield* child.exitCode.pipe( |
| 156 | // Ctrl+C reaches the child too (same process group): let it |
| 157 | // finish its own shutdown and report it before this scope |
| 158 | // kills whatever is left. |
| 159 | Effect.onInterrupt(() => |
| 160 | child.exitCode.pipe( |
| 161 | Effect.timeout("5 seconds"), |
| 162 | Effect.ignore, |
| 163 | Effect.andThen(drain), |
| 164 | timedShutdownStep("stopped exec child"), |
| 165 | ), |
| 166 | ), |
| 167 | ); |
| 168 | yield* drain; |
| 169 | return code; |
| 170 | }), |
| 171 | ), |
| 172 | Effect.scoped, |
| 173 | ); |
| 174 | // Each child gets its own scope so a reload exit releases the old |
| 175 | // handle before the replacement starts; the sidecar spawner lives in |
| 176 | // the command scope and survives every restart. |
| 177 | yield* Effect.repeat(runChild, { |
| 178 | until: (code) => code !== DEV_RELOAD_EXIT_CODE, |
| 179 | }); |
| 180 | }, |
| 181 | (effect, args) => |
| 182 | Effect.andThen( |
| 183 | Effect.flatten(VersionCheck), |
| 184 | Effect.provide( |
| 185 | RpcSpawner.layerServer({ |
| 186 | profile: args.profile, |
| 187 | envFile: Option.getOrUndefined(args.envFile), |
| 188 | }), |
| 189 | )(effect), |
| 190 | ).pipe(logCommandFailure), |
| 191 | ), |
| 192 | ).pipe(Command.withDescription("Develop a stack with live reload")); |