The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { fileURLToPath } from "node:url"; |
| 2 | import { watchImport } from "@alchemy.run/node-utils/watch-import"; |
| 3 | import { trackBunImports } from "@alchemy.run/node-utils/watch-import-bun"; |
| 4 | import * as Cause from "effect/Cause"; |
| 5 | import * as Config from "effect/Config"; |
| 6 | import * as ConfigProvider from "effect/ConfigProvider"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as FileSystem from "effect/FileSystem"; |
| 9 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 10 | import * as Layer from "effect/Layer"; |
| 11 | import * as Option from "effect/Option"; |
| 12 | import * as Path from "effect/Path"; |
| 13 | import * as Schema from "effect/Schema"; |
| 14 | import { resolveStackEntrypoint } from "../Alchemist/Entrypoint.ts"; |
| 15 | import { StackModuleLoader } from "../Alchemist/Entrypoint.ts"; |
| 16 | import * as Alchemist from "../Alchemist/index.ts"; |
| 17 | import { AlchemyContextLive } from "../AlchemyContext.ts"; |
| 18 | import { ArtifactStore, createArtifactStore } from "../Artifacts.ts"; |
| 19 | import { CredentialsStoreLive } from "../Auth/Credentials.ts"; |
| 20 | import { ProfileStoreLive } from "../Auth/Profile.ts"; |
| 21 | import * as Interaction from "../Interaction.ts"; |
| 22 | import * as RpcProviderProxy from "../Local/RpcProviderProxy.ts"; |
| 23 | import { forwardSidecarLogs } from "../Local/RpcSpawner.ts"; |
| 24 | import { renderApply } from "../Report.ts"; |
| 25 | import { TelemetryLive } from "../Telemetry/Layer.ts"; |
| 26 | import { LogProcess, parentLogLayer } from "../Util/LogRecord.ts"; |
| 27 | import { initialCwd } from "../Util/Node.ts"; |
| 28 | import { PlatformServices } from "../Util/PlatformServices.ts"; |
| 29 | import { logShutdown } from "../Util/Shutdown.ts"; |
| 30 | import { processTrace, withTraceParent } from "../Util/TraceParent.ts"; |
| 31 | import { handleCliErrors, installShutdownFeedback } from "./commands/errors.ts"; |
| 32 | import { renderPlanning } from "./commands/render.ts"; |
| 33 | import { stackOutputsView } from "./components/view/StackOutputs.tsx"; |
| 34 | import { DEV_RELOAD_EXIT_CODE, DevOptions } from "./DevOptions.ts"; |
| 35 | import { ConsoleLogLive } from "./GlobalLog.ts"; |
| 36 | import { selectCliServices } from "./selectCli.ts"; |
| 37 | |
| 38 | // Interactive dev/deploy runs use the Sigil progress UI; CI, redirected output, |
| 39 | // and other non-interactive terminals still select the append-only renderer. |
| 40 | // `ALCHEMY_TUI` remains the explicit override in either direction. |
| 41 | const services = Layer.mergeAll( |
| 42 | Layer.provideMerge(selectCliServices(), Interaction.layer()), |
| 43 | RpcProviderProxy.fromEnv(), |
| 44 | Layer.succeed(ArtifactStore, createArtifactStore()), |
| 45 | // Dev runs live in this exec child, not the `alchemy` CLI process, so |
| 46 | // without this layer they'd export no telemetry at all. No root |
| 47 | // `cli.dev` span though: dev remains alive across reloads, so a wrapping |
| 48 | // span would not end (and export) until shutdown — plan/apply spans are the |
| 49 | // trace roots instead. |
| 50 | TelemetryLive, |
| 51 | ConsoleLogLive, |
| 52 | ).pipe( |
| 53 | Layer.provideMerge(Layer.mergeAll(AlchemyContextLive, ProfileStoreLive, CredentialsStoreLive)), |
| 54 | Layer.provideMerge( |
| 55 | Layer.mergeAll( |
| 56 | PlatformServices, |
| 57 | FetchHttpClient.layer, |
| 58 | ConfigProvider.layer(ConfigProvider.fromEnv()), |
| 59 | ), |
| 60 | ), |
| 61 | ); |
| 62 | |
| 63 | /** `alchemy dev` normally parks forever; set for single-pass runs (tests). */ |
| 64 | const devOnce = Config.String("ALCHEMY_DEV_ONCE").pipe( |
| 65 | Config.withDefault(""), |
| 66 | Effect.map((value) => value === "1" || value === "true"), |
| 67 | ); |
| 68 | |
| 69 | const runDev = Effect.fn(function* (options: DevOptions) { |
| 70 | const snapshot = yield* Alchemist.importStack(options.main).pipe( |
| 71 | Effect.flatMap((stack) => |
| 72 | Alchemist.plan({ |
| 73 | stack, |
| 74 | operation: "deploy", |
| 75 | stage: options.stage, |
| 76 | profile: options.profile, |
| 77 | envFile: Option.getOrUndefined(options.envFile), |
| 78 | updateStateStore: true, |
| 79 | dev: true, |
| 80 | force: options.force, |
| 81 | include: options.include, |
| 82 | exclude: options.exclude, |
| 83 | }), |
| 84 | ), |
| 85 | renderPlanning({ operation: "Dev", stage: options.stage }), |
| 86 | ); |
| 87 | const once = yield* devOnce; |
| 88 | const applyAndRender = Alchemist.apply(snapshot).pipe( |
| 89 | renderApply(snapshot.native, { |
| 90 | stage: options.stage, |
| 91 | dev: !once, |
| 92 | }), |
| 93 | ); |
| 94 | const result = yield* once |
| 95 | ? applyAndRender |
| 96 | : applyAndRender.pipe( |
| 97 | Effect.catchCause((cause) => |
| 98 | Effect.logError( |
| 99 | describeFailure("apply", cause, "keeping dev alive so healthy resources keep serving"), |
| 100 | ).pipe(Effect.as(undefined)), |
| 101 | ), |
| 102 | ); |
| 103 | if (result !== undefined && once) { |
| 104 | const kit = yield* Interaction.Interaction; |
| 105 | yield* kit.output.print(stackOutputsView(result)); |
| 106 | } |
| 107 | return once ? undefined : yield* Effect.never; |
| 108 | }); |
| 109 | |
| 110 | /** |
| 111 | * Resolves with the files behind the next debounced change batch. The |
| 112 | * listener detaches itself on delivery — `Effect.callback` only runs its |
| 113 | * cleanup on interruption, so a listener left behind would fire once per |
| 114 | * past generation on every later change. |
| 115 | */ |
| 116 | const nextChange = (watcher: { |
| 117 | subscribe: (listener: (change: { paths: ReadonlySet<string> }) => void) => () => void; |
| 118 | }) => |
| 119 | Effect.callback<ReadonlySet<string>>((resume) => { |
| 120 | const unsubscribe = watcher.subscribe(({ paths }) => { |
| 121 | unsubscribe(); |
| 122 | resume(Effect.succeed(paths)); |
| 123 | }); |
| 124 | return Effect.sync(unsubscribe); |
| 125 | }); |
| 126 | |
| 127 | const logReload = Effect.fn(function* (paths: ReadonlySet<string>) { |
| 128 | const path = yield* Path.Path; |
| 129 | yield* Effect.logInfo( |
| 130 | `Reloading stack: changed ${[...paths] |
| 131 | .map((file) => path.relative(initialCwd, file)) |
| 132 | .join(", ")}`, |
| 133 | ); |
| 134 | }); |
| 135 | |
| 136 | /** |
| 137 | * Node: one process, many generations. The Oxc loader imports the stack graph |
| 138 | * under a fresh namespace each time; a change to any file it loaded |
| 139 | * interrupts the parked run (whose scope tears down the dev widget) and the |
| 140 | * loop imports the next generation. |
| 141 | */ |
| 142 | const runNodeDevWatcher = Effect.fn(function* (options: DevOptions) { |
| 143 | const fs = yield* FileSystem.FileSystem; |
| 144 | const path = yield* Path.Path; |
| 145 | // Node reports real paths for loaded files (symlinked checkouts, macOS |
| 146 | // `/tmp`), so the project root the graph is scoped to must be real too. |
| 147 | // Scope to the invocation directory, not the entrypoint's directory: a |
| 148 | // config under `infra/` commonly imports application code from `src/`. |
| 149 | const entrypoint = yield* fs.realPath(yield* resolveStackEntrypoint(options.main)); |
| 150 | const root = yield* fs.realPath(initialCwd); |
| 151 | const nodeModules = `${path.sep}node_modules${path.sep}`; |
| 152 | return yield* Effect.acquireRelease( |
| 153 | Effect.sync(() => |
| 154 | watchImport<{ readonly default?: unknown }>(entrypoint, { |
| 155 | parentURL: import.meta.url, |
| 156 | shouldInvalidate: (url) => { |
| 157 | if (!url.startsWith("file:")) return false; |
| 158 | const file = fileURLToPath(url); |
| 159 | const relative = path.relative(root, file); |
| 160 | return ( |
| 161 | !file.includes(nodeModules) && |
| 162 | (relative === "" || |
| 163 | (relative !== ".." && |
| 164 | !relative.startsWith(`..${path.sep}`) && |
| 165 | !path.isAbsolute(relative))) |
| 166 | ); |
| 167 | }, |
| 168 | }), |
| 169 | ), |
| 170 | (watcher) => Effect.promise(() => watcher.close()), |
| 171 | ).pipe( |
| 172 | Effect.flatMap((watcher) => { |
| 173 | const generation = devKeepAlive(runDev(options)).pipe( |
| 174 | Effect.provideService(StackModuleLoader, { |
| 175 | import: () => watcher.import().then(({ value }) => value), |
| 176 | }), |
| 177 | Effect.scoped, |
| 178 | ); |
| 179 | return Effect.forever( |
| 180 | Effect.raceFirst(generation, nextChange(watcher)).pipe( |
| 181 | Effect.flatMap((paths) => (paths === undefined ? Effect.void : logReload(paths))), |
| 182 | ), |
| 183 | ); |
| 184 | }), |
| 185 | ); |
| 186 | }); |
| 187 | |
| 188 | /** |
| 189 | * Bun: one process per generation. Bun cannot evict evaluated modules, so the |
| 190 | * tracker only records which project files the stack graph loads; the first |
| 191 | * change to one of them logs, lets the generation scope tear down the dev |
| 192 | * widget, and exits with DEV_RELOAD_EXIT_CODE for the supervisor to respawn. |
| 193 | */ |
| 194 | const runBunDevWatcher = (options: DevOptions) => |
| 195 | Effect.acquireRelease( |
| 196 | Effect.sync(() => |
| 197 | // Match Node's project-wide graph: the stack entrypoint may live in a |
| 198 | // subdirectory while importing sibling source trees. |
| 199 | trackBunImports({ root: initialCwd }), |
| 200 | ), |
| 201 | (tracker) => Effect.promise(() => tracker.close()), |
| 202 | ).pipe( |
| 203 | Effect.flatMap((tracker) => |
| 204 | Effect.raceFirst(devKeepAlive(runDev(options)).pipe(Effect.scoped), nextChange(tracker)), |
| 205 | ), |
| 206 | Effect.flatMap((paths) => |
| 207 | paths === undefined |
| 208 | ? Effect.void |
| 209 | : logReload(paths).pipe( |
| 210 | Effect.andThen( |
| 211 | Effect.sync(() => { |
| 212 | process.exitCode = DEV_RELOAD_EXIT_CODE; |
| 213 | }), |
| 214 | ), |
| 215 | ), |
| 216 | ), |
| 217 | ); |
| 218 | |
| 219 | /** |
| 220 | * A run that ended by itself with nothing but interruptions in its cause was |
| 221 | * cancelled from the inside — a provider or engine race, never the user — |
| 222 | * so it must be reported like any other failure. Ctrl+C is different: it |
| 223 | * interrupts the fiber running this code, so `catchCause` never gets to |
| 224 | * park it (a parked `Effect.never` is interrupted straight away too). |
| 225 | */ |
| 226 | const describeFailure = (what: string, cause: Cause.Cause<unknown>, next: string) => |
| 227 | Cause.hasInterruptsOnly(cause) |
| 228 | ? `alchemy dev: ${what} was interrupted internally (a bug in a provider or the engine — please report it with the trace below); ${next}.\n${Cause.pretty(cause)}` |
| 229 | : `alchemy dev: ${what} failed; ${next}.\n${Cause.pretty(cause)}`; |
| 230 | |
| 231 | // A mid-edit import or planning failure must keep the watch process alive so |
| 232 | // the next save can restart it. Ctrl+C still tears the run down. |
| 233 | export const devKeepAlive = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> => |
| 234 | effect.pipe( |
| 235 | Effect.catchCause((cause) => |
| 236 | Effect.logError( |
| 237 | describeFailure("run", cause, "waiting for the next file change to retry"), |
| 238 | ).pipe(Effect.andThen(Effect.never)), |
| 239 | ), |
| 240 | ); |
| 241 | |
| 242 | const makeExec = () => { |
| 243 | // Decoded eagerly when the program is constructed, not when it runs. |
| 244 | // oxlint-disable-next-line effecttsgo/schema-sync |
| 245 | const options = Schema.decodeSync(DevOptions)(JSON.parse(process.env.ALCHEMY_EXEC_OPTIONS!)); |
| 246 | return Effect.gen(function* () { |
| 247 | yield* installShutdownFeedback; |
| 248 | // Subscribe to the spawner's sidecar log stream BEFORE the stack runs: |
| 249 | // this process owns the terminal renderer, so sidecar output printed |
| 250 | // here lands in chronological order with the run's own lines instead of |
| 251 | // racing the shared tty. No-op outside dev. Like every record of this |
| 252 | // process, they also go up to the `alchemy dev` process, which writes |
| 253 | // the run log (see `parentLogLayer`). |
| 254 | yield* forwardSidecarLogs; |
| 255 | // Single-pass runs park nothing. Otherwise Node reloads the stack graph in |
| 256 | // this process; Bun exits for the supervisor to respawn (see above). |
| 257 | return yield* (yield* devOnce) |
| 258 | ? devKeepAlive(runDev(options)) |
| 259 | : process.versions.bun !== undefined |
| 260 | ? runBunDevWatcher(options) |
| 261 | : runNodeDevWatcher(options); |
| 262 | }).pipe( |
| 263 | logShutdown("exec"), |
| 264 | // Spans join the trace `alchemy dev` passed down, like the records |
| 265 | // logged outside them already do. |
| 266 | withTraceParent(processTrace), |
| 267 | Effect.provide(Layer.provideMerge(parentLogLayer(), services)), |
| 268 | Effect.provideService(LogProcess, "exec"), |
| 269 | Effect.scoped, |
| 270 | handleCliErrors, |
| 271 | ); |
| 272 | }; |
| 273 | |
| 274 | /** Fully wired sidecar CLI program. */ |
| 275 | export const exec: () => Effect.Effect<void, Effect.Error<ReturnType<typeof makeExec>>> = makeExec; |