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

main
ts 163 lines 5.34 KB
Raw
1 import * as Binding from "alchemy/Binding";
2 import type { Rpc } from "alchemy/Rpc";
3 import { unpackEnvValue } from "alchemy/RuntimeContext";
4 import { isYieldableEffectLike } from "alchemy/Util/effect";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import { isRailwayHost } from "./MountVolume.ts";
8 import {
9 DEFAULT_RPC_PORT,
10 RPC_ERROR_TAG,
11 RPC_PATH_PREFIX,
12 RPC_TOKEN_HEADER,
13 rpcEnvKeys,
14 } from "./rpc-token.ts";
15
16 export class RpcCallError extends Data.TaggedError("Railway.RpcCallError")<{
17 readonly method: string;
18 readonly cause: unknown;
19 }> {}
20
21 export class RpcUnauthorized extends Data.TaggedError("Railway.RpcUnauthorized")<{
22 readonly method: string;
23 }> {}
24
25 const fromProcessEnv = (key: string): string => {
26 const unpacked = unpackEnvValue<unknown>(process.env[key]);
27 if (typeof unpacked === "string") return unpacked;
28 return "";
29 };
30
31 type RpcTarget = {
32 readonly Type: string;
33 readonly LogicalId: string;
34 readonly dnsName?: unknown;
35 readonly port?: unknown;
36 readonly rpcToken?: unknown;
37 };
38
39 const resolveTarget = <Shape, Req>(
40 targetEff: (RpcTarget & Rpc<Shape>) | Effect.Effect<RpcTarget & Rpc<Shape>, never, Req>,
41 ): Effect.Effect<RpcTarget & Rpc<Shape>, never, Req> =>
42 isYieldableEffectLike(targetEff)
43 ? (targetEff as Effect.Effect<RpcTarget & Rpc<Shape>, never, Req>)
44 : Effect.succeed(targetEff as RpcTarget & Rpc<Shape>);
45
46 /** Logical id without yielding the Resource (runtime has no engine). */
47 const logicalIdOf = (target: unknown): string => {
48 if (target !== null && typeof target === "object" && "LogicalId" in target) {
49 const id = (target as { LogicalId?: unknown }).LogicalId;
50 if (typeof id === "string" && id.length > 0) return id;
51 }
52 if (typeof target === "function") {
53 const named = (target as { name?: unknown }).name;
54 if (typeof named === "string" && named.length > 0) return named;
55 }
56 return "";
57 };
58
59 const makeStub = <Shape>(options: { readonly baseUrl: string; readonly token: string }): Shape => {
60 const { baseUrl, token } = options;
61 return new Proxy(
62 {},
63 {
64 get: (_obj, prop) => {
65 if (typeof prop !== "string") return undefined;
66 return (...args: unknown[]) =>
67 Effect.gen(function* () {
68 if (!baseUrl || !token) {
69 return yield* new RpcCallError({
70 method: prop,
71 cause: !baseUrl ? "missing host" : "missing token",
72 });
73 }
74 const response = yield* Effect.tryPromise({
75 try: () =>
76 fetch(`${baseUrl}${RPC_PATH_PREFIX}${encodeURIComponent(prop)}`, {
77 method: "POST",
78 headers: {
79 "content-type": "application/json",
80 [RPC_TOKEN_HEADER]: token,
81 },
82 body: JSON.stringify(args),
83 signal: AbortSignal.timeout(25_000),
84 }),
85 catch: (cause) => new RpcCallError({ method: prop, cause }),
86 });
87 if (response.status === 401) {
88 return yield* new RpcUnauthorized({ method: prop });
89 }
90 const value = yield* Effect.tryPromise({
91 try: () => response.json() as Promise<unknown>,
92 catch: (cause) => new RpcCallError({ method: prop, cause }),
93 });
94 if (
95 typeof value === "object" &&
96 value !== null &&
97 (value as { _tag?: unknown })._tag === RPC_ERROR_TAG &&
98 "error" in value
99 ) {
100 return yield* Effect.fail((value as { error: unknown }).error);
101 }
102 return value;
103 });
104 },
105 },
106 ) as Shape;
107 };
108
109 const bindRpc = <Shape, Req = never>(
110 targetEff: (RpcTarget & Rpc<Shape>) | Effect.Effect<RpcTarget & Rpc<Shape>, never, Req>,
111 ): Effect.Effect<Shape, never, Req> =>
112 Effect.gen(function* () {
113 if (!globalThis.__ALCHEMY_RUNTIME__) {
114 const target = yield* resolveTarget(targetEff);
115 const keys = rpcEnvKeys(target.LogicalId);
116 const host = yield* Binding.Host;
117 if (isRailwayHost(host)) {
118 yield* host.bind`${target}`({
119 env: {
120 [keys.host]: target.dnsName,
121 [keys.port]: target.port ?? DEFAULT_RPC_PORT,
122 [keys.token]: target.rpcToken,
123 },
124 });
125 }
126 }
127
128 const keys = rpcEnvKeys(logicalIdOf(targetEff));
129 const hostName = fromProcessEnv(keys.host);
130 const port = fromProcessEnv(keys.port);
131 const token = fromProcessEnv(keys.token);
132 const baseUrl =
133 hostName.length > 0
134 ? `http://${hostName}:${port.length > 0 ? port : String(DEFAULT_RPC_PORT)}`
135 : "";
136
137 return makeStub<Shape>({ baseUrl, token });
138 });
139
140 /**
141 * Bind a {@link Function} and return a typed schemaless RPC stub.
142 * Calls go to `{dnsName}:{port}/__rpc__/{method}` on the private mesh
143 * with a shared token — not the public `*.up.railway.app` URL.
144 *
145 * @example
146 * ```typescript
147 * const query = yield* Railway.bindFunction(Query);
148 * const greeting = yield* query.greet("sam");
149 * ```
150 */
151 export const bindFunction = bindRpc;
152
153 /**
154 * Bind a {@link Service} and return a typed schemaless RPC stub.
155 * Same private-mesh + token path as {@link bindFunction}.
156 *
157 * @example
158 * ```typescript
159 * const api = yield* Railway.bindService(Api);
160 * const greeting = yield* api.greet("sam");
161 * ```
162 */
163 export const bindService = bindRpc;