import { An as Provider, Hr as FactoryContext, Jr as FactoryDefinition, mn as PullRequestRef, qr as Factory } from "./index-DJ6CHaMc.js"; import { l as RunOutcome, o as ReleaseAction, s as ReleasePolicy, u as ResourceRecord } from "./resources-B6ZjmsZN.js"; import { t as RegistrySql } from "./registry-B_Fz0T_P.js"; import { z } from "zod"; import { RequestListener } from "node:http"; import { z as z$1 } from "zod/v4"; //#region ../../node_modules/.pnpm/@workflow+world@5.2.2/node_modules/@workflow/world/dist/shared.d.ts /** * Options for paginated queries. * Provides control over page size and cursor-based navigation. */ interface PaginationOptions { /** Maximum number of items to return (default varies by service, max: 1000) */ limit?: number; /** Cursor for pagination - token from previous response */ cursor?: string; sortOrder?: 'asc' | 'desc'; } declare const PaginatedResponseSchema: (dataSchema: T) => z.ZodObject<{ data: z.ZodArray; cursor: z.ZodNullable; hasMore: z.ZodBoolean; pageInfo: z.ZodOptional; maxWindowStart: z.ZodCoercedDate; upgradeAvailable: z.ZodBoolean; }, z.core.$strip>>; }, z.core.$strip>; type PaginatedResponse = z.infer>>>; /** * Controls how much data is resolved in the response. * - "none": Returns minimal data with input: [] and output: undefined * - "all": Returns full data with complete input and output */ type ResolveData = 'none' | 'all'; /** * {@link ResolveData} for event-log reads, plus one mode for replay: * - "skip-step-inputs": as "all", except that the World MAY leave `input` out * of `step_created` and `step_started` events. Workflow replay recomputes * step arguments by re-running workflow code and never reads the recorded * ones (a step takes its input from the `step_started` response or from * memory, never from the replay log), and for a workflow that passes * growing state into its steps those inputs are the part of the log that * grows quadratically. * * **A World MUST treat any value other than "none" as "all"** for everything * it does not specifically implement. The runtime replays with * "skip-step-inputs", so a World that tests `resolveData === 'all'` (reading * the new value as "none") strips step results and breaks every replay, and * one that validates against `['none', 'all']` rejects the read. Test * `resolveData === 'none'`, or map with {@link entityResolveData}. The * `@workflow/world-testing` suite checks this. */ type EventsResolveData = ResolveData | 'skip-step-inputs'; /** * A single chunk from a stream, with its 0-based index and raw binary data. */ interface StreamChunk { /** The 0-based position of this chunk in the stream */ index: number; /** The raw chunk data */ data: Uint8Array; } /** * Options for paginated chunk retrieval. */ interface GetChunksOptions { /** Maximum number of chunks to return per page (default: 100, max: 1000) */ limit?: number; /** Opaque cursor from a previous response to fetch the next page */ cursor?: string; } /** * Metadata about a stream, returned by {@link Streamer.getStreamInfo}. */ interface StreamInfoResponse { /** * The index of the last known chunk (0-based). * Returns `-1` when no chunks have been written yet. */ tailIndex: number; /** Whether the stream is fully complete (closed). */ done: boolean; } /** * Paginated response for stream chunks. * * Extends the standard `PaginatedResponse` shape with a `done` field that * indicates whether the stream has been fully written (closed). When `done` * is `false`, additional chunks may appear in future requests even after * `hasMore` returns `false` for the current set of available chunks. */ interface StreamChunksResponse { /** Array of stream chunks in index order */ data: StreamChunk[]; /** Cursor for the next page, or `null` when no more pages are available */ cursor: string | null; /** Whether additional pages of already-written chunks exist */ hasMore: boolean; /** Whether the stream is fully complete (all chunks have been written and the stream is closed) */ done: boolean; } //#endregion //#region ../../node_modules/.pnpm/@workflow+world@5.2.2/node_modules/@workflow/world/dist/analytics.d.ts declare const AnalyticsRunSchema: z.ZodObject<{ runId: z.ZodString; status: z.ZodEnum<{ pending: "pending"; running: "running"; completed: "completed"; failed: "failed"; cancelled: "cancelled"; }>; deploymentId: z.ZodString; workflowName: z.ZodString; specVersion: z.ZodOptional>; attributes: z.ZodDefault>; createdAt: z.ZodPreprocess, unknown>; updatedAt: z.ZodPreprocess, unknown>; startedAt: z.ZodOptional, unknown>>>; completedAt: z.ZodOptional, unknown>>>; errorCode: z.ZodOptional>; workflowCoreVersion: z.ZodOptional>; workflowEncryptionEnabled: z.ZodOptional>; }, z.core.$strip>; declare const AnalyticsStepSchema: z.ZodObject<{ runId: z.ZodString; stepId: z.ZodString; stepName: z.ZodOptional>; status: z.ZodEnum<{ pending: "pending"; running: "running"; completed: "completed"; failed: "failed"; cancelled: "cancelled"; }>; attempt: z.ZodOptional; createdAt: z.ZodPreprocess, unknown>; updatedAt: z.ZodPreprocess, unknown>; startedAt: z.ZodOptional, unknown>>>; completedAt: z.ZodOptional, unknown>>>; retryAfter: z.ZodOptional, unknown>>>; errorCode: z.ZodOptional>; workflowCoreVersion: z.ZodOptional>; workflowEncryptionEnabled: z.ZodOptional>; computeInstanceId: z.ZodOptional>; }, z.core.$strip>; declare const AnalyticsEventSchema: z.ZodObject<{ runId: z.ZodString; eventId: z.ZodString; eventType: z.ZodEnum<{ run_created: "run_created"; run_started: "run_started"; run_completed: "run_completed"; run_failed: "run_failed"; run_cancelled: "run_cancelled"; attr_set: "attr_set"; step_created: "step_created"; step_completed: "step_completed"; step_failed: "step_failed"; step_retrying: "step_retrying"; step_started: "step_started"; hook_created: "hook_created"; hook_received: "hook_received"; hook_disposed: "hook_disposed"; hook_conflict: "hook_conflict"; wait_created: "wait_created"; wait_completed: "wait_completed"; noop: "noop"; }>; correlationId: z.ZodOptional>; entityId: z.ZodOptional>; stepName: z.ZodOptional>; workflowName: z.ZodString; deploymentId: z.ZodString; specVersion: z.ZodOptional>; runCreatedAt: z.ZodPreprocess, unknown>; createdAt: z.ZodPreprocess, unknown>; region: z.ZodOptional>; vercelId: z.ZodOptional>; requestId: z.ZodOptional>; computeInstanceId: z.ZodOptional>; resumeAt: z.ZodOptional, unknown>>>; retryAfter: z.ZodOptional, unknown>>>; errorCode: z.ZodOptional>; workflowCoreVersion: z.ZodOptional>; isWebhook: z.ZodOptional>; isSystem: z.ZodOptional>; workflowEncryptionEnabled: z.ZodOptional>; }, z.core.$strip>; declare const AnalyticsHookSchema: z.ZodObject<{ runId: z.ZodString; hookId: z.ZodString; status: z.ZodEnum<{ created: "created"; received: "received"; disposed: "disposed"; conflict: "conflict"; }>; createdAt: z.ZodPreprocess, unknown>; updatedAt: z.ZodPreprocess, unknown>; receivedAt: z.ZodOptional, unknown>>>; disposedAt: z.ZodOptional, unknown>>>; isWebhook: z.ZodOptional>; isSystem: z.ZodOptional>; workflowCoreVersion: z.ZodOptional>; workflowEncryptionEnabled: z.ZodOptional>; }, z.core.$strip>; declare const AnalyticsWaitSchema: z.ZodObject<{ runId: z.ZodString; waitId: z.ZodString; status: z.ZodEnum<{ completed: "completed"; waiting: "waiting"; }>; resumeAt: z.ZodOptional, unknown>>>; createdAt: z.ZodPreprocess, unknown>; updatedAt: z.ZodPreprocess, unknown>; completedAt: z.ZodOptional, unknown>>>; workflowCoreVersion: z.ZodOptional>; workflowEncryptionEnabled: z.ZodOptional>; }, z.core.$strip>; declare const AnalyticsAttributeKeySchema: z.ZodObject<{ key: z.ZodString; runCount: z.ZodCoercedNumber; firstSeenAt: z.ZodPreprocess, unknown>; lastSeenAt: z.ZodPreprocess, unknown>; }, z.core.$strip>; type AnalyticsRun = z.infer; type AnalyticsStep = z.infer; type AnalyticsEvent = z.infer; type AnalyticsHook = z.infer; type AnalyticsWait = z.infer; type AnalyticsAttributeKey = z.infer; interface AnalyticsListRunsParams { workflowName?: string; status?: AnalyticsRun['status']; /** * Bound the listing to runs active between `startTime` and `endTime` * (ISO 8601 timestamps). Both must be provided together. A bounded window * lets the backend prune its scan, so the ClickHouse-backed Vercel * implementation is faster with one. Requesting a window * older than the plan's observability lookback fails with * `observability-upgrade-required`. */ startTime?: string; endTime?: string; /** * Restrict the listing to runs whose latest attribute snapshot matches * every provided key=value pair (up to 8 pairs). Matching is * latest-write-wins: a run whose attribute moved from `v1` to `v2` no * longer matches `v1`. Reserved `$`-prefixed keys may be used in filters * even though user writes to that namespace are rejected. */ attributes?: Record; pagination?: PaginationOptions; } interface AnalyticsListAttributesParams { workflowName?: string; /** * Bound the listing to attribute writes between `startTime` and `endTime` * (ISO 8601 timestamps). Both must be provided together. Requesting a * window older than the plan's observability lookback fails with * `observability-upgrade-required`. */ startTime?: string; endTime?: string; pagination?: PaginationOptions; } interface AnalyticsListRunScopedParams { runId: string; pagination?: PaginationOptions; } interface AnalyticsListEventsParams extends AnalyticsListRunScopedParams { eventType?: AnalyticsEvent['eventType']; correlationId?: string; } /** * @deprecated Parameters of the deprecated `analytics.events.listByCorrelationId`. * Use `AnalyticsListEventsParams` with `list({ runId, correlationId })`. */ interface AnalyticsListEventsByCorrelationIdParams { correlationId: string; /** The run the correlation id belongs to; see `ListEventsByCorrelationIdParams`. */ runId: string; pagination?: PaginationOptions; } interface AnalyticsListHooksParams { runId: string; pagination?: PaginationOptions; } interface AnalyticsListWaitsParams extends AnalyticsListRunScopedParams { status?: AnalyticsWait['status']; } interface Analytics { runs: { get(runId: string): Promise; list(params?: AnalyticsListRunsParams): Promise>; }; attributes: { /** * List the distinct attribute keys observed on runs in the window, * with run counts and first/last seen timestamps. Ordered * alphabetically by key. */ list(params?: AnalyticsListAttributesParams): Promise>; }; steps: { get(runId: string, stepId: string): Promise; list(params: AnalyticsListRunScopedParams): Promise>; }; events: { get(runId: string, eventId: string): Promise; /** * Retrieves the analytics rows present for a bounded set of event IDs in * one run. Missing rows are omitted because analytics ingestion may lag * canonical storage. Duplicate IDs are looked up once; result ordering is * not guaranteed. */ getMany(runId: string, eventIds: readonly string[]): Promise; list(params: AnalyticsListEventsParams): Promise>; /** * @deprecated Use `list({ runId, correlationId })`, which issues the same * request and additionally accepts an `eventType` filter. * * This method was the analytics counterpart of the cross-run correlation * lookup, which took the correlation id alone. Requiring a `runId` (a * correlation id is unique per run, not globally) left it a special case * of `list` with no behaviour of its own. Scheduled for removal in the * next major. * * Note this is unrelated to the storage `events.listByCorrelationId`, * which is not deprecated and keeps a distinct endpoint. */ listByCorrelationId(params: AnalyticsListEventsByCorrelationIdParams): Promise>; }; hooks: { get(hookId: string, params?: { runId?: string; }): Promise; list(params: AnalyticsListHooksParams): Promise>; }; waits: { get(runId: string, waitId: string): Promise; list(params: AnalyticsListWaitsParams): Promise>; }; } //#endregion //#region ../../node_modules/.pnpm/@workflow+world@5.2.2/node_modules/@workflow/world/dist/hooks.d.ts declare const HookSchema: z.ZodObject<{ runId: z.ZodString; hookId: z.ZodString; token: z.ZodString; ownerId: z.ZodString; projectId: z.ZodString; environment: z.ZodString; metadata: z.ZodOptional>, z.ZodType>]>>; createdAt: z.ZodCoercedDate; specVersion: z.ZodOptional; isWebhook: z.ZodOptional; isSystem: z.ZodOptional; tokenRetentionUntil: z.ZodOptional>; resumeContext: z.ZodOptional; workflowCoreVersion: z.ZodOptional; nodeVersion: z.ZodOptional; traceCarrier: z.ZodOptional>; encryptionPublicKey: z.ZodOptional; hookResumeInputVersion: z.ZodOptional; }, z.core.$strip>>; resumeCapabilities: z.ZodOptional>; claimedFrom: z.ZodOptional; deploymentId: z.ZodOptional; runSpecVersion: z.ZodOptional; }, z.core.$strip>>; }, z.core.$strip>; /** * Represents a Hook. Hooks kept by minimum retention remain readable after * their workflow runs end, but cannot be resumed. * * Note: metadata type is SerializedData to support both: * - specVersion >= 2: Uint8Array (binary devalue format) * - specVersion 1: unknown (legacy JSON format) */ type Hook = z.infer; interface ListHooksParams { runId?: string; pagination?: PaginationOptions; resolveData?: ResolveData; } interface GetHookParams { resolveData?: ResolveData; } //#endregion //#region ../../node_modules/.pnpm/@workflow+world@5.2.2/node_modules/@workflow/world/dist/runs.d.ts declare const WorkflowRunStatusSchema: z.ZodEnum<{ pending: "pending"; running: "running"; completed: "completed"; failed: "failed"; cancelled: "cancelled"; }>; type WorkflowRunStatus = z.infer; declare const WorkflowRunSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ runId: z.ZodString; deploymentId: z.ZodString; workflowName: z.ZodString; specVersion: z.ZodOptional; executionContext: z.ZodOptional>; input: z.ZodOptional>, z.ZodType>]>>; dynamicWorkflowCode: z.ZodOptional>, z.ZodType>]>>; errorCode: z.ZodOptional; attributes: z.ZodDefault>; encryptionPublicKey: z.ZodOptional; startHook: z.ZodOptional; tokenRetentionUntil: z.ZodOptional>; metadata: z.ZodOptional>, z.ZodType>]>>; }, z.core.$strip>>; expiredAt: z.ZodOptional>; startedAt: z.ZodOptional>; createdAt: z.ZodCoercedDate; updatedAt: z.ZodCoercedDate; status: z.ZodEnum<{ pending: "pending"; running: "running"; }>; output: z.ZodOptional; error: z.ZodOptional; completedAt: z.ZodOptional; }, z.core.$strip>, z.ZodObject<{ runId: z.ZodString; deploymentId: z.ZodString; workflowName: z.ZodString; specVersion: z.ZodOptional; executionContext: z.ZodOptional>; input: z.ZodOptional>, z.ZodType>]>>; dynamicWorkflowCode: z.ZodOptional>, z.ZodType>]>>; errorCode: z.ZodOptional; attributes: z.ZodDefault>; encryptionPublicKey: z.ZodOptional; startHook: z.ZodOptional; tokenRetentionUntil: z.ZodOptional>; metadata: z.ZodOptional>, z.ZodType>]>>; }, z.core.$strip>>; expiredAt: z.ZodOptional>; startedAt: z.ZodOptional>; createdAt: z.ZodCoercedDate; updatedAt: z.ZodCoercedDate; status: z.ZodLiteral<"cancelled">; output: z.ZodOptional; error: z.ZodOptional; completedAt: z.ZodCoercedDate; }, z.core.$strip>, z.ZodObject<{ runId: z.ZodString; deploymentId: z.ZodString; workflowName: z.ZodString; specVersion: z.ZodOptional; executionContext: z.ZodOptional>; input: z.ZodOptional>, z.ZodType>]>>; dynamicWorkflowCode: z.ZodOptional>, z.ZodType>]>>; errorCode: z.ZodOptional; attributes: z.ZodDefault>; encryptionPublicKey: z.ZodOptional; startHook: z.ZodOptional; tokenRetentionUntil: z.ZodOptional>; metadata: z.ZodOptional>, z.ZodType>]>>; }, z.core.$strip>>; expiredAt: z.ZodOptional>; startedAt: z.ZodOptional>; createdAt: z.ZodCoercedDate; updatedAt: z.ZodCoercedDate; status: z.ZodLiteral<"completed">; output: z.ZodOptional>, z.ZodType>]>>; error: z.ZodOptional; completedAt: z.ZodCoercedDate; }, z.core.$strip>, z.ZodObject<{ runId: z.ZodString; deploymentId: z.ZodString; workflowName: z.ZodString; specVersion: z.ZodOptional; executionContext: z.ZodOptional>; input: z.ZodOptional>, z.ZodType>]>>; dynamicWorkflowCode: z.ZodOptional>, z.ZodType>]>>; errorCode: z.ZodOptional; attributes: z.ZodDefault>; encryptionPublicKey: z.ZodOptional; startHook: z.ZodOptional; tokenRetentionUntil: z.ZodOptional>; metadata: z.ZodOptional>, z.ZodType>]>>; }, z.core.$strip>>; expiredAt: z.ZodOptional>; startedAt: z.ZodOptional>; createdAt: z.ZodCoercedDate; updatedAt: z.ZodCoercedDate; status: z.ZodLiteral<"failed">; output: z.ZodOptional; error: z.ZodOptional>, z.ZodType>]>>; completedAt: z.ZodCoercedDate; }, z.core.$strip>], "status">; type WorkflowRun = z.infer; /** A workflow run with its first start time materialized. */ type StartedWorkflowRun = WorkflowRun & { startedAt: Date; }; /** * WorkflowRun with its payload fields excluded (when resolveData='none'): * input, output, and a dynamic run's stored workflow code. * Used for listing runs without fetching the full serialized data. */ type WorkflowRunWithoutData = Omit & { input: undefined; output: undefined; dynamicWorkflowCode?: undefined; }; interface GetWorkflowRunParams { resolveData?: ResolveData; } /** * Params for the optional `runs.waitForTerminalStatus` long poll. */ interface WaitForTerminalRunStatusParams extends GetWorkflowRunParams { /** * How long the caller is willing to wait, in milliseconds. Treat it as an * upper bound on the wait, not a promise about the duration: the call * resolves as soon as the run is terminal, and a World may also resolve * early with a non-terminal snapshot (see * {@link Storage.runs.waitForTerminalStatus}). * * Implementations clamp this to whatever their backend can hold open. */ timeoutMs?: number; /** * Abandon the wait when this signal aborts. Implementations that cannot * observe it may ignore it; callers must not rely on it to bound the call. */ signal?: AbortSignal; } interface ListWorkflowRunsParams { workflowName?: string; /** * Filter by run status. Accepts a single status or an array of statuses; * with an array, runs matching *any* of the listed statuses are returned. * The array form lets callers express set filters (e.g. "not terminal") * without restating the status vocabulary in application code — see * `TERMINAL_WORKFLOW_RUN_STATUSES` for the complement. * * **Empty-array semantics:** `status: []` matches no runs (mirrors SQL * `IN ()`). To leave the filter unset, omit the field entirely — that * behaviour is unchanged from single-status callers. */ status?: WorkflowRunStatus | WorkflowRunStatus[]; pagination?: PaginationOptions; resolveData?: ResolveData; } /** * Request payload for cancelling many runs in a single operation. * * `runIds` must contain 1–{@link BULK_CANCEL_MAX_RUN_IDS} unique IDs. * `cancelReason` (max 512 chars) is recorded on each run_cancelled event, * mirroring the single-run {@link CancelRunOptions.cancelReason}. */ declare const BulkCancelWorkflowRunsRequestSchema: z.ZodObject<{ runIds: z.ZodArray; cancelReason: z.ZodOptional; }, z.core.$strip>; type BulkCancelWorkflowRunsRequest = z.infer; /** * Aggregate result of a bulk cancellation. `results` preserves the order of * the requested `runIds`; `summary` counts each outcome. */ declare const BulkCancelWorkflowRunsResultSchema: z.ZodObject<{ summary: z.ZodObject<{ requested: z.ZodNumber; cancelled: z.ZodNumber; alreadyCancelled: z.ZodNumber; notCancellable: z.ZodNumber; notFound: z.ZodNumber; failed: z.ZodNumber; }, z.core.$strip>; results: z.ZodArray; }, z.core.$strip>, z.ZodObject<{ runId: z.ZodString; outcome: z.ZodLiteral<"already_cancelled">; }, z.core.$strip>, z.ZodObject<{ runId: z.ZodString; outcome: z.ZodLiteral<"not_cancellable">; status: z.ZodString; }, z.core.$strip>, z.ZodObject<{ runId: z.ZodString; outcome: z.ZodLiteral<"not_found">; }, z.core.$strip>, z.ZodObject<{ runId: z.ZodString; outcome: z.ZodLiteral<"failed">; code: z.ZodString; retryable: z.ZodBoolean; }, z.core.$strip>], "outcome">>; }, z.core.$strip>; type BulkCancelWorkflowRunsResult = z.infer; //#endregion //#region ../../node_modules/.pnpm/@workflow+world@5.2.2/node_modules/@workflow/world/dist/steps.d.ts /** * Schema for workflow steps. * * Note: input/output use SerializedDataSchema to support both: * - specVersion >= 2: Uint8Array (binary devalue format) * - specVersion 1: any (legacy JSON format) */ declare const StepSchema: z.ZodObject<{ runId: z.ZodString; stepId: z.ZodString; stepName: z.ZodString; status: z.ZodEnum<{ pending: "pending"; running: "running"; completed: "completed"; failed: "failed"; cancelled: "cancelled"; }>; input: z.ZodOptional>, z.ZodType>]>>; output: z.ZodOptional>, z.ZodType>]>>; error: z.ZodOptional>, z.ZodType>]>>; attempt: z.ZodNumber; startedAt: z.ZodOptional>; completedAt: z.ZodOptional>; createdAt: z.ZodCoercedDate; updatedAt: z.ZodCoercedDate; retryAfter: z.ZodOptional>; specVersion: z.ZodOptional; }, z.core.$strip>; type Step = z.infer; /** A step with its first start time materialized. */ type StartedStep = Step & { startedAt: Date; }; /** * Step with input/output fields excluded (when resolveData='none'). * Used for listing steps without fetching the full serialized data. */ type StepWithoutData = Omit & { input: undefined; output: undefined; }; interface GetStepParams { resolveData?: ResolveData; } interface ListWorkflowRunStepsParams { runId: string; pagination?: PaginationOptions; resolveData?: ResolveData; } //#endregion //#region ../../node_modules/.pnpm/@workflow+world@5.2.2/node_modules/@workflow/world/dist/waits.d.ts declare const WaitSchema: z.ZodObject<{ waitId: z.ZodString; runId: z.ZodString; status: z.ZodEnum<{ completed: "completed"; waiting: "waiting"; }>; resumeAt: z.ZodOptional>; completedAt: z.ZodOptional>; createdAt: z.ZodCoercedDate; updatedAt: z.ZodCoercedDate; specVersion: z.ZodOptional; }, z.core.$strip>; type Wait = z.infer; //#endregion //#region ../../node_modules/.pnpm/@workflow+world@5.2.2/node_modules/@workflow/world/dist/events.d.ts declare const EventTypeSchema: z.ZodEnum<{ run_created: "run_created"; run_started: "run_started"; run_completed: "run_completed"; run_failed: "run_failed"; run_cancelled: "run_cancelled"; attr_set: "attr_set"; step_created: "step_created"; step_completed: "step_completed"; step_failed: "step_failed"; step_retrying: "step_retrying"; step_started: "step_started"; hook_created: "hook_created"; hook_received: "hook_received"; hook_disposed: "hook_disposed"; hook_conflict: "hook_conflict"; wait_created: "wait_created"; wait_completed: "wait_completed"; noop: "noop"; }>; type EventType = z.infer; /** * Event created when a workflow run is first created. The World implementation * atomically creates both the event and the run entity with status 'pending'. */ declare const RunCreatedEventSchema: z.ZodObject<{ correlationId: z.ZodOptional; specVersion: z.ZodOptional; eventType: z.ZodLiteral<"run_created">; eventData: z.ZodObject<{ deploymentId: z.ZodString; workflowName: z.ZodString; input: z.ZodUnion>, z.ZodType>]>; executionContext: z.ZodOptional>; attributes: z.ZodOptional>; allowReservedAttributes: z.ZodOptional>; dynamicWorkflowCode: z.ZodOptional>, z.ZodType>]>>; dynamicWorkflowCodeRef: z.ZodOptional; encryptionPublicKey: z.ZodOptional; startHook: z.ZodOptional; tokenRetentionUntil: z.ZodOptional>; metadata: z.ZodOptional>, z.ZodType>]>>; }, z.core.$strip>>; }, z.core.$strip>; }, z.core.$strip>; declare const CreateEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{ correlationId: z.ZodOptional; specVersion: z.ZodOptional; eventType: z.ZodLiteral<"run_created">; eventData: z.ZodObject<{ deploymentId: z.ZodString; workflowName: z.ZodString; input: z.ZodUnion>, z.ZodType>]>; executionContext: z.ZodOptional>; attributes: z.ZodOptional>; allowReservedAttributes: z.ZodOptional>; dynamicWorkflowCode: z.ZodOptional>, z.ZodType>]>>; dynamicWorkflowCodeRef: z.ZodOptional; encryptionPublicKey: z.ZodOptional; startHook: z.ZodOptional; tokenRetentionUntil: z.ZodOptional>; metadata: z.ZodOptional>, z.ZodType>]>>; }, z.core.$strip>>; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ correlationId: z.ZodOptional; specVersion: z.ZodOptional; eventType: z.ZodLiteral<"run_started">; eventData: z.ZodOptional>, z.ZodType>]>>; deploymentId: z.ZodOptional; workflowName: z.ZodOptional; executionContext: z.ZodOptional>; attributes: z.ZodOptional>; allowReservedAttributes: z.ZodOptional>; encryptionPublicKey: z.ZodOptional; dynamicWorkflowCode: z.ZodOptional>, z.ZodType>]>>; dynamicWorkflowCodeRef: z.ZodOptional; startHook: z.ZodOptional; tokenRetentionUntil: z.ZodOptional>; metadata: z.ZodOptional>, z.ZodType>]>>; }, z.core.$strip>>; }, z.core.$strip>>; }, z.core.$strip>, z.ZodObject<{ correlationId: z.ZodOptional; specVersion: z.ZodOptional; eventType: z.ZodLiteral<"run_completed">; eventData: z.ZodObject<{ output: z.ZodOptional>, z.ZodType>]>>; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ correlationId: z.ZodOptional; specVersion: z.ZodOptional; eventType: z.ZodLiteral<"run_failed">; eventData: z.ZodObject<{ error: z.ZodUnion>, z.ZodType>]>; errorCode: z.ZodOptional; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ correlationId: z.ZodOptional; specVersion: z.ZodOptional; eventType: z.ZodLiteral<"run_cancelled">; eventData: z.ZodOptional; }, z.core.$strip>>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"attr_set">; correlationId: z.ZodOptional; eventData: z.ZodObject<{ changes: z.ZodArray; }, z.core.$strip>>; writer: z.ZodDiscriminatedUnion<[z.ZodObject<{ type: z.ZodLiteral<"workflow">; }, z.core.$strip>, z.ZodObject<{ type: z.ZodLiteral<"step">; stepId: z.ZodString; attempt: z.ZodNumber; }, z.core.$strip>], "type">; allowReservedAttributes: z.ZodOptional>; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"step_created">; correlationId: z.ZodString; eventData: z.ZodObject<{ stepName: z.ZodString; workflowName: z.ZodOptional; input: z.ZodUnion>, z.ZodType>]>; inline: z.ZodOptional; creatorMessageId: z.ZodOptional; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"step_completed">; correlationId: z.ZodString; eventData: z.ZodObject<{ ttfs: z.ZodOptional; stso: z.ZodOptional; stepCount: z.ZodOptional; eventCount: z.ZodOptional; rsfs: z.ZodOptional; finalSchedulingReplay: z.ZodOptional; optimizations: z.ZodOptional>; stepName: z.ZodOptional; workflowName: z.ZodOptional; result: z.ZodUnion>, z.ZodType>]>; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"step_failed">; correlationId: z.ZodString; eventData: z.ZodObject<{ ttfs: z.ZodOptional; stso: z.ZodOptional; stepCount: z.ZodOptional; eventCount: z.ZodOptional; rsfs: z.ZodOptional; finalSchedulingReplay: z.ZodOptional; optimizations: z.ZodOptional>; stepName: z.ZodOptional; error: z.ZodUnion>, z.ZodType>]>; attempt: z.ZodOptional; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"step_retrying">; correlationId: z.ZodString; eventData: z.ZodObject<{ stepName: z.ZodOptional; error: z.ZodUnion>, z.ZodType>]>; retryAfter: z.ZodOptional>; attempt: z.ZodOptional; creatorMessageId: z.ZodOptional; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"step_started">; correlationId: z.ZodString; eventData: z.ZodOptional; attempt: z.ZodOptional; workflowName: z.ZodOptional; input: z.ZodOptional>, z.ZodType>]>>; inline: z.ZodOptional; ownerMessageId: z.ZodOptional; }, z.core.$strip>>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"hook_created">; correlationId: z.ZodString; eventData: z.ZodObject<{ token: z.ZodString; tokenRetentionUntil: z.ZodOptional>; metadata: z.ZodOptional>, z.ZodType>]>>; isWebhook: z.ZodOptional; isSystem: z.ZodOptional; force: z.ZodOptional; forceClaimedFrom: z.ZodOptional; deploymentId: z.ZodOptional; runSpecVersion: z.ZodOptional; }, z.core.$strip>>; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"hook_received">; correlationId: z.ZodString; eventData: z.ZodObject<{ token: z.ZodOptional; workflowName: z.ZodOptional; payload: z.ZodUnion>, z.ZodType>]>; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"hook_disposed">; correlationId: z.ZodString; eventData: z.ZodOptional; forceClaimedBy: z.ZodOptional>; }, z.core.$strip>>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"wait_created">; correlationId: z.ZodString; eventData: z.ZodObject<{ resumeAt: z.ZodCoercedDate; creatorMessageId: z.ZodOptional; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"wait_completed">; correlationId: z.ZodString; eventData: z.ZodOptional>; }, z.core.$strip>>; }, z.core.$strip>], "eventType">; declare const EventSchema: z.ZodIntersection; specVersion: z.ZodOptional; eventType: z.ZodLiteral<"run_created">; eventData: z.ZodObject<{ deploymentId: z.ZodString; workflowName: z.ZodString; input: z.ZodUnion>, z.ZodType>]>; executionContext: z.ZodOptional>; attributes: z.ZodOptional>; allowReservedAttributes: z.ZodOptional>; dynamicWorkflowCode: z.ZodOptional>, z.ZodType>]>>; dynamicWorkflowCodeRef: z.ZodOptional; encryptionPublicKey: z.ZodOptional; startHook: z.ZodOptional; tokenRetentionUntil: z.ZodOptional>; metadata: z.ZodOptional>, z.ZodType>]>>; }, z.core.$strip>>; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ correlationId: z.ZodOptional; specVersion: z.ZodOptional; eventType: z.ZodLiteral<"run_started">; eventData: z.ZodOptional>, z.ZodType>]>>; deploymentId: z.ZodOptional; workflowName: z.ZodOptional; executionContext: z.ZodOptional>; attributes: z.ZodOptional>; allowReservedAttributes: z.ZodOptional>; encryptionPublicKey: z.ZodOptional; dynamicWorkflowCode: z.ZodOptional>, z.ZodType>]>>; dynamicWorkflowCodeRef: z.ZodOptional; startHook: z.ZodOptional; tokenRetentionUntil: z.ZodOptional>; metadata: z.ZodOptional>, z.ZodType>]>>; }, z.core.$strip>>; }, z.core.$strip>>; }, z.core.$strip>, z.ZodObject<{ correlationId: z.ZodOptional; specVersion: z.ZodOptional; eventType: z.ZodLiteral<"run_completed">; eventData: z.ZodObject<{ output: z.ZodOptional>, z.ZodType>]>>; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ correlationId: z.ZodOptional; specVersion: z.ZodOptional; eventType: z.ZodLiteral<"run_failed">; eventData: z.ZodObject<{ error: z.ZodUnion>, z.ZodType>]>; errorCode: z.ZodOptional; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ correlationId: z.ZodOptional; specVersion: z.ZodOptional; eventType: z.ZodLiteral<"run_cancelled">; eventData: z.ZodOptional; }, z.core.$strip>>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"attr_set">; correlationId: z.ZodOptional; eventData: z.ZodObject<{ changes: z.ZodArray; }, z.core.$strip>>; writer: z.ZodDiscriminatedUnion<[z.ZodObject<{ type: z.ZodLiteral<"workflow">; }, z.core.$strip>, z.ZodObject<{ type: z.ZodLiteral<"step">; stepId: z.ZodString; attempt: z.ZodNumber; }, z.core.$strip>], "type">; allowReservedAttributes: z.ZodOptional>; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"step_created">; correlationId: z.ZodString; eventData: z.ZodObject<{ stepName: z.ZodString; workflowName: z.ZodOptional; input: z.ZodUnion>, z.ZodType>]>; inline: z.ZodOptional; creatorMessageId: z.ZodOptional; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"step_completed">; correlationId: z.ZodString; eventData: z.ZodObject<{ ttfs: z.ZodOptional; stso: z.ZodOptional; stepCount: z.ZodOptional; eventCount: z.ZodOptional; rsfs: z.ZodOptional; finalSchedulingReplay: z.ZodOptional; optimizations: z.ZodOptional>; stepName: z.ZodOptional; workflowName: z.ZodOptional; result: z.ZodUnion>, z.ZodType>]>; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"step_failed">; correlationId: z.ZodString; eventData: z.ZodObject<{ ttfs: z.ZodOptional; stso: z.ZodOptional; stepCount: z.ZodOptional; eventCount: z.ZodOptional; rsfs: z.ZodOptional; finalSchedulingReplay: z.ZodOptional; optimizations: z.ZodOptional>; stepName: z.ZodOptional; error: z.ZodUnion>, z.ZodType>]>; attempt: z.ZodOptional; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"step_retrying">; correlationId: z.ZodString; eventData: z.ZodObject<{ stepName: z.ZodOptional; error: z.ZodUnion>, z.ZodType>]>; retryAfter: z.ZodOptional>; attempt: z.ZodOptional; creatorMessageId: z.ZodOptional; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"step_started">; correlationId: z.ZodString; eventData: z.ZodOptional; attempt: z.ZodOptional; workflowName: z.ZodOptional; input: z.ZodOptional>, z.ZodType>]>>; inline: z.ZodOptional; ownerMessageId: z.ZodOptional; }, z.core.$strip>>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"hook_created">; correlationId: z.ZodString; eventData: z.ZodObject<{ token: z.ZodString; tokenRetentionUntil: z.ZodOptional>; metadata: z.ZodOptional>, z.ZodType>]>>; isWebhook: z.ZodOptional; isSystem: z.ZodOptional; force: z.ZodOptional; forceClaimedFrom: z.ZodOptional; deploymentId: z.ZodOptional; runSpecVersion: z.ZodOptional; }, z.core.$strip>>; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"hook_received">; correlationId: z.ZodString; eventData: z.ZodObject<{ token: z.ZodOptional; workflowName: z.ZodOptional; payload: z.ZodUnion>, z.ZodType>]>; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"hook_disposed">; correlationId: z.ZodString; eventData: z.ZodOptional; forceClaimedBy: z.ZodOptional>; }, z.core.$strip>>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"hook_conflict">; correlationId: z.ZodString; eventData: z.ZodObject<{ token: z.ZodString; conflictingRunId: z.ZodOptional; forceRefusedReason: z.ZodOptional>; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"wait_created">; correlationId: z.ZodString; eventData: z.ZodObject<{ resumeAt: z.ZodCoercedDate; creatorMessageId: z.ZodOptional; }, z.core.$strip>; }, z.core.$strip>, z.ZodObject<{ specVersion: z.ZodOptional; eventType: z.ZodLiteral<"wait_completed">; correlationId: z.ZodString; eventData: z.ZodOptional>; }, z.core.$strip>>; }, z.core.$strip>, z.ZodObject<{ correlationId: z.ZodOptional; specVersion: z.ZodOptional; eventType: z.ZodLiteral<"noop">; eventData: z.ZodOptional; }, z.core.$loose>>; }, z.core.$strip>], "eventType">, z.ZodObject<{ runId: z.ZodString; eventId: z.ZodString; createdAt: z.ZodCoercedDate; occurredAt: z.ZodOptional>; specVersion: z.ZodOptional; resumeId: z.ZodOptional; }, z.core.$strip>>; type Event = z.infer; /** * Union of all possible event request types. * @internal Use CreateEventRequest or RunCreatedEventRequest instead. */ type AnyEventRequest = z.infer; /** * Event request for creating a new workflow run. * Can be used with a client-generated runId or null for server-generated. */ type RunCreatedEventRequest = z.infer; /** * Event request types that require an existing runId. * This is the common case for all events except run_created. */ type CreateEventRequest = Exclude; interface CreateEventParams { v1Compat?: boolean; /** * Whether the run's orchestrator is making this write (spec >= 9). * * In-band writes are everything the orchestrator invocation writes: * `run_started`, `run_completed`, `run_failed`, `step_created`, * `wait_created`, `wait_completed`, `hook_created`, `hook_disposed`, an * `attr_set` from the workflow body, a `hook_received` it writes for a * resume carried on its own queue message, and every event of a step it * runs inline. Out-of-band writes are everything else: events from a * background step's invocation, `hook_received` from `resumeHook()` and * webhooks, `run_cancelled` from `cancel()`, and `attr_set` from * `setAttributes()` outside the workflow body. Classification is by writer, * not by event type. * * A World that creates spec 9 runs implements the in-band fence * (`WorldCapabilities.inBandFence`): it counts the positions it allocates to * in-band writes, and accepts an in-band write only when * {@link expectedSeqInBand} equals that count. */ inBand?: boolean; /** * The orchestrator's count of in-band positions, required with * `inBand: true` (a World answers an in-band write without it with a 400). * The runtime starts * it from {@link EventListResponse.snapshot}`.seqInBand` of the first page * of the delivery's full log load, and advances it by the number of * positions each accepted in-band write allocated (1 for a single create, * the event count for a batch). * * The World refuses a write whose value differs from its count with * `InBandSupersededError`, and writes and allocates nothing for it, so a * refusal never leaves a hole in the log. */ expectedSeqInBand?: number; /** * `'skip-step-inputs'` applies only to the event-log page this create * returns (the `sinceCursor` delta or a replay preload), never to the * created `event` or the returned `step` entity, whose `input` is what step * execution reads. See {@link EventsResolveData}. * * Code that forwards these params to an entity read (runs, steps, hooks, * whose `resolveData` is a plain {@link ResolveData}) must map them with * `entityResolveData()` first. */ resolveData?: EventsResolveData; /** * Lazy hook resume idempotency key. Set only by `resumeHook()` when it * persists a `hook_received` event whose creation must be deduplicated * against a concurrent re-ensure from the queue consumer. The World routes * it to the backend's `(runId, resumeId)` constraint so both writers * converge on exactly one event. Only meaningful for `hook_received`. */ resumeId?: string; /** * Content digest of the serialized resume payload, computed once by * `resumeHook()` and forwarded identically on the direct write and the queue * re-ensure. The World routes it to the backend so both writers record the * same digest on the `(runId, resumeId)` constraint. Only meaningful * alongside {@link resumeId}. */ resumePayloadDigest?: string; /** Require the server's deduplicated resolved-hook endpoint. Unsupported * backends must reject before writing rather than silently dropping dedup. */ requireHookResumeDedup?: boolean; /** * Marks a `step_created` create as the queue consumer's re-ensure of a * resilient step dispatch (a step message carrying `stepInput`, see * `WorkflowInvokePayload.stepInput`): the producer's direct write was * parallelized with the queue publish and may have failed. Only meaningful * for `step_created`. * * Advisory, and not set by the current `@workflow/core` runtime, which * publishes a step's queue message only after its create. A producer that * parallelizes the two accepts that a create can come back refused while * the message carrying its payload is already out, and a backend MAY use * this flag to narrow that window: refuse the re-ensure (world-vercel surfaces the * backend's 410 as `RunExpiredError`, which the consumer treats as "nothing * left to execute" and acks the message) when it has recorded a refusal for * this correlation id and no step entity exists. Best-effort by nature (a * marker written at refusal time cannot be ordered before the redelivery it * is meant to stop), so it hardens, and does not close, the window. Worlds * may ignore this flag entirely. */ viaStepDispatch?: boolean; /** * Marks a `step_failed` write that records the failure of a step body this * invocation already ran. Losing such a write to queue redelivery runs the * body again, so a World may keep a throttled write waiting longer than it * otherwise would (world-vercel waits until the invocation's deadline). * `step_failed` needs the mark because the runtime also writes it for a step * whose arguments failed to serialize, where no body ran. `step_completed` * and `step_retrying` are only ever written after a body ran. Advisory; * Worlds may ignore it. */ afterStepBody?: true; /** Request ID (x-vercel-id when on Vercel) for correlating request logs with workflow events. */ requestId?: string; /** * Compute instance whose handler is writing this event (`COMPUTE_INSTANCE_ID` * in @workflow/core). Ambient per-event identity like {@link requestId}, * which distinguishes invocations *within* an instance. Read back via * `AnalyticsEventSchema` / `AnalyticsStepSchema`. */ computeInstanceId?: string; /** * Creation time of the step a `step_started` starts, as epoch milliseconds: * the `createdAt` the World answered that step's `step_created` with. Set * only on the first-attempt `step_started` of a background step (one * created by `step_created`, and started by its own queue message), so a * World can report the step's creation-to-start latency without reading * the log. Request telemetry, not workflow state: Worlds may ignore it and * must not persist it into the event log. */ stepCreatedAt?: number; /** * How many events the writer held in its loaded log when it decided to write * this one: equivalently, the slot it expects to land on minus one. Sent by * the replay loop and the suspension handler, which merge the report below * back into their loaded log. Omitted by callers with no loaded log to be * stale against, the step executor included: for those the report would be * a read the World does for no one. Independent concurrent hook registrations * in a hooks-only suspension also omit it deliberately: the runtime verifies * their committed events together after every write settles, and reloads if * they do not form a complete suffix. Absence does not imply no loaded log; * without a count there is no evidence for count-based stale rejection. * * A World's slots are dense and 1-based (see `Storage.events`), so a count * and a position are the same number. An id that is not a position does not * produce a count here: it throws, since the runtime cannot state a * snapshot for a log it cannot place. Such a World attempts * `eventCount + 1`, and on contention **bumps** to the next free slot and * commits there anyway: a stale count never rejects a write. What it does * instead is report: when the committed slot is higher than the one asked * for, the events occupying the skipped slots come back on the success * response in {@link EventResult.events} / `cursor` / `hasMore`, so the * writer learns exactly what it had not seen. * * Understating is safe and overstating is not. A count below the writer's * true position only widens the reported span, and the client discards what * its log already holds. A count above it makes the World report less than * the writer is missing, which is a hole the writer never learns about. * * A batch of writes issued from one snapshot starts from the same * `eventCount`; they land on consecutive slots in whatever order the World * serializes them, which is why they can stay a parallel fan-out instead of * a chain of round-trips. The count a given write sends is the writer's * position *at that moment*, so it advances mid-batch as reported events are * folded back into the loaded log: a write issued after a sibling's * bump-and-report already holds the slots that report named, and asks for a * slot above them. * * For an in-band write on a spec >= 9 run the report is authoritative: the * success response carries every event in positions `eventCount + 1` up to * (not including) the write's own first position, in position order, each * committed or sealed. When the World cannot produce all of it within its * request budget it still answers success, with `hasMore: true` * ({@link EventResult}). The orchestrator consumes an * event it wrote that resolves a promise only after merging this report, * so the VM consumes events in log order. Out-of-band writes get no report. */ eventCount?: number; /** * Timestamp for when the event occurred on the client side. Worlds that * support this can persist it separately from `createdAt`, which represents * when the backing service accepted or stored the event. */ occurredAt?: Date; /** * Number of consecutive replay divergences resolved by this event write. * * This is request telemetry, not workflow state. Worlds may use it for * metrics and diagnostics, but must not require it for event * materialization or persist it into the event log. */ replayDivergenceCount?: number; /** * Inline-delta optimization (opt-in). When set, the World MAY return, * on the resulting {@link EventResult}, the first page of events written * strictly after this cursor (via `events`/`cursor`/`hasMore`): the * same page an `events.list({ cursor: sinceCursor, sortOrder: 'asc' })` * call would return immediately after this write. Outside turbo mode the * runtime sets this on every write it makes from the orchestrator loop * and folds any returned delta into its in-memory log, so each write * carries the log forward and the loop reads it back for free: instead of * re-reading its own just-written events (and any events interleaved * in-band, such as `hook_received`), it consumes the authoritative delta * the write already had to compute. Turbo mode does not set it: the * point there is to keep the first invocation's writes as cheap as * possible, and it has no loaded log to extend. * * The suspension handler sets it too, on the hook create of a single-hook * suspension. That write is the whole continuation for the hook's own * awaiter — the event it commits is what settles it — so a delta lets the * runtime advance the workflow in the same process instead of enqueueing a * message whose only job is to read back the event it just wrote. It is * asked for on one hook create per suspension because two creates issued * from the same cursor each diff against it, and only one of the returned * deltas can be folded into the log. * * A World that answers it on `hook_created` MUST answer it on the * `hook_conflict` a create whose token is already claimed commits instead. * That event settles the same awaiter — a payload await rejects, a * `hook.getConflict()` resolves with the conflicting run — and the runtime * continues over it in-process just the same, so withholding the delta * there would silently cost a delivery on exactly the path the caller * asked to avoid one on. The delta is keyed on the requested event type, * not the committed one; there is nothing extra to compute, since it is the * same slice of the log either way. * * The cursor MUST share `events.list` semantics: the returned `events` * are everything sorted strictly after `sinceCursor`, `cursor` is the * position past the last returned event, and `hasMore` indicates a * further page exists. A World MAY return a single page and set * `hasMore: true` rather than paginating to exhaustion. The runtime * consumes that page and continues from its cursor, so it never reads the * returned prefix again. * Returning these fields at all is OPTIONAL: a World that omits them is * fully supported; the runtime falls back to `events.list`. This * preserves the same divergence guarantees as the fetch path because the * delta is computed atomically against the same log the fetch would read. */ sinceCursor?: string; /** * Run-started preload opt-out (advisory). On a `run_started` write a World * MAY preload the run's event log onto the {@link EventResult} * (`events`/`cursor`/`hasMore`) so the runtime can skip its initial * `events.list`. The turbo first invocation backgrounds `run_started` * purely as a write barrier and never reads that preload, so it sets this * to tell the World to skip the wasted list+resolve, trimming the * `run_started` round-trip that the chained first `step_started` waits on. * A World that ignores it (or doesn't preload) remains fully correct: the * runtime falls back to `events.list` whenever it actually needs the log. * Only honored for `run_started`; ignored for other event types. * * Named to match the World boundary, the wire frame meta, and the backend * option end-to-end (cf. {@link sinceCursor}) so the single name greps * across the SDK and the backend. */ skipPreload?: true; /** * Replay-log preload opt-in (advisory): the `hook_received` dual of * {@link skipPreload}. Set only by the queue consumer's idempotent * `hook_received` re-ensure on a lazy hook resume (alongside * {@link resumeId} + {@link resumePayloadDigest}). A World MAY return the * run's current replay event log with the event creation * (`events`/`cursor`/`hasMore`, plus `run` and `maxEvents`) so the runtime * can initialize replay from this one request and skip both the * `run_started` write and the initial `events.list`. * * The runtime trusts a returned preload as replay input ONLY when all of * the following hold (a World that cannot guarantee them should return * its normal {@link EventResult} instead): * * - `events` is the COMPLETE log with `hasMore: false` (the runtime has no * cursor-continuation machinery on this path; a bounded page is * rejected). * - `cursor` is a valid non-null resume point matching `events.list` * semantics (present even on the final page). * - `run` (with `run.startedAt`) and `maxEvents` are present: this * response plays `run_started`'s role, including the event-ceiling * handshake. * - The log contains the run's creation (`run_created`, or a creating * `run_started` at the first slot: `isRunCreationEvent`), `run_started`, * and the canonical * `hook_received` carrying the requested {@link resumeId}. * - `events` uses the same ascending ordering semantics as `events.list`. * - The log is read atomically/consistently WITH (i.e. no earlier than) * the `hook_received` write, so no concurrently committed event can be * omitted from the replay input. * * Anything less and the runtime observes that no usable replay preload * came back and falls back to the existing `run_started` setup. A World * that ignores the param entirely remains fully correct. Only meaningful * for `hook_received`; ignored for other event types. Producer-side * `resumeHook()` must not set it. */ preloadEvents?: true; /** * Synchronously observes each validated event in a streamed replay-log * response. A retried request may observe the same event again; observers * must therefore be idempotent. Throwing aborts the operation and the World * must surface the original error without retrying or reclassifying it. */ replayEventObserver?: (event: Event) => void; } /** * Result of creating an event. Includes the created event and optionally * the entity that was created or updated as a result of the event, with any updates applied to it. * * Note: `event` is optional to support legacy runs where event storage is skipped. */ type EventResult = { /** The created event (optional for legacy compatibility) */ event?: Event; /** * Optional ascending events.list cursor immediately after `event`, minted * by the World that owns the cursor format. This does not attest that the * caller holds any earlier events. The runtime may advance to it only after * proving that its loaded prefix plus committed responses covers every slot * through this event. Worlds that omit it retain the normal reload path. * When supplied, `event` MUST match what ascending events.list returns for * that slot with the same resolveData option, including stored timestamps, * normalized retention, metadata bytes, and hook-conflict details. The * runtime uses this stored event as replay input, not an echo of the request. */ eventCursor?: string; /** The workflow run entity (for run_* events) */ run?: WorkflowRun; /** The step entity (for step_* events) */ step?: Step; /** The hook entity (for hook_created events) */ hook?: Hook; /** The wait entity (for wait_created/wait_completed events) */ wait?: Wait; /** * Lazy step start: set to `true` only when a `step_started` event with * step-creation data atomically *created* the step on this call (the * caller won the create-claim), as opposed to transitioning a step that * already existed. The owned-inline runtime path uses this as the * exactly-once ownership signal: it runs the step body inline only when * it created the step, so a concurrent handler that lost the create race * (and gets `EntityConflictError`/skipped) never double-executes. Absent * (undefined) on the legacy path and from older servers/worlds, which is * the safe default (treated as "not the lazy creator"). */ stepCreated?: true; /** Server-owned max event count for the run (run-lifecycle responses); the runtime enforces it. */ maxEvents?: number; /** * How many positions this write allocated (spec >= 9): * 1 for a create that appended its event, 0 for one that converged on an * event the log already held (an idempotent replay). The orchestrator * advances its in-band count by this number. Absent from a World that * does not report it; the runtime then infers it. */ allocated?: number; } & ({ /** * Events with data resolved. Five producers populate this: * * - On a `run_started` response: all events up to this point, so the * runtime can skip the initial `events.list` call and reduce TTFB. * - On a step-terminal write (`step_completed` / `step_failed`) when * the caller passed {@link CreateEventParams.sinceCursor}: the delta * of events written strictly after that cursor, so the inline loop * can skip the per-step incremental `events.list` round-trip. * - On a hook-create write when the caller passed * {@link CreateEventParams.sinceCursor}: the same delta, which * includes the event the create committed — the `hook_created`, or * the `hook_conflict` of an already-claimed token — so the hook's * awaiter can be settled in the writing process rather than by a * re-invocation that reads the event back. * - On a `hook_received` response when the caller passed * {@link CreateEventParams.preloadEvents}: the run's current replay * log through the canonical `hook_received`, so the lazy hook queue * consumer can skip both the `run_started` write and the initial * `events.list`. * - On any response whose committed slot came out higher than the one * {@link CreateEventParams.eventCount} asked for: * the events occupying the slots that were skipped over, in slot * order. This is the "report" half of bump-and-report: the write * succeeded, and these are the events the writer had not seen when it * decided to make it. */ events: Event[]; /** Pagination cursor for `events`, matching events.list semantics. */ cursor: string | null; /** * Whether additional event pages are available for `events`. On an * in-band write's response (spec >= 9), `true` also means the World * could not produce the complete skipped-slot report within its * request budget: the write committed, and the writer must reload the * log before it consumes anything the write resolves, since the report * may be missing events that sit below its own. */ hasMore: boolean; } | { events?: undefined; cursor?: undefined; hasMore?: undefined; }) & (T extends 'run_created' ? { run: WorkflowRun; } : T extends 'run_started' ? { run: StartedWorkflowRun; } : T extends 'step_started' ? { /** * The started step, on a run that keeps step entities (spec 8 and * below). A single-orchestrator run (spec >= 9) keeps none, so * its start returns no step. */ step?: StartedStep; } : unknown); /** * One event of a batch write ({@link Storage.events.createBatch}), in request * order, which is the order the events land in the run's log. */ interface BatchEventRequest { /** The event, same discriminated union the single `create` takes. */ event: CreateEventRequest; /** * Client event time for this event. Under slot identity this is the source * of the durable event's `createdAt` (a slot id carries no time), so the * timestamp a replay observes is the one the writer chose: set it to the * instant the event logically occurred. */ occurredAt?: Date; /** * Compute-instance attribution for this event, same as the single create's * {@link CreateEventParams.computeInstanceId}. Set on the `step_started` * half of a pre-claimed inline pair so a batched claim attributes the * executing instance exactly like the lazy claim it replaces. */ computeInstanceId?: string; /** * Step creation time for a `step_started`, same as the single create's * {@link CreateEventParams.stepCreatedAt}. */ stepCreatedAt?: number; } /** Per-batch parameters for {@link Storage.events.createBatch}. */ interface CreateEventBatchParams { resolveData?: ResolveData; /** * Request id for per-write attribution, same as the single create's * {@link CreateEventParams.requestId}: stamped on every event in the batch * so a batched write's usage facts and telemetry carry the same request * attribution its single-path twin would. */ requestId?: string; /** * Whether the run's orchestrator makes this batch (spec >= 9), as * {@link CreateEventParams.inBand}. Every event of a batch shares it. */ inBand?: boolean; /** * The orchestrator's in-band count for the whole block, as * {@link CreateEventParams.expectedSeqInBand}. The World allocates the * block's positions in one conditional allocation. */ expectedSeqInBand?: number; /** * The position the batch was decided from, as * {@link CreateEventParams.eventCount}; required with `inBand: true`. The * response then carries the skipped-slot report for * the block at the top level (`events` / `hasMore` on * {@link EventBatchResult}). */ eventCount?: number; } /** * One event's outcome in a batch response, index-aligned with the submitted * events. `error === undefined` discriminates success. * * A batch is processed as a whole (HTTP 200 whenever the World evaluated it); * each event reports the outcome its OWN single `create` would have had: * * - success → `status: 200` plus the committed event and the same * materialized entity the single create returns (`step` for step events, * `wait` for wait events, `run` for run terminals); * - rejection → the status code and error code the single create would have * failed with, so callers reuse their single-path conflict handling per * event. A `409`/`conflict` means the entity was not in the prior state * the event requires, most commonly because an earlier delivery already * applied the same event, but possibly because the entity reached a * DIFFERENT state (e.g. `step_completed` conflicting because the step * failed). A 409 alone does not prove the equivalent effect was applied; * a caller that needs effect-equivalence consults the entity (returned on * sibling successes, or reloaded). * * The batch is atomic per attempt, not all-or-nothing across the submitted * set: a World may drop rejected events and commit the survivors, so a batch * can return a mix of 200s and 409s from one call. * * Retry semantics: a transport retry of a committed batch converges to * per-event 409s ONLY for entity-conditioned events: creates and terminal * transitions. A standalone bare `step_started` or a `step_retrying` * re-patches its step on every attempt and does NOT converge, and * `hook_received` appends a new row per attempt, so `world-vercel` rejects * `hook_received` in a batch outright and only auto-retries batches whose * every event is retry-convergent. * * The born-running `step_created`+`step_started` pair converges (the pair's * create fences it) but is still excluded from auto-retry, because * convergence alone is not enough for the caller: a pair 409 means "this step * already exists", and on a retry that is indistinguishable from "my own * previous attempt committed it". A caller that reads the 409 as a lost claim * would skip a body it actually owns, so a batch carrying a `step_started` * runs single-attempt and leaves transient-failure recovery to queue * redelivery. */ type BatchEventItemResult = { status: 200; error?: undefined; message?: undefined; event: Event; run?: WorkflowRun; step?: Step; wait?: Wait; } | { status: number; error: string; message: string; event?: undefined; run?: undefined; step?: undefined; wait?: undefined; }; /** Result of {@link Storage.events.createBatch}. */ interface EventBatchResult { /** One entry per submitted event, in request order. */ results: BatchEventItemResult[]; /** * The skipped-slot report of an in-band batch (spec >= 9): the events in * positions `eventCount + 1` up to the block's first position. */ events?: Event[]; /** * `true` when the skipped-slot report in `events` is incomplete, as * `hasMore` on an in-band write's {@link EventResult}: the writer reloads * the log before it consumes anything the batch resolves. */ hasMore?: boolean; /** * How many positions the batch allocated: the admitted items, one block. * As {@link EventResult.allocated}; absent when the World does not report * it. */ allocated?: number; } interface GetEventParams { resolveData?: ResolveData; /** * The run's spec version, when the caller knows it. A hint a World may use * to pick how it reads; it never changes which event is returned. See * {@link ListEventsParams.specVersion}. */ specVersion?: number; } /** * The sequencer state a World read, strongly consistently, before it listed * a run's log (spec >= 9). Positions are slots. */ interface EventLogSnapshot { /** Highest position allocated to any write when the list began. */ seq: number; /** Number of positions allocated to in-band writes when the list began. */ seqInBand: number; } /** * Result of {@link Storage.events.list}. * * `snapshot` is set by a World that implements the in-band writer fence * (`WorldCapabilities.inBandFence`), on every page of a slot-numbered run's * log where the World reads one. It is read before the listing, so a full * load (following `cursor` until `hasMore` is false) covers every position * up to the FIRST page's `snapshot.seq`, each one committed or sealed as a * `noop`. A fenced writer takes its * {@link CreateEventParams.expectedSeqInBand} from the first page's * `snapshot.seqInBand`, never from counting events: a count cannot tell * which positions were in-band. * * On a single-orchestrator run (spec >= 9) it is required on every page: the * runtime refuses to write in-band from a full load whose first page has * none. On earlier runs a fencing World that lists no snapshot reports the * counters on a refusal (`InBandSupersededError`) instead. */ type EventListResponse = PaginatedResponse & { snapshot?: EventLogSnapshot; /** * The run's event ceiling, the same value {@link EventResult.maxEvents} * carries on a run-lifecycle write. Optional: a World that does not report * it here leaves the runtime with the ceiling from its own `run_started` * write, if any. The spec 9 orchestrator, which writes `run_started` only on * a run's first delivery, enforces it on every later one from its log load. */ maxEvents?: number; }; /** Options for {@link Storage.events.subscribe}. */ interface EventsSubscribeOptions { /** Called once when the World stops delivering for a transport reason. */ onError?: (error: unknown) => void; } interface ListEventsParams { runId: string; /** Omit `limit` to return every remaining event. */ pagination?: PaginationOptions; resolveData?: EventsResolveData; /** * Aborted when the caller has given up on the read. A World may stop the * request early and reject; one that ignores it is still correct, since the * caller no longer uses the result. */ signal?: AbortSignal; /** * The run's spec version, when the caller knows it. A hint a World may use * to pick how it reads; it never changes which events are returned. The * spec 9 orchestrator passes it on its own log loads, which need * {@link EventListResponse.snapshot}: world-vercel reads a run stamped 9 or * above from the route that reports it, and every other read from the route * earlier releases use. A World that always returns `snapshot` can ignore * it. */ specVersion?: number; } interface ListEventsByCorrelationIdParams { correlationId: string; /** * The run the correlation id belongs to. A correlation id is unique per * run, not globally: a slot-numbered run counts its own steps and waits, so * `step_…001` names the first step of *every* such run. Naming the run is * what makes the answer that run's events, and it is what makes the * pagination cursor unambiguous: `(runId, eventId)` is a key where an * event id alone is not. */ runId: string; pagination?: PaginationOptions; resolveData?: ResolveData; } //#endregion //#region ../../node_modules/.pnpm/@workflow+world@5.2.2/node_modules/@workflow/world/dist/attributes-validation.d.ts /** A single run-attribute change. `null` removes the key. */ interface AttributeChange { key: string; value: string | null; } //#endregion //#region ../../node_modules/.pnpm/@workflow+world@5.2.2/node_modules/@workflow/world/dist/attributes.d.ts /** The post-merge attribute snapshot returned by a World. */ interface ExperimentalSetAttributesResult { attributes: Record; } //#endregion //#region ../../node_modules/.pnpm/@workflow+world@5.2.2/node_modules/@workflow/world/dist/queue.d.ts /** * Pattern matching valid queue prefixes: * - `__wkf_workflow_` (default, no namespace) * - `__{namespace}_wkf_workflow_` (namespaced) * * Namespace must be lowercase alphanumeric starting with a letter. */ declare const QueuePrefix: z$1.ZodString; type QueuePrefix = z$1.infer; declare const ValidQueueName: z$1.ZodString; type ValidQueueName = z$1.infer; declare const MessageId: z$1.core.$ZodBranded; type MessageId = z$1.infer; /** * 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. */ declare const QueuePayloadSchema: z$1.ZodUnion; correlationId: z$1.ZodString; probeRunId: z$1.ZodOptional; runId: z$1.ZodOptional; }, z$1.core.$strip>, z$1.ZodObject<{ runId: z$1.ZodString; runSpecVersion: z$1.ZodCatch>; recovery: z$1.ZodCatch>>; invoke: z$1.ZodOptional>; requestId: z$1.ZodOptional; input: z$1.ZodOptional; traceCarrier: z$1.ZodOptional>; requestedAt: z$1.ZodOptional>; replayDivergence: z$1.ZodOptional>>; }, z$1.core.$strip>>; preconditionReinvocations: z$1.ZodOptional; serverErrorRetryCount: z$1.ZodOptional; deploymentMismatchRetryCount: z$1.ZodOptional; waitContinuation: z$1.ZodCatch; hopAtMs: z$1.ZodOptional; }, z$1.core.$strip>>>; completeWaits: z$1.ZodCatch>>; stepId: z$1.ZodOptional; stepName: z$1.ZodOptional; stepAttempt: z$1.ZodOptional; stepResent: z$1.ZodOptional; stepCreatedEventId: z$1.ZodOptional; stepCreatedAt: z$1.ZodCatch>; runInput: z$1.ZodOptional>; dynamicWorkflowCode: z$1.ZodOptional>, z$1.ZodType>]>>; dynamicWorkflowCodeRef: z$1.ZodOptional; attributes: z$1.ZodOptional>; allowReservedAttributes: z$1.ZodOptional>; encryptionPublicKey: z$1.ZodOptional; startHook: z$1.ZodOptional; tokenRetentionUntil: z$1.ZodOptional>; metadata: z$1.ZodOptional>, z$1.ZodType>]>>; }, z$1.core.$strip>>; environment: z$1.ZodOptional; }, z$1.core.$strip>>; hookInput: z$1.ZodOptional; }, z$1.core.$strip>>; stepInput: z$1.ZodOptional, Uint8Array>; }, z$1.core.$strip>>; runContext: z$1.ZodOptional; rootRunId: z$1.ZodOptional; }, z$1.core.$strip>>; hookResumeTiming: z$1.ZodCatch; consumerStartedAtMs: z$1.ZodOptional; replayStartedAtMs: z$1.ZodOptional; nextStepEncounteredAtMs: z$1.ZodOptional; setupSource: z$1.ZodOptional; }, z$1.core.$strip>>>; }, z$1.core.$strip>]>; type QueuePayload = z$1.infer; 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 */ 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 */ 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 */ 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 */ 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 */ type QueueHoldResult = HeldQueueMessage | NotHeldQueueMessage; /** What {@link Queue.queue} resolves with. */ 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. */ 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`. */ 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; }; 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). */ type QueueAuthMode = 'loopback' | 'skip'; 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; } //#endregion //#region ../../node_modules/.pnpm/@workflow+world@5.2.2/node_modules/@workflow/world/dist/snapshots.d.ts /** @experimental See `Storage.experimental_snapshots`. */ declare const SnapshotMetadataSchema: z.ZodObject<{ eventsCursor: z.ZodNullable; createdAt: z.ZodCoercedDate; eventCount: z.ZodOptional; rngDraws: z.ZodOptional; serdeRootPtr: z.ZodOptional; lastUlid: z.ZodOptional; engineVersion: z.ZodOptional; clockMs: z.ZodOptional; formatVersion: z.ZodOptional; }, z.core.$strip>; /** @experimental See `Storage.experimental_snapshots`. */ type SnapshotMetadata = z.infer; //#endregion //#region ../../node_modules/.pnpm/@workflow+world@5.2.2/node_modules/@workflow/world/dist/interfaces.d.ts interface StreamWriteSession { /** * Write one ordered group from this in-memory writer lifetime. * `chunkSeq` is writer-local and identifies the first chunk in `chunks`. */ write(chunkSeq: number, chunks: (string | Uint8Array)[]): Promise; /** Close this writer lifetime after all prior writes are durable. */ close(): Promise; /** * Release an idle transport after accepted writes are durable, without * closing the stream or invalidating this writer. Later writes and close * must remain usable (for example, over stateless HTTP). */ release?(): Promise | void; /** Release transport resources without semantically closing the stream. */ dispose?(): Promise | void; } interface CreateStreamWriteSessionOptions { /** Stable observational id for this in-memory writer lifetime. */ writerId: `wrtr_${string}`; } interface Streamer { /** * Number of milliseconds a stream waits for additional chunks to arrive * before flushing to the underlying transport. * * Default `0`: the first chunk dispatches immediately, and chunks * arriving while a request is in flight coalesce into the next group. * Setting this to > 0 trades first-chunk latency for fewer requests. * * The `WORKFLOW_STREAM_FLUSH_INTERVAL_MS` environment variable, when * set, overrides this option. * * Not supported by all worlds. */ streamFlushIntervalMs?: number; streams: { /** * Optionally create a stateful writer session. Core creates at most one * session per in-memory WritableStream and otherwise uses the stateless * write/writeMulti/close methods below unchanged. */ createWriteSession?(runId: string, name: string, options: CreateStreamWriteSessionOptions): StreamWriteSession; write(runId: string, name: string, chunk: string | Uint8Array): Promise; /** * Write multiple chunks to a stream in a single operation. * This is an optional optimization for world implementations that can * batch multiple writes efficiently (e.g., single HTTP request for world-vercel). * * If not implemented, the caller should fall back to sequential write() calls. * * @param runId - The run ID * @param name - The stream name * @param chunks - Array of chunks to write, in order */ writeMulti?(runId: string, name: string, chunks: (string | Uint8Array)[]): Promise; close(runId: string, name: string): Promise; /** * Read from a stream starting at the given chunk index. * Positive values skip that many chunks from the start (0-based). * Negative values start that many chunks before the current end * (e.g. -3 on a 10-chunk stream starts at chunk 7). Clamped to 0. */ get(runId: string, name: string, startIndex?: number): Promise>; list(runId: string): Promise; /** * Fetch stream chunks with cursor-based pagination. * * Unlike `get` (which returns a live `ReadableStream` that waits * for new chunks in real-time), `getChunks` returns a snapshot of currently * available chunks in a standard paginated response. * * @param runId - The workflow run ID that owns the stream * @param name - The stream name/ID * @param options - Pagination options (limit defaults to 100, max 1000) * @returns Paginated chunks with a `done` flag indicating stream completion */ getChunks(runId: string, name: string, options?: GetChunksOptions): Promise; /** * Retrieve lightweight metadata about a stream. * * Returns the tail index (index of the last known chunk, 0-based) and * whether the stream is complete. This is useful for resolving a negative * `startIndex` into an absolute position before connecting to a stream. * * @param runId - The workflow run ID that owns the stream * @param name - The stream name/ID */ getInfo(runId: string, name: string): Promise; }; } /** * Storage interface for workflow data. * * Workflow storage models an append-only event log, so all state changes are handled through `events.create()`. * Run/Step/Hook entities provide materialized views into the current state, but entities can't be modified directly. * * User-originated state changes are also handled via events: * - run_cancelled event for run cancellation * - hook_disposed event for explicit hook disposal (optional) * * When a workflow reaches a terminal state, its Hooks can no longer be resumed. * Worlds normally remove them and release their tokens. A Hook with minimum * retention remains readable and keeps its token unavailable until its retention * ends. A hook_disposed event always removes the Hook and releases its token. */ interface Storage { runs: { get(id: string, params: GetWorkflowRunParams & { resolveData: 'none'; }): Promise; get(id: string, params?: GetWorkflowRunParams & { resolveData?: 'all'; }): Promise; get(id: string, params?: GetWorkflowRunParams): Promise; /** * Long poll for a run to reach a terminal status (`completed`, `failed`, * or `cancelled`), returning the same entity `get` returns. * * This is how a caller awaiting a run's outcome (`await run.returnValue`) * avoids paying interval-poll quantization for it: instead of asking * "is it done yet?" every second, it asks once and the World answers the * moment the run finishes. * * The contract: * * - **Resolve as soon as the run is terminal**, with the run entity in * the shape `params.resolveData` asks for. * - **Resolve no later than roughly `params.timeoutMs`** with the latest * snapshot, whatever its status. A timeout is a normal return, never an * error: a run that is still running is a legitimate answer. * - **`timeoutMs` is an upper bound, not a lower one.** An * implementation MAY resolve earlier with a non-terminal snapshot. For * example, `@workflow/world-vercel` does when the backend it is talking * to has no long-poll route and it degrades to a plain read. Callers * must therefore pace their own retries rather than assume one call per * `timeoutMs` (the runtime's `Run#pollReturnValue` keeps consecutive * non-terminal observations at least one poll interval apart). * - **Fail exactly like `get`.** A missing run throws * `WorkflowRunNotFoundError`; transport failures surface as they would * on any other read. * * OPTIONAL. Omit it entirely when the World has no way to wait (a * deterministic simulator, a store with no change notification) and the * runtime keeps interval-polling `get` on * `WORKFLOW_RETURN_VALUE_POLL_INTERVAL_MS`. There is nothing to declare * beyond the method's presence, and no behavior degrades when it is * absent: the fast path is strictly additive. * * Implementations are free to satisfy this however their backend allows, * such as a server-side long poll (`world-vercel` holds * `GET /v2/runs/:runId/status` open), a change notification * (`world-postgres` uses `LISTEN`/`NOTIFY`, `world-local` an in-process * emitter), or a tight internal poll, as long as a lost or missing * notification degrades to returning a snapshot rather than hanging past * the budget. */ waitForTerminalStatus?: { (id: string, params: WaitForTerminalRunStatusParams & { resolveData: 'none'; }): Promise; (id: string, params?: WaitForTerminalRunStatusParams & { resolveData?: 'all'; }): Promise; (id: string, params?: WaitForTerminalRunStatusParams): Promise; }; /** * Retrieves several runs as one snapshot. The result preserves the input * order and contains `null` for run IDs that do not exist. */ getMany?: { (ids: readonly string[], params: GetWorkflowRunParams & { resolveData: 'none'; }): Promise<(WorkflowRunWithoutData | null)[]>; (ids: readonly string[], params?: GetWorkflowRunParams & { resolveData?: 'all'; }): Promise<(WorkflowRun | null)[]>; (ids: readonly string[], params?: GetWorkflowRunParams): Promise<(WorkflowRun | WorkflowRunWithoutData | null)[]>; }; /** * Lists canonical workflow storage records. * * @remarks Observability and inspection usage of this method is * deprecated. Use `world.analytics?.runs.list()` for plan-aware * observability queries. This storage API remains available for * operational and payload-bearing callers. */ list(params: ListWorkflowRunsParams & { resolveData: 'none'; }): Promise>; list(params?: ListWorkflowRunsParams & { resolveData?: 'all'; }): Promise>; list(params?: ListWorkflowRunsParams): Promise>; /** * Apply a batch of attribute changes to a run. Merge semantics: * - `value: string` upserts the key * - `value: null` removes the key * - keys not listed in `changes` are untouched * * Returns the post-merge attribute snapshot on the run. * * Pass `options.allowReservedAttributes: true` to permit keys * starting with the reserved `$` prefix. Default behavior rejects * those keys so user code can't accidentally collide with * framework / tooling namespaces; framework callers that own a * sub-namespace flip this on. * * OPTIONAL. World implementations may omit this method; the SDK * helper (`setAttributes` in `@workflow/core`) feature-detects its * absence and no-ops with a one-time warning so third-party / * community worlds keep working without adopting the experimental * API. * * EXPERIMENTAL: this method exists as a stopgap until the * `attr_set` event type lands in a future spec version. When that * happens, `setAttributes` will dispatch through `events.create` * instead, and this method is expected to be removed. See the * `attributes-mvp` changelog entry for the migration shape. */ experimentalSetAttributes?(runId: string, changes: AttributeChange[], options?: { allowReservedAttributes?: boolean; }): Promise; /** * Cancel many runs in a single operation, returning a per-run outcome * for each requested ID (order preserved) plus an aggregate summary. * * OPTIONAL. The SDK helper `cancelRuns` in `@workflow/core` falls back to * bounded-concurrency single-run cancellation when unavailable. */ cancelMany?(request: BulkCancelWorkflowRunsRequest): Promise; }; steps: { get(runId: string, stepId: string, params: GetStepParams & { resolveData: 'none'; }): Promise; get(runId: string, stepId: string, params?: GetStepParams & { resolveData?: 'all'; }): Promise; get(runId: string, stepId: string, params?: GetStepParams): Promise; list(params: ListWorkflowRunStepsParams & { resolveData: 'none'; }): Promise>; list(params: ListWorkflowRunStepsParams & { resolveData?: 'all'; }): Promise>; list(params: ListWorkflowRunStepsParams): Promise>; }; /** * The event log, and the one part of this interface with a requirement the * types cannot express: **the World allocates every event id, and every id * is a slot**: `evnt_` followed by the event's dense, 1-based position in * its run's log, zero-padded to 26 characters. Use `slotToEventId()` to * format one. * * Not a capability to opt into. The runtime reads a position out of every id * it loads (`requireEventSlot`) and fails the run if it cannot, so a World * whose ids are not positions cannot replay anything at all. Two properties * are what the runtime actually relies on: * * - **Density.** A run's slots are contiguous from 1, so the number of * events a reader holds *is* the position of the last one. That is what * makes {@link CreateEventParams.eventCount} a complete statement of the * writer's snapshot in a single integer, and what lets a reader tell a * complete log from a truncated one by its length. * - **Bump and report.** A create never fails because its requested slot is * taken. The World advances to the next free slot, commits there, and * returns the events occupying the slots it skipped over on the success * response (see {@link EventResult.events}). The writer learns its * snapshot was stale without the write being rejected, which is why no * World needs a precondition guard. * * Allocating at the commit is what makes a reader's log a *prefix* of the * run's log rather than a prefix with a hole in it. A World that hands a * position out earlier, and can therefore let an event land behind one a * reader has already passed, breaks the property every replay depends on. * * **Single-orchestrator runs (spec >= 9).** One orchestrator invocation * makes every decision for a run, and the runtime keeps every invariant of * the step and wait lifecycles itself: * * - Step and wait events (`step_created`, `step_started`, `step_retrying`, * `step_completed`, `step_failed`, `wait_created`, `wait_completed`) are * appends. A World MAY keep step and wait entities and MAY refuse writes * that do not fit them (409, 404, 425), but the runtime never relies on a * refusal for them: it decides from the log alone, so a World that * accepts every such append is fully correct. Refusing a step or wait * write on a terminal run (`step_created`, `step_started`, * `step_retrying`, `wait_created`) is still expected; `step_completed`, * `step_failed` and `wait_completed` must stay accepted after the run * ended. * - Each write says whether the orchestrator made it * ({@link CreateEventParams.inBand}). The **in-band fence** is required * for these runs: `list` returns a `snapshot`, and a stale in-band write * is refused with `InBandSupersededError` before anything is written, * which keeps the run to one writer even when two orchestrator * invocations overlap. The queue delivering a run's orchestrator * messages one at a time (`WorldCapabilities.maxConcurrency`) makes such * an overlap rare; the fence is what makes it safe. A World declares the * fence with `WorldCapabilities.inBandFence`; the runtime refuses to * create or drive a spec 9 run on a World that does not, and such a * World creates spec 8 runs (see `mintedSpecVersion`). * - An in-band write's `createdAt` is the `occurredAt` it was sent with * ({@link CreateEventParams.occurredAt}), on creates and on batch items * alike. The runtime's run-ahead hands an inline step's outcome to the * workflow before the write commits, and the workflow clock * (`Date.now()`) moves to that event's `createdAt`; replay reads the * stored one, so the two must be the same. The runtime checks every * speculative write's stored time, and on a mismatch stops the delivery * before anything else is written and turns run-ahead off for the World * for the rest of the process. * - A `createBatch` on such a run is not atomic: an event of the batch may * commit while another fails, and the runtime treats per-item results * independently. It is ordered per entity: once the World refuses an * item, it refuses every later item of the batch with the same * `correlationId` too, so a step's outcome never commits behind its * refused creation. The runtime relies on this to let one batch carry * several writes for one step. A World without `createBatch` meets it * trivially. */ events: { /** * Create a run_created event to start a new workflow run. * The runId may be provided by the client or left as null for the server to generate. * * A World declaring `capabilities.atomicStartHook` admits a * `run_created` (or resilient `run_started`) carrying * `eventData.startHook` under the contract in `start-hook.ts`: one * immutable decision per candidate `runId`, `HookConflictError` with * `conflictingRunId` for a refused candidate, `run.startHook` echoed for * an accepted one, and `WorkflowWorldError` with code * `START_HOOK_ADMISSION_REJECTED` for a request it will never admit. * * @param runId - Client-generated runId, or null for server-generated * @param data - The run_created event data * @param params - Optional parameters for event creation * @returns Promise resolving to the created event and run entity */ create(runId: string | null, data: T, params?: CreateEventParams): Promise>; /** * Create an event for an existing workflow run and atomically update the entity. * Returns both the event and the affected entity (run/step/hook). * * @param runId - The workflow run ID (required for all events except run_created) * @param data - The event to create * @param params - Optional parameters for event creation * @returns Promise resolving to the created event and affected entity */ create(runId: string, data: T, params?: CreateEventParams): Promise>; /** * OPTIONAL batch write: append an ordered list of events to the run's * log in one durable, atomic-per-attempt write, with a per-event outcome * for each (see {@link BatchEventItemResult}). The events land in request * order at consecutive slots. A concurrent writer may push the whole * batch to slots above the caller's view of the log; no skipped-event * report accompanies the result, so a position-tracking caller compares * the committed slots against its expectation and reloads the log to * observe what landed in between. Its local view stays a strict PREFIX * of the log (never a hole), so replaying it stays correct and the * next reload self-corrects. * * Presence of the method IS the capability declaration: the core runtime * batches only when the World implements it (and the run's spec version * supports slot identity); absent, every write takes the single-event * `create` path unchanged. A World must implement it with real * atomicity per attempt (a lost race must leave nothing behind) or not * implement it at all. * * Size limits are the caller's problem: Worlds enforce their own caps * (world-vercel enforces an event-count cap and a byte budget over frame * meta plus inline-bound payloads) and reject an oversized batch with a * request-level error. The core fold sizes its chunks accordingly. * * Not expressible in a batch (Worlds reject the whole batch with a * request-level error): `run_created`, `run_started`, `run_cancelled`, * `hook_created`, `hook_disposed`, `attr_set`, and more events targeting * one entity than a single write can express (the one legal combination * is `step_created` followed by `step_started` for the same step, which * creates the step born-running: the step's input MUST ride the * `step_created`; a `step_started` carrying a payload rejects the whole * batch). Events outside this list keep their own ordering requirements: * a caller mixing a batch with single writes (hook or attribute events) * owns those barriers itself: the core runtime never batches a * suspension that carries attribute writes, and writes a suspension's * hook events through the single path concurrently with its batch. * * The design is described in * `packages/core/src/runtime/spec8/batched-event-writes.md` in the Workflow * SDK repository. */ createBatch?(runId: string, events: BatchEventRequest[], params?: CreateEventBatchParams): Promise; get(runId: string, eventId: string, params?: GetEventParams): Promise; list(params: ListEventsParams): Promise; listByCorrelationId(params: ListEventsByCorrelationIdParams): Promise>; /** * OPTIONAL live feed of a run's log. The runtime calls it while an * orchestrator invocation is alive and blocked (for example while it runs * a long inline step, or waits on a background step or a hook), so events * other writers commit reach the running workflow without a queue hop. * * Contract: * * - Calls `onEvent` for each event of `runId` whose slot is above * `afterSlot`, in slot order, each slot at most once per subscription, * with no gaps while the subscription is healthy. Events carry the same * shape and data resolution as `list` with `resolveData: 'all'`. * - Best effort. A World may stop delivering at any time (a dropped * connection, a shutdown), and should call `options.onError` when it * does. It need not replay what it missed: the runtime also polls the * log tail, and accepts a pushed event only when it is the next slot * it expects, so a late, duplicated or out-of-order event is dropped * rather than misapplied. Correctness never depends on this method. * - Returns an unsubscribe function. Calling it stops delivery promptly * and is idempotent. `onEvent` must not be called after it returns. * - Must not throw synchronously for a transport failure; report it * through `options.onError` instead. * * A World that omits it is fully supported: the runtime then polls the * log tail at `WORKFLOW_ORCHESTRATOR_POLL_INTERVAL_MS`. While a * subscription is live, the poll runs at the slower * `WORKFLOW_ORCHESTRATOR_FEED_POLL_INTERVAL_MS`, so a World that offers * it must report a closed or ended subscription through `onError`. */ subscribe?(runId: string, afterSlot: number, onEvent: (event: Event) => void, options?: EventsSubscribeOptions): () => void; }; hooks: { /** * Returns a Hook by ID. A Hook kept by minimum retention remains readable * after its run ends, but cannot be resumed. */ get(hookId: string, params?: GetHookParams): Promise; /** * Returns the Hook that owns a token, including a Hook kept by minimum * retention after its run ends. */ getByToken(token: string, params?: GetHookParams): Promise; /** * Lists Hooks, including Hooks kept by minimum retention after their runs * end. */ list(params: ListHooksParams): Promise>; }; /** * VM snapshot storage for the QuickJS engine's VM-memory snapshotting. * * @experimental The shape of this interface and of `SnapshotMetadata` * may change without a major version bump. It is OPTIONAL and World * implementations do not need to provide it: a World that omits it * simply runs every invocation with full event replay, which is always * correct (snapshots are an optimization, never a correctness * requirement). Consumers must feature-detect * (`world.experimental_snapshots?.…`). * * Snapshots capture the state of the QuickJS WASM VM at a suspension * point, allowing workflow execution to resume from the exact point of * suspension instead of replaying the full event log. * * The metadata (including eventsCursor) is stored alongside the snapshot * data so that on restore, only events created after the snapshot need * to be fetched. Implementations MUST round-trip the metadata object * losslessly and atomically with the bytes it describes — a snapshot * paired with another suspension's metadata replays from the wrong log * position and silently diverges. The `encodeSnapshotEnvelope` / * `decodeSnapshotEnvelope` helpers pack both into one self-describing * blob so a plain blob store satisfies this with a single atomic * write; worlds with transactional metadata storage may store the * fields natively instead. */ experimental_snapshots?: { /** * Save a VM snapshot for a workflow run. * Each save overwrites the previous snapshot for this run. * * @param runId - The workflow run ID * @param data - The serialized snapshot bytes (from QuickJS.serializeSnapshot()) * @param metadata - Snapshot metadata including the events cursor */ save(runId: string, data: Uint8Array, metadata: SnapshotMetadata): Promise; /** * Load the most recent VM snapshot for a workflow run. * Returns null if no snapshot exists (first invocation). * * @param runId - The workflow run ID * @returns The snapshot data and metadata, or null if not found */ load(runId: string): Promise<{ data: Uint8Array; metadata: SnapshotMetadata; } | null>; /** * Delete the snapshot for a workflow run. * Called when the workflow reaches a terminal state (completed, * failed, cancelled). MUST be idempotent: terminal-state cleanup is * exactly the path most likely to retry or run for a run that never * snapshotted, so deleting a nonexistent snapshot resolves * successfully. * * @param runId - The workflow run ID */ delete(runId: string): Promise; }; } /** * Feature capabilities a World implementation declares so the core runtime * can enable behavior that depends on the backend, instead of inferring * support from environment variables alone. Every capability defaults to * "unsupported" when absent: runtime fast paths that rely on one must fail * closed (keep their conservative behavior) unless the World explicitly * declares it. * * {@link inBandFence} is required for spec 9 runs, which are opt-in * (`WORKFLOW_SPEC_VERSION=9`): the runtime refuses to create or drive one on * a World that does not declare it. A World without it creates spec 8 runs. */ interface WorldCapabilities { /** * Enables invoke() and request/response processing through createQueueHandler. * Requires at most one active workflow runner per runId across all worker * processes. Different runs may execute concurrently. * * The active runner must process inputs while it awaits step work. A replacement * runner may take over after the previous runner stops, so process identity can * change over the run's lifetime. */ invoke?: boolean; /** * Supports `experimental_minRetention` for Hooks. Missing or inactive means * the runtime rejects retained Hooks before registration. */ hookRetention?: { active: boolean; }; /** * Admits `start({ experimental_hook })`: `events.create` creates the start Hook * `startHookId(runId)` for `eventData.startHook.token` atomically with * creating the run on `run_created` and on a resilient `run_started` * (resumable at once, even while the run is pending), makes one immutable * accept-or-reject decision per candidate `runId`, and refuses a duplicate * with `HookConflictError` naming the owner. The full contract is in * `start-hook.ts`; `test-support/atomic-start-hook-conformance.ts` checks * it. Missing or inactive means `start({ experimental_hook })` fails before it publishes * anything. A start that also sets a retention requires `hookRetention`. * * Like every capability, this describes the complete World: a World whose * backend may not implement admission (for example an adapter that talks to * a remote service) must not declare it until the backend does, because a * backend that drops `startHook` would admit duplicates silently. */ atomicStartHook?: { active: boolean; }; /** * The World's queue delivers a single-orchestrator run's orchestrator * messages one at a time (see `singleOrchestratorRunIdOf`): on Vercel * Queues, a concurrency key per run; an in-process per-run gate or a * per-run job queue elsewhere. Worlds whose queue cannot serialize a run's orchestrator * deliveries must leave this unset. * * Declares queue *support*, not deployed configuration. The runtime takes * no fast path from it: one orchestrator at a time is a frequency * mechanism, and the in-band fence ({@link inBandFence}) is what makes an * overlap safe. */ maxConcurrency?: boolean; /** * **Experimental.** The World's queue can hold a message for its sender * (`QueueOptions.experimental_hold`): `queue()` may come back with * `experimental_hold.status: 'held'`, a claim the sender runs itself in * the request that sent it, with the queue as the crash backstop. * Declares *support*: a given send can still come back `not_held` (the * queue service has send-and-hold off, local development), and is then * delivered as usual. * A caller that runs work in process behind a delayed backstop message * where this is unset can send undelayed with a hold where it is set. * * @experimental */ experimental_queueHold?: boolean; /** * The World implements the in-band writer fence on single-orchestrator runs * (spec >= 9). **Required for spec 9 runs**: `@workflow/core` refuses to * create one in `start()`, or to begin a spec 9 orchestrator delivery, on * a World that does not declare it, before it writes anything. Spec 9 runs * are opt-in (`WORKFLOW_SPEC_VERSION=9`), and a World that declares this * passes `{ inBandFence: true }` to `mintedSpecVersion` so the setting can * take effect. A World without it creates spec 8 runs, which need no * fence. * * Declaring it commits the World to all of: * * - **A per-run in-band count.** Next to the position counter its sequencer * allocates from (`seq`), the World counts the positions allocated to * in-band writes (`seqInBand`, see {@link CreateEventParams.inBand}). A * new run's `run_created` counts as in-band and is never fenced itself, * so a fresh run holds `seq = 1, seqInBand = IN_BAND_SEQ_AT_RUN_CREATION`. * - **A list snapshot.** `events.list` on a slot-numbered run returns * `snapshot: { seq, seqInBand }` ({@link EventListResponse.snapshot}), * read before the listing. A full load from the first page covers every * position up to that `seq`, each one committed or sealed. Required on * every page of a single-orchestrator run (spec >= 9). On earlier runs a * World may list none (world-vercel lists one only where its backend * reports it); its refusals then carry both counters, read together * (`InBandSupersededError.seq` and `.seqInBand`). * - **Fenced in-band creates.** A create or batch with `inBand: true` * carries {@link CreateEventParams.expectedSeqInBand}. The World checks it * against `seqInBand` and advances both counters by the positions it * allocates in one atomic step. On a mismatch it throws * `InBandSupersededError` (HTTP 412, `in-band-superseded`) and writes and * allocates nothing. An in-band write without an expected count is a 400. * - **Unfenced out-of-band creates.** Writes with `inBand: false` (or * absent) move `seq` and never `seqInBand`, and are never refused by the * fence. * * `@workflow/world`'s `test-support/in-band-fence-conformance.ts` checks * each of these against a World's `events` storage. "Implementing spec 9 in * a World" in `packages/core/src/runtime/spec9/README.md` (in the Workflow SDK * repository) is the full guide. */ inBandFence?: boolean; /** * The World's `events.create` deduplicates concurrent `hook_received` writes * that carry the same `(runId, resumeId)`, collapsing them onto a single * committed event and returning the canonical one to every caller. Two * writers rely on it: `resumeHook()`'s durable write attaches a `resumeId` + * payload digest so transport-level retries of one write converge on exactly * one event, and legacy `hookInput` queue redeliveries (from older * producers) converge through the same constraint. * * The core runtime fails closed on this: a `resumeId` is attached ONLY when * the World declares `hookResumeDedup === true` (or the live backend attests * it per-lookup, below, or `resolvedHookResume` requires it for a cached * hook). A World that accepts a `resumeId` but does not * enforce the `(runId, resumeId)` constraint must leave this unset so the * runtime keeps the plain single-shot write. * * Declaring this also commits the World to ROUND-TRIPPING the key: * `events.list` must return `resumeId` on `hook_received` events it * persisted with one, because the legacy `hookInput` consumer path detects * an already-materialized resume by matching `resumeId` in the loaded log. * * Enabled statically for `world-local` (filesystem sidecar claim keyed on * `(runId, resumeId)`; the adapter and its backend ship together, so a static * capability can never drift from the backend). `world-vercel` deliberately * leaves this UNSET and instead attests support per-lookup via the * server-computed, response-only `Hook.resumeCapabilities.hookResumeDedupVersion` * (see `HookResumeCapabilitiesSchema`), so a server rollback or kill switch * degrades new resumes to plain writes immediately without redeploying * the adapter. `world-postgres` enforces resume identities transactionally * and declares the capability statically. * * The resume gate treats EITHER signal as backend support (see * `resume-hook.ts`): this static capability OR a current * `resumeCapabilities.hookResumeDedupVersion` on the by-token hook. */ hookResumeDedup?: boolean; /** * Supports cached hook delivery with `requireHookResumeDedup`. The adapter * must enforce atomic resume deduplication or reject before writing, even * against an older backend or when dedup support is disabled. This is an * adapter contract, not a cached attestation of live backend support. * A definite refusal (HTTP 400/404) MUST guarantee nothing was written: * core may then resolve the token and deliver through the ordinary route. * Uncertain failures MUST NOT be retried or reported as definite refusals. */ resolvedHookResume?: boolean; /** * Supports `createHook({ experimental_force: true })`: a `hook_created` * carrying `eventData.force` whose token is held by another live run takes * the token over instead of returning `hook_conflict`. The World must: * * 1. append `hook_disposed{forceClaimedBy: { runId, hookId }}` to the * current owner's log — atomically with whatever that World uses to * refuse later `hook_received` writes to it — BEFORE re-pointing the * token, so a delivery that already resolved the old owner is refused * rather than landing in a run that no longer holds the token; * 2. re-point the token to the claimer atomically, recording * `Hook.claimedFrom` on the claimer's hook; * 3. journal the claimer's `hook_created{force, forceClaimedFrom}`, * refusing it if the claimer's own hook was taken over in between; * 4. answer a `hook_received` refused by a takeover with * `HookForceClaimedError` (not `HookNotFoundError`), after completing * the re-pointing if the claimer had not, so `resumeHook()` can follow * the token to its new owner and retry with the same `resumeId`. * * A World that * cannot give these guarantees must leave this unset; the runtime then * rejects `experimental_force` at `createHook()` time. */ hookForceClaim?: boolean; /** * Deployments are atomic and immutable: a deployment id names one fixed * build for its whole lifetime, so a run pinned to one may only execute * there. Worlds that declare this get the runtime's deployment-affinity * guard, which re-routes a misrouted delivery to the run's own deployment * and ultimately fails the run with `DEPLOYMENT_MISMATCH`. * * Worlds whose deployment id is synthetic or version-tagged (e.g. * `dpl_local@`, which legitimately differs across SDK versions * within one logical environment) must leave this unset: there a * "mismatch" is not a real cross-deployment delivery, and guarding would * fail ordinary runs after a version bump. */ deploymentAffinity?: boolean; /** * Stores a dynamic run's workflow code with the run. The World must persist * `dynamicWorkflowCode` from `run_created` (and from a resilient * `run_started` that creates the run), echo it on the created run, and * return it from `runs.get` with `resolveData: 'all'` for the run's * lifetime, because every replay evaluates that code and it exists nowhere * else. `start()` refuses a dynamic start on a World that leaves this unset. * * Code too large for the creating write goes through * {@link World.uploadDynamicWorkflowCode} when the World implements it; * otherwise it is always sent inline. */ dynamicWorkflowCode?: boolean; } /** * The "World" interface represents how Workflows are able to communicate with the outside world. */ interface World extends Queue, Streamer, Storage { /** * Optional analytics read namespace for observability surfaces. * * These APIs return metadata-only rows intended for UI/CLI listing and * trace views. Payload-bearing fields remain on the canonical runtime * storage APIs (`runs`, `steps`, `events`, `hooks`) and their RemoteRef * resolution path. */ analytics?: Analytics; /** * The Workflow protocol spec version this World implements, and the version * stamped on every run it creates. * * Declare `SPEC_VERSION_CURRENT` rather than a literal. The runtime checks * this against `[SPEC_VERSION_CURRENT, SPEC_VERSION_MAX_SUPPORTED]` before it * creates or replays anything, and refuses a World outside that range: below * the floor the World allocates event ids the runtime cannot read positions * out of (see the event log contract above), above the ceiling it speaks a * spec this runtime has not learned. */ specVersion: number; /** * Feature capabilities this World implementation supports. See * {@link WorldCapabilities}. Absent (or absent members) means * "unsupported": runtime optimizations gated on a capability fail closed. */ capabilities?: WorldCapabilities; /** * Validates a dynamic run's complete execution context against * World-specific limits. `start()` calls it only for dynamic starts, before * any durable start side effect, so implementations throw to refuse the * start. */ validateRunExecutionContext?(value: Record): void; /** * Absolute wall-clock time when the current function invocation will be * terminated by the hosting platform, if known. Used to optimize runtime behavior. */ getRuntimeDeadline?(): Promise; /** * A function that will be called to start any background tasks needed by the World implementation. * For example, in the case of a queue backed World, this would start the queue processing. */ start?(): Promise; /** * Release any resources held by the World implementation (connection pools, listeners, etc.). * After calling `close()`, the World instance should not be used again. * * This is important for CLI commands and short-lived processes that need to exit cleanly * without relying on `process.exit()`. */ close?(): Promise; /** * Resolve the most recent deployment ID for the current deployment's environment. * * Used when `deploymentId: 'latest'` is passed to `start()`. The implementation * determines the latest deployment that shares the same environment (e.g., same * "production" target or same git branch for "preview" deployments) as the * current deployment. * * The CLI's `workflow start` uses it too, so a process that is not itself a * deployment resolves "latest" the same way `start()` does. Such a process * has no current deployment, so an implementation that supports it resolves * relative to the environment it was configured for. * * Not all World implementations support this: it is only implemented by * world-vercel where deployment routing is meaningful. */ resolveLatestDeploymentId?(): Promise; /** * Retrieve the AES-256 encryption key for a specific workflow run. * * The returned key is a ready-to-use 32-byte AES-256 key. The World * implementation handles all key retrieval and derivation internally * (e.g., HKDF from a deployment key). The core encryption module uses * this key directly for AES-GCM encrypt/decrypt operations. * * Two overloads: * * - `getEncryptionKeyForRun(run)`: Used when the runtime already holds * the `WorkflowRun` entity. The World reads any context it needs (e.g., * `deploymentId`) directly from the run. * * - `getEncryptionKeyForRun(runId, context?)`: Used everywhere else: when * the run does not exist yet (`start()` before run creation), and when * the runtime has a run id but no reason to load the run's payloads * (stream reads, forwarded writable streams, hook resumption). The * `context` parameter carries opaque world-specific data (e.g., * `{ deploymentId }` for world-vercel) needed to resolve the correct key. * When `context` is omitted, the World assumes the current deployment. * * Implementations must resolve the same key from either form. * * When not implemented, encryption is disabled: data is stored unencrypted. */ getEncryptionKeyForRun?(run: WorkflowRun): Promise; getEncryptionKeyForRun?(runId: string, context?: Record): Promise; /** * Mint a new workflow run ID. * * Called by `start()` to generate the unique ID for a newly-created run. * The returned value is the "bare" ID (without any `wrun_` prefix); the * core attaches the prefix. * * Implementations are free to embed world-specific metadata in the ID * (e.g., a region identifier) as long as the returned string remains a * valid ULID. When omitted, `start()` falls back to generating a standard * monotonic ULID. * * @param options - The full options bag passed to `start()` (typed as * `Record` here to avoid a circular dependency with * `@workflow/core`). Worlds should read only the fields they * recognize. For example, `@workflow/world-vercel` reads * `options.region` to embed a region identifier. Unrecognized keys * must be ignored. `start()` always passes an object (an empty one * when it was called with no options), but implementations should * tolerate `undefined` for direct callers. */ createRunId?(options?: Readonly>): string; /** * The region an existing run's data lives in, derived from its run ID * alone (no I/O, never throws). * * The counterpart of {@link createRunId} for worlds that embed a region in * the IDs they mint. Callers that create a run on behalf of an existing one * (e.g. `recreateRunFromExisting()`) pass the result to `start({ region })` * so the new run is placed where the original was, rather than wherever the * calling process happens to execute. Return `null` when the ID is not one * this world recognizes. Worlds without a regional dimension omit this. */ regionForRunId?(runId: string): string | null; /** * Upload a dynamic run's serialized workflow VM code to the World's blob * storage ahead of `run_created`, returning the ref key to attach to the * run. * * The inline path — sending the bytes on `run_created` itself — is the * common case and needs nothing from this method: a generated orchestration * function is usually a couple of KB, and keeping it on the creating write * costs no extra round-trip. This exists for the tail: a definition too * large to ride the event wire, which has to be streamed separately and * referenced. * * Worlds that store run records whole (local, Postgres) have no size * pressure and leave this unset; `start()` then always sends inline, and a * definition over its own source limit is rejected client-side rather than * silently truncated. * * The upload necessarily precedes the run it belongs to, so implementations * must accept a `runId` that does not exist yet, and must scope the stored * object to the caller's tenant and that run so it is reclaimed with the * run's other storage. * * @param runId - The client-minted ID of the run being started. * @param params.workflowName - The run's generated dynamic workflow name. * Worlds that embed it in the storage key need it passed in, because the * run record does not exist yet to read it from. * @param params.code - Serialized (compressed + encrypted) workflow code. * @returns The ref key to send as `run_created`'s * `eventData.dynamicWorkflowCodeRef`. */ uploadDynamicWorkflowCode?(runId: string, params: { workflowName: string; code: Uint8Array; }): Promise; /** * The environment this World's writes are attributed to by the backend * (`@workflow/world-vercel`: `'production' | 'preview' | 'development'`). * * Synchronous and side-effect free: implementations derive this from * configuration or environment variables they already hold, never from a * network call. Return `undefined` when the environment can't be determined. * * The value MUST match the attribution the backend will actually apply to * this client's writes: for `world-vercel` that means keeping it in lockstep * with the `x-vercel-environment` header (proxy path) and the OIDC token's * `environment` claim (in-deployment path). A value that merely looks * plausible is worse than `undefined`, because callers use it to detect * cross-tenant mismatches and a wrong answer manufactures a false one. * * `start()` stamps this into the queue message's `runInput` so the consuming * deployment can tell that a message it was handed was created against a * different environment than its own. Not all Worlds have an environment * dimension: local dev and Postgres have exactly one tenant, so they omit * this and the check is skipped. */ getEnvironment?(): string | undefined; /** * World-specific display fields for a run. * * Tooling (e.g. the `workflow inspect` CLI) calls this to enrich a * run's listing row / detail output with fields only the world can * derive: a region decoded from the run ID, placement read off the * run's `executionContext`, a shard, a billing tier, etc. Consumers * render each returned key as an additional column/property; when the * hook is absent, no extra fields appear at all. * * The contract: * - **Cheap and pure.** Called once per displayed run, so avoid I/O. * Prefer deriving fields from the entity you are given. * - **Read only what you recognize.** The argument is the run entity * as the caller has it (a full storage run, or a leaner analytics * row), typed loosely for the same reason as {@link createRunId}. * Tolerate missing fields. * - **Must not throw.** * - A `null` field value means "applicable but undeterminable" and is * preserved as `null` in structured output (vs. the hook being * absent, where the key does not exist at all). Return `null` or an * empty object to add nothing for a given run. */ describeRun?(run: Readonly>): Record | null | Promise | null>; /** * Optional telemetry write namespace for non-critical observability signals. */ telemetry?: Telemetry; } interface Telemetry { /** * Called immediately before a step's user code begins executing. * * Worlds may use this synchronous hook to correlate step execution with the * current platform invocation. Implementations must not throw. */ recordStepExecution?(stepId: string): void; } //#endregion //#region src/service/app.d.ts /** What the routes reach beyond the request. Each defaults to the service's own. */ interface AppDeps { /** The factory the service answers for. */ context: FactoryContext; /** The World whose hooks a poke and a cancel list. */ world: () => Promise<{ hooks: Pick; }>; /** The jigs registry. */ registry: () => RegistrySql; } /** Build the service HTTP application for one factory's workflows. */ declare function createApp(factory: Factory, deps?: Partial): RequestListener; //#endregion //#region src/service/wake.d.ts interface WakeNote { /** What resumed the hook: a provider event, a poke, a Slack reply, or the hub falling behind. */ kind: string; at: string; } //#endregion //#region src/workflow/hook-tokens.d.ts /** * A hook token jigs minted, taken apart. Every kind names the installation * jigs reaches its provider through, so an event from another installation * never wakes it. The prefix alone decides the kind, so a token whose rest is * unreadable keeps its kind and loses only its parts. */ type HookToken = { kind: "ticket-claim"; provider: "linear"; ticket: { installationName: string; issueId: string; } | null; } | { kind: "pull-request"; provider: "github"; slug: string; pr: PullRequestRef | null; } | { kind: "slack-thread"; provider: "slack"; thread: { installationName: string; channel: string; threadTs: string; } | null; } | { kind: "linear-session" | "linear-listening"; provider: "linear"; session: { installationName: string; sessionId: string; } | null; }; type HookKind = HookToken["kind"]; //#endregion //#region src/run-suspension.d.ts /** One hook a run is currently parked on. */ interface RunSuspension { token: string; kind: Exclude | "external"; /** What the run is waiting for, in the words an operator acts on. */ reason: string; /** The pull request to go and act on. */ url?: string; /** What last resumed this wait, on the single-run route, if the service has woken it since it started. */ lastWake?: WakeNote; } //#endregion //#region src/steps/runtime/run-state.d.ts /** What an event trigger started a run for, as the trigger's source describes it. */ interface RunSource { /** The provider the occurrence came from. */ kind: Provider; /** The occurrence in an operator's words. */ label: string; } interface RunStep { name: string; status: string; at: string | null; } /** One run as plain data: the World's run, its hooks and its resources. */ interface RunState { runId: string; /** The World's status, as the SDK reports it; null when the World has no such run. */ status: string | null; /** The workflow ID the World stores, or null where it was not read. */ workflowName: string | null; /** Which schedule or event trigger launched the run, or `manual`. */ trigger: string | null; /** What an event trigger started the run for, or null for any other run. */ source: RunSource | null; /** The ticket the run was launched with, as the operator typed it. */ ticket: string | null; createdAt: string | null; /** The last thing that happened to this run, step timings included. */ lastActivityAt: string | null; /** How many steps the run recorded, or null where nothing read them. */ steps: number | null; lastStep: RunStep | null; /** * What the run is parked on: a pull request watch, a person's reply, or another event. A * parked run's status stays `running`; a non-empty list is what says it is waiting. */ suspensions: RunSuspension[]; /** The ticket claim hook the run holds for its whole life, or null. */ claim: string | null; /** Every resource the run recorded in this factory, released ones included. */ resources: ResourceRecord[]; } //#endregion //#region src/service/automatic-release.d.ts /** Injectable operations used by automatic release reconciliation. */ interface AutomaticReleaseDeps { /** Runs holding releasable resources that are live, or failed and due for a retry. */ pendingRuns: () => Promise; readState: (runId: string) => Promise; waitForTerminal: (runId: string, signal: AbortSignal) => Promise; hasActiveStep: (runId: string) => Promise; policy: (factory: Factory, run: RunState, outcome: RunOutcome) => ReleaseAction; withLock: (runId: string, action: (sql: RegistrySql) => Promise) => Promise; release: (sql: RegistrySql, runId: string, action: ReleaseAction, outcome: RunOutcome) => Promise; ready: () => boolean; log: (line: string) => void; warn: (line: string) => void; setTimer: (fire: () => void, ms: number) => () => void; } /** Counts from one automatic release reconciliation pass. */ interface AutomaticReleaseReport { considered: number; released: number; kept: number; busy: number; failed: number; } /** Resolve the cleanup action for a workflow outcome and its effective release policy. */ declare function automaticReleaseAction(factory: Factory, workflowName: string, outcome: RunOutcome, factoryPolicy?: ReleasePolicy): ReleaseAction; /** One idempotent recovery pass; the long-poll watcher only makes this run sooner. */ declare function reconcileAutomaticRelease(factory: Factory, deps?: AutomaticReleaseDeps, options?: { canStart?: () => boolean; }): Promise; //#endregion //#region src/service/service.d.ts /** * Point Nitro and the World at `JIGS_SERVICE_PORT`, or exit naming a missing port variable. Call * it at the top level of the service's Nitro plugin, after the factory configuration has loaded * its environment and before Nitro reads `PORT` to listen. */ declare function listenOnServicePort(): void; /** * Pin the World to this copy's deployment version, `JIGS_DEPLOYMENT_VERSION`, when it has one, or * exit naming what is wrong with it. Call it at the top level of the service's Nitro plugin, * beside {@link listenOnServicePort}, before the World module is created. */ declare function pinDeploymentVersion(): void; /** * Start everything the service runs beside its routes: the World behind its startup checks, then * the dashboard, schedules, event triggers, automatic release and the hub client. A copy with a * deployment version runs those only while its version is current, and drains otherwise. Call it * once, from the service's Nitro plugin, with the factory configuration the service was built * from. */ declare function startService(factory: Factory, config: FactoryDefinition): void; //#endregion export { type AppDeps, automaticReleaseAction, createApp, listenOnServicePort, pinDeploymentVersion, reconcileAutomaticRelease, startService };