diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e367646..3601ade 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/README.md b/README.md index 00f121c..7c0b69a 100644 --- a/README.md +++ b/README.md @@ -13,13 +13,13 @@

English · 核心特性 · 快速开始 · Python API · 演示 · 项目结构

-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。 ## 快速开始 @@ -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 行 @@ -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) ## 文档与贡献 diff --git a/README_EN.md b/README_EN.md index 46729d6..54bcf52 100644 --- a/README_EN.md +++ b/README_EN.md @@ -13,13 +13,13 @@

中文 · Key features · Quick start · Python API · Demos · Project structure

-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 @@ -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 @@ -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 diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index bb9b041..371319f 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -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 设置明确报错。 diff --git a/docs/lean-harness.md b/docs/lean-harness.md index 2f3649e..32c7e4c 100644 --- a/docs/lean-harness.md +++ b/docs/lean-harness.md @@ -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 diff --git a/docs/legacy-migration.md b/docs/legacy-migration.md index 90d56bc..4c99a8d 100644 --- a/docs/legacy-migration.md +++ b/docs/legacy-migration.md @@ -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 生命周期与统一授权 | @@ -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,文本截断边界测试继续保留,并增加退役入口、包内容、配置拒绝和示例导入回归。测试数减少不作为质量提升的证据。 diff --git a/docs/plugin-lifecycle.md b/docs/plugin-lifecycle.md new file mode 100644 index 0000000..27e1cc3 --- /dev/null +++ b/docs/plugin-lifecycle.md @@ -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. diff --git a/miniagent/__init__.py b/miniagent/__init__.py index 4b809f7..bcb72b4 100644 --- a/miniagent/__init__.py +++ b/miniagent/__init__.py @@ -1,5 +1,6 @@ """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 @@ -7,7 +8,7 @@ __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__", ] diff --git a/miniagent/agent.py b/miniagent/agent.py index 1fc1380..9bc2917 100644 --- a/miniagent/agent.py +++ b/miniagent/agent.py @@ -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: diff --git a/miniagent/harness.py b/miniagent/harness.py index 05e4e34..4575d8c 100644 --- a/miniagent/harness.py +++ b/miniagent/harness.py @@ -1,4 +1,4 @@ -"""Small static plugin runtime with instance ownership and async cleanup.""" +"""Plugin runtime with instance ownership, async cleanup and opt-in reconciliation.""" import asyncio import inspect from contextlib import AsyncExitStack @@ -13,31 +13,44 @@ class Plugin: name: str setup: object requires: tuple = () + inject: tuple = () class Scope: def __init__(self, app): self.app, self.stack = app, AsyncExitStack() + self.provided, self.setting_up, self.closed = set(), True, False + + def _registration(self): + if self.closed: + raise RuntimeError("Plugin scope is closed") + if not self.setting_up: + self.app._idle() def service(self, name, value): + self._registration() if name in self.app.services: raise ValueError(f"Duplicate service: {name}") self.app.services[name] = value + self.provided.add(name) self.stack.callback(self.app.services.pop, name) def get(self, name): return self.app.services[name] def tool(self, tool): + self._registration() self.app.registry.add(tool) self.stack.callback(self.app.registry.tools.pop, tool.name) def on(self, event, callback): + self._registration() listeners = self.app.events.setdefault(event, []) listeners.append(callback) self.stack.callback(listeners.remove, callback) def cleanup(self, callback, *args): + self._registration() async def invoke(): result = callback(*args) if inspect.isawaitable(result): @@ -48,7 +61,7 @@ async def invoke(): class Harness: def __init__(self, backend=None, *, model=None, providers=None, api_key=None, base_url=None, temperature=None, policy=None, - session=None, context_budget=32768, + session=None, context_budget=32768, reactive=False, system_prompt="You are a helpful assistant."): self.services, self.events, self.plugins, self.active = {}, {}, {}, {} self.registry = Registry() @@ -61,6 +74,9 @@ def __init__(self, backend=None, *, model=None, providers=None, api_key=None, self._base_prompt = system_prompt self._base_temperature = temperature self.skill = None + self.reactive = reactive + from .agent import loop_plugin + self.use(loop_plugin()) if model: from .llm import llm_plugin self.use(llm_plugin(model, providers=providers, api_key=api_key, @@ -99,12 +115,16 @@ async def start(self): self.busy = False async def _start(self): + self._check_cycles() pending = {n: p for n, p in self.plugins.items() if n not in self.active} added = [] try: while pending: - ready = [p for p in pending.values() if all(n in self.active for n in p.requires)] + ready = [p for p in pending.values() if all(n in self.active for n in p.requires) + and all(n in self.services for n in p.inject)] if not ready: + if self.reactive: + break # Registered dependents wait for a later start/provider change. raise ValueError("Missing or cyclic plugin dependency") for plugin in ready: scope = Scope(self) @@ -112,33 +132,74 @@ async def _start(self): result = plugin.setup(scope) if inspect.isawaitable(result): await result - except BaseException: - await scope.stack.aclose() + except BaseException as failure: + scope.closed = True + try: + await scope.stack.aclose() + except BaseException as error: + raise BaseExceptionGroup("Plugin setup and cleanup failed", [failure, error]) raise + finally: + scope.setting_up = False self.active[plugin.name] = scope added.append(plugin.name) pending.pop(plugin.name) except BaseException as failure: - errors = [failure] - for name in reversed(added): - try: - await self.active.pop(name).stack.aclose() - except BaseException as error: - errors.append(error) + errors = [failure, *await self._close_scopes(reversed(added))] if len(errors) > 1: raise BaseExceptionGroup("Plugin activation and rollback failed", errors) raise + @property + def states(self): + return {name: "ACTIVE" if name in self.active else "PENDING" for name in self.plugins} + + def _check_cycles(self): + visited = set() + def visit(name, path): + if name in path: + raise ValueError("Cyclic plugin dependency") + if name not in visited: + for dependency in self.plugins[name].requires: + if dependency in self.plugins: + visit(dependency, path | {name}) + visited.add(name) + for name in self.plugins: + visit(name, set()) + + async def _close_scopes(self, names): + errors = [] + for name in names: + scope = self.active.pop(name) + scope.closed = True + try: + await scope.stack.aclose() + except BaseException as error: + errors.append(error) + return errors + async def unuse(self, name): self._idle() - if any(name in self.plugins[n].requires for n in self.active if n != name): + if name not in self.plugins: + raise KeyError(name) + removed, services = {name}, set() + while True: + services.update(s for n in removed if n in self.active for s in self.active[n].provided) + dependents = {n for n in self.active if set(self.plugins[n].requires) & removed + or set(self.plugins[n].inject) & services} + if dependents <= removed: + break + removed.update(dependents) + if not self.reactive and removed != {name}: raise ValueError("Plugin has active dependents") self.busy = True try: - scope = self.active.pop(name, None) - if scope: - await scope.stack.aclose() + errors = await self._close_scopes(n for n in reversed(tuple(self.active)) if n in removed) self.plugins.pop(name) + if errors: + raise BaseExceptionGroup("Plugin cleanup failures", errors) + if self.reactive: + await self._start() finally: self.busy = False @@ -157,12 +218,7 @@ async def aclose(self): self._idle() self.busy = True try: - errors = [] - for name in reversed(tuple(self.active)): - try: - await self.active.pop(name).stack.aclose() - except BaseException as error: - errors.append(error) + errors = await self._close_scopes(reversed(tuple(self.active))) if errors: raise BaseExceptionGroup("Plugin cleanup failures", errors) finally: @@ -184,10 +240,12 @@ async def arun(self, query, *, max_steps=None, stream=None): backend = self.backend or self.services.get("llm") if backend and hasattr(backend, "temperature") and self.skill.temperature is not None: backend.temperature = self.skill.temperature - from .agent import agent_loop + loop = self.services.get("agent_loop") + if loop is None: + raise ValueError("An active agent_loop service is required") if max_steps is None: max_steps = self.skill.max_iterations if self.skill and self.skill.max_iterations is not None else 10 - return await agent_loop(self, query, max_steps=max_steps, stream=stream) + return await loop(self, query, max_steps=max_steps, stream=stream) finally: try: if not self.session or self.session.lock is not None: diff --git a/tests/test_mcp_skills.py b/tests/test_mcp_skills.py index 2b77ca0..2e7e57f 100644 --- a/tests/test_mcp_skills.py +++ b/tests/test_mcp_skills.py @@ -51,8 +51,10 @@ async def scenario(): pid = result["structuredContent"]["pid"] # Enter and exit from separate tasks: SDK context remains in its owner task. await asyncio.create_task(app.unuse("mcp:local")) - assert not app.registry.tools and not app.services + assert not app.registry.tools and set(app.services) == {"agent_loop"} assert not psutil.pid_exists(pid) + await app.aclose() + assert not app.services asyncio.run(scenario()) diff --git a/tests/test_reactive_plugins.py b/tests/test_reactive_plugins.py new file mode 100644 index 0000000..8dda2dc --- /dev/null +++ b/tests/test_reactive_plugins.py @@ -0,0 +1,295 @@ +"""Lifecycle transitions retain ownership, cleanup and busy/session protections.""" +import asyncio + +import pytest + +from miniagent import Harness, Plugin, loop_plugin +from tests.test_harness import tool + + +def test_pending_plugin_recovers_without_reregistration(): + async def scenario(): + seen = [] + app = Harness(reactive=True) + app.use(Plugin("consumer", lambda c: seen.append(c.get("value")), requires=("provider",))) + await app.start() + assert app.states["consumer"] == "PENDING" and seen == [] + app.use(Plugin("provider", lambda c: c.service("value", 1))) + await app.start() + assert seen == [1] and app.states["consumer"] == "ACTIVE" + await app.unuse("provider") + assert app.states["consumer"] == "PENDING" and "value" not in app.services + app.use(Plugin("provider", lambda c: c.service("value", 2))) + await app.start() + assert seen == [1, 2] + await app.aclose() + asyncio.run(scenario()) + + +def test_service_injection_transitive_cleanup_and_different_provider(): + async def scenario(): + cleaned, seen = [], [] + app = Harness(reactive=True) + def base(ctx): + ctx.service("inference", 1) + ctx.service("other", 2) + ctx.cleanup(cleaned.append, "base") + def middle(ctx): + seen.append(ctx.get("inference")) + ctx.service("derived", 3) + ctx.tool(tool()) + ctx.on("notice", lambda e: None) + ctx.cleanup(cleaned.append, "middle") + def leaf(ctx): + ctx.cleanup(cleaned.append, "leaf") + app.use(Plugin("leaf", leaf, inject=("derived",))) + app.use(Plugin("middle", middle, inject=("inference",))) + app.use(Plugin("base", base)) + await app.start() + await app.unuse("base") + assert cleaned == ["leaf", "middle", "base"] + assert app.states["middle"] == app.states["leaf"] == "PENDING" + assert not app.registry.tools and not app.events["notice"] + assert set(app.services) == {"agent_loop"} + app.use(Plugin("replacement", lambda c: c.service("inference", 42))) + await app.start() + assert seen == [1, 42] and app.states["leaf"] == "ACTIVE" + await app.aclose() + asyncio.run(scenario()) + + +def test_static_service_dependents_require_explicit_unload(): + async def scenario(): + app = Harness() + app.use(Plugin("provider", lambda c: c.service("value", 1))) + app.use(Plugin("consumer", lambda c: None, inject=("value",))) + await app.start() + with pytest.raises(ValueError, match="active dependents"): + await app.unuse("provider") + assert app.services["value"] == 1 and app.states["consumer"] == "ACTIVE" + await app.unuse("consumer") + await app.unuse("provider") + await app.aclose() + asyncio.run(scenario()) + + +def test_known_dependency_cycles_are_errors_even_in_reactive_mode(): + async def scenario(): + app = Harness(reactive=True) + app.use(Plugin("a", lambda c: None, requires=("b",))) + app.use(Plugin("b", lambda c: None, requires=("a",))) + with pytest.raises(ValueError, match="Cyclic"): + await app.start() + assert not app.active and not app.services and not app.busy + asyncio.run(scenario()) + + +def test_reactivation_failure_rolls_back_new_batch_preserves_existing(): + async def scenario(): + app = Harness(reactive=True) + app.use(Plugin("stable", lambda c: c.service("stable", "kept"))) + def broken(ctx): + ctx.tool(tool()) + ctx.service("partial", 1) + raise RuntimeError("setup failed") + app.use(Plugin("dependent", broken, inject=("value",))) + await app.start() + app.use(Plugin("provider", lambda c: c.service("value", 2))) + with pytest.raises(RuntimeError, match="setup failed"): + await app.start() + assert set(app.services) == {"agent_loop", "stable"} + assert not app.registry.tools + assert app.states["dependent"] == app.states["provider"] == "PENDING" + assert app.states["stable"] == "ACTIVE" and not app.busy + await app.unuse("dependent") + assert app.states["provider"] == "ACTIVE" + await app.aclose() + asyncio.run(scenario()) + + +def test_cleanup_failure_does_not_leave_transitive_consumers_running(): + async def scenario(): + app = Harness(reactive=True) + cleaned = [] + def provider(ctx): + ctx.service("value", 1) + ctx.cleanup(cleaned.append, "provider") + def consumer(ctx): + def fail(): + cleaned.append("consumer") + raise RuntimeError("cleanup failed") + ctx.service("child", 2) + ctx.cleanup(fail) + app.use(Plugin("provider", provider)) + app.use(Plugin("consumer", consumer, inject=("value",))) + app.use(Plugin("leaf", lambda c: c.cleanup(cleaned.append, "leaf"), inject=("child",))) + await app.start() + with pytest.raises(BaseExceptionGroup): + await app.unuse("provider") + assert cleaned == ["leaf", "consumer", "provider"] + assert set(app.services) == {"agent_loop"} + assert app.states["consumer"] == app.states["leaf"] == "PENDING" + assert "provider" not in app.plugins and not app.busy + await app.aclose() + asyncio.run(scenario()) + + +def test_setup_and_cleanup_failures_both_reported(): + async def scenario(): + app = Harness(reactive=True) + def bad(ctx): + def fail(): + raise ValueError("cleanup") + ctx.service("temporary", 1) + ctx.cleanup(fail) + raise RuntimeError("setup") + app.use(Plugin("bad", bad)) + with pytest.raises(BaseExceptionGroup) as captured: + await app.start() + assert {type(e) for e in captured.value.exceptions} == {RuntimeError, ValueError} + assert not app.active and not app.services and not app.busy + asyncio.run(scenario()) + + +def test_replace_loop_keeps_harness_busy_and_uncertain_guards(): + async def scenario(): + app = Harness(reactive=True) + entered, release = asyncio.Event(), asyncio.Event() + async def custom(runtime, query, *, max_steps, stream): + entered.set() + await release.wait() + return f"{query}:{max_steps}" + await app.unuse("agent-loop") + app.use(loop_plugin(custom)) + task = asyncio.create_task(app.arun("go", max_steps=3)) + await entered.wait() + with pytest.raises(RuntimeError, match="running"): + await app.unuse("agent-loop") + with pytest.raises(RuntimeError, match="running"): + await app.start() + release.set() + assert await task == "go:3" + app.record({"role": "tool", "tool_call_id": "unknown", "content": "inspect effects"}, + tool=True, uncertain=True) + with pytest.raises(RuntimeError, match="uncertain"): + await app.arun("again") + await app.aclose() + asyncio.run(scenario()) + + +def test_cancelled_setup_rolls_back_resources_and_releases_busy(): + async def scenario(): + app = Harness(reactive=True) + entered, release = asyncio.Event(), asyncio.Event() + cleaned = [] + async def setup(ctx): + ctx.service("partial", 1) + ctx.cleanup(cleaned.append, "closed") + entered.set() + await release.wait() + app.use(Plugin("slow", setup)) + task = asyncio.create_task(app.start()) + await entered.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert cleaned == ["closed"] and not app.active and not app.services and not app.busy + asyncio.run(scenario()) + + +def test_custom_loop_cancellation_closes_persistent_session(tmp_path): + from miniagent.session import Session + async def scenario(): + app = Harness(session=Session(tmp_path / "session")) + entered, release = asyncio.Event(), asyncio.Event() + async def custom(runtime, query, **kwargs): + runtime.record({"role": "user", "content": query}) + entered.set() + await release.wait() + await app.unuse("agent-loop") + app.use(loop_plugin(custom)) + task = asyncio.create_task(app.arun("cancelled")) + await entered.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert not app.busy and app.session.lock is None + restored = Session(app.session.path).open() + assert restored.messages == [{"role": "user", "content": "cancelled"}] + restored.close() + await app.aclose() + asyncio.run(scenario()) + + +def test_loop_service_waits_for_injected_dependency(): + async def scenario(): + app = Harness(reactive=True) + await app.unuse("agent-loop") + async def custom(runtime, query, **kwargs): + return str(runtime.services["value"]) + app.use(loop_plugin(custom, inject=("value",))) + await app.start() + with pytest.raises(ValueError, match="active agent_loop"): + await app.arun("waiting") + app.use(Plugin("provider", lambda c: c.service("value", 42))) + assert await app.arun("ready") == "42" + await app.unuse("provider") + assert app.states["agent-loop"] == "PENDING" + app.use(Plugin("new-provider", lambda c: c.service("value", 7))) + assert await app.arun("restored") == "7" + await app.aclose() + asyncio.run(scenario()) + + +@pytest.mark.parametrize("resource", ["service", "tool", "listener", "cleanup"]) +def test_active_scope_cannot_register_resources_during_task_or_after_close(resource): + async def scenario(): + scopes = [] + app = Harness() + app.use(Plugin("owner", lambda ctx: scopes.append(ctx))) + await app.start() + def register(): + scope = scopes[0] + if resource == "service": + scope.service("late", 1) + elif resource == "tool": + scope.tool(tool("late")) + elif resource == "listener": + scope.on("late", lambda event: None) + else: + scope.cleanup(lambda: None) + async def custom(runtime, query, **kwargs): + with pytest.raises(RuntimeError, match="running"): + register() + return "ok" + await app.unuse("agent-loop") + app.use(loop_plugin(custom)) + assert await app.arun("go") == "ok" + await app.unuse("owner") + with pytest.raises(RuntimeError, match="closed"): + register() + await app.aclose() + assert not app.services and not app.registry.tools + assert not app.events.get("late") + asyncio.run(scenario()) + + +def test_failed_setup_scope_cannot_register_after_rollback(): + async def scenario(): + scopes = [] + app = Harness() + def broken(ctx): + scopes.append(ctx) + ctx.service("partial", 1) + raise RuntimeError("setup failed") + app.use(Plugin("broken", broken)) + with pytest.raises(RuntimeError, match="setup failed"): + await app.start() + with pytest.raises(RuntimeError, match="closed"): + scopes[0].service("late", 2) + assert not app.active and not app.services and not app.busy + await app.unuse("broken") + await app.start() + assert app.states["agent-loop"] == "ACTIVE" + await app.aclose() + asyncio.run(scenario())