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

main
ts 133 lines 5.17 KB
Raw
1 import * as Namespace from "alchemy/Namespace";
2 import * as Effect from "effect/Effect";
3 import * as Layer from "effect/Layer";
4 import { AWSEnvironment } from "../Environment.ts";
5 import type { Room } from "../IVSChat/Room.ts";
6 import {
7 RoomMessageReviewEventSource as IVSChatRoomMessageReviewEventSource,
8 type RoomMessageEvent,
9 type RoomMessageReviewEventSourceService,
10 type RoomMessageReviewHandlerFn,
11 type RoomMessageReviewProps,
12 } from "../IVSChat/RoomMessageReviewEventSource.ts";
13 import * as Lambda from "./Function.ts";
14 import { Permission as LambdaPermission } from "./Permission.ts";
15
16 /**
17 * An IVS Chat message review invocation — the PascalCase
18 * `Content`/`MessageId`/`RoomArn` envelope IVS Chat sends the handler for
19 * every `SendMessage` request.
20 */
21 export const isRoomMessageEvent = (event: any): event is RoomMessageEvent =>
22 typeof event?.Content === "string" &&
23 typeof event?.MessageId === "string" &&
24 typeof event?.RoomArn === "string";
25
26 /**
27 * Connects an IVS Chat room's message review handler to the current Lambda
28 * function.
29 *
30 * At deploy time this layer injects the function ARN into the room's
31 * `messageReviewHandler` through the room's binding contract and
32 * materializes the `lambda:InvokeFunction` Permission for
33 * `ivschat.amazonaws.com`; at runtime it dispatches review invocations
34 * (matched on `RoomArn`) to the registered handler and returns the verdict
35 * to IVS Chat.
36 * ### Reviewing room messages
37 * **Example:** Deny messages containing a banned word
38 * ```typescript
39 * yield* IVSChat.onReviewMessage(room, (event) =>
40 * Effect.succeed(
41 * event.Content.includes("banned-word")
42 * ? { ReviewResult: "DENY", Attributes: { Reason: "moderated" } }
43 * : undefined,
44 * ),
45 * );
46 * ```
47 *
48 * @binding
49 */
50 export const RoomMessageReviewEventSource = Layer.effect(
51 IVSChatRoomMessageReviewEventSource,
52 Effect.gen(function* () {
53 // this layer can only be used in a Lambda Function
54 const host = yield* Lambda.eventSourceHost("AWS.Lambda.RoomMessageReviewEventSource");
55 const Permission = yield* LambdaPermission;
56
57 return Effect.fn(function* <Req = never>(
58 room: Room,
59 handler: RoomMessageReviewHandlerFn<Req>,
60 props?: RoomMessageReviewProps,
61 ) {
62 const RoomArn = yield* room.roomArn;
63
64 // Deploy-time: inject this function's ARN into the room's
65 // messageReviewHandler (the room's provider syncs it) and create the
66 // invoke Permission for ivschat. Skipped once running inside the
67 // deployed Function (the global guard), where the only work is
68 // registering the runtime dispatcher below. Namespaced under the
69 // host for stable logical identity.
70 if (!globalThis.__ALCHEMY_RUNTIME__) {
71 yield* Namespace.push(
72 host.LogicalId,
73 Effect.gen(function* () {
74 // IVS Chat VALIDATES the invoke permission when the handler is
75 // associated (CreateRoom/UpdateRoom fails with "invalid lambda
76 // permission" otherwise), so the Permission must exist BEFORE
77 // the room and cannot reference the room's ARN (that would be
78 // circular). Scope it to this account's rooms instead — the
79 // pattern the IVS Chat resource-policy docs recommend.
80 const { accountId, region } =
81 yield* AWSEnvironment.current as unknown as Effect.Effect<{
82 accountId: string;
83 region: string;
84 }>;
85 const permission = yield* Permission(`${room.LogicalId}-MessageReview-Permission`, {
86 action: "lambda:InvokeFunction",
87 functionName: Lambda.qualifiedArnOf(host),
88 principal: "ivschat.amazonaws.com",
89 sourceAccount: accountId,
90 sourceArn: `arn:aws:ivschat:${region}:${accountId}:room/*`,
91 });
92
93 // The Permission echoes the `functionName` prop (the function
94 // ARN) as an attribute — threading it as the handler `uri`
95 // makes the room reconcile only AFTER the invoke permission
96 // exists.
97 yield* room.bind`AWS.IVSChat.RoomMessageReview(${host}, ${room})`({
98 messageReviewHandler: {
99 uri: permission.functionName,
100 fallbackResult: props?.fallbackResult,
101 },
102 });
103 }),
104 );
105 }
106
107 yield* host.listen(
108 Effect.gen(function* () {
109 const roomArn = yield* RoomArn;
110
111 return (event: any) => {
112 if (isRoomMessageEvent(event) && event.RoomArn === roomArn) {
113 // Message review is request-response: the Lambda's return
114 // value IS the verdict IVS Chat applies. `void` from the
115 // handler allows the message unchanged.
116 return handler(event).pipe(
117 Effect.map(
118 (result) =>
119 result ?? {
120 ReviewResult: "ALLOW" as const,
121 Content: event.Content,
122 Attributes: event.Attributes,
123 },
124 ),
125 Effect.orDie,
126 );
127 }
128 };
129 }),
130 );
131 }) as RoomMessageReviewEventSourceService;
132 }),
133 );