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

main
ts 229 lines 9.08 KB
Raw
1 import { CurrentActivity, makeCurrentActivity } from "alchemy/WorkflowEncoding";
2 import * as Duration from "effect/Duration";
3 import * as Effect from "effect/Effect";
4 import * as Exit from "effect/Exit";
5 import * as Fiber from "effect/Fiber";
6 import * as Layer from "effect/Layer";
7 import * as Option from "effect/Option";
8 import * as Semaphore from "effect/Semaphore";
9 import { Workflow, WorkflowEngine } from "effect/workflow";
10
11 /**
12 * What the in-memory platform gives its workflow engine: its clock, its work
13 * queue, and its timers. Runs and clocks go through these, so a story's
14 * `drain` runs sagas to where they wait, and moving its clock fires their sleeps.
15 */
16 export interface Host {
17 readonly now: () => number;
18 /** Queue a run; it runs in the background, counted as running until it finishes. */
19 readonly enqueue: (run: Effect.Effect<void>) => Effect.Effect<void>;
20 /** Fire `fire` at `at` on the platform's clock; scheduling the same key again replaces it. */
21 readonly timer: (key: string, at: number, fire: Effect.Effect<void>) => Effect.Effect<void>;
22 /** Record a run that failed, so a story can report it. */
23 readonly failed: (cause: unknown) => void;
24 /** Record a run that ended with a defect, so a story can report it. */
25 readonly died: (workflow: string, executionId: string, defect: unknown) => void;
26 }
27
28 type Execute = (
29 payload: object,
30 executionId: string,
31 ) => Effect.Effect<
32 unknown,
33 unknown,
34 WorkflowEngine.WorkflowInstance | WorkflowEngine.WorkflowEngine
35 >;
36
37 interface Execution {
38 readonly workflow: Workflow.Any;
39 readonly payload: object;
40 readonly parent: { readonly workflow: Workflow.Any; readonly executionId: string } | undefined;
41 interrupted: boolean;
42 result: Workflow.Complete<unknown, unknown> | undefined;
43 }
44
45 /**
46 * A `WorkflowEngine` that keeps every execution's journal in memory and runs
47 * on the in-memory platform. Like the Durable Object engine, a run replays the
48 * workflow from the top and stops where it waits; the next wake-up runs it again.
49 */
50 export const make = (host: Host): WorkflowEngine.WorkflowEngine["Service"] => {
51 const handlers = new Map<string, Execute>();
52 const executions = new Map<string, Execution>();
53 const activities = new Map<string, Exit.Exit<unknown, unknown>>();
54 const deferreds = new Map<string, Exit.Exit<unknown, unknown>>();
55 const clocks = new Map<string, number>();
56
57 const keyOf = (workflowName: string, executionId: string) => `${workflowName}/${executionId}`;
58
59 // One run per execution at a time; a wake-up during a run queues the next.
60 const locks = new Map<string, Semaphore.Semaphore>();
61 const lockOf = (key: string) => {
62 let lock = locks.get(key);
63 if (!lock) locks.set(key, (lock = Semaphore.makeUnsafe(1)));
64 return lock;
65 };
66
67 const run = (key: string): Effect.Effect<void> => lockOf(key).withPermits(1)(runOnce(key));
68
69 const runOnce = (key: string): Effect.Effect<void> =>
70 Effect.suspend(() => {
71 const execution = executions.get(key);
72 if (!execution || execution.result) return Effect.void;
73 const execute = handlers.get(execution.workflow._tag)!;
74 const executionId = key.slice(execution.workflow._tag.length + 1);
75 const instance = WorkflowEngine.WorkflowInstance.initial(execution.workflow, executionId);
76 return execute(execution.payload, executionId).pipe(
77 // An interrupted execution replays to where it waits, then is
78 // interrupted there, which fails it and runs its compensations.
79 Effect.onExit(() => {
80 if (!execution.interrupted) return Effect.void;
81 instance.interrupted = true;
82 instance.suspended = false;
83 return Effect.withFiber((fiber) => fiber.pipe(Fiber.interrupt, Effect.interruptible));
84 }),
85 Workflow.intoResult,
86 Effect.provide(
87 Layer.mergeAll(
88 Layer.succeed(WorkflowEngine.WorkflowInstance, instance),
89 Layer.succeed(WorkflowEngine.WorkflowEngine, engine),
90 ),
91 ),
92 Effect.flatMap((result) => {
93 if (result._tag === "Suspended") return Effect.void;
94 execution.result = result;
95 if (Exit.isFailure(result.exit)) {
96 const reasons = result.exit.cause.reasons;
97 const defect = reasons.find((reason) => reason._tag === "Die");
98 if (defect?._tag === "Die" && !reasons.some((reason) => reason._tag === "Fail")) {
99 host.died(execution.workflow._tag, executionId, defect.defect);
100 }
101 }
102 return execution.parent
103 ? wake(keyOf(execution.parent.workflow._tag, execution.parent.executionId))
104 : Effect.void;
105 }),
106 Effect.catchCause((cause) => Effect.sync(() => host.failed(cause))),
107 );
108 });
109
110 const wake = (key: string) => host.enqueue(run(key));
111
112 const engine: WorkflowEngine.WorkflowEngine["Service"] = WorkflowEngine.makeUnsafe({
113 register: (workflow, execute) => Effect.sync(() => void handlers.set(workflow._tag, execute)),
114
115 execute: (workflow, options) =>
116 Effect.gen(function* () {
117 const key = keyOf(workflow._tag, options.executionId);
118 let execution = executions.get(key);
119 if (!execution) {
120 execution = {
121 workflow,
122 payload: options.payload,
123 parent: options.parent
124 ? { workflow: options.parent.workflow, executionId: options.parent.executionId }
125 : undefined,
126 interrupted: false,
127 result: undefined,
128 };
129 executions.set(key, execution);
130 yield* wake(key);
131 }
132 if (options.discard) return undefined;
133 return execution.result ?? Workflow.Suspended.make({});
134 }) as Effect.Effect<any>,
135
136 poll: (workflow, executionId) =>
137 Effect.sync(() => {
138 const execution = executions.get(keyOf(workflow._tag, executionId));
139 if (!execution) return Option.none();
140 return Option.some(execution.result ?? Workflow.Suspended.make({}));
141 }),
142
143 interrupt: (workflow, executionId) =>
144 Effect.suspend(() => {
145 const key = keyOf(workflow._tag, executionId);
146 const execution = executions.get(key);
147 if (!execution || execution.result) return Effect.void;
148 execution.interrupted = true;
149 return wake(key);
150 }),
151
152 interruptUnsafe: (workflow, executionId) =>
153 Effect.sync(() => {
154 const execution = executions.get(keyOf(workflow._tag, executionId));
155 if (!execution || execution.result) return;
156 execution.interrupted = true;
157 execution.result = new Workflow.Complete({ exit: Exit.interrupt() });
158 }),
159
160 resume: (workflow, executionId) => wake(keyOf(workflow._tag, executionId)),
161
162 activityExecute: (activity, attempt) =>
163 Effect.gen(function* () {
164 const instance = yield* WorkflowEngine.WorkflowInstance;
165 const key = `${keyOf(instance.workflow._tag, instance.executionId)}/${activity.name}/${attempt}`;
166 const stored = activities.get(key);
167 if (stored) return new Workflow.Complete({ exit: stored });
168 const activityInstance = WorkflowEngine.WorkflowInstance.initial(
169 instance.workflow,
170 instance.executionId,
171 );
172 activityInstance.interrupted = instance.interrupted;
173 const result = yield* activity.executeEncoded.pipe(
174 Workflow.intoResult,
175 Effect.provide(
176 Layer.mergeAll(
177 Layer.succeed(WorkflowEngine.WorkflowInstance, activityInstance),
178 Layer.succeed(
179 CurrentActivity,
180 makeCurrentActivity(instance.workflow._tag, instance.executionId, activity.name),
181 ),
182 ),
183 ),
184 );
185 if (result._tag === "Complete") activities.set(key, result.exit);
186 return result;
187 }),
188
189 deferredResult: (deferred) =>
190 Effect.gen(function* () {
191 const instance = yield* WorkflowEngine.WorkflowInstance;
192 return Option.fromNullishOr(
193 deferreds.get(`${keyOf(instance.workflow._tag, instance.executionId)}/${deferred.name}`),
194 );
195 }),
196
197 deferredDone: (options) =>
198 Effect.suspend(() => {
199 const key = keyOf(options.workflowName, options.executionId);
200 const name = `${key}/${options.deferredName}`;
201 if (deferreds.has(name)) return Effect.void;
202 deferreds.set(name, options.exit);
203 return wake(key);
204 }),
205
206 // A clock keeps the due time it was first given, however many times the
207 // run replays past `DurableClock.sleep`.
208 scheduleClock: (workflow, options) =>
209 Effect.suspend(() => {
210 const key = keyOf(workflow._tag, options.executionId);
211 const name = `${key}/${options.clock.name}`;
212 if (clocks.has(name)) return Effect.void;
213 const due = host.now() + Duration.toMillis(options.clock.duration);
214 clocks.set(name, due);
215 return host.timer(
216 name,
217 due,
218 engine.deferredDone(options.clock.deferred, {
219 workflowName: workflow._tag,
220 executionId: options.executionId,
221 deferredName: options.clock.deferred.name,
222 exit: Exit.void,
223 }),
224 );
225 }),
226 });
227
228 return engine;
229 };