Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ jobs:
- run: uv run --locked --python ${{ matrix.python }} --extra mcp --extra credentials python -m pytest tests -q -m "not live"
- run: uv run --locked --python ${{ matrix.python }} --extra mcp --extra credentials python -m compileall -q miniagent
- name: Native runtime static checks
run: uv run --locked --python ${{ matrix.python }} --extra mcp --extra credentials ruff check --select F miniagent tests/test_runtime_recovery.py tests/test_provider_protocols.py tests/test_cli_runtime.py tests/test_model_selection.py tests/test_connections.py tests/conftest.py scripts/source_stats.py scripts/minimal_install_smoke.py
run: uv run --locked --python ${{ matrix.python }} --extra mcp --extra credentials ruff check --select F miniagent tests/test_runtime_recovery.py tests/test_reactive_plugins.py tests/test_provider_protocols.py tests/test_cli_runtime.py tests/test_model_selection.py tests/test_connections.py tests/conftest.py scripts/source_stats.py scripts/minimal_install_smoke.py
- name: Export locked production dependencies
run: uv export --locked --no-dev --extra mcp --extra credentials --no-emit-project --output-file audit-requirements.txt
- name: Audit production dependencies
Expand Down
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@

<p align="center"><a href="README_EN.md">English</a> · <a href="#核心特性">核心特性</a> · <a href="#快速开始">快速开始</a> · <a href="#作为-python-调用">Python API</a> · <a href="#演示">演示</a> · <a href="#项目结构">项目结构</a></p>

MiniAgent 是一个**超轻量、常用功能齐备的 Python Agent / Harness**,核心仅 **524 行代码**。支持工具调用、会话记忆、上下文管理与插件扩展等主流 Agent 常用能力,**可以直接使用,也适合快速入门学习、定制修改和二次开发。**
MiniAgent 是一个**超轻量、常用功能齐备的 Python Agent / Harness**,核心仅 **591 行代码**。支持工具调用、会话记忆、上下文管理与插件扩展等主流 Agent 常用能力,**可以直接使用,也适合快速入门学习、定制修改和二次开发。**

## 核心特性

- 🧠 **功能齐备**:原生工具调用、流式输出、会话记忆、上下文压缩、Skills、MCP、插件管理与权限控制,组成可运行的 Agent / Harness。
- 🚀 **直接使用**:连接模型后即可通过 CLI 执行编程与自动化任务,也能通过 Python API 嵌入现有项目。
- 📖 **快速入门**:核心仅 **524 行、4 个文件**,从模型调用、工具执行到插件管理,适合通过阅读和运行源码理解 Agent / Harness 的工作原理。
- 📖 **快速入门**:核心仅 **591 行、4 个文件**,从模型调用、工具执行到插件管理,适合通过阅读和运行源码理解 Agent / Harness 的工作原理。
- 🧩 **定制开发**:修改提示词与 Skills,通过 Plugin 接入自己的工具和服务;复用已有的会话与权限机制,开发自己的 Agent。

## 快速开始
Expand Down Expand Up @@ -88,8 +88,8 @@ Harness 负责模型与工具之间的循环、插件启动和清理,以及会

```text
miniagent/
├── agent.py # Agent 循环 · 65 行
├── harness.py # 插件、服务与生命周期 · 256 行
├── agent.py # Agent 循环 · 74 行
├── harness.py # 插件、服务与生命周期 · 314 行
├── llm.py # 模型调用与流式输出 · 149 行
├── tools/
│ ├── registry.py # 工具注册与执行检查 · 54 行
Expand All @@ -102,7 +102,7 @@ miniagent/
└── cli.py # 命令行入口
```

四文件核心 **524 行**;全部官方包 Python **2,067 行**。行数包含注释和空行,不含第三方依赖。运行 `python scripts/source_stats.py` 可复核。[统计脚本](scripts/source_stats.py)
四文件核心 **591 行**;全部官方包 Python **2,135 行**。行数包含注释和空行,不含第三方依赖。运行 `python scripts/source_stats.py` 可复核。[统计脚本](scripts/source_stats.py)

## 文档与贡献

Expand Down
10 changes: 5 additions & 5 deletions README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@

<p align="center"><a href="README.md">中文</a> · <a href="#key-features">Key features</a> · <a href="#quick-start">Quick start</a> · <a href="#use-from-python">Python API</a> · <a href="#demos">Demos</a> · <a href="#project-structure">Project structure</a></p>

