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

main
ts 279 lines 10.1 KB
Raw
1 import * as lexm from "@distilled.cloud/aws/lex-models-v2";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { retryWhileConflict, toLexName } from "./internal.ts";
11
12 export class IntentUnexpectedResponse extends Data.TaggedError("IntentUnexpectedResponse")<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export interface IntentProps {
18 /**
19 * ID of the bot the intent belongs to. Changing it replaces the intent.
20 */
21 botId: string;
22 /**
23 * Locale the intent lives under, e.g. `en_US`. Changing it replaces the
24 * intent. Pass the `localeId` attribute of a `BotLocale` so the intent
25 * depends on the locale.
26 */
27 localeId: string;
28 /**
29 * Name of the intent. Mutable — renames update the intent in place
30 * (identity is the generated intent ID).
31 * @default ${app}-${id}-${stage}-${suffix}
32 */
33 intentName?: string;
34 /**
35 * Description of the intent.
36 */
37 description?: string;
38 /**
39 * Sample utterances that invoke the intent, e.g. `"I want to order a
40 * pizza"`. Utterances may reference slots with `{slotName}`.
41 */
42 sampleUtterances?: string[];
43 /**
44 * Signature of a built-in intent to base this intent on, e.g.
45 * `AMAZON.HelpIntent`.
46 */
47 parentIntentSignature?: string;
48 /**
49 * Invoke the alias's Lambda code hook on every dialog turn of this intent
50 * (slot elicitation, validation). Attach the function itself with
51 * `LexV2.onCodeHook`.
52 * @default false
53 */
54 dialogCodeHook?: boolean;
55 /**
56 * Invoke the alias's Lambda code hook to fulfill the intent once all
57 * required slots are filled. Attach the function itself with
58 * `LexV2.onCodeHook`.
59 * @default false
60 */
61 fulfillmentCodeHook?: boolean;
62 }
63
64 export interface Intent extends Resource<
65 "AWS.LexV2.Intent",
66 IntentProps,
67 {
68 /** Unique identifier assigned to the intent. */
69 intentId: string;
70 /** Name of the intent. */
71 intentName: string;
72 /** ID of the bot the intent belongs to. */
73 botId: string;
74 /** Bot version the intent lives on — always `DRAFT`. */
75 botVersion: string;
76 /** Locale the intent lives under. */
77 localeId: string;
78 },
79 never,
80 Providers
81 > {}
82
83 /**
84 * An intent on the DRAFT locale of an Amazon Lex V2 bot — an action the user
85 * wants to perform, recognized from sample utterances.
86 *
87 * ### Creating Intents
88 * **Example:** Intent with Sample Utterances
89 * ```typescript
90 * import * as AWS from "@alchemy.run/aws";
91 *
92 * const greet = yield* AWS.LexV2.Intent("Greet", {
93 * botId: locale.botId,
94 * localeId: locale.localeId,
95 * sampleUtterances: ["hello", "hi", "good morning"],
96 * });
97 * ```
98 *
99 * **Example:** Built-in Parent Intent
100 * ```typescript
101 * const help = yield* AWS.LexV2.Intent("Help", {
102 * botId: locale.botId,
103 * localeId: locale.localeId,
104 * parentIntentSignature: "AMAZON.HelpIntent",
105 * });
106 * ```
107 *
108 * @resource
109 */
110 export const Intent = Resource<Intent>("AWS.LexV2.Intent");
111
112 const createIntentName = (id: string, props: { intentName?: string | undefined }) =>
113 Effect.gen(function* () {
114 if (props.intentName) return props.intentName;
115 return toLexName(yield* createPhysicalName({ id, maxLength: 100 }));
116 });
117
118 const describeIntent = Effect.fn(function* (botId: string, localeId: string, intentId: string) {
119 return yield* lexm
120 .describeIntent({ botId, botVersion: "DRAFT", localeId, intentId })
121 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
122 });
123
124 /** Find an intent of the locale by exact name (used when state was lost). */
125 const findIntentByName = Effect.fn(function* (botId: string, localeId: string, intentName: string) {
126 const pages = yield* lexm.listIntents
127 .pages({
128 botId,
129 botVersion: "DRAFT",
130 localeId,
131 filters: [{ name: "IntentName", values: [intentName], operator: "EQ" }],
132 })
133 .pipe(
134 Stream.runCollect,
135 Effect.catchTag("ResourceNotFoundException", () =>
136 Effect.succeed([] as lexm.ListIntentsResponse[]),
137 ),
138 );
139 const summary = Array.from(pages)
140 .flatMap((page) => page.intentSummaries ?? [])
141 .find((intent) => intent.intentName === intentName);
142 if (summary?.intentId === undefined) return undefined;
143 return yield* describeIntent(botId, localeId, summary.intentId);
144 });
145
146 const utterancesOf = (intent: lexm.DescribeIntentResponse | lexm.CreateIntentResponse): string[] =>
147 (intent.sampleUtterances ?? []).map((u) => u.utterance);
148
149 const toUtterances = (utterances: string[] | undefined): lexm.SampleUtterance[] | undefined =>
150 utterances?.map((utterance) => ({ utterance }));
151
152 const attributesOf = (intent: lexm.DescribeIntentResponse): Intent["Attributes"] => ({
153 intentId: intent.intentId!,
154 intentName: intent.intentName!,
155 botId: intent.botId!,
156 botVersion: "DRAFT",
157 localeId: intent.localeId!,
158 });
159
160 export const IntentProvider = () =>
161 Provider.effect(
162 Intent,
163 Effect.gen(function* () {
164 return {
165 stables: ["intentId", "botId", "botVersion", "localeId"],
166
167 // Sub-resource keyed entirely by its bot locale — nuke reaches it
168 // through the parent bot's deletion.
169 list: () => Effect.succeed([]),
170
171 read: Effect.fn(function* ({ id, olds, output }) {
172 const botId = output?.botId ?? olds?.botId;
173 const localeId = output?.localeId ?? olds?.localeId;
174 if (botId === undefined || localeId === undefined) return undefined;
175 const observed =
176 output?.intentId !== undefined
177 ? yield* describeIntent(botId, localeId, output.intentId)
178 : yield* findIntentByName(botId, localeId, yield* createIntentName(id, olds ?? {}));
179 return observed === undefined ? undefined : attributesOf(observed);
180 }),
181
182 diff: Effect.fn(function* ({ news, olds }) {
183 if (!isResolved(news)) return undefined;
184 if (olds?.botId !== news.botId || olds?.localeId !== news.localeId) {
185 return { action: "replace" } as const;
186 }
187 }),
188
189 reconcile: Effect.fn(function* ({ id, news, output, session }) {
190 const intentName = yield* createIntentName(id, news);
191 const desiredUtterances = news.sampleUtterances ?? [];
192 const desiredDialogCodeHook =
193 news.dialogCodeHook !== undefined ? { enabled: news.dialogCodeHook } : undefined;
194 const desiredFulfillmentCodeHook =
195 news.fulfillmentCodeHook !== undefined
196 ? { enabled: news.fulfillmentCodeHook }
197 : undefined;
198
199 // 1. OBSERVE — output.intentId is only a cache; fall back to name.
200 let observed =
201 output?.intentId !== undefined
202 ? yield* describeIntent(news.botId, news.localeId, output.intentId)
203 : undefined;
204 if (observed === undefined) {
205 observed = yield* findIntentByName(news.botId, news.localeId, intentName);
206 }
207
208 // 2. ENSURE — create when missing.
209 if (observed === undefined) {
210 const created = yield* retryWhileConflict(
211 lexm.createIntent({
212 botId: news.botId,
213 botVersion: "DRAFT",
214 localeId: news.localeId,
215 intentName,
216 description: news.description,
217 sampleUtterances: toUtterances(news.sampleUtterances),
218 parentIntentSignature: news.parentIntentSignature,
219 dialogCodeHook: desiredDialogCodeHook,
220 fulfillmentCodeHook: desiredFulfillmentCodeHook,
221 }),
222 );
223 observed = yield* describeIntent(news.botId, news.localeId, created.intentId!);
224 if (observed === undefined) {
225 return yield* new IntentUnexpectedResponse({
226 message: `failed to read created Lex intent ${intentName}`,
227 });
228 }
229 } else if (
230 // 3. SYNC — UpdateIntent replaces the declared aspects; skip the
231 // call when nothing drifted.
232 observed.intentName !== intentName ||
233 (observed.description ?? undefined) !== (news.description ?? undefined) ||
234 JSON.stringify([...utterancesOf(observed)].sort()) !==
235 JSON.stringify([...desiredUtterances].sort()) ||
236 (observed.dialogCodeHook?.enabled ?? false) !== (news.dialogCodeHook ?? false) ||
237 (observed.fulfillmentCodeHook?.enabled ?? false) !== (news.fulfillmentCodeHook ?? false)
238 ) {
239 yield* retryWhileConflict(
240 lexm.updateIntent({
241 botId: news.botId,
242 botVersion: "DRAFT",
243 localeId: news.localeId,
244 intentId: observed.intentId!,
245 intentName,
246 description: news.description,
247 sampleUtterances: toUtterances(news.sampleUtterances),
248 parentIntentSignature: news.parentIntentSignature,
249 dialogCodeHook: desiredDialogCodeHook,
250 fulfillmentCodeHook: desiredFulfillmentCodeHook,
251 }),
252 );
253 observed = yield* describeIntent(news.botId, news.localeId, observed.intentId!);
254 if (observed === undefined) {
255 return yield* new IntentUnexpectedResponse({
256 message: `failed to read updated Lex intent ${intentName}`,
257 });
258 }
259 }
260
261 yield* session.note(observed.intentId!);
262 return attributesOf(observed);
263 }),
264
265 delete: Effect.fn(function* ({ output }) {
266 // Lex reports a missing intent (or already-deleted parent) as
267 // PreconditionFailed.
268 yield* retryWhileConflict(
269 lexm.deleteIntent({
270 botId: output.botId,
271 botVersion: "DRAFT",
272 localeId: output.localeId,
273 intentId: output.intentId,
274 }),
275 ).pipe(Effect.catchTag("PreconditionFailedException", () => Effect.void));
276 }),
277 };
278 }),
279 );