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

main
ts 470 lines 17.1 KB
Raw
1 import * as Cause from "effect/Cause";
2 import * as Context from "effect/Context";
3 import * as Effect from "effect/Effect";
4 import type * as Headers from "effect/http/Headers";
5 import * as Option from "effect/Option";
6 import type * as Rpc from "effect/rpc/Rpc";
7 import * as Schema from "effect/Schema";
8 import * as Stream from "effect/Stream";
9 import { Command, type Subscription } from "foldkit";
10 import { defineMessageUnion, type MessageUnion } from "foldkit/message";
11 import type * as Aggregate from "./Aggregate.ts";
12 import type * as Api from "./Api.ts";
13 import type * as DomainCommand from "./Command.ts";
14 import * as Key from "./Key.ts";
15 import * as Read from "./Read.ts";
16 import { nameOf } from "./ReadRpcs.ts";
17 import type * as DomainStream from "./Stream.ts";
18 import type * as View from "./View.ts";
19
20 /** Per-call headers, resolved at execution time and excluded from replayable args. */
21 export class CommandHeaders extends Context.Service<
22 CommandHeaders,
23 {
24 readonly get: (command: string) => Effect.Effect<Headers.Input>;
25 }
26 >()("@alchemy.run/domain/Foldkit/CommandHeaders") {}
27
28 /** Page-local command id state. Give each page load a fresh session in Flags. */
29 export const CommandIds = Schema.Struct({ session: Schema.String, sent: Schema.Number });
30 /** Page-local command id state. */
31 export type CommandIds = typeof CommandIds.Type;
32
33 /** Allocate an id without reading time or changing the supplied state. */
34 export const next = (ids: CommandIds) => ({
35 commandId: `${ids.session}:${ids.sent}`,
36 commandIds: CommandIds.make({ session: ids.session, sent: ids.sent + 1 }),
37 });
38
39 type Input<C extends DomainCommand.Any> = Omit<C["Type"], "_tag">;
40 type Reply<C extends DomainCommand.Any> = C["reply"] extends Schema.Top ? C["reply"]["Type"] : void;
41 type Rejection<C extends DomainCommand.Any> = C["rejects"][number]["Type"];
42 type Denial<C extends DomainCommand.Any> = C["middleware"][number]["error"]["Type"];
43
44 /** A refusal is final; an unknown outcome can be retried with the same id. */
45 export type Failure<C extends DomainCommand.Any> =
46 | Readonly<{ _tag: "Rejected"; rejection: Rejection<C> }>
47 | Readonly<{ _tag: "Denied"; error: Denial<C> }>
48 | Readonly<{ _tag: "Unknown" }>;
49
50 type Cases<A extends Api.Any> = {
51 readonly [C in Api.CommandsOf<A> as `Succeeded${C["tag"]}`]: {
52 commandId: typeof Schema.String;
53 reply: Schema.Schema<Reply<C>>;
54 receipt: Schema.Struct<{ stream: typeof Schema.String; version: typeof Schema.Number }>;
55 };
56 } & {
57 readonly [C in Api.CommandsOf<A> as `Failed${C["tag"]}`]: {
58 commandId: typeof Schema.String;
59 failure: Schema.Schema<Failure<C>>;
60 };
61 };
62
63 type Args<C extends DomainCommand.Any> = {
64 target: Schema.toType<C["target"]>;
65 input: Schema.Schema<Input<C>>;
66 commandId: typeof Schema.String;
67 };
68 type Result<A extends Api.Any, C extends DomainCommand.Any> = Extract<
69 MessageUnion<Cases<A>>["Type"],
70 { readonly _tag: `Succeeded${C["tag"]}` | `Failed${C["tag"]}` }
71 >;
72
73 /** Typed Command definitions and their result Message union, derived from an Api. */
74 type CommandDefinitions<A extends Api.Any> = {
75 readonly [C in Api.CommandsOf<A> as C["tag"]]: Command.CommandDefinitionWithArgs<
76 C["tag"],
77 Args<C>,
78 Effect.Effect<
79 Result<A, C>,
80 never,
81 A["Client"]["Identifier"] | Effect.Services<ReturnType<Api.CommandClient<C>>>
82 >
83 >;
84 } & { readonly Message: MessageUnion<Cases<A>> };
85
86 const Receipt = Schema.Struct({ stream: Schema.String, version: Schema.Number });
87
88 /** Build one Foldkit Command per Api command. Provide the Api client at the runtime boundary. */
89 function commandDefinitions<A extends Api.Any>(api: A): CommandDefinitions<A>;
90 function commandDefinitions(api: Api.Any): unknown {
91 const cases: Record<string, Schema.Struct.Fields> = {};
92 for (const command of api.commands) {
93 const rejection = Schema.Union(command.rejects);
94 const denial = Schema.Union(command.middleware.map((middleware) => middleware.error));
95 cases[`Succeeded${command.tag}`] = {
96 commandId: Schema.String,
97 reply: command.reply ?? Schema.Void,
98 receipt: Receipt,
99 };
100 cases[`Failed${command.tag}`] = {
101 commandId: Schema.String,
102 failure: Schema.Union([
103 Schema.TaggedStruct("Rejected", { rejection }),
104 Schema.TaggedStruct("Denied", { error: denial }),
105 Schema.TaggedStruct("Unknown", {}),
106 ]),
107 };
108 }
109 const Message = defineMessageUnion(cases);
110 const definitions: Record<string, unknown> = { Message };
111 for (const command of api.commands) {
112 const { payloadSchema } = command.rpc as Rpc.AnyWithProps;
113 definitions[command.tag] = Command.define(command.tag, {
114 args: {
115 target: Schema.toType(command.target),
116 input: Schema.toType((payloadSchema as Schema.Struct<{ input: Schema.Top }>).fields.input),
117 commandId: Schema.String,
118 },
119 messages: [Message],
120 execute: Effect.fn(
121 function* ({ target, input, commandId }) {
122 const client = (yield* Effect.service(api.Client)) as Record<
123 string,
124 (
125 target: string,
126 input: unknown,
127 options: Api.CommandOptions,
128 ) => Effect.Effect<{ reply: unknown; stream: string; version: number }, unknown>
129 >;
130 const headersService = yield* Effect.serviceOption(CommandHeaders);
131 const headers =
132 headersService._tag === "Some"
133 ? yield* headersService.value.get(command.tag)
134 : undefined;
135 const { reply, stream, version } = yield* client[command.tag](target, input, {
136 commandId,
137 headers,
138 });
139 return {
140 _tag: `Succeeded${command.tag}`,
141 commandId,
142 reply,
143 receipt: { stream, version },
144 };
145 },
146 (effect, { commandId }) =>
147 effect.pipe(
148 Effect.catchCauseIf(
149 (cause) => Cause.hasFails(cause) || Cause.hasDies(cause),
150 (cause) =>
151 Effect.succeed({
152 _tag: `Failed${command.tag}`,
153 commandId,
154 failure: Cause.hasDies(cause)
155 ? { _tag: "Unknown" }
156 : classifyFailure(
157 command,
158 cause.pipe(Cause.findErrorOption, Option.getOrUndefined),
159 ),
160 }),
161 ),
162 ),
163 ),
164 });
165 }
166 return definitions;
167 }
168
169 const classifyFailure = (command: DomainCommand.Any, error: unknown) => {
170 if (command.rejects.some((rejection) => Schema.is(rejection)(error))) {
171 return { _tag: "Rejected", rejection: error };
172 }
173 if (command.middleware.some((middleware) => Schema.is(middleware.error)(error))) {
174 return { _tag: "Denied", error };
175 }
176 return { _tag: "Unknown" };
177 };
178
179 type ReadEntry = View.Any | Aggregate.Any | DomainStream.Any;
180 type Reads<A extends Api.Any> = Extract<A["serves"][number], ReadEntry>;
181 type ReadName<V extends ReadEntry> = V extends View.Any
182 ? V["viewName"]
183 : V extends Aggregate.Any
184 ? V["aggregateName"]
185 : V extends DomainStream.Any
186 ? V["streamName"]
187 : never;
188 type ReadClient<V extends ReadEntry> = V extends View.Any
189 ? Api.ViewClient<V>
190 : V extends Aggregate.Any
191 ? Api.AggregateClient<V>
192 : V extends DomainStream.Any
193 ? Api.StreamClient<V>
194 : never;
195 type ReadKey<V extends ReadEntry> = Parameters<ReadClient<V>["watch"]>[0];
196 type StateOf<V extends ReadEntry> = Stream.Success<ReturnType<ReadClient<V>["watch"]>>["state"];
197 type EntryOf<V extends ReadEntry> = Exclude<
198 Stream.Success<ReturnType<ReadClient<V>["events"]>>,
199 Read.CaughtUp
200 >;
201 type ErrorOf<V extends ReadEntry> = Stream.Error<ReturnType<ReadClient<V>["watch"]>>;
202 type ViewStateSchema<V extends View.Any> = [NonNullable<V["definition"]["state"]>] extends [never]
203 ? typeof Schema.Never
204 : Extract<NonNullable<V["definition"]["state"]>, Schema.Top>;
205 type ViewFlags<V extends View.Any> = ReturnType<typeof snapshotFlags<ViewStateSchema<V>>>;
206
207 /** A read namespace with Foldkit Subscription entries, bound to one Api entry. */
208 export interface ReadClientOf<A extends Api.Any, V extends ReadEntry> {
209 readonly watch: <Model, Message>(
210 options: WatchOptions<Model, Message, V>,
211 ) => Subscription.EntryWithoutKeepAlive<
212 Model,
213 Message,
214 { key: ReadKey<V>; isEnabled: boolean },
215 A["Client"]["Identifier"]
216 >;
217 readonly events: <Model, Message>(
218 options: EventsOptions<Model, Message, V>,
219 ) => EventsSubscription<A, Model, Message, V>;
220 }
221
222 /** Commands and read namespaces computed from the Api's entries. Message is reserved. */
223 export type ClientOf<A extends Api.Any> = CommandDefinitions<A> & {
224 readonly [V in Reads<A> as ReadName<V>]: ReadClientOf<A, V> &
225 (V extends View.Any
226 ? {
227 readonly SnapshotFlags: ViewFlags<V>;
228 readonly decodeSnapshotFlags: (flags: unknown) => Option.Option<ViewFlags<V>["Type"]>;
229 }
230 : {});
231 };
232
233 /** Build the Foldkit Commands and Subscriptions for an Api. The app provides api.layerClient in its runtime resources. */
234 export function make<A extends Api.Any>(
235 api: A & ("Message" extends keyof Api.ClientOf<A> ? never : unknown),
236 ): ClientOf<A>;
237 export function make(api: Api.Any): unknown {
238 // The signature rejects an Api with an entry named Message; the result union is assigned last.
239 const definitions = commandDefinitions(api) as Record<string, unknown>;
240 const { Message } = definitions;
241 for (const entry of api.serves) {
242 if (entry.kind !== "View" && entry.kind !== "Aggregate" && entry.kind !== "Stream") {
243 continue;
244 }
245 const name = nameOf(entry);
246 const flags =
247 entry.kind === "View"
248 ? snapshotFlags(
249 (entry.definition.state ?? Schema.Never) as Schema.Schema<unknown> & {
250 readonly DecodingServices: never;
251 },
252 )
253 : undefined;
254 definitions[name] = {
255 watch: (options: WatchOptions<unknown, unknown, ReadEntry>) =>
256 watchRead(api, entry, name, options),
257 events: (options: EventsOptions<unknown, unknown, ReadEntry>) =>
258 readEvents(api, entry, name, options),
259 ...(flags === undefined
260 ? {}
261 : {
262 SnapshotFlags: flags,
263 decodeSnapshotFlags: Schema.decodeUnknownOption(flags),
264 }),
265 };
266 }
267 definitions.Message = Message;
268 return definitions;
269 }
270
271 const keySchemaOf = (entry: ReadEntry) =>
272 Schema.toType(
273 entry.kind === "Aggregate" ? entry.definition.id : Key.idSchemaOf(entry.definition.key),
274 );
275
276 /** A watch Snapshot with explicit absence for Foldkit Models. */
277 export type Snapshot<State> = Readonly<{
278 state: Option.Option<NonNullable<State>>;
279 cursor: number;
280 }>;
281
282 /** Callbacks for live read state. Cursor changes do not restart the watch. */
283 export interface WatchOptions<Model, Message, V extends ReadEntry> {
284 readonly key: (model: Model) => ReadKey<V>;
285 readonly isEnabled?: (model: Model) => boolean;
286 readonly toMessage: (snapshot: Snapshot<StateOf<V>>) => Message;
287 readonly onFailure: (error: ErrorOf<V>) => Message;
288 /** Handle unexpected read defects. Interruption does not call this callback. */
289 readonly onDefect: (cause: Cause.Cause<unknown>) => Message;
290 }
291
292 /** Follow read state and cursor. Pass the result as an entry to Subscription.make. */
293 function watchRead(
294 api: Api.Any,
295 entry: ReadEntry,
296 name: string,
297 options: WatchOptions<unknown, unknown, ReadEntry>,
298 ): unknown {
299 return {
300 dependenciesSchema: Schema.Struct({
301 key: keySchemaOf(entry),
302 isEnabled: Schema.Boolean,
303 }),
304 modelToDependencies: (model: unknown) => ({
305 key: options.key(model),
306 isEnabled: options.isEnabled?.(model) ?? true,
307 }),
308 dependenciesToStream: ({ key, isEnabled }: { key: string; isEnabled: boolean }) =>
309 isEnabled
310 ? Stream.unwrap(
311 api.Client.pipe(
312 Effect.map((client) =>
313 (client as Record<string, ReadClient<ReadEntry>>)[name].watch(key),
314 ),
315 ),
316 ).pipe(
317 Stream.map(({ state, cursor }) =>
318 options.toMessage({ state: Option.fromNullishOr(state), cursor }),
319 ),
320 Stream.catchCause((cause) => {
321 if (Cause.hasDies(cause)) {
322 return Stream.succeed(options.onDefect(cause));
323 }
324 const error = Cause.findErrorOption(cause);
325 return Option.isSome(error)
326 ? Stream.succeed(options.onFailure(error.value))
327 : Stream.failCause(cause);
328 }),
329 )
330 : Stream.empty,
331 };
332 }
333
334 /** Callbacks for a resumable event feed. The app stores the cursor after applying each entry. */
335 export interface EventsOptions<Model, Message, V extends ReadEntry> {
336 readonly key: (model: Model) => ReadKey<V>;
337 readonly cursor: (model: Model) => Option.Option<number>;
338 readonly isEnabled?: (model: Model) => boolean;
339 readonly restartKey?: (model: Model) => number;
340 readonly onEntry: (entry: EntryOf<V>) => Message;
341 readonly onCaughtUp: (cursor: number) => Message;
342 readonly onFailure: (error: ErrorOf<V>) => Message;
343 /** Handle unexpected read defects. Interruption does not call this callback. */
344 readonly onDefect: (cause: Cause.Cause<unknown>) => Message;
345 }
346
347 /** Follow event entries after the Model's cursor, without counting sequence gaps. */
348 type EventsSubscription<A extends Api.Any, Model, Message, V extends ReadEntry> = {
349 readonly dependenciesSchema: Schema.Struct<{
350 key: Schema.Schema<ReadKey<V>>;
351 cursor: Schema.Schema<Option.Option<number>>;
352 restartKey: Schema.optional<typeof Schema.Number>;
353 isEnabled: typeof Schema.Boolean;
354 }>;
355 readonly modelToDependencies: (model: Model) => {
356 key: ReadKey<V>;
357 cursor: Option.Option<number>;
358 restartKey?: number;
359 isEnabled: boolean;
360 };
361 readonly keepAliveEquivalence: (
362 left: {
363 key: ReadKey<V>;
364 cursor: Option.Option<number>;
365 restartKey?: number;
366 isEnabled: boolean;
367 },
368 right: {
369 key: ReadKey<V>;
370 cursor: Option.Option<number>;
371 restartKey?: number;
372 isEnabled: boolean;
373 },
374 ) => boolean;
375 readonly dependenciesToStream: (
376 dependencies: {
377 key: ReadKey<V>;
378 cursor: Option.Option<number>;
379 restartKey?: number;
380 isEnabled: boolean;
381 },
382 readDependencies: () => {
383 key: ReadKey<V>;
384 cursor: Option.Option<number>;
385 restartKey?: number;
386 isEnabled: boolean;
387 },
388 ) => Stream.Stream<Message, never, A["Client"]["Identifier"]>;
389 };
390 function readEvents(
391 api: Api.Any,
392 entry: ReadEntry,
393 name: string,
394 options: EventsOptions<unknown, unknown, ReadEntry>,
395 ): unknown {
396 const keySchema = keySchemaOf(entry);
397 const sameKey = Schema.toEquivalence(keySchema);
398 type Dependencies = {
399 key: string;
400 cursor: Option.Option<number>;
401 restartKey?: number;
402 isEnabled: boolean;
403 };
404 return {
405 dependenciesSchema: Schema.Struct({
406 key: keySchema,
407 cursor: Schema.Option(Schema.Number),
408 restartKey: Schema.optional(Schema.Number),
409 isEnabled: Schema.Boolean,
410 }),
411 modelToDependencies: (model: unknown): Dependencies => ({
412 key: options.key(model),
413 cursor: options.cursor(model),
414 restartKey: options.restartKey?.(model),
415 isEnabled: options.isEnabled?.(model) ?? true,
416 }),
417 keepAliveEquivalence: (left: Dependencies, right: Dependencies) =>
418 sameKey(left.key, right.key) &&
419 left.isEnabled === right.isEnabled &&
420 left.restartKey === right.restartKey,
421 dependenciesToStream: (_: Dependencies, readDependencies: () => Dependencies) =>
422 Stream.suspend(() => {
423 const { key, cursor, isEnabled } = readDependencies();
424 if (!isEnabled) {
425 return Stream.empty;
426 }
427 let deliveredCursor = Option.getOrElse(cursor, () => 0);
428 return Stream.unwrap(
429 api.Client.pipe(
430 Effect.map((client) =>
431 (client as Record<string, ReadClient<ReadEntry>>)[name].events(key, {
432 after: Option.getOrUndefined(cursor),
433 }),
434 ),
435 ),
436 ).pipe(
437 Stream.filter((frame) => {
438 if (Read.isCaughtUp(frame)) {
439 return true;
440 }
441 const appliedCursor = Option.getOrElse(readDependencies().cursor, () => 0);
442 if (frame.envelope.seq <= Math.max(deliveredCursor, appliedCursor)) {
443 return false;
444 }
445 deliveredCursor = frame.envelope.seq;
446 return true;
447 }),
448 Stream.map((frame) =>
449 Read.isCaughtUp(frame) ? options.onCaughtUp(frame.cursor) : options.onEntry(frame),
450 ),
451 Stream.catchCause((cause) => {
452 if (Cause.hasDies(cause)) {
453 return Stream.succeed(options.onDefect(cause));
454 }
455 const error = Cause.findErrorOption(cause);
456 return Option.isSome(error)
457 ? Stream.succeed(options.onFailure(error.value))
458 : Stream.failCause(cause);
459 }),
460 );
461 }),
462 };
463 }
464
465 /** Decode snapshot wire data in Flags, converting null state to Option.none. */
466 const snapshotFlags = <State extends Schema.Top>(state: State) =>
467 Schema.Struct({
468 state: Schema.OptionFromNullOr(state),
469 cursor: Schema.Number.check(Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)),
470 });