MiniAgent is an **ultra-lightweight Python Agent / Harness with the essentials built in**, centered on just **524 lines of core code**. It supports common agent capabilities such as tool calling, session memory, context management and plugin extensions. **Use it directly, learn how agents work, or customize it to build your own.**
MiniAgent is an **ultra-lightweight Python Agent / Harness with the essentials built in**, centered on just **591 lines of core code**. It supports common agent capabilities such as tool calling, session memory, context management and plugin extensions. **Use it directly, learn how agents work, or customize it to build your own.**

## Key features

- 🧠 **Essential capabilities**: native tool calling, streaming, session memory, context compaction, Skills, MCP, plugin management and permission controls form a working Agent / Harness.
- 🚀 **Ready to use**: connect a model and run coding and automation tasks through the CLI, or embed the runtime in an existing project through the Python API.
- 📖 **Learn by exploring**: the core is just **524 lines across 4 files**, covering model calls, tool execution and plugin management. Read and run the code to understand how an Agent / Harness works.
- 📖 **Learn by exploring**: the core is just **591 lines across 4 files**, covering model calls, tool execution and plugin management. Read and run the code to understand how an Agent / Harness works.
- 🧩 **Build your own**: customize prompts and Skills, add tools and services through Plugin. Reuse the existing session and permission mechanisms as you develop your own agent.

