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 *_CHUNKSTART/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 the patches; the empty/invalid-op rejection is the verify stage's job (Story 2.11 / Addendum F.1), so an empty patch decodes to an empty patches list here.
ActivitySnapshotEvent
ACTIVITY_SNAPSHOT — a frontend-only structured-UI element (progress bar, checklist, …) keyed by messageId and activityType. Activity content never reaches the agent; it is rendered by the consumer surface (Epic 6/7).
AddOp
RFC 6902 add: inserts value at path — replacing an existing object member, inserting into an array (shifting later elements), appending when the final token is -, or replacing the whole document when path is "".
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 AbstractAgent emits.
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 apply pipeline 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 apply pipeline 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 at from and adds it at path. from must exist.
CustomEvent
CUSTOM — a provider- or consumer-declared extension event: a named value outside koel's typed families, carried by the protocol as a first-class shape (AG-UI CustomEvent = name + value).
DefaultChatStateReducer
The default ChatStateReducer — folds the canonical AG-UI stream (the post-chunks, post-verify events) 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:io or package:http (koel_core is the six-platform kernel — web has no dart: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 what koel_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 in koel_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_DELTA carries (StateDeltaEvent.patches: List<JsonPatchOp>, Story 2.6) and JsonPatch.apply folds 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.incomingPatches verbatim onto StateConflict.localState via JsonPatch.apply — no merge against the snapshot. (snapshotState exists 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, replacing ChatState.messages wholesale (Story 2.12). messages consumes the Story-2.1 Message leaf type and delegates element (de)serialization to its own codec, so every field — including DateTime and the optional toolCallId/name — round-trips without information loss.
MoveOp
RFC 6902 move: removes the value at from and adds it at path. from must exist and must not be a proper prefix of path (a location cannot be moved into one of its own children).
RawEvent
RAW — an opaque passthrough event whose payload koel 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 by entityId (echoed back via RunAgentInput.reasoningEcho in a later run, accumulated by the reducer in Story 2.12) and subtype ("tool-call" or "message", kept a permissive String).
ReasoningEndEvent
REASONING_END — closes the reasoning span identified by messageId.
ReasoningMessageChunkEvent
REASONING_MESSAGE_CHUNK — the convenience wire shape (all fields optional) the chunks pipeline stage (Story 2.11) expands into ReasoningMessageStartEventReasoningMessageContentEventReasoningMessageEndEvent using messageId+delta. Story 2.7 ships only the typed value; the expansion is Story 2.11. Unlike TEXT_MESSAGE_CHUNK, the reasoning chunk carries no role.
ReasoningMessageContentEvent
REASONING_MESSAGE_CONTENT — one streamed delta of the reasoning message identified by messageId. The consumer concatenates deltas in order.
ReasoningMessageEndEvent
REASONING_MESSAGE_END — closes the streamed reasoning message identified by messageId.
ReasoningMessageStartEvent
REASONING_MESSAGE_START — opens a streamed reasoning message. The canonical long form: ReasoningMessageContentEvent deltas follow, closed by ReasoningMessageEndEvent, all sharing messageId.
ReasoningStartEvent
REASONING_START — opens a reasoning (chain-of-thought) span identified by messageId, closed by ReasoningEndEvent. The reasoning message stream (ReasoningMessageStartEvent→…→ReasoningMessageEndEvent) lives between them.
RemoveOp
RFC 6902 remove: deletes the value at path. The target must exist.
ReplaceOp
RFC 6902 replace: sets the value at path to value. Equivalent to a remove followed by an add; 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_DELTA whose incomingPatches touch a path the consumer mutated locally since the last STATE_SNAPSHOT (F-A8).
StateConflictResolver
The F-A8 resolution policy: given a detected StateConflict, returns the state map the next ChatState.state should 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 via JsonPatch.apply. This event only transports the patches; the empty-patches and invalid-op rejection is the verify stage's job (Story 2.11 / Addendum F.1), so an empty delta decodes to an empty patches list here.
StateSnapshotEvent
STATE_SNAPSHOT — a full replacement of the shared agent state (cold start or resync). The reducer (Story 2.12) replaces ChatState.state wholesale with state.
StepFinishedEvent
STEP_FINISHED — the agent left the named step. Its stepName must 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 at path is deeply equal to value. A mismatch (or a missing path) fails the entire patch.
TextMessageChunkEvent
TEXT_MESSAGE_CHUNK — the convenience wire shape (all fields optional) the chunks pipeline stage (Story 2.11) expands into TextMessageStartEventTextMessageContentEventTextMessageEndEvent using messageId+role+delta. Story 2.5 ships only the typed value; the expansion and the "must carry messageId" verify rule (Addendum F.1) are Story 2.11.
TextMessageContentEvent
TEXT_MESSAGE_CONTENT — one streamed delta of the message identified by messageId. The reducer concatenates deltas in order (Story 2.12).
TextMessageEndEvent
TEXT_MESSAGE_END — closes the streamed message identified by messageId.
TextMessageStartEvent
TEXT_MESSAGE_START — opens a streamed assistant message. The canonical long form: TextMessageContentEvent deltas follow, closed by TextMessageEndEvent, all sharing messageId.
ToolCall
An in-flight tool invocation accumulated by the reducer — the element type of ChatState.pendingToolCalls.
ToolCallArgsEvent
TOOL_CALL_ARGS — one streamed delta of the tool-call arguments for toolCallId. The argument deltas are JSON fragments; concatenate them in order to reconstruct the complete arguments JSON string (the chunks/reducer stages own that assembly, not this event).
ToolCallChunkEvent
TOOL_CALL_CHUNK — the convenience wire shape (all fields optional) the chunks pipeline stage (Story 2.11) expands into ToolCallStartEventToolCallArgsEventToolCallEndEvent using toolCallId+toolCallName+parentMessageId+delta per Addendum F.2. Story 2.6 ships only the typed value; the expansion and the "must carry toolCallId" verify rule (Addendum F.1) are Story 2.11.
ToolCallEndEvent
TOOL_CALL_END — closes the streamed tool call identified by toolCallId.
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 a role: "tool" Message on the next run). content is the result payload as a string; messageId identifies the result message and toolCallId links 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 sharing toolCallId.
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 type the current koel_core event 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 *_CHUNK convenience shapes into the canonical STARTCONTENT/ARGSEND triplets every downstream stage and consumer expects (Addendum F.2). Runs before verifyStage because verify checks the START/END pairing 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.