SemanticMemoryMiddleware

org.llm4s.agent.harness.memory.SemanticMemoryMiddleware
See theSemanticMemoryMiddleware companion object
@Experimental
final class SemanticMemoryMiddleware(stores: Option[TenantId] => Result[MemoryStore], manager: (MemoryStore, LLMClient) => MemoryManager, client: LLMClient, val recall: Option[MemoryRecall], val record: Option[MemoryRecording], val consolidate: Option[MemoryConsolidation], val bounds: MemoryBounds, clock: Clock, val id: MiddlewareId, val maxTenants: Int, release: MemoryStore => Unit) extends AgentMiddleware, AutoCloseable

Long-term semantic memory for an agent (design ยง4.31): before each turn it recalls what earlier threads of the same tenant recorded and shows it to the model; after the turn it records the exchange, and, when consolidate is set, replaces groups of old memories with a summary.

  • Tenant scope. stores is asked once per tenant (RunContext.config.tenantId) for that tenant's store; the store is held in one cell per tenant, whose writes are serialised. Every thread of a tenant shares it; no two tenants may share a store (refused): not one instance, nor two instances with one storageIdentity - one SQLite file, however its path is spelled, or one Postgres table and tenant (#3032). A store that names no identity is told apart by instance only, so a resolver that opens one shared backend twice must scope it to the tenant itself. A failed resolution is asked again on the next turn.
  • The manager is built for each hook call by manager(view, context.accounted(client)), over a view of the tenant's store whose writes are the middleware's effects, so every model call it makes is counted in the thread's usage.
  • Recall (beforeAgent) runs getRelevantContext on the turn's input, cuts it to maxRecallTokens * 4 characters and stores it in SemanticMemoryMiddleware.RecalledKey; every model step of the turn shows it as the prompt section semantic-memory. A resolution or configuration failure refuses the input before any model call; a failed search is skipped, announced by MemoryEvents.Skipped.
  • Recalled text is data. Memories are earlier users' input and model answers, shared by every thread of the tenant, so the section fences them as llm4s-prompt's Untrusted text under a heading that says they are never instructions (#3033): escaped, so no memory can close the fence, and, from llm4s-memory's managers, one line per memory, so none can forge a heading. Fencing reduces prompt injection; it does not prevent it.
  • Recording (afterAgent) records the turn's query and answer through the manager as one replayable effect (memory.record, C4): on a org.llm4s.agent.memory.TransactionalMemoryStore a replay after a crash returns the recorded outcome and never writes twice; on any other store a replay of a write that may have run is refused. Each memory is cut to maxRecordChars.
  • Consolidation (afterAgent, after recording) runs the manager's consolidateMemories on memories older than olderThan; each group it replaces is one effect (memory.consolidate, keyed by the group's ids). It needs a transactional store: on any other, the input is refused. A summary carries its sources' writer, and one longer than maxRecordChars is refused, never cut, so its sources are kept (#3035).
  • Bounds. Every memory the middleware writes carries SemanticMemoryMiddleware.WriterKey set to its id, and bounds counts only those: every write evicts, in its own transaction, the middleware's own memories of lowest importance, oldest first, beyond bounds, so what it records stays bounded whether or not consolidation is on. A memory it did not write - knowledge an application loaded, facts it stored - is never counted or evicted (#3034).
  • Failures after the answer are skipped and announced by MemoryEvents.Skipped: the answer is never retracted because memory could not be written. A crash is replayed by recover from C4's records.

It runs outside guardrail middleware, so that a blocked answer is never recorded: afterAgent runs in reverse stack order, and a guardrail's block stops the others. In one agent's stack that is arranged, wherever the two were registered (runsBefore: every GuardrailMiddleware and GuardrailReviewMiddleware, if there is one). Across a handoff family it cannot be arranged, so build() refuses it on a handoff target when the root agent has one (placement), since the root's afterAgent runs after every agent's own. An effect that applied stays applied: a Block restores thread state, not the store.

