@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 306 lines 10.7 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 /**
15 * A criteria block controlling when a custom action button is shown on a
16 * notification.
17 */
18 export interface CustomActionAttachmentCriteria {
19 /**
20 * The operation to perform on the named variable: `HAS_VALUE` or `EQUALS`.
21 */
22 operator: "HAS_VALUE" | "EQUALS" | (string & {});
23 /**
24 * The name of the notification variable to operate on.
25 */
26 variableName: string;
27 /**
28 * The value to compare the variable against when the operator is `EQUALS`.
29 */
30 value?: string;
31 }
32
33 /**
34 * Defines when and how a custom action surfaces as a button on chat
35 * notifications.
36 */
37 export interface CustomActionAttachment {
38 /**
39 * The type of notification the action button appears on, e.g.
40 * `CloudWatch`. Although the AWS API documentation marks this optional,
41 * the live API rejects attachments without it (`Invalid request body`).
42 */
43 notificationType: string;
44 /**
45 * The label of the button that appears on the notification.
46 */
47 buttonText?: string;
48 /**
49 * Conditions (over notification variables) that must be met for the button
50 * to appear.
51 */
52 criteria?: CustomActionAttachmentCriteria[];
53 /**
54 * Variable values bound into the action's command text.
55 */
56 variables?: Record<string, string>;
57 }
58
59 export interface CustomActionProps {
60 /**
61 * Name of the custom action (1-64 characters, `A-Za-z0-9-_`). Forms the
62 * trailing segment of the custom action ARN.
63 *
64 * Changing the name replaces the custom action.
65 * @default ${app}-${stage}-${id}
66 */
67 actionName?: string;
68 /**
69 * The CLI command text executed when the action is invoked, e.g.
70 * `aws lambda list-functions`. Variables from attachments may be
71 * interpolated with `$variable` syntax.
72 */
73 commandText: string;
74 /**
75 * An alias that lets chat users invoke the action as `@aws run <alias>`.
76 */
77 aliasName?: string;
78 /**
79 * Notification attachments that surface the action as a button on
80 * matching notifications.
81 */
82 attachments?: CustomActionAttachment[];
83 /**
84 * Tags to apply to the custom action. Merged with internal Alchemy tags.
85 */
86 tags?: Record<string, string>;
87 }
88
89 export interface CustomAction extends Resource<
90 "AWS.Chatbot.CustomAction",
91 CustomActionProps,
92 {
93 /**
94 * Name of the custom action.
95 */
96 actionName: string;
97 /**
98 * The ARN of the custom action.
99 */
100 customActionArn: string;
101 },
102 never,
103 Providers
104 > {}
105
106 /**
107 * An AWS Chatbot (Amazon Q Developer in chat applications) custom action —
108 * a reusable CLI command that chat users invoke by alias or as a button on
109 * notifications.
110 *
111 * Custom actions exist at the account level and do not require a chat
112 * workspace to be onboarded, though they only become usable once a Slack or
113 * Microsoft Teams channel configuration exists.
114 *
115 * ### Creating Custom Actions
116 * **Example:** List Lambda functions from chat
117 * ```typescript
118 * import * as Chatbot from "@alchemy.run/aws/Chatbot";
119 *
120 * const action = yield* Chatbot.CustomAction("ListFunctions", {
121 * commandText: "aws lambda list-functions",
122 * aliasName: "list-functions",
123 * });
124 * ```
125 *
126 * **Example:** Button on CloudWatch alarm notifications
127 * ```typescript
128 * const action = yield* Chatbot.CustomAction("DescribeAlarm", {
129 * commandText: "aws cloudwatch describe-alarms --alarm-names $AlarmName",
130 * attachments: [
131 * {
132 * notificationType: "CloudWatch",
133 * buttonText: "Describe alarm",
134 * criteria: [
135 * { operator: "HAS_VALUE", variableName: "AlarmName" },
136 * ],
137 * },
138 * ],
139 * });
140 * ```
141 *
142 * @resource
143 */
144 export const CustomAction = Resource<CustomAction>("AWS.Chatbot.CustomAction");
145
146 const toWireAttachment = (attachment: CustomActionAttachment): chatbot.CustomActionAttachment => ({
147 NotificationType: attachment.notificationType,
148 ButtonText: attachment.buttonText,
149 Criteria: attachment.criteria?.map((c) => ({
150 Operator: c.operator,
151 VariableName: c.variableName,
152 Value: c.value,
153 })),
154 Variables: attachment.variables,
155 });
156
157 export const CustomActionProvider = () =>
158 Provider.effect(
159 CustomAction,
160 Effect.gen(function* () {
161 const createActionName = Effect.fn(function* (
162 id: string,
163 props: Pick<CustomActionProps, "actionName">,
164 ) {
165 // Custom action names are limited to 64 characters of [A-Za-z0-9-_].
166 return props.actionName ?? (yield* createPhysicalName({ id, maxLength: 64 }));
167 });
168
169 const actionArn = Effect.fn(function* (actionName: string) {
170 const { accountId } = yield* AWSEnvironment.current;
171 // Chatbot custom action ARNs are global (no region component).
172 return `arn:aws:chatbot::${accountId}:custom-action/${actionName}`;
173 });
174
175 const observeAction = (arn: string) =>
176 chatbot.getCustomAction({ CustomActionArn: arn }).pipe(
177 inChatbotRegion,
178 Effect.map((r) => r.CustomAction),
179 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
180 );
181
182 const observedTags = (arn: string) =>
183 chatbot.listTagsForResource({ ResourceARN: arn }).pipe(
184 inChatbotRegion,
185 Effect.map((r) => fromChatbotTags(r.Tags)),
186 Effect.catchTag("ResourceNotFoundException", () =>
187 Effect.succeed({} as Record<string, string>),
188 ),
189 );
190
191 return CustomAction.Provider.of({
192 stables: ["actionName", "customActionArn"],
193 list: () =>
194 Effect.gen(function* () {
195 const arns = yield* chatbot.listCustomActions
196 .items({})
197 .pipe(Stream.runCollect, inChatbotRegion);
198 return Array.from(arns).map((arn) => ({
199 actionName: arn.slice(arn.lastIndexOf("/") + 1),
200 customActionArn: arn,
201 }));
202 }),
203 read: Effect.fn(function* ({ id, olds, output }) {
204 const actionName = output?.actionName ?? (yield* createActionName(id, olds ?? {}));
205 const arn = output?.customActionArn ?? (yield* actionArn(actionName));
206 const found = yield* observeAction(arn);
207 if (found === undefined) return undefined;
208 const attrs = { actionName, customActionArn: found.CustomActionArn };
209 const tags = yield* observedTags(found.CustomActionArn);
210 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
211 }),
212 diff: Effect.fn(function* ({ id, news, olds }) {
213 if (!isResolved(news)) return undefined;
214 const oldName = yield* createActionName(id, olds ?? {});
215 const newName = yield* createActionName(id, news ?? {});
216 if (oldName !== newName) {
217 return { action: "replace" } as const;
218 }
219 // fall through: engine default update logic for mutable fields
220 }),
221 reconcile: Effect.fn(function* ({ id, news, output, session }) {
222 const actionName = output?.actionName ?? (yield* createActionName(id, news));
223 const arn = output?.customActionArn ?? (yield* actionArn(actionName));
224 const internalTags = yield* createInternalTags(id);
225 const desiredTags = { ...news.tags, ...internalTags };
226 const desiredDefinition = { CommandText: news.commandText };
227 const desiredAttachments = news.attachments?.map(toWireAttachment);
228
229 // 1. OBSERVE — cloud state is authoritative.
230 let live = yield* observeAction(arn);
231
232 // 2. ENSURE — create when missing; a concurrent create surfaces as
233 // the typed ConflictException, which we treat as a race and
234 // re-observe.
235 if (live === undefined) {
236 live = yield* chatbot
237 .createCustomAction({
238 ActionName: actionName,
239 Definition: desiredDefinition,
240 AliasName: news.aliasName,
241 Attachments: desiredAttachments,
242 Tags: toChatbotTags(desiredTags),
243 })
244 .pipe(
245 inChatbotRegion,
246 Effect.map((r) => r.CustomActionArn),
247 Effect.catchTag("ConflictException", () => Effect.succeed(arn)),
248 Effect.flatMap(observeAction),
249 );
250 }
251
252 // 3. SYNC — diff the OBSERVED definition, alias, and attachments
253 // against the desired state; update only on drift.
254 const inSync =
255 live !== undefined &&
256 live.Definition.CommandText === news.commandText &&
257 live.AliasName === news.aliasName &&
258 JSON.stringify(live.Attachments ?? []) === JSON.stringify(desiredAttachments ?? []);
259 if (!inSync) {
260 yield* chatbot
261 .updateCustomAction({
262 CustomActionArn: arn,
263 Definition: desiredDefinition,
264 AliasName: news.aliasName,
265 Attachments: desiredAttachments,
266 })
267 .pipe(inChatbotRegion);
268 }
269
270 // 3b. SYNC TAGS — diff against OBSERVED cloud tags so adoption
271 // converges (create-time Tags only apply on first create).
272 const currentTags = yield* observedTags(arn);
273 const { upsert, removed } = diffTags(currentTags, desiredTags);
274 if (upsert.length > 0) {
275 yield* chatbot
276 .tagResource({
277 ResourceARN: arn,
278 Tags: upsert.map(({ Key, Value }) => ({
279 TagKey: Key,
280 TagValue: Value,
281 })),
282 })
283 .pipe(inChatbotRegion);
284 }
285 if (removed.length > 0) {
286 yield* chatbot
287 .untagResource({
288 ResourceARN: arn,
289 TagKeys: removed,
290 })
291 .pipe(inChatbotRegion);
292 }
293
294 yield* session.note(actionName);
295 return { actionName, customActionArn: arn };
296 }),
297 delete: Effect.fn(function* ({ output }) {
298 yield* chatbot.deleteCustomAction({ CustomActionArn: output.customActionArn }).pipe(
299 inChatbotRegion,
300 // Idempotent delete — a missing action is not an error.
301 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
302 );
303 }),
304 });
305 }),
306 );