Yolk SDK
API reference

Workflow APIs

Public Vercel Workflow orchestration exports.

Use @yolk-sdk/vercel-workflows or the equivalent @yolk-sdk/vercel-workflows/workflow subpath for orchestration. Use @yolk-sdk/vercel-workflows/effect for Effect-native host route wrappers around public workflow/api calls, and @yolk-sdk/vercel-workflows/testing for host tests. The ./cloudflare* subpaths run the same Workflow code on Cloudflare Durable Objects (Cloudflare runtime).

Loop exports

ExportPurpose
runVercelAgentWorkfloworchestrate model/tool/HITL/close callbacks
defaultMaxWorkflowTurnsdefault max turns, currently 500
noWorkflowStepRetrydefault retry policy (except closeStreamRetry), { maxAttempts: 1 }; queue redelivery still happens (at-least-once)
defaultCloseStreamRetrydefault closeStreamRetry, { maxAttempts: 3 }; a Vercel stream close is idempotent
retryWorkflowStepretry helper for Workflow callback promises
settleWorkflowStepconvert a promise into Success / Failure result

WorkflowStepResult and VercelAgentWorkflowRunResult are both types and constructor values on the package root and @yolk-sdk/vercel-workflows/workflow. Use WorkflowStepResult.Success({ value }) / .Failure({ error }) for settled steps and VercelAgentWorkflowRunResult.Completed({ turns, state }) or its failure variants for terminal results. Their $is(tag) helpers narrow to a specific variant.

Independent child helpers

Both helpers are exported from root and ./workflow and run in Workflow orchestration, not inside a single parent tool step. They do not start children or implement storage/authorization themselves.

orchestrateWorkflowToolBatch<Call, Result, Pause>

Inputs:

  • calls: ReadonlyArray<Call> and concurrency: number.
  • preflight: () => Promise<{ ready: true } | { ready: false; value: Pause }>: runs once before dispatch; a pause fences every call.
  • execute: (call: Call, index: number) => Promise<Result>: invokes host steps or child starts.

Returns a Promise of { ready: false, value } or { ready: true, results: ReadonlyArray<Result>, failures?: ReadonlyArray<{ index: number, error: unknown }> }. Concurrency is floored/clamped to at least one; non-finite values become one. On rejection, no new calls are dispatched; active siblings settle and successful results retain original call order. ready: true is not a success guarantee: inspect failures, retain partial progress, and map errors to safe wire data before returning the loop callback result. Results omit failed and undispatched calls; carry call identity in each result when mapping partial progress.

awaitWorkflowChild<A>

Accepts read: (attempt: number) => Promise<{ done: false } | { done: true; value: A }> and sleep: (attempt: number) => Promise<void>, returning Promise<A>. Attempts start at zero. Each read returning done: false is followed by a sleep with the same index, then the next read. Existing zero-argument callbacks remain compatible.

It alternates short durable read steps with Workflow sleep until done: true. There is no built-in timeout or observation ceiling. Hosts can use the index for budgets/backoff and return { done: true, value } at their ceiling with a truthful still-running or unknown value; this ends observation, not the child. Represent completed, failed, and cancelled states explicitly and keep Stop policy host-owned. Never place a long child returnValue poll inside one step.

See Bounded child observations for host budgeting and Nonterminal child observations for the subagent result marker.

Durable event exports

ExportPurpose
makeDurableAgentEventSequencerStateinitialize event sequence state
durableAgentEventIdbuild ${streamId}:${turn}:${eventSequence}, plus :${executionId} when set
sequenceDurableAgentEventadd deterministic eventId without writing
writeDurableAgentEventwrite sequenced NDJSON to a writer
DurableAgentEventWriteErrorwriter rejection, kept as cause
commitThenWriteTerminalEventcommit durable state before writing terminal event

Effect API exports

Import from @yolk-sdk/vercel-workflows/effect.

