rath.memory#
Memory backends, store handles, memory operations, typed results, registry helpers, and local/OpenViking adapter boundaries.
Memory is a runtime plane beside sandbox execution: agents can read and write durable knowledge without coupling memory backends to tool backends.#
Source#
Module |
Source |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Public contract#
Store lifecycle#
API |
Behavior |
|---|---|
|
Opens a store handle with |
|
Adds or drops one reference; final release calls |
|
Applies a |
|
Reads |
Operations and results#
Operation |
Purpose |
Typical result |
|---|---|---|
|
Write or replace text at a |
|
|
Read one entry at abstract/overview/detail level. |
|
|
List entries under a URI. |
|
|
Semantic or lexical search. |
|
|
Intent-aware search when a backend supports it. |
|
|
Ingest a file, directory, or URL resource. |
Backend-specific result or |
|
Archive a session and extract durable memory. |
|
Registry#
Function |
Behavior |
|---|---|
|
Decorator that registers a |
|
Returns registered memory backend names. |
|
Returns a backend instance or registered class. |
|
Checks registration plus backend availability. |
|
Returns the first available backend instance. |
|
Sets and gets the default backend. The base install defaults to |
Built-in adapters#
Backend |
Availability |
Notes |
|---|---|---|
|
Ships with base |
Persists under |
|
Optional |
Connects to OpenViking and maps public |
Agent integration#
flow.Agent(memory=...) accepts a MemoryStore, MemoryStoreSpec, a configured backend/preset string such as "local", or None.
Agent API |
Behavior |
|---|---|
|
Writes explicit memory content. |
|
Searches attached memory and returns hits. |
|
Commits a session transcript for archive and extraction. |
|
Injects recalled memory into the prompt path. |
|
Best-effort commit after each agent forward call. |
URI boundary#
OpenRath exposes memory://... as the public user-facing URI scheme. Adapter-specific schemes such as OpenViking’s internal viking://... stay inside the adapter and should not appear in portable OpenRath workflows.
Autodoc#
- class rath.memory.MemoryBackend[source]#
Abstract base class for memory backends.
Subclasses must:
Set the
nameclass attribute and register viarath.memory.register().Implement the classmethods
is_available,capabilitiesandsupported_ops.Implement the instance methods
store_count,open,closeanddispatch.
- abstractmethod classmethod is_available() bool[source]#
Return whether this backend is usable in the current environment.
Must be cheap (microseconds, no network, no subprocess). Examples: check that a required SDK is importable, or that a config file or environment variable is present.
- abstractmethod classmethod capabilities() MemoryCapabilities[source]#
Return the static capability description of this backend type.
- abstractmethod classmethod supported_ops() frozenset[type[MemoryOp]][source]#
Return
MemoryOpsubclasses this backend handles.
- abstractmethod store_count() int[source]#
Return the number of open memory stores managed by this instance.
- abstractmethod open(spec: MemoryStoreSpec | None = None) MemoryStore[source]#
Open a fresh memory store and return its handle.
- abstractmethod close(store: MemoryStore) None[source]#
Close
storeand release resources.Calling close on an already-closed store is a no-op.
- abstractmethod dispatch(store: MemoryStore, op: MemoryOp) MemoryResult[source]#
Execute
opagainststoreand return its result.Implementations should raise
UnsupportedMemoryOpfor op types not insupported_ops().
- class rath.memory.MemoryStore(backend: MemoryBackend, handle: str, spec: MemoryStoreSpec | None = None, closed: bool = False, _refcount: int = 0)[source]#
Memory store handle with reference counting.
Lifecycle mirrors
BackendSandbox: eachAgentslot, eachwith store:block, and any explicitacquire()counts as one reference.release()decrements and, when the count reaches zero, callsbackend.close(self). There is no “force close” path — callers that want immediate teardown must drop all references.MemoryBackend.open()returns a store with_refcount == 0. The caller is expected to either bind it to anAgent(which acquires) or enterwith store:(which acquires) before it can be safely held.- acquire() MemoryStore[source]#
Add one reference; return
selffor chaining.
- dispatch(op: MemoryOp) MemoryResult[source]#
Apply
opthroughMemoryBackend.dispatch().
- class rath.memory.MemoryStoreSpec(namespace: str | None = None, account_id: str | None = None, user_id: str | None = None, agent_id: str | None = None, options: Mapping[str, Any] | None = None)[source]#
User-facing description of a memory store to open.
All fields are optional; backends may ignore fields that do not apply (e.g. an embedded backend ignores
account_id/user_id).- classmethod from_config(name: str | None = None, *, store: ConfigStore | None = None, **overrides: Any) MemoryStoreSpec[source]#
Build a
MemoryStoreSpecfrom~/.openrath/config.json.Looks up
name(ormemory.default_providerwhenname=None) undermemory.providers. Only local presets are modeled in config today; OpenViking stores should be built explicitly viaMemoryStoreSpeckwargs /options.Lazy-imports
rath.configsoimport rath.memorynever touches the filesystem.Raises
KeyErrorwhen the named provider is missing.
- class rath.memory.MemoryCapabilities(scope_model: ScopeModel, supports_write: bool, supports_read: bool, supports_list: bool, supports_tree: bool, supports_vector_search: bool, supports_intent_search: bool, supports_resource_ingest: bool, supports_session_commit: bool, supports_l0_l1_l2: bool)[source]#
Static, class-level capability description for a memory backend.
- class rath.memory.MemoryOp[source]#
Marker root for memory-plane op payloads.
Concrete subclasses are frozen dataclasses. The marker exists so backends can declare
supported_ops()and so the registry can refuse unknown subtypes.
- class rath.memory.MemoryOpWrite(uri: str, content: str, mode: str = 'replace', wait: bool = False, timeout_seconds: float | None = None, metadata: Mapping[str, str] | None = None)[source]#
Update an existing memory entry at
uriwith free-form text content.OpenViking’s
writesemantics are an update of an existing memory file (created bycommit_sessionextraction or seeded viaMemoryOpResource); it is not a generic create-file path.
- class rath.memory.MemoryOpRead(uri: str, level: Literal['abstract', 'overview', 'detail'] = 'detail', encoding: str | None = 'utf-8')[source]#
Read the entry at
uriat the requested hierarchical level.
- class rath.memory.MemoryOpTree(uri: str, depth: int = 2)[source]#
Recursively list entries under
uriup todepthlevels.
- class rath.memory.MemoryOpFind(query: str, target_uri: str | None = None, top_k: int = 8)[source]#
Direct semantic search;
target_uriscopes the search namespace.
- class rath.memory.MemoryOpSearch(query: str, session_id: str | None = None, target_uri: str | None = None, top_k: int = 8)[source]#
Intent-aware search;
session_idscopes ranking against a session.
- class rath.memory.MemoryOpResource(source: str, target_uri: str | None = None, reason: str = '', instruction: str = '', wait: bool = True, timeout_seconds: float | None = None)[source]#
Register an external resource (URL / file / dir) for ingestion.
target_uriis the destination directory undermemory://resources/.
- class rath.memory.MemoryOpCommit(session_id: str, messages: ~collections.abc.Sequence[~typing.Any], used_uris: ~collections.abc.Sequence[str] = <factory>, wait: bool = False, timeout_seconds: float | None = None)[source]#
Commit a session’s messages for archive + memory extraction.
Each entry in
messagesis a{"role": ..., "content": ...}dict (or{"role": ..., "parts": [...]}for multipart messages).
- class rath.memory.MemoryHit(uri: str, score: float, snippet: str | None = None, level: Literal['abstract', 'overview', 'detail'] | None = None)[source]#
One ranked hit returned by
MemoryFindResult.
- class rath.memory.MemoryEntry(name: str, uri: str, is_dir: bool, size: int | None = None)[source]#
A single entry inside
MemoryListResult.
- class rath.memory.MemoryFindResult(hits: tuple[MemoryHit, ...])[source]#
Result of
MemoryOpFind/MemoryOpSearch.
- class rath.memory.MemoryReadResult(uri: str, data: str | bytes, level: Literal['abstract', 'overview', 'detail'])[source]#
Result of
MemoryOpRead.dataisstrwhen the op carried anencodingand the backend decoded the bytes;byteswhenencoding=None.
- class rath.memory.MemoryListResult(entries: tuple[MemoryEntry, ...])[source]#
Result of
MemoryOpList/MemoryOpTree.
- class rath.memory.MemoryWriteResult(uri: str, bytes_written: int)[source]#
Result of
MemoryOpWrite.
- class rath.memory.MemoryCommitResult(task_id: str | None, archived_uri: str | None, extracted_count: int)[source]#
Result of
MemoryOpCommit.extracted_countis-1when the backend cannot report the count (e.g.wait=Falseasync extraction).
- class rath.memory.MemoryExecutionFailure(kind: Literal['not_found', 'unsupported', 'transport', 'extraction_failed', 'store_closed', 'unauthorized', 'timeout', 'invalid_uri', 'internal'], message: str, detail: str | None = None)[source]#
Structured failure surface for memory dispatch.
kindmust be one of_KNOWN_FAILURE_KINDS; adapters route unexpected exceptions throughkind="internal".
- rath.memory.register(name: str) Callable[[type[B]], type[B]][source]#
Decorator: register a
MemoryBackendsubclass undername.
- rath.memory.list_names() list[str][source]#
Return the names of all registered memory backends, in registration order.
- rath.memory.get(name: str) MemoryBackend[source]#
Look up a memory backend by name and return a fresh instance.
- rath.memory.get_class(name: str) type[MemoryBackend][source]#
Look up the registered class for
namewithout instantiating it.
- rath.memory.is_available(name: str) bool[source]#
Return
Trueiff a memory backend namednameis registered and available.
- rath.memory.preferred(names: list[str]) MemoryBackend[source]#
Return an instance of the first available memory backend in
names.Raises
MemoryBackendNotFoundif none of the listed backends are registered and available.
- rath.memory.current() MemoryBackend[source]#
Return a fresh instance of the default memory backend.
Raises
MemoryBackendNotFoundif no default has been set.
- exception rath.memory.MemoryBackendNotFound(name: str, available: list[str])[source]#
Raised when a memory backend is requested by name but isn’t registered.
- exception rath.memory.MemoryStoreClosed(handle: str)[source]#
Raised when an op is dispatched against an already-closed
MemoryStore.
- exception rath.memory.UnsupportedMemoryOp(op_type: type['MemoryOp'], backend_name: str)[source]#
Raised when a memory backend cannot service a given
MemoryOptype.
- exception rath.memory.MemoryNotFound(uri: str)[source]#
Raised when an explicit URI is read but the backend has no such entry.