Yolk SDK
Agent

Loop and runtime

Choose `run` or `runRuntime` and stream agent events from your app.

Use the loop when you want direct control. Use runtime when you want a reusable HTTP/session boundary.

APIUse when
runyou already have messages/tools/provider layers and want a stream
runRuntime + Transcriptthe client sends the full transcript each turn
runRuntime + AppendInputyour server stores an append log
runRuntime + AppendHitlResponseresuming a paused approval/question

Direct loop

import { Effect, Stream } from 'effect'
import { run } from '@yolk-sdk/agent/loop'
import { UserMessage } from '@yolk-sdk/agent/protocol'

const stream = run({
  messages: [UserMessage.make({ content: 'Draft a reply.' })],
  systemPrompt: 'Be helpful.',
  tools,
  model: 'gpt-5.5'
})

const events = await Effect.runPromise(
  stream.pipe(Stream.runCollect, Effect.provide(AppAgentLayer))
)

Provide these Effect services from your host:

  • LLMProvider
  • ToolExecutor
  • ContextTransformer
  • LoopConfig (LoopConfigSettings for LoopConfig.layer; formerly LoopConfigShape)

Compose the loop layer

makeAgentLoopLayer merges those four Layers. The provider layer is required. Omitted tools use ToolExecutor.unavailable (calls fail with ToolError cause: 'execution'). Omitted transformer/config use ContextTransformer.identity and LoopConfig.defaultLayer.

Fragment. This constructs a layer and does not run a provider call:

import { makeAgentLoopLayer } from '@yolk-sdk/agent/loop'
import { FauxProvider, Reply } from '@yolk-sdk/agent/loop/testing'

const LoopLayer = makeAgentLoopLayer({
  provider: FauxProvider.layer(Reply.text('ok'))
})

Intercept by decorating a service (decorateLLMProvider), not with hooks. Pass the decorator layer as provider after providing the inner provider.

collectModelTurn(stream, { initialUsage, onEvent }) is the success-only wrapper: it returns a finalized ModelTurnResult or re-fails. initialUsage is the starting cumulative usage; UsageUpdate events add to it. usageUnavailable: true says the stream's LLMStreamEnd was marked usageUnavailable, so usage under-counts the turn; a tool that runs model turns reports it as ToolResult.usageIncomplete.

collectModelTurnAttempt keeps a ModelTurnCollection on typed stream or sink failure:

TagMeaning
Collectedstream completed; collection is finalized
StreamFailedtyped provider/loop error; partial collection kept
SinkFailedtyped onEvent error; not a model-recovery outcome

onEvent sink errors are not model-recovery outcomes. Defects, interrupts, and mixed typed+defect/interrupt Causes are re-failed as Causes rather than StreamFailed / SinkFailed.

For durable Workflow hosts, use the existing Harness composition cookbook rather than duplicating collector/recovery policy here.

Stateless transcript runtime

Use this when your route receives the whole transcript from a client:

import { runRuntime } from '@yolk-sdk/agent/runtime'
import { UserMessage } from '@yolk-sdk/agent/protocol'

const stream = runRuntime(
  {
    _tag: 'Transcript',
    sessionId: 'browser-session',
    messages: [UserMessage.make({ content: 'Hello' })]
  },
  {
    systemPrompt: 'Be helpful.',
    tools,
    model: 'gpt-5.5'
  }
)

Your route converts the stream to NDJSON/SSE and provides provider/tool layers.

Append-backed runtime

Use this when your server stores every input/run/result in SessionEventStore. This fits Durable Objects, databases, or other append logs:

const stream = runRuntime(
  {
    _tag: 'AppendInput',
    sessionId: 'session_123',
    input: UserMessage.make({ content: 'Continue' }),
    runId: 'run_123'
  },
  runtimeConfig
)

Production apps implement SessionEventStore; tests can use the in-memory layer.

Host instructions

A RunInstruction ({ key, state, render }) is host context kept current in the conversation, for example the code mode catalog (toolSet.instructions from resolveTools). Pass it as RunConfig.instructions or RuntimeConfig.instructions.

  • Before each model request the loop compares state with the latest instruction message of the same key. Only when it changed does it append a user-role message with render(state) and a non-model-visible instruction: { key, state } envelope (state: undefined appends a removal notice once). Earlier messages never change, so the cached request prefix survives.
  • render gets only the current state: compaction keeps the latest message of each key, so every message must stand alone.
  • Appended messages are part of the run's created messages (persist them with the turn) but emit no UserMessage event. Chat projections hide them and toAgentMessages round-trips them.
  • Durable hosts driving runModelTurn append and persist instructionMessages(transcript, instructions) before each model step; runModelTurn does not accept instructions.
  • Two instructions with one key fail resolution (duplicate_instruction).

Add compaction

@yolk-sdk/agent/compaction provides helpers for budgets, token estimation, preview summaries, checkpoint messages, transcript formatting, overflow retry, and window transforms.

For long-lived server-owned sessions, see Implement durable compaction.

On this page