Yolk SDK
Agent

Client and React

Connect browser UI to an agent stream and render replay-safe chat state.

Use @yolk-sdk/agent/client for transport helpers and @yolk-sdk/agent/react for headless chat state.

Stream events from an endpoint

import { Stream } from 'effect'
import { streamAgentEventStreamUntilTerminal } from '@yolk-sdk/agent/client'

const events = streamAgentEventStreamUntilTerminal({
  endpoint: '/api/agent',
  sessionId: 'browser-session',
  messages
})

for await (const event of Stream.toAsyncIterable(events)) {
  // update state, persist event, or project into UI
}

Use client helpers for:

  • NDJSON event streams
  • terminal-event detection
  • durable run continuation headers
  • HITL response submission
  • abort/cancel flows
  • typed error/retry state

Durable transports may replay events. Prefer event ids and projection helpers for reconnect-safe UI.

Use React state

@yolk-sdk/agent/react exports useAgentChat and everything in @yolk-sdk/agent/chat, the same chat projection without React (for another UI framework, or a fold on a server):

  • buildAgentChatItems
  • applyAgentEventToChatProjection, and stepAgentChatProjection for a host that folds status beside it; stepAgentChatProjectionAll folds a batch of events (the projection, the events status follows, and whether the message ids changed)
  • the state's Effect Schemas, the types derived from them (each …Schema export, for example AgentChatEventProjectionStateSchema, plus HitlPauses); Schema.toCodecJson of one is its JSON form (seenEventIds, a persistent HashSet, as an array of ids)
  • chat reducer and selectors
  • tagged constructors: AgentChatPart, ChatToolState, AgentChatItem, ToolRunState, DeleteChatTurnResult, EditChatUserMessageResult, RegenerateChatMessagesResult, AgentChatAction, and hook results (AgentChatSubmitResult, AgentChatDeleteTurnResult, AgentChatRegenerateResult, AgentChatEditUserMessageResult, AgentChatHitlResponseResult)
  • ToolDurationKnown / ToolDurationUnknown (Schema.TaggedStruct)

The tagged chat ADTs are Data.taggedEnum values (plain objects, _tag last, not Equal/Hash classes). Build parts with AgentChatPart.Text({ id, content, state }) rather than handwritten { _tag: 'Text', ... }. Omit absent optionals. Discriminate with $is, for example AgentChatSubmitResult.$is('Submitted')(result). useAgentChat dispatches AgentChatAction constructors and returns the hook-result constructors. Duration descriptors use Schema.TaggedStruct.make.

Client and chat state carry the run's status as an AgentStatus plus subagents; failures and pending retries are statuses (Failed, Working(Retrying)), not separate fields.

Name the pause an answer is for

