sessions library

Session management, artifact storage, and long-term memory services.

Provides Session, State, BaseSessionService, InMemorySessionService, SqliteSessionService, BaseArtifactService, FileArtifactService, and BaseMemoryService.

import 'package:adk_dart/sessions.dart';

final sessionService = InMemorySessionService();

Classes

ArtifactVersion
Metadata describing one persisted artifact version.
BaseArtifactService
Base contract for artifact persistence services.
BaseMemoryService
Base contract for memory ingestion and search implementations.
BaseSessionService
Contract for session lifecycle and event persistence operations.
BufferedSessionService
A session service that writes events to another one in the background.
BufferedSessionServiceConfig
Configuration for BufferedSessionService.
DatabaseSessionService
Session service that dispatches to concrete implementations by URL scheme.
DynamicJson
Helpers for tolerant JSON encode/decode behavior.
FileArtifactService
File-system-backed artifact service for persisting session artifacts.
FileArtifactVersion
On-disk metadata model for a single version of a file-backed artifact.
GcsArtifactHttpRequest
Low-level HTTP request model used by GCS artifact operations.
GcsArtifactHttpResponse
Low-level HTTP response model used by GCS artifact operations.
GcsArtifactService
Artifact service implementation backed by Google Cloud Storage.
GetSessionConfig
Options for narrowing session retrieval results.
InMemoryArtifactService
Artifact service backed by process-local memory maps.
InMemoryMemoryService
Memory service backed by process-local event collections.
InMemoryMongoDbSessionClient
In-memory implementation of MongoDbSessionClient.
InMemoryMongoDbSessionCollection
In-memory implementation of MongoDbSessionCollection for testing and local use.
InMemoryMongoDbSessionDatabase
In-memory implementation of MongoDbSessionDatabase.
InMemorySessionService
Session service backed by process-local maps.
InMemoryVertexAiMemoryBankApiClient
In-memory Memory Bank API client used for tests.
InMemoryVertexAiRagClient
In-memory RAG client used for local testing.
ListSessionsResponse
Response model for session list operations.
MemoryEntry
One memory item with content and optional metadata.
MongoDbMemoryService
A MongoDB-backed memory service supporting keyword, vector, and auto-embedding retrieval.
MongoDbSessionClient
Client interface used by MongoDbSessionService.
MongoDbSessionCollection
Collection interface used by MongoDbSessionService.
MongoDbSessionDatabase
Database interface used by MongoDbSessionService.
MongoDbSessionService
Session storage service backed by MongoDB collections.
MongoDbUpdateResult
Result returned by MongoDbSessionCollection.updateOne.
ParsedArtifactUri
Parsed components of an artifact:// URI.
PreciseTimestamp
Utilities for preserving microsecond precision timestamps.
RsaPrivateKey
Pure-Dart RSA private key parsed from a PKCS#8 or PKCS#1 PEM string.
SearchMemoryResponse
Response model returned by memory search operations.
Session
A conversational session containing state and event history.
SessionKey
Identifies one session.
SessionStateDelta
Split representation of app, user, and session-scoped state entries.
SessionWriteBuffer
Buffers the writes of many sessions until the store has them.
SqliteMemoryService
A persistent memory service backed by SQLite with optional FTS5 search.
SqliteSessionService
Session service that stores sessions and events in SQLite.
State
Map-like state container with change tracking.
StorageAppStateV0
Application-level state row model for schema v0.
StorageEventV0
Event row model for schema v0.
StorageEventV1
Event row model for schema v1.
StorageMetadataV1
Key-value metadata row model for schema v1.
StorageSessionV0
Session row model for schema v0.
StorageSessionV1
Session row model for schema v1.
StorageUserStateV0
User-level state row model for schema v0.
VertexAiMemoryBankApiClient
Contract for Memory Bank API client implementations.
VertexAiMemoryBankHttpApiClient
HTTP implementation of VertexAiMemoryBankApiClient.
VertexAiMemoryBankProfileApiClient
Optional contract for Memory Bank API clients that retrieve profiles.
VertexAiMemoryBankService
Memory service that writes and retrieves memories via Vertex AI.
VertexAiMemoryProfile
Structured user profile returned by Vertex AI Memory Bank.
VertexAiRagClient
Client contract for interacting with a RAG backend.
VertexAiRagContext
One retrieval context returned from Vertex AI RAG.
VertexAiRagMemoryService
Memory service that stores sessions in a Vertex AI RAG corpus.
VertexAiRagRetrievalResponse
Retrieval result container for RAG contexts.
VertexAiRetrievedMemory
One memory row returned by Vertex AI retrieval APIs.
VertexAiSessionApiClient
API client interface for Vertex AI session operations.
VertexAiSessionHttpApiClient
HTTP client for Vertex AI session APIs.
VertexAiSessionService
Session service implementation backed by Vertex AI.
VertexRagStore
RAG store configuration used for retrieval queries.
VertexRagStoreRagResource
One RAG corpus resource reference.

