Step contracts
Model, tool, stream, error, retry, and terminal contracts for Vercel Workflow agents.
runVercelAgentWorkflow is orchestration only. Your app provides all work as Workflow-safe callbacks.
Wrapper
import { createHook } from 'workflow'
import { runVercelAgentWorkflow } from '@yolk-sdk/vercel-workflows'
export async function runAgentWorkflow(input: { request: unknown; context: unknown }) {
'use workflow'
return await runVercelAgentWorkflow({
input,
maxTurns: 64,
runModelStep,
runToolBatchStep,
closeStream,
writeError,
awaitInput: async awaitingInput => {
using hook = createHook<unknown>({ token: awaitingInput.hookToken })
return await hook
}
})
}Keep provider calls, tool execution, persistence, telemetry, and Effect runtimes in 'use step' callbacks, not in the 'use workflow' body.
Callback table
| Callback | Directive | Input | Output |
|---|---|---|---|
runModelStep | 'use step' | { context, state } | model result with done, messages, createdMessages, toolCalls, usage, turn |
runToolBatchStep | step or workflow orchestration | { context, request, calls, createdMessages, hitlResponses, usage, turn, eventSequence } | tool results, awaitingInput, or a wire-safe partial-progress failure |
awaitInput | workflow body | awaiting-input payload | one host-decoded HITL response that the package appends to accumulated hitlResponses |
closeStream | 'use step' | none | closes the writer only; AgentEnd is written before it by the final model step |
writeError | 'use step' | unknown error | writes safe final error and closes failure stream; best-effort, not retried |
Model step
Fragment:
async function runModelStep(input: VercelAgentWorkflowModelStepInput) {
'use step'
return await runHostModelTurn(input.state)
}Rules:
- Return
done: truewhen no tool batch is needed; the workflow closes the stream. - Return
done: falsewith orderedtoolCallswhen tools must run. - A
done: falseresult with no tool calls continues directly to the next model step without invokingrunToolBatchStep; use this when host-promoted input already advanced model state. - Put assistant/model-created messages in
createdMessages. - With host instructions (for example the code mode
catalog), append
instructionMessages(transcript, instructions)from@yolk-sdk/agent/loopbefore callingrunModelTurn, and return them increatedMessagesahead of the assistant message;runModelTurndoes not acceptinstructions. - Carry
eventSequenceif the model step wrote durable stream events.
The Next example keeps that model result finalized: it folds collectModelTurn(runModelTurn(...))
and does not promote a missing Done into a Workflow continuation. See
Harness composition for that recipe versus an optional
@yolk-sdk/harness/outcome policy.
Tool batch step
Fragment:
async function runToolBatchStep(input: VercelAgentWorkflowToolBatchStepInput) {
'use step'
return await runHostToolBatch({
calls: input.calls,
hitlResponses: input.hitlResponses ?? [],
eventSequence: input.eventSequence ?? 0
})
}Rules:
- Return one tool-result message per host tool call.
- Preserve original model tool-call order.
- Represent expected per-tool failures as result messages, not thrown step errors.
- If the step boundary catches a batch failure after sibling progress, return wire-safe
failure, cumulativeusage, and the latesteventSequence. - Return
awaitingInputwhen approvals/questions must pause the workflow. - A background acknowledgement (
ToolResultMessage.acceptance) is a normal result message for the original call: it carries no nested usage and must not be treated as completion. Make the hostBackgroundToolHost.acceptidempotent per call id so a retried tool step replays the same receipt instead of launching twice.
Independent child orchestration
For independent children, runToolBatchStep may be a Workflow-safe orchestration callback instead
of one 'use step' function. Use orchestrateWorkflowToolBatch to fence the whole batch with a
durable preflight, then invoke separate tool steps or Workflow 5 start calls. Do not wrap a whole
child loop in one parent step: nested step calls from a step execute inline.
Fragment inside a host 'use workflow' function; hostPreflightStep, hostReadChildStep, and
hostChildWorkflow are host-owned placeholders, not SDK exports:
import { sleep } from 'workflow'
import { start } from 'workflow/api'
import { awaitWorkflowChild, orchestrateWorkflowToolBatch } from '@yolk-sdk/vercel-workflows'
const outcome = await orchestrateWorkflowToolBatch({
calls: hostChildCalls,
concurrency: 2,
preflight: () => hostPreflightStep(hostChildCalls),
execute: async call => {
const child = await start(hostChildWorkflow, [call])
return await awaitWorkflowChild({
read: () => hostReadChildStep(child.runId),
sleep: async () => {
await sleep('1s')
}
})
}
})The preflight step returns { ready: false, value } to pause without launching any call, or
{ ready: true } to allow dispatch. When using prepareToolBatch inside that step, any
pendingRequests fence all launches, including executable siblings. Preserve its synthetic
results and merge executed results by original call index.
The read step returns { done: false } or { done: true, value }; represent child failure as a
terminal value rather than polling forever. Keep reads short-lived and use Workflow sleep, not a
long returnValue poll inside a step. Effect, storage, and provider work remain inside steps.
Handle outcome before returning the loop's tool-batch result: ready: true may include
failures and only partial ordered results. On rejection, dispatch stops and active siblings
settle. Hosts map progress/failure into the loop's wire-safe result and never proceed to another
model turn with unmatched calls.
Hosts own admission, durable reservations/results, ownership checks, child HITL support, and Stop policy. Background acceptance is not child completion; see Background subagents.
Bounded child observations
The fragment above polls without a ceiling. awaitWorkflowChild passes deterministic zero-based
indices to read(attempt) and sleep(attempt): read zero, sleep zero if pending, read one, and so
on. Existing zero-argument callbacks remain valid; no timeout or backoff is added automatically.
Pass attempt into the host read step to enforce an observation budget, and use it in the sleep
callback for host-chosen capped backoff. At the ceiling, the read step returns
{ done: true, value } with the latest truthful still-running or unknown status and a recovery
handle. Here done means observation ended, not that the child completed or was cancelled.
Durable storage, authorization, terminal-state detection, and Stop policy remain host-owned.
When mapping that value into a nonterminal subagent tool result, use the matching logical ID and
observation marker, rather than fabricating a
terminal child result or charging nested usage. The physical Workflow run id is a separate
host-owned recovery handle. See the callback signatures.
Run result tags
runVercelAgentWorkflow returns VercelAgentWorkflowRunResult values from
@yolk-sdk/vercel-workflows (Data.taggedEnum plain objects, _tag last). Construct or match
with VercelAgentWorkflowRunResult.Completed({ turns, state }) and siblings, or
VercelAgentWorkflowRunResult.$is('Completed'). settleWorkflowStep returns
WorkflowStepResult.Success({ value }) / WorkflowStepResult.Failure({ error }).
| Tag | Meaning |
|---|---|
Completed | model ended and closeStream succeeded |
ModelStepFailed | model step exhausted retries |
ToolBatchStepFailed | tool batch step exhausted retries |
AwaitInputFailed | final HITL hook/resume failure; unlike a successful pause |
CloseStreamFailed | terminal model step succeeded but every close failed |
MaxTurnsExceeded | loop exceeded maxTurns |
Retry policy
Default retry policy is noWorkflowStepRetry (maxAttempts: 1), except for closeStream, which
defaults to defaultCloseStreamRetry (maxAttempts: 3). Closing a Workflow stream is idempotent on
Vercel, so a close-only step's retry writes nothing. The platform redelivers a close step whose
function died; the loop retry matters after the step's platform attempts are used up, when the close
was applied but the step still failed (for example its completion was lost): a later attempt that
succeeds completes the run instead of reporting CloseStreamFailed for a stream the client saw end.
The loop retries any rejection, a FatalError thrown by closeStream too. Keep closeStream
close-only and safe to repeat, or pass closeStreamRetry: noWorkflowStepRetry to close once. Opt
into retries per callback:
await runVercelAgentWorkflow({
input,
runModelStep,
runToolBatchStep,
closeStream,
writeError,
modelStepRetry: { maxAttempts: 2 },
toolBatchStepRetry: { maxAttempts: 2 },
awaitInputRetry: { maxAttempts: 2 },
closeStreamRetry: { maxAttempts: 2 }
})Finite maxAttempts values are floored and clamped to at least 1; non-finite values normalize to
1. Retries run immediately with no backoff. writeError is best-effort cleanup and is not retried.
One attempt does not stop platform retries (fn.maxRetries) or queue redelivery: a model or
tool-batch step can still run again after a failure or crash, or concurrently with a running
execution. See
Tool steps run at least once.
maxTurns accepts positive integers. Finite values are floored and clamped to at least 1; omitted
or non-finite values use defaultMaxWorkflowTurns.
eventId de-dupe alone does not make a retried streamed step safe: a retried model step streams a
different answer from the same eventSequence. Give its live events an executionId per execution
and keep deterministic ids only for events every execution writes identically. See
Emit replay-safe stream events.
Terminal barrier
Use commitThenWriteTerminalEvent when terminal events imply durable state is settled:
const result =
yield *
commitThenWriteTerminalEvent({
terminal: agentEndEvent,
commit: persistRunState,
write: event => writeEvent(event),
writeCommitError: error => writeEvent(toAgentErrorEvent(error))
})The helper never writes success terminal before commit succeeds, cannot infer finality from the
event tag, and never closes the writer. It may guard a resumable AgentAwaitingInput persistence
barrier; release the writer lock but leave the Workflow stream open in that case.
writeCommitError is typed as (error: CommitError) => …, where CommitError is the existing
generic on commit. The producer is Effect.matchEffect onFailure; defects do not enter the
callback. CommitThenWriteTerminalEventResult still carries commitError and error as
unknown. Existing (error: unknown) => … callbacks remain assignable.
runVercelAgentWorkflow invokes closeStream only after a model step returns done: true.
Failure paths call writeError and return without invoking closeStream; writeError must write
the safe final error and attempt to close that path. After CloseStreamFailed the stream may
already carry the committed AgentEnd (a close can apply while its step still fails), so a
writeError that records a failure must not replace a committed completion: check for the run's
committed completion (or compare-and-set against it) before recording the failure.