A durable host matches an answer to the pause that asked, not to its request id alone (requests pend again after an invalid answer, and providers reuse call ids; HITL resume). useAgentChat remembers, per request id, the eventId of the latest AgentAwaitingInput that holds the request (state.hitlPauses, from your transport's streams and from applyEvent replays; every pause counts, seen or not, so a replay from an earlier index ends at the latest; stream order decides, so a replay that stops partway or a late duplicate of an earlier pause leaves the earlier one, the route refuses that answer, and a full replay recovers), and gives an answer's transport request that pause as request.pause (absent when no such pause had an eventId). A durable transport passes it on (fragment; the full transport is in HITL resume):

const hitlResponse = request.hitlResponses?.[0]

if (hitlResponse !== undefined) {
  return Stream.toAsyncIterable(
    streamAgentRunHitlResponseEventStreamUntilTerminal({
      endpoint: runEndpoint,
      hitlResponses: [hitlResponse],
      pause: request.pause, // sent as `?pause=<eventId>` on the POST, never on tail reads
      signal: request.signal
    })
  )
}

The map belongs to one stream, like seenEventIds: a new message, an answer, a regeneration or an edit starts afresh. Without React, keep a HitlPauses yourself with rememberHitlPause and hitlPauseFor from @yolk-sdk/agent/client. The default transport (streamAgentEventStream) ignores pause.

The package is headless. It does not ship Yolk UI components, styling, auth, uploads, or route handlers. Your UI owns the input box, message bubbles, attachments, voice controls, pending states, and errors.

Replay-safe projection

import {
  applyAgentEventToChatProjection,
  makeAgentChatEventProjectionState
} from '@yolk-sdk/agent/react'

const projection = events.reduce(
  (state, event) => applyAgentEventToChatProjection(state, event),
  makeAgentChatEventProjectionState()
)

Use append-only projection for durable logs. Use simpler message reducers only for ephemeral local streams.

A retried or redelivered model step streams a second answer for the same turn. Events from a model call can carry executionId and streamId (its run); the chat projection, the useAgentChat reducer and reduceAgentEvents route by them, per run and turn. When a newer execution of a turn starts, the older one's output (streaming text, its assistant message, tool calls nothing acted on) is removed and its later events are dropped; a start for an older turn, or after its run's terminal event, is dropped. At AgentEnd and AgentAwaitingInput, each turn in which a newer execution superseded an older one shows the committed answer from the event's messages, with its tool calls' state; before that event, a non-final turn whose older execution committed shows the newer one. A turn retried after a user message and a client that connected mid-turn have limits. A model event whose execution this client never saw start but that names its turn (executionTurn) starts that turn first, as its LLMStreamStart would have, keeping the draft. Hosts folding status beside the projection fold stepAgentChatProjection's missedStart before its statusEvent. Keep the projection's executions and turnStart with its seenEventIds, and reset executions to [] per run if events carry no streamId. Events without executionId only discard output still streaming at the next LLMStreamStart.

Providers can reuse tool call ids across turns. The chat projection and the useAgentChat reducer record where the latest model turn starts (turnStart), and a turn's tool events only match a call after it, so a later turn's call never changes an earlier turn's call with the same id. A replayed or late request or tool-batch event updates the earlier part holding the same call (send the call as the model emitted it), and a replayed answer the part holding its request, also when the latest turn holds another call reusing the id: a replay of an earlier turn's pause leaves a later turn's pending card, and the status blocked on it, alone. An answer whose request no part holds changes nothing when the call it reaches holds another request or already has its result (a stale answer), and a denial answers only a pending approval (or a call holding no request); reduceAgentEvents reads its runs the same way. A replayed request (or AgentAwaitingInput) never reopens a call already answered, cancelled, denied or finished, and the useAgentChat reducer keeps its status when a replayed AgentAwaitingInput names only such calls (a pause naming some blocks only on its pending requests); a host folding status beside the projection gets the same answer from stepAgentChatProjection (status). An invalid input answer re-pends a request that is still pending, and a running call stopped by an abort is asked again when the next run resumes it. A replayed start of the same call leaves a completed, accepted or errored call, and the status, alone. AgentStart and a local submit (or answer, regenerate, edit) mark a run start, so a resumed run's tool batch, which runs before the run's first model turn, acts on the paused call, or adds its own, never on an earlier turn's call reusing its id. Before any start is seen, and in applyAgentEventToChatMessages, a tool event matches the last message holding the call (answers and added results update only that one). reduceAgentEvents scopes its tool runs the same way (turnStart on its state): a later turn's call reusing an id gets its own run, also when the id was an accepted background call's, so toolRuns can hold one run per turn for an id (the last is the latest). It follows the same request rule and status fence: a replayed request leaves a run already answered, cancelled, denied or finished alone (a running call is asked again), and a replayed pause blocks only on its pending requests.

Rebuild from a snapshot

A host that keeps its own snapshot (stored messages, pending requests, accepted interaction receipts) rebuilds chat state with buildAgentChatMessages. Its toolRuns can hold runs of several turns for one call id (one per turn from reduceAgentEvents, or pending requests from toolRunsFromHitlRequests beside an earlier turn's receipt), so each run goes to one card, later runs first, each card taking at most one. A run holding a call (its own or its request's) takes the last card holding the same call (id, name and arguments equal). A run holding no call (an input still streaming, an answer or denial without its request) that answers an earlier run's request takes that run's card (a later denial wins over the pending approval it denies), else the last card with its id that no run took (one without a result message first while the run still waits on its result: an input streaming, a submitted interaction). A card no run reaches shows its own result message: the result after it, never another turn's reusing the id (a result with no card before it shows on its own).

Give each run the call as the transcript holds it (toolRunsFromHitlRequests does, from the loop's requests). A run whose call equals no card's (arguments you normalized or re-serialized) falls back to the last card with its id and name that no run took and that has no result message, and shows nowhere when there is none; a different name is another turn's call.

When the snapshot's run may resume (a HITL answer, a stopped run going on), mark a run start on the rebuilt state:

import { initialAgentClientState, markAgentRunStart } from '@yolk-sdk/agent/client'
import {
  buildAgentChatMessages,
  makeAgentChatEventProjectionState,
  markChatRunStart
} from '@yolk-sdk/agent/react'

const projection = markChatRunStart(
  makeAgentChatEventProjectionState(
    buildAgentChatMessages({
      messages,
      toolRuns,
      userDraft: '',
      assistantDraft: '',
      reasoningDraft: '',
      error: null
    })
  )
)

const client = markAgentRunStart({ ...initialAgentClientState, messages, toolRuns })

The resumed run's AgentStart can lie before your stream cursor, and its tool batch runs before its first model turn. Without a start, the batch acts on the last card or run holding its call id, which can be an earlier turn's (client runs kept from earlier turns, or stored messages that lag the run). With the run start, it reaches the snapshot's cards and runs only as the same call or, for answers, the one holding their request, and adds its own otherwise. A snapshot taken mid-turn keeps working: that turn's later host events name calls in the snapshot's last message and find them as the same call. Its model events carrying executionTurn with their executionId (the vercel-workflows sequencer sets both) start the turn they name, as its missed LLMStreamStart would, so a reused id among them stays off earlier turns' calls. Model events without executionTurn before the next LLMStreamStart count as replays of an earlier run's, so a reused id among them can still reach an earlier turn's call, as without a start. A client that missed a run's LLMStreamStart otherwise (it connected mid-turn after a local submit, or an AgentStart replayed without eventId after the turn's start, whose replay its event id then dedupes) has the same limit for such events. The next AgentStart or LLMStreamStart replaces the run start.

On this page