Skip to main content

OACS: Open Agent Context Standard

CI PyPI Python License: Apache 2.0

Portable, governed memory and context for AI agents.

English | Русский | Documentation / Документация | Changelog

EN

OACS defines how agents store memory, retrieve evidence, and assemble context with explicit permissions and an audit trail. This repository contains the OACS v1.0 standard and its Python reference implementation: the oacs package and acs CLI, backed by SQLite with a FastAPI interface.

Use it to preserve project knowledge between sessions, build explainable context capsules, and attach tool results as evidence. OACS complements MCP: MCP connects tools and servers; OACS governs the memory and context an agent uses around those calls. It is not an agent framework, model provider, or vault.

Standard vs Reference Implementation

Layer What lives here
Portable standard Memory lifecycle, context capsules, capability grants, evidence, audit semantics, and JSON schemas.
Python reference implementation CLI, HTTP API, SQLite storage, encryption, lexical retrieval, and context prompt rendering.
Supported reference adapters Codex integration, CLI/API, SQLite storage, context rendering, and lifecycle helpers. These do not expand the standard.
Examples and validation Tool, skill, MCP, repository-workflow, and benchmark fixtures.

Start with the specification and compatibility policy when implementing OACS in another runtime. The standard version and Python package release version are separate; see releases for package changes.

Quickstart

Requires Python 3.11 or later. No model server or API key is needed. The commands below use a POSIX shell; on Windows, activate the virtual environment and set environment variables using your shell's syntax.

python3 -m venv .venv
source .venv/bin/activate
python -m pip install oacs

export OACS_DB=./.oacs/oacs.db
acs init --json
acs key init --json

CANDIDATE_ID=$(acs memory propose --type procedure --depth 2 --scope project \
  --text "In project Alpha reports are generated with make report-safe." --json \
  | python -c 'import json,sys; print(json.load(sys.stdin)["id"])')
acs memory commit "$CANDIDATE_ID" --json
acs memory query --query "Alpha report" --scope project --json
acs context build --intent answer_project_question --query "Alpha report" \
  --scope project --budget 4000 --json

Expected result: the query finds the committed procedure, and the ctx_... capsule includes its memory reference. --intent describes the task category; --query supplies retrieval text. The reference budget limits selected memory lines, not the total tokens of a later model request.

For an exact package version and more detail, use the PyPI quickstart. For editable installation and checks, see Contributing.

Supported Codex integration

OACS includes a supported Codex reference adapter. It is packaged with OACS, not maintained as an example Skill:

acs integrations codex install
acs integrations codex status
acs integrations codex doctor

The installer manages the user-scoped oacs and proof-loop Skills, a small global policy block, and lifecycle hooks without storing persistent memory inside either Skill. The proof loop adds acceptance criteria, evidence-backed delivery, and fresh verification without creating a parallel task store. See Codex integration and consumer packs.

Core concepts

  • MemoryRecord: scoped memory with lifecycle, depth, encrypted content, and evidence. D0-D2 records and D3-D5 hypotheses have different evidence rules.
  • ContextCapsule: portable context selected for a task, with permissions, evidence references, and forbidden assumptions.
  • CapabilityGrant: actor permissions constrained by operation, scope, namespace, and memory depth.
  • EvidenceRef: provenance for observations and decisions. Tool results enter capsule evidence through included memories that reference them.
  • ProtectedRef: a reference to an external secret or protected value; plaintext and vault state remain outside OACS.
  • memory_calls: auditable memory operation traces, not final model answers.

Try the local demo

From a source checkout:

python examples/killer_demo/run_demo.py --out .oacs/killer-demo

The demo writes a memory, builds and exports a capsule, checks the export, records memory operations, imports MCP metadata, and verifies the audit chain. It runs offline without LM Studio or a model. Read the generated SUMMARY.md and summary.json; see the demo guide.

Documentation

