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

main
ts 550 lines 21.6 KB
Raw
1 import type { Dependencies } from "alchemy/Dependencies";
2 import type { HttpEffect } from "alchemy/Http";
3 import type { InputProps } from "alchemy/Input";
4 import type { Named } from "alchemy/Named";
5 import type { PlatformIdentity } from "alchemy/Platform";
6 import type { Rpc as RpcShape } from "alchemy/Rpc";
7 import { effectClass, taggedFunction } from "alchemy/Util/effect";
8 import type { ConfigError } from "effect/Config";
9 import * as Context from "effect/Context";
10 import * as Effect from "effect/Effect";
11 import * as HttpClient from "effect/http/HttpClient";
12 import * as HttpClientResponse from "effect/http/HttpClientResponse";
13 import * as Layer from "effect/Layer";
14 import { type Rpc, RpcClient, type RpcGroup, RpcSerialization } from "effect/rpc";
15 import type * as RpcClientError from "effect/rpc/RpcClientError";
16 import type { Worker, WorkerProps } from "./Worker.ts";
17 import { Worker as WorkerCtor, WorkerEnvironment } from "./Worker.ts";
18
19 /**
20 * Props for {@link RpcWorker}. Same shape as {@link WorkerProps} with
21 * an additional `schema` field carrying the rpc group definition.
22 */
23 export type RpcWorkerProps<Rpcs extends Rpc.Any> = {
24 /**
25 * The {@link RpcGroup.RpcGroup} served on this worker's `fetch`
26 * handler. The same value should be importable by any consumer of
27 * the worker (other workers or scripts using `RpcClient.make`).
28 */
29 readonly schema: RpcGroup.RpcGroup<Rpcs>;
30 };
31
32 // Context tag carrying the surrounding `RpcWorker` value, so
33 // `yield* RpcWorker` inside the impl resolves to the worker itself
34 // (mirrors `yield* Worker` semantics inside `Cloudflare.Worker`).
35 // Documented as part of the main `RpcWorker` JSDoc below.
36 export class RpcWorkerScope extends Context.Service<RpcWorkerScope, Worker>()(
37 "Cloudflare.RpcWorker",
38 ) {}
39
40 // Symbol used internally to stash the rpc `RpcGroup` schema on the
41 // `effectClass` that `RpcWorker(...)` returns, so `RpcWorker.bind`
42 // can recover it when handed the class later.
43 const SchemaSymbol = Symbol.for("alchemy.RpcWorker.schema");
44
45 // Phantom carrier — `RpcWorker.bind` uses `Rpcs` to type the returned
46 // rpc client. We don't tie it to a specific `Effect.R` since the
47 // requirements come from the underlying `Cloudflare.Worker` factory
48 // and shouldn't leak into the Stack-side service signature.
49 //
50 // `Deps` mirrors `Cloudflare.Worker<Self, Bindings, Deps>` — declares
51 // the DOs / Workers this script publishes for cross-script binding so
52 // `Counter.from(WorkerA)` type-checks from another script.
53 //
54 // `Id` is the const logical id (`Named<Id>`), matching `Cloudflare.Worker`.
55 export interface RpcWorkerYieldable<
56 Self,
57 Rpcs extends Rpc.Any,
58 Deps = never,
59 Id extends string = string,
60 >
61 extends
62 Effect.Effect<Worker<{}> & RpcShape<Self> & Dependencies<Deps>, never, any>,
63 Named<Id>,
64 PlatformIdentity<Id> {
65 /** @internal */
66 readonly [SchemaSymbol]: RpcGroup.RpcGroup<Rpcs>;
67 }
68
69 /**
70 * Type of the {@link RpcWorker} constructor. Mirrors the class-form
71 * signature of {@link Worker} so `class X extends RpcWorker<X>()(...)`
72 * works identically and the resulting worker is `Rpc<Self>`-typed for
73 * binding consumers.
74 */
75 export interface RpcWorkerClass extends Effect.Effect<Worker, never, RpcWorkerScope> {
76 /**
77 * Class-based form: `class X extends RpcWorker<X>()(name, props, impl)`.
78 *
79 * The optional second type argument `Deps` mirrors
80 * `Cloudflare.Worker<Self, Bindings, Deps>` — it declares the DOs
81 * this Worker publishes for cross-script binding so consumers can
82 * write `Counter.from(WorkerA)` and have it type-check. `Rpcs` is
83 * always inferred from `props.schema`.
84 *
85 * Yielding the class in a Stack returns the {@link Worker} resource
86 * (so `worker.url`, `worker.workerName`, etc. work as usual). To get
87 * a typed `RpcClient` for *this* worker's rpc group from inside
88 * another worker's init, call {@link RpcWorker.bind}.
89 */
90 <Self, Deps = never>(): {
91 /**
92 * Modular form (no impl). Mirrors `Cloudflare.Worker<Self>()(id, props)`.
93 * Use `WorkerClass.make(impl)` to provide the runtime as a
94 * `Layer.Layer<Self>` so consumers that don't host the worker can
95 * import the class without pulling its runtime into their bundle.
96 */
97 <const Id extends string, Rpcs extends Rpc.Any>(
98 id: Id,
99 props: RpcWorkerProps<Rpcs>,
100 ): RpcWorkerYieldable<Self, Rpcs, Deps, Id> & {
101 new (_: never): Named<Id>;
102 make<InnerR = never, InitReq = never>(
103 props: InputProps<WorkerProps>,
104 impl: Effect.Effect<Effect.Effect<HttpEffect<InnerR>, never, InnerR>, ConfigError, InitReq>,
105 ): Layer.Layer<Self, never, Exclude<InitReq | InnerR, never>>;
106 };
107 /** Inline-impl form. */
108 <const Id extends string, Rpcs extends Rpc.Any, InnerR = never, InitReq = never>(
109 id: Id,
110 props: RpcWorkerProps<Rpcs> & InputProps<WorkerProps>,
111 impl: Effect.Effect<Effect.Effect<HttpEffect<InnerR>, never, InnerR>, ConfigError, InitReq>,
112 ): RpcWorkerYieldable<Self, Rpcs, Deps, Id> & {
113 // Phantom — `class X extends RpcWorker<X>()(...)` carries `X`
114 // through the result type via `Rpc<Self>` on the binding side;
115 // the instance shape itself is empty besides `Named<Id>` (no
116 // methods exposed on `new X(...)` — everything goes through
117 // `fetch`).
118 new (_: never): Named<Id>;
119 };
120 };
121
122 /**
123 * Bind a typed Effect rpc client to a worker resource, using the
124 * worker's declared rpc {@link RpcGroup.RpcGroup} schema. Mirrors
125 * `Cloudflare.R2.ReadWriteBucket(MyBucket)` and friends.
126 *
127 * Yield once at **init** — the result is a normal `RpcClient` you
128 * can call directly from any per-request handler. Internally each
129 * method invocation builds a fresh underlying `RpcClient` (through
130 * a Proxy) because Cloudflare rejects I/O objects created on a
131 * previous request; this is hidden from the consumer.
132 *
133 * Pair with {@link RpcWorker} on the server side; both ends share
134 * the same schema so values round-trip through one `Schema` codec.
135 *
136 * @example
137 * ```ts
138 * // INIT: register the binding once and get the typed client
139 * const tasks = yield* Cloudflare.RpcWorker.bind(TaskWorker);
140 *
141 * // PER-REQUEST: call methods directly
142 * proxyGetTask: ({ id }) => tasks.getTask({ id }),
143 * ```
144 */
145 readonly bind: <Self, Rpcs extends Rpc.Any>(
146 workerEff: RpcWorkerYieldable<Self, Rpcs>,
147 ) => Effect.Effect<
148 RpcClient.RpcClient<Rpcs, RpcClientError.RpcClientError> & RpcShape<Self>,
149 never,
150 Worker
151 >;
152 }
153
154 /** @internal helper — exposed as `RpcWorker.bind` below. */
155 const bind = <Self, Rpcs extends Rpc.Any>(
156 workerEff: RpcWorkerYieldable<Self, Rpcs>,
157 ): Effect.Effect<
158 RpcClient.RpcClient<Rpcs, RpcClientError.RpcClientError> & RpcShape<Self>,
159 never,
160 Worker
161 > =>
162 Effect.gen(function* () {
163 const schema = (workerEff as unknown as Record<symbol, unknown>)[SchemaSymbol] as
164 | RpcGroup.RpcGroup<Rpcs>
165 | undefined;
166 if (!schema) {
167 return yield* Effect.die(
168 new Error("RpcWorker.bind: passed value isn't an RpcWorker class — no schema attached."),
169 );
170 }
171 const worker = (yield* workerEff) as Worker;
172 // Register the service binding on the surrounding worker at INIT.
173 // Mirrors `Cloudflare.Workers.bindWorker` — yielding the class is *not*
174 // enough; we need an explicit `self.bind\`${worker}\`(...)` so
175 // workerd surfaces the stub on `env` at request time.
176 const self = yield* WorkerCtor;
177 yield* self.bind`${worker}`({
178 bindings: [{ type: "service", name: worker.LogicalId, service: worker.workerName }],
179 });
180
181 // Build a per-call factory that wraps the Cloudflare service-
182 // binding stub (Promise-based fetch) into an Effect `HttpClient`,
183 // then `RpcClient.make` over that transport. Each call gets its
184 // own `RpcClient` because Cloudflare rejects I/O objects (the
185 // stub.fetch body) that were created on a previous request.
186 const makeFreshClient = Effect.gen(function* () {
187 const env = yield* WorkerEnvironment;
188 const stub = (env as Record<string, { fetch: typeof fetch }>)[worker.LogicalId];
189 const httpClient = HttpClient.make((req) =>
190 Effect.promise((signal) =>
191 stub.fetch(
192 new Request(req.url, {
193 method: req.method,
194 headers: new Headers(req.headers as any),
195 body: (req.body as any)?.body ?? undefined,
196 signal,
197 }),
198 ),
199 ).pipe(Effect.map((res) => HttpClientResponse.fromWeb(req, res))),
200 );
201 const protocol = RpcClient.layerProtocolHttp({ url: "http://alchemy-rpc-worker/" }).pipe(
202 Layer.provide(RpcSerialization.layerNdjson),
203 Layer.provide(Layer.succeed(HttpClient.HttpClient, httpClient)),
204 );
205 return yield* RpcClient.make(schema).pipe(Effect.provide(protocol));
206 });
207
208 // Return a Proxy that LOOKS like an `RpcClient<Rpcs>` but defers
209 // the actual `RpcClient` construction to call time. Mirrors
210 // `makeRpcStub` from `./Rpc.ts`: each method invocation builds a
211 // fresh client, runs the call inside `Effect.scoped`, and tears
212 // the client's scope down with the call. From the consumer's
213 // perspective this is a normal `RpcClient`:
214 //
215 // const tasks = yield* Cloudflare.RpcWorker.bind(TaskWorker);
216 // yield* tasks.getTask({ id: "abc" });
217 return new Proxy(
218 {},
219 {
220 get: (_target, method) => {
221 if (typeof method !== "string") return undefined;
222 return (...args: unknown[]) =>
223 Effect.gen(function* () {
224 const client = yield* makeFreshClient;
225 const fn = (
226 client as unknown as Record<
227 string,
228 (...a: unknown[]) => Effect.Effect<unknown, unknown, unknown>
229 >
230 )[method];
231 return yield* fn(...args);
232 }).pipe(Effect.scoped);
233 },
234 },
235 ) as RpcClient.RpcClient<Rpcs, RpcClientError.RpcClientError> & RpcShape<Self>;
236 });
237
238 /**
239 * `RpcWorker` is a thin sugar over {@link Worker} for the common case
240 * where a worker's entire `fetch` surface is a typed Effect `RpcGroup`.
241 * It takes the rpc `schema` directly in props alongside `main`, and
242 * accepts an init Effect that returns the already-piped
243 * `RpcServer.toHttpEffect(...)`-producing Effect (no `{ fetch }`
244 * wrapper) — the wrapper plugs it into the worker's `fetch` for you.
245 *
246 * Functionally identical to writing `Cloudflare.Worker(...)` with
247 * `return { fetch: RpcServer.toHttpEffect(schema).pipe(...) }`; use
248 * whichever style you prefer.
249 *
250 * The class form (`class X extends Cloudflare.RpcWorker<X>()(...)`)
251 * carries `Self` through the result type as `Rpc<Self>`, so other
252 * workers binding to this one see the rpc shape pinned to `Self`.
253 *
254 *
255 * ### Defining the rpc group
256 * **Example:** Pure schema description
257 * The rpc group and its schemas live outside any worker so both the
258 * server (`RpcWorker`) and any consumers (`RpcClient.make` /
259 * `RpcDurableObject`) import the same value.
260 * ```typescript
261 * import * as Schema from "effect/Schema";
262 * import { Rpc, RpcGroup } from "effect/rpc";
263 *
264 * export class TaskNotFound extends Schema.TaggedClass<TaskNotFound>()(
265 * "TaskNotFound",
266 * { id: Schema.String },
267 * ) {}
268 *
269 * const getTask = Rpc.make("getTask", {
270 * payload: { id: Schema.String },
271 * success: Schema.String,
272 * error: TaskNotFound,
273 * });
274 *
275 * export class TaskRpcs extends RpcGroup.make(getTask) {}
276 * ```
277 *
278 * ### Implementing the worker
279 * **Example:** Class form (recommended)
280 * Mirrors `Cloudflare.Worker<Self>()(...)` — `class X extends ...`
281 * works the same. The init Effect builds a handlers `Layer` from the
282 * group and returns the `RpcServer.toHttpEffect(schema)`-piped Effect
283 * directly.
284 * ```typescript
285 * import * as Cloudflare from "@alchemy.run/cloudflare";
286 * import * as Effect from "effect/Effect";
287 * import * as Layer from "effect/Layer";
288 * import { RpcSerialization, RpcServer } from "effect/rpc";
289 * import { TaskRpcs } from "./rpcs.ts";
290 *
291 * export default class Worker extends Cloudflare.RpcWorker<Worker>()(
292 * "Worker",
293 * { main: import.meta.url, schema: TaskRpcs },
294 * Effect.gen(function* () {
295 * const handlers = TaskRpcs.toLayer({
296 * getTask: ({ id }) => Effect.succeed(`task-${id}`),
297 * });
298 * return RpcServer.toHttpEffect(TaskRpcs).pipe(
299 * Effect.provide(Layer.mergeAll(handlers, RpcSerialization.layerJson)),
300 * );
301 * }),
302 * ) {}
303 * ```
304 *
305 * **Example:** NDJSON for streaming rpcs
306 * If any rpc in the group is a streaming rpc, the wire serialization
307 * must be `RpcSerialization.layerNdjson` — streaming rpcs need
308 * newline framing on the wire.
309 * ```typescript
310 * return RpcServer.toHttpEffect(ChatRpcs).pipe(
311 * Effect.provide(handlers),
312 * Effect.provide(RpcSerialization.layerNdjson),
313 * );
314 * ```
315 *
316 * ### Modular form: separate the class from its runtime
317 * **Example:** Class declaration with no impl + `static make(impl)`
318 * The inline class form above bundles the runtime into the class
319 * declaration. The two-arg form `(id, props)` declares the class
320 * as a pure tagged identifier; provide the runtime separately via
321 * `WorkerClass.make(impl)` so consumers can import the class for
322 * binding without pulling the host's runtime into their bundle.
323 * ```typescript
324 * export class TaskWorker extends Cloudflare.RpcWorker<TaskWorker>()(
325 * "TaskWorker",
326 * { main: import.meta.url, schema: TaskRpcs },
327 * ) {}
328 *
329 * // Only the host script imports this default export; consumers
330 * // import the class above for `RpcWorker.bind(TaskWorker)`.
331 * export default TaskWorker.make(
332 * Effect.gen(function* () {
333 * const handlers = TaskRpcs.toLayer({
334 * getTask: ({ id }) => Effect.succeed(`task-${id}`),
335 * });
336 * return RpcServer.toHttpEffect(TaskRpcs).pipe(
337 * Effect.provide(Layer.mergeAll(handlers, RpcSerialization.layerJson)),
338 * );
339 * }),
340 * );
341 * ```
342 *
343 * ### Hosting a Durable Object for cross-script binding
344 * **Example:** `RpcWorker<Self, Deps>()` declares published DOs
345 * The optional second type argument `Deps` mirrors
346 * `Cloudflare.Worker<Self, Bindings, Deps>` — it declares the DOs
347 * this Worker publishes for cross-script binding. With `Counter`
348 * named in `Deps`, any other Worker can write
349 * `Counter.from(TaskWorker)` and have it type-check.
350 * ```typescript
351 * import { Counter } from "./counter.ts";
352 *
353 * export class TaskWorker extends Cloudflare.RpcWorker<TaskWorker, Counter>()(
354 * "TaskWorker",
355 * { main: import.meta.url, schema: TaskRpcs },
356 * ) {}
357 * ```
358 * See {@link RpcDurableObject} for the consumer side
359 * (`Counter.from(TaskWorker)`).
360 *
361 * ### Binding it from another worker
362 * **Example:** `Cloudflare.RpcWorker.bind(WorkerClass)`
363 * Inside another worker's init, `RpcWorker.bind(WorkerClass)`
364 * registers the service binding on the surrounding worker and returns
365 * a typed `RpcClient` you can call directly from any per-request
366 * handler. Internally each method invocation builds a fresh underlying
367 * client (because Cloudflare rejects cross-request reuse of the
368 * stub I/O), but that's hidden behind a Proxy so the consumer sees a
369 * normal `RpcClient`.
370 * ```typescript
371 * import TaskWorker from "./task-worker.ts";
372 *
373 * export default class Caller extends Cloudflare.RpcWorker<Caller>()(
374 * "Caller",
375 * { main: import.meta.url, schema: CallerRpcs },
376 * Effect.gen(function* () {
377 * // INIT: register binding, get the typed client
378 * const tasks = yield* Cloudflare.RpcWorker.bind(TaskWorker);
379 *
380 * const handlers = CallerRpcs.toLayer({
381 * // PER-REQUEST: just call methods directly
382 * proxyGetTask: ({ id }) => tasks.getTask({ id }),
383 * });
384 * return RpcServer.toHttpEffect(CallerRpcs).pipe(
385 * Effect.provide(Layer.mergeAll(handlers, RpcSerialization.layerJson)),
386 * );
387 * }),
388 * ) {}
389 * ```
390 *
391 * ### Driving it from a test
392 * **Example:** `Test.make` + `RpcClient.make`
393 * The same `RpcGroup` drives a typed client. `Test.make` deploys the
394 * stack once for the file; each test yields the deploy handle for its
395 * URL and calls procedures directly.
396 * ```typescript
397 * import { expect } from "@alchemy.run/test";
398 * import * as Cloudflare from "@alchemy.run/cloudflare";
399 * import * as Test from "@alchemy.run/test/Alchemy";
400 * import * as Effect from "effect/Effect";
401 * import * as Layer from "effect/Layer";
402 * import * as Schedule from "effect/Schedule";
403 * import * as FetchHttpClient from "effect/http/FetchHttpClient";
404 * import * as RpcClient from "effect/rpc/RpcClient";
405 * import * as RpcSerialization from "effect/rpc/RpcSerialization";
406 * import Stack from "../alchemy.run.ts";
407 * import { TaskRpcs } from "../src/rpcs.ts";
408 *
409 * const { test, beforeAll, afterAll, deploy, destroy } = Test.make({
410 * providers: Cloudflare.providers(),
411 * });
412 * const stack = beforeAll(deploy(Stack));
413 * afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack));
414 *
415 * const layer = (url: string) =>
416 * RpcClient.layerProtocolHttp({ url }).pipe(
417 * Layer.provide(FetchHttpClient.layer),
418 * Layer.provide(
419 * Layer.succeed(RpcSerialization.RpcSerialization, RpcSerialization.json),
420 * ),
421 * );
422 *
423 * test(
424 * "getTask",
425 * Effect.gen(function* () {
426 * const { url } = yield* stack;
427 * yield* Effect.gen(function* () {
428 * const client = yield* RpcClient.make(TaskRpcs);
429 * const result = yield* client
430 * .getTask({ id: "abc" })
431 * .pipe(Effect.retry({ schedule: Schedule.exponential("500 millis"), times: 5 }));
432 * expect(result).toBe("task-abc");
433 * }).pipe(Effect.scoped, Effect.provide(layer(url)));
434 * }),
435 * );
436 * ```
437 *
438 * ### Yielding the surrounding worker from inside the impl
439 * **Example:** `yield* RpcWorker` inside the init effect
440 * Mirrors `yield* DurableObject` — yield the tag to access
441 * the surrounding worker.
442 * ```typescript
443 * Effect.gen(function* () {
444 * const self = yield* Cloudflare.RpcWorker;
445 * });
446 * ```
447 *
448 * @resource
449 * @product Workers
450 * @category Workers & Compute
451 */
452 export const RpcWorker: RpcWorkerClass = (() => {
453 const fn = (...args: any[]) => {
454 // Class-form: zero args returns the inner builder. Inner-arg arity
455 // distinguishes modular (`(id, props)`, no impl — `static make(impl)`
456 // provides the runtime) from inline-impl (`(id, props, impl)`).
457 if (args.length === 0) {
458 return (...inner: any[]) => {
459 if (inner.length === 2) {
460 const [id, props] = inner as [string, RpcWorkerProps<any>];
461 return buildModular(id, props);
462 }
463 const [id, props, impl] = inner as [
464 string,
465 RpcWorkerProps<any>,
466 Effect.Effect<Effect.Effect<HttpEffect<any>>>,
467 ];
468 return build(id, props, impl);
469 };
470 }
471 // Bare form: `(name, props, impl)`.
472 const [id, props, impl] = args as [
473 string,
474 RpcWorkerProps<any>,
475 Effect.Effect<Effect.Effect<HttpEffect<any>>>,
476 ];
477 return build(id, props, impl);
478 };
479
480 const tagged = taggedFunction(RpcWorkerScope, fn as any) as any;
481 tagged.bind = bind;
482 return tagged;
483 })() as any;
484
485 const wrapImpl = (impl: Effect.Effect<Effect.Effect<HttpEffect<any>>>) =>
486 // The user's inner Effect resolves to `HttpEffect`; the underlying
487 // `Cloudflare.Worker` expects `{ fetch: HttpEffect }`. Box it.
488 Effect.map(impl, (fetch) => ({ fetch }) as unknown as { fetch: HttpEffect<any> });
489
490 // `effectClass` does not copy statics from the underlying Worker.
491 const stampLogicalId = (
492 klass: Record<symbol | string, unknown>,
493 source: { LogicalId?: unknown },
494 id: string,
495 ) => {
496 klass.LogicalId = typeof source.LogicalId === "string" ? source.LogicalId : id;
497 return klass;
498 };
499
500 const buildModular = (id: string, props: RpcWorkerProps<any>) => {
501 const { schema } = props;
502 // Delegate to `Cloudflare.Worker<Self>()(id, props)` (modular form)
503 // so we inherit its `static make(impl)` plumbing for free. We just
504 // wrap the user's HttpEffect-returning impl into the `{ fetch }`
505 // shape `Cloudflare.Worker` expects, and stash the rpc schema on
506 // the class so `RpcWorker.bind(WorkerClass)` can recover it.
507 const Underlying: any = (WorkerCtor as any)()(id);
508 // `Underlying` is itself an Effect (the no-impl Worker class), so hand it
509 // straight to `effectClass` rather than reaching for a removed `.asEffect()`.
510 const klass = class extends effectClass(Underlying as Effect.Effect<Worker>) {
511 static make = (
512 props: InputProps<WorkerProps>,
513 impl: Effect.Effect<Effect.Effect<HttpEffect<any>>>,
514 ): Layer.Layer<any, never, any> => Underlying.make(props, wrapImpl(impl));
515 } as unknown as Record<symbol | string, unknown>;
516 klass[SchemaSymbol] = schema;
517 return stampLogicalId(klass, Underlying, id);
518 };
519
520 const build = (
521 id: string,
522 props: RpcWorkerProps<any>,
523 impl: Effect.Effect<Effect.Effect<HttpEffect<any>>>,
524 ) => {
525 const { schema, ...workerProps } = props;
526
527 // Wrap the user's HttpEffect-returning Effect into the `{ fetch }`
528 // shape `Cloudflare.Worker` expects.
529 const wrappedImpl = Effect.map(
530 impl,
531 (fetch) => ({ fetch }) as unknown as { fetch: HttpEffect<any> },
532 );
533
534 // Delegate registration / binding metadata to the underlying
535 // `Cloudflare.Worker`. The returned `effectClass`, when yielded,
536 // produces the standard `Worker` resource (so `worker.url`,
537 // `worker.workerName`, etc. all work as usual).
538 const underlying = (WorkerCtor as any)()(id, workerProps, wrappedImpl);
539
540 // Re-wrap as our own `effectClass` so we can stash the rpc schema
541 // on the class for `RpcWorker.bind` to recover later. (Re-using
542 // `effectClass` here means `class X extends RpcWorker<X>()(...)`
543 // still works.) `underlying` is already an Effect, so pass it directly.
544 const klass = effectClass(underlying as Effect.Effect<Worker>) as unknown as Record<
545 symbol | string,
546 unknown
547 >;
548 klass[SchemaSymbol] = schema;
549 return stampLogicalId(klass, underlying, id);
550 };