| 1 | import * as Effect from "effect/Effect"; |
| 2 | import * as Layer from "effect/Layer"; |
| 3 | import * as S from "effect/Schema"; |
| 4 | import { HttpClientRequest } from "effect/http"; |
| 5 | |
| 6 | import * as AI from "alchemy/AI"; |
| 7 | import * as Cloudflare from "alchemy/Cloudflare"; |
| 8 | import { dedent } from "alchemy/Util"; |
| 9 | |
| 10 | export const code = AI.Parameter("code")(S.String)` |
| 11 | The JavaScript code to evaluate. |
| 12 | Must be a valid module with a default export function accepting no arguments. |
| 13 | Can return any value, including a Promise.`; |
| 14 | |
| 15 | export class Eval extends (AI.Tool<Eval>()("eval")` |
| 16 | Evaluate JavaScript ${code}`) {} |
| 17 | |
| 18 | export 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 | ); |