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

main
ts 401 lines 14.4 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 * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags, hasAlchemyTags, type Tags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import type { Providers } from "../Providers.ts";
11
12 export class WebExperienceInvalidProps extends Data.TaggedError("WebExperienceInvalidProps")<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export class WebExperienceUnexpectedResponse extends Data.TaggedError(
18 "WebExperienceUnexpectedResponse",
19 )<{
20 readonly message: string;
21 readonly cause?: unknown;
22 }> {}
23
24 export type WebExperienceStatus = qbusiness.WebExperienceStatus;
25
26 export interface WebExperienceProps {
27 /**
28 * The identifier of the Amazon Q Business application the web experience
29 * fronts. Changing it replaces the web experience.
30 */
31 applicationId: string;
32 /**
33 * The title displayed in the web experience header.
34 */
35 title?: string;
36 /**
37 * The subtitle displayed under the title.
38 */
39 subtitle?: string;
40 /**
41 * A custom welcome message displayed when a conversation starts.
42 */
43 welcomeMessage?: string;
44 /**
45 * Whether sample chat prompts are shown to end users.
46 */
47 samplePromptsControlMode?: qbusiness.WebExperienceSamplePromptsControlMode;
48 /**
49 * Website domains allowed to embed the web experience.
50 */
51 origins?: string[];
52 /**
53 * ARN of the IAM role the web experience assumes to talk to the
54 * application on behalf of end users.
55 */
56 roleArn?: string;
57 /**
58 * External identity-provider settings (SAML or OIDC) for the web
59 * experience.
60 */
61 identityProviderConfiguration?: qbusiness.IdentityProviderConfiguration;
62 /**
63 * Which browser extensions (Chrome, Firefox) may connect to the web
64 * experience.
65 */
66 browserExtensionConfiguration?: qbusiness.BrowserExtensionConfiguration;
67 /**
68 * Custom logo/font/CSS customization for the web experience.
69 */
70 customizationConfiguration?: qbusiness.CustomizationConfiguration;
71 /**
72 * Tags to associate with the web experience.
73 */
74 tags?: Record<string, string>;
75 }
76
77 export interface WebExperience extends Resource<
78 "AWS.QBusiness.WebExperience",
79 WebExperienceProps,
80 {
81 /**
82 * Service-assigned unique identifier of the web experience (unique
83 * within its application).
84 */
85 webExperienceId: string;
86 /**
87 * The identifier of the application the web experience belongs to.
88 */
89 applicationId: string;
90 /**
91 * ARN of the web experience.
92 */
93 webExperienceArn: string;
94 /**
95 * The AWS-hosted URL end users open to chat with the application.
96 */
97 defaultEndpoint: string | undefined;
98 /**
99 * Current lifecycle status of the web experience.
100 */
101 status: WebExperienceStatus | undefined;
102 /**
103 * Current tags reported for the web experience.
104 */
105 tags: Record<string, string>;
106 },
107 never,
108 Providers
109 > {}
110
111 /**
112 * An Amazon Q Business web experience — the hosted chat UI end users open
113 * to converse with an application.
114 *
115 * ### Creating Web Experiences
116 * **Example:** Basic Web Experience
117 * ```typescript
118 * import * as AWS from "@alchemy.run/aws";
119 *
120 * const web = yield* AWS.QBusiness.WebExperience("Chat", {
121 * applicationId: app.applicationId,
122 * title: "Company Assistant",
123 * welcomeMessage: "Ask me anything about our docs.",
124 * });
125 * ```
126 *
127 * **Example:** Embeddable Web Experience
128 * ```typescript
129 * const web = yield* AWS.QBusiness.WebExperience("Chat", {
130 * applicationId: app.applicationId,
131 * origins: ["https://intranet.example.com"],
132 * samplePromptsControlMode: "ENABLED",
133 * });
134 * ```
135 *
136 * @resource
137 */
138 export const WebExperience = Resource<WebExperience>("AWS.QBusiness.WebExperience");
139
140 const fetchTags = Effect.fn(function* (arn: string) {
141 const response = yield* qbusiness
142 .listTagsForResource({ resourceARN: arn })
143 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
144 return Object.fromEntries((response?.tags ?? []).map((tag) => [tag.key, tag.value]));
145 });
146
147 interface WebExperienceState {
148 attrs: WebExperience["Attributes"];
149 described: qbusiness.GetWebExperienceResponse;
150 }
151
152 const readWebExperienceById = Effect.fn(function* (applicationId: string, webExperienceId: string) {
153 const described = yield* qbusiness
154 .getWebExperience({ applicationId, webExperienceId })
155 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
156 if (!described || described.status === "DELETING") return undefined;
157 const arn = described.webExperienceArn;
158 if (arn === undefined) return undefined;
159 const state: WebExperienceState = {
160 described,
161 attrs: {
162 webExperienceId: described.webExperienceId ?? webExperienceId,
163 applicationId: described.applicationId ?? applicationId,
164 webExperienceArn: arn,
165 defaultEndpoint: described.defaultEndpoint,
166 status: described.status,
167 tags: yield* fetchTags(arn),
168 },
169 };
170 return state;
171 });
172
173 /**
174 * A web experience still transitioning toward a settled status — retried by
175 * {@link waitForWebExperienceSettled}'s bounded schedule.
176 */
177 class WebExperienceNotReady extends Data.TaggedError("WebExperienceNotReady")<{
178 readonly webExperienceId: string;
179 readonly status: string | undefined;
180 }> {}
181
182 /**
183 * A web experience whose asynchronous provisioning converged to the
184 * terminal `FAILED` status.
185 */
186 export class WebExperienceProvisioningFailed extends Data.TaggedError(
187 "WebExperienceProvisioningFailed",
188 )<{
189 readonly webExperienceId: string;
190 readonly message: string | undefined;
191 }> {}
192
193 // Explicitly-typed retry wrapper — an inline `Effect.retry` in provider
194 // lifecycle code leaks `Retry.Return`'s conditional type into declaration
195 // emit and widens the provider layer to `unknown` for every consumer of
196 // `AWS.providers()`.
197 const retryWhileNotReady = <A, E extends { readonly _tag: string }, R>(
198 self: Effect.Effect<A, E, R>,
199 ): Effect.Effect<A, E, R> =>
200 Effect.retry(self, {
201 while: (e) => e._tag === "WebExperienceNotReady",
202 // Web experience provisioning is fast; poll every 5s up to ~5 min.
203 schedule: Schedule.max([Schedule.spaced("5 seconds"), Schedule.recurs(60)]),
204 });
205
206 // A web experience without identity-provider auth settles in
207 // PENDING_AUTH_CONFIG rather than ACTIVE — both are converged states.
208 const waitForWebExperienceSettled = (
209 applicationId: string,
210 webExperienceId: string,
211 target: "SETTLED" | "DELETED",
212 ) =>
213 retryWhileNotReady(
214 Effect.gen(function* () {
215 const described = yield* qbusiness
216 .getWebExperience({ applicationId, webExperienceId })
217 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
218 if (target === "DELETED") {
219 if (described === undefined) return;
220 return yield* new WebExperienceNotReady({
221 webExperienceId,
222 status: described.status,
223 });
224 }
225 if (described?.status === "ACTIVE" || described?.status === "PENDING_AUTH_CONFIG") {
226 return;
227 }
228 if (described?.status === "FAILED") {
229 return yield* new WebExperienceProvisioningFailed({
230 webExperienceId,
231 message: described.error?.errorMessage,
232 });
233 }
234 return yield* new WebExperienceNotReady({
235 webExperienceId,
236 status: described?.status,
237 });
238 }),
239 );
240
241 export const WebExperienceProvider = () =>
242 Provider.effect(
243 WebExperience,
244 Effect.gen(function* () {
245 return {
246 stables: ["webExperienceId", "applicationId", "webExperienceArn"],
247 // Keyed by a parent application; cannot be enumerated account-wide
248 // without iterating every application — treated as a sub-resource per
249 // the factory list() convention.
250 list: () => Effect.succeed([]),
251 read: Effect.fn(function* ({ id, olds, output }) {
252 const applicationId = output?.applicationId ?? olds?.applicationId;
253 // Web experience summaries carry no display name, so there is no
254 // name-based fallback — without a cached id the resource is
255 // treated as missing.
256 if (applicationId === undefined || output?.webExperienceId === undefined) {
257 return undefined;
258 }
259 const state = yield* readWebExperienceById(applicationId, output.webExperienceId);
260 if (!state) return undefined;
261 return (yield* hasAlchemyTags(id, state.attrs.tags as Tags))
262 ? state.attrs
263 : Unowned(state.attrs);
264 }),
265 diff: Effect.fn(function* ({ news, olds }) {
266 if (!isResolved(news)) return;
267 if (olds === undefined) return;
268 // The parent application is fixed at creation.
269 if (olds.applicationId !== news.applicationId) {
270 return { action: "replace" } as const;
271 }
272 }),
273 reconcile: Effect.fn(function* ({ id, news, output, session }) {
274 if (!news) {
275 return yield* new WebExperienceInvalidProps({
276 message: "QBusiness WebExperience requires props",
277 });
278 }
279 const applicationId = news.applicationId;
280 const internalTags = yield* createInternalTags(id);
281 const desiredTags = { ...internalTags, ...news.tags };
282
283 // Observe — the cached id is the only handle (summaries carry no
284 // display name to search by).
285 let state = output?.webExperienceId
286 ? yield* readWebExperienceById(applicationId, output.webExperienceId)
287 : undefined;
288
289 // Ensure — create if missing, then wait for a settled status.
290 if (state === undefined) {
291 const created = yield* qbusiness.createWebExperience({
292 applicationId,
293 title: news.title,
294 subtitle: news.subtitle,
295 welcomeMessage: news.welcomeMessage,
296 samplePromptsControlMode: news.samplePromptsControlMode,
297 origins: news.origins,
298 roleArn: news.roleArn,
299 identityProviderConfiguration: news.identityProviderConfiguration,
300 browserExtensionConfiguration: news.browserExtensionConfiguration,
301 customizationConfiguration: news.customizationConfiguration,
302 tags: Object.entries(desiredTags).map(([key, value]) => ({
303 key,
304 value,
305 })),
306 });
307 if (!created.webExperienceId) {
308 return yield* new WebExperienceUnexpectedResponse({
309 message: `CreateWebExperience for '${id}' returned no webExperienceId`,
310 });
311 }
312 yield* session.note(`Creating web experience (${created.webExperienceId})...`);
313 yield* waitForWebExperienceSettled(applicationId, created.webExperienceId, "SETTLED");
314 state = yield* readWebExperienceById(applicationId, created.webExperienceId);
315 if (state === undefined) {
316 return yield* new WebExperienceUnexpectedResponse({
317 message: `failed to read created web experience for '${id}'`,
318 });
319 }
320 }
321
322 // Sync mutable settings via UpdateWebExperience — only when
323 // drifted.
324 const described = state.described;
325 const needsUpdate =
326 (news.title ?? "") !== (described.title ?? "") ||
327 (news.subtitle ?? "") !== (described.subtitle ?? "") ||
328 (news.welcomeMessage ?? "") !== (described.welcomeMessage ?? "") ||
329 (news.samplePromptsControlMode !== undefined &&
330 news.samplePromptsControlMode !== described.samplePromptsControlMode) ||
331 (news.roleArn !== undefined && news.roleArn !== described.roleArn) ||
332 JSON.stringify(news.origins ?? []) !== JSON.stringify(described.origins ?? []) ||
333 news.identityProviderConfiguration !== undefined ||
334 news.browserExtensionConfiguration !== undefined ||
335 news.customizationConfiguration !== undefined;
336 if (needsUpdate) {
337 yield* qbusiness.updateWebExperience({
338 applicationId,
339 webExperienceId: state.attrs.webExperienceId,
340 title: news.title,
341 subtitle: news.subtitle,
342 welcomeMessage: news.welcomeMessage,
343 samplePromptsControlMode: news.samplePromptsControlMode,
344 origins: news.origins,
345 roleArn: news.roleArn,
346 identityProviderConfiguration: news.identityProviderConfiguration,
347 browserExtensionConfiguration: news.browserExtensionConfiguration,
348 customizationConfiguration: news.customizationConfiguration,
349 });
350 yield* waitForWebExperienceSettled(
351 applicationId,
352 state.attrs.webExperienceId,
353 "SETTLED",
354 );
355 yield* session.note(`Updated web experience ${id}`);
356 }
357
358 // Sync tags — diff against observed cloud tags.
359 const { removed, upsert } = diffTags(state.attrs.tags, desiredTags);
360 if (removed.length > 0) {
361 yield* qbusiness.untagResource({
362 resourceARN: state.attrs.webExperienceArn,
363 tagKeys: removed,
364 });
365 }
366 if (upsert.length > 0) {
367 yield* qbusiness.tagResource({
368 resourceARN: state.attrs.webExperienceArn,
369 tags: upsert.map(({ Key, Value }) => ({
370 key: Key,
371 value: Value,
372 })),
373 });
374 }
375
376 yield* session.note(state.attrs.webExperienceArn);
377
378 const final = yield* readWebExperienceById(applicationId, state.attrs.webExperienceId);
379 if (!final) {
380 return yield* new WebExperienceUnexpectedResponse({
381 message: `failed to read reconciled web experience for '${id}'`,
382 });
383 }
384 return final.attrs;
385 }),
386 delete: Effect.fn(function* ({ output }) {
387 yield* qbusiness
388 .deleteWebExperience({
389 applicationId: output.applicationId,
390 webExperienceId: output.webExperienceId,
391 })
392 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
393 yield* waitForWebExperienceSettled(
394 output.applicationId,
395 output.webExperienceId,
396 "DELETED",
397 );
398 }),
399 };
400 }),
401 );