import { z } from 'zod/v4'; import { SerializedDataSchema } from './serialization.js'; import { SPEC_VERSION_SINGLE_ORCHESTRATOR } from './spec-version.js'; import { StartHookSchema } from './start-hook.js'; export type QueueKind = 'workflow'; /** * Pattern matching valid queue prefixes: * - `__wkf_workflow_` (default, no namespace) * - `__{namespace}_wkf_workflow_` (namespaced) * * Namespace must be lowercase alphanumeric starting with a letter. */ export const QueuePrefix = z .string() .regex( /^__(?:[a-z][a-z0-9]*_)?wkf_workflow_$/, 'Must match __wkf_workflow_ or __{namespace}_wkf_workflow_' ); export type QueuePrefix = z.infer; export const ValidQueueName = z .string() .regex( /^__(?:[a-z][a-z0-9]*_)?wkf_workflow_.+$/, 'Must be a valid queue name with a recognized prefix' ); export type ValidQueueName = z.infer; const QueueNamespace = z .string() .regex( /^[a-z][a-z0-9]*$/, 'Must be lowercase alphanumeric, starting with a letter' ); /** * Resolves the active queue namespace from an explicit argument or the * `WORKFLOW_QUEUE_NAMESPACE` env var. */ export function resolveQueueNamespace(namespace?: string): string | undefined { return namespace ?? process.env.WORKFLOW_QUEUE_NAMESPACE ?? undefined; } /** * Builds the workflow queue topic prefix for an optional namespace. * * The literal kind argument is retained so existing workflow-only callers keep * their meaning after removal of the former `'step'` variant. * * - `getQueueTopicPrefix('workflow')` → `'__wkf_workflow_'` * - `getQueueTopicPrefix('workflow', 'custom')` → `'__custom_wkf_workflow_'` */ export function getQueueTopicPrefix( kind: QueueKind, namespace?: string ): QueuePrefix { if (kind !== 'workflow') { throw new Error(`Unsupported queue kind: ${kind}`); } if (namespace !== undefined) { QueueNamespace.parse(namespace); return `__${namespace}_wkf_workflow_` as QueuePrefix; } return '__wkf_workflow_' as QueuePrefix; } /** * The route a World that delivers over HTTP sends a prefix's messages to when * no other route or handler is registered for that prefix (see * {@link Queue.registerRoute}): the Workflow SDK's generated flow route, * relative to the app's base URL. */ export const WORKFLOW_FLOW_ROUTE = '/.well-known/workflow/v1/flow'; /** * Validates a delivery route for {@link Queue.registerRoute}: an absolute path * on the app's base URL (`/api/agent/queue`), with no query or fragment. * Returns it unchanged. */ export function parseQueueRoute(path: string): string { if ( typeof path !== 'string' || !path.startsWith('/') || path.startsWith('//') || /[?#\s]/.test(path) ) { throw new TypeError( `Invalid queue route "${String(path)}": must be an absolute path such as "/api/agent/queue", without a query or fragment` ); } return path; } /** * The queue namespace a run's messages travel on, as recorded when the run was * created (`executionContext.queueNamespace`), or `undefined` when it recorded * none (or an invalid one), in which case the World's default namespace * applies. A World uses this to re-enqueue a run to its own consumer (see * `reenqueueActiveRuns`) rather than to the recovering process's prefix. */ export function getRunQueueNamespace( executionContext: unknown ): string | undefined { if ( typeof executionContext !== 'object' || executionContext === null || executionContext instanceof Uint8Array ) { return undefined; } const namespace = (executionContext as { queueNamespace?: unknown }) .queueNamespace; return typeof namespace === 'string' && QueueNamespace.safeParse(namespace).success ? namespace : undefined; } export function parseQueueName(name: ValidQueueName): { prefix: QueuePrefix; id: string; } { const match = name.match(/^(__(?:[a-z][a-z0-9]*_)?wkf_workflow_)(.+)$/); if (!match) { throw new Error(`Invalid queue name: ${name}`); } return { prefix: QueuePrefix.parse(match[1]), id: match[2], }; } export const MessageId = z .string() .brand<'MessageId'>() .describe('A stored queue message ID'); export type MessageId = z.infer; /** * OpenTelemetry trace context for distributed tracing */ export const TraceCarrierSchema = z.record(z.string(), z.string()); export type TraceCarrier = z.infer; /** * Run creation data carried through the queue for resilient start. * Only present on the first queue delivery: re-enqueues omit this. * When the runtime processes the message, it passes this data to the * run_started event so the server can create the run if it doesn't exist yet. */ export const RunInputSchema = z .object({ input: z.unknown(), deploymentId: z.string(), workflowName: z.string(), specVersion: z.number(), executionContext: z.record(z.string(), z.any()).optional(), /** Dynamic workflow code carried for resilient run creation. */ dynamicWorkflowCode: SerializedDataSchema.optional(), /** Ref for deferred dynamic workflow code; mutually exclusive with bytes. */ dynamicWorkflowCodeRef: z.string().optional(), /** Initial plaintext run attributes, for resilient run creation. */ attributes: z.record(z.string(), z.string()).optional(), /** * Permits reserved `$`-prefixed keys in `attributes`, mirrored from the * `start()` option so resilient run creation validates the same way as * the original `run_created` attempt. */ allowReservedAttributes: z.literal(true).optional(), /** * The run's X25519 public key, mirrored from `run_created` so a run the * resilient-start path creates can still receive sealed writes. */ encryptionPublicKey: z.string().optional(), /** * The atomic start Hook request, mirrored from `run_created` so the * queued copy of the candidate can admit (or be refused) on its own. * See `start-hook.ts`. */ startHook: StartHookSchema.optional(), /** * The environment the creating client's writes are attributed to, as * reported by {@link World.getEnvironment} at `start()` time (on Vercel: * `'production' | 'preview' | 'development'`). * * This exists so the resilient-start path can be checked for a tenant * mismatch. `start()` writes `run_created` under the caller's own * credentials while pinning the queue message to a deployment, and those * two can disagree: if the message is consumed by a deployment in a * DIFFERENT environment, that consumer's `run_started` re-creates the run * under ITS tenant, so the same client-minted `wrun_` id ends up existing * in two environments: one stuck pending forever, the other executing. * Carrying the creator's environment lets the consumer compare it against * its own and refuse the delivery instead of forking the run. * * Absent for worlds with no environment dimension (local, Postgres), and * for older SDKs. Consumers must treat it as advisory and skip the check * when it is missing. */ environment: z.string().optional(), }) .refine( (value) => value.dynamicWorkflowCode === undefined || value.dynamicWorkflowCodeRef === undefined, { path: ['dynamicWorkflowCodeRef'], message: 'dynamicWorkflowCode and dynamicWorkflowCodeRef are mutually exclusive', } ); export type RunInput = z.infer; /** * Legacy lazy hook resume data carried through the queue alongside a workflow * invocation. Older producers publish this invocation and write no event of * their own. On receipt, a consumer that understands `hookInput` idempotently * ensures the `hook_received` event exists (keyed by `resumeId`) before * replaying, so repeated deliveries converge on exactly one event. * * The `payload` is the already-serialized (and possibly encrypted) resume * payload, and on this path the queue message is its only carrier. Every write * derived from this message therefore hashes to the same digest under the * `(runId, resumeId)` constraint. */ /** * Resilient step dispatch data carried through the queue alongside a * step-execution message ({@link WorkflowInvokePayload.stepId}). Present when * the producer (the suspension handler dispatching a newly created step) * parallelized the `step_created` event write with the queue publish: the * same shape as resilient start (`runInput`) and the resilient hook resume * (`hookInput`). * * When the producer's `step_created` write fails transiently (429 / 5xx / * transport), the step entity may not exist when this message is consumed. A * consumer that understands `stepInput` idempotently re-ensures the * `step_created` event, keyed by the message's `stepId` (the step's * correlation id, unique per `(runId, correlationId)`), before executing, so * the producer's write and the consumer's re-ensure converge on exactly one * event. * * The `input` is the already-serialized (and possibly encrypted) step input: * the identical bytes the producer also sent on the direct `events.create`. * * The current `@workflow/core` runtime neither attaches nor reads this field: * it publishes a step message only after its `step_created` write. The schema * keeps accepting it so a message that carries it still parses. */ export const StepDispatchInputSchema = z.object({ /** * The serialized step input, reused verbatim from the direct write. Always * binary: producers only attach `stepInput` when the dehydrated input is a * `Uint8Array` and the run's queue transport preserves bytes (CBOR). * Validated here so a malformed or transport-mangled payload fails the * message parse instead of being silently written into a `step_created` as * non-binary data. `Buffer` is a `Uint8Array` subclass and passes. */ input: z.custom((value) => value instanceof Uint8Array, { message: 'stepInput.input must be a Uint8Array', }), }); export type StepDispatchInput = z.infer; /** * Immutable run identity carried on a step-execution message so the consumer * can start the step without a blocking `runs.get` round trip. Every field is * fixed for the life of a run (runs are pinned to their deployment), and the * producer holds the run row at dispatch time, so the copy can never go * stale. Run *status* is deliberately NOT carried: liveness is enforced by * the `step_started` claim itself, which the World rejects on a terminal run. * * Consumers that need the full run row for inline replay * still fetch it lazily; messages without this field (older producers) take * the legacy `runs.get` prologue. */ export const RunDispatchContextSchema = z.object({ /** The deployment the run is pinned to (`WorkflowRun.deploymentId`). */ deploymentId: z.string(), /** The run's spec version (`WorkflowRun.specVersion`). */ specVersion: z.number(), /** The run's start time as epoch ms (`WorkflowRun.startedAt`). Numeric so * it survives both queue transports without Date revival concerns. */ startedAt: z.number().optional(), /** The run's lineage root (its `$rootRunId` attribute, or its own id). */ rootRunId: z.string().optional(), }); export type RunDispatchContext = z.infer; export const HookResumeInputSchema = z.object({ /** Stable idempotency key minted once per `resumeHook()` call. */ resumeId: z.string(), /** The hook being resumed. */ hookId: z.string(), /** * The hook's token, written into the `hook_received` event's `eventData` so * the consumer's re-ensured event carries the same token the producer * would. Replay validates `eventData.token` against the `createHook` token. */ token: z.string(), /** The serialized resume payload, reused verbatim from the direct write. */ payload: z.unknown(), /** * Content digest of `payload`, computed once by the producer over the * serialized bytes and forwarded verbatim on both the direct `events.create` * and this queue message. The consumer forwards it back to the server so both * writers of the same `resumeId` record an identical digest on the * `(runId, resumeId)` constraint, required because the v4 payload ref is not * content-stable server-side. */ payloadDigest: z.string(), /** * The deployment the run is pinned to, from the producer's resume context. * Lets the consumer detect a misrouted delivery with a cheap ambient * deployment-id comparison BEFORE its hoisted `hook_received` replay-preload * write: only a detected mismatch pays for the authoritative run fetch and * the deployment-affinity guard. Optional for queued-message compatibility: * messages from older producers omit it and skip the pre-write * check (the authoritative guard before replay still protects them). */ deploymentId: z.string().optional(), }); export type HookResumeInput = z.infer; /** * Wall-clock boundaries of a hook-triggered resume, carried on the queue * message so the SDK can report end-to-end time-to-resume (TTR, entry into * `resumeHook()` through to the first line of the next durable step) and its * non-overlapping phase breakdown, as span attributes on that step's * `step.execute` span. See `runtime/resume-latency.ts` in `@workflow/core`. * * Two groups of fields: * * - Producer fields (`resumeRequestedAtMs`, `queuePublishRequestedAtMs`, * `strategy`) are stamped by `resumeHook()` on the invocation message. They * ride along on a deployment-affinity re-route unchanged, so a misrouted * delivery's extra hop stays inside `queue_delivery`. * - Consumer fields (`consumerStartedAtMs`, `replayStartedAtMs`, * `nextStepEncounteredAtMs`, `setupSource`) are filled in by the invocation * that replayed the resume, and ONLY when it dispatches the next durable * step to a separate queue invocation instead of running it inline. They let * that invocation report the same single TTR measurement. * * Every field is advisory and the whole object is optional, in all three * directions that matter for a rolling deploy: a new producer's timing is * ignored by an old consumer, a new consumer reports no TTR for an old * message, and the world-vercel backend never reads it at all. * * `strategy` and `setupSource` are deliberately typed as plain strings rather * than enums: an unrecognized value from a newer producer must not fail the * parse of the whole invocation payload (which would wedge the run), since it * is only ever forwarded to a span attribute. */ export const HookResumeTimingSchema = z.object({ /** Epoch ms at entry into `resumeHook()`: the start of the TTR window. */ resumeRequestedAtMs: z.number(), /** Epoch ms immediately before the queue publish was requested. */ queuePublishRequestedAtMs: z.number(), /** * Which `resumeHook()` dispatch path ran. Current producers always report * `sequential` (durable write, then wake); older producers may report * `lazy` or `parallel`. */ strategy: z.string().optional(), /** Epoch ms the final consumer's queue handler was entered. */ consumerStartedAtMs: z.number().optional(), /** Epoch ms this invocation's first replay pass began. */ replayStartedAtMs: z.number().optional(), /** Epoch ms replay first encountered a durable step after the resume. */ nextStepEncounteredAtMs: z.number().optional(), /** How the consumer initialized replay state: see `ResumeSetupSource`. */ setupSource: z.string().optional(), }); export type HookResumeTiming = z.infer; export const WorkflowInvokePayloadSchema = z.object({ runId: z.string(), /** * The run's persisted spec version (`WorkflowRun.specVersion`), which picks * the orchestrator that drives it. A routing hint only: a message without * it (from a producer that predates the field, or one the World sends * itself) is routed off the run instead, and a step message's * `runContext` or a first delivery's `runInput` carries the same value. */ runSpecVersion: z.number().int().optional().catch(undefined), /** * Set on a message a World sent to resume a run after it lost its queue * (`reenqueueActiveRuns` with `queueLost`, world-local after a restart): * every message the run had queued, its step messages and wait timers, * died with the queue. A single-orchestrator delivery of it re-sends * every open step message and arms every open wait's timer. A consumer * that predates the field ignores it, and `.catch(undefined)` keeps a * malformed value from failing the parse. */ recovery: z.literal(true).optional().catch(undefined), /** Process this input and return the handler's result as response data. */ invoke: z.literal(true).optional(), /** Identifies one input across retries, separately from the queue delivery ID. */ requestId: z.string().optional(), input: z.unknown().optional(), traceCarrier: TraceCarrierSchema.optional(), requestedAt: z.coerce.date().optional(), /** * Consecutive replay divergences in this recovery chain and latest position * (spec <= 8 runs: a spec 9 orchestrator recovers within its delivery and * never sends it). * * `eventIds` is every divergent event id in the chain, oldest first, so the * terminal failure can say whether each recovery replay diverged at the same * event or wandered. The producer bounds it to the recovery budget plus one. * `.catch(undefined)` on the field for the reason `hookResumeTiming` has it: * a malformed history must degrade to "no history" rather than fail the * parse of every delivery of this message. A consumer that predates the * field ignores it; a producer that predates it sends none, and the consumer * restarts the history from `eventId`. */ replayDivergence: z .object({ eventId: z.string(), count: z.number().int().positive(), eventIds: z.array(z.string()).optional().catch(undefined), }) .optional(), /** * Re-invocations so far in this chain of stale-snapshot (precondition) * rejections. Counted on the message because the in-process restart budget * lives in the invocation closure and the queue's delivery count resets on * every fresh enqueue, so without this a permanently fenced run would cycle * forever instead of failing. */ preconditionReinvocations: z.number().int().positive().optional(), /** Number of times this message has been re-enqueued due to server errors (5xx) */ serverErrorRetryCount: z.number().int().optional(), /** Number of times this message has been re-routed after a deployment mismatch */ deploymentMismatchRetryCount: z.number().int().nonnegative().optional(), /** * The wait this message is the delayed continuation for, and which attempt * in that wait's chain it is. * * Present only on wait-continuation messages. It exists so the invocation a * continuation wakes can recognize itself as that continuation: if the wait * is STILL pending when it replays — the continuation arrived before its * deadline — then its own idempotency key is already spent, and re-enqueueing * under the same key is silently dropped by the world's dedupe window. The * attempt number is what makes the next key fresh, so an early delivery * costs one extra hop instead of losing the wait's timer permanently. * * Counted on the message for the same reason as * {@link WorkflowInvokePayloadSchema.shape.preconditionReinvocations}: the * budget has to survive across invocations, and a fresh enqueue resets * anything the queue tracks itself. Absent on the first continuation, so a * producer that predates this field is indistinguishable from attempt 0 and * a consumer that predates it simply ignores the field. */ /** * `.catch(undefined)` for the reason `hookResumeTiming` has it: this field * must never be able to fail the parse of the invocation payload. A * malformed value would otherwise throw on every delivery of the message * and burn the run's delivery budget. Degrading to `undefined` reads as * "not a continuation", which costs at worst the pre-attempt behavior for * that one wait rather than killing the run. */ waitContinuation: z .object({ correlationId: z.string(), attempt: z.number().int().nonnegative(), /** * The wait's `resumeAt` (epoch ms), set only on an intermediate hop * of a spec 9 wait longer than one queue delay: a timer sent to fire * before the wait is due, only so that the next hop can be sent (see * {@link isIntermediateWaitHop}). Absent on a final hop, the timer * due when the wait is. */ resumeAtMs: z.number().optional(), /** * The deadline (epoch ms) of this intermediate hop, set beside * `resumeAtMs`. Hops are anchored on the wait's deadline, and each * is keyed by its own deadline, so the delivery of this hop sends * the one after it: one it could not compute from its own clock * when it was delivered a little early. */ hopAtMs: z.number().optional(), }) .optional() .catch(undefined), /** * Waits the orchestrator completes on this delivery whatever their * `resumeAt` (spec >= 9): `run.wakeUp()` names them here instead of * writing `wait_completed` itself, so the orchestrator writes it in-band, * in log order with its own decisions. A wait already completed, or not * open, is ignored. The message is an ordinary orchestrator message: a * queue that coalesces it into a running delivery drops the names, and * the waits then run their full length (`run.wakeUp()` is best-effort * there). `.catch(undefined)` so a malformed value degrades to "no waits * named" rather than failing the parse. */ completeWaits: z.array(z.string()).optional().catch(undefined), /** Step ID for inline step execution in combined handler. If provided, the flow execution * will jump directly to execute the step with the given ID before doing an event replay. */ stepId: z.string().optional(), /** Step name, sent alongside stepId to avoid loading the event log to resolve the name. */ stepName: z.string().optional(), /** * The attempt this step message starts with (spec >= 9). Absent means 1. * Set above 1 when a step that ran inline in the orchestrator failed with * a retryable error and its retry moved to this message. A message whose * `stepAttempt` is above 1 counts as a retry, so its handler reads the * log before running the body. */ stepAttempt: z.number().int().positive().optional(), /** * Set on a step message the orchestrator sent again (spec >= 9): a * re-send of a step whose message a delivery that died may never have * sent (`Queue.createQueueHandler`). Normally the step's stable key * deduplicates it against the first message. When it does go out as a * new message, its handler reads the log before running the body even on * the message's first delivery: the re-send was decided from a log that * can be older than the step's progress, so the step may already have * an outcome. */ stepResent: z.boolean().optional(), /** * Event id of the step's `step_created` (spec >= 9). The step handler * reads the step's input from that event when the message does not carry * it in {@link WorkflowInvokePayloadSchema.shape.stepInput}. */ stepCreatedEventId: z.string().optional(), /** * When the step's `step_created` was committed, as epoch milliseconds * (spec >= 9): the `createdAt` the World answered it with. The step * handler passes it on the step's first-attempt `step_started` as * `CreateEventParams.stepCreatedAt`, for creation-to-start latency * telemetry. Absent on retry messages and from older runtimes. * `.catch(undefined)` so a malformed value only drops the telemetry. */ stepCreatedAt: z.number().optional().catch(undefined), /** Run creation data, only present on the first queue delivery from start() */ runInput: RunInputSchema.optional(), /** * Legacy lazy hook resume data. A consumer that understands this field * idempotently ensures the `hook_received` event exists (keyed by `resumeId`) * before replaying. */ hookInput: HookResumeInputSchema.optional(), /** * Resilient step dispatch data, only present alongside `stepId` when the * producer parallelized the `step_created` write with this queue publish. A * consumer that understands this field idempotently ensures the * `step_created` event exists (keyed by `stepId`) before executing the step. */ stepInput: StepDispatchInputSchema.optional(), /** * Immutable run identity for step-execution messages (`stepId` present). * Lets the consumer skip the blocking `runs.get` before starting the step. * See {@link RunDispatchContextSchema}. */ runContext: RunDispatchContextSchema.optional(), /** * Hook-resume TTR timing. Present on both `resumeHook()` dispatch paths * (unlike legacy `hookInput`), and * forwarded onto a dispatched step message when the resuming invocation * hands the next durable step to another invocation. Purely observational. * See {@link HookResumeTimingSchema}. * * `.catch(undefined)` because this field must never be able to fail the * parse of the invocation payload: a malformed value (a NaN boundary, a * shape change from a future producer) would otherwise throw on every * delivery of that message and burn the run's delivery budget over a * telemetry field. Anything unparseable degrades to "no measurement". */ hookResumeTiming: HookResumeTimingSchema.optional().catch(undefined), /** * The event an out-of-band writer committed before it sent this wake (a * `resumeHook()`'s `hook_received`). An orchestrator that consumed the log * only below it knows the wake has something new, so it skips the tail * read that decides a no-op wake. A hint only: absent from other wakes and * older producers, and `.catch(undefined)` so a malformed value never fails * the payload's parse. */ wakeEventId: z.string().optional().catch(undefined), }); export type WorkflowInvokePayload = z.infer; export type HealthCheckPayload = z.infer; /** * Health check payload - used to verify that the queue pipeline * can deliver messages to the combined workflow endpoint. */ export const HealthCheckPayloadSchema = z.object({ __healthCheck: z.literal(true), correlationId: z.string(), /** * The run id the caller is about to create, when the probe is being used to * prepare a cross-deployment `start()`. * * The responder runs inside the target deployment, so it can derive that * run's public key locally from its own key material and return it in the * probe response. That lets the caller seal the workflow arguments without * a separate key lookup. Absent for probes issued for other reasons (CLI * health command, dashboard), in which case no key is returned. * * Deliberately not named `runId`: `runId` is the only required field of * `WorkflowInvokePayloadSchema`, and 4.x deployments parse queue payloads * with a union that tries the invoke schema before the health check. A * probe carrying `runId` is read there as "replay this run", which POSTs * `run_started` for a run that does not exist yet (404) and retries the * delivery, so the probe never answers. */ probeRunId: z.string().optional(), /** * Legacy spelling of {@link probeRunId}, sent by 5.x callers released * before the rename. Accepted so those callers still get a public key * back from this deployment; never sent. */ runId: z.string().optional(), }); /** * Health check MUST come first. * * Zod unions return the first matching member's output, and `z.object` strips * keys the matching member doesn't declare. A probe from an older caller can * carry the legacy `runId`, which also satisfies `WorkflowInvokePayloadSchema` * (whose only required field is `runId`). With the invoke member first, * parsing such a probe silently drops `__healthCheck` and `correlationId`, and * the runtime (which dispatches on `__healthCheck` before falling through to * the invoke schema) reinterprets the probe as "replay this run". * * Ordering health check first is safe in the other direction: it requires * `__healthCheck: true`, which an invoke payload never carries. */ export const QueuePayloadSchema = z.union([ HealthCheckPayloadSchema, WorkflowInvokePayloadSchema, ]); export type QueuePayload = z.infer; /** * The run whose orchestrator a queue message is a delivery for, or * `undefined` when the message is not an orchestrator delivery. * * An orchestrator delivery is a {@link WorkflowInvokePayload} without a * `stepId`: the start of a run, a wake after a step outcome, a hook resume, * a cancellation or a timer. A step execution message (`stepId` set), a * health check (`__healthCheck`, which may carry the `runId` it prepares) * and an intermediate hop of a long wait's timer * ({@link isIntermediateWaitHop}) are not, and keep full parallelism. * * A run's orchestrator deliveries are serialized only on single-orchestrator * runs (spec >= 9, see {@link singleOrchestratorRunIdOf}). */ export function orchestratorRunIdOf(payload: unknown): string | undefined { if (typeof payload !== 'object' || payload === null) return undefined; const message = payload as Record; if (message.__healthCheck === true) return undefined; if (typeof message.stepId === 'string') return undefined; if (isIntermediateWaitHop(payload)) return undefined; return typeof message.runId === 'string' ? message.runId : undefined; } /** * Whether a queue message is an intermediate hop of a long wait's timer * chain: a timer the runtime sends to fire before its wait is due, because * the wait is longer than one queue delay, so that the delivery sends the * next hop. Marked by `waitContinuation.resumeAtMs`, which only such a hop * carries. * * Its delivery is not an orchestrator delivery: it reads only the run's * status, writes nothing, sends the next hop (the last one an ordinary * timer) and acknowledges. So it is never serialized behind, or coalesced * into, a delivery of its run ({@link orchestratorRunIdOf} leaves it out), * and it must not be: a coalesced hop is never delivered, and the holder's * re-run, which finds its wait not yet due, would not send the next one. */ export function isIntermediateWaitHop(payload: unknown): boolean { if (typeof payload !== 'object' || payload === null) return false; const continuation = (payload as Record).waitContinuation; return ( typeof continuation === 'object' && continuation !== null && Number.isFinite((continuation as { resumeAtMs?: unknown }).resumeAtMs) ); } /** * The spec version of the run a queue message belongs to, as the message * says it: a first delivery's `runInput.specVersion`, a step message's * `runContext.specVersion`, or the `runSpecVersion` hint the runtime stamps * on every other message of a run. `undefined` for a health check, a * message without a run, and a message from a producer that predates the * fields. A World treats `undefined` as a run below spec 9: every runtime * that creates spec 9 runs stamps its messages. * * A producer outside that runtime (an older SDK, or another client of the * World) may still send a message for a spec 9 run that is unstamped or * stamped below 9, and nothing can prevent it. The World then treats it as a * message of an earlier run: world-vercel sends it without the run's * concurrency key, and world-local and world-postgres do not serialize it, so * it can run beside the run's serialized orchestrator. The runtime still * routes it to the run's orchestrator (from the run itself, or by handing it * on once the run is loaded), and the in-band fence refuses the second * writer's in-band writes, so the run's log stays correct. The cost is wasted * orchestrator work, which can include running the body of an inline step a * second time; it does not corrupt the log. */ export function messageRunSpecVersion(payload: unknown): number | undefined { if (typeof payload !== 'object' || payload === null) return undefined; const message = payload as Record; if (message.__healthCheck === true) return undefined; if (typeof message.runId !== 'string') return undefined; const version = (value: unknown) => typeof value === 'object' && value !== null && typeof (value as { specVersion?: unknown }).specVersion === 'number' ? (value as { specVersion: number }).specVersion : undefined; return ( version(message.runInput) ?? version(message.runContext) ?? (typeof message.runSpecVersion === 'number' ? message.runSpecVersion : undefined) ); } /** * Whether a queue message belongs to a single-orchestrator run (spec >= 9), * by {@link messageRunSpecVersion}. The handler-result semantics of * {@link Queue.createQueueHandler} and per-run serialization apply to these * messages; a message of an earlier run keeps the World's earlier behavior. */ export function isSingleOrchestratorMessage(payload: unknown): boolean { const specVersion = messageRunSpecVersion(payload); return ( specVersion !== undefined && specVersion >= SPEC_VERSION_SINGLE_ORCHESTRATOR ); } /** * The run whose orchestrator deliveries a World serializes for this message: * {@link orchestratorRunIdOf} for a message of a single-orchestrator run * (spec >= 9), else `undefined`. * * A World serializes these per run: at most one delivery for a given run id * is in flight at a time, the others wait behind it, and step messages are * never held back by it. That is the queue half of the single-writer * guarantee; the in-band fence is the other half, and makes an overlap that * the queue still lets through (a delivery that outlives its lease) safe. * * Messages of earlier runs (spec <= 8) are not serialized: a spec 8 * orchestrator can hold an inline step until another wake of the same run * aborts it, and run-level exclusion would hold that wake back. */ export function singleOrchestratorRunIdOf( payload: unknown ): string | undefined { return isSingleOrchestratorMessage(payload) ? orchestratorRunIdOf(payload) : undefined; } /** * What a single-orchestrator continuation message takes from the message it * replaces, field by field of {@link WorkflowInvokePayload} (see * {@link singleOrchestratorContinuationPayload}). Typed as a record of every * payload field, so a new field fails the typecheck until it is classified * here. * * - `'carry'`: copied. The run (`runId`), its identity on step messages * (`runContext`), the trace link (`traceCarrier`), and what the message is * a wake for: the wait a timer is for (`waitContinuation`), the waits a * `run.wakeUp()` names (`completeWaits`), and a legacy hook resume * (`hookInput`, which the orchestrator writes deduplicated by its * `resumeId`, so a second copy writes nothing). * - `'stamp'`: `runSpecVersion`, set to the spec version the replaced * message carried in any of its fields ({@link messageRunSpecVersion}), so * the continuation is routed and serialized as the run's other messages * are, even though it drops `runInput`. * - `'drop'`: not copied. `runInput` marks the run's first orchestrator * message, and with a first delivery count it is what selects the * runtime's fresh-start path, which assumes a log holding only * `run_created`; a continuation always continues a progressed run. * `requestedAt` and `hookResumeTiming` measure the request that sent the * replaced message. `wakeEventId` names an event the replaced message's * delivery may already have consumed. `recovery` asks a delivery to * re-send everything a lost queue held, which the replaced message's * delivery did. `invoke`, * `requestId` and `input` are a request/response invocation, not a * continuation. The retry counters (`replayDivergence`, * `preconditionReinvocations`, `serverErrorRetryCount`, * `deploymentMismatchRetryCount`) belong to runs below spec 9 or to one * chain of re-enqueues. The step fields (`stepId` and the rest) are never * on an orchestrator message. */ export const SINGLE_ORCHESTRATOR_CONTINUATION_FIELDS = { runId: 'carry', runContext: 'carry', traceCarrier: 'carry', waitContinuation: 'carry', completeWaits: 'carry', hookInput: 'carry', runSpecVersion: 'stamp', runInput: 'drop', requestedAt: 'drop', hookResumeTiming: 'drop', wakeEventId: 'drop', recovery: 'drop', invoke: 'drop', requestId: 'drop', input: 'drop', replayDivergence: 'drop', preconditionReinvocations: 'drop', serverErrorRetryCount: 'drop', deploymentMismatchRetryCount: 'drop', stepId: 'drop', stepName: 'drop', stepAttempt: 'drop', stepResent: 'drop', stepCreatedEventId: 'drop', stepCreatedAt: 'drop', stepInput: 'drop', } as const satisfies Record< keyof WorkflowInvokePayload, 'carry' | 'stamp' | 'drop' >; /** * The payload a World sends when it continues a single-orchestrator run's * orchestrator message on a new message instead of handing it off (as * world-vercel does for a message close to its expiry), or `undefined` when * `payload` is not an orchestrator message of a single-orchestrator run * ({@link singleOrchestratorRunIdOf}), which a World hands off instead. * * Built from an explicit list of fields * ({@link SINGLE_ORCHESTRATOR_CONTINUATION_FIELDS}), never by copying: the * replaced message may be the run's start message, and a copy of its * `runInput` on a message delivered for the first time would take the * runtime's fresh-start path over a log that already holds the run's * progress, and could run completed step bodies again. */ export function singleOrchestratorContinuationPayload( payload: unknown ): WorkflowInvokePayload | undefined { if (singleOrchestratorRunIdOf(payload) === undefined) return undefined; const source = payload as Record; const continuation: Record = {}; for (const [field, rule] of Object.entries( SINGLE_ORCHESTRATOR_CONTINUATION_FIELDS )) { if (rule === 'carry' && source[field] !== undefined) { continuation[field] = source[field]; } } continuation.runSpecVersion = messageRunSpecVersion(payload); return continuation as WorkflowInvokePayload; } /** * The shortest time, in milliseconds, a World's queue must deduplicate sends * that carry a single-orchestrator run's step key * (`QueueOptions.idempotencyKey` on a step's execution message): for at * least this long after the key's first send, while the message that send * made lives (held, delayed, being delivered or in retry backoff), every * later send under the key is a no-op. The runtime sends a step's message * again from later deliveries of its run (see `Queue.createQueueHandler`) * only while the step's last send is this young, less a margin, so each such * re-send is deduplicated against the step's live message instead of giving * the step a second owner. * * A re-send is decided from the log its delivery loaded, which can be older * than the step's progress: the step's message may have been delivered, run * the step to its outcome and been acknowledged since. A World is not * required to keep the key past the acknowledgment, nor to refuse a * `step_started` for a step that already has an outcome. The runtime marks a * re-sent message (`stepResent`), and its handler reads the run's log before * it runs the body, even on the message's first delivery, so a re-send the * queue takes as a new message after the step's outcome acknowledges without * running it. A World that does either of the two still gets the same result * without that read. * * world-vercel keeps a key for `min(retention, 24h)` whether or not its * message was acknowledged, and retains a step message for at least this * long. world-local and world-postgres keep it while the first message lives * (world-postgres: while its job exists, with Graphile's `unsafe_dedupe`), * which a step message outlives only by completing, and both refuse a * `step_started` for a step that already has an outcome. */ export const QUEUE_MIN_STEP_KEY_DEDUPE_WINDOW_MS = 24 * 60 * 60 * 1000; /** * How long, in milliseconds, a single-orchestrator run's step message whose * deliveries keep failing must go on being redelivered at least, from its * first delivery. A delivery that throws before it writes anything (the * step's input cannot be read, say) leaves the step's log as it was; past * the runtime's delivery cap, a delivery that finds the step's log showing * no activity for this long fails the step (`MAX_DELIVERIES_EXCEEDED`) and * wakes the run. A queue that gives up on the message sooner strands the * run. world-vercel retains a step message for at least a day; world-local * backs off its retries so that its safety limit lasts longer than this; * world-postgres keeps retrying a job without a time limit. */ export const QUEUE_MIN_STEP_REDELIVERY_SPAN_MS = 60 * 60 * 1000; export interface QueueOptions { deploymentId?: string; /** * Deduplicates sends that carry the same key while the first message with * that key exists (on Vercel Queues: for `min(retention, 24h)`). * * On a spec 9 run's messages the runtime sets it on a step's execution * message, with a key stable for the step, because a second message for a * step would be a second owner of its body. * * Every wake of a spec 9 run's orchestrator (after a background step's * outcome, `resumeHook()`, `cancel()`, a force-claimed hook, a fence * refusal) carries no key: a duplicate wake costs one cheap delivery, * while a key can be absorbed by a delivery that is already exiting and * lose the wakeup. A wait's timer is the exception. Each hop of it carries * `wait:::`, the wait, its deadline and the * hop's own deadline (epoch ms; hops are anchored on the wait's deadline), * so the timers that a message's first delivery and every sender of an * intermediate hop send for the same hop are one message; a re-arm after a * timer that came before its wait was due appends `:a`. A * delivery that may hold a coalesced timer (any but its message's first) * keys a wait's last hop by its second instead (the near-due key below), * so a redelivery of a delivery that sent a wait's last hop and then failed * can add one duplicate timer. The duplicate finds its wait completed, or * re-arms it. A near-due re-arm, the timer a delivery that may * hold a coalesced timer sends for an open wait due within a few seconds, * whatever its chain, carries `wait:::s`, * the sender's second in place of the hop's deadline. Deduplicate these as * you do a step's key. * Wakes of runs below spec 9 keep their earlier keys (`hook-`, * `hook-force-claim-`, the QuickJS engine's * `hook_conflict_`). */ idempotencyKey?: string; /** * How long the message may live, in seconds, including every redelivery. * Set on step messages so that the message outlives its step's whole retry * span (the step is retried in place on the same message). A World caps it * at what its queue supports (Vercel Queues: 7 days) and uses its default * when it is absent. */ retentionSeconds?: number; headers?: Record; /** Delay message delivery by this many seconds */ delaySeconds?: number; /** Spec version of the target run. Used to select the queue transport format. */ specVersion?: number; /** * World-specific routing hint identifying the region the message should * be sent to (e.g. a Vercel compute region code such as `'iad1'`). * * Worlds that don't have a regional dimension ignore this field. For * `@workflow/world-vercel`, this overrides the region the underlying * `@vercel/queue` client uses to route the message; when omitted, the * region is resolved from the payload's tagged run ID, then from the * `VERCEL_REGION` environment variable, and finally defaults to `'iad1'` * (the pre-regional-routing behavior). */ region?: string; /** * **Experimental.** Ask the queue to claim the message for its sender * before `queue()` returns, so this process can run it now, in the request * that sent it, with the queue as the crash backstop (see * {@link HeldQueueMessage}). Only on a World that declares * `capabilities.experimental_queueHold`; other Worlds ignore it and send * the message as usual. * * `true` holds with the World's defaults, the same as `{}`; pass * {@link QueueHoldOptions} to name the consumer group or the lease. * * The result's `experimental_hold` says what came of it * ({@link QueueHoldResult}): `status: 'held'`, and this process runs the * message with its `consume(handler)`; or `status: 'not_held'` with the * reason, and the queue delivers the message as usual. It is absent on a * World that ignores the option, which also means the queue delivers it. * Either way short of `held`, do not process the message here. * * Cannot be combined with `delaySeconds`. Send an `idempotencyKey` with it: * a send that fails with a network error may already have enqueued the * message, and a retry without a key enqueues a second one. * * Only this deployment's messages are held: a send pinned to another * deployment (`deploymentId`) is sent as usual and reports `not_held` / * `unsupported`, because its own deployment must run it. A batched send * ({@link Queue.queueBatch}) never holds; its results carry no * `experimental_hold`. * * @experimental */ experimental_hold?: true | QueueHoldOptions; } /** * **Experimental.** Options for {@link QueueOptions.experimental_hold}. * * @experimental */ export interface QueueHoldOptions { /** * The consumer group to hold the message for: the group whose handler * would otherwise receive it, so a hold that lapses is delivered to the * same route. A World with one fixed group uses it and ignores this; a * World whose queue names groups per route needs it whenever the route's * group is not the World's default (world-vercel: `'default'`, the group * the Workflow SDK's generated triggers subscribe with; a Function * configured in `vercel.json` / `vercel.ts` gets a group named after its * path instead, see world-vercel's `vercelTriggerConsumerGroup`). */ consumerGroup?: string; /** * The hold's lease, in seconds. While `consume()` runs the World renews it; * if nothing renews it (the sender died, or never called `consume`), the * message is delivered as usual about this long after the last renewal. A * World clamps it to what its queue supports (Vercel Queues: 30-3600 s, * default 30). */ visibilityTimeoutSeconds?: number; } /** * **Experimental.** Why a send with {@link QueueOptions.experimental_hold} * did not come back holding its message. In every case the queue (or a * delivery it already made) is responsible for the message, so the sender * must not process it. * * - `unsupported`: the queue ignored the hold (send-and-hold not enabled, an * older queue service, local development). The message is delivered as * usual. * - `deferred`: the queue accepted the message for deferred processing. It * is delivered once it is ingested. * - `lost`: another claim on the message won, or its run's orchestrator is * busy (the run's concurrency key is held). The queue delivers it. * - `coalesced`: the run's orchestrator is running in another delivery and * this message was coalesced into it; that delivery covers it. * - `concurrency_limited`: no delivery slot was free. Delivered once one is. * - `duplicate`: the idempotency key belongs to an earlier message. * - `error`: the hold could not be taken or its answer could not be read. * The queue delivers the message once any lease taken for it lapses. * * @experimental */ export type QueueNotHeldReason = | 'unsupported' | 'deferred' | 'lost' | 'coalesced' | 'concurrency_limited' | 'duplicate' | 'error'; /** * **Experimental.** A message the queue claimed for its sender before * `queue()` returned ({@link QueueOptions.experimental_hold}). It counts as * the message's first delivery: running it here replaces the queue hop to a * consumer, and the queue stays the backstop if this process stops renewing * the lease. * * @experimental */ export interface HeldQueueMessage { readonly status: 'held'; /** ID of the held message. The same ID a redelivery of it carries. */ readonly messageId: MessageId; /** When the hold lapses unless `consume()` renews it. */ readonly leaseExpiresAt: Date; /** * Run `handler` on the message here, as the World's * {@link Queue.createQueueHandler} runs a delivery of it: the same * handler-result semantics (a `{ timeoutSeconds }` result redelivers the * message, a handoff continues it in a fresh delivery) and the same retries * when it rejects. The lease is renewed while the handler runs and the * message is acknowledged when it resolves. * * `meta` is a first delivery's (`deliveryCount: 1`, `attempt: 1`), with * two differences from a pushed one. `invocationStartedAt` is when the * enclosing queue delivery began if `consume` runs inside one, else when * `consume` was called; coalesced re-runs share it either way. And * `requestId` is set only inside a queue delivery, so do not hold an * `invoke: true` request, which needs one. * * Pass the same handler the queue consumer for this message's prefix uses. * Call it as soon as `queue()` returns (nothing renews the hold until it * starts), at most once, and not after `release()`. Keep the invocation * alive until it settles (for example with `waitUntil`). */ consume(handler: QueueHandler): Promise; /** * Give the message back without running it here: the queue delivers it as * usual after `delaySeconds` (default 0). */ release(delaySeconds?: number): Promise; } /** * **Experimental.** A send that asked for a hold and did not get it: the * queue delivers the message (see {@link QueueNotHeldReason}). * * @experimental */ export interface NotHeldQueueMessage { readonly status: 'not_held'; readonly reason: QueueNotHeldReason; } /** * **Experimental.** What came of {@link QueueOptions.experimental_hold}, by * `status`: the held message, to run here, or why it was not held. * * @experimental */ export type QueueHoldResult = HeldQueueMessage | NotHeldQueueMessage; /** What {@link Queue.queue} resolves with. */ export interface QueueResult { messageId: MessageId | null; /** * **Experimental.** Present when the send asked for a hold * ({@link QueueOptions.experimental_hold}) on a World that supports it. * * @experimental */ experimental_hold?: QueueHoldResult; } /** The handler {@link Queue.createQueueHandler} runs for each delivery. */ export type QueueHandler = ( message: unknown, meta: { attempt: number; deliveryCount?: number; createdAt?: Date; queueName: ValidQueueName; messageId: MessageId; requestId?: string; invocationStartedAt?: number; } ) => Promise; /** * Outcome of one message in a {@link Queue.queueBatch} call, in input order. * * `messageId: null` with no `error` means accepted for deferred processing * (the same "accepted, no ID yet" case {@link Queue.queue} reports), so * `error === undefined` is the success test, not a non-null `messageId`. */ export type QueueBatchResult = | { messageId: MessageId | null; error?: undefined } | { messageId: null; /** Human-readable failure description for this message. */ error: string; /** Republishing the batch may succeed. */ retryable: boolean; }; export interface InvokeOptions { /** Retries of one request reuse this key and the exact same payload. */ idempotencyKey?: string; /** Maximum time to await a response. Timeout does not undo processing. */ timeoutMs?: number; } /** * How the runtime authenticates a delivery that reaches the Workflow SDK's * flow route, before it does any work. See {@link Queue.queueAuthMode}. * * - `'loopback'`: the World's queue delivers back to the app it runs in, and * attaches the app's queue key as the `QUEUE_AUTH_HEADER` header of every * delivery it sends, over HTTP or to an in-process handler registered with * `registerHandler`. The runtime checks it against the key sources Worlds * registered, one per data directory (`setQueueAuthKeySource()` from * `@workflow/utils`; the Local World's is the key file in its data * directory), or `getQueueAuthKey()` when there is none, and refuses, with * a 401 and without touching any run, a delivery that carries none of * them. "Loopback" means sent by this * app's own processes, which share the key through the data directory, not * any request from localhost. Temporary: it goes away once the Local * World's queue no longer delivers back to the app over its own routes. * - `'skip'`: the runtime does not check. Only for a World whose platform * guarantees that only its queue reaches the route, as Vercel's does; * world-postgres declares it until its messages are delivered in-process * (https://github.com/vercel/workflow/issues/5258). */ export type QueueAuthMode = 'loopback' | 'skip'; export interface Queue { getDeploymentId(): Promise; /** * How the runtime authenticates the deliveries this World's queue sends * (see {@link QueueAuthMode}). Opt-in: a World that declares nothing is not * checked. The mode becomes required in SDK v6. * * `WORKFLOW_QUEUE_AUTH=off` turns the check off for `'loopback'` Worlds (a * trusted network), except while dynamic workflows are enabled. */ queueAuthMode?: QueueAuthMode; /** * Send an invocation to a run's executor. Must be enabled via capabilities.invoke. * An invocation carries an out-of-band request that must be processed by the * executor. The executor's response is propagated back and errors are rethrown * by invoke(). A transport error is an unknown outcome: the request may have * been successfully processed by the executor, for example, and the success * result may be lost. */ invoke?( runId: string, payload: unknown, options?: InvokeOptions ): Promise; /** * Returns true only when a queue error definitively means the explicitly * targeted deployment cannot receive the message. Unknown and transient * errors must return false so the current delivery can be retried safely. */ isDeploymentUnavailableError?(error: unknown): boolean; /** * Enqueues a message to the specified queue. * * @param queueName - The name of the queue to which the message will be sent. * @param message - The content of the message to be sent to the queue. * @param opts - Optional parameters for the queue operation. */ queue( queueName: ValidQueueName, message: QueuePayload, opts?: QueueOptions ): Promise; /** * Enqueues several messages to the SAME logical queue in as few round trips * as the backing transport allows. Optional: callers MUST fall back to * per-message {@link Queue.queue} when a World does not implement it. * Never holds a message: `opts.experimental_hold` is ignored here, and a * result carries no `experimental_hold`. * * Exists for wide fan-outs. Publishing an N-branch `Promise.all` one message * at a time costs N round trips through a bounded connection pool, and that * cost is paid before the fan-out's first step body runs, so it lands * directly on time-to-first-step. * * Contract: * * - Results are returned in input order, one per input message. Returning * a different number of results than there were messages is a contract * violation the runtime rejects the whole batch on: an omitted result is * indistinguishable from a message that was never published, and reading * it as success would strand that step with no error anywhere. * - Partial failure is normal. A rejected entry reports `error`; a * `retryable` entry may succeed if the whole batch is published again. * Implementations MUST NOT throw for a per-entry failure — reserve * rejection for request-level failures where no entry outcome is known. * - Callers are expected to pass `opts.idempotencyKey` per message, because * the recovery for both a request-level failure and a retryable entry is * to republish the batch: without keys that redelivers the entries that * already succeeded. * - Every message must target one logical `queueName`. Implementations are * free to split the batch (by transport cap, or by any per-message routing * dimension they derive from the payload, such as region or physical * topic); the split must not be observable in the returned order. */ queueBatch?( queueName: ValidQueueName, messages: readonly { message: QueuePayload; opts?: QueueOptions }[] ): Promise; /** * Creates an HTTP queue handler for processing messages from a specific queue. * * Handler outcomes, for a message that is not an `invoke: true` request. * What a `{ timeoutSeconds }` result asks for depends on the run the * message belongs to ({@link isSingleOrchestratorMessage}): * * - **Single-orchestrator run (spec >= 9), `{ timeoutSeconds: n }` with * `n > 0`**: do NOT acknowledge the message. Deliver the SAME message * again (same `messageId`, next `deliveryCount`) after about `n` seconds. * The runtime returns this from a step handler to retry a step in place * after `retryAfter`, and from an orchestrator delivery to defer the run * (an inline step start refused for load) or to stand down after the * in-band fence refused its write, whose redelivery must count as one * (next `deliveryCount`) so that it re-sends what a delivery that died * left unsent. A World MAY clamp `n` to what * its queue supports (Vercel Queues clamps a redelivery delay to * [5s, 900s]); the runtime tolerates an early redelivery by checking the * log and asking again. A World whose queue cannot redeliver the same * message may publish a new message with the same payload instead, * provided it carries the same `messageId` and the next `deliveryCount` * in `meta` on delivery; otherwise the runtime's re-send rule loses its * anchor (see `meta.deliveryCount`). * - **Single-orchestrator run, `{ timeoutSeconds: 0 }`: a handoff.** The * delivery is not done and continues in a fresh one. Deliver the SAME * message again at once, and do not count this delivery toward * `attempt`. The orchestrator returns this when its invocation must end * before its work does (the invocation deadline, a stream flush, the * replay budget, a wait or a write it cannot read yet). The runtime never * returns it where the next delivery has to count as an attempt: a * fence-refused delivery sends what its writes owe and returns * `{ timeoutSeconds: n }` with `n > 0`. A World should not treat a non-finite * `n` as a handoff (a handoff is not an attempt, so a handler that kept * returning one would never stop); world-vercel redelivers after its * longest delay. * - **Earlier runs (spec <= 8), `{ timeoutSeconds: n }`**: continue the run * after about `n` seconds (`0`: at once), by redelivering the same message * or by publishing a new message with the same payload. world-vercel * publishes a new message, with up to 23 hours of delay, before it * acknowledges this one; world-local and world-postgres redeliver. * - **Resolves with anything else**: acknowledge the message. * - **Rejects**: retry the same message, with a World-chosen backoff. * * With `invoke: true`, the return value is response data delivered by the * World and is never queue control. * * `meta` describes the delivery: * * - `messageId` SHOULD be stable across redeliveries of the same message * (one id per enqueued message, reused on every delivery), and MUST be * for a World that creates spec 9 runs. On a spec 9 run the runtime * records it on `step_created` and `wait_created` (`creatorMessageId`): * the delivery that wrote a wait's `wait_created`, or a later delivery of * that message, schedules the wait's timer. On earlier runs the runtime's * inline step ownership uses it as a liveness lease: the lazy * `step_started` records the handling invocation's messageId, and only a * delivery of that same message may re-execute the step before the * ownership lease expires. A World whose queue mints a fresh id per * delivery degrades gracefully there: owner redeliveries fall back to the * delayed-backstop path, adding recovery latency but never wedging or * duplicating. * - `deliveryCount` is 1 on a message's first delivery and increments on * every redelivery, whatever caused it (lease lapse, a rejected handler, a * `{ timeoutSeconds }` result, a handoff, a coalesced re-run). An * orchestrator delivery whose count is above 1 re-sends, once per * invocation and under each step's stable key, every background step * that has a `step_created` and no `step_started`: a delivery that died * between the two left it with no message. The queue must therefore * follow any delivery that dies with a delivery counted above 1, of the * same message or of one it was coalesced into, and must dedupe a step * key for at least {@link QUEUE_MIN_STEP_KEY_DEDUPE_WINDOW_MS} while the * step's first message lives. Leave it `undefined` * when the queue cannot say: the runtime then treats every delivery as a * possible redelivery and reads the run's log before running a step * body, which is correct but slower. A queue that reports 1 for a redelivery breaks * the at-most-once guarantee of a `maxRetries: 0` step. * - `createdAt` is when the message was first enqueued, when known. * - `attempt` is `deliveryCount` less the deliveries that followed a * handoff (`{ timeoutSeconds: 0 }` on a single-orchestrator run) and less * coalesced re-runs (below). It is what the runtime's delivery cap * counts. On a World with neither it equals `deliveryCount`. * - A World whose queue coalesces a run's orchestrator messages into the * delivery that is running (world-vercel, with `@vercel/queue`'s * experimental concurrency key) runs the handler again within that * delivery when coalesced messages arrived while it ran. Each such * re-run reports the next `deliveryCount` (the delivery's count plus the * re-runs so far) and leaves `attempt` unchanged: a coalesced message is * never delivered, so a re-run must read the run's log, as a redelivery * does, and whatever those messages were sent for was committed to the * log before they were sent. Two orchestrator payload fields carry more * than the log. `run.wakeUp()`'s `completeWaits` is best-effort: * coalesced, it is lost, and the waits run their full length. A timer's * `waitContinuation` names its wait: coalesced, the name is lost, which * costs nothing for a final timer (the holder's re-run sees the wait due * and completes it, and the delivery that completes a wait arms the next * one of its chain), and an intermediate hop of a long wait, which would * lose its chain, is never coalesced ({@link isIntermediateWaitHop}). * - `invocationStartedAt` (epoch ms) is when the function invocation running * this handler call began, when the World knows it. It is the same for * every coalesced re-run of a delivery, which all share that invocation: * the runtime measures its inline deadline from it, so a late re-run does * not get a fresh budget the invocation no longer has. Absent: the runtime * measures from the start of each handler call. */ createQueueHandler( queueNamePrefix: QueuePrefix, handler: QueueHandler ): (req: Request) => Promise; /** * Optional. Delivers every message whose queue name starts with `prefix` to * `handler` inside this process, without HTTP. For Worlds whose queue runs * in the app's own process (world-local, world-postgres). `handler` takes * the same request a route serving `createQueueHandler(prefix, ...)` would, * so passing that route handler works. Takes precedence over * {@link Queue.registerRoute} for the prefix; a later registration for the * same prefix replaces an earlier one. * * Keyed by the exact prefix: registering `__wkf_workflow_` also takes the * Workflow SDK's own messages. A queue consumer other than the Workflow SDK * uses a prefix of its own, `__{namespace}_wkf_workflow_`. */ registerHandler?( prefix: QueuePrefix, handler: (req: Request) => Promise ): void; /** * Optional. The route (a path on the app's base URL, such as * `/api/agent/queue`) that this World's HTTP delivery POSTs the messages of * `prefix` to. The app serves it with `createQueueHandler(prefix, ...)`. * A prefix without a registered route goes to the Workflow SDK's flow route * ({@link WORKFLOW_FLOW_ROUTE}), so only the Workflow SDK relies on that * path, and a queue consumer of its own registers its route here, before * the World's `start()` when it has one (`start()` re-enqueues active runs). * An in-process handler for the prefix ({@link Queue.registerHandler}) * takes precedence; a later registration for the same prefix replaces an * earlier one. * * Worlds that deliver by subscription rather than by path (world-vercel) * do not implement this: subscribe the route to the prefix's topics there. */ registerRoute?(prefix: QueuePrefix, path: string): void; }