@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, 04:45 UTC

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