ExportPurpose
VercelWorkflowsEffect service for start/read/replay/resume/cancel operations
VercelWorkflowsClientservice shape for injected fakes/custom layers
VercelWorkflowsErrortagged error for public Workflow SDK failures
VercelWorkflowsSdkinjectable low-level SDK dependency for tests/custom hosts
VercelWorkflowsSdkClientlow-level SDK dependency shape
VercelWorkflowsSdkRunlow-level SDK run shape
VercelWorkflowFunctionWorkflow function type accepted by start
VercelWorkflowRunEffect-native run handle returned by start/getRun
VercelWorkflowRunStatusnative Workflow run status type
VercelWorkflowStartOptionsstart options: plaintext run attributes
VercelWorkflowReadableOptionsreadable stream options, including startIndex
VercelWorkflowReadableStreamnative Workflow readable stream type
VercelWorkflowsOperationoperation names carried by VercelWorkflowsError

Layers:

LayerPurpose
VercelWorkflows.layerlive service backed by public workflow/api
VercelWorkflows.layerFromSdkservice requiring injected VercelWorkflowsSdk for tests/custom SDKs

VercelWorkflows methods:

MethodPurpose
start(workflow, args, opts?)start a Workflow and return an Effect-native run handle
getRun(runId)create an Effect-native handle for an existing run
getReadable(runId, options?)read/replay a run stream
tailIndex(runId)read current stream tail index
resumeHook(token, payload)resume a pending Workflow hook
cancel(runId)cancel a run

start's optional attributes seed the run's searchable metadata (Workflow run attributes) at creation, without an extra event. They are plaintext and the platform validates them before the run exists, so an invalid one fails the start: keys of 1-256 characters not starting with $, values of at most 256 UTF-8 bytes, at most 64 per run. Use identifiers, never secrets or content. A run started from inside a workflow or step also gets the reserved $parentRunId and $rootRunId.

VercelWorkflowRun members:

MemberPurpose
runIdnative Workflow run id
getReadable(options?)Effect-wrapped readable stream for this run
cancelEffect that cancels this run
statusEffect that resolves the native run status
returnValueEffect that resolves the typed Workflow function return value

The API wrapper keeps Vercel's SDK underneath. It does not reimplement Vercel backend HTTP, queue, hook, or stream internals.

Every Effect operation on VercelWorkflows and VercelWorkflowRun fails with VercelWorkflowsError, which carries _tag, operation, message, and the original cause. operation is one of start, getRun, getReadable, tailIndex, resumeHook, cancel, status, or returnValue. runId is plain data and cannot fail.

VercelWorkflowsClient is the Effect service shape. VercelWorkflowsSdkClient and VercelWorkflowsSdkRun are the lower-level Promise SDK seam used by VercelWorkflowsSdk.

Testing exports

Import from @yolk-sdk/vercel-workflows/testing.

ExportPurpose
TestWorkflowWorldbehavioral emulator for lifecycle, streams, steps, hooks, and cancellation
testWorkflowModuleambient workflow module surface for vi.mock
defaultTestWorkflowStepMaxRetriesemulated platform default retry budget
TestWorkflowStreamConflictError, TestWorkflowRunConflictErrorwrite-after-close and run-state conflict errors
TestWorkflowHookNotFoundError, TestWorkflowHookConflictError, TestWorkflowRunNotFoundError, TestWorkflowRunCancelledErrorhook/run lookup and cancellation errors; awaiting a hook whose token another live hook held fails with TestWorkflowHookConflictError (token, conflictingRunId)
TestWorkflowRunStatus, TestWorkflowRunInspection, TestWorkflowMetadata, TestWorkflowStepMetadata, TestWorkflowStepFunctiontest-world status, inspection, and step contracts
TestWorkflowHookdisposable promise returned by emulated createHook
TestWorkflowUnstorableStepErrora step error the platform could not store (inspect(runId).unstorableStepErrors)
TestWorkflowWorldOptions, TestWorkflowDiscardedStepExecutiondiscardStepExecution reproduces Workflow 5.8 speculative execution; a discarded execution with its Effect Result outcome (inspect(runId).discardedStepExecutions)

Executing steps loads the installed workflow runtime's step-error serializer, so tests that run steps need Vitest's Node environment (Step errors).

Cloudflare runtime exports

See Cloudflare runtime for wiring.

