agentic_core library

Foundation layer of the agentic framework.

agentic_core holds the vocabulary every other package speaks: messages and content parts, JSON Schema, the error hierarchy, cancellation, resilience policies, the event bus, structured logging and tracing, the plugin registry and the run context.

It is pure Dart with two dependencies — meta and collection — and no knowledge of any provider, transport or UI framework. Everything here is either an immutable value object or a port that adapters implement, which is what lets a Flutter app, a server and a CLI share the same domain model.

import 'package:agentic_core/agentic_core.dart';

final context = AgenticContext.root(
  logger: StructuredLogger(level: LogLevel.debug),
  events: BroadcastEventBus(),
);

final history = <Message>[
  Message.system('You are a helpful assistant.'),
  Message.user('What is the capital of France?'),
];

Most applications depend on agentic_flutter instead, which re-exports this library along with the agent, workflow and provider packages. Depend on agentic_core directly when writing a plugin: a tool, a provider or a store should never pull in the whole framework.

Classes

AgenticContext
Carries the identity, services and lifetime of one run.
AgenticEvent
A fact that has already happened.
AgenticLogger
Emits log records.
AudioPart
Recorded audio, optionally with a transcript.
BackoffStrategy
Computes the wait before a given retry attempt.
BroadcastEventBus
The default EventBus: a broadcast stream with bounded replay.
CancellationToken
A read-only view of a cancellation signal.
CancellationTokenSource
Owns a CancellationToken and the right to cancel it.
CircuitBreaker
Trips after repeated failures and fails fast until the dependency recovers.
Clock
A source of the current time and of delays.
ConsoleLogSink
Writes records to the console through a caller-supplied print function.
ConstantBackoff
Waits the same delay before every attempt.
ContentPart
One element of a message's content.
Disposable
An object that owns resources which must be released explicitly.
DisposableBag
Disposes a group of objects as a unit, in reverse registration order.
Err<T>
A failed Result holding error.
EventBus
Delivers events to interested subscribers.
ExponentialBackoff
Doubles the delay on every attempt, capped at maximum.
FilePart
A document such as a PDF or a spreadsheet.
FixedScheduleBackoff
Replays a fixed list of delays, then repeats the last one.
GenericEvent
An event carrying an arbitrary payload under a caller-chosen type.
HumanWaitLedger
Accumulates the time a run spent blocked on a person.
IdGenerator
Mints identifiers.
ImagePart
An image.
InMemoryLogSink
Buffers records in memory.
InMemorySpanExporter
Retains spans in memory.
JsonSchema
An immutable JSON Schema node.
LinearBackoff
Grows the delay linearly: initial * attempt.
LogRecord
One immutable log entry.
LogSink
Receives log records.
MediaPart
Binary or remote content referenced by a message.
Message
One turn in a conversation.
MultiLogSink
Fans records out to several sinks.
NoopEventBus
An EventBus that accepts events and delivers nothing.
NoopLogger
A logger that discards everything.
NoopSpanExporter
Discards every span.
Ok<T>
A successful Result holding value.
ReasoningPart
The model's intermediate reasoning.
Registry<T extends Object>
A named collection of implementations of T.
Result<T>
The outcome of a computation that either produced a T or failed.
RetryPolicy
Re-runs a transient failure according to a schedule and a budget.
SchemaValidationResult
The outcome of validating a value against a schema.
SchemaViolation
One reason a value failed validation.
SequentialIdGenerator
Produces predictable identifiers of the form <prefix><n>.
Span
A unit of work being timed.
SpanData
An immutable snapshot of a finished span.
SpanEvent
A timestamped point of interest inside a span.
SpanExporter
Receives finished spans.
StructuredLogger
The default AgenticLogger: filters by level, binds fields, writes to a LogSink.
SystemClock
The production Clock, backed by the platform clock and dart:async.
TextPart
Plain text.
TokenUsage
Tokens consumed by one or more model calls.
ToolCallPart
The model's request to invoke a tool.
ToolResultPart
The outcome of a tool invocation, returned to the model.
TraceContext
Identifies a span and the trace it belongs to.
Tracer
Creates spans.
Ulid
Generates ULIDs: 48 bits of timestamp followed by 80 bits of randomness, rendered as 26 characters of Crockford base-32.
UntrustedContentLedger
Records the untrusted content a run has taken in.

