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

main
ts 319 lines 10.4 KB
Raw
1 import * as lexm from "@distilled.cloud/aws/lex-models-v2";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, hasAlchemyTags } from "alchemy/Tags";
7 import { toWireSeconds } from "alchemy/Util/Duration";
8 import * as Data from "effect/Data";
9 import type * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Predicate from "effect/Predicate";
12 import * as Stream from "effect/Stream";
13 import { AWSEnvironment } from "../Environment.ts";
14 import type { Providers } from "../Providers.ts";
15 import {
16 readLexTags,
17 toLexName,
18 retryWhileConflict,
19 syncLexTags,
20 waitForBotSettled,
21 } from "./internal.ts";
22
23 export class BotUnexpectedResponse extends Data.TaggedError("BotUnexpectedResponse")<{
24 readonly message: string;
25 readonly cause?: unknown;
26 }> {}
27
28 export interface BotProps {
29 /**
30 * Name of the bot. Mutable — renames update the bot in place (identity is
31 * the generated bot ID).
32 * @default ${app}-${id}-${stage}-${suffix}
33 */
34 botName?: string;
35 /**
36 * ARN of an IAM role that Amazon Lex assumes to call AWS services on the
37 * bot's behalf (e.g. Polly for speech). The role must trust
38 * `lexv2.amazonaws.com`.
39 */
40 roleArn: string;
41 /**
42 * COPPA data-privacy declaration. Set `childDirected: true` when the bot
43 * is directed at children under 13.
44 * @default { childDirected: false }
45 */
46 dataPrivacy?: {
47 /** Whether the bot is directed at children under 13 (COPPA). */
48 childDirected: boolean;
49 };
50 /**
51 * How long Amazon Lex retains a conversation session after the last user
52 * input (60 seconds to 24 hours). Accepts any `Duration.Input` (e.g.
53 * `"10 minutes"`, `Duration.minutes(10)`; a bare number is milliseconds);
54 * the wire unit is whole seconds.
55 * @default 300 seconds
56 */
57 idleSessionTTL?: Duration.Input;
58 /**
59 * Description of the bot.
60 */
61 description?: string;
62 /**
63 * Tags to associate with the bot.
64 */
65 tags?: Record<string, string>;
66 }
67
68 export interface Bot extends Resource<
69 "AWS.LexV2.Bot",
70 BotProps,
71 {
72 /** Unique identifier assigned to the bot. */
73 botId: string;
74 /** Name of the bot. */
75 botName: string;
76 /** ARN of the bot. */
77 botArn: string;
78 /** Current status of the bot (e.g. `Available`). */
79 botStatus: string;
80 /** ARN of the IAM role the bot assumes. */
81 roleArn: string;
82 /** Tags currently associated with the bot. */
83 tags: Record<string, string>;
84 },
85 never,
86 Providers
87 > {}
88
89 /**
90 * An Amazon Lex V2 conversational bot. The bot is the container for locales,
91 * intents, and slot types; conversations run against an alias of a built
92 * version.
93 *
94 * ### Creating a Bot
95 * **Example:** Basic Bot
96 * ```typescript
97 * import * as AWS from "@alchemy.run/aws";
98 *
99 * const role = yield* AWS.IAM.Role("BotRole", {
100 * assumeRolePolicyDocument: {
101 * Version: "2012-10-17",
102 * Statement: [
103 * {
104 * Effect: "Allow",
105 * Principal: { Service: "lexv2.amazonaws.com" },
106 * Action: ["sts:AssumeRole"],
107 * },
108 * ],
109 * },
110 * });
111 *
112 * const bot = yield* AWS.LexV2.Bot("OrderBot", {
113 * roleArn: role.roleArn,
114 * });
115 * ```
116 *
117 * **Example:** Bot with Session and Privacy Settings
118 * ```typescript
119 * const bot = yield* AWS.LexV2.Bot("KidsBot", {
120 * roleArn: role.roleArn,
121 * dataPrivacy: { childDirected: true },
122 * idleSessionTTL: "10 minutes",
123 * description: "A bot for children",
124 * });
125 * ```
126 *
127 * ### Building the Conversation Graph
128 * **Example:** Locale, Intent, and Alias
129 * ```typescript
130 * const locale = yield* AWS.LexV2.BotLocale("En", {
131 * botId: bot.botId,
132 * localeId: "en_US",
133 * });
134 * const intent = yield* AWS.LexV2.Intent("Greet", {
135 * botId: locale.botId,
136 * localeId: locale.localeId,
137 * sampleUtterances: ["hello", "hi"],
138 * });
139 * const version = yield* AWS.LexV2.BotVersion("V1", {
140 * botId: intent.botId,
141 * localeIds: [intent.localeId],
142 * });
143 * const alias = yield* AWS.LexV2.BotAlias("Live", {
144 * botId: version.botId,
145 * botVersion: version.botVersion,
146 * });
147 * ```
148 *
149 * @resource
150 */
151 export const Bot = Resource<Bot>("AWS.LexV2.Bot");
152
153 const createBotName = (id: string, props: { botName?: string | undefined }) =>
154 Effect.gen(function* () {
155 if (props.botName) return props.botName;
156 return toLexName(yield* createPhysicalName({ id, maxLength: 100 }));
157 });
158
159 const describeBot = Effect.fn(function* (botId: string) {
160 return yield* lexm
161 .describeBot({ botId })
162 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
163 });
164
165 /** Find a bot by exact name. The physical name embeds app/stage/id. */
166 const findBotByName = Effect.fn(function* (botName: string) {
167 const pages = yield* lexm.listBots
168 .pages({
169 filters: [{ name: "BotName", values: [botName], operator: "EQ" }],
170 })
171 .pipe(Stream.runCollect);
172 const summary = Array.from(pages)
173 .flatMap((page) => page.botSummaries ?? [])
174 .find((bot) => bot.botName === botName);
175 if (summary?.botId === undefined) return undefined;
176 return yield* describeBot(summary.botId);
177 });
178
179 const botArnOf = Effect.fn(function* (botId: string) {
180 const { accountId, region } = yield* AWSEnvironment.current;
181 return `arn:aws:lex:${region}:${accountId}:bot/${botId}`;
182 });
183
184 const attributesOf = Effect.fn(function* (bot: lexm.DescribeBotResponse) {
185 const botArn = yield* botArnOf(bot.botId!);
186 return {
187 botId: bot.botId!,
188 botName: bot.botName!,
189 botArn,
190 botStatus: bot.botStatus!,
191 roleArn: bot.roleArn!,
192 tags: yield* readLexTags(botArn),
193 } satisfies Bot["Attributes"];
194 });
195
196 export const BotProvider = () =>
197 Provider.effect(
198 Bot,
199 Effect.gen(function* () {
200 return {
201 stables: ["botId", "botArn"],
202
203 list: () =>
204 Effect.gen(function* () {
205 const pages = yield* lexm.listBots.pages({}).pipe(Stream.runCollect);
206 const ids = Array.from(pages)
207 .flatMap((page) => page.botSummaries ?? [])
208 .map((bot) => bot.botId)
209 .filter((id): id is string => id !== undefined);
210 const hydrated = yield* Effect.forEach(
211 ids,
212 (id) =>
213 Effect.flatMap(describeBot(id), (bot) =>
214 bot === undefined ? Effect.undefined : attributesOf(bot),
215 ),
216 { concurrency: 5 },
217 );
218 return hydrated.filter(Predicate.isNotUndefined);
219 }),
220
221 read: Effect.fn(function* ({ id, olds, output }) {
222 const observed =
223 output?.botId !== undefined
224 ? yield* describeBot(output.botId)
225 : yield* findBotByName(yield* createBotName(id, olds ?? {}));
226 if (observed === undefined) return undefined;
227 const attrs = yield* attributesOf(observed);
228 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
229 }),
230
231 // All bot props are mutable via UpdateBot — no replacement triggers.
232
233 reconcile: Effect.fn(function* ({ id, news, output, session }) {
234 const botName = yield* createBotName(id, news);
235 const internalTags = yield* createInternalTags(id);
236 const desiredTags = { ...internalTags, ...news.tags };
237 const desiredDataPrivacy = news.dataPrivacy ?? {
238 childDirected: false,
239 };
240 // Wire unit is whole seconds (idleSessionTTLInSeconds).
241 const desiredTtl = toWireSeconds(news.idleSessionTTL) ?? 300;
242
243 // 1. OBSERVE — output.botId is only a cache; fall back to name.
244 let observed = output?.botId !== undefined ? yield* describeBot(output.botId) : undefined;
245 if (observed === undefined) {
246 observed = yield* findBotByName(botName);
247 }
248
249 // 2. ENSURE — create when missing; a Conflict is a concurrent
250 // create of the same name.
251 if (observed === undefined) {
252 const created = yield* lexm
253 .createBot({
254 botName,
255 roleArn: news.roleArn,
256 dataPrivacy: desiredDataPrivacy,
257 idleSessionTTLInSeconds: desiredTtl,
258 description: news.description,
259 botTags: desiredTags,
260 })
261 .pipe(
262 Effect.map((r) => r.botId),
263 Effect.catchTag("ConflictException", () =>
264 Effect.map(findBotByName(botName), (bot) => bot?.botId),
265 ),
266 );
267 if (created === undefined) {
268 return yield* new BotUnexpectedResponse({
269 message: `failed to create Lex bot ${botName}`,
270 });
271 }
272 observed = yield* waitForBotSettled(created);
273 }
274
275 const botId = observed.botId!;
276
277 // 3. SYNC — apply the delta when any declared prop drifted.
278 if (
279 observed.botName !== botName ||
280 observed.roleArn !== news.roleArn ||
281 (observed.description ?? undefined) !== (news.description ?? undefined) ||
282 observed.idleSessionTTLInSeconds !== desiredTtl ||
283 (observed.dataPrivacy?.childDirected ?? false) !== desiredDataPrivacy.childDirected
284 ) {
285 yield* retryWhileConflict(
286 lexm.updateBot({
287 botId,
288 botName,
289 roleArn: news.roleArn,
290 dataPrivacy: desiredDataPrivacy,
291 idleSessionTTLInSeconds: desiredTtl,
292 description: news.description,
293 }),
294 );
295 observed = yield* waitForBotSettled(botId);
296 }
297
298 // 3b. SYNC TAGS — diff against observed cloud tags.
299 const botArn = yield* botArnOf(botId);
300 const observedTags = yield* readLexTags(botArn);
301 yield* syncLexTags(botArn, observedTags, desiredTags);
302
303 yield* session.note(botId);
304 return yield* attributesOf(observed);
305 }),
306
307 delete: Effect.fn(function* ({ output }) {
308 // DeleteBot is asynchronous (status `Deleting`); Lex reports a
309 // missing bot as PreconditionFailed.
310 yield* retryWhileConflict(
311 lexm.deleteBot({
312 botId: output.botId,
313 skipResourceInUseCheck: true,
314 }),
315 ).pipe(Effect.catchTag("PreconditionFailedException", () => Effect.void));
316 }),
317 };
318 }),
319 );