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

main
ts 384 lines 12.6 KB
Raw
1 import * as qapps from "@distilled.cloud/aws/qapps";
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 EffectStream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12
13 export class QAppInvalidProps extends Data.TaggedError("QAppInvalidProps")<{
14 readonly message: string;
15 readonly cause?: unknown;
16 }> {}
17
18 export class QAppUnexpectedResponse extends Data.TaggedError("QAppUnexpectedResponse")<{
19 readonly message: string;
20 readonly cause?: unknown;
21 }> {}
22
23 export type AppStatus = qapps.AppStatus;
24 export type AppRequiredCapability = qapps.AppRequiredCapability;
25 export type CardInput = qapps.CardInput;
26
27 /**
28 * Definition of an Amazon Q App — the ordered cards that make up the app's
29 * flow plus an optional initial prompt.
30 */
31 export interface QAppDefinition {
32 /**
33 * The cards that make up the Q App. Card ids must be UUIDs; dependencies
34 * between cards are calculated by the service from references in prompts
35 * (e.g. `@card-title`).
36 */
37 cards: qapps.CardInput[];
38 /**
39 * The initial prompt displayed when the Q App is started.
40 */
41 initialPrompt?: string;
42 }
43
44 export interface QAppProps {
45 /**
46 * The unique identifier of the Amazon Q Business application environment
47 * instance the Q App is created in. Changing it replaces the Q App.
48 */
49 instanceId: string;
50 /**
51 * Title of the Q App.
52 * @default ${app}-${stage}-${id}
53 */
54 title?: string;
55 /**
56 * A description of the Q App.
57 */
58 description?: string;
59 /**
60 * The definition of the Q App — its cards and flow.
61 */
62 appDefinition: QAppDefinition;
63 /**
64 * Tags to associate with the Q App.
65 */
66 tags?: Record<string, string>;
67 }
68
69 export interface QApp extends Resource<
70 "AWS.QApps.QApp",
71 QAppProps,
72 {
73 /**
74 * Service-assigned unique identifier of the Q App.
75 */
76 appId: string;
77 /**
78 * ARN of the Q App.
79 */
80 appArn: string;
81 /**
82 * The Q Business application environment instance the Q App belongs to.
83 */
84 instanceId: string;
85 /**
86 * The Q App's title.
87 */
88 title: string;
89 /**
90 * The Q App's description.
91 */
92 description: string | undefined;
93 /**
94 * The current version of the Q App definition.
95 */
96 appVersion: number;
97 /**
98 * Lifecycle status of the Q App (`DRAFT`, `PUBLISHED`, `DELETED`).
99 */
100 status: AppStatus;
101 /**
102 * Capabilities end users need to run the Q App (e.g. `FileUpload`).
103 */
104 requiredCapabilities: AppRequiredCapability[] | undefined;
105 /**
106 * Current tags reported for the Q App.
107 */
108 tags: Record<string, string>;
109 },
110 never,
111 Providers
112 > {}
113
114 /**
115 * An Amazon Q App — a lightweight, purpose-built AI app defined as a flow of
116 * cards (text inputs, file uploads, LLM query cards, plugin cards) running
117 * inside an Amazon Q Business application environment.
118 *
119 * :::caution
120 * Q Apps live inside an Amazon Q Business application (pass its id as
121 * `instanceId`), which itself requires IAM Identity Center. The calling
122 * identity must be a user of that Q Business application.
123 * :::
124 * ### Creating Q Apps
125 * **Example:** Prompt-Driven Q App
126 * ```typescript
127 * import * as AWS from "@alchemy.run/aws";
128 *
129 * const summarizer = yield* AWS.QApps.QApp("Summarizer", {
130 * instanceId: qbusinessApp.applicationId,
131 * description: "Summarizes pasted text",
132 * appDefinition: {
133 * cards: [
134 * {
135 * textInput: {
136 * id: "11111111-1111-4111-8111-111111111111",
137 * title: "Source Text",
138 * type: "text-input",
139 * },
140 * },
141 * {
142 * qQuery: {
143 * id: "22222222-2222-4222-8222-222222222222",
144 * title: "Summary",
145 * type: "q-query",
146 * prompt: "Summarize the following text: @Source Text",
147 * },
148 * },
149 * ],
150 * },
151 * });
152 * ```
153 *
154 * **Example:** File Upload Q App
155 * ```typescript
156 * const analyzer = yield* AWS.QApps.QApp("DocAnalyzer", {
157 * instanceId: qbusinessApp.applicationId,
158 * appDefinition: {
159 * initialPrompt: "Upload a document to analyze",
160 * cards: [
161 * {
162 * fileUpload: {
163 * id: "33333333-3333-4333-8333-333333333333",
164 * title: "Document",
165 * type: "file-upload",
166 * },
167 * },
168 * {
169 * qQuery: {
170 * id: "44444444-4444-4444-8444-444444444444",
171 * title: "Analysis",
172 * type: "q-query",
173 * prompt: "List the key points of @Document",
174 * },
175 * },
176 * ],
177 * },
178 * });
179 * ```
180 *
181 * @resource
182 */
183 export const QApp = Resource<QApp>("AWS.QApps.QApp");
184
185 const createTitle = (id: string, props: { title?: string | undefined }) =>
186 props.title ? Effect.succeed(props.title) : createPhysicalName({ id, maxLength: 100 });
187
188 const fetchTags = Effect.fn(function* (arn: string) {
189 const response = yield* qapps
190 .listTagsForResource({ resourceARN: arn })
191 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
192 const tags: Record<string, string> = {};
193 for (const [key, value] of Object.entries(response?.tags ?? {})) {
194 if (value !== undefined) tags[key] = value;
195 }
196 return tags;
197 });
198
199 interface QAppState {
200 attrs: QApp["Attributes"];
201 observed: qapps.GetQAppOutput;
202 }
203
204 const readQAppById = Effect.fn(function* (instanceId: string, appId: string) {
205 const observed = yield* qapps
206 .getQApp({ instanceId, appId })
207 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
208 if (!observed || observed.status === "DELETED") return undefined;
209 const state: QAppState = {
210 observed,
211 attrs: {
212 appId: observed.appId,
213 appArn: observed.appArn,
214 instanceId,
215 title: observed.title,
216 description: observed.description,
217 appVersion: observed.appVersion,
218 status: observed.status,
219 requiredCapabilities: observed.requiredCapabilities?.slice(),
220 tags: yield* fetchTags(observed.appArn),
221 },
222 };
223 return state;
224 });
225
226 const findQAppByTitle = Effect.fn(function* (instanceId: string, title: string) {
227 const apps = yield* qapps.listQApps.pages({ instanceId }).pipe(
228 EffectStream.runCollect,
229 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.apps ?? [])),
230 );
231 const match = apps.find((app) => app.title === title && app.status !== "DELETED");
232 if (!match?.appId) return undefined;
233 return yield* readQAppById(instanceId, match.appId);
234 });
235
236 /**
237 * Structural subset comparison: every defined field of `desired` must be
238 * present (deep-equal) in `observed`. Observed cards carry service-computed
239 * fields (`dependencies`, resolved `outputSource` defaults, …) that the
240 * desired card input never specifies — those must not register as drift.
241 */
242 const isSubsetOf = (desired: unknown, observed: unknown): boolean => {
243 if (desired === undefined) return true;
244 if (Array.isArray(desired)) {
245 if (!Array.isArray(observed) || observed.length !== desired.length) {
246 return false;
247 }
248 return desired.every((item, index) => isSubsetOf(item, observed[index]));
249 }
250 if (typeof desired === "object" && desired !== null) {
251 if (typeof observed !== "object" || observed === null) return false;
252 const observedRecord: Record<string, unknown> = { ...observed };
253 return Object.entries(desired).every(([key, value]) => isSubsetOf(value, observedRecord[key]));
254 }
255 return desired === observed;
256 };
257
258 const definitionDrifted = (desired: QAppDefinition, observed: qapps.GetQAppOutput): boolean => {
259 if (desired.initialPrompt !== undefined && desired.initialPrompt !== observed.initialPrompt) {
260 return true;
261 }
262 return !isSubsetOf(desired.cards, observed.appDefinition.cards);
263 };
264
265 export const QAppProvider = () =>
266 Provider.effect(
267 QApp,
268 Effect.gen(function* () {
269 return {
270 stables: ["appId", "appArn", "instanceId"],
271 // Q Apps are keyed by their parent Q Business application environment
272 // instance — enumeration across all instances is not meaningful here.
273 list: () => Effect.succeed([]),
274 read: Effect.fn(function* ({ id, olds, output }) {
275 const instanceId = output?.instanceId ?? olds?.instanceId;
276 if (instanceId === undefined) return undefined;
277 const state = output?.appId
278 ? yield* readQAppById(instanceId, output.appId)
279 : yield* findQAppByTitle(instanceId, yield* createTitle(id, olds ?? {}));
280 if (!state) return undefined;
281 return (yield* hasAlchemyTags(id, state.attrs.tags as Tags))
282 ? state.attrs
283 : Unowned(state.attrs);
284 }),
285 diff: Effect.fn(function* ({ news, olds }) {
286 if (!isResolved(news)) return;
287 if (olds === undefined) return;
288 // A Q App is bound to its Q Business application environment
289 // instance at creation.
290 if (olds.instanceId !== news.instanceId) {
291 return { action: "replace" } as const;
292 }
293 }),
294 reconcile: Effect.fn(function* ({ id, news, output, session }) {
295 if (!news) {
296 return yield* new QAppInvalidProps({ message: "QApps QApp requires props" });
297 }
298 const title = yield* createTitle(id, news);
299 const internalTags = yield* createInternalTags(id);
300 const desiredTags = { ...internalTags, ...news.tags };
301
302 // Observe — prefer the cached id; fall back to a title lookup so a
303 // create whose state failed to persist is adopted, not duplicated.
304 let state = output?.appId
305 ? yield* readQAppById(news.instanceId, output.appId)
306 : yield* findQAppByTitle(news.instanceId, title);
307
308 // Ensure — create if missing.
309 if (state === undefined) {
310 const created = yield* qapps.createQApp({
311 instanceId: news.instanceId,
312 title,
313 description: news.description,
314 appDefinition: {
315 cards: news.appDefinition.cards,
316 initialPrompt: news.appDefinition.initialPrompt,
317 },
318 tags: desiredTags,
319 });
320 yield* session.note(`Created Q App ${title} (${created.appId})`);
321 state = yield* readQAppById(news.instanceId, created.appId);
322 if (state === undefined) {
323 return yield* new QAppUnexpectedResponse({
324 message: `failed to read created Q App ${title}`,
325 });
326 }
327 }
328
329 // Sync title/description/definition via UpdateQApp — only on drift.
330 const observed = state.observed;
331 const needsUpdate =
332 title !== observed.title ||
333 (news.description ?? "") !== (observed.description ?? "") ||
334 definitionDrifted(news.appDefinition, observed);
335 if (needsUpdate) {
336 yield* qapps.updateQApp({
337 instanceId: news.instanceId,
338 appId: state.attrs.appId,
339 title,
340 description: news.description,
341 appDefinition: {
342 cards: news.appDefinition.cards,
343 initialPrompt: news.appDefinition.initialPrompt,
344 },
345 });
346 yield* session.note(`Updated Q App ${title}`);
347 }
348
349 // Sync tags — diff against observed cloud tags.
350 const { removed, upsert } = diffTags(state.attrs.tags, desiredTags);
351 if (removed.length > 0) {
352 yield* qapps.untagResource({
353 resourceARN: state.attrs.appArn,
354 tagKeys: removed,
355 });
356 }
357 if (upsert.length > 0) {
358 yield* qapps.tagResource({
359 resourceARN: state.attrs.appArn,
360 tags: Object.fromEntries(upsert.map(({ Key, Value }) => [Key, Value])),
361 });
362 }
363
364 yield* session.note(state.attrs.appArn);
365
366 const final = yield* readQAppById(news.instanceId, state.attrs.appId);
367 if (!final) {
368 return yield* new QAppUnexpectedResponse({
369 message: `failed to read reconciled Q App ${title}`,
370 });
371 }
372 return final.attrs;
373 }),
374 delete: Effect.fn(function* ({ output }) {
375 yield* qapps
376 .deleteQApp({
377 instanceId: output.instanceId,
378 appId: output.appId,
379 })
380 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
381 }),
382 };
383 }),
384 );