The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as http from "node:http"; |
| 2 | import * as https from "node:https"; |
| 3 | import * as Fly from "@alchemy.run/fly"; |
| 4 | import * as Effect from "effect/Effect"; |
| 5 | import * as HttpClient from "effect/http/HttpClient"; |
| 6 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 7 | import * as Layer from "effect/Layer"; |
| 8 | |
| 9 | export interface TransportEvent { |
| 10 | sequence: number; |
| 11 | stage: "request" | "completed" | "forwarded" | "dropped" | "cut" | "held" | "upstream-error"; |
| 12 | method: string; |
| 13 | path: string; |
| 14 | machineId?: string; |
| 15 | name?: string; |
| 16 | phase?: string; |
| 17 | status?: number; |
| 18 | image?: string; |
| 19 | digest?: string; |
| 20 | instanceId?: string; |
| 21 | state?: string; |
| 22 | cordoned?: boolean; |
| 23 | minSecretsVersion?: number; |
| 24 | secretsVersion?: number; |
| 25 | checks?: { name?: string; status?: string }[]; |
| 26 | } |
| 27 | |
| 28 | export interface FaultRule { |
| 29 | match: (event: TransportEvent) => boolean; |
| 30 | action: "drop-response" | "cut-request" | "hold-response"; |
| 31 | remaining: number; |
| 32 | } |
| 33 | |
| 34 | /** No bodies, authorization headers, secret values, or lease nonces enter the journal. */ |
| 35 | export const transportProxy = (upstream = "https://api.machines.dev") => |
| 36 | Effect.acquireRelease( |
| 37 | Effect.callback< |
| 38 | { |
| 39 | url: string; |
| 40 | events: TransportEvent[]; |
| 41 | arm: (rule: FaultRule) => void; |
| 42 | clear: () => void; |
| 43 | release: () => void; |
| 44 | dropHeld: () => void; |
| 45 | wait: (match: (event: TransportEvent) => boolean) => Effect.Effect<TransportEvent, Error>; |
| 46 | close: () => void; |
| 47 | }, |
| 48 | Error |
| 49 | >((resume) => { |
| 50 | const origin = new URL(upstream); |
| 51 | if (origin.protocol !== "https:") { |
| 52 | resume(Effect.fail(new Error("The fault proxy requires a real HTTPS upstream"))); |
| 53 | return; |
| 54 | } |
| 55 | const events: TransportEvent[] = []; |
| 56 | const listeners = new Set<(event: TransportEvent) => void>(); |
| 57 | const pending = new Set<http.ClientRequest>(); |
| 58 | const held = new Map<() => void, () => void>(); |
| 59 | const rules: FaultRule[] = []; |
| 60 | let sequence = 0; |
| 61 | const record = (event: TransportEvent) => { |
| 62 | events.push(event); |
| 63 | for (const listener of listeners) listener(event); |
| 64 | }; |
| 65 | const server = http.createServer((incoming, outgoing) => { |
| 66 | const chunks: Buffer[] = []; |
| 67 | incoming.on("data", (chunk: Buffer) => chunks.push(chunk)); |
| 68 | incoming.on("error", () => outgoing.destroy()); |
| 69 | incoming.on("end", () => { |
| 70 | const body = Buffer.concat(chunks); |
| 71 | const path = new URL(incoming.url!, origin).pathname; |
| 72 | const event: TransportEvent = { |
| 73 | sequence: ++sequence, |
| 74 | stage: "request", |
| 75 | method: incoming.method!, |
| 76 | path, |
| 77 | machineId: path.match(/\/machines\/([^/]+)/)?.[1], |
| 78 | }; |
| 79 | // Only allowlisted identity/phase fields survive request inspection. |
| 80 | if (body.length && incoming.headers["content-type"]?.includes("json")) { |
| 81 | try { |
| 82 | const value = JSON.parse(body.toString()); |
| 83 | if (typeof value.name === "string") event.name = value.name; |
| 84 | if (typeof value.config?.image === "string") event.image = value.config.image; |
| 85 | if (typeof value.min_secrets_version === "number") |
| 86 | event.minSecretsVersion = value.min_secrets_version; |
| 87 | const phase = |
| 88 | value.metadata?.["alchemy.phase"] ?? value.config?.metadata?.["alchemy.phase"]; |
| 89 | if (typeof phase === "string") event.phase = phase; |
| 90 | } catch { |
| 91 | // Forward malformed payloads unchanged; the real API decides their validity. |
| 92 | } |
| 93 | } |
| 94 | record(event); |
| 95 | const rule = rules.find((rule) => rule.remaining > 0 && rule.match(event)); |
| 96 | if (rule) rule.remaining--; |
| 97 | if (rule?.action === "cut-request") { |
| 98 | record({ ...event, stage: "cut" }); |
| 99 | incoming.socket.destroy(); |
| 100 | return; |
| 101 | } |
| 102 | const request = https.request( |
| 103 | new URL(incoming.url!, origin), |
| 104 | { |
| 105 | method: incoming.method, |
| 106 | headers: { |
| 107 | ...incoming.headers, |
| 108 | host: origin.host, |
| 109 | connection: "close", |
| 110 | "accept-encoding": "identity", |
| 111 | }, |
| 112 | }, |
| 113 | (response) => { |
| 114 | const parts: Buffer[] = []; |
| 115 | response.on("data", (chunk: Buffer) => parts.push(chunk)); |
| 116 | response.on("error", () => outgoing.destroy()); |
| 117 | response.on("end", () => { |
| 118 | pending.delete(request); |
| 119 | const bytes = Buffer.concat(parts); |
| 120 | const completed: TransportEvent = { |
| 121 | ...event, |
| 122 | status: response.statusCode, |
| 123 | }; |
| 124 | if (response.statusCode! >= 200 && response.statusCode! < 300) { |
| 125 | try { |
| 126 | const value = JSON.parse(bytes.toString()); |
| 127 | if (/\/machines(?:\/[^/]+)?$/.test(path) && !Array.isArray(value)) { |
| 128 | if (typeof value.id === "string") completed.machineId = value.id; |
| 129 | if (typeof value.instance_id === "string") |
| 130 | completed.instanceId = value.instance_id; |
| 131 | if (typeof value.image_ref?.digest === "string") |
| 132 | completed.digest = value.image_ref.digest; |
| 133 | if (typeof value.state === "string") completed.state = value.state; |
| 134 | if (typeof value.cordoned === "boolean") completed.cordoned = value.cordoned; |
| 135 | if (Array.isArray(value.checks)) { |
| 136 | completed.checks = value.checks.map( |
| 137 | (check: { name?: string; status?: string }) => ({ |
| 138 | name: typeof check.name === "string" ? check.name : undefined, |
| 139 | status: typeof check.status === "string" ? check.status : undefined, |
| 140 | }), |
| 141 | ); |
| 142 | } |
| 143 | } |
| 144 | if (/\/secrets(?:\/[^/]+)?$/.test(path)) { |
| 145 | const version = value.version ?? value.Version; |
| 146 | if (typeof version === "number") completed.secretsVersion = version; |
| 147 | } |
| 148 | } catch { |
| 149 | // Response bytes are never altered to accommodate the observer. |
| 150 | } |
| 151 | } |
| 152 | record({ ...completed, stage: "completed" }); |
| 153 | const forward = () => { |
| 154 | const headers = { ...response.headers }; |
| 155 | delete headers["transfer-encoding"]; |
| 156 | delete headers.connection; |
| 157 | headers["content-length"] = String(bytes.length); |
| 158 | outgoing.writeHead(response.statusCode!, headers); |
| 159 | outgoing.end(bytes); |
| 160 | record({ ...completed, stage: "forwarded" }); |
| 161 | }; |
| 162 | if (rule?.action === "drop-response") { |
| 163 | record({ ...completed, stage: "dropped" }); |
| 164 | incoming.socket.destroy(); |
| 165 | } else if (rule?.action === "hold-response") { |
| 166 | held.set(forward, () => { |
| 167 | record({ ...completed, stage: "dropped" }); |
| 168 | incoming.socket.destroy(); |
| 169 | }); |
| 170 | record({ ...completed, stage: "held" }); |
| 171 | } else forward(); |
| 172 | }); |
| 173 | }, |
| 174 | ); |
| 175 | pending.add(request); |
| 176 | request.setTimeout(90_000, () => request.destroy()); |
| 177 | request.on("error", () => { |
| 178 | pending.delete(request); |
| 179 | record({ ...event, stage: "upstream-error" }); |
| 180 | incoming.socket.destroy(); |
| 181 | }); |
| 182 | request.end(body); |
| 183 | }); |
| 184 | }); |
| 185 | const close = () => { |
| 186 | rules.length = 0; |
| 187 | held.clear(); |
| 188 | for (const request of pending) request.destroy(); |
| 189 | server.closeAllConnections(); |
| 190 | server.close(); |
| 191 | }; |
| 192 | server.on("error", (error) => resume(Effect.fail(error))); |
| 193 | server.listen(0, "127.0.0.1", () => { |
| 194 | const address = server.address(); |
| 195 | if (!address || typeof address === "string") { |
| 196 | resume(Effect.fail(new Error("Missing proxy listen address"))); |
| 197 | return; |
| 198 | } |
| 199 | resume( |
| 200 | Effect.succeed({ |
| 201 | url: `http://127.0.0.1:${address.port}`, |
| 202 | events, |
| 203 | arm: (rule) => rules.push({ ...rule }), |
| 204 | clear: () => { |
| 205 | rules.length = 0; |
| 206 | }, |
| 207 | release: () => { |
| 208 | for (const forward of held.keys()) forward(); |
| 209 | held.clear(); |
| 210 | }, |
| 211 | dropHeld: () => { |
| 212 | for (const drop of held.values()) drop(); |
| 213 | held.clear(); |
| 214 | }, |
| 215 | wait: (match) => |
| 216 | Effect.callback<TransportEvent>((resume) => { |
| 217 | const found = events.find(match); |
| 218 | if (found) { |
| 219 | resume(Effect.succeed(found)); |
| 220 | return; |
| 221 | } |
| 222 | const listener = (event: TransportEvent) => { |
| 223 | if (match(event)) { |
| 224 | listeners.delete(listener); |
| 225 | resume(Effect.succeed(event)); |
| 226 | } |
| 227 | }; |
| 228 | listeners.add(listener); |
| 229 | return Effect.sync(() => listeners.delete(listener)); |
| 230 | }).pipe( |
| 231 | Effect.timeout("120 seconds"), |
| 232 | Effect.mapError( |
| 233 | () => new Error("Real API operation barrier was not reached within 120 seconds"), |
| 234 | ), |
| 235 | ), |
| 236 | close, |
| 237 | }), |
| 238 | ); |
| 239 | }); |
| 240 | return Effect.sync(close); |
| 241 | }), |
| 242 | (proxy) => |
| 243 | Effect.forEach( |
| 244 | Array.from({ length: Math.ceil(proxy.events.length / 50) }, (_, index) => index), |
| 245 | (index) => |
| 246 | Effect.logInfo("Fly transport journal", { |
| 247 | endpoint: proxy.url, |
| 248 | offset: index * 50, |
| 249 | events: proxy.events.slice(index * 50, (index + 1) * 50), |
| 250 | }), |
| 251 | { discard: true }, |
| 252 | ).pipe(Effect.andThen(Effect.sync(proxy.close))), |
| 253 | ); |
| 254 | |
| 255 | /** Adapt only transport routing; the original SDK, provider and real state remain intact. */ |
| 256 | export const throughProxy = (endpoint: () => string | undefined) => |
| 257 | Layer.effect( |
| 258 | HttpClient.HttpClient, |
| 259 | Effect.gen(function* () { |
| 260 | const client = yield* HttpClient.HttpClient; |
| 261 | return HttpClient.mapRequest(client, (request) => { |
| 262 | const url = endpoint(); |
| 263 | return url && request.url.startsWith("https://api.machines.dev/") |
| 264 | ? HttpClientRequest.setUrl(request, request.url.replace("https://api.machines.dev", url)) |
| 265 | : request; |
| 266 | }); |
| 267 | }), |
| 268 | ).pipe(Layer.provideMerge(Fly.providers())); |