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

main
ts 528 lines 20.4 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import * as QBusiness from "@alchemy.run/aws/QBusiness";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import path from "pathe";
9
10 const main = path.resolve(import.meta.dirname, "handler.ts");
11
12 export class QBusinessTestFunction extends Lambda.Function<Lambda.Function>()(
13 "QBusinessTestFunction",
14 ) {}
15
16 /**
17 * Every route answers `{ …fields }` on success or `{ errorTag }` when the
18 * operation fails with a TYPED error — the test asserts on concrete fields
19 * (or a typed tag), which proves the binding wiring, the id injection, and
20 * the IAM grants. An untyped error crashes into a 500.
21 */
22 const errorTagged = <A, E extends { _tag: string }, R>(
23 effect: Effect.Effect<A, E, R>,
24 ): Effect.Effect<A | { errorTag: string }, never, R> =>
25 effect.pipe(
26 Effect.map((a): A | { errorTag: string } => a),
27 Effect.catch((e) => Effect.succeed({ errorTag: e._tag })),
28 );
29
30 /**
31 * Runtime fixture: an `ANONYMOUS`-identity Amazon Q Business application (no
32 * IAM Identity Center required) with a STARTER index, a CUSTOM data source,
33 * a native retriever, and a web experience, plus a Lambda bound to all
34 * thirty-six QBusiness bindings. Gated behind AWS_TEST_QBUSINESS=1 — the
35 * index bills hourly while it exists and the application takes minutes to
36 * provision.
37 */
38 export default QBusinessTestFunction.make(
39 {
40 main,
41 functionUrl: true,
42 timeout: Duration.seconds(60),
43 },
44 Effect.gen(function* () {
45 const app = yield* QBusiness.Application("BindingsApp", {
46 identityType: "ANONYMOUS",
47 description: "alchemy QBusiness bindings fixture",
48 });
49
50 const index = yield* QBusiness.Index("BindingsIndex", {
51 applicationId: app.applicationId,
52 });
53
54 const retriever = yield* QBusiness.Retriever("BindingsRetriever", {
55 applicationId: app.applicationId,
56 type: "NATIVE_INDEX",
57 configuration: {
58 nativeIndexConfiguration: { indexId: index.indexId },
59 },
60 });
61
62 const source = yield* QBusiness.DataSource("BindingsSource", {
63 applicationId: app.applicationId,
64 indexId: index.indexId,
65 configuration: { type: "CUSTOM", version: "1.0.0" },
66 });
67
68 const web = yield* QBusiness.WebExperience("BindingsChat", {
69 applicationId: app.applicationId,
70 title: "Alchemy QBusiness Bindings",
71 });
72
73 // Application-scoped bindings.
74 const chat = yield* QBusiness.ChatSync(app);
75 const search = yield* QBusiness.SearchRelevantContent(app);
76 const feedback = yield* QBusiness.PutFeedback(app);
77 const getControls = yield* QBusiness.GetChatControlsConfiguration(app);
78 const updateControls = yield* QBusiness.UpdateChatControlsConfiguration(app);
79 const deleteControls = yield* QBusiness.DeleteChatControlsConfiguration(app);
80 const listConversations = yield* QBusiness.ListConversations(app);
81 const deleteConversation = yield* QBusiness.DeleteConversation(app);
82 const listMessages = yield* QBusiness.ListMessages(app);
83 const listAttachments = yield* QBusiness.ListAttachments(app);
84 const deleteAttachment = yield* QBusiness.DeleteAttachment(app);
85 const getMedia = yield* QBusiness.GetMedia(app);
86 const createUser = yield* QBusiness.CreateUser(app);
87 const getUser = yield* QBusiness.GetUser(app);
88 const updateUser = yield* QBusiness.UpdateUser(app);
89 const deleteUser = yield* QBusiness.DeleteUser(app);
90 const getPolicy = yield* QBusiness.GetPolicy(app);
91 const associatePermission = yield* QBusiness.AssociatePermission(app);
92 const disassociatePermission = yield* QBusiness.DisassociatePermission(app);
93 const createSubscription = yield* QBusiness.CreateSubscription(app);
94 const updateSubscription = yield* QBusiness.UpdateSubscription(app);
95 const cancelSubscription = yield* QBusiness.CancelSubscription(app);
96 const listSubscriptions = yield* QBusiness.ListSubscriptions(app);
97
98 // Index-scoped bindings.
99 const putDocuments = yield* QBusiness.BatchPutDocument(index);
100 const deleteDocuments = yield* QBusiness.BatchDeleteDocument(index);
101 const listDocuments = yield* QBusiness.ListDocuments(index);
102 const getDocumentContent = yield* QBusiness.GetDocumentContent(index);
103 const checkDocumentAccess = yield* QBusiness.CheckDocumentAccess(index);
104 const putGroup = yield* QBusiness.PutGroup(index);
105 const getGroup = yield* QBusiness.GetGroup(index);
106 const deleteGroup = yield* QBusiness.DeleteGroup(index);
107 const listGroups = yield* QBusiness.ListGroups(index);
108
109 // Data-source-scoped bindings.
110 const startSync = yield* QBusiness.StartDataSourceSyncJob(source);
111 const stopSync = yield* QBusiness.StopDataSourceSyncJob(source);
112 const listSyncJobs = yield* QBusiness.ListDataSourceSyncJobs(source);
113
114 // Web-experience-scoped binding.
115 const createAnonymousUrl = yield* QBusiness.CreateAnonymousWebExperienceUrl(web);
116
117 // Needed by /search — resolved lazily at request time.
118 const retrieverId = yield* retriever.retrieverId;
119
120 const bound = {
121 chat,
122 search,
123 feedback,
124 getControls,
125 updateControls,
126 deleteControls,
127 listConversations,
128 deleteConversation,
129 listMessages,
130 listAttachments,
131 deleteAttachment,
132 getMedia,
133 createUser,
134 getUser,
135 updateUser,
136 deleteUser,
137 getPolicy,
138 associatePermission,
139 disassociatePermission,
140 createSubscription,
141 updateSubscription,
142 cancelSubscription,
143 listSubscriptions,
144 putDocuments,
145 deleteDocuments,
146 listDocuments,
147 getDocumentContent,
148 checkDocumentAccess,
149 putGroup,
150 getGroup,
151 deleteGroup,
152 listGroups,
153 startSync,
154 stopSync,
155 listSyncJobs,
156 createAnonymousUrl,
157 };
158
159 return {
160 fetch: Effect.gen(function* () {
161 const request = yield* HttpServerRequest;
162 const url = new URL(request.originalUrl);
163 const pathname = url.pathname;
164
165 if (pathname === "/bindings") {
166 return yield* HttpServerResponse.json({ bound: Object.keys(bound) });
167 }
168
169 // ------------------------------------------------- document plane
170 if (pathname === "/put-documents") {
171 const result = yield* errorTagged(
172 putDocuments({
173 documents: [
174 {
175 id: "welcome",
176 title: "Welcome to Alchemy",
177 content: {
178 blob: new TextEncoder().encode(
179 "Alchemy is an Infrastructure-as-Effects framework. " +
180 "The zanzibar passphrase is quicksilver.",
181 ),
182 },
183 contentType: "PLAIN_TEXT",
184 },
185 ],
186 }),
187 );
188 return yield* HttpServerResponse.json(
189 "errorTag" in result ? result : { failed: (result.failedDocuments ?? []).length },
190 );
191 }
192
193 if (pathname === "/documents") {
194 const result = yield* errorTagged(listDocuments());
195 return yield* HttpServerResponse.json(
196 "errorTag" in result
197 ? result
198 : {
199 count: (result.documentDetailList ?? []).length,
200 statuses: (result.documentDetailList ?? []).map((d) => d.status),
201 },
202 );
203 }
204
205 if (pathname === "/document-content") {
206 const result = yield* errorTagged(getDocumentContent({ documentId: "welcome" }));
207 return yield* HttpServerResponse.json(
208 "errorTag" in result ? result : { hasUrl: typeof result.presignedUrl === "string" },
209 );
210 }
211
212 if (pathname === "/check-access") {
213 const result = yield* errorTagged(
214 checkDocumentAccess({
215 userId: "anon@example.com",
216 documentId: "welcome",
217 }),
218 );
219 return yield* HttpServerResponse.json(
220 "errorTag" in result ? result : { hasAccess: result.hasAccess },
221 );
222 }
223
224 if (pathname === "/delete-documents") {
225 const result = yield* errorTagged(
226 deleteDocuments({ documents: [{ documentId: "welcome" }] }),
227 );
228 return yield* HttpServerResponse.json(
229 "errorTag" in result ? result : { failed: (result.failedDocuments ?? []).length },
230 );
231 }
232
233 // ----------------------------------------------------------- chat
234 if (pathname === "/chat") {
235 const q = url.searchParams.get("q") ?? "What is the passphrase?";
236 const result = yield* errorTagged(chat({ userMessage: q }));
237 return yield* HttpServerResponse.json(
238 "errorTag" in result
239 ? result
240 : {
241 conversationId: result.conversationId,
242 messageId: result.systemMessageId,
243 hasMessage: typeof result.systemMessage === "string",
244 },
245 );
246 }
247
248 if (pathname === "/search") {
249 const q = url.searchParams.get("q") ?? "zanzibar passphrase";
250 const result = yield* errorTagged(
251 search({
252 queryText: q,
253 contentSource: {
254 retriever: { retrieverId: yield* retrieverId },
255 },
256 }),
257 );
258 return yield* HttpServerResponse.json(
259 "errorTag" in result ? result : { count: (result.relevantContent ?? []).length },
260 );
261 }
262
263 if (pathname === "/feedback") {
264 const conversationId = url.searchParams.get("conversationId") ?? "";
265 const messageId = url.searchParams.get("messageId") ?? "";
266 const result = yield* errorTagged(
267 feedback({
268 conversationId,
269 messageId,
270 messageUsefulness: {
271 usefulness: "USEFUL",
272 submittedAt: new Date(),
273 },
274 }),
275 );
276 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
277 }
278
279 // -------------------------------------------------- conversations
280 if (pathname === "/conversations") {
281 const result = yield* errorTagged(listConversations());
282 return yield* HttpServerResponse.json(
283 "errorTag" in result ? result : { count: (result.conversations ?? []).length },
284 );
285 }
286
287 if (pathname === "/delete-conversation") {
288 const conversationId = url.searchParams.get("conversationId") ?? "";
289 const result = yield* errorTagged(deleteConversation({ conversationId }));
290 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
291 }
292
293 if (pathname === "/messages") {
294 const conversationId = url.searchParams.get("conversationId") ?? "";
295 const result = yield* errorTagged(listMessages({ conversationId }));
296 return yield* HttpServerResponse.json(
297 "errorTag" in result ? result : { count: (result.messages ?? []).length },
298 );
299 }
300
301 if (pathname === "/attachments") {
302 const result = yield* errorTagged(listAttachments());
303 return yield* HttpServerResponse.json(
304 "errorTag" in result ? result : { count: (result.attachments ?? []).length },
305 );
306 }
307
308 if (pathname === "/delete-attachment") {
309 const result = yield* errorTagged(
310 deleteAttachment({
311 conversationId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
312 attachmentId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
313 }),
314 );
315 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
316 }
317
318 if (pathname === "/media") {
319 const result = yield* errorTagged(
320 getMedia({
321 conversationId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
322 messageId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
323 mediaId: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
324 }),
325 );
326 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
327 }
328
329 // ------------------------------------------------- admin controls
330 if (pathname === "/controls") {
331 const result = yield* errorTagged(getControls());
332 return yield* HttpServerResponse.json(
333 "errorTag" in result ? result : { responseScope: result.responseScope ?? null },
334 );
335 }
336
337 if (pathname === "/update-controls") {
338 const result = yield* errorTagged(
339 updateControls({ responseScope: "ENTERPRISE_CONTENT_ONLY" }),
340 );
341 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
342 }
343
344 if (pathname === "/delete-controls") {
345 const result = yield* errorTagged(deleteControls());
346 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
347 }
348
349 // ---------------------------------------------------------- users
350 if (pathname === "/users") {
351 // create -> get -> update -> delete round trip through the four
352 // user-store bindings (an ANONYMOUS-identity application may
353 // reject the user store with a typed error — surfaced as tags).
354 const created = yield* errorTagged(createUser({ userId: "user@example.com" }));
355 if ("errorTag" in created) {
356 return yield* HttpServerResponse.json(created);
357 }
358 const read = yield* errorTagged(getUser({ userId: "user@example.com" }));
359 const updated = yield* errorTagged(
360 updateUser({
361 userId: "user@example.com",
362 userAliasesToUpdate: [{ userId: "corp-user" }],
363 }),
364 );
365 const deleted = yield* errorTagged(deleteUser({ userId: "user@example.com" }));
366 return yield* HttpServerResponse.json({
367 aliases: "errorTag" in read ? read : (read.userAliases ?? []).length,
368 updated: !("errorTag" in updated),
369 deleted: !("errorTag" in deleted),
370 });
371 }
372
373 // --------------------------------------------------------- groups
374 if (pathname === "/groups") {
375 const put = yield* errorTagged(
376 putGroup({
377 groupName: "engineering",
378 type: "INDEX",
379 groupMembers: {
380 memberUsers: [{ userId: "user@example.com", type: "INDEX" }],
381 },
382 }),
383 );
384 if ("errorTag" in put) {
385 return yield* HttpServerResponse.json(put);
386 }
387 const read = yield* errorTagged(getGroup({ groupName: "engineering" }));
388 const listed = yield* errorTagged(listGroups({ updatedEarlierThan: new Date() }));
389 const deleted = yield* errorTagged(deleteGroup({ groupName: "engineering" }));
390 return yield* HttpServerResponse.json({
391 status: "errorTag" in read ? read.errorTag : (read.status?.status ?? null),
392 listed: "errorTag" in listed ? listed.errorTag : true,
393 deleted: !("errorTag" in deleted),
394 });
395 }
396
397 // -------------------------------------------------------- policy
398 if (pathname === "/policy") {
399 const result = yield* errorTagged(getPolicy());
400 return yield* HttpServerResponse.json(
401 "errorTag" in result ? result : { policy: result.policy ?? null },
402 );
403 }
404
405 if (pathname === "/associate-permission") {
406 const result = yield* errorTagged(
407 associatePermission({
408 statementId: "alchemy-probe",
409 actions: ["qbusiness:SearchRelevantContent"],
410 principal: "arn:aws:iam::123456789012:role/AlchemyProbeRole",
411 }),
412 );
413 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
414 }
415
416 if (pathname === "/disassociate-permission") {
417 const result = yield* errorTagged(
418 disassociatePermission({ statementId: "alchemy-probe" }),
419 );
420 return yield* HttpServerResponse.json("errorTag" in result ? result : { ok: true });
421 }
422
423 // -------------------------------------------------- subscriptions
424 if (pathname === "/subscriptions") {
425 const result = yield* errorTagged(listSubscriptions());
426 return yield* HttpServerResponse.json(
427 "errorTag" in result ? result : { count: (result.subscriptions ?? []).length },
428 );
429 }
430
431 if (pathname === "/subscription-cycle") {
432 // Expected to fail typed on an ANONYMOUS application (no Identity
433 // Center) — proves the three write bindings serialize correctly.
434 const created = yield* errorTagged(
435 createSubscription({
436 principal: { user: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee" },
437 type: "Q_LITE",
438 }),
439 );
440 const updated = yield* errorTagged(
441 updateSubscription({
442 subscriptionId: "nonexistent",
443 type: "Q_BUSINESS",
444 }),
445 );
446 const cancelled = yield* errorTagged(
447 cancelSubscription({ subscriptionId: "nonexistent" }),
448 );
449 return yield* HttpServerResponse.json({
450 created: "errorTag" in created ? created.errorTag : "ok",
451 updated: "errorTag" in updated ? updated.errorTag : "ok",
452 cancelled: "errorTag" in cancelled ? cancelled.errorTag : "ok",
453 });
454 }
455
456 // ------------------------------------------------------ sync jobs
457 if (pathname === "/sync-cycle") {
458 // CUSTOM connector flow: open a sync scope, list, close it.
459 const started = yield* errorTagged(startSync());
460 if ("errorTag" in started) {
461 return yield* HttpServerResponse.json(started);
462 }
463 const listed = yield* errorTagged(listSyncJobs());
464 const stopped = yield* errorTagged(stopSync());
465 return yield* HttpServerResponse.json({
466 executionId: started.executionId ?? null,
467 jobs: "errorTag" in listed ? listed.errorTag : (listed.history ?? []).length,
468 stopped: !("errorTag" in stopped),
469 });
470 }
471
472 // -------------------------------------------------- anonymous url
473 if (pathname === "/anonymous-url") {
474 const result = yield* errorTagged(createAnonymousUrl({ sessionDuration: "15 minutes" }));
475 return yield* HttpServerResponse.json(
476 "errorTag" in result ? result : { hasUrl: typeof result.anonymousUrl === "string" },
477 );
478 }
479
480 return yield* HttpServerResponse.json(
481 { error: "Not found", method: request.method, pathname },
482 { status: 404 },
483 );
484 }).pipe(Effect.orDie),
485 };
486 }).pipe(
487 Effect.provide(
488 Layer.mergeAll(
489 QBusiness.ChatSyncHttp,
490 QBusiness.SearchRelevantContentHttp,
491 QBusiness.PutFeedbackHttp,
492 QBusiness.GetChatControlsConfigurationHttp,
493 QBusiness.UpdateChatControlsConfigurationHttp,
494 QBusiness.DeleteChatControlsConfigurationHttp,
495 QBusiness.ListConversationsHttp,
496 QBusiness.DeleteConversationHttp,
497 QBusiness.ListMessagesHttp,
498 QBusiness.ListAttachmentsHttp,
499 QBusiness.DeleteAttachmentHttp,
500 QBusiness.GetMediaHttp,
501 QBusiness.CreateUserHttp,
502 QBusiness.GetUserHttp,
503 QBusiness.UpdateUserHttp,
504 QBusiness.DeleteUserHttp,
505 QBusiness.GetPolicyHttp,
506 QBusiness.AssociatePermissionHttp,
507 QBusiness.DisassociatePermissionHttp,
508 QBusiness.CreateSubscriptionHttp,
509 QBusiness.UpdateSubscriptionHttp,
510 QBusiness.CancelSubscriptionHttp,
511 QBusiness.ListSubscriptionsHttp,
512 QBusiness.BatchPutDocumentHttp,
513 QBusiness.BatchDeleteDocumentHttp,
514 QBusiness.ListDocumentsHttp,
515 QBusiness.GetDocumentContentHttp,
516 QBusiness.CheckDocumentAccessHttp,
517 QBusiness.PutGroupHttp,
518 QBusiness.GetGroupHttp,
519 QBusiness.DeleteGroupHttp,
520 QBusiness.ListGroupsHttp,
521 QBusiness.StartDataSourceSyncJobHttp,
522 QBusiness.StopDataSourceSyncJobHttp,
523 QBusiness.ListDataSourceSyncJobsHttp,
524 QBusiness.CreateAnonymousWebExperienceUrlHttp,
525 ),
526 ),
527 ),
528 );