The best way to control Claude Code, Codex and more from any computer or phone
| 1 | // Alchemy modifications are licensed under Apache-2.0. |
| 2 | // This file includes third-party code; see /THIRD_PARTY_LICENSES.md. |
| 3 | // Alchemy modifications: uses Effect Schema instead of Zod, preserving strict option validation. |
| 4 | import { RpcTarget } from "cloudflare:workers"; |
| 5 | import * as Result from "effect/Result"; |
| 6 | import * as Schema from "effect/Schema"; |
| 7 | import { ms } from "itty-time"; |
| 8 | import type { ResolvedStepConfig } from "./context.ts"; |
| 9 | |
| 10 | const WorkflowSubscriptionEventCommonSchema = Schema.Struct({ |
| 11 | instanceId: Schema.String, |
| 12 | eventId: Schema.Number.check(Schema.isFinite()), |
| 13 | timestamp: Schema.Number.check(Schema.isFinite()), |
| 14 | }); |
| 15 | const StepDurationSchema = Schema.declare<ResolvedStepConfig["timeout"]>( |
| 16 | (value): value is ResolvedStepConfig["timeout"] => |
| 17 | typeof value === "number" || (typeof value === "string" && !Number.isNaN(ms(value))), |
| 18 | ); |
| 19 | const ResolvedStepDelaySchema = Schema.Union([StepDurationSchema, Schema.Literal("[dynamic]")]); |
| 20 | const ResolvedStepConfigSchema = Schema.Struct({ |
| 21 | retries: Schema.Struct({ |
| 22 | limit: Schema.declare<number>( |
| 23 | (value): value is number => |
| 24 | typeof value === "number" && (Number.isFinite(value) || value === Infinity), |
| 25 | ), |
| 26 | delay: ResolvedStepDelaySchema, |
| 27 | backoff: Schema.optional(Schema.Literals(["constant", "linear", "exponential"])), |
| 28 | }), |
| 29 | timeout: StepDurationSchema, |
| 30 | sensitive: Schema.optional(Schema.Literal("output")), |
| 31 | }); |
| 32 | |
| 33 | /** |
| 34 | * Parses a resolved step config read from persisted local Workflow state. |
| 35 | * |
| 36 | * @param value Persisted value to parse. |
| 37 | * @returns The resolved config, or `undefined` when the value is invalid. |
| 38 | */ |
| 39 | export function parseResolvedStepConfig(value: unknown) { |
| 40 | const result = Schema.decodeUnknownResult(ResolvedStepConfigSchema)(value); |
| 41 | return Result.isSuccess(result) ? result.success : undefined; |
| 42 | } |
| 43 | const WorkflowSubscriptionEventSchema = Schema.Union([ |
| 44 | Schema.Struct({ |
| 45 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 46 | type: Schema.Literal("workflow_queued"), |
| 47 | }), |
| 48 | Schema.Struct({ |
| 49 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 50 | type: Schema.Literal("workflow_started"), |
| 51 | params: Schema.optional(Schema.Unknown), |
| 52 | }), |
| 53 | Schema.Struct({ |
| 54 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 55 | type: Schema.Literal("workflow_running"), |
| 56 | }), |
| 57 | Schema.Struct({ |
| 58 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 59 | type: Schema.Literal("workflow_paused"), |
| 60 | }), |
| 61 | Schema.Struct({ |
| 62 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 63 | type: Schema.Literal("workflow_waiting_for_pause"), |
| 64 | }), |
| 65 | Schema.Struct({ |
| 66 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 67 | type: Schema.Literal("workflow_waiting"), |
| 68 | }), |
| 69 | Schema.Struct({ |
| 70 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 71 | type: Schema.Literal("workflow_completed"), |
| 72 | output: Schema.optional(Schema.Unknown), |
| 73 | }), |
| 74 | Schema.Struct({ |
| 75 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 76 | type: Schema.Literal("workflow_errored"), |
| 77 | error: Schema.Struct({ name: Schema.String, message: Schema.String }), |
| 78 | }), |
| 79 | Schema.Struct({ |
| 80 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 81 | type: Schema.Literal("workflow_terminated"), |
| 82 | }), |
| 83 | Schema.Struct({ |
| 84 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 85 | type: Schema.Literal("step_started"), |
| 86 | stepName: Schema.String, |
| 87 | config: Schema.optional(ResolvedStepConfigSchema), |
| 88 | }), |
| 89 | Schema.Struct({ |
| 90 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 91 | type: Schema.Literal("step_completed"), |
| 92 | stepName: Schema.String, |
| 93 | output: Schema.optional(Schema.Unknown), |
| 94 | }), |
| 95 | Schema.Struct({ |
| 96 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 97 | type: Schema.Literal("step_errored"), |
| 98 | stepName: Schema.String, |
| 99 | }), |
| 100 | Schema.Struct({ |
| 101 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 102 | type: Schema.Literal("attempt_started"), |
| 103 | stepName: Schema.String, |
| 104 | attempt: Schema.Number.check(Schema.isFinite()), |
| 105 | }), |
| 106 | Schema.Struct({ |
| 107 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 108 | type: Schema.Literal("attempt_completed"), |
| 109 | stepName: Schema.String, |
| 110 | attempt: Schema.Number.check(Schema.isFinite()), |
| 111 | }), |
| 112 | Schema.Struct({ |
| 113 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 114 | type: Schema.Literal("attempt_errored"), |
| 115 | stepName: Schema.String, |
| 116 | attempt: Schema.Number.check(Schema.isFinite()), |
| 117 | retryDelayMs: Schema.optional(Schema.Number.check(Schema.isFinite())), |
| 118 | error: Schema.Struct({ name: Schema.String, message: Schema.String }), |
| 119 | }), |
| 120 | Schema.Struct({ |
| 121 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 122 | type: Schema.Literal("sleep_started"), |
| 123 | stepName: Schema.String, |
| 124 | durationMs: Schema.Number.check(Schema.isFinite()), |
| 125 | }), |
| 126 | Schema.Struct({ |
| 127 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 128 | type: Schema.Literal("sleep_completed"), |
| 129 | stepName: Schema.String, |
| 130 | }), |
| 131 | Schema.Struct({ |
| 132 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 133 | type: Schema.Literal("wait_started"), |
| 134 | stepName: Schema.String, |
| 135 | eventType: Schema.String, |
| 136 | }), |
| 137 | Schema.Struct({ |
| 138 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 139 | type: Schema.Literal("wait_completed"), |
| 140 | stepName: Schema.String, |
| 141 | }), |
| 142 | Schema.Struct({ |
| 143 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 144 | type: Schema.Literal("wait_timed_out"), |
| 145 | stepName: Schema.String, |
| 146 | }), |
| 147 | Schema.Struct({ |
| 148 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 149 | type: Schema.Literal("rollback_started"), |
| 150 | }), |
| 151 | Schema.Struct({ |
| 152 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 153 | type: Schema.Literal("rollback_step_started"), |
| 154 | stepName: Schema.String, |
| 155 | config: Schema.optional(ResolvedStepConfigSchema), |
| 156 | }), |
| 157 | Schema.Struct({ |
| 158 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 159 | type: Schema.Literal("rollback_step_completed"), |
| 160 | stepName: Schema.String, |
| 161 | }), |
| 162 | Schema.Struct({ |
| 163 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 164 | type: Schema.Literal("rollback_step_errored"), |
| 165 | stepName: Schema.String, |
| 166 | error: Schema.Struct({ name: Schema.String, message: Schema.String }), |
| 167 | }), |
| 168 | Schema.Struct({ |
| 169 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 170 | type: Schema.Literal("rollback_attempt_started"), |
| 171 | stepName: Schema.String, |
| 172 | attempt: Schema.Number.check(Schema.isFinite()), |
| 173 | }), |
| 174 | Schema.Struct({ |
| 175 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 176 | type: Schema.Literal("rollback_attempt_completed"), |
| 177 | stepName: Schema.String, |
| 178 | attempt: Schema.Number.check(Schema.isFinite()), |
| 179 | }), |
| 180 | Schema.Struct({ |
| 181 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 182 | type: Schema.Literal("rollback_attempt_errored"), |
| 183 | stepName: Schema.String, |
| 184 | attempt: Schema.Number.check(Schema.isFinite()), |
| 185 | retryDelayMs: Schema.optional(Schema.Number.check(Schema.isFinite())), |
| 186 | error: Schema.Struct({ name: Schema.String, message: Schema.String }), |
| 187 | }), |
| 188 | Schema.Struct({ |
| 189 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 190 | type: Schema.Literal("rollback_completed"), |
| 191 | }), |
| 192 | Schema.Struct({ |
| 193 | ...WorkflowSubscriptionEventCommonSchema.fields, |
| 194 | type: Schema.Literal("rollback_errored"), |
| 195 | }), |
| 196 | ]); |
| 197 | |
| 198 | export type WorkflowSubscriptionEvent = typeof WorkflowSubscriptionEventSchema.Type; |
| 199 | |
| 200 | const workflowSubscriptionEventTypeNames = new Set( |
| 201 | WorkflowSubscriptionEventSchema.members.map((option) => option.fields.type.literal), |
| 202 | ); |
| 203 | const WorkflowSubscriptionEventTypeSchema = Schema.declare<WorkflowSubscriptionEvent["type"]>( |
| 204 | (value): value is WorkflowSubscriptionEvent["type"] => |
| 205 | typeof value === "string" && |
| 206 | workflowSubscriptionEventTypeNames.has(value as WorkflowSubscriptionEvent["type"]), |
| 207 | ); |
| 208 | |
| 209 | export type WorkflowSubscriptionOptions = { |
| 210 | cursor?: number; |
| 211 | filter?: Array<WorkflowSubscriptionEvent["type"]>; |
| 212 | }; |
| 213 | |
| 214 | const WORKFLOW_SUBSCRIPTION_OPTIONS_SCHEMA = Schema.Struct({ |
| 215 | cursor: Schema.optional( |
| 216 | Schema.Number.check(Schema.isFinite(), Schema.isInt(), Schema.isGreaterThanOrEqualTo(0)), |
| 217 | ), |
| 218 | filter: WorkflowSubscriptionEventTypeSchema.pipe(Schema.Array, Schema.mutable, Schema.optional), |
| 219 | }); |
| 220 | |
| 221 | export function parseWorkflowSubscriptionOptions(options: unknown) { |
| 222 | if (options === undefined) { |
| 223 | return {} satisfies WorkflowSubscriptionOptions; |
| 224 | } |
| 225 | |
| 226 | const parsed = Schema.decodeUnknownResult(WORKFLOW_SUBSCRIPTION_OPTIONS_SCHEMA)(options, { |
| 227 | onExcessProperty: "error", |
| 228 | }); |
| 229 | if (Result.isFailure(parsed)) { |
| 230 | throw new Error("Invalid Workflow subscription options"); |
| 231 | } |
| 232 | |
| 233 | return parsed.success satisfies WorkflowSubscriptionOptions; |
| 234 | } |
| 235 | |
| 236 | export type WorkflowSubscriptionState = { |
| 237 | instanceId: string; |
| 238 | params: unknown; |
| 239 | lastEventId: number; |
| 240 | filter: ReadonlySet<WorkflowSubscriptionEvent["type"]> | undefined; |
| 241 | waiter: { resolve: () => void } | undefined; |
| 242 | closed: boolean; |
| 243 | }; |
| 244 | |
| 245 | export interface WorkflowSubscription extends Disposable { |
| 246 | next(): Promise<IteratorResult<WorkflowSubscriptionEvent, undefined>>; |
| 247 | } |
| 248 | |
| 249 | export function isTerminalEvent(event: WorkflowSubscriptionEvent): boolean { |
| 250 | return ( |
| 251 | event.type === "workflow_completed" || |
| 252 | event.type === "workflow_errored" || |
| 253 | event.type === "workflow_terminated" |
| 254 | ); |
| 255 | } |
| 256 | |
| 257 | export class WorkflowSubscriptionTarget extends RpcTarget implements WorkflowSubscription { |
| 258 | readonly #nextEvent: () => Promise<IteratorResult<WorkflowSubscriptionEvent, undefined>>; |
| 259 | readonly #onClose: () => void; |
| 260 | #nextRequest = Promise.resolve<unknown>(undefined); |
| 261 | #closed = false; |
| 262 | |
| 263 | constructor( |
| 264 | nextEvent: () => Promise<IteratorResult<WorkflowSubscriptionEvent, undefined>>, |
| 265 | onClose: () => void, |
| 266 | ) { |
| 267 | super(); |
| 268 | this.#nextEvent = nextEvent; |
| 269 | this.#onClose = onClose; |
| 270 | } |
| 271 | |
| 272 | async next(): Promise<IteratorResult<WorkflowSubscriptionEvent, undefined>> { |
| 273 | if (this.#closed) { |
| 274 | return { done: true, value: undefined }; |
| 275 | } |
| 276 | |
| 277 | const request = this.#nextRequest.then(async () => { |
| 278 | if (this.#closed) { |
| 279 | return { done: true, value: undefined } as const; |
| 280 | } |
| 281 | |
| 282 | try { |
| 283 | const result = await this.#nextEvent(); |
| 284 | if (this.#closed) { |
| 285 | return { done: true, value: undefined } as const; |
| 286 | } |
| 287 | if (result.done || isTerminalEvent(result.value)) { |
| 288 | this.#finish(); |
| 289 | } |
| 290 | return result; |
| 291 | } catch (error) { |
| 292 | this.#finish(); |
| 293 | throw error; |
| 294 | } |
| 295 | }); |
| 296 | this.#nextRequest = request; |
| 297 | return request; |
| 298 | } |
| 299 | |
| 300 | [Symbol.dispose](): void { |
| 301 | this.#finish(); |
| 302 | } |
| 303 | |
| 304 | #finish(): void { |
| 305 | if (this.#closed) { |
| 306 | return; |
| 307 | } |
| 308 | this.#closed = true; |
| 309 | this.#onClose(); |
| 310 | } |
| 311 | } |