@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, 04:45 UTC

main
ts 107 lines 4.01 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import * as Effect from "effect/Effect";
3 import { HttpServerRequest } from "effect/http/HttpServerRequest";
4 import * as HttpServerResponse from "effect/http/HttpServerResponse";
5 import * as ChildProcess from "effect/process/ChildProcess";
6 import { ChildProcessSpawner } from "effect/process/ChildProcessSpawner";
7 import * as Stream from "effect/Stream";
8
9 /**
10 * The trailer the in-VM server appends after a command's output so the
11 * Durable Object can learn the exit code without it leaking into the
12 * terminal: `\n__EXIT__:<code>\n`.
13 */
14 const EXIT_MARKER = "__EXIT__:";
15
16 const encoder = new TextEncoder();
17
18 /**
19 * The build role is created bare; the image grants it the trust + build
20 * permissions it needs through a binding.
21 */
22 export const ShellBuildRole = AWS.IAM.Role("ShellMicrovmBuildRole");
23
24 /**
25 * The shell MicroVM image — an **effectful** image: this module is both the
26 * image declaration and the in-VM server. The Effect program below is
27 * bundled into the image (bun runtime) and served by the alchemy MicroVM
28 * bootstrap; there is no Dockerfile and no hand-rolled HTTP server.
29 *
30 * `POST /exec { "command": "<sh command>" }` → a chunked text/plain response
31 * streaming the command's interleaved stdout+stderr as it is produced,
32 * terminated by the `__EXIT__` trailer. The MicroVM auth token is enforced
33 * by the endpoint proxy in front of this server, so the server itself
34 * trusts every request it receives.
35 */
36 export class ShellMicrovm extends AWS.Lambda.MicrovmImage<ShellMicrovm>()("ShellMicrovm") {}
37
38 export default ShellMicrovm.make(
39 ShellBuildRole.pipe(
40 Effect.map((buildRole) => ({
41 main: import.meta.filename,
42 buildRole,
43 runtime: "bun" as const,
44 resources: [{ minimumMemoryInMiB: 512 }],
45 cpuConfigurations: [{ architecture: "ARM_64" }],
46 })),
47 ),
48 Effect.gen(function* () {
49 return {
50 fetch: Effect.gen(function* () {
51 const request = yield* HttpServerRequest;
52 const url = new URL(request.url, "http://microvm");
53
54 if (url.pathname === "/health") {
55 return HttpServerResponse.text("ok");
56 }
57
58 if (request.method === "POST" && url.pathname === "/exec") {
59 const body = (yield* request.json.pipe(Effect.orElseSucceed(() => undefined))) as
60 | { command?: unknown }
61 | undefined;
62 const command = typeof body?.command === "string" ? body.command : "";
63 if (!command.trim()) {
64 return HttpServerResponse.text("empty command", { status: 400 });
65 }
66
67 const spawner = yield* ChildProcessSpawner;
68 // The spawned handle is scoped; `Stream.unwrap` folds that scope
69 // into the stream's lifetime, so the process is reaped exactly when
70 // the response stream completes (or the client goes away).
71 const output = Stream.unwrap(
72 spawner
73 .spawn(ChildProcess.make("sh", ["-c", command], { shell: false }))
74 .pipe(
75 Effect.map((handle) =>
76 Stream.merge(handle.stdout, handle.stderr).pipe(
77 Stream.concat(
78 Stream.fromEffect(
79 handle.exitCode.pipe(
80 Effect.map((code) => encoder.encode(`\n${EXIT_MARKER}${code}\n`)),
81 ),
82 ),
83 ),
84 ),
85 ),
86 ),
87 ).pipe(
88 // Spawn/pipe failures still terminate the protocol: report them
89 // as a non-zero exit with the error as output.
90 Stream.catchCause((cause) =>
91 Stream.make(encoder.encode(`\n${EXIT_MARKER}1\n${String(cause)}\n`)),
92 ),
93 );
94
95 return HttpServerResponse.stream(output, {
96 contentType: "text/plain; charset=utf-8",
97 headers: { "cache-control": "no-store" },
98 });
99 }
100
101 return HttpServerResponse.text("shell microvm: POST /exec", {
102 status: 404,
103 });
104 }),
105 };
106 }),
107 );