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

main
ts 231 lines 8.88 KB
Raw
1 import * as chatbot from "@distilled.cloud/aws/chatbot";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { inChatbotRegion } from "./internal.ts";
11
12 /**
13 * Raised when a freshly created Chatbot association has not become visible
14 * to `listAssociations` within the bounded eventual-consistency window.
15 */
16 export class AssociationNotVisible extends Data.TaggedError("AssociationNotVisible")<{
17 readonly chatConfiguration: string;
18 readonly resource: string;
19 }> {}
20
21 export interface AssociationProps {
22 /**
23 * ARN of the Slack or Microsoft Teams channel configuration to associate
24 * the resource with (e.g.
25 * `arn:aws:chatbot::123456789012:chat-configuration/slack-channel/alerts`).
26 *
27 * Changing the configuration replaces the association.
28 */
29 chatConfiguration: string;
30 /**
31 * ARN of the resource to associate with the channel configuration — a
32 * Chatbot custom action ARN (e.g.
33 * `arn:aws:chatbot::123456789012:custom-action/describe-alarm`).
34 *
35 * Changing the resource replaces the association.
36 */
37 resource: string;
38 }
39
40 export interface Association extends Resource<
41 "AWS.Chatbot.Association",
42 AssociationProps,
43 {
44 /**
45 * ARN of the channel configuration the resource is associated with.
46 */
47 chatConfigurationArn: string;
48 /**
49 * ARN of the associated resource (the custom action).
50 */
51 resourceArn: string;
52 },
53 never,
54 Providers
55 > {}
56
57 /**
58 * An AWS Chatbot (Amazon Q Developer in chat applications) association that
59 * links a resource — a {@link CustomAction} — to a Slack or Microsoft Teams
60 * channel configuration so the action is available in that channel.
61 *
62 * ### Associating Custom Actions
63 * **Example:** Attach a custom action to a Slack channel configuration
64 * ```typescript
65 * import * as Chatbot from "@alchemy.run/aws/Chatbot";
66 *
67 * const action = yield* Chatbot.CustomAction("DescribeAlarm", {
68 * commandText: "aws cloudwatch describe-alarms --alarm-names $AlarmName",
69 * });
70 *
71 * const config = yield* Chatbot.SlackChannelConfiguration("Alerts", {
72 * slackTeamId: "T012ABCDEFG",
73 * slackChannelId: "C012AB3CD",
74 * iamRoleArn: role.roleArn,
75 * });
76 *
77 * const association = yield* Chatbot.Association("AlarmAction", {
78 * chatConfiguration: config.chatConfigurationArn,
79 * resource: action.customActionArn,
80 * });
81 * ```
82 *
83 * @resource
84 */
85 export const Association = Resource<Association>("AWS.Chatbot.Association");
86
87 export const AssociationProvider = () =>
88 Provider.effect(
89 Association,
90 Effect.gen(function* () {
91 // listAssociations is a filter over a single configuration; an unknown
92 // configuration ARN yields an empty list (verified live), while a
93 // malformed ARN surfaces the typed InvalidRequestException — both are
94 // treated as "no association".
95 const observeAssociation = Effect.fn(function* (chatConfiguration: string, resource: string) {
96 return yield* chatbot.listAssociations.items({ ChatConfiguration: chatConfiguration }).pipe(
97 Stream.runCollect,
98 inChatbotRegion,
99 Effect.map((listings) =>
100 Array.from(listings).find((listing) => listing.Resource === resource),
101 ),
102 Effect.catchTag("InvalidRequestException", () => Effect.undefined),
103 );
104 });
105
106 const toAttributes = (chatConfiguration: string, resource: string) => ({
107 chatConfigurationArn: chatConfiguration,
108 resourceArn: resource,
109 });
110
111 return Association.Provider.of({
112 stables: ["chatConfigurationArn", "resourceArn"],
113 // The configuration/resource ARN pair IS the association's identity —
114 // changing either side replaces it. There is nothing to update.
115 diff: Effect.fn(function* ({ olds, news }) {
116 if (!isResolved(news)) return undefined;
117 if (
118 olds !== undefined &&
119 (olds.chatConfiguration !== news.chatConfiguration || olds.resource !== news.resource)
120 ) {
121 return { action: "replace" } as const;
122 }
123 }),
124 read: Effect.fn(function* ({ olds, output }) {
125 const chatConfiguration = output?.chatConfigurationArn ?? olds?.chatConfiguration;
126 const resource = output?.resourceArn ?? olds?.resource;
127 if (chatConfiguration === undefined || resource === undefined) {
128 return undefined;
129 }
130 const found = yield* observeAssociation(chatConfiguration, resource);
131 if (found === undefined) return undefined;
132 // Associations cannot carry tags; existence of the exact
133 // configuration/resource pair is the ownership signal.
134 return toAttributes(chatConfiguration, resource);
135 }),
136 // Existence-only resource: observe → if missing, associate. There is
137 // no mutable aspect to sync.
138 reconcile: Effect.fn(function* ({ news, session }) {
139 // 1. OBSERVE — cloud state is authoritative.
140 const observed = yield* observeAssociation(news.chatConfiguration, news.resource);
141
142 // 2. ENSURE — associate when missing. The API is an idempotent
143 // upsert, so a concurrent associate converges naturally.
144 if (observed === undefined) {
145 yield* chatbot
146 .associateToConfiguration({
147 Resource: news.resource,
148 ChatConfiguration: news.chatConfiguration,
149 })
150 .pipe(inChatbotRegion);
151
152 // 3. RETURN — bounded wait until the association is visible.
153 yield* observeAssociation(news.chatConfiguration, news.resource).pipe(
154 Effect.flatMap((listing) =>
155 listing !== undefined
156 ? Effect.void
157 : Effect.fail(
158 new AssociationNotVisible({
159 chatConfiguration: news.chatConfiguration,
160 resource: news.resource,
161 }),
162 ),
163 ),
164 Effect.retry({
165 while: (e): boolean => e._tag === "AssociationNotVisible",
166 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(8)]),
167 }),
168 );
169 }
170
171 yield* session.note(news.resource);
172 return toAttributes(news.chatConfiguration, news.resource);
173 }),
174 delete: Effect.fn(function* ({ output }) {
175 // Observe before delete — disassociating a pair that is already
176 // gone (or whose configuration was deleted) is not an error.
177 const observed = yield* observeAssociation(
178 output.chatConfigurationArn,
179 output.resourceArn,
180 );
181 if (observed === undefined) return;
182 yield* chatbot
183 .disassociateFromConfiguration({
184 Resource: output.resourceArn,
185 ChatConfiguration: output.chatConfigurationArn,
186 })
187 .pipe(
188 inChatbotRegion,
189 // Idempotent delete — a concurrently removed association or
190 // configuration is not an error. A configuration deleted out
191 // from under the association surfaces the typed
192 // ResourceNotFoundException ("Channel Arn ... does not
193 // exist!", patched in distilled).
194 Effect.catchTag(
195 ["InvalidRequestException", "ResourceNotFoundException"],
196 () => Effect.void,
197 ),
198 );
199 }),
200 list: () =>
201 Effect.gen(function* () {
202 const configurationArns: string[] = [];
203 const slack = yield* chatbot.describeSlackChannelConfigurations
204 .items({})
205 .pipe(Stream.runCollect, inChatbotRegion);
206 for (const config of slack) {
207 configurationArns.push(config.ChatConfigurationArn);
208 }
209 const teams = yield* chatbot.listMicrosoftTeamsChannelConfigurations
210 .items({})
211 .pipe(Stream.runCollect, inChatbotRegion);
212 for (const config of teams) {
213 configurationArns.push(config.ChatConfigurationArn);
214 }
215 const results: {
216 chatConfigurationArn: string;
217 resourceArn: string;
218 }[] = [];
219 for (const arn of configurationArns) {
220 const associations = yield* chatbot.listAssociations
221 .items({ ChatConfiguration: arn })
222 .pipe(Stream.runCollect, inChatbotRegion);
223 for (const association of associations) {
224 results.push(toAttributes(arn, association.Resource));
225 }
226 }
227 return results;
228 }),
229 });
230 }),
231 );