@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 466 lines 16.1 KB
Raw
1 import { Command, Flag } from "effect/cli";
2 import * as Argument from "effect/cli/Argument";
3 import * as Console from "effect/Console";
4 import * as Effect from "effect/Effect";
5 import * as Option from "effect/Option";
6 import * as Stream from "effect/Stream";
7 import * as Alchemist from "../../Alchemist/index.ts";
8 import type { StateStoreLogEntry } from "../../Contributions.ts";
9 import * as Interaction from "../../Interaction.ts";
10 import * as State from "../../State/index.ts";
11 import {
12 stateExplorerScreen,
13 type StateExplorerSource,
14 } from "../components/view/StateExplorer.tsx";
15 import { formatLocalTimestamp } from "../Format.ts";
16 import { confirmOrDecline } from "./confirm.ts";
17 import { failWithHelp, UserInputError } from "./errors.ts";
18 import { envFile, parseSince, profile, yes } from "./flags.ts";
19 import { instrumentCommand } from "./instrument.ts";
20
21 const backend = Flag.String("backend").pipe(
22 Flag.withDescription(
23 "State backend: configured (default), local, or a provider's state store (e.g. aws, cloudflare)",
24 ),
25 Flag.withDefault("configured"),
26 );
27 /** A provider's store other than the account's default, e.g. an S3 bucket. */
28 const storeName = Flag.String("name").pipe(
29 Flag.withDescription(
30 "State store to address instead of the account's default (e.g. an S3 bucket; with --backend)",
31 ),
32 Flag.optional,
33 Flag.map(Option.getOrUndefined),
34 );
35 const config = Flag.File("config").pipe(
36 Flag.withDescription("Alchemy entrypoint file (default: alchemy.run.ts)"),
37 Flag.withAlias("c"),
38 Flag.withDefault("alchemy.run.ts"),
39 );
40 const pathArgument = Argument.String("path").pipe(
41 Argument.withDescription("State path (stack/stage/namespace/resource)"),
42 Argument.optional,
43 );
44 const requiredPathArgument = Argument.String("path").pipe(
45 Argument.withDescription("State path (stack/stage/namespace/resource)"),
46 );
47 const recursive = Flag.Boolean("recursive").pipe(
48 Flag.withAlias("r"),
49 Flag.withDescription("Operate recursively on directories"),
50 Flag.withDefault(false),
51 );
52
53 type StateArgs = {
54 readonly main: string;
55 readonly envFile: Option.Option<string>;
56 readonly profile: string | undefined;
57 readonly backend: string;
58 readonly name: string | undefined;
59 };
60
61 const source = (args: StateArgs): Alchemist.State.StateSource =>
62 args.backend === "local"
63 ? { type: "local" }
64 : args.backend === "configured"
65 ? {
66 type: "configured",
67 entrypoint: args.main,
68 profile: args.profile,
69 envFile: Option.getOrUndefined(args.envFile),
70 }
71 : {
72 type: "provider",
73 backend: args.backend,
74 name: args.name,
75 profile: args.profile,
76 envFile: Option.getOrUndefined(args.envFile),
77 };
78
79 /** Lifecycle commands act on a provider's state store. */
80 const lifecycleBackend = Flag.String("backend").pipe(
81 Flag.withDescription("Provider state store to act on (e.g. aws, cloudflare)"),
82 );
83
84 const lifecycleSource = (
85 args: Pick<StateArgs, "envFile" | "profile" | "backend" | "name">,
86 ): Alchemist.State.ProviderSource => ({
87 type: "provider",
88 backend: args.backend,
89 name: args.name,
90 profile: args.profile,
91 envFile: Option.getOrUndefined(args.envFile),
92 });
93
94 const normalizedPath = (path: string | undefined) => {
95 const parts = (path ?? "").split("/").filter((part) => part !== "" && part !== ".");
96 return parts.includes("..")
97 ? Effect.fail(new UserInputError({ message: `invalid state path: ${path ?? "/"}` }))
98 : Effect.succeed(parts.join("/"));
99 };
100
101 const provideStore =
102 (store: State.StateService) =>
103 <A, E>(operation: Effect.Effect<A, E, State.State>) =>
104 operation.pipe(Effect.provideService(State.State, Effect.succeed(store)));
105
106 /** Run a state tree operation against a resolved store, mapping a bad path
107 * to a single-line user error instead of a cause dump. */
108 const usingStore =
109 (store: State.StateService) =>
110 <A>(operation: Effect.Effect<A, State.InvalidStatePath | State.StateStoreError, State.State>) =>
111 provideStore(store)(operation).pipe(
112 Effect.catchTag("InvalidStatePath", (error) =>
113 Effect.fail(new UserInputError({ message: `${error.path}: ${error.reason}` })),
114 ),
115 );
116
117 const listCommand = Command.make(
118 "list",
119 { path: pathArgument, recursive, main: config, envFile, profile, backend, name: storeName },
120 instrumentCommand("state.list")(
121 Effect.fn(function* ({ path, recursive, ...args }) {
122 const store = yield* Alchemist.State.store(source(args));
123 const items = yield* usingStore(store)(
124 State.listState({
125 path: yield* path.pipe(Option.getOrUndefined, normalizedPath),
126 recursive,
127 }),
128 );
129 yield* Console.log([...items].sort().join("\n"));
130 }),
131 ),
132 ).pipe(Command.withAlias("ls"), Command.withDescription("List a state-store directory"));
133
134 const readCommand = Command.make(
135 "read",
136 { path: pathArgument, recursive, main: config, envFile, profile, backend, name: storeName },
137 instrumentCommand("state.read")(
138 Effect.fn(function* ({ path, recursive, ...args }) {
139 const store = yield* Alchemist.State.store(source(args));
140 const requested = yield* path.pipe(Option.getOrUndefined, normalizedPath);
141 const entries = yield* usingStore(store)(State.readState({ path: requested, recursive }));
142 yield* Console.log(
143 JSON.stringify(
144 entries.length === 1
145 ? entries[0]!.value
146 : Object.fromEntries(entries.map((entry) => [entry.path, entry.value])),
147 null,
148 2,
149 ),
150 );
151 }),
152 ),
153 ).pipe(Command.withAlias("cat"), Command.withDescription("Read a state-store file or directory"));
154
155 const deleteCommand = Command.make(
156 "delete",
157 {
158 path: requiredPathArgument,
159 recursive,
160 main: config,
161 envFile,
162 profile,
163 backend,
164 name: storeName,
165 },
166 instrumentCommand("state.delete")(
167 Effect.fn(function* ({ path, recursive, ...args }) {
168 const requested = yield* normalizedPath(path);
169 if (requested === "") {
170 return yield* new UserInputError({ message: "cannot delete the state root" });
171 }
172 const store = yield* Alchemist.State.store(source(args));
173 yield* usingStore(store)(State.deleteState({ path: requested, recursive }));
174 yield* Interaction.success(`Deleted state at ${requested}`);
175 }),
176 ),
177 ).pipe(
178 Command.withAlias("rm"),
179 Command.withDescription("Delete state records without deleting cloud resources"),
180 );
181
182 const stateExplorer = (args: StateArgs) =>
183 Effect.gen(function* () {
184 const cli = yield* Interaction.Interaction;
185 const store = yield* Alchemist.State.store(source(args));
186 const on = provideStore(store);
187 const explorer: StateExplorerSource = {
188 backend: store.id,
189 listStacks: on(State.listState({})).pipe(
190 Effect.map((paths) => paths.map((path) => path.slice(0, -1))),
191 ),
192 listStages: (stack) =>
193 on(State.listState({ path: stack })).pipe(
194 Effect.map((paths) => paths.map((path) => path.slice(stack.length + 1, -1))),
195 ),
196 listResources: (stack, stage) =>
197 on(State.listState({ path: `${stack}/${stage}`, recursive: true })).pipe(
198 Effect.map((paths) =>
199 paths
200 .filter((path) => path !== `${stack}/${stage}/output`)
201 .map((path) => path.slice(`${stack}/${stage}/`.length)),
202 ),
203 ),
204 readFile: (file) =>
205 on(
206 State.readState({
207 path: `${file.stack}/${file.stage}/${file.kind === "output" ? "output" : file.fqn}`,
208 }),
209 ).pipe(Effect.map((entries) => entries[0]?.value)),
210 deleteNodes: (nodes) =>
211 Effect.forEach(
212 nodes.filter(
213 (node, index) =>
214 !nodes.some(
215 (parent, parentIndex) =>
216 parentIndex !== index &&
217 ["stack", "stage", "namespace"].includes(parent.kind) &&
218 node.path.startsWith(`${parent.path}/`),
219 ),
220 ),
221 (node) =>
222 node.kind === "output"
223 ? Effect.void
224 : on(State.deleteState({ path: node.path, recursive: true })).pipe(Effect.asVoid),
225 { concurrency: 32, discard: true },
226 ),
227 };
228 // Captured here so the explorer's forked fibers run with the command's
229 // ambient services (tracing, terminal) rather than the default runtime.
230 const services = yield* Effect.context<never>();
231 yield* cli
232 .session(cli.prompt.screen(stateExplorerScreen(explorer, services)), { alternate: true })
233 .pipe(Effect.catchTag("TerminalCancelled", () => Effect.void));
234 });
235
236 const nukeCommand = Command.make(
237 "nuke",
238 { main: config, envFile, profile, backend, name: storeName, yes },
239 instrumentCommand("state.unsafe.nuke")(
240 Effect.fn(function* ({ yes, ...args }) {
241 const store = yield* Alchemist.State.store(source(args));
242 const stacks = [...(yield* store.listStacks())].sort();
243 if (stacks.length === 0) {
244 yield* Interaction.info("Nothing to clear.");
245 return;
246 }
247 yield* Console.log(stacks.map((stack) => `• ${stack}`).join("\n"));
248 yield* confirmOrDecline({
249 yes,
250 message: `Permanently delete ALL ${stacks.length} stacks from the state store? This cannot be undone. Cloud resources will remain.`,
251 });
252 yield* Effect.forEach(
253 stacks,
254 (stack) =>
255 store
256 .deleteStack({ stack })
257 .pipe(Effect.andThen(Interaction.success(`Cleared ${stack}`))),
258 { concurrency: 32, discard: true },
259 );
260 }),
261 ),
262 ).pipe(
263 Command.withDescription("Delete all stacks, stages, and outputs from the state store"),
264 Command.unlisted,
265 );
266
267 const bootstrapCommand = Command.make(
268 "bootstrap",
269 {
270 main: config,
271 envFile,
272 profile,
273 backend: Flag.String("backend").pipe(
274 Flag.withDescription(
275 "Provider state store to act on (e.g. aws, cloudflare); defaults to the one the config sets",
276 ),
277 Flag.optional,
278 Flag.map(Option.getOrUndefined),
279 ),
280 name: storeName,
281 force: Flag.Boolean("force").pipe(
282 Flag.withDescription(
283 "Redeploy an existing state store instead of adopting it (with --backend)",
284 ),
285 Flag.withDefault(false),
286 ),
287 },
288 instrumentCommand("state.bootstrap")(
289 Effect.fn(function* ({ force, main, backend, ...args }) {
290 if (backend === undefined) {
291 if (force || args.name !== undefined) {
292 return yield* new UserInputError({ message: "--force and --name need --backend." });
293 }
294 const { version } = yield* Alchemist.State.bootstrapConfigured({
295 type: "configured",
296 entrypoint: main,
297 profile: args.profile,
298 envFile: Option.getOrUndefined(args.envFile),
299 });
300 yield* Interaction.success(`State store configured in '${main}' is ready (v${version})`);
301 return;
302 }
303 const result = yield* Alchemist.State.bootstrap({
304 ...lifecycleSource({ ...args, backend }),
305 force,
306 });
307 yield* Interaction.success(
308 `State store '${result.store}' ${result.status} (${Object.values(result.location).join(", ")})`,
309 );
310 }),
311 ),
312 ).pipe(Command.withDescription("Provision (or adopt) a state store"));
313
314 const teardownCommand = Command.make(
315 "teardown",
316 { envFile, profile, backend: lifecycleBackend, name: storeName, yes },
317 instrumentCommand("state.teardown")(
318 Effect.fn(function* ({ yes: approved, ...args }) {
319 yield* confirmOrDecline({
320 yes: approved,
321 message: `Tear down the ${args.backend} state store and its backing resources?`,
322 confirmLabel: "Destroy",
323 cancelLabel: "Cancel",
324 });
325 const result = yield* Alchemist.State.teardown(lifecycleSource(args));
326 yield* Interaction.success(
327 result.deleted.length === 0 ? "Nothing to delete" : `Deleted ${result.deleted.join(", ")}`,
328 );
329 }),
330 ),
331 ).pipe(Command.withDescription("Delete a state store and its backing resources"), Command.unlisted);
332
333 const migrateCommand = Command.make(
334 "migrate",
335 {
336 main: config,
337 envFile,
338 profile,
339 backend,
340 name: storeName,
341 stack: Flag.String("stack").pipe(
342 Flag.withDescription("Only migrate this stack's stages"),
343 Flag.optional,
344 Flag.map(Option.getOrUndefined),
345 ),
346 stage: Flag.String("stage").pipe(
347 Flag.withDescription("Only migrate stages of this name"),
348 Flag.optional,
349 Flag.map(Option.getOrUndefined),
350 ),
351 rollback: Flag.Boolean("rollback").pipe(
352 Flag.withDescription("Move stages back to the state store this one replaces"),
353 Flag.withDefault(false),
354 ),
355 },
356 instrumentCommand("state.migrate")(
357 Effect.fn(function* ({ stack, stage, rollback, ...args }) {
358 const result = yield* Alchemist.State.migrate(source(args), { stack, stage, rollback });
359 if (result.stages.length === 0) {
360 yield* Interaction.info("No stages to migrate.");
361 return;
362 }
363 for (const entry of result.stages) {
364 const detail =
365 entry.reason ?? (entry.records === undefined ? "" : `${entry.records} records`);
366 yield* Console.log(
367 `${entry.stack}/${entry.stage}: ${entry.status}${detail === "" ? "" : ` (${detail})`}`,
368 );
369 }
370 const unfinished = result.stages.filter(
371 (entry) => entry.status === "blocked" || entry.status === "failed",
372 );
373 if (unfinished.length > 0) {
374 return yield* new UserInputError({
375 message: `${unfinished.length} stage(s) did not move. Run the command again once the deploys holding them finish, or fix the failures above.`,
376 });
377 }
378 yield* Interaction.success(
379 rollback ? "Rolled back the state store" : "Migrated the state store",
380 );
381 }),
382 ),
383 ).pipe(
384 Command.withDescription(
385 "Move stages into the configured state store from the one it replaces (or --backend)",
386 ),
387 );
388
389 const logsCommand = Command.make(
390 "logs",
391 {
392 envFile,
393 profile,
394 backend: lifecycleBackend,
395 name: storeName,
396 tail: Flag.Boolean("tail").pipe(
397 Flag.withAlias("t"),
398 Flag.withDescription("Stream logs as they happen instead of fetching past entries"),
399 Flag.withDefault(false),
400 ),
401 limit: Flag.Int("limit").pipe(
402 Flag.withDescription("Number of log entries to fetch (ignored with --tail)"),
403 Flag.withDefault(100),
404 ),
405 since: Flag.String("since").pipe(
406 Flag.withDescription("Fetch logs since this time (e.g. '1h', '30m', '2024-01-01T00:00:00Z')"),
407 Flag.optional,
408 Flag.map(Option.getOrUndefined),
409 ),
410 },
411 instrumentCommand("state.logs")(
412 Effect.fn(function* ({ tail, limit, since, ...args }) {
413 const target = lifecycleSource(args);
414 const format = (entry: StateStoreLogEntry) =>
415 `${formatLocalTimestamp(entry.timestamp)} ${entry.message}`;
416 if (tail) {
417 yield* Interaction.info(`Tailing the ${args.backend} state store...`);
418 yield* Alchemist.State.tailLogs(target).pipe(
419 Stream.runForEach((entry) => Console.log(format(entry))),
420 );
421 return;
422 }
423 const entries = yield* Alchemist.State.logs({
424 ...target,
425 limit,
426 since: since ? yield* parseSince(since) : undefined,
427 });
428 if (entries.length === 0) {
429 yield* Console.log(`(no log entries for the ${args.backend} state store)`);
430 return;
431 }
432 for (const entry of entries) yield* Console.log(format(entry));
433 }),
434 ),
435 ).pipe(Command.withDescription("Fetch or stream a state store's own logs"));
436
437 const unsafeCommand = Command.make("unsafe", {}).pipe(
438 Command.withDescription("Destructive state operations"),
439 Command.withSubcommands([nukeCommand]),
440 Command.unlisted,
441 );
442
443 export const stateCommand = Command.make(
444 "state",
445 { main: config, envFile, profile, backend, name: storeName },
446 instrumentCommand("state")(
447 Effect.fn(function* (args) {
448 if (!(yield* Interaction.Interaction).terminal.input) {
449 return yield* failWithHelp(["alchemy", "state"]);
450 }
451 yield* stateExplorer(args);
452 }),
453 ),
454 ).pipe(
455 Command.withDescription("Inspect and manage deployment state"),
456 Command.withSubcommands([
457 listCommand,
458 readCommand,
459 deleteCommand,
460 bootstrapCommand,
461 teardownCommand,
462 migrateCommand,
463 logsCommand,
464 unsafeCommand,
465 ]),
466 );