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

main
ts 75 lines 2.85 KB
Raw
1 import { RuntimeContext } from "alchemy/RuntimeContext";
2 import * as Chat from "effect/ai/Chat";
3 import * as Arr from "effect/Array";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import {
7 BackingPersistence,
8 PersistenceError,
9 type BackingPersistenceStore,
10 } from "effect/persistence/Persistence";
11 import { DurableObjectState } from "../Workers/DurableObjectState.ts";
12
13 export const DurableObjectChatPersistence = Layer.effect(BackingPersistence)(
14 Effect.gen(function* () {
15 const state = yield* DurableObjectState;
16 const storage = state.storage;
17
18 const wrapErr = (op: string, key?: string) => (cause: unknown) =>
19 PersistenceError.make({
20 message: `Failed to ${op}${key !== undefined ? ` key ${key}` : ""} in DurableObject storage`,
21 cause,
22 });
23
24 return BackingPersistence.of({
25 make: (storeId) =>
26 Effect.sync(() => {
27 const prefixed = (k: string) => `${storeId}:${k}`;
28 return {
29 get: (key) =>
30 storage
31 .get<object>(prefixed(key))
32 .pipe(Effect.mapError(wrapErr("get", key)), Effect.provide(RuntimeContext.phantom)),
33 getMany: (keys) =>
34 storage.get<object>(keys.map(prefixed)).pipe(
35 Effect.mapError(wrapErr("getMany")),
36 Effect.map(
37 (map) =>
38 keys.map((k) => map.get(prefixed(k))) as Arr.NonEmptyArray<object | undefined>,
39 ),
40 Effect.provide(RuntimeContext.phantom),
41 ),
42 set: (key, value, _ttl) =>
43 storage
44 .put(prefixed(key), value)
45 .pipe(Effect.mapError(wrapErr("set", key)), Effect.provide(RuntimeContext.phantom)),
46 setMany: (entries) =>
47 storage
48 .put(Object.fromEntries(entries.map(([k, v]) => [prefixed(k), v])))
49 .pipe(Effect.mapError(wrapErr("setMany")), Effect.provide(RuntimeContext.phantom)),
50 remove: (key) =>
51 storage
52 .delete(prefixed(key))
53 .pipe(
54 Effect.asVoid,
55 Effect.mapError(wrapErr("remove", key)),
56 Effect.provide(RuntimeContext.phantom),
57 ),
58 clear: storage.list({ prefix: `${storeId}:` }).pipe(
59 Effect.flatMap((map) => {
60 const ks = [...map.keys()];
61 if (ks.length === 0) return Effect.void;
62 return Effect.asVoid(storage.delete(ks));
63 }),
64 Effect.mapError(wrapErr("clear")),
65 Effect.provide(RuntimeContext.phantom),
66 ),
67 } satisfies BackingPersistenceStore;
68 }),
69 });
70 }),
71 );
72
73 export const layerChatDurableObject = Chat.layerPersisted({
74 storeId: "alchemy.chat",
75 }).pipe(Layer.provide(DurableObjectChatPersistence));