Open-source memory engine for AI agentsОткрытый движок памяти для ИИ-агентов
Agent memory that keeps its receipts. Память агента, которая помнит, откуда знает.
Onfim stores what your agents learn together with the evidence behind each fact. Knowledge gets stronger when it is confirmed and used, fades when nobody needs it, and changes only when the change is confirmed. Every automatic step is a written rule with a test.
Onfim хранит то, что узнают ваши агенты, вместе с доказательством для каждого факта. Знание крепнет, когда его подтверждают и используют, угасает, когда оно никому не нужно, и меняется только после подтверждения. Каждый автоматический шаг записан правилом и проверен тестом.
Apache-2.0 Self-hostedСтавится у вас Postgres + pgvector MCP · REST EN · RU searchПоиск RU · EN
A Next.js redirect built from request.url points to localhost behind nginx. Build the address from the Host header.
Редирект Next.js через request.url за nginx уводит на localhost. Адрес собирать из заголовка Host.
after login the redirect lands on localhost:3002
после входа редирект уходит на localhost:3002
confirmed, same on staging
подтверждаю, на стенде так же
One recordОдна запись
A fact, the slot it fills, how strong it is and the quotes that back it. Nothing here was rewritten by a model.
Факт, слот, который он занимает, его сила и цитаты, на которых он держится. Модель здесь ничего не переписывала.
P1–P3principlesпринципы
Most agent memory can't tell you where a fact came from.Обычная память агента не может сказать, откуда она знает факт.
A typical memory layer is a vector store plus a model that rewrites what you save. Facts that look alike get merged, so three different quotes become one. Stale facts stay. Deletes are soft. The nightly job reports success when a stage failed. We built Onfim after running into each of these with our own agents.
Типичный слой памяти — векторная база и модель, которая переписывает сохранённое. Похожие факты сливаются, и три разные сметы становятся одной. Устаревшее остаётся. Удаление мягкое. Ночная задача сообщает об успехе, когда одна из стадий упала. Мы сделали Onfim, наступив на каждую из этих проблем с собственными агентами.
- P1
The service never rewrites what the client sent. There is no model on the write path: text, kind, slot and tags are stored as they came.
Сервис не переписывает то, что прислал клиент. На пути записи нет модели: текст, вид, слот и теги хранятся как пришли.
- P2
Every automatic action is a formula or a gate, written to the audit log and covered by a test. A model may only propose.
Каждое автоматическое действие — формула или ворота с записью в журнал и тестом. Модель может только предложить.
- P3
An old fact is replaced only by a confirmed new one. Anything disputed goes to a person, with quotes from both sides.
Старый факт заменяется только подтверждённым новым. Спорное уходит человеку с цитатами обеих сторон.
Evidence on every recordДоказательство у каждой записи
Each record carries at least one piece of evidence: source, speaker, date and a short quote. Answers and reports show the quotes, so an agent can say “per Anna, sales chat, Sept 22”.
У каждой записи есть хотя бы одно доказательство: источник, кто сказал, дата и короткая цитата. Ответы и отчёты показывают цитаты, и агент может сказать «со слов Анны, чат продаж, 22.09».
Knowledge strengthСила знания
Strength grows with independent confirmations and real use, and decays at the half-life of the record's kind. A recount never raises it. Decisions and conventions don't decay at all.
Сила растёт от независимых подтверждений и реального использования и затухает по полураспаду вида записи. Пересчёт никогда её не повышает. Решения и конвенции не затухают вовсе.
Replacement with confirmationЗамена с подтверждением
A slot names what a fact is about, like person:anna#role. A new fact in a taken slot waits as a candidate until it is confirmed. History stays, and any replacement can be reverted for 30 days.
Слот называет, о чём факт, например person:anna#role. Новый факт в занятом слоте ждёт претендентом, пока его не подтвердят. История остаётся, любую замену можно откатить в течение 30 дней.
Sleep cyclesЦиклы сна
Light sleep runs every night and is fully deterministic. Deep sleep runs weekly: a model looks for contradictions and stale facts and drafts summaries, and nothing it proposes applies without passing a gate.
Лёгкий сон идёт каждую ночь и полностью детерминирован. Глубокий — раз в неделю: модель ищет противоречия и устаревшее и готовит сводки, но её предложения применяются только через ворота.
Forgetting that actually forgetsЗабывание всерьёз
Weak records move to an archive you can restore from. Purge physically deletes the text, the vector and the links; the audit log keeps only the fact that it happened.
Слабые записи уходят в архив, откуда их можно вернуть. Purge физически удаляет текст, вектор и связи; в журнале остаётся только факт операции.
Ranking you can readРанжирование, которое можно прочитать
Hybrid search over local embeddings and Postgres full-text in English and Russian. The score is one fixed formula, and every term comes back with the result.
Гибридный поиск: локальные эмбеддинги и полнотекстовый поиск Postgres на русском и английском. Оценка — одна формула, и каждое слагаемое возвращается вместе с результатом.
statelifecycleжизненный цикл
A record's life, from remember to purge.Жизнь записи от remember до purge.
States change only through functions in one module, each writing the audit log in the same transaction. Three gates decide the automatic transitions.
Состояние меняется только функциями одного модуля, и каждая пишет журнал в той же транзакции. Автоматические переходы решают трое ворот.
Promote a candidateПродвинуть претендента
The candidate is newer and confirmed: by the owner, by two independent sources, or by the same person who said the original. Nothing new has come in for the old fact since.
Претендент новее и подтверждён: владельцем, двумя независимыми источниками или тем же человеком, который сказал исходное. С тех пор в пользу старого факта ничего нового не пришло.
Apply a summaryПрименить сводку
Every date, number and name in the summary appears in the sources, so “30.09” can't turn into “by October 1”. Decisions, conventions and facts about people are never folded into summaries.
Каждая дата, число и имя из сводки есть в источниках, и «30.09» не превратится в «до 1 октября». Решения, конвенции и факты о людях в сводки не сворачиваются.
Archive by strengthАрхив по силе
Strength is below 0.08, the record isn't pinned, nobody used it in the last 30 days, and it isn't part of an open dispute.
Сила ниже 0,08, запись не закреплена, её не использовали 30 дней и она не участвует в открытом споре.
sleepnightly · weeklyкаждую ночь · раз в неделю
Sleep that reports what it actually did.Сон, который честно отчитывается.
Run status is computed from stage errors: OK, PARTIAL or FAILED, with an alert to your webhook. Running a stage twice on the same data changes nothing, and a dry run returns the same counts without touching anything.
Статус прогона вычисляется из ошибок стадий: OK, PARTIAL или FAILED, с уведомлением на ваш вебхук. Повторный прогон на тех же данных ничего не меняет, а пробный прогон возвращает те же счётчики, ничего не трогая.
Light sleepЛёгкий сонevery night · no modelкаждую ночь · без модели
decayRecords strength after half-life decayФиксирует затухание силыpromoteRuns G1 for every candidateПроверяет претендентов воротами G1dedup_exactFolds exact duplicates; their evidence reinforces the originalСворачивает точные дубли, их доказательства подкрепляют оригиналforgetArchives by strength through G3Архивирует по силе через G3retentionApplies purge rulesПрименяет правила purgemaintenanceChecks data invariantsПроверяет инварианты данныхexportWrites a JSONL backup of each spaceПишет JSONL-копию каждого пространства
Deep sleepГлубокий сонweekly · your modelраз в неделю · ваша модель
contradictionsFinds facts that can't both be true and queues them with quotesИщет факты, которые не могут быть верны одновременно, и ставит их в очередь с цитатамиslot_suggestionsSuggests slots for records about the same attributeПредлагает слоты для записей об одном атрибутеstaleAsks a person whether a weak gotcha still holdsСпрашивает человека, жива ли ослабевшая грабляsummariesFolds old episodes into a summary, applied only through G2Сворачивает старые эпизоды в сводку, применяется только через G2reportWrites the cleanup reportПишет отчёт уборки
Works with any model behind an OpenAI- or Anthropic-compatible API, including one inside your own network. Without a model, deep sleep skips the model stages.
Подходит любая модель с API, совместимым с OpenAI или Anthropic, в том числе развёрнутая внутри вашей сети. Без модели глубокий сон пропускает её стадии.
# GET /v1/alice.work/sleep/latest deep sleep · 2026-10-04 · PARTIAL replaced 2 G1b same speaker archived 14 episode 11 · note 3 stale? 1 gotcha · strength 0.22 disputes 1 person:anna#role · 2 quotes summaries 3 applied · 1 rejected (G2a: date not in sources) stages contradictions: model timeout → PARTIAL
policy.resolveaccessдоступ
Built for teams, and for agents acting on someone's behalf.Для команд и для агентов, которые действуют от имени человека.
Memory in layersПамять слоями
Personal, team, department and organization layers, each a separate space with its own owner and grants. Search runs across the layers a person may see, nearest first. Sharing a personal fact with the team goes through the team's curator.
Личный слой, команда, отдел и организация, у каждого слоя своё пространство, владелец и гранты. Поиск идёт по слоям, которые человеку можно видеть, ближние выше. Личное попадает в командное только через куратора команды.
Classification levelsУровни конфиденциальности
Each record has a level. Filtering happens in SQL before ranking, so a record above your clearance never shows up in results, counts or explanations.
У каждой записи есть уровень. Фильтр работает в SQL до ранжирования, и запись выше вашего допуска не появляется ни в выдаче, ни в счётчиках, ни в объяснениях.
Agents act for a personАгент действует за человека
An agent works on behalf of a person and never sees more than that person. In a team chat it acts for the group, so personal layers are out of reach by design.
Агент работает от имени человека и никогда не видит больше, чем он. В командном чате агент действует от имени группы, и личные слои ему недоступны по построению.
Protection from memory poisoningЗащита от отравления памяти
Trust is computed from evidence. Rules from untrusted sources wait for the owner. Hidden text is stripped, keys and tokens are refused, and a forwarded message doesn't count as independent confirmation.
Доверие вычисляется из доказательств. Правила из недоверенных источников ждут владельца. Скрытый текст вырезается, ключи и токены отклоняются, а пересланное сообщение не считается независимым подтверждением.
Texts stay on your serverТексты остаются у вас
Embeddings run in-process on CPU (multilingual-e5-small, ONNX). Record texts leave the server only for deep sleep, only to the model you configure, and owner-only records never do.
Эмбеддинги считаются в процессе на CPU (multilingual-e5-small, ONNX). Тексты уходят с сервера только в глубокий сон, только в модель, которую вы указали, а записи «только для владельца» не уходят никогда.
Open format, your PostgresОткрытый формат, ваш Postgres
Everything lives in one Postgres with pgvector. Export any space to JSONL and import it back. If we disappear, your memory doesn't.
Всё лежит в одном Postgres с pgvector. Любое пространство выгружается в JSONL и загружается обратно. Если нас не станет, ваша память останется.
vshow it differsчем отличается
What changes compared with the usual setups.Что меняется по сравнению с привычными решениями.
| Vector storeВекторная база | Memory with model extractionПамять с извлечением моделью | Onfim | |
|---|---|---|---|
| What you saveЧто вы сохранили | Stored as isХранится как есть | Rewritten by a model on writeПереписывается моделью при записи | Stored as isХранится как есть |
| Where a fact came fromОткуда факт | Metadata, if you add itМетаданные, если вы их добавили | Often lost in extractionЧасто теряется при извлечении | Required evidence with quotes, shown in answersОбязательное доказательство с цитатой, видно в ответах |
| A fact changesФакт изменился | Another vector next to the old oneЕщё один вектор рядом со старым | Merged or appended by the modelМодель сливает или дописывает | Candidate, confirmation, history, revertПретендент, подтверждение, история, откат |
| Facts that look alikeПохожие факты | Close in vector spaceБлизки в пространстве векторов | May be merged into oneМогут слиться в один | Never merged; only exact duplicates foldНе сливаются; сворачиваются только точные дубли |
| ForgettingЗабывание | Manual deleteУдаление вручную | Rare; deletes are often softРедко; удаление часто мягкое | Archive by strength, real purgeАрхив по силе, настоящее удаление |
| Background jobФоновая задача | NoneНет | OpaqueНепрозрачна | Rules, gates and an honest reportПравила, ворота и честный отчёт |
:3120quick startбыстрый старт
From docker compose to the first recall.От docker compose до первого recall.
Onfim runs as one API process with a worker for sleep, next to Postgres 16 with pgvector. Agents connect over MCP (streamable HTTP) or REST with a bearer token.
Onfim — это один процесс API и обработчик сна рядом с Postgres 16 и pgvector. Агенты подключаются по MCP (streamable HTTP) или REST с токеном.
git clone https://github.com/datatim-hq/onfim cd onfim cp .env.example .env sed -i "s/change-me/$(openssl rand -hex 16)/" .env # database password docker compose up -d # API and MCP on 127.0.0.1:3120 docker compose exec api python -m mem.cli init \ --tenant acme --person alice --name "Alice" docker compose restart api # so MCP picks up the new space
init creates the organization, the first person and their personal space alice.work, and prints the agent token once. Save it. The Python package is called mem. Deep sleep needs a model key in .env; without one, Onfim runs everything except the model stages.
init создаёт организацию, первого человека и его личное пространство alice.work и один раз печатает токен агента. Сохраните его. Пакет Python называется mem. Для глубокого сна нужен ключ модели в .env; без него Onfim выполняет всё, кроме стадий модели.
claude mcp add --transport http onfim http://127.0.0.1:3120/mcp/alice.work/ \ --header "Authorization: Bearer $ONFIM_TOKEN"
Works the same in Claude Desktop, Cursor and any client that speaks MCP over streamable HTTP. The space comes from the path, the person from the token. Tool descriptions are in English; set MEM_MCP_LANG=ru for Russian.
Так же подключаются Claude Desktop, Cursor и любой клиент MCP по streamable HTTP. Пространство берётся из адреса, человек — из токена. Описания инструментов по умолчанию английские, MEM_MCP_LANG=ru включает русские.
rememberrecalladd_evidenceusedhelpfulhistoryconfirmpinreview_listreview_decidesleep_reportforgetstats# remember curl -s http://127.0.0.1:3120/v1/alice.work/memories \ -H "Authorization: Bearer $ONFIM_TOKEN" -H "Content-Type: application/json" \ -d '{"kind": "gotcha", "slot": "project:shop#redirects", "tags": ["project:shop"], "text": "Next.js redirect via request.url points to localhost behind nginx", "evidence": [{"source_ref": "claude-code:shop", "source_scope": "dev", "speaker": "agent", "observed_at": "2026-09-27T10:12:00Z", "quote": "after login the redirect lands on localhost:3002"}]}' # recall, with the score broken down curl -s http://127.0.0.1:3120/v1/alice.work/recall \ -H "Authorization: Bearer $ONFIM_TOKEN" -H "Content-Type: application/json" \ -d '{"query": "redirect goes to localhost", "tags": ["project:shop"], "explain": true}'
Preview of the 0.1 setup. Commands may change before the release. A record without evidence is refused with 400.
Предварительный вид установки 0.1. До выпуска команды могут измениться. Запись без доказательства сервис отклоняет с ошибкой 400.
0.1statusстатус
Where Onfim is today.Где Onfim сейчас.
- Late Oct 2026Конец октября 2026
Release 0.1Выпуск 0.1
Public repository, quick start, English docs and a concepts guide, CI on GitHub, a Docker image on GHCR. Design specs ship in
docs/designin Russian with English summaries.Публичный репозиторий, быстрый старт, документация на английском и описание понятий, CI на GitHub, образ Docker в GHCR. Проектные спецификации лежат в
docs/designна русском с кратким английским изложением. - After 0.1После 0.1
Driven by feedbackПо отзывам
OAuth sign-in for third-party MCP clients, Python and TypeScript clients, more team memory features. Contributions are welcome under the DCO, with no CLA.
Вход по OAuth для сторонних MCP-клиентов, клиенты на Python и TypeScript, новые возможности памяти команды. Вклады принимаем по DCO, без CLA.