Yolk SDK
Vercel Workflows

Routes

Start, tail, resume, and cancel durable Workflow-backed agent runs.

Routes are app-owned. @yolk-sdk/vercel-workflows gives workflow orchestration, @yolk-sdk/vercel-workflows/effect gives Effect wrappers around public workflow/api, and @yolk-sdk/agent/client gives optional NDJSON transport helpers. Your app owns auth, run ownership, persistence, and response shape.

Start a run

Effect route fragment:

import { Effect } from 'effect'
import { VercelWorkflows } from '@yolk-sdk/vercel-workflows/effect'
import { runAgentWorkflow } from './host-run-agent-workflow'

export const startProgram = (request: Request) =>
  Effect.gen(function* () {
    const workflows = yield* VercelWorkflows
    const body = yield* Effect.promise(() => request.json())
    const input = yield* Effect.promise(() => decodeStartRequest(body))
    yield* Effect.promise(() => assertCanStartRun(input))

    const run = yield* workflows.start(runAgentWorkflow, [
      {
        request: input.request,
        context: input.context
      }
    ])
    const readable = yield* run.getReadable<Uint8Array>()

    return new Response(readable, {
      headers: {
        'content-type': 'application/x-ndjson',
        'x-workflow-run-id': run.runId
      }
    })
  })

decodeStartRequest and assertCanStartRun are host functions. Do not trust client-provided tools, provider config, or workflow context.

Tail an existing run

import { Effect } from 'effect'
import { VercelWorkflows } from '@yolk-sdk/vercel-workflows/effect'

export const tailProgram = (request: Request, runId: string) =>
  Effect.gen(function* () {
    const workflows = yield* VercelWorkflows
    yield* Effect.promise(() => assertCanReadRun(runId))
    const startIndex = startIndexFromRequest(request)
    const readable = yield* workflows.getReadable<Uint8Array>(runId, { startIndex })

    return new Response(readable, {
      headers: { 'content-type': 'application/x-ndjson' }
    })
  })

Clients can use streamAgentRunEventStreamUntilTerminal with this route.

At AgentAwaitingInput, clients reach a logical terminal boundary and should drain/release the HTTP body without cancellation. The underlying Workflow writable remains open. After resume, tail from the saved Workflow stream index so continued tool/model events append to the same run.

Quiet runs

A run writes nothing while its model thinks or a tool runs, and a client that resumes at the tail reads nothing until the next event. Next.js sends a streamed response's headers only with its first body chunk, so until then the client cannot even tell the route answered. The Yolk client reads blank lines as heartbeats: they are not events and do not move the stream index, but they prove the connection is alive, so the idleReconnect: { idleTimeoutMs, maxAttempts } option of the *UntilTerminal helpers reconnects only after idleTimeoutMs of silence. Start the body with one blank line and send another whenever the run has been quiet for well under the client's idleTimeoutMs (a third of it leaves room for a late one). Insert them only between whole lines: writeDurableAgentEvent writes one NDJSON line per chunk, so a stream of its chunks qualifies.

Heartbeats prove the route is alive, not that the run makes progress: if the Workflow readable stalls while the route keeps beating, the client waits until the response ends (at the function's maximum duration, for example) and then continues from its index. Without heartbeats it reconnects every idleTimeoutMs instead, healthy quiet runs included.

const blankLine = new TextEncoder().encode('\n')

const withHeartbeats = (readable: ReadableStream<Uint8Array>, intervalMs: number) => {
  const reader = readable.getReader()
  let timer: ReturnType<typeof setTimeout> | undefined
  let open = true

  const stop = () => {
    open = false
    clearTimeout(timer)
  }

  const beatAfterQuiet = (controller: ReadableStreamDefaultController<Uint8Array>) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      // A connection still busy with earlier bytes needs no heartbeat.
      if (open && (controller.desiredSize ?? 0) > 0) controller.enqueue(blankLine)
      beatAfterQuiet(controller)
    }, intervalMs)
  }

  return new ReadableStream<Uint8Array>({
    start(controller) {
      controller.enqueue(blankLine)
      beatAfterQuiet(controller)
    },
    async pull(controller) {
      try {
        const result = await reader.read()

        if (!open) return

        if (result.done) {
          stop()
          controller.close()
        } else {
          controller.enqueue(result.value)
          beatAfterQuiet(controller)
        }
      } catch (error) {
        stop()
        controller.error(error)
      }
    },
    cancel(reason) {
      stop()

      return reader.cancel(reason)
    }
  })
}

