@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 76 lines 2.66 KB
Raw
1 import { HttpServer, type HttpEffect } from "alchemy/Http";
2 import * as Output from "alchemy/Output";
3 import { serveRpc } from "alchemy/Rpc";
4 import type { ProcessContext } from "alchemy/Runtime/Process";
5 import { packEnvValueKeepRedacted, unpackEnvValue } from "alchemy/RuntimeContext";
6 import * as Effect from "effect/Effect";
7 import * as Option from "effect/Option";
8
9 export const MicrovmImageTypeId = "AWS.Lambda.MicrovmImage" as const;
10
11 /**
12 * Runtime context for the in-VM process: an HTTP server (the MicroVM endpoint)
13 * that exposes the impl's `fetch` handler plus any RPC shape methods. Mirrors
14 * the Cloudflare `ContainerPlatform` process context.
15 */
16 export const makeMicrovmRuntimeContext = (id: string): ProcessContext => {
17 const runners: Effect.Effect<void, never, any>[] = [];
18 const env: Record<string, any> = {};
19
20 const serve = <Req = never>(
21 handler: HttpEffect<Req>,
22 options?: { shape?: Record<string, unknown> },
23 ) =>
24 Effect.sync(() => {
25 const finalHandler = options?.shape ? serveRpc(options.shape, handler) : handler;
26 runners.push(
27 Effect.gen(function* () {
28 const httpServer = yield* Effect.serviceOption(HttpServer).pipe(
29 Effect.map(Option.getOrUndefined),
30 );
31 if (httpServer) {
32 yield* httpServer.serve(finalHandler);
33 return yield* Effect.never;
34 }
35 }).pipe(Effect.orDie),
36 );
37 });
38
39 return {
40 Type: MicrovmImageTypeId,
41 LogicalId: id,
42 id,
43 env,
44 set: (bindingId: string, output: Output.Output) =>
45 Effect.sync(() => {
46 const key = bindingId.replaceAll(/[^a-zA-Z0-9]/g, "_");
47 // `packEnvValueKeepRedacted` keeps the Redacted wrapper on the
48 // outside so deploy-time code can route secrets while the inner
49 // marker lets the runtime `get` accessor rebuild the wrapper.
50 env[key] = output.pipe(Output.map(packEnvValueKeepRedacted));
51 return key;
52 }),
53 get: <T>(key: string) =>
54 // Read straight from `process.env` — see `unpackEnvValue` for why
55 // this must never resolve through `Config.String`.
56 Effect.sync(() => unpackEnvValue<T>(process.env[key]) as T),
57 run: ((effect: Effect.Effect<void, never, any>) =>
58 Effect.sync(() => {
59 runners.push(effect);
60 })) as unknown as ProcessContext["run"],
61 serve,
62 exports: Effect.sync(() => ({
63 default: Effect.forEach(
64 runners,
65 (eff) =>
66 Effect.forever(
67 eff.pipe(
68 Effect.tapError((err) => Effect.logError(err)),
69 Effect.ignore,
70 ),
71 ),
72 { concurrency: "unbounded" },
73 ),
74 })),
75 } as ProcessContext;
76 };