Enums

GcsArtifactMode
Runtime mode for GcsArtifactService.

Constants

defaultMaxKeyLength → const int
Default max key length used by storage schemas.
defaultMaxVarcharLength → const int
Default max varchar length used by storage schemas.
defaultMemoriesCollection → const String
Default MongoDB collection name used by MongoDbMemoryService.
defaultMongoDbAutoEmbeddingModel → const String
Default Voyage AI model name used by MongoDbMemoryService in 'auto' mode.
defaultMongoDbEmbeddingDimensions → const int
Default embedding vector dimensions for defaultMongoDbEmbeddingModelName.
defaultMongoDbEmbeddingModelName → const String
Default Google embedding model name used by MongoDbMemoryService in 'vector' mode.
defaultMongoDbMemoryVectorIndexName → const String
Default Atlas Vector Search index name used by MongoDbMemoryService.
defaultStopWords → const Set<String>
Default English stop words filtered out during keyword extraction.
latestSchemaVersion → const String
The latest schema version supported by this migration implementation.
latestVersion → const String
Latest supported schema version.
maxArtifactReferenceDepth → const int
The maximum number of artifact:// references a single lookup may follow before giving up. Shared by every artifact service so that a self-referential or cyclic reference chain fails with a clear error instead of exhausting the stack.
maxUnreportedFailures → const int
How many sessions keep a failure to report before the oldest is forgotten.
mongoDbMemoryRetrievalModes → const Set<String>
Supported retrieval modes for MongoDbMemoryService.
schemaVersion0Pickle → const String
The legacy schema version that stores event payloads in pickled form.
schemaVersion1Json → const String
The schema version that stores event payloads as JSON structures.
schemaVersionKey → const String
The metadata key used to store session schema version values.

Properties

migrations → Map<String, (String, MigrationFunction)>
Registry of available schema migrations keyed by start version.
final
vertexAiAppendRetryDelayForTest ↔ Duration?
Optional test hook to override the 429 retry delay in VertexAiSessionService.appendEvent.
getter/setter pair

Functions

coerceBytesForJson(Object? value) → Object?
Recursively coerces raw Uint8List byte buffers into JSON-compatible strings (UTF-8 decoded when valid, or base64-encoded for binary bytes).
createMongoDbClientFromUrl(String dbUrl, {Map<String, Object?>? mongoClientKwargs}) → MongoDbSessionClient
Creates a MongoDbSessionClient from dbUrl using the active factory.
decodeEventData(Map<String, Object?> eventData, {String? id, String? invocationId, double? timestamp}) → Event
Decodes v1 event_data payload into runtime Event.
decodeModel<T>(Object? data, T fromJson(Map<String, Object?> json)) → T?
Decodes data into a model using fromJson.
encodeEventData(Event event) → Map<String, Object?>
Encodes runtime event into v1 event_data payload.
extractStateDelta(Map<String, Object?>? state) → SessionStateDelta
Splits a mixed state map into app, user, and session deltas.
formatTimestamp(num timestamp) → String
The ISO-8601 timestamp string converted from UNIX seconds timestamp.
generateGcsV4SignedUrl({required String bucketName, required String blobName, required String serviceAccountEmail, required GcsV4SignBytes signBytes, required Duration expiration, String method = 'GET', DateTime? now, String storageHost = 'storage.googleapis.com', String? contentType, Map<String, String>? headers, Map<String, String>? queryParameters}) → Future<String>
Generates a Google Cloud Storage V4 (GOOG4-RSA-SHA256) signed URL.
getArtifactUri(String appName, String userId, String filename, int version, {String? sessionId}) → String
Builds an artifact URI from the provided scope and version fields.
getDbSchemaVersion(String dbUrl) → Future<String>
The detected schema version for the database URL dbUrl.
getDbSchemaVersionFromConnection(SqliteMigrationDatabase db) → String
The detected schema version from an open SQLite db connection.
getDbSchemaVersionFromDecoded(Object? decoded) → String
The detected schema version from decoded session store decoded data.
getInMemoryMongoDbIndexOptions(MongoDbSessionCollection collection) → Map<String, Map<String, Object?>>
Returns index options (such as expireAfterSeconds) recorded on collection in memory.
getInMemoryMongoDbSearchIndexes(MongoDbSessionCollection collection) → List<Map<String, Object?>>
Returns the search indexes registered on collection in memory.
isArtifactRef(Part artifact) → bool
Whether artifact references an artifact:// file URI.
isRewindTombstone(Part artifact) → bool
Whether artifact is the tombstone part saved by session rewind.
makeJsonSafeState(Map<String, Object?>? state) → Map<String, Object?>
Returns a copy of state with all values normalized via makeJsonSafeValue.
makeJsonSafeValue(Object? value) → Object?
Recursively converts value into a JSON-serializable structure.
migrateFromSqlalchemyPickle(String sourceDbUrl, String destDbUrl) → Future<void>
Migrates a legacy SQLAlchemy-pickle session database into the v1 schema.
migrateFromSqlalchemySqlite(String sourceDbUrl, String destDbPath) → Future<void>
Migrates a SQLAlchemy-backed SQLite DB into ADK SQLite format.
parseArtifactUri(String uri) → ParsedArtifactUri?
Parses uri into a ParsedArtifactUri when it matches known formats.
resetMongoDbSessionClientFactory() → void
Restores the default MongoDbSessionClient factory.
resolveArtifactReference({required String fileUri, required String appName, required String userId, required String? sessionId, required int remainingDepth}) → ParsedArtifactUri
Validates an artifact reference URI before following it.
resolveDbPath(String dbUrl) → String
The filesystem path resolved from dbUrl when it targets SQLite.
setInMemoryMongoDbSearchIndexes(MongoDbSessionCollection collection, List<Map<String, Object?>> indexes) → void
Seeds the search indexes registered on collection in memory.
setMongoDbSessionClientFactory(MongoDbSessionClientFactory factory) → void
Overrides the factory used when MongoDbSessionService is created from dbUrl.
toSyncUrl(String dbUrl) → String
The synchronous-driver variant of dbUrl.
trimTempState(Map<String, Object?>? state) → Map<String, Object?>
Returns state without transient temp: entries.
upgrade(String sourceDbUrl, String destDbUrl, {bool allowUnsafeUnpickling = false}) → Future<void>
Upgrades sourceDbUrl schema into destDbUrl using migration steps.
validateArtifactReferenceScope({required String appName, required String userId, required String? sessionId, required ParsedArtifactUri parsedUri}) → void
Ensures artifact references cannot escape the caller's scope.
validatePathSegment(String value, String fieldName) → void
Rejects values that could alter the constructed path.
validateSessionIdForFlatStorage(String sessionId) → void
Validates a sessionId used by flat storage artifact backends.

