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

main
ts 363 lines 13.2 KB
Raw
1 import * as qbusiness from "@distilled.cloud/aws/qbusiness";
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, type Tags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as EffectStream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13
14 export class RetrieverInvalidProps extends Data.TaggedError("RetrieverInvalidProps")<{
15 readonly message: string;
16 readonly cause?: unknown;
17 }> {}
18
19 export class RetrieverUnexpectedResponse extends Data.TaggedError("RetrieverUnexpectedResponse")<{
20 readonly message: string;
21 readonly cause?: unknown;
22 }> {}
23
24 export type RetrieverStatus = qbusiness.RetrieverStatus;
25 export type RetrieverType = qbusiness.RetrieverType;
26
27 export interface RetrieverProps {
28 /**
29 * The identifier of the Amazon Q Business application the retriever
30 * attaches to. Changing it replaces the retriever.
31 */
32 applicationId: string;
33 /**
34 * The retriever type — `NATIVE_INDEX` (an Amazon Q Business index) or
35 * `KENDRA_INDEX` (an existing Amazon Kendra index). Changing it replaces
36 * the retriever.
37 */
38 type: RetrieverType;
39 /**
40 * Display name of the retriever.
41 * @default ${app}-${stage}-${id}
42 */
43 displayName?: string;
44 /**
45 * The index the retriever queries — `nativeIndexConfiguration` for a
46 * `NATIVE_INDEX` retriever, `kendraIndexConfiguration` for a
47 * `KENDRA_INDEX` retriever.
48 */
49 configuration: qbusiness.RetrieverConfiguration;
50 /**
51 * ARN of the IAM role the retriever assumes (required for
52 * `KENDRA_INDEX` retrievers to query the Kendra index).
53 */
54 roleArn?: string;
55 /**
56 * Tags to associate with the retriever.
57 */
58 tags?: Record<string, string>;
59 }
60
61 export interface Retriever extends Resource<
62 "AWS.QBusiness.Retriever",
63 RetrieverProps,
64 {
65 /**
66 * Service-assigned unique identifier of the retriever (unique within
67 * its application).
68 */
69 retrieverId: string;
70 /**
71 * The identifier of the application the retriever belongs to.
72 */
73 applicationId: string;
74 /**
75 * ARN of the retriever.
76 */
77 retrieverArn: string;
78 /**
79 * The retriever's display name.
80 */
81 displayName: string;
82 /**
83 * The retriever type.
84 */
85 type: RetrieverType | undefined;
86 /**
87 * Current lifecycle status of the retriever.
88 */
89 status: RetrieverStatus | undefined;
90 /**
91 * Current tags reported for the retriever.
92 */
93 tags: Record<string, string>;
94 },
95 never,
96 Providers
97 > {}
98
99 /**
100 * An Amazon Q Business retriever — the query engine that fetches relevant
101 * passages from an index (native or Kendra) to ground chat responses.
102 *
103 * ### Creating Retrievers
104 * **Example:** Native Index Retriever
105 * ```typescript
106 * import * as AWS from "@alchemy.run/aws";
107 *
108 * const retriever = yield* AWS.QBusiness.Retriever("Docs", {
109 * applicationId: app.applicationId,
110 * type: "NATIVE_INDEX",
111 * configuration: {
112 * nativeIndexConfiguration: { indexId: index.indexId },
113 * },
114 * });
115 * ```
116 *
117 * **Example:** Kendra Index Retriever
118 * ```typescript
119 * const retriever = yield* AWS.QBusiness.Retriever("Kendra", {
120 * applicationId: app.applicationId,
121 * type: "KENDRA_INDEX",
122 * roleArn: role.roleArn,
123 * configuration: {
124 * kendraIndexConfiguration: { indexId: kendraIndex.id },
125 * },
126 * });
127 * ```
128 *
129 * @resource
130 */
131 export const Retriever = Resource<Retriever>("AWS.QBusiness.Retriever");
132
133 const createDisplayName = (id: string, props: { displayName?: string | undefined }) =>
134 props.displayName
135 ? Effect.succeed(props.displayName)
136 : createPhysicalName({ id, maxLength: 100 });
137
138 const fetchTags = Effect.fn(function* (arn: string) {
139 const response = yield* qbusiness
140 .listTagsForResource({ resourceARN: arn })
141 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
142 return Object.fromEntries((response?.tags ?? []).map((tag) => [tag.key, tag.value]));
143 });
144
145 interface RetrieverState {
146 attrs: Retriever["Attributes"];
147 described: qbusiness.GetRetrieverResponse;
148 }
149
150 const readRetrieverById = Effect.fn(function* (applicationId: string, retrieverId: string) {
151 const described = yield* qbusiness
152 .getRetriever({ applicationId, retrieverId })
153 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
154 if (!described) return undefined;
155 const arn = described.retrieverArn;
156 if (arn === undefined) return undefined;
157 const state: RetrieverState = {
158 described,
159 attrs: {
160 retrieverId: described.retrieverId ?? retrieverId,
161 applicationId: described.applicationId ?? applicationId,
162 retrieverArn: arn,
163 displayName: described.displayName ?? "",
164 type: described.type,
165 status: described.status,
166 tags: yield* fetchTags(arn),
167 },
168 };
169 return state;
170 });
171
172 const findRetrieverByName = Effect.fn(function* (applicationId: string, displayName: string) {
173 const summaries = yield* qbusiness.listRetrievers.pages({ applicationId }).pipe(
174 EffectStream.runCollect,
175 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.retrievers ?? [])),
176 // The parent application may itself be gone.
177 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([] as qbusiness.Retriever[])),
178 );
179 const match = summaries.find((summary) => summary.displayName === displayName);
180 if (!match?.retrieverId) return undefined;
181 return yield* readRetrieverById(applicationId, match.retrieverId);
182 });
183
184 /**
185 * A retriever still transitioning toward `ACTIVE` — retried by
186 * {@link waitForRetrieverActive}'s bounded schedule.
187 */
188 class RetrieverNotReady extends Data.TaggedError("RetrieverNotReady")<{
189 readonly retrieverId: string;
190 readonly status: string | undefined;
191 }> {}
192
193 /**
194 * A retriever whose asynchronous provisioning converged to the terminal
195 * `FAILED` status.
196 */
197 export class RetrieverProvisioningFailed extends Data.TaggedError("RetrieverProvisioningFailed")<{
198 readonly retrieverId: string;
199 }> {}
200
201 // Explicitly-typed retry wrapper — an inline `Effect.retry` in provider
202 // lifecycle code leaks `Retry.Return`'s conditional type into declaration
203 // emit and widens the provider layer to `unknown` for every consumer of
204 // `AWS.providers()`.
205 const retryWhileNotReady = <A, E extends { readonly _tag: string }, R>(
206 self: Effect.Effect<A, E, R>,
207 ): Effect.Effect<A, E, R> =>
208 Effect.retry(self, {
209 while: (e) => e._tag === "RetrieverNotReady",
210 // Retriever provisioning is fast; poll every 5s up to ~5 min.
211 schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(60)]),
212 });
213
214 const waitForRetrieverActive = (applicationId: string, retrieverId: string) =>
215 retryWhileNotReady(
216 Effect.gen(function* () {
217 const described = yield* qbusiness
218 .getRetriever({ applicationId, retrieverId })
219 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
220 if (described?.status === "ACTIVE") return;
221 if (described?.status === "FAILED") {
222 return yield* new RetrieverProvisioningFailed({ retrieverId });
223 }
224 return yield* new RetrieverNotReady({ retrieverId, status: described?.status });
225 }),
226 );
227
228 export const RetrieverProvider = () =>
229 Provider.effect(
230 Retriever,
231 Effect.gen(function* () {
232 return {
233 stables: ["retrieverId", "applicationId", "retrieverArn"],
234 // Keyed by a parent application; cannot be enumerated account-wide
235 // without iterating every application — treated as a sub-resource per
236 // the factory list() convention.
237 list: () => Effect.succeed([]),
238 read: Effect.fn(function* ({ id, olds, output }) {
239 const applicationId = output?.applicationId ?? olds?.applicationId;
240 if (applicationId === undefined) return undefined;
241 const state = output?.retrieverId
242 ? yield* readRetrieverById(applicationId, output.retrieverId)
243 : yield* findRetrieverByName(applicationId, yield* createDisplayName(id, olds ?? {}));
244 if (!state) return undefined;
245 return (yield* hasAlchemyTags(id, state.attrs.tags as Tags))
246 ? state.attrs
247 : Unowned(state.attrs);
248 }),
249 diff: Effect.fn(function* ({ news, olds }) {
250 if (!isResolved(news)) return;
251 if (olds === undefined) return;
252 // The parent application and retriever type are fixed at creation.
253 if (olds.applicationId !== news.applicationId || olds.type !== news.type) {
254 return { action: "replace" } as const;
255 }
256 }),
257 reconcile: Effect.fn(function* ({ id, news, output, session }) {
258 if (!news) {
259 return yield* new RetrieverInvalidProps({
260 message: "QBusiness Retriever requires props",
261 });
262 }
263 const applicationId = news.applicationId;
264 const displayName = yield* createDisplayName(id, news);
265 const internalTags = yield* createInternalTags(id);
266 const desiredTags = { ...internalTags, ...news.tags };
267
268 // Observe — prefer the cached id; fall back to a name lookup so a
269 // create whose state failed to persist is adopted, not duplicated.
270 let state = output?.retrieverId
271 ? yield* readRetrieverById(applicationId, output.retrieverId)
272 : yield* findRetrieverByName(applicationId, displayName);
273
274 // Ensure — create if missing, then wait for ACTIVE.
275 if (state === undefined) {
276 const created = yield* qbusiness.createRetriever({
277 applicationId,
278 type: news.type,
279 displayName,
280 configuration: news.configuration,
281 roleArn: news.roleArn,
282 tags: Object.entries(desiredTags).map(([key, value]) => ({
283 key,
284 value,
285 })),
286 });
287 if (!created.retrieverId) {
288 return yield* new RetrieverUnexpectedResponse({
289 message: `CreateRetriever for '${displayName}' returned no retrieverId`,
290 });
291 }
292 yield* session.note(`Creating retriever ${displayName} (${created.retrieverId})...`);
293 yield* waitForRetrieverActive(applicationId, created.retrieverId);
294 state = yield* readRetrieverById(applicationId, created.retrieverId);
295 if (state === undefined) {
296 return yield* new RetrieverUnexpectedResponse({
297 message: `failed to read created retriever ${displayName}`,
298 });
299 }
300 }
301
302 // Sync mutable settings via UpdateRetriever — only when drifted.
303 const described = state.described;
304 const desiredNativeIndexId = news.configuration.nativeIndexConfiguration?.indexId;
305 const observedNativeIndexId = described.configuration?.nativeIndexConfiguration?.indexId;
306 const desiredKendraIndexId = news.configuration.kendraIndexConfiguration?.indexId;
307 const observedKendraIndexId = described.configuration?.kendraIndexConfiguration?.indexId;
308 const needsUpdate =
309 displayName !== described.displayName ||
310 (news.roleArn !== undefined && news.roleArn !== described.roleArn) ||
311 desiredNativeIndexId !== observedNativeIndexId ||
312 desiredKendraIndexId !== observedKendraIndexId;
313 if (needsUpdate) {
314 yield* qbusiness.updateRetriever({
315 applicationId,
316 retrieverId: state.attrs.retrieverId,
317 displayName,
318 configuration: news.configuration,
319 roleArn: news.roleArn,
320 });
321 yield* waitForRetrieverActive(applicationId, state.attrs.retrieverId);
322 yield* session.note(`Updated retriever ${displayName}`);
323 }
324
325 // Sync tags — diff against observed cloud tags.
326 const { removed, upsert } = diffTags(state.attrs.tags, desiredTags);
327 if (removed.length > 0) {
328 yield* qbusiness.untagResource({
329 resourceARN: state.attrs.retrieverArn,
330 tagKeys: removed,
331 });
332 }
333 if (upsert.length > 0) {
334 yield* qbusiness.tagResource({
335 resourceARN: state.attrs.retrieverArn,
336 tags: upsert.map(({ Key, Value }) => ({
337 key: Key,
338 value: Value,
339 })),
340 });
341 }
342
343 yield* session.note(state.attrs.retrieverArn);
344
345 const final = yield* readRetrieverById(applicationId, state.attrs.retrieverId);
346 if (!final) {
347 return yield* new RetrieverUnexpectedResponse({
348 message: `failed to read reconciled retriever ${displayName}`,
349 });
350 }
351 return final.attrs;
352 }),
353 delete: Effect.fn(function* ({ output }) {
354 yield* qbusiness
355 .deleteRetriever({
356 applicationId: output.applicationId,
357 retrieverId: output.retrieverId,
358 })
359 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
360 }),
361 };
362 }),
363 );