The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Context from "effect/Context"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import { FileSystem } from "effect/FileSystem"; |
| 4 | import * as Option from "effect/Option"; |
| 5 | import type { Path } from "effect/Path"; |
| 6 | import type { ChildProcessSpawner } from "effect/process/ChildProcessSpawner"; |
| 7 | import type { Stdio } from "effect/Stdio"; |
| 8 | import type { Terminal } from "effect/Terminal"; |
| 9 | import type { HttpEffect } from "../Http.ts"; |
| 10 | import * as Http from "../Http.ts"; |
| 11 | import * as Output from "../Output.ts"; |
| 12 | import { packEnvValue, unpackEnvValue, type BaseRuntimeContext } from "../RuntimeContext.ts"; |
| 13 | import { ManagedHttpShutdown } from "./ManagedHttpShutdown.ts"; |
| 14 | |
| 15 | export type ProcessServices = ChildProcessSpawner | FileSystem | Path | Stdio | Terminal; |
| 16 | |
| 17 | export interface ProcessContext extends BaseRuntimeContext { |
| 18 | run: <Req = never, RunReq = never>( |
| 19 | effect: Effect.Effect<void, never, RunReq>, |
| 20 | ) => Effect.Effect<void, never, Req | RunReq>; |
| 21 | } |
| 22 | |
| 23 | /** |
| 24 | * Long-running host loop registration (`run`). Provided by `Platform` when the |
| 25 | * execution context implements {@link ProcessContext} (i.e. carries `run`). |
| 26 | * |
| 27 | * `Platform` wires this automatically for every host runtime context that |
| 28 | * implements `run` (EC2 instances, ECS tasks, processes), so an inline program |
| 29 | * can `yield* ServerHost` and call `host.run(...)` during plan/deploy without |
| 30 | * the caller providing the layer itself. |
| 31 | */ |
| 32 | export class ServerHost extends Context.Service<ServerHost, Pick<ProcessContext, "run">>()( |
| 33 | "Alchemy::ServerHost", |
| 34 | ) {} |
| 35 | |
| 36 | /** |
| 37 | * Deploy-time / plan-time host context for platforms that bundle a long-lived |
| 38 | * program. It collects background work registered via `run` and HTTP handlers |
| 39 | * registered via `serve` into a single `exports.program` effect that the |
| 40 | * generated container/instance entrypoint runs. |
| 41 | */ |
| 42 | export interface HostRuntimeContext extends ProcessContext { |
| 43 | serve: <Req = never>( |
| 44 | handler: HttpEffect<Req> | Effect.Effect<HttpEffect<Req>>, |
| 45 | options?: { shape?: Record<string, unknown> }, |
| 46 | ) => Effect.Effect<void, never, Req>; |
| 47 | exports: Effect.Effect<{ |
| 48 | readonly program: Effect.Effect<void, never, any>; |
| 49 | }>; |
| 50 | } |
| 51 | |
| 52 | /** |
| 53 | * Build a {@link HostRuntimeContext} for a hosted platform of the given |
| 54 | * resource `type`. Both `run` (background loops) and `serve` (HTTP handlers) |
| 55 | * append to a single list of runners; `exports.program` runs them all |
| 56 | * concurrently. This is the shared host context used by `AWS.EC2.Instance` and |
| 57 | * `AWS.ECS.Task`. Managed Fly shutdown gives each runner a sequential resource |
| 58 | * scope; runner scopes close concurrently while HTTP and shared dependencies live. |
| 59 | * A shutdown signal starts an independent deadline, including for application-owned |
| 60 | * scopes. Without a signal, a nested `Effect.scoped` runner must finish its own |
| 61 | * finalizers before the host can observe completion or failure. Applications must |
| 62 | * bound that cleanup; the host cannot observe an opaque scope's earlier body exit. |
| 63 | */ |
| 64 | export const createHostRuntimeContext = |
| 65 | (type: string) => |
| 66 | (id: string): HostRuntimeContext => { |
| 67 | const runners: Effect.Effect<void, never, any>[] = []; |
| 68 | const env: Record<string, any> = {}; |
| 69 | |
| 70 | return { |
| 71 | Type: type, |
| 72 | id, |
| 73 | env, |
| 74 | set: (bindingId: string, output: Output.Output) => |
| 75 | Effect.sync(() => { |
| 76 | const key = bindingId.replaceAll(/[^a-zA-Z0-9]/g, "_"); |
| 77 | // `packEnvValue` marker-packs Redacted values so they survive the |
| 78 | // Output → env round-trip. |
| 79 | env[key] = output.pipe(Output.map(packEnvValue)); |
| 80 | return key; |
| 81 | }), |
| 82 | get: <T>(key: string) => |
| 83 | // Read straight from `process.env` — see `unpackEnvValue` for why |
| 84 | // this must never resolve through `Config.String`. |
| 85 | Effect.sync(() => unpackEnvValue<T>(process.env[key]) as T), |
| 86 | run: (effect: Effect.Effect<void, never, any>) => |
| 87 | Effect.sync(() => { |
| 88 | runners.push(effect); |
| 89 | }), |
| 90 | serve: ((handler) => |
| 91 | Effect.sync(() => { |
| 92 | // Register the HTTP handler as a runner. At container runtime the |
| 93 | // ambient `HttpServer` (if provided) serves it; `Http.serve` is a |
| 94 | // no-op when no server is bound, so this never crashes plan/deploy. |
| 95 | runners.push(Http.serve(handler as HttpEffect<any>)); |
| 96 | })) as HostRuntimeContext["serve"], |
| 97 | exports: Effect.sync(() => ({ |
| 98 | program: Effect.serviceOption(ManagedHttpShutdown).pipe( |
| 99 | Effect.flatMap((managed) => { |
| 100 | let remaining = runners.length; |
| 101 | return Effect.all( |
| 102 | Option.isSome(managed) |
| 103 | ? runners.map((runner) => |
| 104 | runner.pipe( |
| 105 | Effect.onExit((exit) => |
| 106 | Effect.sync(() => managed.value.runnerFinished(exit, --remaining === 0)), |
| 107 | ), |
| 108 | Effect.scoped, |
| 109 | // Parent interruption may discard child finalizer defects. |
| 110 | Effect.onExit((exit) => |
| 111 | Effect.sync(() => managed.value.runnerFinished(exit, false)), |
| 112 | ), |
| 113 | ), |
| 114 | ) |
| 115 | : runners, |
| 116 | { concurrency: "unbounded" }, |
| 117 | ); |
| 118 | }), |
| 119 | ), |
| 120 | })), |
| 121 | } satisfies HostRuntimeContext; |
| 122 | }; |
| 123 | |
| 124 | /** |
| 125 | * Host runtime context for container platforms (`AWS.ECS.Task`, |
| 126 | * `AWS.ECS.Service`, `Docker.Service`): extends the shared process host |
| 127 | * context so an impl shape's `run` effect is registered as a one-shot runner |
| 128 | * (the container exits when it completes) and the HTTP server only boots when |
| 129 | * the impl actually declares a `fetch` handler. |
| 130 | */ |
| 131 | export const createContainerRuntimeContext = |
| 132 | (type: string) => |
| 133 | (id: string): HostRuntimeContext => { |
| 134 | const base = createHostRuntimeContext(type)(id); |
| 135 | // Capture the host serve BEFORE Object.assign overwrites `base.serve` |
| 136 | // with the wrapper below — calling `base.serve` inside the wrapper would |
| 137 | // resolve to the wrapper itself (property lookup happens at call time) |
| 138 | // and recurse without bound the moment an impl declares `fetch`. |
| 139 | const serveBase = base.serve; |
| 140 | const serve: HostRuntimeContext["serve"] = (handler, options) => |
| 141 | Effect.gen(function* () { |
| 142 | const shape = options?.shape; |
| 143 | const run = shape?.run; |
| 144 | if (Effect.isEffect(run)) { |
| 145 | // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- `run` is a user program; the host runner surfaces its failures |
| 146 | yield* base.run(run as Effect.Effect<void, never, any>); |
| 147 | } |
| 148 | // Boot the HTTP server only for an impl that declared `fetch` — a |
| 149 | // pure one-shot `{ run }` program must exit when `run` completes |
| 150 | // rather than parking behind the 404 fallback server forever. |
| 151 | if (shape === undefined || shape.fetch !== undefined) { |
| 152 | yield* serveBase(handler, options); |
| 153 | } |
| 154 | }) as Effect.Effect<void, never, never>; |
| 155 | return Object.assign(base, { serve }); |
| 156 | }; |