The best way to control Claude Code, Codex and more from any computer or phone

main
ts 182 lines 6.97 KB
Raw
1 import { Command, Flag } from "effect/cli";
2 import * as Clock from "effect/Clock";
3 import * as Console from "effect/Console";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import * as Option from "effect/Option";
7 import * as Alchemist from "../../Alchemist/index.ts";
8 import * as Interaction from "../../Interaction.ts";
9 import { renderNukeScan, renderNukeDelete, reviewNuke } from "../components/view/Nuke.tsx";
10 import { formatElapsed } from "../Format.ts";
11 import { exitDeclined, UserInputError } from "./errors.ts";
12 import { configPath, envFile, optionalConfig, profile, resolveConfig, yes } from "./flags.ts";
13 import { instrumentCommand } from "./instrument.ts";
14
15 const includeFlag = Flag.String("include").pipe(
16 Flag.withDescription("Glob of provider IDs to include (repeatable)"),
17 Flag.atLeast(0),
18 );
19 const excludeFlag = Flag.String("exclude").pipe(
20 Flag.withDescription("Glob of provider IDs to exclude (repeatable)"),
21 Flag.atLeast(0),
22 );
23 const filterFlag = Flag.String("filter").pipe(
24 Flag.withDescription(
25 "JavaScript expression evaluated with resource in scope; matching resources are excluded from deletion (repeatable)",
26 ),
27 Flag.atLeast(0),
28 );
29 const concurrencyFlag = Flag.Int("concurrency").pipe(
30 Flag.withDescription("Maximum providers processed in parallel; 0 is unbounded"),
31 Flag.withDefault(16),
32 Flag.map((value): number | "unbounded" => (value <= 0 ? "unbounded" : value)),
33 );
34 const timeoutFlag = Flag.Int("timeout").pipe(
35 Flag.withDescription("Per-provider timeout in seconds"),
36 Flag.withDefault(120),
37 Flag.map(Duration.seconds),
38 );
39 const independentFlag = Flag.Boolean("independent").pipe(
40 Flag.withDescription("Retry each resource independently"),
41 Flag.withDefault(false),
42 );
43 const retriesFlag = Flag.Int("retries").pipe(
44 Flag.withDescription("Independent retries per resource"),
45 Flag.withDefault(10),
46 );
47 const localFlag = Flag.Boolean("local").pipe(
48 Flag.withDescription("Target only locally emulated providers"),
49 Flag.withDefault(false),
50 );
51 const dryRunFlag = Flag.Boolean("dry-run").pipe(
52 Flag.withDescription("Scan and show targets without deleting"),
53 Flag.withDefault(false),
54 );
55
56 // A broken filter must abort the nuke, not silently widen the kill list:
57 // compile and evaluation errors both fail the command before any deletion.
58 const compileFilter = (expression: string) =>
59 Effect.try({
60 try: () =>
61 // oxlint-disable-next-line typescript/no-implied-eval -- --filter is a user-supplied JS expression by design
62 new Function("scope", `with (scope) { return (${expression}); }`) as (scope: {
63 resource: Record<string, unknown>;
64 }) => unknown,
65 catch: (cause) =>
66 new UserInputError({
67 message: `--filter expression ${JSON.stringify(expression)} failed to compile: ${cause instanceof Error ? cause.message : String(cause)}`,
68 }),
69 }).pipe(
70 Effect.map(
71 (predicate) => (resource: Record<string, unknown>) =>
72 Effect.try({
73 try: () => Boolean(predicate({ resource })),
74 catch: (cause) =>
75 new UserInputError({
76 message: `--filter expression ${JSON.stringify(expression)} threw while evaluating a resource: ${cause instanceof Error ? cause.message : String(cause)}`,
77 }),
78 }),
79 ),
80 );
81
82 const nukeCommand = Command.make(
83 "nuke",
84 {
85 config: optionalConfig,
86 configPath,
87 envFile,
88 profile,
89 yes,
90 dryRun: dryRunFlag,
91 concurrency: concurrencyFlag,
92 timeout: timeoutFlag,
93 independent: independentFlag,
94 retries: retriesFlag,
95 include: includeFlag,
96 exclude: excludeFlag,
97 filter: filterFlag,
98 local: localFlag,
99 },
100 (args) =>
101 resolveConfig(args).pipe(
102 Effect.flatMap(
103 instrumentCommand("unsafe.nuke", (args: { profile: string | undefined; main: string }) => ({
104 "alchemy.profile": args.profile ?? "",
105 "alchemy.main": args.main,
106 }))(
107 Effect.fn(function* (args) {
108 const scan = yield* Effect.flatMap(Alchemist.importStack(args.main), (stack) =>
109 Alchemist.Nuke.scan({
110 stack,
111 profile: args.profile,
112 envFile: Option.getOrUndefined(args.envFile),
113 dev: args.local,
114 include: args.include,
115 exclude: args.exclude,
116 concurrency: args.concurrency,
117 providerTimeoutSeconds: Duration.toSeconds(args.timeout),
118 }),
119 ).pipe(renderNukeScan());
120 const predicates = yield* Effect.forEach(args.filter, compileFilter);
121 const targets: Array<(typeof scan.resources)[number]> = [];
122 for (const resource of scan.resources) {
123 const matches = yield* Effect.forEach(predicates, (predicate) =>
124 predicate({
125 ...resource.attributes,
126 Type: resource.providerId,
127 LogicalId: resource.displayName,
128 }),
129 );
130 if (!matches.some(Boolean)) targets.push(resource);
131 }
132 if (targets.length === 0) {
133 yield* Interaction.info("Nothing to delete.");
134 return;
135 }
136 const approved = yield* reviewNuke(targets, {
137 mode: scan.mode,
138 yes: args.yes,
139 dryRun: args.dryRun,
140 });
141 if (!approved) {
142 yield* Interaction.info("Aborted.");
143 return yield* exitDeclined;
144 }
145 if (args.dryRun) {
146 yield* Console.log("Dry run complete: nothing was deleted.");
147 return;
148 }
149 const deleteStartedAt = yield* Clock.currentTimeMillis;
150 const result = yield* Alchemist.Nuke.execute({
151 scan,
152 resources: targets,
153 strategy: args.independent
154 ? { type: "independent", retries: args.retries }
155 : { type: "coordinated" },
156 concurrency: args.concurrency,
157 providerTimeoutSeconds: Duration.toSeconds(args.timeout),
158 }).pipe(renderNukeDelete(targets, scan.mode));
159 const deleteElapsed = (yield* Clock.currentTimeMillis) - deleteStartedAt;
160 yield* Interaction.success(
161 `Deleted ${result.deleted.length} resource(s) over ${result.passes} pass(es) (${formatElapsed(deleteElapsed)}).`,
162 );
163 if (result.held.length > 0) {
164 yield* Interaction.warning(`${result.held.length} resource(s) were held back.`);
165 }
166 if (result.failed.length > 0) {
167 yield* Interaction.error(`${result.failed.length} resource(s) could not be deleted.`);
168 }
169 }),
170 ),
171 ),
172 ),
173 ).pipe(
174 Command.withDescription("Enumerate resources across the stack providers and delete them"),
175 Command.unlisted,
176 );
177
178 export const unsafeCommand = Command.make("unsafe", {}).pipe(
179 Command.withDescription("Dangerous, irreversible operations"),
180 Command.withSubcommands([nukeCommand]),
181 Command.unlisted,
182 );