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

main
ts 181 lines 7.57 KB
Raw
1 import { fileURLToPath } from "node:url";
2 /**
3 * `AWS.Lambda.MicrovmImage` under `alchemy dev`: the dev provider builds the
4 * image with a plain HOST-side `docker build` (BuildKit layer cache against
5 * the user's real sources) and hands the emulator a pre-built
6 * `docker://<tag>` artifact, which the alchemy floci fork runs as-is —
7 * nothing is zipped, uploaded, or built inside the emulator.
8 *
9 * Proof structure:
10 * - deploy an effectful image: attrs carry the dummy account AND a
11 * `docker://alchemy-dev/microvm-…` artifact uri — the live cloud can
12 * never mint either, and the uri is proof the host-build path ran;
13 * - `RunMicrovm` out-of-band reaches RUNNING — the emulator actually
14 * BOOTED a VM from the host-built reference (an invalid or unbuilt ref
15 * fails the run);
16 * - re-deploy with NO change: a true noop (dev diff policy — content is
17 * the watch loop's job, and nothing changed);
18 * - rewrite the program's marker in the clone WITHOUT a deploy: the
19 * sidecar watch loop rebuilds (docker layer cache — only the COPY layer
20 * re-runs) and re-reconciles; the emulator's `latestActiveImageVersion`
21 * advances within seconds, and a fresh `RunMicrovm` boots the new
22 * version;
23 * - destroy removes the image from the emulator.
24 *
25 * Requires Docker (floci runs as a container, MicroVMs run as containers);
26 * skipped when the daemon is unavailable.
27 */
28 import * as AWS from "@alchemy.run/aws";
29 import * as Endpoint from "@alchemy.run/aws/Endpoint";
30 import * as Region from "@alchemy.run/aws/Region";
31 import { expect } from "@alchemy.run/test";
32 import * as Test from "@alchemy.run/test/Alchemy";
33 import { Credentials } from "@distilled.cloud/aws/Credentials";
34 import * as microvms from "@distilled.cloud/aws/lambda-microvms";
35 import type { RegionName } from "@distilled.cloud/aws/Region";
36 import * as Effect from "effect/Effect";
37 import * as FileSystem from "effect/FileSystem";
38 import * as Layer from "effect/Layer";
39 import * as Path from "effect/Path";
40 import * as Redacted from "effect/Redacted";
41 import * as Schedule from "effect/Schedule";
42 import { cloneFixture } from "../../Cloudflare/Utils/Fixture.ts";
43 import { FLOCI_ENDPOINT } from "../Local/fixtures/raw.ts";
44
45 const { test } = Test.make({ providers: AWS.providers(), dev: true });
46
47 const fixtureDir = fileURLToPath(new URL("../Lambda/fixtures/microvm-dev", import.meta.url));
48
49 /** Floci-scoped context for the raw distilled calls the test makes itself. */
50 const flociContext = Layer.mergeAll(
51 Endpoint.of(FLOCI_ENDPOINT),
52 Region.of("us-east-1"),
53 Layer.succeed(
54 Credentials,
55 Effect.succeed({
56 accessKeyId: Redacted.make("test"),
57 secretAccessKey: Redacted.make("test"),
58 sessionToken: undefined,
59 region: "us-east-1" as RegionName,
60 }),
61 ),
62 );
63
64 /** Boot a VM from the image and prove it reaches RUNNING, then clean up. */
65 const bootsToRunning = (imageArn: string, imageVersion?: string) =>
66 Effect.gen(function* () {
67 const vm = yield* microvms.runMicrovm({
68 imageIdentifier: imageArn,
69 ...(imageVersion !== undefined ? { imageVersion } : {}),
70 });
71 const state = yield* microvms.getMicrovm({ microvmIdentifier: vm.microvmId }).pipe(
72 Effect.map((m) => m.state),
73 Effect.repeat({
74 schedule: Schedule.spaced("1 second"),
75 until: (s): boolean => s !== "PENDING",
76 times: 60,
77 }),
78 Effect.ensuring(
79 microvms.terminateMicrovm({ microvmIdentifier: vm.microvmId }).pipe(Effect.ignore),
80 ),
81 );
82 return { state, imageVersion: vm.imageVersion };
83 }).pipe(Effect.provide(flociContext));
84
85 test.provider(
86 "dev builds the image host-side (docker://), boots it, and a content edit hot-rebuilds it within seconds",
87 (stack) =>
88 Effect.gen(function* () {
89 const fs = yield* FileSystem.FileSystem;
90 const path = yield* Path.Path;
91
92 yield* stack.destroy();
93
94 const clone = yield* cloneFixture(fixtureDir, {
95 prefix: "floci-dev-microvm-",
96 });
97 const mainPath = path.join(clone, "program.ts");
98
99 const declaration = Effect.gen(function* () {
100 const buildRole = yield* AWS.IAM.Role("DevMicrovmBuildRole");
101 return yield* AWS.Lambda.MicrovmImage("DevMicrovm", {
102 main: mainPath,
103 buildRole,
104 runtime: "bun",
105 resources: [{ minimumMemoryInMiB: 512 }],
106 cpuConfigurations: [{ architecture: "ARM_64" }],
107 });
108 });
109
110 const first = yield* stack.deploy(declaration);
111 // Emulator identity: the live cloud never mints the dummy account.
112 expect(first.imageArn).toContain(":000000000000:");
113 // The host-build path: a pre-built local docker reference, not an
114 // uploaded-zip S3 uri.
115 expect(first.codeArtifact?.uri).toMatch(/^docker:\/\/alchemy-dev\/microvm-/);
116 expect(first.codeArtifact?.hash).toBeDefined();
117 const v1 = first.latestActiveImageVersion;
118 expect(v1).toBeDefined();
119
120 // The emulator can BOOT the host-built reference: RunMicrovm reaches
121 // RUNNING (a missing or broken image ref fails the run).
122 const booted = yield* bootsToRunning(first.imageArn);
123 expect(booted.state).toBe("RUNNING");
124 expect(booted.imageVersion).toBe(v1);
125
126 // Same declaration, same source — a true noop: nothing is rebuilt.
127 const unchanged = yield* stack.deploy(declaration);
128 expect(unchanged.codeArtifact?.hash).toBe(first.codeArtifact!.hash);
129 expect(unchanged.latestActiveImageVersion).toBe(v1);
130
131 // Content-only edit, NO deploy: the sidecar watch loop rebuilds
132 // (cached docker build) and re-reconciles; the emulator's active
133 // version advances. This is the latency the whole design exists for.
134 const source = yield* fs.readFileString(mainPath);
135 const editStartedAt = Date.now();
136 yield* fs.writeFileString(
137 mainPath,
138 source.replace(`"microvm-marker-v1"`, `"microvm-marker-v2"`),
139 );
140 const rebuilt = yield* microvms.getMicrovmImage({ imageIdentifier: first.imageArn }).pipe(
141 Effect.provide(flociContext),
142 Effect.repeat({
143 schedule: Schedule.spaced("500 millis"),
144 until: (image): boolean =>
145 image.latestActiveImageVersion !== undefined && image.latestActiveImageVersion !== v1,
146 times: 120,
147 }),
148 );
149 const rebuildMs = Date.now() - editStartedAt;
150 // eslint-disable-next-line no-console
151 console.log(`microvm content edit -> new active version in ${rebuildMs}ms`);
152 expect(rebuilt.latestActiveImageVersion).not.toBe(v1);
153 // The point of the docker:// path: a content edit is a cached docker
154 // build, not a zip-upload-extract-rebuild. Well under a minute even
155 // on a cold-ish daemon; typically a few seconds.
156 expect(rebuildMs).toBeLessThan(30_000);
157
158 // A fresh VM boots the NEW active version.
159 const rebooted = yield* bootsToRunning(first.imageArn);
160 expect(rebooted.state).toBe("RUNNING");
161 expect(rebooted.imageVersion).toBe(rebuilt.latestActiveImageVersion);
162
163 // Destroy: the image must be gone from the emulator.
164 yield* stack.destroy();
165 const gone = yield* microvms.getMicrovmImage({ imageIdentifier: first.imageArn }).pipe(
166 Effect.map(() => false),
167 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(true)),
168 Effect.provide(flociContext),
169 Effect.repeat({
170 schedule: Schedule.spaced("1 second"),
171 until: (isGone): boolean => isGone,
172 times: 20,
173 }),
174 );
175 expect(gone).toBe(true);
176 }),
177 {
178 tags: ["provider:aws", "provider:aws:iam", "provider:aws:lambda", "local"],
179 timeout: 600_000,
180 },
181 );