The key is registered only by an agent family with a SemanticMemoryMiddleware: adding one to an existing agent changes its graph's structure.

Value parameters

bounds

the most of the middleware's own memories each tenant's store keeps; any owner it has is replaced by the middleware's (SemanticMemoryMiddleware.WriterKey, id)

client

the client the manager calls a model with; every call is accounted to the run

clock

where consolidation reads "now" from

consolidate

when to consolidate old memories after a turn; None never

id

this middleware's id

manager

builds the manager over a store and a client, e.g. LLMMemoryManager(config, _, _)

maxTenants

how many tenants' stores are held open at once (#3040): past it, the least recently used one that no turn is using is released (release) and resolved again on its tenant's next turn. Only a durable store (a SQLite file, a Postgres table) is evicted; one whose memories die with it, such as an InMemoryStore or an in-memory SQLite database, is kept

recall

what to recall before a turn; None recalls nothing

record

how to record a turn; None records nothing

release

what releasing a tenant's store does, when it is evicted or the middleware is closed; by default it closes a store that is AutoCloseable (the SQLite and Postgres stores), which the resolver made for it Resources: close releases every tenant's store, and refuses later turns.

stores

the store of each tenant (None for runs without one): a store scoped to that tenant

Attributes

Companion
object
Source
SemanticMemoryMiddleware.scala
Graph
Supertypes
class Object
trait Matchable
class Any

Members list

Value members

Concrete methods

override def afterAgent(answer: String, context: ModelContext): Result[BoundaryResult]

Sees the run's final answer: returns it, possibly changed, with an update to this middleware's writes. A Left blocks the turn, removing it; block blocks it as an outcome, AgentStatus.Blocked.

Sees the run's final answer: returns it, possibly changed, with an update to this middleware's writes. A Left blocks the turn, removing it; block blocks it as an outcome, AgentStatus.Blocked.

Attributes

Definition Classes
Source
SemanticMemoryMiddleware.scala
override def beforeAgent(input: String, context: ModelContext): Result[BoundaryResult]