Typedefs

DatabaseSessionServiceFactory = BaseSessionService Function(String dbUrl)
Factory signature for creating session services from database URLs.
DatabaseSessionServiceResolver = BaseSessionService? Function(String dbUrl)
Resolver signature for dynamically resolving custom session services.
GcsArtifactAuthHeadersProvider = Future<Map<String, String>> Function()
Function that returns auth headers for GCS requests.
GcsArtifactHttpRequestProvider = Future<GcsArtifactHttpResponse> Function(GcsArtifactHttpRequest request)
Function that executes one GCS HTTP request.
GcsSignedUrlGenerator = Future<String> Function({required String blobName, required String bucketName, required Duration expiration, Map<String, Object?>? extraOptions, required String method, String? signingVersion})
Function that generates a signed URL for a GCS object.
GcsV4SignBytes = Future<List<int>> Function(List<int> data)
Callback that signs a raw UTF-8 stringToSign payload with RSA-SHA256.
MigrationFunction = Future<void> Function(String sourceDbUrl, String destDbUrl)
Migration function signature for source/destination DB URLs.
MongoDbSessionClientFactory = MongoDbSessionClient Function(String dbUrl, {Map<String, Object?>? mongoClientKwargs})
Factory signature for constructing a MongoDbSessionClient from a MongoDB URI.
PersistFn = Future<Object?> Function(Session storeSession, List<Event> events)
Writes events, in order and all or none, through a store session.
VertexAiMemoryBankAccessTokenProvider = Future<String?> Function()
Access-token provider used by HTTP Memory Bank clients.
VertexAiMemoryBankApiClientFactory = VertexAiMemoryBankApiClient Function({String? apiKey, Object? httpOptions, String? location, String? project})
Factory signature for creating Memory Bank API clients.
VertexAiMemoryBankUriBuilder = Uri Function({required String agentEngineId, required String? apiKey, required String apiVersion, required String? location, required String operation, required String? project})
URI builder used by HTTP Memory Bank clients.
VertexAiRagClientFactory = VertexAiRagClient Function({String? location, String? project})
Factory that constructs a VertexAiRagClient for a given GCP project and location.
VertexAiSessionAccessTokenProvider = Future<String?> Function()
Access-token provider signature for Vertex session API calls.
VertexAiSessionApiClientFactory = VertexAiSessionApiClient Function({String? apiKey, String? location, String? project})
Factory signature for creating VertexAiSessionApiClient instances.
VertexAiSessionUriBuilder = Uri Function({required String? apiKey, required String apiVersion, required String? location, required String operation, required String? project, required String reasoningEngineId, required String? sessionId})
URI builder signature for Vertex session API operations.

Exceptions / Errors

MongoDbDuplicateKeyException
Exception thrown when inserting a document with a duplicate _id.
MongoDbOperationFailure
Exception representing a MongoDB server operation failure with an error code.
SessionPersistenceError
Raised when buffered session writes could not be persisted.
StateSchemaError
Exception thrown when a state key or value violates a declared state schema.