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

main
ts 137 lines 4.61 KB
Raw
1 import * as detective from "@distilled.cloud/aws/detective";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
6 import * as Effect from "effect/Effect";
7 import type { Providers } from "../Providers.ts";
8
9 export interface GraphProps {
10 /**
11 * Tags applied to the behavior graph. Alchemy ownership tags are merged in
12 * automatically so the graph can be recognized on subsequent runs.
13 */
14 tags?: Record<string, string>;
15 }
16
17 /** @resource */
18 export interface Graph extends Resource<
19 "AWS.Detective.Graph",
20 GraphProps,
21 {
22 /** ARN of the Detective behavior graph. */
23 graphArn: string;
24 /** ISO timestamp of when the graph was created. */
25 createdTime: string | undefined;
26 },
27 never,
28 Providers
29 > {}
30
31 /**
32 * A Detective behavior graph — the account/region singleton that enables Amazon
33 * Detective. An account can have at most one behavior graph per region, so this
34 * resource is a capture-and-restore singleton: adopting a pre-existing graph
35 * that Alchemy did not create requires `--adopt`.
36 *
37 * ### Enabling Detective
38 * **Example:** Enable a behavior graph
39 * ```typescript
40 * const graph = yield* Detective.Graph("Graph", {});
41 * ```
42 *
43 * **Example:** Enable with tags
44 * ```typescript
45 * const graph = yield* Detective.Graph("Graph", {
46 * tags: { team: "security" },
47 * });
48 * ```
49 */
50 const GraphResource = Resource<Graph>("AWS.Detective.Graph");
51
52 export { GraphResource as Graph };
53
54 const buildAttrs = (g: detective.Graph) => ({
55 graphArn: g.Arn!,
56 createdTime: g.CreatedTime?.toISOString(),
57 });
58
59 export const GraphProvider = () =>
60 Provider.effect(
61 GraphResource,
62 Effect.gen(function* () {
63 // Detective allows at most one behavior graph per account/region. Return
64 // the first (only) graph, if any.
65 const firstGraph = detective.listGraphs({}).pipe(Effect.map((r) => r.GraphList?.[0]));
66
67 const readTags = (arn: string) =>
68 detective.listTagsForResource({ ResourceArn: arn }).pipe(
69 Effect.map((r) => (r.Tags ?? {}) as Record<string, string>),
70 Effect.orElseSucceed(() => ({}) as Record<string, string>),
71 );
72
73 return {
74 read: Effect.fn(function* ({ id, output }) {
75 const graph = yield* firstGraph;
76 if (!graph?.Arn) return undefined;
77 // If we have a cached ARN and it no longer matches the single graph,
78 // the graph we knew about is gone.
79 if (output?.graphArn && output.graphArn !== graph.Arn) {
80 return undefined;
81 }
82 const attrs = buildAttrs(graph);
83 const tags = yield* readTags(graph.Arn);
84 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
85 }),
86
87 // Account/region singleton — enumerate the single behavior graph.
88 list: () =>
89 detective.listGraphs({}).pipe(Effect.map((r) => (r.GraphList ?? []).map(buildAttrs))),
90
91 reconcile: Effect.fn(function* ({ id, news = {}, session }) {
92 const internalTags = yield* createInternalTags(id);
93 const desiredTags = { ...news.tags, ...internalTags };
94
95 // 1. OBSERVE — cloud state is authoritative.
96 let graph = yield* firstGraph;
97
98 // 2. ENSURE — create the graph (with tags inline) if none exists.
99 if (!graph?.Arn) {
100 const created = yield* detective.createGraph({
101 Tags: desiredTags,
102 });
103 graph = { Arn: created.GraphArn! };
104 }
105
106 const arn = graph.Arn!;
107
108 // 3. SYNC tags — diff against OBSERVED cloud tags.
109 const currentTags = yield* readTags(arn);
110 const { upsert, removed } = diffTags(currentTags, desiredTags);
111 if (upsert.length > 0) {
112 yield* detective.tagResource({
113 ResourceArn: arn,
114 Tags: Object.fromEntries(upsert.map((t) => [t.Key, t.Value])),
115 });
116 }
117 if (removed.length > 0) {
118 yield* detective.untagResource({
119 ResourceArn: arn,
120 TagKeys: removed,
121 });
122 }
123
124 // 4. RETURN fresh attributes.
125 const final = yield* firstGraph;
126 yield* session.note(arn);
127 return final?.Arn ? buildAttrs(final) : { graphArn: arn, createdTime: undefined };
128 }),
129
130 delete: Effect.fn(function* ({ output }) {
131 yield* detective
132 .deleteGraph({ GraphArn: output.graphArn })
133 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
134 }),
135 };
136 }),
137 );