Metadata-Version: 2.4
Name: agent-env-protocol
Version: 0.1.0
Summary: Agent Environment Protocol - 基于文件系统的 Agent 管理协议
Requires-Python: >=3.12
Requires-Dist: loguru>=0.7.0
Requires-Dist: mcp>=1.26.0
Requires-Dist: strictyaml>=1.7.3
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == 'dev'
Description-Content-Type: text/markdown

﻿<p align="right">
<a href="README_zh.md">中文</a>
</p>

# AEP - Agent Environment Protocol

<p align="center">
<img src="docs/aep-logo.svg" alt="AEP Logo" width="720" />
</p>

<p align="center">
<strong>What if an Agent could call tools just like writing Python? Introducing AEP! 🚀</strong>

<em>A unified protocol for capability management, discovery, and execution in Agent environments.</em>
</p>

---

## 🤔 Why AEP?

As large language models have evolved, common pain points have emerged from practices like Claude Skills, PageIndex, and OpenViking. AEP was created to address these challenges:

1. **Embrace the Agent evolution: replace hard-coding with the file system**
   With the rise of LLM coding and terminal capabilities, Agents can now operate computers and locate resources just like humans. In medium-scale data scenarios, letting an Agent **browse the file system autonomously** is often smarter than pre-loading structured data into the prompt. AEP exposes Tools, Skills, and Library entirely via the file system, enabling Agents to access and orchestrate them in the most natural way.

2. **Eliminate context waste: break free from MCP with a Pythonic approach**
   Traditional MCP and tool-calling patterns waste significant context:
   * *Initialization overhead*: Providing full tool descriptions and schemas to the model consumes roughly 15% of the system context upfront.
   * *Multi-turn call overhead*: When invoking tools sequentially, the LLM must repeatedly emit instructions and receive intermediate results — many of which don't need to be retained long-term.

   AEP introduces an innovative approach: **let tool calls execute directly within a Python runtime**. The Agent simply writes code to chain logic together, dramatically reducing the token cost of multi-turn interactions.

3. **Solve dependency conflicts once and for all: manage Skills like ``uv``/``npm``**
   Traditional Skill structures are too permissive — mixing multiple scripted Skills easily causes Python dependency conflicts. AEP draws from modern package managers, giving each Skill its own **isolated virtual environment**, ensuring system stability without sacrificing flexibility.

---

## 💡 Core Design & Innovations

AEP organizes Agent capabilities into three clearly defined categories, each deeply optimized:

### 🛠️ ``tools/``: Unified Tools and MCP

* **Unified execution semantics**: Whether a local Python tool or a remote MCP service, the Agent invokes everything via ``tools run "tools.<tool>.<func>(...)"``。MCP services are automatically stubbed as local Python modules.
* **Agent-friendly**: The model only needs to emit a single expression — no complex shell pipelines required.
* **Observability**: Track tool execution state easily via the session's ``output / kill / history`` commands.

### 🧰 ``skills/``: Spec-Driven Isolated Skills

* **Dependency isolation**: Each Skill has its own dedicated virtual environment (``.venv``), completely eliminating environment pollution.
* **Spec-defined**: Strict format validation and field declarations via ``SKILL.md`` frontmatter.
* **Clear invocation**: Run any skill precisely with ``skills run <skill/path.py> [args]``. Supports both directory-based and single-file ``.md`` import formats.

### 📚 ``library/``: Tree-Structured Knowledge Base

* **File system organization**: Instead of forcing all knowledge into a single flat database, content is organized by directory (supports writing to arbitrary subdirectories via ``add_library``).
* **Recursive indexing**: Each directory has its own ``index.md``, perfectly suited for hierarchical LLM reading — read the directory index first, then drill into specific files as needed.

---

## 🏗️ Architecture

AEP uses a clean **three-layer model**:

1. **Config layer (``AEPProfile``)**: Manages CRUD operations for Tools/Skills/Library/MCP configurations and generates the unified ``index.md``.
2. **Mount layer (``AEPWorkspace``)**: Physically mounts the Profile's configuration into the workspace (e.g., a ``.agents/`` directory).
3. **Runtime layer (``AEPSession``)**: Unified execution entry point supporting command queuing, incremental output retrieval, termination control, and state management.

<details>
<summary>Click to see the standard AEP Profile directory structure</summary>

