Unified public API for the AgentOS memory system.

One Memory instance manages the full lifecycle of an agent's memories: storing, retrieving, ingesting documents, building a knowledge graph, self-improving through consolidation, and importing/exporting data.

Quick start

const mem = await Memory.create({ store: 'sqlite', path: './brain.sqlite' });

await mem.remember('The user prefers dark mode');
const results = await mem.recall('dark mode preference');
console.log(results[0].trace.content);

await mem.close();

Accessors

Methods

  • Open a Memory backed by PostgreSQL. Requires the pg npm package.

    Parameters

    • connectionString: string

      Standard Postgres connection URL.

    • opts: Omit<MemoryConfig, "path" | "store"> & {
          brainId: string;
          poolSize?: number;
      }

      Plus standard Memory options (graph, selfImprove, decay, embeddings).

    Returns Promise<Memory>

  • Open a Memory with a pre-resolved StorageAdapter. Use when sharing an adapter across subsystems or when you need full control over adapter resolution.

    Parameters

    • adapter: StorageAdapter
    • opts: Omit<MemoryConfig, "path" | "store"> & {
          brainId?: string;
      } = {}

    Returns Promise<Memory>

  • Store a new memory trace.

    Creates a trace in the memory_traces table with a unique ID, content hash for deduplication, and optional type/scope/tags metadata. If the memory graph is available the trace is also added as a graph node.

    Parameters

    • content: string

      The text content to remember.

    • Optional options: RememberOptions

      Optional metadata (type, scope, tags, importance, etc.).

    Returns Promise<MemoryTrace>

    The created MemoryTrace-like object.

  • Search for memory traces matching a natural-language query.

    Uses FTS5 full-text search with the Porter tokenizer, ranked by strength * abs(fts_rank). With the HNSW index active and an embedder, the vector index's candidates and the full-text ones are fused by reciprocal rank. The filters bind both halves: a trace of another type, scope or scope id, weaker than minStrength or outside after and before is never returned, however near its vector.

    Parameters

    • query: string

      Natural-language search query.

    • Optional options: RecallOptions

      Optional filters (limit, type, scope, scopeId, minStrength, after, before).

    Returns Promise<ScoredTrace[]>

    Ranked array of ScoredTrace results.

  • Soft-delete a memory trace by setting deleted = 1.

    The trace remains in the database for audit/recovery purposes but is excluded from all recall queries and health reports. Its knowledge-graph copy goes (deleteGraphCopies), so its words do not stay in the graph.

    Parameters

    • traceId: string

      The ID of the trace to forget.

    Returns Promise<void>

  • Deletes the knowledge-graph copies of the given traces and leaves the traces: the episodic record a memory manager on this facade's Brain writes of each trace it stores (SqlKnowledgeGraph.recordMemory). A soft delete calls it (forget, and the memory tools' memory_delete and memory_merge), so a deleted trace's words do not stay in the graph; a trace a revert brings back needs no copy, since no recall reads one. Best-effort: a graph that cannot be reached leaves its copies, which a later delete by trace id or by scope finds.

    Parameters

    • traceIds: readonly string[]

    Returns Promise<number>

    How many copies it deleted.

  • Deletes every trace of one scope for good: the rows, their memory-graph nodes and knowledge-graph copies, and the full-text index entries. With turnUserId, only the scope's traces whose metadata names that user, as the second user a memory write on another user's session records, or among the contributors of a summary the rolling-summary sink filed. Account deletion calls it.

    It reads the rows by their scope_id column, after filing the brain's rows that hold '' there while their metadata names a scope id: a release older than the column writes those, to a Brain this facade holds open too.

    Parameters

    • scope: string
    • scopeId: string
    • options: {
          turnUserId?: string;
      } = {}
      • Optional turnUserId?: string

    Returns Promise<{
        deleted: number;
    }>

    Throws

    TypeError when scopeId is empty, so a caller's missing id never deletes every trace filed under no scope id, or when turnUserId is given and is not a non-empty string.

    Throws

    When the knowledge graph cannot delete the copies: of the traces, before any row is deleted; of the scope, once the traces are deleted, so a second call finds the copies alone.

  • Deletes the given traces for good, as deleteScope does for a scope. The rows that name a trace go first, as the Brain's foreign keys require: its retrieval_feedback rows are deleted, and a document_chunks row it was filed from lets go of it and keeps its text. Each trace's memory-graph node goes with its edges, whichever facade on the Brain wrote them, a relation a host made to the node (addRelation) included. Each trace's knowledge-graph copy goes before its row. Unknown ids are skipped.

    Parameters

    • traceIds: readonly string[]

    Returns Promise<{
        deleted: number;
    }>

    How many trace rows it deleted, so a call made again counts none.

    Throws

    When the knowledge graph cannot delete the copies: no row is deleted, so a later call deletes them.

  • Brings one trace back to the state a snapshot holds (readTraceSnapshot): its content, tags, scope and metadata, live again. A ledger revert of a memory tool's update, delete or merge calls it with the before-state its row recorded; a revert of an add calls forget. The full-text index then matches the restored words: SQLite rebuilds its index, and Postgres re-indexes the restored row alone.

    A snapshot read before the Brain was re-filed in the encoded scope-id form (ensureEncodedScopeIds) is written under the encoded id, as the re-file wrote the row: once the Brain holds the record, the plain form of an id that holds a / names a namespaced user (team/ana is user ana of namespace team), so the trace stays the plain user's. On Postgres the restore reads the record under the lock a re-file takes, so a re-file another process makes meanwhile comes before or after it.

    Parameters

    Returns Promise<void>

    Throws

    When the snapshot is of another trace.

  • Re-files this facade's Brain in the encoded form a learning layer reads, once per Brain (refileBrainScopeIds); every live MemoryStore on the Brain in this process then moves what it holds of the traces the re-file moved. The layer calls it when it is first handed the facade.

    Returns Promise<number>

    How many traces it moved: none when the Brain held the record already.

  • List traces created strictly after sinceMs (Unix-ms). Newest-first by default; pass order: 'asc' for oldest-first (used by the wiki compiler to drain the window in chronological batches).

    Unlike recall, this performs no FTS match — it is a time-window scan, used by the wiki compiler to fold recent activity into pages.

    Parameters

    • sinceMs: number

      Exclusive lower bound on created_at (Unix ms). Use 0 for "all".

    • Optional options: {
          limit?: number;
          scope?: string;
          order?: "asc" | "desc";
      }

      Optional scope filter, result cap (default 200), and sort order.

      • Optional limit?: number
      • Optional scope?: string
      • Optional order?: "asc" | "desc"

    Returns Promise<MemoryTrace[]>

  • Attach a markdown wiki store + compiler. Called by the agent at boot once the memory/ workspace directory is known. Idempotent (last call wins).

    Parameters

    • wiki: {
          store: {
              index: ((o?) => Promise<unknown>);
              readMetaWatermark: (() => Promise<null | string>);
              writeMetaWatermark: ((iso) => Promise<void>);
          };
          compiler: {
              compile: ((input) => Promise<WikiCompileResult>);
          };
      }
      • store: {
            index: ((o?) => Promise<unknown>);
            readMetaWatermark: (() => Promise<null | string>);
            writeMetaWatermark: ((iso) => Promise<void>);
        }
        • index: ((o?) => Promise<unknown>)
            • (o?): Promise<unknown>
            • Parameters

              • Optional o: {
                    force?: boolean;
                }
                • Optional force?: boolean

              Returns Promise<unknown>

        • readMetaWatermark: (() => Promise<null | string>)
            • (): Promise<null | string>
            • Returns Promise<null | string>

        • writeMetaWatermark: ((iso) => Promise<void>)
            • (iso): Promise<void>
            • Parameters

              • iso: string

              Returns Promise<void>

      • compiler: {
            compile: ((input) => Promise<WikiCompileResult>);
        }

    Returns void

  • Compile recent (non-wiki) traces into the markdown wiki, then re-index. Reads the wiki's watermark, folds every trace created since into pages, and advances the watermark. No-op when no wiki is attached. A batch whose compile rejects, such as on a page write that fails for want of disk space or permission, leaves the watermark where it was, so the next compile starts from that batch again.

    Parameters

    • Optional opts: {
          reason?: "consolidation" | "session-end" | "explicit";
      }
      • Optional reason?: "consolidation" | "session-end" | "explicit"

        What triggered this compile (telemetry + compiler hint).

    Returns Promise<WikiCompileResult>

  • Ingest documents from a file, directory, or URL.

    Workflow:

    1. Detect source type (file, directory, or URL).
    2. Load document(s) using the appropriate loader.
    3. Chunk each document using the configured strategy.
    4. For each chunk: insert into document_chunks, create a memory trace.
    5. Record the document in the documents table.

    Parameters

    • source: string

      File path, directory path, or URL.

    • Optional options: IngestOptions

      Optional ingestion settings (recursive, include/exclude globs).

    Returns Promise<IngestResult>

    Summary of the ingestion run.

  • Record retrieval feedback for a memory trace.

    The feedback is persisted asynchronously. This method returns a Promise that resolves once the feedback has been written.

    Parameters

    • traceId: string

      The ID of the trace being evaluated.

    • signal: "used" | "ignored"

      Whether the trace was 'used' or 'ignored' by the LLM.

    • Optional query: string

      Optional retrieval context, typically the original user query.

    Returns Promise<void>

  • Detect and persist used/ignored feedback for a batch of injected traces based on the assistant's final response text.

    This is the high-level bridge used by long-term-memory integrations that already know which traces were injected into the prompt.

    Parameters

    • injectedTraces: MemoryTrace[]
    • response: string
    • Optional query: string

    Returns Promise<RetrievalFeedback[]>

  • Export the memory store to a file or directory.

    Format is detected from options.format or the file extension:

    • .json -> JSON
    • .sqlite / .db -> a new SQLite file holding this brain's own rows
    • directory path -> Markdown or Obsidian (based on options.format)

    A SQLite export writes this brain's rows of every portable table, from a SQLite or a Postgres brain; another brain in the same database is left out. Nothing may exist at outputPath yet.

    A Markdown or Obsidian export writes one file per trace, in folders named after the trace's scope and type, and leaves out a trace whose scope, type or id is not a safe file or folder name, whose place in the export folder holds a link, symbolic or hard, or anything but a regular file, or whose file would be an older trace's, where names ignore case or by the file system's own reckoning; the result lists each one left out. No file is written outside the export folder.

    Parameters

    • outputPath: string

      Path to write the export to.

    • Optional options: ExportOptions

      Optional format and content controls.

    Returns Promise<ExportResult>

    The traces the export left out, with the reason for each.

  • Import memory data from a file or directory.

    Format is detected from options.format, the file extension, or by inspecting the content.

    A SQLite source is read one brain at a time: a file whose rows carry several brain ids imports nothing, and errors names the ids.

    Parameters

    • source: string

      Path to the import source (file or directory).

    • Optional options: ImportOptions

      Optional format hint and dedup settings.

    Returns Promise<ImportResult>

    Summary of the import operation.

  • Import memory data from a string without filesystem access.

    Supports JSON and CSV formats. Useful in browser environments or when the data is already in memory.

    Parameters

    • content: string

      The raw string content to import.

    • format: "json" | "csv"

      The format of the content: 'json' or 'csv'.

    • Optional options: Pick<ImportOptions, "dedup">

      Optional deduplication controls.

    Returns Promise<ImportResult>

    Summary of the import operation.

  • Export the full brain state as a JSON string without filesystem access.

    Useful in browser environments or when the data needs to be sent over a network connection.

    Parameters

    • Optional options: ExportOptions

      Optional export configuration (embeddings, conversations).

    Returns Promise<string>

    Pretty-printed JSON string of the full brain payload.

  • Create runtime ITool instances backed by this memory facade's SQLite brain.

    This is the supported bridge from the standalone memory engine into AgentOS tool registration. The returned tools share this Memory instance's underlying SQLite database and consolidation loop.

    Typical usage:

    for (const tool of memory.createTools()) {
    await agentos.getToolOrchestrator().registerTool(tool);
    }

    Where a learning layer puts a turn's scope ids on a call, the tools file and read under them and record each write in the layer's ledger, and memory_reflect refuses (withdrawn); a host that registers the tools itself leaves memory_reflect out (includeReflect: false).

    When self-improvement is disabled, memory_reflect is omitted because there is no backing ConsolidationLoop instance.

    Parameters

    • Optional options: {
          includeReflect?: boolean;
      }
      • Optional includeReflect?: boolean

    Returns ITool<any, any>[]

  • Close the Memory instance and release all resources.

    Flushes the SQLite WAL and releases the file lock. Must be called when the agent shuts down.

    Returns Promise<void>