Goal Guide
Understand memory and context Memory model, capsules, memory loop
Pass context to a model Context prompting
Integrate tools and services API, tools, MCP, skills
Use OACS during repository work Agent workflow, consumer packs, dogfood
Evaluate the implementation Conformance, benchmarks
Develop or release Contributing, build, release, roadmap

The documentation index covers all guides and reference material.

Security and limits

Memory and sensitive capsule payloads are encrypted at rest. The default local key provider, local_unlocked, stores key material beside the local database; encryption does not protect against someone who can read both. Keep .oacs/ private and out of version control. Passphrase wrapping is available.

Local setup uses development bootstrap permissions. Use OACS_POLICY_MODE=strict with explicit grants when bootstrap access is not appropriate. Read Security and the external vault boundary before handling sensitive data.

This is a local reference implementation, not a hosted multi-tenant service. Retrieval is deterministic and lexical by default; embeddings and model execution are optional adapters. Benchmark results describe specific fixtures and models, not a general performance guarantee. Post-quantum key wrapping is an optional integration, not a default security claim.

RU

OACS определяет, как агенты сохраняют память, находят подтверждающие данные и собирают контекст с явными разрешениями и журналом аудита. Репозиторий содержит стандарт OACS v1.0 и эталонную реализацию на Python: пакет oacs, CLI acs, хранилище SQLite и интерфейс FastAPI.

OACS помогает сохранять знания о проекте между сессиями, объяснять состав контекста и связывать результаты инструментов с доказательствами. MCP отвечает за связь инструментов и серверов, OACS управляет памятью и контекстом вокруг этих вызовов. Это не агентский фреймворк, поставщик моделей или хранилище секретов.

Стандарт и эталонная реализация

Уровень Содержимое
Переносимый стандарт Жизненный цикл памяти, капсулы контекста, разрешения, доказательства, семантика аудита и схемы JSON.
Реализация на Python CLI, HTTP API, SQLite, шифрование, лексический поиск и подготовка контекста для модели.
Поддерживаемые эталонные адаптеры Интеграция Codex, CLI/API, SQLite, подготовка контекста и lifecycle helpers. Они не расширяют стандарт.
Примеры и проверка Fixtures инструментов, Skill, MCP, работы с репозиторием и измерений.

Для реализации OACS в другой среде начните со спецификации и политики совместимости. Версия стандарта и версия пакета Python различаются; изменения пакета указаны в релизах.

Быстрый старт

Нужен Python 3.11 или новее. Сервер модели и ключ API не требуются. Команды рассчитаны на POSIX shell. В Windows используйте синтаксис своей оболочки для активации окружения и переменных среды.

python3 -m venv .venv
source .venv/bin/activate
python -m pip install oacs

export OACS_DB=./.oacs/oacs.db
acs init --json
acs key init --json

CANDIDATE_ID=$(acs memory propose --type procedure --depth 2 --scope project \
  --text "В проекте Alpha отчёты генерируются через make report-safe." --json \
  | python -c 'import json,sys; print(json.load(sys.stdin)["id"])')
acs memory commit "$CANDIDATE_ID" --json
acs memory query --query "Alpha отчёты" --scope project --json
acs context build --intent answer_project_question --query "Alpha отчёты" \
  --scope project --budget 4000 --json

Запрос должен найти сохранённую процедуру, а капсула ctx_... включить ссылку на неё. --intent задаёт категорию задачи, --query передаёт текст поиска. Бюджет ограничивает выбранные строки памяти, а не весь будущий запрос к модели.

Установка конкретной версии описана в руководстве PyPI. Установка из исходников и проверки: участие в разработке.

Поддерживаемая интеграция Codex

OACS включает поддерживаемый reference adapter Codex. Он входит в пакет OACS и не поддерживается как пример Skill:

acs integrations codex install
acs integrations codex status
acs integrations codex doctor

Установщик управляет пользовательскими Skills oacs и proof-loop, небольшим global policy block и lifecycle hooks, не помещая persistent memory внутрь Skills. Proof loop добавляет критерии приемки, доказательное выполнение и свежую проверку без параллельного хранилища задач. Подробнее: интеграция Codex и consumer packs.

