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, 06:00 UTC
| 1 | import { AlchemyContext, AlchemyContextLive } from "alchemy/AlchemyContext"; |
| 2 | import { ArtifactStore, createArtifactStore } from "alchemy/Artifacts"; |
| 3 | import { CredentialsStoreLive } from "alchemy/Auth/Credentials"; |
| 4 | import { ProfileStoreLive } from "alchemy/Auth/Profile"; |
| 5 | import * as Contributions from "alchemy/Contributions"; |
| 6 | import { TelemetryLive } from "alchemy/Telemetry/Layer"; |
| 7 | import { moduleExtension } from "alchemy/Util/Node"; |
| 8 | import { PlatformServices } from "alchemy/Util/PlatformServices"; |
| 9 | import * as CliConfig from "effect/cli/CliConfig"; |
| 10 | import * as CliError from "effect/cli/CliError"; |
| 11 | import * as Command from "effect/cli/Command"; |
| 12 | import * as Flag from "effect/cli/Flag"; |
| 13 | import * as GlobalFlag from "effect/cli/GlobalFlag"; |
| 14 | import * as ConfigProvider from "effect/ConfigProvider"; |
| 15 | import * as Context from "effect/Context"; |
| 16 | import * as Effect from "effect/Effect"; |
| 17 | import * as FileSystem from "effect/FileSystem"; |
| 18 | import * as FetchHttpClient from "effect/http/FetchHttpClient"; |
| 19 | import * as HttpClient from "effect/http/HttpClient"; |
| 20 | import * as Layer from "effect/Layer"; |
| 21 | import * as Path from "effect/Path"; |
| 22 | import * as Scope from "effect/Scope"; |
| 23 | import packageJson from "../../package.json" with { type: "json" }; |
| 24 | import * as Interaction from "../Interaction.ts"; |
| 25 | import { logShutdown } from "../Util/Shutdown.ts"; |
| 26 | import { checkLatestVersion } from "./checkVersion.ts"; |
| 27 | import { |
| 28 | compatibilityCommand, |
| 29 | compatibilityCommands, |
| 30 | type CompatibilityCommand, |
| 31 | } from "./commands/compat.ts"; |
| 32 | import { handleCliErrors } from "./commands/errors.ts"; |
| 33 | import { VersionCheck } from "./commands/instrument.ts"; |
| 34 | import { GlobalLogLive, LogFormatFlag, LogLevelFlag } from "./GlobalLog.ts"; |
| 35 | import { selectCliServices } from "./selectCli.ts"; |
| 36 | |
| 37 | const commandMetadata = [ |
| 38 | ["provider", "Manage cloud provider prerequisites and utilities"], |
| 39 | ["deploy", "Deploy a stack"], |
| 40 | ["dev", "Develop a stack with live reload"], |
| 41 | ["destroy", "Destroy a deployed stack"], |
| 42 | ["plan", "Preview changes to a stack"], |
| 43 | ["logs", "Fetch or tail logs from stack resources"], |
| 44 | ["profile", "Manage authentication profiles and accounts"], |
| 45 | ["state", "Inspect and manage deployment state"], |
| 46 | ["drift", "Detect infrastructure drift"], |
| 47 | ["unsafe", "Unsafe maintenance commands"], |
| 48 | ] as const; |
| 49 | |
| 50 | type CommandName = (typeof commandMetadata)[number][0]; |
| 51 | |
| 52 | const placeholderCommand = (name: CommandName, description: string) => |
| 53 | Command.make(name, {}, () => Effect.void).pipe( |
| 54 | Command.withDescription(description), |
| 55 | name === "unsafe" ? Command.unlisted : (command) => command, |
| 56 | ); |
| 57 | |
| 58 | // A broken provider shouldn't take the whole CLI down: warn and run without |
| 59 | // providers. Commands that need them (auth, `state --backend`) fail with the |
| 60 | // provider error when they load them again. |
| 61 | const loadContributions = () => |
| 62 | Effect.runPromise( |
| 63 | Contributions.load().pipe( |
| 64 | Effect.catch((error) => Effect.as(Effect.logWarning(error.message), [])), |
| 65 | Effect.provide(PlatformServices), |
| 66 | ), |
| 67 | ); |
| 68 | |
| 69 | const loadCommand = async (name: CommandName) => { |
| 70 | switch (name) { |
| 71 | case "provider": |
| 72 | return (await import("./commands/provider.ts")).providerCommand(await loadContributions()); |
| 73 | case "deploy": |
| 74 | return (await import("./commands/deploy.ts")).deployCommand; |
| 75 | case "dev": |
| 76 | return (await import("./commands/dev.ts")).devCommand; |
| 77 | case "destroy": |
| 78 | return (await import("./commands/deploy.ts")).destroyCommand; |
| 79 | case "plan": |
| 80 | return (await import("./commands/deploy.ts")).planCommand; |
| 81 | case "logs": |
| 82 | return (await import("./commands/logs.ts")).logsCommand; |
| 83 | case "profile": |
| 84 | return (await import("./commands/profile/index.ts")).profileCommand; |
| 85 | case "state": |
| 86 | return (await import("./commands/state.ts")).stateCommand; |
| 87 | case "drift": |
| 88 | return (await import("./commands/drift.ts")).driftCommand; |
| 89 | case "unsafe": |
| 90 | return (await import("./commands/nuke.ts")).unsafeCommand; |
| 91 | } |
| 92 | }; |
| 93 | |
| 94 | const argv = process.argv.slice(2); |
| 95 | const compatibilityName = Object.hasOwn(compatibilityCommands, argv[0] ?? "") |
| 96 | ? (argv[0] as CompatibilityCommand) |
| 97 | : undefined; |
| 98 | |
| 99 | // Compatibility commands only print their replacement. Discard everything |
| 100 | // after the old command name so historical positional arguments and flags are |
| 101 | // accepted without teaching the retired parser surface about every old form. |
| 102 | if (compatibilityName !== undefined) { |
| 103 | const index = process.argv.indexOf(compatibilityName, 2); |
| 104 | process.argv.splice(index + 1); |
| 105 | } |
| 106 | |
| 107 | const commandNames = new Set<CommandName>(commandMetadata.map(([name]) => name)); |
| 108 | const requestedCommand = argv.find((value): value is CommandName => |
| 109 | commandNames.has(value as CommandName), |
| 110 | ); |
| 111 | const loadEveryCommand = argv.includes("--completions"); |
| 112 | const commands = await Promise.all( |
| 113 | commandMetadata.map(([name, description]) => |
| 114 | loadEveryCommand || name === requestedCommand |
| 115 | ? loadCommand(name) |
| 116 | : Promise.resolve(placeholderCommand(name, description)), |
| 117 | ), |
| 118 | ); |
| 119 | |
| 120 | /** |
| 121 | * `--no-input` forces plain, prompt-free output regardless of TTY or env |
| 122 | * detection. The value is read via an argv scan in `Util/interactive.ts` |
| 123 | * (capability detection runs while the service layers are built, before flag |
| 124 | * parsing); this registration exists so the parser accepts the flag. |
| 125 | */ |
| 126 | const NoInput = GlobalFlag.Setting("no-input")({ |
| 127 | flag: Flag.Boolean("no-input").pipe( |
| 128 | Flag.withDescription( |
| 129 | "Disable prompts and the interactive TUI (plain output; commands needing input fail)", |
| 130 | ), |
| 131 | Flag.withDefault(false), |
| 132 | ), |
| 133 | }); |
| 134 | |
| 135 | /** |
| 136 | * `--fast-distilled` loads distilled SDKs through their lazy service stubs |
| 137 | * under Node. The launcher (`bin/cli.js`) reads it from argv before any |
| 138 | * module loads and passes it on as `ALCHEMY_FAST_DISTILLED=1`; this |
| 139 | * registration exists so the parser accepts the flag. |
| 140 | */ |
| 141 | const FastDistilled = GlobalFlag.Setting("fast-distilled")({ |
| 142 | flag: Flag.Boolean("fast-distilled").pipe( |
| 143 | Flag.withDescription( |
| 144 | "Load distilled SDK operations on first use (Node only; lowers startup memory)", |
| 145 | ), |
| 146 | Flag.withDefault(false), |
| 147 | ), |
| 148 | }); |
| 149 | |
| 150 | const root = Command.make("alchemy", {}, () => |
| 151 | Effect.fail(CliError.ShowHelp.make({ commandPath: ["alchemy"], errors: [] })), |
| 152 | ).pipe( |
| 153 | Command.withDescription( |
| 154 | "Define, deploy, and operate cloud infrastructure with type-safe Effect programs.", |
| 155 | ), |
| 156 | Command.withExamples([ |
| 157 | { command: "alchemy deploy" }, |
| 158 | { command: "alchemy plan --stage prod" }, |
| 159 | { command: "alchemy dev" }, |
| 160 | { command: "alchemy logs --tail" }, |
| 161 | ]), |
| 162 | Command.withSubcommands([ |
| 163 | ...commands, |
| 164 | ...Object.keys(compatibilityCommands).map((name) => |
| 165 | compatibilityCommand(name as CompatibilityCommand), |
| 166 | ), |
| 167 | ]), |
| 168 | Command.withGlobalFlags([NoInput, FastDistilled, LogLevelFlag, LogFormatFlag]), |
| 169 | ); |
| 170 | |
| 171 | /** |
| 172 | * How this CLI process is running, appended to `--version` in a checkout |
| 173 | * for debugging the launcher's implicit mode selection (`bin/cli.js`): the |
| 174 | * runtime, and whether we're executing `.ts` source (bun, or node with type |
| 175 | * stripping + the Oxc register hook) or built output — `node <x>, lib` is |
| 176 | * the tell for the old-node fallback that still needs a build. Published |
| 177 | * installs print the plain version string. |
| 178 | */ |
| 179 | const devRunMode = import.meta.url.includes("/node_modules/") |
| 180 | ? undefined |
| 181 | : `${ |
| 182 | typeof globalThis.Bun !== "undefined" |
| 183 | ? `bun ${globalThis.Bun.version}` |
| 184 | : `node ${process.versions.node}` |
| 185 | }, ${moduleExtension(import.meta.url) === ".ts" ? "src" : "lib"}`; |
| 186 | |
| 187 | const cli = Command.run(root, { |
| 188 | version: |
| 189 | devRunMode === undefined ? packageJson.version : `${packageJson.version} (${devRunMode})`, |
| 190 | }); |
| 191 | |
| 192 | const services = Layer.mergeAll( |
| 193 | CliConfig.layer({ |
| 194 | builtIns: [GlobalFlag.Help, GlobalFlag.Version, GlobalFlag.Completions], |
| 195 | }), |
| 196 | Layer.provideMerge(AlchemyContextLive, PlatformServices), |
| 197 | Layer.provide(ProfileStoreLive, PlatformServices), |
| 198 | Layer.provide(CredentialsStoreLive, PlatformServices), |
| 199 | // Ambient per-CLI-run artifact root. Commands that define their own run |
| 200 | // boundary (deploy, drift) provide a fresh store closer to the work, which |
| 201 | // wins over this one. |
| 202 | Layer.succeed(ArtifactStore, createArtifactStore()), |
| 203 | FetchHttpClient.layer, |
| 204 | ConfigProvider.layer(ConfigProvider.fromEnv()), |
| 205 | Layer.provide(Layer.provideMerge(selectCliServices(), Interaction.layer()), PlatformServices), |
| 206 | // Debug run log in the project's .alchemy/log — the console noise floor stays at |
| 207 | // Info, but full causes and auth-flow breadcrumbs land in the file so |
| 208 | // support can ask users for it. |
| 209 | Layer.provide(GlobalLogLive, PlatformServices), |
| 210 | TelemetryLive, |
| 211 | ); |
| 212 | |
| 213 | const program = Effect.gen(function* () { |
| 214 | // Best-effort check for a newer published version, run by each command |
| 215 | // before its handler: the console flags are parsed by then, and the |
| 216 | // warning prints before any interactive prompt. Cached for a day and |
| 217 | // bounded by a short timeout, so it stays fast. Its fetch may finish in |
| 218 | // the background, in this scope. |
| 219 | // Only the check's own services, so the command's flags and loggers win. |
| 220 | const services = Context.pick( |
| 221 | AlchemyContext, |
| 222 | FileSystem.FileSystem, |
| 223 | HttpClient.HttpClient, |
| 224 | Path.Path, |
| 225 | Scope.Scope, |
| 226 | )( |
| 227 | yield* Effect.context< |
| 228 | AlchemyContext | FileSystem.FileSystem | HttpClient.HttpClient | Path.Path | Scope.Scope |
| 229 | >(), |
| 230 | ); |
| 231 | const check = yield* Effect.cached(Effect.provideContext(checkLatestVersion, services)); |
| 232 | return yield* cli.pipe(Effect.provideService(VersionCheck, check)); |
| 233 | }).pipe(logShutdown("cli")); |
| 234 | |
| 235 | const mainEffect = program.pipe( |
| 236 | // $USER and $ALCHEMY_STAGE are set by the environment |
| 237 | Effect.provide(services), |
| 238 | Effect.scoped, |
| 239 | handleCliErrors, |
| 240 | ); |
| 241 | |
| 242 | /** Fully wired CLI program. */ |
| 243 | export const main = mainEffect as Effect.Effect<void, Effect.Error<typeof mainEffect>>; |