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.
| API | Use when |
|---|---|
run | you already have messages/tools/provider layers and want a stream |
runRuntime + Transcript | the client sends the full transcript each turn |
runRuntime + AppendInput | your server stores an append log |
runRuntime + AppendHitlResponse | resuming 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:
LLMProviderToolExecutorContextTransformerLoopConfig(LoopConfigSettingsforLoopConfig.layer; formerlyLoopConfigShape)
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:
| Tag | Meaning |
|---|---|
Collected | stream completed; collection is finalized |
StreamFailed | typed provider/loop error; partial collection kept |
SinkFailed | typed 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
statewith the latest instruction message of the samekey. Only when it changed does it append a user-role message withrender(state)and a non-model-visibleinstruction: { key, state }envelope (state: undefinedappends a removal notice once). Earlier messages never change, so the cached request prefix survives. rendergets 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
UserMessageevent. Chat projections hide them andtoAgentMessagesround-trips them. - Durable hosts driving
runModelTurnappend and persistinstructionMessages(transcript, instructions)before each model step;runModelTurndoes not acceptinstructions. - 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.