@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 224 lines 7.73 KB
Raw
1 import * as IAM from "@alchemy.run/aws/IAM";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as LexV2 from "@alchemy.run/aws/LexV2";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import * as Redacted from "effect/Redacted";
9 import * as Result from "effect/Result";
10 import path from "pathe";
11
12 const main = path.resolve(import.meta.dirname, "handler.ts");
13
14 export class LexTestFunction extends Lambda.Function<Lambda.Function>()("LexTestFunction") {}
15
16 const contentOf = (content: string | Redacted.Redacted<string> | undefined): string | undefined =>
17 content === undefined
18 ? undefined
19 : typeof content === "string"
20 ? content
21 : Redacted.value(content);
22
23 /**
24 * Surface a typed failure as JSON. Only `AccessDeniedException` (fresh IAM
25 * policy propagation) maps to a retryable 502 — any other tag is terminal
26 * and returns 400 so the test fails fast with the tag visible.
27 */
28 const respond = <A, E extends { readonly _tag: string }>(
29 self: Effect.Effect<A, E>,
30 onSuccess: (a: A) => Record<string, unknown>,
31 ) =>
32 Effect.gen(function* () {
33 const result = yield* Effect.result(self);
34 if (Result.isFailure(result)) {
35 return yield* HttpServerResponse.json(
36 {
37 error: result.failure._tag,
38 message: String((result.failure as { message?: string }).message ?? ""),
39 },
40 {
41 status: result.failure._tag === "AccessDeniedException" ? 502 : 400,
42 },
43 );
44 }
45 return yield* HttpServerResponse.json(onSuccess(result.success));
46 });
47
48 export default LexTestFunction.make(
49 {
50 main,
51 functionUrl: true,
52 timeout: Duration.seconds(30),
53 },
54 Effect.gen(function* () {
55 // The whole Lex chain: role -> bot -> DRAFT locale -> intents -> built
56 // version -> alias. BotVersion builds the locale before snapshotting.
57 const role = yield* IAM.Role("LexBotRole", {
58 assumeRolePolicyDocument: {
59 Version: "2012-10-17",
60 Statement: [
61 {
62 Effect: "Allow",
63 Principal: { Service: "lexv2.amazonaws.com" },
64 Action: ["sts:AssumeRole"],
65 },
66 ],
67 },
68 });
69 const bot = yield* LexV2.Bot("E2EBot", {
70 roleArn: role.roleArn,
71 description: "alchemy lex recognize-text e2e bot",
72 });
73 const locale = yield* LexV2.BotLocale("En", {
74 botId: bot.botId,
75 localeId: "en_US",
76 });
77 const greet = yield* LexV2.Intent("Greet", {
78 botId: locale.botId,
79 localeId: locale.localeId,
80 intentName: "Greet",
81 sampleUtterances: ["hello", "hi", "hey there"],
82 });
83 // Slotless intent fulfilled by this function's code hook.
84 const order = yield* LexV2.Intent("Order", {
85 botId: greet.botId,
86 localeId: greet.localeId,
87 intentName: "OrderPizza",
88 sampleUtterances: ["order a pizza", "I want to order a pizza"],
89 fulfillmentCodeHook: true,
90 });
91 const version = yield* LexV2.BotVersion("V1", {
92 botId: order.botId,
93 localeIds: [order.localeId],
94 });
95 const alias = yield* LexV2.BotAlias("Live", {
96 botId: version.botId,
97 botVersion: version.botVersion,
98 });
99
100 const recognizeText = yield* LexV2.RecognizeText(alias);
101 const recognizeUtterance = yield* LexV2.RecognizeUtterance(alias);
102 const getSession = yield* LexV2.GetSession(alias);
103 const putSession = yield* LexV2.PutSession(alias);
104 const deleteSession = yield* LexV2.DeleteSession(alias);
105
106 // Fulfillment code hook: Lex invokes this same function while
107 // /recognize awaits the RecognizeText response.
108 yield* LexV2.onCodeHook(alias, { localeId: "en_US" }, (event) =>
109 Effect.succeed(
110 LexV2.fulfillIntent(event, {
111 message: `Order placed for ${event.sessionId}!`,
112 }),
113 ),
114 );
115
116 return {
117 fetch: Effect.gen(function* () {
118 const request = yield* HttpServerRequest;
119 const url = new URL(request.originalUrl);
120 const sessionId = url.searchParams.get("sessionId") ?? "missing";
121
122 if (request.method === "POST" && url.pathname === "/recognize") {
123 const body = (yield* request.json) as unknown as {
124 text: string;
125 sessionId: string;
126 };
127 return yield* respond(
128 recognizeText({
129 localeId: "en_US",
130 sessionId: body.sessionId,
131 text: body.text,
132 }),
133 (reply) => ({
134 intent: reply.sessionState?.intent?.name ?? null,
135 state: reply.sessionState?.intent?.state ?? null,
136 messages: (reply.messages ?? []).map((message) => contentOf(message.content)),
137 interpretations: (reply.interpretations ?? []).map(
138 (interpretation) => interpretation.intent?.name,
139 ),
140 }),
141 );
142 }
143
144 if (request.method === "POST" && url.pathname === "/utterance") {
145 const body = (yield* request.json) as unknown as {
146 text: string;
147 sessionId: string;
148 };
149 return yield* respond(
150 recognizeUtterance({
151 localeId: "en_US",
152 sessionId: body.sessionId,
153 requestContentType: "text/plain; charset=utf-8",
154 // Default is speech — the test locale has no voice configured.
155 responseContentType: "text/plain; charset=utf-8",
156 inputStream: new TextEncoder().encode(body.text),
157 }),
158 (reply) => ({
159 contentType: reply.contentType ?? null,
160 sessionId: reply.sessionId ?? null,
161 }),
162 );
163 }
164
165 if (request.method === "POST" && url.pathname === "/session") {
166 const body = (yield* request.json) as unknown as {
167 sessionId: string;
168 attributes: Record<string, string>;
169 };
170 return yield* respond(
171 putSession({
172 localeId: "en_US",
173 sessionId: body.sessionId,
174 sessionState: {
175 dialogAction: { type: "ElicitIntent" },
176 sessionAttributes: body.attributes,
177 },
178 // ElicitIntent requires a message to relay to the user.
179 messages: [{ contentType: "PlainText", content: "How can I help?" }],
180 // Default is speech — the test locale has no voice configured.
181 responseContentType: "text/plain; charset=utf-8",
182 }),
183 (reply) => ({ sessionId: reply.sessionId ?? null }),
184 );
185 }
186
187 if (request.method === "GET" && url.pathname === "/session") {
188 return yield* respond(getSession({ localeId: "en_US", sessionId }), (reply) => ({
189 sessionId: reply.sessionId ?? null,
190 attributes: reply.sessionState?.sessionAttributes ?? {},
191 }));
192 }
193
194 if (request.method === "DELETE" && url.pathname === "/session") {
195 return yield* respond(deleteSession({ localeId: "en_US", sessionId }), (reply) => ({
196 sessionId: reply.sessionId ?? null,
197 }));
198 }
199
200 if (request.method === "GET" && url.pathname === "/health") {
201 return yield* HttpServerResponse.json({ ok: true });
202 }
203
204 return yield* HttpServerResponse.json(
205 {
206 error: "Not found",
207 method: request.method,
208 pathname: url.pathname,
209 },
210 { status: 404 },
211 );
212 }).pipe(Effect.orDie),
213 };
214 }).pipe(
215 Effect.provide([
216 LexV2.RecognizeTextHttp,
217 LexV2.RecognizeUtteranceHttp,
218 LexV2.GetSessionHttp,
219 LexV2.PutSessionHttp,
220 LexV2.DeleteSessionHttp,
221 LexV2.LambdaCodeHookEventSource,
222 ]),
223 ),
224 );