1import * as Effect from "effect/Effect";
2import * as Layer from "effect/Layer";
3import * as S from "effect/Schema";
4import { HttpClientRequest } from "effect/http";
5
6import * as AI from "alchemy/AI";
7import * as Cloudflare from "alchemy/Cloudflare";
8import { dedent } from "alchemy/Util";
9
10export const code = AI.Parameter("code")(S.String)`
11The JavaScript code to evaluate.
12Must be a valid module with a default export function accepting no arguments.
13Can return any value, including a Promise.`;
14
15export class Eval extends (AI.Tool<Eval>()("eval")`
16Evaluate JavaScript ${code}`) {}
17
18export const EvalLive = Layer.effect(
19 Eval,
20 Effect.gen(function* () {
21 const vm = yield* Cloudflare.WorkerLoader("Eval");
22
23 return ({ code }) =>
24 vm
25 .load({
26 mainModule: "index.js",
27 compatibilityDate: "2026-08-31",
28 modules: {
29 "code.js": code,
30 "index.js": dedent`
31 import util from "node:util";
32 import code from "./code.js";
33 const lines: string[] = [];
34 console.log = (...args) => lines.push(util.formatWithOptions({ depth: null }, ...args));
35 export default {
36 fetch: async () => {
37 const output = await code();
38 return Response(lines.join("\\n") + "\\n" + util.inspect(output, { depth: null }));
39 }
40 }`,
41 },
42 })
43 .pipe(
44 Effect.flatMap((worker) =>
45 worker.fetch(HttpClientRequest.get("https://worker/")),
46 ),
47 Effect.flatMap((response) => response.text),
48 Effect.catch((e) =>
49 Effect.succeed({
50 error: e,
51 }),
52 ),
53 );
54 }),
55);