Sees the run's input, as admitted, before anything else of the turn runs: returns it, possibly changed, with an update to this middleware's writes that the turn's first model call sees. A Left blocks the turn; block blocks it as an outcome, AgentStatus.Blocked. The query it is given is already in the turn's first checkpoint: to keep text out of the store, rewrite or refuse it in admit. On a handoff target it also runs at the handoff (#3312), after the target's admit stages, on the turn's stored query and before the target's first model call; its update commits with the handoff, and a question it asks suspends the run with the handoff stored.

Sees the run's input, as admitted, before anything else of the turn runs: returns it, possibly changed, with an update to this middleware's writes that the turn's first model call sees. A Left blocks the turn; block blocks it as an outcome, AgentStatus.Blocked. The query it is given is already in the turn's first checkpoint: to keep text out of the store, rewrite or refuse it in admit. On a handoff target it also runs at the handoff (#3312), after the target's admit stages, on the turn's stored query and before the target's first model call; its update commits with the handoff, and a question it asks suspends the run with the handoff stored.

Attributes

Definition Classes
Source
SemanticMemoryMiddleware.scala
override def close(): Unit

Releases every tenant's store (release), at once for those no turn is using and as its last turn ends for the others, and refuses every later turn. Idempotent.

Releases every tenant's store (release), at once for those no turn is using and as its last turn ends for the others, and refuses every later turn. Idempotent.

Attributes

Definition Classes
Source
SemanticMemoryMiddleware.scala

How many tenants' stores are open.

How many tenants' stores are open.

Attributes

Source
SemanticMemoryMiddleware.scala
override def placement(other: AgentMiddleware): Option[Placement]

Outside guardrail middleware, at the boundary, so a blocked answer is never recorded; see the class's Scaladoc.

Outside guardrail middleware, at the boundary, so a blocked answer is never recorded; see the class's Scaladoc.

Attributes

Definition Classes
Source
SemanticMemoryMiddleware.scala

Content for the system prompt of each model request: collected before every model step from the committed state, in stack order, and never stored. Each middleware bounds its own; the agent bounds them all together (maxPromptSectionTokens). Left fails the run.

Content for the system prompt of each model request: collected before every model step from the committed state, in stack order, and never stored. Each middleware bounds its own; the agent bounds them all together (maxPromptSectionTokens). Left fails the run.

Attributes

Definition Classes
Source
SemanticMemoryMiddleware.scala
override def runsBefore: Set[MiddlewareRef]

Outside the guardrail middleware of its stack, when there is any, whatever ids they were given (#2795).

Outside the guardrail middleware of its stack, when there is any, whatever ids they were given (#2795).

Attributes

Definition Classes
Source
SemanticMemoryMiddleware.scala
def withStore[A](tenant: Option[TenantId])(f: MemoryStore => Result[A]): Result[A]

f on tenant's store as the middleware's last write left it, resolving it if no run of the tenant has yet. f runs under the tenant's lock, so it never overlaps a turn's read or write of the store: read through this, not through a reference kept from the resolver, while runs may be active.

f on tenant's store as the middleware's last write left it, resolving it if no run of the tenant has yet. f runs under the tenant's lock, so it never overlaps a turn's read or write of the store: read through this, not through a reference kept from the resolver, while runs may be active.

Attributes

Source
SemanticMemoryMiddleware.scala
override def writes: Set[StateKey[_, _]]

The state keys this middleware's hooks may write: an update from beforeAgent, wrapModelCall or afterAgent, or one wrapToolCall adds to a Success. A hook's write to any other key fails the run.

The state keys this middleware's hooks may write: an update from beforeAgent, wrapModelCall or afterAgent, or one wrapToolCall adds to a Success. A hook's write to any other key fails the run.

Attributes

Definition Classes
Source
SemanticMemoryMiddleware.scala

Inherited methods

def admit(query: String, context: AdmissionContext): Result[String]

Admits the turn's query before anything of the turn is stored (#2854): returns it, possibly rewritten, or refuses it. Each middleware's stage runs in stack order on the query the one before returned, and all of them before any beforeAgent.

Admits the turn's query before anything of the turn is stored (#2854): returns it, possibly rewritten, or refuses it. Each middleware's stage runs in stack order on the query the one before returned, and all of them before any beforeAgent.

  • Right(query) admits the turn with that text: it is what the turn's first checkpoint, its run queue entry and every later hook hold, and the query as submitted is stored nowhere. Redact here, not in beforeAgent.
  • block refuses it: the turn ends AgentStatus.Blocked(id, reason), and nothing of the query is stored - the blocked run records which middleware refused, and its GuardrailBlocked event, and no text.
  • any other Left refuses to start the turn: agent.run returns it as its Left, the thread unchanged and no run started. A blank query returned is refused the same way.

It decides and rewrites, and nothing else: it has no thread state to read, returns no update, cannot ask a question (a middleware that asks from here is refused) and has no tool to call; its context offers only the turn's identity and a way to count a model call. Run before the turn is stored, it runs once for the turn, however often the turn's input step runs afterwards - a recover or a resume runs beforeAgent again, never this - and its verdict is final: a later change of mind is beforeAgent's.

It runs before the thread is claimed, so a turn the runtime then refuses (ThreadBusy, PendingInterrupts, ...) has had its stages run, and a model call one of them made is counted in no thread's usage.

It runs before the query is stored whenever the turn starts through Agent.run, start or stream, and when a queue's submitter calls Agent.admit first. A turn that is stored before the agent sees it - a query put on a run queue as it is, a delegated child's task - runs the stage as the first thing of its input step instead: the verdict is the same, but that query was already stored by whoever stored it, and the stage runs again if that step does (a recover of a step that failed).

Attributes

Inherited from:
AgentMiddleware
Source
AgentMiddleware.scala

Whether this middleware's afterAgent can block or rewrite the final answer (#3231). With streaming (withStreaming()), the answer is then not sent to listeners as the model writes it: the text of a model call that makes no tool call is held, and the answer is sent as one TextDelta, as stored, once every afterAgent of the agent (and, for a handoff target, of the root) has passed it; a blocked answer is never sent. Text the model writes beside a tool call is sent when the call returns. false by default, so a middleware whose afterAgent only reads the answer leaves streaming live; GuardrailMiddleware and GuardrailReviewMiddleware are true when they have output guardrails, and a middleware whose afterAgent blocks or rewrites should override it too.

Whether this middleware's afterAgent can block or rewrite the final answer (#3231). With streaming (withStreaming()), the answer is then not sent to listeners as the model writes it: the text of a model call that makes no tool call is held, and the answer is sent as one TextDelta, as stored, once every afterAgent of the agent (and, for a handoff target, of the root) has passed it; a blocked answer is never sent. Text the model writes beside a tool call is sent when the call returns. false by default, so a middleware whose afterAgent only reads the answer leaves streaming live; GuardrailMiddleware and GuardrailReviewMiddleware are true when they have output guardrails, and a middleware whose afterAgent blocks or rewrites should override it too.

Attributes

Inherited from:
AgentMiddleware
Source
AgentMiddleware.scala

Middleware this one must run inside of (be wrapped by), named and arranged as runsBefore's are.

Middleware this one must run inside of (be wrapped by), named and arranged as runsBefore's are.

Attributes

Inherited from:
AgentMiddleware
Source
AgentMiddleware.scala

Tools this middleware contributes; they join the loop's tool set and are validated like any other.

Tools this middleware contributes; they join the loop's tool set and are validated like any other.

Attributes

Inherited from:
AgentMiddleware
Source
AgentMiddleware.scala

Wraps one model call. A wrapper may rewrite the request (inject a note, filter tools), call next more than once (retry, fallback), transform its response, add an update to its writes (ModelResponse.addUpdate), or return Left, which fails the run. Only an AgentMiddleware.Asking wrapper suspends, by asking its question. Every call next makes is counted in the thread's usage, whichever response the wrapper returns.

Wraps one model call. A wrapper may rewrite the request (inject a note, filter tools), call next more than once (retry, fallback), transform its response, add an update to its writes (ModelResponse.addUpdate), or return Left, which fails the run. Only an AgentMiddleware.Asking wrapper suspends, by asking its question. Every call next makes is counted in the thread's usage, whichever response the wrapper returns.

Filtering ModelRequest.tools shapes what the model is offered and is not a permission control: a tool the model calls anyway still runs through wrapToolCall, where denial belongs.

Attributes

Inherited from:
AgentMiddleware
Source
AgentMiddleware.scala
def wrapToolCall(request: ToolCallRequest, context: ToolContext)(next: () => ToolOutcome): ToolOutcome

Wraps one tool call, after its arguments were validated. A wrapper denies with ToolOutcome.Error("Denied: ..."), asks for approval with NeedsApproval(reason) (unless context.approved), fails the run with Fatal - its Left: the run fails with GraphError.ToolFailed - and short-circuits by not calling next. It may call next more than once (retry) and transform the outcome next returns, adding an update to its writes with ToolOutcome.addUpdate. next takes no request: the call is read-only.

Wraps one tool call, after its arguments were validated. A wrapper denies with ToolOutcome.Error("Denied: ..."), asks for approval with NeedsApproval(reason) (unless context.approved), fails the run with Fatal - its Left: the run fails with GraphError.ToolFailed - and short-circuits by not calling next. It may call next more than once (retry) and transform the outcome next returns, adding an update to its writes with ToolOutcome.addUpdate. next takes no request: the call is read-only.

Attributes

Inherited from:
AgentMiddleware
Source
AgentMiddleware.scala

Concrete fields

This middleware's identifier, unique in its stack; must match [a-zA-Z0-9_-]{1,64}.

This middleware's identifier, unique in its stack; must match [a-zA-Z0-9_-]{1,64}.

Attributes

Source
SemanticMemoryMiddleware.scala