koel_core library
AG-UI protocol kernel for Dart — the framework-free core every other koel package builds on.
This barrel is the public 1.x contract of koel_core: every symbol
reachable through it is a one-way door (AR-15 / NFR-13). It surfaces the
three-layer client API, the sealed AgUiEvent union, the sealed KoelError
hierarchy, the ChatState reduction seam, session persistence, and the
value-level protocol types (events, messages, tools, JSON Patch operations) —
and deliberately nothing else. The wire deserializer and the JSON Patch
applier are kernel machinery: consumers reach them through
KoelClient/ChatSession, never directly, so they stay in lib/src/ off
the contract. The pipeline stays internal too, with one carve-out:
chunksStage, the *_CHUNK → START/CONTENT/END synthesizer, is public
because a sibling transport package (koel_http, HttpAgent.synthesizeChunks,
Addendum F.2) must reuse the single F.2 source of truth rather than fork it.
verifyStage/applyStage/transformStage remain internal — nothing outside
the pipeline composes them.
Import this file — never a package:koel_core/src/... path (the internals
are unstable across minor versions). Exports are grouped by subsystem in
dependency order.
Classes
- AbstractAgent
- Backend-bridge SPI: the single contract every transport/backend adapter implements.
- ActivityDeltaEvent
-
ACTIVITY_DELTA— an incremental mutation of a prior ActivitySnapshotEvent's content, carried as RFC 6902 JSON Patch ops the consumer folds onto the activity. This event only transports thepatches; the empty/invalid-op rejection is the verify stage's job (Story 2.11 / Addendum F.1), so an emptypatchdecodes to an emptypatcheslist here. - ActivitySnapshotEvent
-
ACTIVITY_SNAPSHOT— a frontend-only structured-UI element (progress bar, checklist, …) keyed bymessageIdandactivityType. Activity content never reaches the agent; it is rendered by the consumer surface (Epic 6/7). - AddOp
-
RFC 6902
add: insertsvalueatpath— replacing an existing object member, inserting into an array (shifting later elements), appending when the final token is-, or replacing the whole document whenpathis"". - AgentSubscriber
- A passive, post-pipeline observer of an agent run — the cross-cutting hook bag for devtools, telemetry, and analytics (FR-A10).
- AgUiEvent
-
Root of the AG-UI event union — the canonical stream element every
AbstractAgentemits. - ChatSession
- The middle layer of the three-layer API (F-A2): one stateful conversation over a KoelClient. Construct it via KoelClient.newSession, never directly.
- ChatState
-
An immutable snapshot of a conversation — the value the reducer folds events
into (FR-D2). The
applypipeline stage surfaces it as a side accumulation; it is never serialized here (persistence is Story 2.13 / Epic 6). - ChatStateReducer
-
The pure fold that drives the
applypipeline stage: given the current ChatState and one canonical AgUiEvent, it returns the next state. - ComposedReducer
- Composes reducers left-to-right over the same event — the F-D2 layering seam consumers use to stack custom reduction on top of DefaultChatStateReducer.
- Context
- A piece of contextual information supplied to the agent for a run.
- CopyOp
-
RFC 6902
copy: deep-copies the value atfromand adds it atpath.frommust exist. - CustomEvent
-
CUSTOM— a provider- or consumer-declared extension event: a namedvalueoutside koel's typed families, carried by the protocol as a first-class shape (AG-UICustomEvent=name+value). - DefaultChatStateReducer
-
The default
ChatStateReducer— folds the canonical AG-UI stream (the post-chunks, post-verifyevents) into ChatState per the Addendum A.1 / C.1 fold contract. - DefaultErrorClassifier
-
The framework-free base classifier mapping common Dart exception shapes to
KoelError subtypes. Web-safe by design: it never imports
dart:ioorpackage:http(koel_core is the six-platform kernel — web has nodart:io, architecture §D4). - ErrorClassifier
-
Maps a raw failure (a caught exception, a thrown
Object, …) onto the typed KoelError union — the pluggable classification seam (architecture §5). - InMemorySessionStorage
-
Process-lifetime SessionStorage backed by a plain in-process
Map— the zero-dependency reference impl, the fallback when no persistent adapter is configured, and whatkoel_test/examples wire. - Interceptor
-
A single cross-cutting stage wrapped around agent execution — auth, retry,
logging, telemetry, anything that observes or rewrites a run without being
the run itself (FR-A4). The contract lives here in
koel_core; the six built-ins (AuthInterceptor,RetryInterceptor, …) ship inkoel_http. - InterceptorChain
- Drives an ordered Interceptor list around a terminal AbstractAgent.
- JsonPatchOp
-
One RFC 6902 JSON Patch operation — the typed, value-comparable unit a
STATE_DELTAcarries (StateDeltaEvent.patches: List<JsonPatchOp>, Story 2.6) andJsonPatch.applyfolds into a state document. - KoelClient
- The top of the three-layer API (F-A2): a non-singleton client that wires every Epic 2 kernel piece — the terminal AbstractAgent, the Interceptor chain, the AgentSubscriber bag, the ChatStateReducer, the ErrorClassifier, the StateConflictResolver, persistence, and the backpressure/devtools config — into one consumable surface.
- LastWriterWinsResolver
-
The default StateConflictResolver: the incoming delta is the last writer,
so it wins. Applies
StateConflict.incomingPatchesverbatim ontoStateConflict.localStateviaJsonPatch.apply— no merge against the snapshot. (snapshotStateexists for smarter resolvers; this one ignores it.) This makes conflict resolution a no-op relative to plain application: the conflict machinery exists so other resolvers can do better. - Message
-
A single conversation message — the element type of
RunAgentInput.messages(and, from Story 2.12,ChatState.messages). - MessagesSnapshotEvent
-
MESSAGES_SNAPSHOT— a full replay of the conversation history, replacingChatState.messageswholesale (Story 2.12).messagesconsumes the Story-2.1 Message leaf type and delegates element (de)serialization to its own codec, so every field — includingDateTimeand the optionaltoolCallId/name— round-trips without information loss. - MoveOp
-
RFC 6902
move: removes the value atfromand adds it atpath.frommust exist and must not be a proper prefix ofpath(a location cannot be moved into one of its own children). - RawEvent
-
RAW— an opaque passthrough event whosepayloadkoel never inspects, validates, or redacts: it flows verbatim from the wire through the pipeline to subscribers. The escape hatch for provider-specific events that pre-date or sit outside koel's typed families. - ReasoningEncryptedValueEvent
-
REASONING_ENCRYPTED_VALUE— an opaque provider reasoning blob (Anthropic / OpenAI zero-retention chain-of-thought) that must round-trip verbatim or the provider rejects the next request (FR-A9). Keyed byentityId(echoed back viaRunAgentInput.reasoningEchoin a later run, accumulated by the reducer in Story 2.12) andsubtype("tool-call"or"message", kept a permissiveString). - ReasoningEndEvent
-
REASONING_END— closes the reasoning span identified bymessageId. - ReasoningMessageChunkEvent
-
REASONING_MESSAGE_CHUNK— the convenience wire shape (all fields optional) thechunkspipeline stage (Story 2.11) expands into ReasoningMessageStartEvent→ReasoningMessageContentEvent→ReasoningMessageEndEvent usingmessageId+delta. Story 2.7 ships only the typed value; the expansion is Story 2.11. UnlikeTEXT_MESSAGE_CHUNK, the reasoning chunk carries norole. - ReasoningMessageContentEvent
-
REASONING_MESSAGE_CONTENT— one streameddeltaof the reasoning message identified bymessageId. The consumer concatenates deltas in order. - ReasoningMessageEndEvent
-
REASONING_MESSAGE_END— closes the streamed reasoning message identified bymessageId. - ReasoningMessageStartEvent
-
REASONING_MESSAGE_START— opens a streamed reasoning message. The canonical long form: ReasoningMessageContentEvent deltas follow, closed by ReasoningMessageEndEvent, all sharingmessageId. - ReasoningStartEvent
-
REASONING_START— opens a reasoning (chain-of-thought) span identified bymessageId, closed by ReasoningEndEvent. The reasoning message stream (ReasoningMessageStartEvent→…→ReasoningMessageEndEvent) lives between them. - RemoveOp
-
RFC 6902
remove: deletes the value atpath. The target must exist. - ReplaceOp
-
RFC 6902
replace: sets the value atpathtovalue. Equivalent to aremovefollowed by anadd; the target must already exist. - RunAgentInput
- The wire payload that initiates an agent run.
- RunErrorEvent
-
RUN_ERROR— the agent terminated a run with a failure. Carries the typed KoelError consumed via the Story-2.3 union (no new error type). - RunFinishedEvent
-
RUN_FINISHED— the agent completed a run successfully. Closes the lifecycle opened by RunStartedEvent. - RunStartedEvent
-
RUN_STARTED— the agent has begun a run on a thread. The first lifecycle event of every run; brackets the stream with RunFinishedEvent (or RunErrorEvent). - SessionStorage
-
Persistence SPI for ChatState keyed by
threadId(F-D1). - StateConflict
-
A detected state divergence: a
STATE_DELTAwhoseincomingPatchestouch a path the consumer mutated locally since the lastSTATE_SNAPSHOT(F-A8). - StateConflictResolver
-
The F-A8 resolution policy: given a detected StateConflict, returns the
state map the next
ChatState.stateshould carry. - StateDeltaEvent
-
STATE_DELTA— an incremental mutation of the shared agent state as RFC 6902 JSON Patch ops the reducer (Story 2.12) folds onto the current state viaJsonPatch.apply. This event only transports thepatches; the empty-patches and invalid-op rejection is the verify stage's job (Story 2.11 / Addendum F.1), so an emptydeltadecodes to an emptypatcheslist here. - StateSnapshotEvent
-
STATE_SNAPSHOT— a full replacement of the shared agent state (cold start or resync). The reducer (Story 2.12) replacesChatState.statewholesale withstate. - StepFinishedEvent
-
STEP_FINISHED— the agent left the named step. ItsstepNamemust match the prior StepStartedEvent; that cross-event pairing invariant is enforced by the verify pipeline stage in Story 2.11, not by this transient value. - StepStartedEvent
-
STEP_STARTED— the agent entered a named step within a run (a tool phase, a planning stage, …). Brackets the step with StepFinishedEvent. - TestOp
-
RFC 6902
test: asserts the value atpathis deeply equal tovalue. A mismatch (or a missingpath) fails the entire patch. - TextMessageChunkEvent
-
TEXT_MESSAGE_CHUNK— the convenience wire shape (all fields optional) thechunkspipeline stage (Story 2.11) expands into TextMessageStartEvent→TextMessageContentEvent→TextMessageEndEvent usingmessageId+role+delta. Story 2.5 ships only the typed value; the expansion and the "must carrymessageId" verify rule (Addendum F.1) are Story 2.11. - TextMessageContentEvent
-
TEXT_MESSAGE_CONTENT— one streameddeltaof the message identified bymessageId. The reducer concatenates deltas in order (Story 2.12). - TextMessageEndEvent
-
TEXT_MESSAGE_END— closes the streamed message identified bymessageId. - TextMessageStartEvent
-
TEXT_MESSAGE_START— opens a streamed assistant message. The canonical long form: TextMessageContentEvent deltas follow, closed by TextMessageEndEvent, all sharingmessageId. - ToolCall
-
An in-flight tool invocation accumulated by the reducer — the element type of
ChatState.pendingToolCalls. - ToolCallArgsEvent
-
TOOL_CALL_ARGS— one streameddeltaof the tool-call arguments fortoolCallId. The argument deltas are JSON fragments; concatenate them in order to reconstruct the complete arguments JSON string (thechunks/reducer stages own that assembly, not this event). - ToolCallChunkEvent
-
TOOL_CALL_CHUNK— the convenience wire shape (all fields optional) thechunkspipeline stage (Story 2.11) expands into ToolCallStartEvent→ToolCallArgsEvent→ToolCallEndEvent usingtoolCallId+toolCallName+parentMessageId+deltaper Addendum F.2. Story 2.6 ships only the typed value; the expansion and the "must carrytoolCallId" verify rule (Addendum F.1) are Story 2.11. - ToolCallEndEvent
-
TOOL_CALL_END— closes the streamed tool call identified bytoolCallId. - ToolCallResultEvent
-
TOOL_CALL_RESULT— the result of a tool invocation, emitted by the agent when it executes a backend tool itself (the frontend-tool path instead returns arole: "tool"Message on the next run).contentis the result payload as a string;messageIdidentifies the result message andtoolCallIdlinks it back to the originating call. - ToolCallStartEvent
-
TOOL_CALL_START— the agent has begun a tool invocation. Opens the streaming call: N×ToolCallArgsEvent deltas follow, closed by ToolCallEndEvent, all sharingtoolCallId. - ToolDefinition
- A tool the agent is permitted to call during a run.
- UnknownAgUiEvent
-
Forward-compat fallback member of the AgUiEvent union: the typed home for
any wire event whose
typethe currentkoel_coreevent registry does not recognize (FR-A6 / FC-1).
Enums
- BackpressurePolicy
- How the SDK sheds load when a consumer reads slower than an agent produces.
- KoelErrorCode
-
The typed failure vocabulary classified onto every
KoelError. - MessageRole
- Author of a Message in the AG-UI conversation.
- RunPhase
-
Lifecycle phase of the current run, folded from the
RUN_*/STEP_*events.
Extensions
- ActivityDeltaEventPatterns on ActivityDeltaEvent
- Adds pattern-matching-related methods to ActivityDeltaEvent.
- ActivitySnapshotEventPatterns on ActivitySnapshotEvent
- Adds pattern-matching-related methods to ActivitySnapshotEvent.
- AddOpPatterns on AddOp
- Adds pattern-matching-related methods to AddOp.
- AgentErrorPatterns on AgentError
- Adds pattern-matching-related methods to AgentError.
- BusinessErrorPatterns on BusinessError
- Adds pattern-matching-related methods to BusinessError.
- ChatStatePatterns on ChatState
- Adds pattern-matching-related methods to ChatState.
- ContextPatterns on Context
- Adds pattern-matching-related methods to Context.
- CopyOpPatterns on CopyOp
- Adds pattern-matching-related methods to CopyOp.
- CustomEventPatterns on CustomEvent
- Adds pattern-matching-related methods to CustomEvent.
- MessagePatterns on Message
- Adds pattern-matching-related methods to Message.
- MessagesSnapshotEventPatterns on MessagesSnapshotEvent
- Adds pattern-matching-related methods to MessagesSnapshotEvent.
- MoveOpPatterns on MoveOp
- Adds pattern-matching-related methods to MoveOp.
- ProtocolErrorPatterns on ProtocolError
- Adds pattern-matching-related methods to ProtocolError.
- RawEventPatterns on RawEvent
- Adds pattern-matching-related methods to RawEvent.
- ReasoningEncryptedValueEventPatterns on ReasoningEncryptedValueEvent
- Adds pattern-matching-related methods to ReasoningEncryptedValueEvent.
- ReasoningEndEventPatterns on ReasoningEndEvent
- Adds pattern-matching-related methods to ReasoningEndEvent.
- ReasoningMessageChunkEventPatterns on ReasoningMessageChunkEvent
- Adds pattern-matching-related methods to ReasoningMessageChunkEvent.
- ReasoningMessageContentEventPatterns on ReasoningMessageContentEvent
- Adds pattern-matching-related methods to ReasoningMessageContentEvent.
- ReasoningMessageEndEventPatterns on ReasoningMessageEndEvent
- Adds pattern-matching-related methods to ReasoningMessageEndEvent.
- ReasoningMessageStartEventPatterns on ReasoningMessageStartEvent
- Adds pattern-matching-related methods to ReasoningMessageStartEvent.
- ReasoningStartEventPatterns on ReasoningStartEvent
- Adds pattern-matching-related methods to ReasoningStartEvent.
- RemoveOpPatterns on RemoveOp
- Adds pattern-matching-related methods to RemoveOp.
- ReplaceOpPatterns on ReplaceOp
- Adds pattern-matching-related methods to ReplaceOp.
- RunAgentInputPatterns on RunAgentInput
- Adds pattern-matching-related methods to RunAgentInput.
- RunErrorEventPatterns on RunErrorEvent
- Adds pattern-matching-related methods to RunErrorEvent.
- RunFinishedEventPatterns on RunFinishedEvent
- Adds pattern-matching-related methods to RunFinishedEvent.
- RunStartedEventPatterns on RunStartedEvent
- Adds pattern-matching-related methods to RunStartedEvent.
- StateConflictPatterns on StateConflict
- Adds pattern-matching-related methods to StateConflict.
- StateDeltaEventPatterns on StateDeltaEvent
- Adds pattern-matching-related methods to StateDeltaEvent.
- StateSnapshotEventPatterns on StateSnapshotEvent
- Adds pattern-matching-related methods to StateSnapshotEvent.
- StepFinishedEventPatterns on StepFinishedEvent
- Adds pattern-matching-related methods to StepFinishedEvent.
- StepStartedEventPatterns on StepStartedEvent
- Adds pattern-matching-related methods to StepStartedEvent.
- TestOpPatterns on TestOp
- Adds pattern-matching-related methods to TestOp.
- TextMessageChunkEventPatterns on TextMessageChunkEvent
- Adds pattern-matching-related methods to TextMessageChunkEvent.
- TextMessageContentEventPatterns on TextMessageContentEvent
- Adds pattern-matching-related methods to TextMessageContentEvent.
- TextMessageEndEventPatterns on TextMessageEndEvent
- Adds pattern-matching-related methods to TextMessageEndEvent.
- TextMessageStartEventPatterns on TextMessageStartEvent
- Adds pattern-matching-related methods to TextMessageStartEvent.
- ToolCallArgsEventPatterns on ToolCallArgsEvent
- Adds pattern-matching-related methods to ToolCallArgsEvent.
- ToolCallChunkEventPatterns on ToolCallChunkEvent
- Adds pattern-matching-related methods to ToolCallChunkEvent.
- ToolCallEndEventPatterns on ToolCallEndEvent
- Adds pattern-matching-related methods to ToolCallEndEvent.
- ToolCallPatterns on ToolCall
- Adds pattern-matching-related methods to ToolCall.
- ToolCallResultEventPatterns on ToolCallResultEvent
- Adds pattern-matching-related methods to ToolCallResultEvent.
- ToolCallStartEventPatterns on ToolCallStartEvent
- Adds pattern-matching-related methods to ToolCallStartEvent.
- ToolDefinitionPatterns on ToolDefinition
- Adds pattern-matching-related methods to ToolDefinition.
- TransportErrorPatterns on TransportError
- Adds pattern-matching-related methods to TransportError.
- UnknownAgUiEventPatterns on UnknownAgUiEvent
- Adds pattern-matching-related methods to UnknownAgUiEvent.
Properties
-
chunksStage
→ StreamTransformer<
AgUiEvent, AgUiEvent> -
Pipeline stage 1 — synthesizes the streaming
*_CHUNKconvenience shapes into the canonicalSTART→CONTENT/ARGS→ENDtriplets every downstream stage and consumer expects (Addendum F.2). Runs beforeverifyStagebecause verify checks theSTART/ENDpairing this stage creates.final
Exceptions / Errors
- AgentError
- A failure originating inside the agent's execution — it refused the request, a tool call failed, or it errored internally. Also the least-wrong home for an unclassifiable failure (KoelErrorCode.unknown), since an opaque error is — from the SDK's vantage — a failure at the agent-execution boundary.
- BusinessError
- A failure carrying business/policy semantics — quota exceeded, rate limited, authentication required, or access forbidden.
- KoelError
- Root of the sealed koel error union — the single typed failure model the SDK classifies every raw failure into (F-A5).
- ProtocolError
- A failure in the AG-UI protocol itself — a malformed payload, an unrecognized event, or a version drift the SDK cannot reconcile.
- TransportError
- A failure at the network/transport boundary — connection refused, timed out, TLS handshake failed, or the stream closed mid-flight.