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

main
ts 346 lines 12.9 KB
Raw
1 import * as chatbot from "@distilled.cloud/aws/chatbot";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { AWSEnvironment } from "../Environment.ts";
11 import type { Providers } from "../Providers.ts";
12 import { fromChatbotTags, inChatbotRegion, toChatbotTags } from "./internal.ts";
13
14 export interface SlackChannelConfigurationProps {
15 /**
16 * Name of the configuration (1-128 characters, `A-Za-z0-9-_`). Forms the
17 * trailing segment of the chat configuration ARN.
18 *
19 * Changing the name replaces the configuration.
20 * @default ${app}-${stage}-${id}
21 */
22 configurationName?: string;
23 /**
24 * ID of the Slack workspace (team) authorized with AWS Chatbot, e.g.
25 * `T012ABCDEFG`. The workspace must first be onboarded via the AWS Chatbot
26 * console OAuth flow — this cannot be automated.
27 *
28 * Changing the workspace replaces the configuration.
29 */
30 slackTeamId: string;
31 /**
32 * ID of the Slack channel, e.g. `C012AB3CD`. In Slack, copy it from the
33 * channel details or the channel URL.
34 */
35 slackChannelId: string;
36 /**
37 * Name of the Slack channel. Informational only.
38 */
39 slackChannelName?: string;
40 /**
41 * ARN of the IAM role that defines the permissions for running commands
42 * from this channel (the channel role). Must trust
43 * `chatbot.amazonaws.com`.
44 */
45 iamRoleArn: string;
46 /**
47 * ARNs of the SNS topics that deliver notifications to this channel.
48 */
49 snsTopicArns?: string[];
50 /**
51 * Logging level for the configuration: `ERROR`, `INFO`, or `NONE`.
52 * @default NONE
53 */
54 loggingLevel?: "ERROR" | "INFO" | "NONE";
55 /**
56 * ARNs of the IAM managed policies applied as channel guardrails. The AWS
57 * managed `AdministratorAccess` policy is applied by default if this is
58 * not set.
59 */
60 guardrailPolicyArns?: string[];
61 /**
62 * Whether channel members must have their AWS user identities authorized
63 * before running commands.
64 * @default false
65 */
66 userAuthorizationRequired?: boolean;
67 /**
68 * Tags to apply to the configuration. Merged with internal Alchemy tags.
69 */
70 tags?: Record<string, string>;
71 }
72
73 export interface SlackChannelConfiguration extends Resource<
74 "AWS.Chatbot.SlackChannelConfiguration",
75 SlackChannelConfigurationProps,
76 {
77 /**
78 * Name of the channel configuration.
79 */
80 configurationName: string;
81 /**
82 * The ARN of the channel configuration.
83 */
84 chatConfigurationArn: string;
85 /**
86 * The Slack workspace (team) ID.
87 */
88 slackTeamId: string;
89 /**
90 * The Slack channel ID.
91 */
92 slackChannelId: string;
93 /**
94 * Name of the Slack workspace.
95 */
96 slackTeamName: string;
97 /**
98 * Current state of the configuration (e.g. `ENABLED`).
99 */
100 state: string | undefined;
101 },
102 never,
103 Providers
104 > {}
105
106 /**
107 * An AWS Chatbot (Amazon Q Developer in chat applications) Slack channel
108 * configuration that delivers SNS notifications to a Slack channel and lets
109 * channel members run read-only or scoped AWS commands.
110 *
111 * The Slack workspace must be onboarded to AWS Chatbot beforehand via the
112 * console OAuth flow (Chatbot console -> Configure new client -> Slack) —
113 * workspace authorization cannot be automated.
114 *
115 * ### Creating Slack Channel Configurations
116 * **Example:** Notify a Slack channel from an SNS topic
117 * ```typescript
118 * import * as Chatbot from "@alchemy.run/aws/Chatbot";
119 * import { Role } from "@alchemy.run/aws/IAM/Role";
120 * import * as SNS from "@alchemy.run/aws/SNS";
121 *
122 * const topic = yield* SNS.Topic("Alerts", {});
123 * const role = yield* Role("ChatbotRole", {
124 * assumeRolePolicyDocument: {
125 * Version: "2012-10-17",
126 * Statement: [
127 * {
128 * Effect: "Allow",
129 * Principal: { Service: "chatbot.amazonaws.com" },
130 * Action: ["sts:AssumeRole"],
131 * },
132 * ],
133 * },
134 * managedPolicyArns: ["arn:aws:iam::aws:policy/ReadOnlyAccess"],
135 * });
136 *
137 * const config = yield* Chatbot.SlackChannelConfiguration("Alerts", {
138 * slackTeamId: "T012ABCDEFG",
139 * slackChannelId: "C012AB3CD",
140 * iamRoleArn: role.roleArn,
141 * snsTopicArns: [topic.topicArn],
142 * loggingLevel: "ERROR",
143 * });
144 * ```
145 *
146 * @resource
147 */
148 export const SlackChannelConfiguration = Resource<SlackChannelConfiguration>(
149 "AWS.Chatbot.SlackChannelConfiguration",
150 );
151
152 export const SlackChannelConfigurationProvider = () =>
153 Provider.effect(
154 SlackChannelConfiguration,
155 Effect.gen(function* () {
156 const createConfigurationName = Effect.fn(function* (
157 id: string,
158 props: Pick<SlackChannelConfigurationProps, "configurationName">,
159 ) {
160 return props.configurationName ?? (yield* createPhysicalName({ id, maxLength: 128 }));
161 });
162
163 const configurationArn = Effect.fn(function* (configurationName: string) {
164 const { accountId } = yield* AWSEnvironment.current;
165 // Chatbot chat-configuration ARNs are global (no region component).
166 return `arn:aws:chatbot::${accountId}:chat-configuration/slack-channel/${configurationName}`;
167 });
168
169 // describeSlackChannelConfigurations is a filter — an unknown ARN
170 // yields an empty list rather than a not-found error.
171 const observeConfiguration = (arn: string) =>
172 chatbot.describeSlackChannelConfigurations({ ChatConfigurationArn: arn }).pipe(
173 inChatbotRegion,
174 Effect.map((r) => r.SlackChannelConfigurations?.[0]),
175 );
176
177 const observedTags = (arn: string) =>
178 chatbot.listTagsForResource({ ResourceARN: arn }).pipe(
179 inChatbotRegion,
180 Effect.map((r) => fromChatbotTags(r.Tags)),
181 Effect.catchTag("ResourceNotFoundException", () =>
182 Effect.succeed({} as Record<string, string>),
183 ),
184 );
185
186 const toAttributes = (
187 configurationName: string,
188 live: chatbot.SlackChannelConfiguration,
189 ) => ({
190 configurationName,
191 chatConfigurationArn: live.ChatConfigurationArn,
192 slackTeamId: live.SlackTeamId,
193 slackChannelId: live.SlackChannelId,
194 slackTeamName: live.SlackTeamName,
195 state: live.State,
196 });
197
198 return SlackChannelConfiguration.Provider.of({
199 stables: ["configurationName", "chatConfigurationArn", "slackTeamId"],
200 list: () =>
201 Effect.gen(function* () {
202 const configurations = yield* chatbot.describeSlackChannelConfigurations
203 .items({})
204 .pipe(Stream.runCollect, inChatbotRegion);
205 return Array.from(configurations).map((config) => {
206 const arn = config.ChatConfigurationArn;
207 return toAttributes(arn.slice(arn.lastIndexOf("/") + 1), config);
208 });
209 }),
210 read: Effect.fn(function* ({ id, olds, output }) {
211 const configurationName =
212 output?.configurationName ?? (yield* createConfigurationName(id, olds ?? {}));
213 const arn = output?.chatConfigurationArn ?? (yield* configurationArn(configurationName));
214 const found = yield* observeConfiguration(arn);
215 if (found === undefined) return undefined;
216 const attrs = toAttributes(configurationName, found);
217 const tags = yield* observedTags(found.ChatConfigurationArn);
218 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
219 }),
220 diff: Effect.fn(function* ({ id, news, olds }) {
221 if (!isResolved(news)) return undefined;
222 const oldName = yield* createConfigurationName(id, olds ?? {});
223 const newName = yield* createConfigurationName(id, news ?? {});
224 if (oldName !== newName || olds?.slackTeamId !== news.slackTeamId) {
225 return { action: "replace" } as const;
226 }
227 // fall through: engine default update logic for mutable fields
228 }),
229 reconcile: Effect.fn(function* ({ id, news, output, session }) {
230 const configurationName =
231 output?.configurationName ?? (yield* createConfigurationName(id, news));
232 const arn = output?.chatConfigurationArn ?? (yield* configurationArn(configurationName));
233 const internalTags = yield* createInternalTags(id);
234 const desiredTags = { ...news.tags, ...internalTags };
235 const desiredTopics = [...(news.snsTopicArns ?? [])].sort();
236 const desiredGuardrails = news.guardrailPolicyArns
237 ? [...news.guardrailPolicyArns].sort()
238 : undefined;
239
240 // 1. OBSERVE — cloud state is authoritative.
241 let live = yield* observeConfiguration(arn);
242
243 // 2. ENSURE — create when missing; a concurrent create surfaces as
244 // the typed ConflictException, which we treat as a race and
245 // re-observe.
246 if (live === undefined) {
247 live = yield* chatbot
248 .createSlackChannelConfiguration({
249 SlackTeamId: news.slackTeamId,
250 SlackChannelId: news.slackChannelId,
251 SlackChannelName: news.slackChannelName,
252 ConfigurationName: configurationName,
253 IamRoleArn: news.iamRoleArn,
254 SnsTopicArns: news.snsTopicArns,
255 LoggingLevel: news.loggingLevel,
256 GuardrailPolicyArns: news.guardrailPolicyArns,
257 UserAuthorizationRequired: news.userAuthorizationRequired,
258 Tags: toChatbotTags(desiredTags),
259 })
260 .pipe(
261 inChatbotRegion,
262 Effect.map((r) => r.ChannelConfiguration),
263 Effect.catchTag("ConflictException", () => observeConfiguration(arn)),
264 );
265 }
266
267 // 3. SYNC — diff the OBSERVED mutable aspects against the desired
268 // state; update only on drift.
269 const inSync =
270 live !== undefined &&
271 live.SlackChannelId === news.slackChannelId &&
272 live.IamRoleArn === news.iamRoleArn &&
273 JSON.stringify([...live.SnsTopicArns].sort()) === JSON.stringify(desiredTopics) &&
274 (live.LoggingLevel ?? "NONE") === (news.loggingLevel ?? "NONE") &&
275 JSON.stringify(
276 live.GuardrailPolicyArns ? [...live.GuardrailPolicyArns].sort() : undefined,
277 ) === JSON.stringify(desiredGuardrails) &&
278 (live.UserAuthorizationRequired ?? false) === (news.userAuthorizationRequired ?? false);
279 if (!inSync) {
280 live = yield* chatbot
281 .updateSlackChannelConfiguration({
282 ChatConfigurationArn: arn,
283 SlackChannelId: news.slackChannelId,
284 SlackChannelName: news.slackChannelName,
285 IamRoleArn: news.iamRoleArn,
286 SnsTopicArns: news.snsTopicArns,
287 LoggingLevel: news.loggingLevel,
288 GuardrailPolicyArns: news.guardrailPolicyArns,
289 UserAuthorizationRequired: news.userAuthorizationRequired,
290 })
291 .pipe(
292 inChatbotRegion,
293 Effect.map((r) => r.ChannelConfiguration),
294 );
295 }
296
297 // 3b. SYNC TAGS — diff against OBSERVED cloud tags so adoption
298 // converges (create-time Tags only apply on first create).
299 const currentTags = yield* observedTags(arn);
300 const { upsert, removed } = diffTags(currentTags, desiredTags);
301 if (upsert.length > 0) {
302 yield* chatbot
303 .tagResource({
304 ResourceARN: arn,
305 Tags: upsert.map(({ Key, Value }) => ({
306 TagKey: Key,
307 TagValue: Value,
308 })),
309 })
310 .pipe(inChatbotRegion);
311 }
312 if (removed.length > 0) {
313 yield* chatbot
314 .untagResource({
315 ResourceARN: arn,
316 TagKeys: removed,
317 })
318 .pipe(inChatbotRegion);
319 }
320
321 yield* session.note(configurationName);
322 return live !== undefined
323 ? toAttributes(configurationName, live)
324 : {
325 configurationName,
326 chatConfigurationArn: arn,
327 slackTeamId: news.slackTeamId,
328 slackChannelId: news.slackChannelId,
329 slackTeamName: "",
330 state: undefined,
331 };
332 }),
333 delete: Effect.fn(function* ({ output }) {
334 yield* chatbot
335 .deleteSlackChannelConfiguration({
336 ChatConfigurationArn: output.chatConfigurationArn,
337 })
338 .pipe(
339 inChatbotRegion,
340 // Idempotent delete — a missing configuration is not an error.
341 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
342 );
343 }),
344 });
345 }),
346 );