Return new Response(withHeartbeats(readable, intervalMs), { headers }). Validate access and the run before building it, so refusals keep their status: once the blank line is sent the status is 200, and a later failure can only end the body early.

Resume HITL

Route fragment (host-owned helpers):

import { Effect } from 'effect'
import { VercelWorkflows } from '@yolk-sdk/vercel-workflows/effect'

export const resumeProgram = (request: Request, runId: string) =>
  Effect.gen(function* () {
    const workflows = yield* VercelWorkflows
    yield* Effect.promise(() => assertCanResumeRun(runId))

    const body = yield* Effect.promise(() => request.json())
    const hitlResponse = yield* Effect.promise(() => decodeSingleHitlResponse(body.hitlResponses))
    // The pause this answers: the `eventId` of its `AgentAwaitingInput`, named by the client.
    const pauseId = new URL(request.url).searchParams.get('pause')

    if (pauseId === null) return refusedAnswerResponse('Name the pause this answers')

    const tailIndex = yield* workflows.tailIndex(runId)
    // Host-owned, as in HITL resume: records the answer for the named pause (with this tail index;
    // an identical retry gets the first record's), then resumes that pause's own hook token with
    // it, retrying a bounded number of times on `HookNotFoundError` while the pause is pending.
    // A delivered pause's identical answer is reported without resuming; the rest are refused.
    const recorded = yield* Effect.promise(() =>
      recordAndResumeHitlAnswer({ runId, pauseId, response: hitlResponse, tailIndex })
    )

    if (recorded.status === 'refused') return refusedAnswerResponse(recorded.reason)
    // Out of resume attempts: the answer stays recorded; a retryable 503 says retrying is safe.
    if (recorded.status === 'hook-pending') return answerRecordedRetryResponse(recorded)

    // Replay from the recorded tail, so every retry of this answer replays the same continuation.
    const readable = yield* workflows.getReadable<Uint8Array>(runId, {
      startIndex: recorded.tailIndex + 1
    })

    return new Response(readable, {
      headers: {
        'content-type': 'application/x-ndjson',
        'x-workflow-stream-tail-index': String(recorded.tailIndex)
      }
    })
  })

The helper-compatible request body is { hitlResponses }; the client names the pause as the pause query parameter of the POST (?pause=<eventId>, what streamAgentRunHitlResponseEventStreamUntilTerminal sends for its pause option; tail reads carry none). The resume side must verify the authenticated user owns the run, match the response against the requests of the pause it names (never by request id alone), and record it before resuming. The full record-then-resume code and its rules are in HITL resume.

If your resume route returns 202 with no body, do not use streamAgentRunHitlResponseEventStreamUntilTerminal. POST the resume yourself, then call streamAgentRunEventStreamUntilTerminal on the tail route.

Cancel a run

import { Effect } from 'effect'
import { VercelWorkflows } from '@yolk-sdk/vercel-workflows/effect'

export const cancelProgram = (runId: string) =>
  Effect.gen(function* () {
    const workflows = yield* VercelWorkflows
    yield* Effect.promise(() => assertCanCancelRun(runId))
    yield* workflows.cancel(runId)

    return new Response(null, { status: 204 })
  })

Cancellation is host/Vercel-owned. The package does not define a cancellation protocol event.

Client helpers

Import these from @yolk-sdk/agent/client.

Client APIRoute shape
streamAgentEventStreamUntilTerminalstarts run and follows continuation headers
streamAgentRunEventStreamUntilTerminalreads an existing run tail
streamAgentRunHitlResponseEventStreamUntilTerminalresumes HITL and follows returned/tail chunks
cancelAgentRuncalls your cancel route

Headers

Use the SDK header helpers from @yolk-sdk/agent/client on the client:

  • agentRunIdFromHeaders
  • agentRunStreamTailIndexFromHeaders
  • agentRunStreamStartIndexFromHeaders
  • agentRunEndpointWithStartIndex

Header meanings:

HeaderMeaning
x-workflow-run-idVercel Workflow run id returned by your start route
x-workflow-stream-tail-indexVercel stream chunk index immediately before the response body starts

The stream tail index is for Vercel continuation chunks. It is distinct from durable agent eventSequence, which is part of replay-safe event ids.

On this page