The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Context from "effect/Context"; |
| 2 | import * as Effect from "effect/Effect"; |
| 3 | import * as Exit from "effect/Exit"; |
| 4 | import * as Layer from "effect/Layer"; |
| 5 | import * as Option from "effect/Option"; |
| 6 | import * as Schedule from "effect/Schedule"; |
| 7 | import type * as Schema from "effect/Schema"; |
| 8 | import { type DurableDeferred, type Workflow, WorkflowEngine } from "effect/workflow"; |
| 9 | import type { RuntimeContext } from "./RuntimeContext.ts"; |
| 10 | |
| 11 | declare const ImplementedTypeId: unique symbol; |
| 12 | |
| 13 | /** |
| 14 | * Annotates a workflow with the name an engine stores its runs under, when |
| 15 | * that differs from the workflow's own name. An engine that names storage |
| 16 | * after the workflow, like Cloudflare's Durable Object engine with one class |
| 17 | * per workflow, uses it as given. |
| 18 | */ |
| 19 | export class StorageName extends Context.Service<StorageName, string>()( |
| 20 | "alchemy/Workflows/StorageName", |
| 21 | ) {} |
| 22 | |
| 23 | /** |
| 24 | * Marks a workflow as runnable here: something in the context implements it. |
| 25 | * `Workflows.layer` provides it for the workflow it implements, and a remote |
| 26 | * engine, like `AWS.Lambda.DurableFunctionEngine`, for the workflows its |
| 27 | * hosts run. `Workflows.RunWorkflow` requires it, so running a workflow |
| 28 | * nothing implements is a type error. |
| 29 | */ |
| 30 | export interface Implemented<Name extends string> { |
| 31 | readonly [ImplementedTypeId]: Name; |
| 32 | } |
| 33 | |
| 34 | /** @internal */ |
| 35 | export const Implemented = <Name extends string>(name: Name) => |
| 36 | Context.Service<Implemented<Name>, true>(`alchemy/Workflows/Implemented/${name}`); |
| 37 | |
| 38 | /** @internal */ |
| 39 | export const implemented = <Name extends string>( |
| 40 | names: ReadonlyArray<Name>, |
| 41 | ): Layer.Layer<Implemented<Name>> => |
| 42 | Layer.succeedContext( |
| 43 | names.reduce( |
| 44 | (context, name) => Context.add(context, Implemented(name), true), |
| 45 | Context.empty() as Context.Context<Implemented<Name>>, |
| 46 | ), |
| 47 | ); |
| 48 | |
| 49 | type Requirements<L> = L extends Layer.Layer<any, any, infer R> ? R : never; |
| 50 | |
| 51 | /** A workflow's handler: runs it for a payload, inside a run. */ |
| 52 | export type Execute< |
| 53 | Payload extends Workflow.AnyStructSchema, |
| 54 | Success extends Schema.Top, |
| 55 | Error extends Schema.Top, |
| 56 | R, |
| 57 | > = ( |
| 58 | payload: Payload["Type"], |
| 59 | executionId: string, |
| 60 | ) => Effect.Effect<Success["Type"], Error["Type"], R>; |
| 61 | |
| 62 | /** |
| 63 | * Implement a workflow. Like `workflow.toLayer(execute)`, it registers the |
| 64 | * handler with the engine, and it marks the workflow as implemented, so |
| 65 | * `RunWorkflow` can run it. |
| 66 | * |
| 67 | * Pass the handler, or an Effect that builds it. The Effect runs once, when |
| 68 | * the Layer is built, so resolve bindings and services there and use them in |
| 69 | * the handler it returns. |
| 70 | * |
| 71 | * Handlers can call runtime-only APIs, like a bucket's `put` or another |
| 72 | * Durable Object's methods. A runtime-only API requires `RuntimeContext`, |
| 73 | * which a Worker's or Lambda function's init doesn't have. A handler only |
| 74 | * runs inside a run, and every run has one, so this Layer doesn't ask for it. |
| 75 | * |
| 76 | * ### Implementing a workflow |
| 77 | * **Example:** A handler |
| 78 | * ```typescript |
| 79 | * import * as Workflows from "alchemy/Workflows"; |
| 80 | * import * as Effect from "effect/Effect"; |
| 81 | * import { Activity } from "effect/workflow"; |
| 82 | * |
| 83 | * export const GreetLive = Workflows.layer( |
| 84 | * Greet, |
| 85 | * Effect.fn(function* ({ name }) { |
| 86 | * return yield* Activity.make({ |
| 87 | * name: "greet", |
| 88 | * success: Schema.String, |
| 89 | * execute: Effect.succeed(`hello ${name}`), |
| 90 | * }); |
| 91 | * }), |
| 92 | * ); |
| 93 | * ``` |
| 94 | * |
| 95 | * **Example:** A handler that uses a binding |
| 96 | * ```typescript |
| 97 | * import * as Cloudflare from "@alchemy.run/cloudflare"; |
| 98 | * import * as Workflows from "alchemy/Workflows"; |
| 99 | * import * as Effect from "effect/Effect"; |
| 100 | * import { Activity } from "effect/workflow"; |
| 101 | * import { Receipts } from "./Receipts.ts"; |
| 102 | * |
| 103 | * export const CheckoutLive = Workflows.layer( |
| 104 | * Checkout, |
| 105 | * Effect.gen(function* () { |
| 106 | * const receipts = yield* Cloudflare.R2.WriteBucket(Receipts); |
| 107 | * return Effect.fn(function* ({ orderId }) { |
| 108 | * yield* Activity.make({ |
| 109 | * name: "receipt", |
| 110 | * execute: receipts.put(`${orderId}.json`, JSON.stringify({ orderId })).pipe(Effect.orDie), |
| 111 | * }); |
| 112 | * }); |
| 113 | * }), |
| 114 | * ); |
| 115 | * ``` |
| 116 | * |
| 117 | * @primitive |
| 118 | */ |
| 119 | export function layer< |
| 120 | Name extends string, |
| 121 | Payload extends Workflow.AnyStructSchema, |
| 122 | Success extends Schema.Top, |
| 123 | Error extends Schema.Top, |
| 124 | R, |
| 125 | >( |
| 126 | workflow: Workflow.Workflow<Name, Payload, Success, Error>, |
| 127 | execute: Execute<Payload, Success, Error, R>, |
| 128 | ): Layer.Layer< |
| 129 | Implemented<Name>, |
| 130 | never, |
| 131 | Exclude<Requirements<ReturnType<typeof workflow.toLayer<R>>>, RuntimeContext> |
| 132 | >; |
| 133 | export function layer< |
| 134 | Name extends string, |
| 135 | Payload extends Workflow.AnyStructSchema, |
| 136 | Success extends Schema.Top, |
| 137 | Error extends Schema.Top, |
| 138 | R, |
| 139 | InitE, |
| 140 | InitR, |
| 141 | >( |
| 142 | workflow: Workflow.Workflow<Name, Payload, Success, Error>, |
| 143 | make: Effect.Effect<Execute<Payload, Success, Error, R>, InitE, InitR>, |
| 144 | ): Layer.Layer< |
| 145 | Implemented<Name>, |
| 146 | InitE, |
| 147 | // oxlint-disable-next-line typescript/no-redundant-type-constituents -- generic in R; only looks like `never` to the linter |
| 148 | InitR | Exclude<Requirements<ReturnType<typeof workflow.toLayer<R>>>, RuntimeContext> |
| 149 | >; |
| 150 | export function layer( |
| 151 | workflow: Workflow.Workflow<string, Workflow.AnyStructSchema, Schema.Top, Schema.Top>, |
| 152 | execute: |
| 153 | | Execute<Workflow.AnyStructSchema, Schema.Top, Schema.Top, unknown> |
| 154 | | Effect.Effect< |
| 155 | Execute<Workflow.AnyStructSchema, Schema.Top, Schema.Top, unknown>, |
| 156 | unknown, |
| 157 | unknown |
| 158 | >, |
| 159 | ): Layer.Layer<any, any, any> { |
| 160 | return Effect.isEffect(execute) |
| 161 | ? Layer.unwrap(Effect.map(execute, (handler) => layer(workflow, handler))) |
| 162 | : Layer.merge( |
| 163 | workflow.toLayer(execute as any) as Layer.Layer<never, never, any>, |
| 164 | implemented([workflow._tag]), |
| 165 | ); |
| 166 | } |
| 167 | |
| 168 | type NameOf<W> = W extends Workflow.Workflow<infer Name, any, any, any> ? Name : never; |
| 169 | type SuccessOf<W> = W extends Workflow.Workflow<any, any, infer S, any> ? S["Type"] : never; |
| 170 | type ErrorOf<W> = W extends Workflow.Workflow<any, any, any, infer E> ? E["Type"] : never; |
| 171 | type PayloadOf<W> = |
| 172 | W extends Workflow.Workflow<any, infer P, any, any> ? P["~type.make.in"] : never; |
| 173 | |
| 174 | /** Where a run is. */ |
| 175 | export type Status<A, E> = |
| 176 | | { readonly _tag: "NotStarted" } |
| 177 | | { readonly _tag: "Running" } |
| 178 | | { readonly _tag: "Completed"; readonly result: A } |
| 179 | | { readonly _tag: "Failed"; readonly error: E } |
| 180 | | { readonly _tag: "Interrupted" } |
| 181 | | { readonly _tag: "Died"; readonly defect: unknown }; |
| 182 | |
| 183 | /** One run of a workflow. */ |
| 184 | export interface Run<A, E> { |
| 185 | /** The run's id. Store it to read the run again later, with `get`. */ |
| 186 | readonly executionId: string; |
| 187 | /** Where the run is now. */ |
| 188 | readonly status: Effect.Effect<Status<A, E>>; |
| 189 | /** |
| 190 | * Wait for the run to finish: its result, or its failure. A run can take |
| 191 | * days, so wait in tests and scripts, not in a request. |
| 192 | */ |
| 193 | readonly result: Effect.Effect<A, E>; |
| 194 | /** Complete a `DurableDeferred` the run waits on. */ |
| 195 | readonly signal: <Success extends Schema.Constraint>( |
| 196 | deferred: DurableDeferred.DurableDeferred<Success, any>, |
| 197 | value: Success["Type"], |
| 198 | ) => Effect.Effect<void>; |
| 199 | /** Stop the run: it fails where it waits, and its compensations run. */ |
| 200 | readonly interrupt: Effect.Effect<void>; |
| 201 | } |
| 202 | |
| 203 | /** Starts and reads runs of one workflow. */ |
| 204 | export interface WorkflowClient<W> { |
| 205 | /** Start a run, or return the run already started with the same key. Returns at once. */ |
| 206 | readonly start: (payload: PayloadOf<W>) => Effect.Effect<Run<SuccessOf<W>, ErrorOf<W>>>; |
| 207 | /** A run started earlier, by its id. */ |
| 208 | readonly get: (executionId: string) => Run<SuccessOf<W>, ErrorOf<W>>; |
| 209 | } |
| 210 | |
| 211 | /** How often to check a run while waiting for it. */ |
| 212 | const POLL = Schedule.min([Schedule.exponential("100 millis"), Schedule.spaced("5 seconds")]); |
| 213 | |
| 214 | /** |
| 215 | * Start and read runs of a workflow, on whichever engine the runtime |
| 216 | * provides. Resolve it once, during init; its methods need nothing else. |
| 217 | * |
| 218 | * It needs the workflow implemented: by `Workflows.layer` in the same |
| 219 | * runtime, or by a host a remote engine routes to. Running a workflow nothing |
| 220 | * implements is a type error. |
| 221 | * |
| 222 | * ### Running a workflow |
| 223 | * **Example:** Start a run from a request |
| 224 | * ```typescript |
| 225 | * import * as Workflows from "alchemy/Workflows"; |
| 226 | * import * as Effect from "effect/Effect"; |
| 227 | * import * as HttpServerResponse from "effect/http/HttpServerResponse"; |
| 228 | * |
| 229 | * const app = Effect.gen(function* () { |
| 230 | * const greet = yield* Workflows.RunWorkflow(Greet); |
| 231 | * return { |
| 232 | * fetch: Effect.gen(function* () { |
| 233 | * const run = yield* greet.start({ name: "sam" }); |
| 234 | * return HttpServerResponse.text(run.executionId); |
| 235 | * }), |
| 236 | * }; |
| 237 | * }); |
| 238 | * ``` |
| 239 | * |
| 240 | * **Example:** Read a run later |
| 241 | * ```typescript |
| 242 | * const run = greet.get(executionId); |
| 243 | * const status = yield* run.status; |
| 244 | * yield* run.signal(Approval, "agent-7"); |
| 245 | * ``` |
| 246 | * |
| 247 | * @primitive |
| 248 | */ |
| 249 | export const RunWorkflow = <W extends Workflow.Any>( |
| 250 | workflow: W, |
| 251 | ): Effect.Effect< |
| 252 | WorkflowClient<W>, |
| 253 | never, |
| 254 | WorkflowEngine.WorkflowEngine | Implemented<NameOf<W>> |
| 255 | > => |
| 256 | Effect.gen(function* () { |
| 257 | const engine = yield* WorkflowEngine.WorkflowEngine; |
| 258 | const typed = workflow as unknown as Workflow.Workflow<string, any, any, any>; |
| 259 | const run = (executionId: string) => |
| 260 | makeRun(engine, typed, executionId) as Run<SuccessOf<W>, ErrorOf<W>>; |
| 261 | return { |
| 262 | start: (payload) => |
| 263 | typed |
| 264 | .execute(payload, { discard: true }) |
| 265 | .pipe( |
| 266 | Effect.provideService(WorkflowEngine.WorkflowEngine, engine), |
| 267 | Effect.map(run), |
| 268 | ) as Effect.Effect<Run<SuccessOf<W>, ErrorOf<W>>>, |
| 269 | get: run, |
| 270 | } satisfies WorkflowClient<W>; |
| 271 | }); |
| 272 | |
| 273 | /** |
| 274 | * A handle to one run of a workflow on an engine. |
| 275 | * |
| 276 | * @internal |
| 277 | */ |
| 278 | export const makeRun = ( |
| 279 | engine: WorkflowEngine.WorkflowEngine["Service"], |
| 280 | workflow: Workflow.Workflow<string, any, any, any>, |
| 281 | executionId: string, |
| 282 | ): Run<unknown, unknown> => { |
| 283 | const poll = engine.poll(workflow, executionId); |
| 284 | return { |
| 285 | executionId, |
| 286 | status: Effect.map(poll, (result): Status<unknown, unknown> => { |
| 287 | if (Option.isNone(result)) return { _tag: "NotStarted" }; |
| 288 | if (result.value._tag === "Suspended") return { _tag: "Running" }; |
| 289 | const exit = result.value.exit; |
| 290 | if (Exit.isSuccess(exit)) return { _tag: "Completed", result: exit.value }; |
| 291 | const failure = exit.cause.reasons.find((reason) => reason._tag === "Fail"); |
| 292 | if (failure?._tag === "Fail") return { _tag: "Failed", error: failure.error }; |
| 293 | const defect = exit.cause.reasons.find((reason) => reason._tag === "Die"); |
| 294 | return defect?._tag === "Die" |
| 295 | ? { _tag: "Died", defect: defect.defect } |
| 296 | : { _tag: "Interrupted" }; |
| 297 | }) as Effect.Effect<Status<unknown, unknown>>, |
| 298 | result: poll.pipe( |
| 299 | Effect.flatMap((result) => |
| 300 | Option.isSome(result) && result.value._tag === "Complete" |
| 301 | ? Effect.succeed(result.value.exit) |
| 302 | : Effect.fail("running" as const), |
| 303 | ), |
| 304 | Effect.retry({ schedule: POLL }), |
| 305 | Effect.orDie, |
| 306 | Effect.flatten, |
| 307 | ) as Effect.Effect<unknown, unknown>, |
| 308 | signal: (deferred, value) => |
| 309 | engine.deferredDone(deferred, { |
| 310 | workflowName: workflow._tag, |
| 311 | executionId, |
| 312 | deferredName: deferred.name, |
| 313 | exit: Exit.succeed(value), |
| 314 | }) as Effect.Effect<void>, |
| 315 | interrupt: engine.interrupt(workflow, executionId), |
| 316 | }; |
| 317 | }; |