Enums

CircuitState
The three states of a CircuitBreaker.
Jitter
How randomness is applied to a computed backoff delay.
JsonSchemaType
The JSON Schema primitive types the framework supports.
LogLevel
Severity of a log record, ordered from most to least verbose.
MessageRole
Who produced a message.
SpanKind
What kind of work a span represents.
SpanStatus
Outcome recorded on a finished span.

Extensions

AgenticLoggerLevels on AgenticLogger
Level-specific shorthands shared by every AgenticLogger.
ClockOperations on Clock
Time-derived helpers that every Clock gets for free.
ConversationHistory on List<Message>
Operations over a conversation history.
EventBusOperations on EventBus
Convenience subscriptions available on every EventBus.
JsonMapReader on JsonMap
Checked field access for a JsonMap.
NullableCancellationToken on CancellationToken?
Convenience checks on a possibly-absent token.
PrefixedIds on IdGenerator
Attaches a human-readable namespace to a generated identifier.
ResultFuture on Future<T>
Bridges a throwing Future into a Result.
TokenUsageAggregation on Iterable<TokenUsage>
Summing helpers for collections of usage records.

Constants

sensitiveFieldMarkers → const Set<String>
Field keys whose values are masked by redactSensitiveFields.

Functions

applyJitter(Duration delay, Jitter jitter, Duration previousDelay, Random random) Duration
Applies jitter to delay.
pruneNulls(JsonMap json) JsonMap
Returns a copy of json with every null-valued entry removed.
redactSensitiveFields(String key, Object? value) Object?
Masks values whose key looks like a credential.
withResource<T extends Disposable, R>(T resource, FutureOr<R> body(T resource)) Future<R>
Runs body with resource and disposes it afterwards, even on failure.

Typedefs

CancellationSubscription = void Function()
Removes a previously registered cancellation callback.
FieldRedactor = Object? Function(String key, Object? value)
Rewrites a field value before it is emitted.
JsonDecode<T> = T Function(JsonMap json)
Reconstructs a domain object from its wire representation.
JsonEncode<T> = JsonMap Function(T value)
Converts a domain object into its wire representation.
JsonList = List<Object?>
A decoded JSON array.
JsonMap = Map<String, Object?>
A decoded JSON object.
RegistryFactory<T> = T Function()
Lazily constructs a registered value.
RetryListener = void Function(AgenticException error, int attempt, Duration delay)
Notified before each wait, for logging and metrics.
RetryPredicate = bool Function(AgenticException error, int attempt)
Decides whether a particular failure should be retried.
Sampler = bool Function(String spanName)
Decides whether a trace is recorded.

Exceptions / Errors

AgenticException
Base class for every error raised by the framework.
AgenticTimeoutException
An operation exceeded its time budget.
AuthenticationException
Credentials were missing, malformed, expired or rejected.
CancelledException
The operation was cancelled through a CancellationToken.
CapabilityNotSupportedException
A requested capability is not supported by the selected implementation.
CircuitOpenException
Thrown when a request is rejected because the circuit is open.
ConfigurationException
The framework was assembled incorrectly.
InvalidStateException
An operation was attempted against an object in the wrong lifecycle state.
NotFoundException
A named resource could not be found.
PermissionDeniedException
The caller is authenticated but not permitted to perform the operation.
ProviderException
An upstream provider returned an error.
QuotaExceededException
A hard quota was exhausted — billing, not throttling.
RateLimitException
The provider signalled that the caller is sending requests too quickly.
SerializationException
A payload could not be decoded into the shape its contract promised.
StorageException
A persistence adapter failed.
ToolExecutionException
A tool threw while executing.
UnexpectedException
Wraps an error that escaped from outside the framework.
ValidationException
Input failed validation before any work was attempted.