Protocol
Create transcript messages, pass files, and consume stream events.
Use @yolk-sdk/agent/protocol any time your app needs to build messages, inspect stream events, or persist a transcript.
Create messages
Concrete transcript message variants:
UserMessageAssistantAgentMessageToolResultMessage
AgentMessage is the union of those variants, not a fourth message kind:
type AgentMessage = UserMessage | AssistantAgentMessage | ToolResultMessageAssistantAgentMessage is the assistant/model-authored variant. It can contain text, reasoning, host tool calls, provider tool calls, and provider tool results.
Create a normal user message:
import { UserMessage } from '@yolk-sdk/agent/protocol'
const message = UserMessage.make({ content: 'Summarize this file.' })Add optional model-visible envelope facts:
const message = UserMessage.make({
content: 'Summarize this.',
createdAtMs: Date.now(),
author: { displayName: 'Magoz' },
annotations: { timezone: 'Europe/Madrid' }
})Do not put secrets, auth state, private ids, or hidden policy in envelope fields. Providers may send them to models.
Send files and media
Content is either plain text or ordered content parts:
TextPartImagePartDocumentPartAudioPartFilePart: bytes a tool yields for other tools to move, not for the model to view. Tool resolution stores them and the model only sees afileIdlabel (the file claim check,docs/adr/0009-file-claim-check.mdin the repository; tools in@yolk-sdk/files).
Media sources can be inline base64, durable URLs, or host-owned refs:
import { ImagePart, UserMessage, urlAttachmentSource } from '@yolk-sdk/agent/protocol'
const message = UserMessage.make({
content: [
ImagePart.make({
source: urlAttachmentSource('https://cdn.example.com/image.webp'),
mimeType: 'image/webp'
})
]
})Hosts own upload, auth, URL durability, retention, and ref hydration policy. Use
resolveMessageAttachmentSources or resolveMessagesAttachmentSources to resolve sources throughout
user, assistant, and tool-result content without changing durable history. These Effect-native helpers
also traverse nested assistant provider tool results and preserve envelope/part metadata and ordering.
They do not interpret opaque tool/provider payloads or add provider media capabilities.
For private files, resolve fresh URLs inside each provider attempt, after context projection and compaction. See Resolve private attachments for authorization, overflow-retry composition, native tool-result content, and bounded connector downloads.
Consume events
Streams emit AgentEvent values such as:
AgentStart,AgentEnd,AgentError,AgentRetryTurnStart,TurnEndLLMStreamStart,LLMTextDelta,LLMReasoningDelta,LLMStreamEndLLMReasoningReplay(closes a reasoning block with opaque provider state for replay; UIs ignore it)ToolExecutionStarted,ToolExecutionCompleted,ToolExecutionErrorToolExecutionAccepted(a host admitted a background tool call; not completion, no usage)UserMessageEvent,AssistantMessageEventAgentAwaitingInput,QuestionRequested, approval events
Use UserMessageEvent when a host promotes queued user input into a durable stream. The host owns
queue/promotion policy and assigns a stable eventId so replay does not project the message twice:
import { UserMessage, UserMessageEvent } from '@yolk-sdk/agent/protocol'
const event = UserMessageEvent.make({
eventId: 'session_1:user-message_42',
message: UserMessage.make({ content: 'Please compare the alternatives too.' })
})Durable HITL payloads that must be plain JSON use plainHitlResponse /
plainQuestionResponse / plainToolApprovalResponse. Those helpers omit absent optionals and
call PlainHitlResponse.QuestionResponse / PlainHitlResponse.ToolApprovalResponse
(Data.taggedEnum plain objects, _tag last, not Schema classes). QuestionResponse and
ToolApprovalResponse remain Schema classes for protocol values.
Use isTerminalAgentEvent to detect logical stream termination.
import { isTerminalAgentEvent } from '@yolk-sdk/agent/protocol'
for (const event of events) {
if (event._tag === 'LLMTextDelta') {
process.stdout.write(event.text)
}
if (isTerminalAgentEvent(event)) {
break
}
}Missing usage
UsageUpdate carries each model call's token usage as an additive delta, and AgentEnd /
AgentAwaitingInput carry the run's total. When a model stream completes without the usage report
its request asked for (a streamed chat completion cut after its finish chunk, before the
stream_options.include_usage chunk; a streamed Responses response.completed without usage; a
Codex stream without response.completed, or whose recovered response.completed has no usage
that decodes; a Claude or native Messages stream whose
message_stop came without a message_delta carrying an output count), the turn still completes,
and that stream's LLMStreamEnd carries
usageUnavailable: true. Its usage is then missing from the totals, or partial when the stream
sent some UsageUpdates first. Hosts decide how to account for it, for example:
import type { AgentEvent } from '@yolk-sdk/agent/protocol'
const unreportedModelCalls = (events: ReadonlyArray<AgentEvent>) =>
events.filter(event => event._tag === 'LLMStreamEnd' && event.usageUnavailable === true).lengthThe field is optional: it is absent when the report arrived and on events recorded before it existed, so persisted streams decode either way. Non-streamed (JSON) responses are never marked.
Validate transcripts before provider calls
Every assistant host tool call must have a matching ToolResultMessage before the next provider request. Use validateNoDanglingHostToolCalls before lowering transcripts to providers.
Choose model-visible tool content intentionally
ToolResult.content is the provider-facing result. Provider adapters preserve its supported text and
media plus error semantics, but they do not automatically serialize structuredContent into model
requests. structuredContent remains available in tool events, transcript messages, durable wire
round-trips, host UI, and replay.
If the model must use an event, continuation cursor, or other structured value, render a bounded,
intentional projection into content as well. Do not rely on structuredContent alone, and do not
put secrets or private host metadata into model-visible content.
Preserving tool acknowledgements
Use toolResultMessageFromResult(result, envelope?) to copy toolCallId, content, isError,
structuredContent, and background acceptance into a ToolResultMessage. It invents no timestamp,
author, or annotations; pass those optional message-envelope fields explicitly.
It intentionally drops ToolResult.nestedCalls, ToolResult.usage and
ToolResult.usageIncomplete, which are never model-visible. Capture them from the ToolResult or
tool events if you keep audit or billing records. The loop does not add ToolResult.usage to run
usage. usageIncomplete: true means usage under-counts the nested work: a nested model call
completed without (all of) its usage report (its stream's LLMStreamEnd.usageUnavailable, a
provider's LLMDone.usageUnavailable, a classification without usage). It can be set without
usage. A tool that runs its own model calls sets it; recordNestedToolCall ORs it from the
nested calls it records, dropped ones included.
An accepted call is settled, not completed. Client and React projections preserve its original call and receipt across active-event replays (even without event IDs), turn cleanup, and transcript hydration. Persisted acceptance takes precedence over stale active client runs.