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

main
ts 364 lines 12.7 KB
Raw
1 import * as lexm from "@distilled.cloud/aws/lex-models-v2";
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, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import { AWSEnvironment } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 readLexTags,
15 toLexName,
16 retryWhileConflict,
17 syncLexTags,
18 waitForAliasSettled,
19 } from "./internal.ts";
20
21 /**
22 * Lambda code hooks per locale (`localeId` → function ARN). Attached to the
23 * alias's `botAliasLocaleSettings` as
24 * `codeHookSpecification.lambdaCodeHook` with interface version `1.0`.
25 */
26 export interface BotAliasCodeHooks extends Record<string, string> {}
27
28 /**
29 * The binding contract of a bot alias: event sources contribute Lambda code
30 * hooks (`localeId` → function ARN) that the provider merges with
31 * `props.codeHooks` and syncs onto the alias's `botAliasLocaleSettings`.
32 */
33 export interface BotAliasBinding {
34 /** Code hook entries injected by `LexV2.onCodeHook`. */
35 codeHooks?: BotAliasCodeHooks;
36 }
37
38 /**
39 * Two different Lambda functions were registered as the code hook of the
40 * same alias locale — Lex supports exactly one dialog/fulfillment function
41 * per alias locale.
42 */
43 export class ConflictingCodeHook extends Data.TaggedError("ConflictingCodeHook")<{
44 readonly localeId: string;
45 readonly functionArns: readonly string[];
46 }> {}
47
48 export interface BotAliasProps {
49 /**
50 * ID of the bot the alias belongs to. Changing it replaces the alias.
51 */
52 botId: string;
53 /**
54 * Name of the alias. Mutable — renames update the alias in place (identity
55 * is the generated alias ID).
56 * @default ${app}-${id}-${stage}-${suffix}
57 */
58 botAliasName?: string;
59 /**
60 * The numbered bot version the alias points at. Leave undefined to create
61 * the alias unassociated and point it at a version later. Pass the
62 * `botVersion` attribute of a `BotVersion` so the alias depends on it.
63 */
64 botVersion?: string;
65 /**
66 * Description of the alias.
67 */
68 description?: string;
69 /**
70 * Lambda code hooks per locale (`localeId` → function ARN). Merged with
71 * code hook entries injected through the binding contract by
72 * `LexV2.onCodeHook` — prefer the event source over declaring ARNs here,
73 * since it also creates the invoke Permission and registers the runtime
74 * handler.
75 */
76 codeHooks?: BotAliasCodeHooks;
77 /**
78 * Tags to associate with the alias.
79 */
80 tags?: Record<string, string>;
81 }
82
83 export interface BotAlias extends Resource<
84 "AWS.LexV2.BotAlias",
85 BotAliasProps,
86 {
87 /** Unique identifier assigned to the alias. */
88 botAliasId: string;
89 /** Name of the alias. */
90 botAliasName: string;
91 /** ARN of the alias (`arn:aws:lex:...:bot-alias/{botId}/{botAliasId}`). */
92 botAliasArn: string;
93 /** ID of the bot the alias belongs to. */
94 botId: string;
95 /** The bot version the alias points at, if associated. */
96 botVersion: string | undefined;
97 /** Current status of the alias (e.g. `Available`). */
98 botAliasStatus: string;
99 /** Tags currently associated with the alias. */
100 tags: Record<string, string>;
101 },
102 BotAliasBinding,
103 Providers
104 > {}
105
106 /**
107 * An alias of an Amazon Lex V2 bot — a stable pointer to a numbered bot
108 * version that runtime conversations (e.g. `RecognizeText`) target.
109 *
110 * ### Creating an Alias
111 * **Example:** Alias on a Version
112 * ```typescript
113 * import * as AWS from "@alchemy.run/aws";
114 *
115 * const alias = yield* AWS.LexV2.BotAlias("Live", {
116 * botId: version.botId,
117 * botVersion: version.botVersion,
118 * });
119 * ```
120 *
121 * **Example:** Unassociated Alias
122 * ```typescript
123 * // point it at a version later without changing consumers
124 * const alias = yield* AWS.LexV2.BotAlias("Staging", {
125 * botId: bot.botId,
126 * });
127 * ```
128 *
129 * ### Conversing at Runtime
130 * **Example:** RecognizeText from a Lambda
131 * ```typescript
132 * const recognizeText = yield* AWS.LexV2.RecognizeText(alias);
133 * const reply = yield* recognizeText({
134 * localeId: "en_US",
135 * sessionId: "user-123",
136 * text: "hello",
137 * });
138 * ```
139 *
140 * @resource
141 */
142 export const BotAlias = Resource<BotAlias>("AWS.LexV2.BotAlias");
143
144 const createAliasName = (id: string, props: { botAliasName?: string | undefined }) =>
145 Effect.gen(function* () {
146 if (props.botAliasName) return props.botAliasName;
147 return toLexName(yield* createPhysicalName({ id, maxLength: 100 }));
148 });
149
150 const describeAlias = Effect.fn(function* (botId: string, botAliasId: string) {
151 return yield* lexm
152 .describeBotAlias({ botId, botAliasId })
153 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
154 });
155
156 /** Find an alias of the bot by exact name (used when state was lost). */
157 const findAliasByName = Effect.fn(function* (botId: string, botAliasName: string) {
158 const pages = yield* lexm.listBotAliases.pages({ botId }).pipe(
159 Stream.runCollect,
160 Effect.catchTag("ResourceNotFoundException", () =>
161 Effect.succeed([] as lexm.ListBotAliasesResponse[]),
162 ),
163 );
164 const summary = Array.from(pages)
165 .flatMap((page) => page.botAliasSummaries ?? [])
166 .find((alias) => alias.botAliasName === botAliasName);
167 if (summary?.botAliasId === undefined) return undefined;
168 return yield* describeAlias(botId, summary.botAliasId);
169 });
170
171 const aliasArnOf = Effect.fn(function* (botId: string, botAliasId: string) {
172 const { accountId, region } = yield* AWSEnvironment.current;
173 return `arn:aws:lex:${region}:${accountId}:bot-alias/${botId}/${botAliasId}`;
174 });
175
176 /**
177 * The alias's desired code hooks: `props.codeHooks` merged with the entries
178 * contributed through the binding contract (`LexV2.onCodeHook`). Fails when
179 * two different function ARNs target the same locale. Returns `undefined`
180 * when no code hooks are desired (omitting `botAliasLocaleSettings` clears
181 * them on both create and update).
182 */
183 const resolveCodeHooks = Effect.fn(function* (
184 news: BotAliasProps,
185 bindings: ReadonlyArray<BotAliasBinding | { data?: BotAliasBinding }>,
186 ) {
187 const merged: Record<string, string> = {};
188 const contributions = [
189 news.codeHooks,
190 ...bindings.map(
191 (binding) =>
192 (binding as { data?: BotAliasBinding }).data?.codeHooks ??
193 (binding as BotAliasBinding).codeHooks,
194 ),
195 ];
196 for (const hooks of contributions) {
197 if (hooks === undefined) continue;
198 for (const [localeId, arn] of Object.entries(hooks)) {
199 const existing = merged[localeId];
200 if (existing !== undefined && existing !== arn) {
201 return yield* new ConflictingCodeHook({
202 localeId,
203 functionArns: [existing, arn],
204 });
205 }
206 merged[localeId] = arn;
207 }
208 }
209 return Object.keys(merged).length > 0 ? merged : undefined;
210 });
211
212 /** Build the wire `botAliasLocaleSettings` map from desired code hooks. */
213 const toLocaleSettings = (
214 codeHooks: Record<string, string> | undefined,
215 ): { [key: string]: lexm.BotAliasLocaleSettings } | undefined =>
216 codeHooks === undefined
217 ? undefined
218 : Object.fromEntries(
219 Object.entries(codeHooks).map(([localeId, lambdaARN]) => [
220 localeId,
221 {
222 enabled: true,
223 codeHookSpecification: {
224 lambdaCodeHook: { lambdaARN, codeHookInterfaceVersion: "1.0" },
225 },
226 },
227 ]),
228 );
229
230 /**
231 * Project the aspects of `botAliasLocaleSettings` this resource manages
232 * (enabled + lambda ARN per locale) into a canonical string for drift
233 * comparison.
234 */
235 const localeSettingsProjection = (
236 settings: { [key: string]: lexm.BotAliasLocaleSettings | undefined } | undefined,
237 ): string =>
238 JSON.stringify(
239 Object.entries(settings ?? {})
240 .filter(([, value]) => value !== undefined)
241 .map(([localeId, value]) => [
242 localeId,
243 value!.enabled,
244 value!.codeHookSpecification?.lambdaCodeHook.lambdaARN,
245 ])
246 .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
247 );
248
249 const attributesOf = Effect.fn(function* (alias: lexm.DescribeBotAliasResponse) {
250 const botAliasArn = yield* aliasArnOf(alias.botId!, alias.botAliasId!);
251 return {
252 botAliasId: alias.botAliasId!,
253 botAliasName: alias.botAliasName!,
254 botAliasArn,
255 botId: alias.botId!,
256 botVersion: alias.botVersion,
257 botAliasStatus: alias.botAliasStatus!,
258 tags: yield* readLexTags(botAliasArn),
259 } satisfies BotAlias["Attributes"];
260 });
261
262 export const BotAliasProvider = () =>
263 Provider.effect(
264 BotAlias,
265 Effect.gen(function* () {
266 return {
267 stables: ["botAliasId", "botAliasArn", "botId"],
268
269 // Sub-resource keyed entirely by its bot — nuke reaches it through
270 // the parent bot's deletion.
271 list: () => Effect.succeed([]),
272
273 read: Effect.fn(function* ({ id, olds, output }) {
274 const botId = output?.botId ?? olds?.botId;
275 if (botId === undefined) return undefined;
276 const observed =
277 output?.botAliasId !== undefined
278 ? yield* describeAlias(botId, output.botAliasId)
279 : yield* findAliasByName(botId, yield* createAliasName(id, olds ?? {}));
280 if (observed === undefined) return undefined;
281 const attrs = yield* attributesOf(observed);
282 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
283 }),
284
285 diff: Effect.fn(function* ({ news, olds }) {
286 if (!isResolved(news)) return undefined;
287 if (olds?.botId !== news.botId) {
288 return { action: "replace" } as const;
289 }
290 }),
291
292 reconcile: Effect.fn(function* ({ id, news, output, session, bindings }) {
293 const botAliasName = yield* createAliasName(id, news);
294 const internalTags = yield* createInternalTags(id);
295 const desiredTags = { ...internalTags, ...news.tags };
296 const desiredCodeHooks = yield* resolveCodeHooks(news, bindings);
297 const desiredLocaleSettings = toLocaleSettings(desiredCodeHooks);
298
299 // 1. OBSERVE — output.botAliasId is only a cache; fall back to name.
300 let observed =
301 output?.botAliasId !== undefined
302 ? yield* describeAlias(news.botId, output.botAliasId)
303 : undefined;
304 if (observed === undefined) {
305 observed = yield* findAliasByName(news.botId, botAliasName);
306 }
307
308 // 2. ENSURE — create when missing.
309 if (observed === undefined) {
310 const created = yield* retryWhileConflict(
311 lexm.createBotAlias({
312 botId: news.botId,
313 botAliasName,
314 botVersion: news.botVersion,
315 botAliasLocaleSettings: desiredLocaleSettings,
316 description: news.description,
317 tags: desiredTags,
318 }),
319 );
320 observed = yield* waitForAliasSettled(news.botId, created.botAliasId!);
321 } else if (
322 // 3. SYNC — apply the delta when a declared prop drifted.
323 observed.botAliasName !== botAliasName ||
324 (observed.botVersion ?? undefined) !== (news.botVersion ?? undefined) ||
325 (observed.description ?? undefined) !== (news.description ?? undefined) ||
326 localeSettingsProjection(observed.botAliasLocaleSettings) !==
327 localeSettingsProjection(desiredLocaleSettings)
328 ) {
329 yield* retryWhileConflict(
330 lexm.updateBotAlias({
331 botId: news.botId,
332 botAliasId: observed.botAliasId!,
333 botAliasName,
334 botVersion: news.botVersion,
335 botAliasLocaleSettings: desiredLocaleSettings,
336 description: news.description,
337 }),
338 );
339 observed = yield* waitForAliasSettled(news.botId, observed.botAliasId!);
340 }
341
342 // 3b. SYNC TAGS — diff against observed cloud tags.
343 const botAliasArn = yield* aliasArnOf(news.botId, observed.botAliasId!);
344 const observedTags = yield* readLexTags(botAliasArn);
345 yield* syncLexTags(botAliasArn, observedTags, desiredTags);
346
347 yield* session.note(observed.botAliasId!);
348 return yield* attributesOf(observed);
349 }),
350
351 delete: Effect.fn(function* ({ output }) {
352 // Lex reports a missing alias (or already-deleted parent bot) as
353 // PreconditionFailed.
354 yield* retryWhileConflict(
355 lexm.deleteBotAlias({
356 botId: output.botId,
357 botAliasId: output.botAliasId,
358 skipResourceInUseCheck: true,
359 }),
360 ).pipe(Effect.catchTag("PreconditionFailedException", () => Effect.void));
361 }),
362 };
363 }),
364 );