Основные понятия

  • MemoryRecord: память с областью действия, жизненным циклом, глубиной, зашифрованным содержимым и доказательствами. Для D0-D2 и гипотез D3-D5 действуют разные правила использования доказательств.
  • ContextCapsule: контекст задачи с разрешениями, ссылками на доказательства и запрещёнными предположениями.
  • CapabilityGrant: разрешения участника по операциям, области действия, пространству имён и глубине памяти.
  • EvidenceRef: происхождение наблюдений и решений. Результаты инструментов попадают в доказательства капсулы через включённые записи памяти со ссылками на эти результаты.
  • ProtectedRef: ссылка на внешний секрет или защищённое значение без переноса открытого содержимого и состояния хранилища в OACS.
  • memory_calls: журнал операций с памятью, а не готовые ответы модели.

Локальная демонстрация

После установки из исходников:

python examples/killer_demo/run_demo.py --out .oacs/killer-demo

Пример сохраняет память, собирает и экспортирует капсулу, проверяет экспорт, записывает операции памяти, импортирует метаданные MCP и проверяет цепочку аудита. Он работает без сети, LM Studio и модели. Результат находится в SUMMARY.md и summary.json; подробнее в руководстве.

Документация

Задача Руководство
Разобраться в памяти и контексте Модель памяти, капсулы, цикл памяти
Передать контекст модели Подготовка контекста
Подключить инструменты и сервисы API, инструменты, MCP, навыки
Применить OACS в репозитории Работа агента, пакеты интеграции, проверка на собственном проекте
Проверить реализацию Соответствие стандарту, измерения
Разрабатывать и выпускать версии Участие, сборка, релиз, планы

Полный список руководств: оглавление документации.

Безопасность и ограничения

Память и чувствительные данные капсул шифруются перед сохранением. Локальный поставщик ключей local_unlocked по умолчанию хранит ключ рядом с базой: шифрование не защищает от того, кто может прочитать оба файла. Не публикуйте .oacs/ и ограничьте доступ к этому каталогу. Доступна защита ключа парольной фразой.

Локальный запуск использует начальные разрешения режима разработки. Если они не подходят, используйте OACS_POLICY_MODE=strict и явные разрешения. Перед работой с чувствительными данными прочитайте модель безопасности и границу внешнего хранилища секретов.

Это локальная эталонная реализация, не сервис для нескольких клиентов. Поиск по умолчанию лексический и детерминированный; векторный поиск и вызовы моделей относятся к необязательным адаптерам. Результаты измерений относятся к конкретным наборам и моделям и не гарантируют общего ускорения. Постквантовая защита ключей доступна как необязательная интеграция, не как свойство по умолчанию.

License / Лицензия

Apache License 2.0.

Release files for oacs 1.0.24

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for oacs 1.0.24
File Size Uploaded
oacs-1.0.24.tar.gz 303.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for oacs 1.0.24
File Interpreter ABI Platform
oacs-1.0.24-py3-none-any.whl Python 3 none any Details

Total release size: 467.6 kB

Release files / oacs-1.0.24.tar.gz

Download URL oacs-1.0.24.tar.gz
Size 303.0 kB
Tags Source
SHA-256 checksum
How to use checksums
0ead52146d74c9dcdb4950b6ba7f9fedc179dc98599a38dda9454100aea3f870
BLAKE2b-256 checksum
How to use checksums
5aabae14829e51d87de160d98fc195d27d025cf03d86b1e77e7b86f4f382a40e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 27, 2026.

Transparency log

Release files / oacs-1.0.24-py3-none-any.whl

Download URL oacs-1.0.24-py3-none-any.whl
Size 164.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
113d3ec6c93095190af00b2202e83b54581706b69b8d050c0137b8126a8c1cef
BLAKE2b-256 checksum
How to use checksums
60de26c2931d8d0ab1720a751989ac9417cc0809a7cbf0654dd6c964a87dc1af
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 27, 2026.

Transparency log
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page