## Quick start
Expand Down Expand Up @@ -88,8 +88,8 @@ The core lives in [agent.py](miniagent/agent.py), [harness.py](miniagent/harness

```text
miniagent/
├── agent.py # Agent loop · 65 lines
├── harness.py # Plugins, services and lifecycle · 256 lines
├── agent.py # Agent loop · 74 lines
├── harness.py # Plugins, services and lifecycle · 314 lines
├── llm.py # Model calls and streaming · 149 lines
├── tools/
│ ├── registry.py # Tool registration and execution checks · 54 lines
Expand All @@ -102,7 +102,7 @@ miniagent/
└── cli.py # CLI entry point
```

The core totals **524 lines**; all first-party package Python totals **2,067 lines**. Counts include comments and blank lines and exclude third-party dependencies. Run `python scripts/source_stats.py` to verify. [Counting script](scripts/source_stats.py)
The core totals **591 lines**; all first-party package Python totals **2,135 lines**. Counts include comments and blank lines and exclude third-party dependencies. Run `python scripts/source_stats.py` to verify. [Counting script](scripts/source_stats.py)

## Docs and contributing

Expand Down
2 changes: 2 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## [Unreleased]

- [修复] 插件 Scope 在任务执行中和关闭后拒绝注册服务、工具、事件与清理回调;初始化和清理同时失败时保留两项异常,失败激活回滚新增资源。
- [新增] 显式启用 `Harness(reactive=True)` 可等待插件和服务依赖,依赖卸载时传递清理,恢复后在生命周期边界重新激活;`loop_plugin` 支持替换可信 Agent Loop,默认仍使用原生循环。
- [修复] 自定义算术工具及指南示例接收 Policy 注入的 path,补充实际 Registry 执行与清理检查;温度按 CLI、JSON、环境的最终生效值校验,空环境回退默认值,不再阻止高优先级配置覆盖。
- [改进] 0.3.0a1 候选集中原生 Harness / Session / Plugin / MCP,退役旧文本 Agent、系统工具、Memory 和 Orchestrator;旧实现保留在 codex/legacy-pre-harness,迁移说明列出不兼容入口。
- [改进] 文件工具元数据不再注册到全局目录,Shell 复用单一异步实现;移除旧版运行依赖和无效配置字段,未知 JSON 设置明确报错。
Expand Down
7 changes: 5 additions & 2 deletions docs/lean-harness.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,11 @@ side effect or global decorator catalog.

Dependencies are static: `requires` names plugins, missing or cyclic dependencies
fail at startup, and an active dependency cannot be unloaded before its consumers.
Harness calls the native agent loop directly. Reactive dependencies and a public
replaceable Loop interface are separate proposals, not requirements of this version.
The default remains strict startup. `Harness(reactive=True)` lets consumers wait
for declared plugins (`requires`) or services (`inject`) and reactivate at explicit
lifecycle boundaries. The default native Loop is provided by `agent-loop`;
`loop_plugin` can replace it while Harness retains session and run guards.
See [lifecycle, examples and trusted Loop responsibilities](plugin-lifecycle.md).

## Models and configuration

Expand Down
4 changes: 2 additions & 2 deletions docs/legacy-migration.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ git clone --branch codex/legacy-pre-harness --single-branch https://github.com/Z
| --- | --- | --- |
| `MiniAgent`、`run(mode="text")`、`--legacy` | `Harness`、`app.run()` / `await app.arun()`、默认 CLI | 只使用原生工具调用,不再解析 TOOL/ARGS 文本;旧入口明确提示迁移 |
| `Memory` / `memory.json` | 显式 `Session(path)` / CLI JSONL 会话 | 保留旧文件,不自动转换;长期事实记忆暂不新增 |
| `Orchestrator` | 旧编排继续使用旧分支;原生版可用 Python 调用 Harness 并组合 Plugin | 没有内置编排器等价替代,本轮不新增子 Agent 或可替换 Loop 接口 |
| `Orchestrator` | 旧编排继续使用旧分支;原生版可用 Python 调用 Harness 并组合 Plugin | 没有内置编排器或子 Agent 等价替代;可替换 Loop 的职责与边界见[生命周期指南](plugin-lifecycle.md) |
| `register_tool`、全局工具目录、`load_tools` | `ctx.tool(Tool(...))`、`coding_tools()` | 工具归属各 Harness;导入文件工具不会写入全局注册表 |
| 同步 `code_tools.bash()` | `miniagent.plugins.shell()` 或 `coding_tools()` 中的 bash | 统一异步进程、超时、取消和输出上限;直接调用 shell 时超时抛异常 |
| `MCPClient` / `load_mcp_tools` | `mcp_plugin`、`miniagent[mcp]` | 官方 SDK stdio 生命周期与统一授权 |
Expand Down Expand Up @@ -62,6 +62,6 @@ JSON agent 顶层接受:`llm`、`providers`、`mcp_servers`、`system_prompt`

## 测试与代码量

本 PR 已同步 main `929cfe2`(含 #15 的 CLI 展示),不依赖 #13 的响应式插件和可替换 Loop。相对该基线:四文件核心 **531 → 524**,运行机制 **833 → 827**,全部包 **5079 → 2067**。删除的是已退役实现,没有把它们挪到统计边界之外。
原生精简由 #16 独立完成,不依赖 #13 的响应式插件和可替换 Loop。相对当时 main `929cfe2`(含 #15 的 CLI 展示):四文件核心 **531 → 524**,运行机制 **833 → 827**,全部包 **5079 → 2067**。这是 #16 的历史统计,当前统计见双语 README 与 `scripts/source_stats.py`。删除的是已退役实现,没有把它们挪到统计边界之外。

旧文本协议、系统工具、Memory、Orchestrator 和旧入口的专用测试随能力退役。主线的原生 Harness、模型协议、授权、会话恢复、真实本地 MCP 和连接套件保留;Skill/工具案例迁移至原生 API,文本截断边界测试继续保留,并增加退役入口、包内容、配置拒绝和示例导入回归。测试数减少不作为质量提升的证据。
106 changes: 106 additions & 0 deletions docs/plugin-lifecycle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
# Plugin lifecycle and replaceable Agent Loop

MiniAgent keeps the small async runtime. It does not implement a Fiber tree,
HMR, a plugin market or configuration hot reload.

## Strict and reactive modes

The default `Harness()` preserves strict startup: unresolved dependencies are
errors; a provider with active dependents cannot be unloaded until the caller
explicitly unloads those dependents. `Harness(reactive=True)` opts into waiting
and transitive cleanup instead. This flag is an API option, not a new CLI default.

`Plugin.requires` names plugins; `Plugin.inject` names services. Declare every
service consumed by a plugin. Scope service ownership tracks which provider
must outlive each consumer. `Scope.get()` reads services; it does not infer hidden
dependencies. Direct mutation of `app.services` bypasses these contracts and
is unsupported. Plugins, custom loops and cleanup callbacks are trusted Python.

```python
from miniagent import Harness, Plugin

app = Harness(reactive=True)
seen = []
app.use(Plugin("consumer", lambda ctx: seen.append(ctx.get("value")),
inject=("value",)))
await app.start() # consumer is PENDING
app.use(Plugin("provider", lambda ctx: ctx.service("value", 1)))
await app.start() # consumer becomes ACTIVE
await app.unuse("provider") # consumer is cleaned up and returns to PENDING
app.use(Plugin("replacement", lambda ctx: ctx.service("value", 2)))
await app.start() # the same registered consumer activates with the new service
assert seen == [1, 2]
await app.aclose()
```

Examples with `await` belong inside an async function or notebook event loop.
`use()` registers synchronously. `start()` or the next `arun()` reconciles the
graph; `unuse()` reconciles after successful cleanup. Consumers do not need to
be re-registered. `app.states` reports `ACTIVE` or `PENDING`; the latter means
registered but inactive, including after rollback. PENDING does not mean a
background worker is polling or retrying.

Known cycles in `requires` fail before setup, even in reactive mode. Missing
plugins/services can wait. Service-production cycles cannot be inferred from
arbitrary setup functions and remain PENDING; inspect declarations to resolve them.

## Ownership, failure and cancellation

Unloading a provider computes all transitive plugin/service consumers, closes
them in reverse activation order, then closes the provider. Their registrations
remain PENDING; only the explicitly unloaded provider registration is removed.
Tools, event listeners and services are released by their owning Scope.

Setup failure closes its partial Scope and rolls back every plugin added in that
activation batch. Previously active plugins remain intact. A cleanup failure
does not stop the remaining Scope cleanup; errors are reported as exception
groups and automatic activation stops for that operation. Failure does not
promise external resources closed successfully: inspect reported cleanup errors
before calling `start()` to retry. If setup and cleanup both fail, both causes survive.

Lifecycle operations and active Scope resource registrations reject changes while
a task is running. Setup may register resources; a closed Scope may not. Cancellation
rolls back activation and clears the busy guard. A custom Loop cancellation also
closes the Session lock; the existing complete-tool-batch recovery guard remains.

## Replace the Loop

Every Harness registers `agent-loop`, which provides the async `agent_loop`
service. `/plugins` therefore also lists this default plugin. `arun()` resolves
that service rather than directly calling the core loop. There is no fallback to
the default Loop if its plugin was removed or is PENDING.

```python
from miniagent import loop_plugin
from miniagent.agent import agent_loop

async def measured_loop(app, query, *, max_steps, stream):
await app.emit("custom.loop", query_length=len(query))
return await agent_loop(app, query, max_steps=max_steps, stream=stream)

# Given an app with a configured backend:
await app.unuse("agent-loop")
app.use(loop_plugin(measured_loop))
answer = await app.arun("Inspect the project")
```

`loop_plugin` can declare `requires` and `inject`. Replacing a Loop obeys the
same idle-only rules; injected dependencies may leave it PENDING. Harness still
holds run exclusivity, opens/closes sessions, rejects unresolved effects and
repairs known interrupted tool batches. A completely custom Loop must itself
use Registry authorization and record messages/tool starts/results correctly;
it is trusted control flow, not a way to automatically sandbox arbitrary code.
Delegating to `agent_loop` preserves the native tool protocol and event behavior.

## Validation and rollback

Tests cover missing-dependency waiting, reactivation with a replacement service
provider, transitive resource cleanup, strict-mode refusal, cycles, failed
activation preserving old scopes, setup/cleanup error groups, busy guards,
cancelled activation and persistent Session cancellation with a custom Loop.
Real local MCP stdio call/denial/process cleanup still passes.

Rollback this PR restores the fixed native Loop and strict plugin lifecycle.
Callers using `inject`, `reactive` or `loop_plugin` must remove those new options
or explicitly unload/reload their dependents first. Session format is unchanged;
preserve session files and resolve uncertain effects without replaying tools.
3 changes: 2 additions & 1 deletion miniagent/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
"""Python-native mini harness and coding agent."""
from .harness import Harness, Plugin
from .agent import loop_plugin
from .policy import Policy
from .session import Session
from .tools.registry import Tool
from .skills import Skill, register_skill, get_skill, list_skills

__version__ = "0.3.0a1"
__all__ = [
"Harness", "Plugin", "Policy", "Session", "Tool",
"Harness", "Plugin", "Policy", "Session", "Tool", "loop_plugin",
"Skill", "register_skill", "get_skill", "list_skills", "__version__",
]

Expand Down
9 changes: 9 additions & 0 deletions miniagent/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@
from .utils.text_utils import smart_truncate


def loop_plugin(loop=None, *, name="agent-loop", requires=(), inject=()):
"""Register a trusted async loop while Harness retains run/session guards."""
from .harness import Plugin
loop = agent_loop if loop is None else loop
if not callable(loop):
raise ValueError("Agent loop must be callable")
return Plugin(name, lambda ctx: ctx.service("agent_loop", loop), requires, inject)


async def agent_loop(app, query, *, max_steps=10, stream=None):
"""Native loop shared by the Harness; messages never contain SDK objects."""
if max_steps < 1:
Expand Down
Loading
Loading