SubpathMain exports
@yolk-sdk/vercel-workflows/cloudflareWorkflowRun (Durable Object class), registerWorkflowModules, registerRunPreloads, WorkflowExecution, ExecutionHost, HookClaim, makeMemoryRunStore, makeSqliteRunStore, makeHookIndex, RunStore, RunRecord, RunStatus, JournalEntry, workflowRunsBinding, runNamespace, WorkflowRunStub, WorkflowRunNamespace, StartRunInput, StartNewOutcome, RunOutcome, WorkflowFunction, serialize, deserialize, FatalError, RetryableError, HookConflictError, HookNotFoundError, WorkflowRunCancelledError, parseDuration, defaultStepMaxRetries, stepGuardIntervalMs
@yolk-sdk/vercel-workflows/cloudflare/workflowdrop-in workflow: createHook, sleep, getWritable, getStepMetadata, getWorkflowMetadata, FatalError, RetryableError; Cloudflare-only getStepSignal
@yolk-sdk/vercel-workflows/cloudflare/apidrop-in workflow/api: start, getRun, resumeHook, WorkflowRun, WorkflowReadableStream, WorkflowReadableStreamOptions, HookNotFoundError, WorkflowRunCancelledError; Cloudflare-only startWithRunId, StartWithRunIdResult, prepareRun, createRunId, isRunId
@yolk-sdk/vercel-workflows/cloudflare/directivesworkflowStep, workflowEntry (imported by compiled directives)
@yolk-sdk/vercel-workflows/cloudflare/viteworkflowDirectives, WorkflowDirectivesOptions, workflowDirectivesRuntime, compileWorkflowDirectives

Callback types

TypeMeaning
VercelAgentWorkflowInput{ request, context } passed to workflow
SerializableWorkflowStatepersisted loop state between steps
VercelAgentWorkflowLoopConfigfull config for runVercelAgentWorkflow
VercelAgentWorkflowModelStepInputmodel callback input
VercelAgentWorkflowModelStepResultmodel callback result
VercelAgentWorkflowToolBatchStepInputtool callback input
VercelAgentWorkflowToolBatchStepResulttool callback result
VercelAgentWorkflowAwaitingInputHITL hook payload
VercelAgentWorkflowRunResultterminal run result union
VercelAgentWorkflowStepRetryPolicy{ maxAttempts }; finite values floor/clamp to 1, non-finite values become 1
WorkflowStepResultSuccess / Failure wrapper from settleWorkflowStep

Durable event types

TypeMeaning
DurableAgentEventJSON event with deterministic eventId
DurableAgentEventIdInputinput for durableAgentEventId
DurableAgentEventSequencerStatecurrent durable event sequence state
SequenceDurableAgentEventInputinput for sequenceDurableAgentEvent
SequencedDurableAgentEventevent plus current/next sequence values
WriteDurableAgentEventInputsequenced event input plus stream writer
CommitThenWriteTerminalEventInputterminal barrier input
CommitThenWriteTerminalEventResultterminal barrier result union

Run result tags

TagMeaning
Completedclosed normally
ModelStepFailedmodel callback failed after retries
ToolBatchStepFailedtool callback failed after retries
AwaitInputFailedHITL hook failed or missing handler
CloseStreamFailedclose callback failed after retries
MaxTurnsExceededexceeded maxTurns

Harness constructors

The separate @yolk-sdk/harness package exposes lifecycle model companions:

SubpathConstructor values
@yolk-sdk/harness/inboxHitlDecision, PauseDecision, RecoveryAttempt, RecoveryAdmission, DrainBegin
@yolk-sdk/harness/driverStopDecision
@yolk-sdk/harness/outcomeOverflowCompactionResult, StepOutcome, HitlMatch

These are Data.taggedEnum constructors for the corresponding public types. They construct receipt values, not lifecycle operations: hosts still use Driver/Inbox services to perform work.

Terminal helper results

TagMeaning
Committedcommit succeeded and terminal write succeeded
CommitFailedcommit failed and commit-error terminal write succeeded
TerminalWriteFailedcommit succeeded but terminal write failed
CommitErrorWriteFailedcommit failed and commit-error terminal write failed

The terminal helper does not close streams or infer finality from event tags. Successful AgentEnd closes through closeStream; failure AgentError closes through writeError. Release the writer lock without final-closing resumable AgentAwaitingInput.

On this page