```text
config_dir/
├── tools/
│   ├── .venv/
│   ├── requirements.txt
│   ├── index.md
│   └── *.py
├── skills/
│   ├── index.md
│   └── <skill-name>/
│       ├── .venv/
│       ├── SKILL.md
│       ├── requirements.txt
│       └── scripts/...
├── library/
│   ├── index.md
│   └── ...
└── _mcp/
    └── <server>/config.json

```

</details>

---

## 🚀 Quick Start

### Installation

Once published, install via pip:

```bash
pip install agent-env-protocol

```

For local development:

```bash
git clone https://github.com/Slipstream-Max/Agent-Environment-Protocol
cd Agent-Environment-Protocol
uv sync --extra dev

```

### CLI Interactive Experience (great for human experimentation)

```bash
# 1. Initialize and generate index
aep index --profile ./agent_config

# 2. Inject capabilities (tools / skills / docs)
aep tool add ./examples/calc.py --name calc --profile ./agent_config
aep skill add ./examples/greeter --name greeter --profile ./agent_config
aep library add ./docs/guide.md --target-dir intro --profile ./agent_config
aep index --profile ./agent_config

# 3. Enter an interactive session
aep shell --profile ./agent_config --workspace ./workspace

# Inside the shell, test just like an Agent would:
# > tools list
# > tools run "tools.calc.add(1, 2)"
# > skills run greeter/main.py

```

### Minimal Python API Example

```python
import asyncio
from aep import AEPProfile, AEPWorkspace

async def main() -> None:
    # 1. Load config and build index
    profile = AEPProfile("./agent_capabilities")
    profile.index()

    # 2. Mount workspace and create session
    aep = AEPWorkspace.attach(workspace="./my_project", config=profile)
    session = aep.create_session()

    # 3. Execute a tool call
    run_result = await session.run("tools list")
    await session.wait(run_result.exec_id, timeout_ms=5_000)
    
    # 4. Retrieve output
    out = await session.output(run_result.exec_id, cursor=0, limit=200)
    print("".join(chunk.content for chunk in out.chunks))

asyncio.run(main())

```

---

## 🤖 Integrating with Your LLM Agent

AEP provides a ready-to-use Adapter. The recommended pattern for integrating AEP with any LLM SDK:

1. **Inject context**: Generate capability descriptions via ``profile.build_context()``.
2. **Register tools**: Expose ``adapter.tool_schemas()`` to the model.
3. **Constrain the prompt**: Use ``adapter.usage_contract()`` to tell the model how to use AEP correctly.
4. **Route calls**: Intercept the model's Tool Calls and dispatch them to ``adapter.call_tool(...)``.

```python
import asyncio
from aep import AEPProfile, AEPWorkspace, AEPSessionToolAdapter

async def run_with_llm(user_input: str) -> None:
    profile = AEPProfile("./agent_capabilities")
    profile.index()

    aep = AEPWorkspace.attach("./workspace", profile)
    session = aep.create_session()
    adapter = AEPSessionToolAdapter(session)

    # Get configuration parameters for the LLM
    tools = adapter.tool_schemas()
    context = profile.build_context(include_tools=True, include_skills=True, max_chars=8_000)
    usage_contract = adapter.usage_contract()

    system_prompt = f"{usage_contract}\n\nCapability context:\n{context}"

    # --- Pseudocode: wire up your own LLM SDK ---
    # response = llm.chat(system=system_prompt, messages=[user_input], tools=tools)
    # for call in response.tool_calls:
    #     result = await adapter.call_tool(call.name, call.arguments)
    #     messages.append({"role": "tool", "content": str(result)})
    
if __name__ == "__main__":
    asyncio.run(run_with_llm("List all available tools"))

```

*Note: ``AEPSessionToolAdapter`` provides 5 atomic tools for model orchestration by default: ``aep_exec`` (execute), ``aep_output`` (fetch output), ``aep_kill`` (terminate), ``aep_history`` (history), ``aep_env`` (environment variables).*

---

## 📖 References

* Detailed API docs: ``docs/api.md``
* Architecture deep-dive: ``docs/arch.md``
* More examples: ``examples/demo.py``, ``examples/demo_skill_scripts.py``

## 📄 License

[MIT License](https://www.google.com/search?q=LICENSE)