diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 7407cd7..8e43dbc 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -5,3 +5,5 @@ - [修复] CLI 不再重复注入当前用户消息,日志不再输出 API Key 前缀。 - [改进] 默认 CLI 工具限制为 Coding Tools;原有基础工具保持显式可用。 - [文档] 记录六阶段迁移、权限边界和可复现源码统计。 +- [新功能] 异步 Harness、实例级工具、静态插件生命周期和统一授权入口。 +- [改进] Python 最低版本提升至 3.11,打包元数据统一到 pyproject.toml。 diff --git a/miniagent/__init__.py b/miniagent/__init__.py index af84f22..54a9709 100644 --- a/miniagent/__init__.py +++ b/miniagent/__init__.py @@ -10,12 +10,15 @@ from typing import Any from .agent import MiniAgent +from .harness import Harness, Plugin from .skills import Skill, register_skill, get_skill, list_skills __version__ = "0.1.0" __all__ = [ "MiniAgent", + "Harness", + "Plugin", "Orchestrator", "load_mcp_tools", "Skill", diff --git a/miniagent/agent.py b/miniagent/agent.py index ae18e48..cf4733a 100644 --- a/miniagent/agent.py +++ b/miniagent/agent.py @@ -846,3 +846,39 @@ def run(self, query: str, max_iterations: int = 10, mode: str = "text") -> str: if mode == "native": return self.run_with_native_tools(query, max_iterations) return self.run_with_tools(query, max_iterations) + + +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: + raise ValueError("max_steps must be positive") + if app.backend is None: + raise ValueError("An LLM backend is required") + if not app.messages: + app.messages.append({"role": "system", "content": app.system_prompt}) + app.messages.append({"role": "user", "content": query}) + for step in range(max_steps): + await app.emit("agent.step", step=step) + await app.emit("llm.request", step=step) + message = await app.backend.complete(app.messages, app.registry.schemas(), stream) + await app.emit("llm.response", usage=getattr(app.backend, "usage", {})) + app.messages.append(message) + calls = message.get("tool_calls") or [] + if not calls: + return message.get("content") or "" + for call in calls: + name = call["function"]["name"] + await app.emit("tool.start", name=name, call_id=call["id"]) + try: + args = json.loads(call["function"]["arguments"]) + if not isinstance(args, dict): + raise ValueError("Tool arguments must be an object") + result = await app.registry.execute(name, args, app.policy) + content = result if isinstance(result, str) else json.dumps(result, ensure_ascii=False, default=str) + error = False + except Exception as exc: + content, error = f"Tool failed: {type(exc).__name__}: {exc}", True + content = smart_truncate(content, int(os.environ.get("TOOL_RESULT_LIMIT", "16000"))) + app.messages.append({"role": "tool", "tool_call_id": call["id"], "content": content}) + await app.emit("tool.end", name=name, call_id=call["id"], error=error) + raise RuntimeError("Agent reached max_steps before a final answer") diff --git a/miniagent/harness.py b/miniagent/harness.py new file mode 100644 index 0000000..4fbf2d1 --- /dev/null +++ b/miniagent/harness.py @@ -0,0 +1,160 @@ +"""Small static plugin runtime with instance ownership and async cleanup.""" +import asyncio +import inspect +from contextlib import AsyncExitStack +from dataclasses import dataclass + +from .policy import Policy +from .tools.registry import Registry + + +@dataclass +class Plugin: + name: str + setup: object + requires: tuple = () + + +class Scope: + def __init__(self, app): + self.app, self.stack = app, AsyncExitStack() + + def service(self, name, value): + if name in self.app.services: + raise ValueError(f"Duplicate service: {name}") + self.app.services[name] = value + self.stack.callback(self.app.services.pop, name) + + def get(self, name): + return self.app.services[name] + + def tool(self, tool): + self.app.registry.add(tool) + self.stack.callback(self.app.registry.tools.pop, tool.name) + + def on(self, event, callback): + listeners = self.app.events.setdefault(event, []) + listeners.append(callback) + self.stack.callback(listeners.remove, callback) + + def cleanup(self, callback, *args): + if inspect.iscoroutinefunction(callback): + self.stack.push_async_callback(callback, *args) + else: + self.stack.callback(callback, *args) + + +class Harness: + def __init__(self, backend=None, *, policy=None, system_prompt="You are a helpful assistant."): + self.services, self.events, self.plugins, self.active = {}, {}, {}, {} + self.registry = Registry() + self.policy = policy or Policy() + self.system_prompt, self.backend = system_prompt, backend + self.messages = [] + self.busy = False + + def _idle(self): + if self.busy: + raise RuntimeError("Harness is running; plugin changes are disabled") + + def use(self, plugin): + self._idle() + if plugin.name in self.plugins: + raise ValueError(f"Duplicate plugin: {plugin.name}") + self.plugins[plugin.name] = plugin + return self + + async def start(self): + self._idle() + await self._start() + + async def _start(self): + 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)] + if not ready: + raise ValueError("Missing or cyclic plugin dependency") + for plugin in ready: + scope = Scope(self) + try: + result = plugin.setup(scope) + if inspect.isawaitable(result): + await result + except BaseException: + await scope.stack.aclose() + raise + 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) + if len(errors) > 1: + raise BaseExceptionGroup("Plugin activation and rollback failed", errors) + raise + + async def unuse(self, name): + self._idle() + if any(name in self.plugins[n].requires for n in self.active if n != name): + raise ValueError("Plugin has active dependents") + scope = self.active.pop(name, None) + if scope: + await scope.stack.aclose() + self.plugins.pop(name) + + async def emit(self, event, **payload): + for callback in tuple(self.events.get(event, ())): + try: + result = callback(payload) + if inspect.isawaitable(result): + await result + except Exception: + # Observers do not control authorization or terminate the run. + from .logger import get_logger + get_logger(__name__).warning("Event observer failed: %s", event) + + async def aclose(self): + self._idle() + errors = [] + for name in reversed(tuple(self.active)): + try: + await self.active.pop(name).stack.aclose() + except BaseException as error: + errors.append(error) + if errors: + raise BaseExceptionGroup("Plugin cleanup failures", errors) + + async def arun(self, query, *, max_steps=10, stream=None): + self._idle() + self.busy = True + try: + await self._start() + from .agent import agent_loop + return await agent_loop(self, query, max_steps=max_steps, stream=stream) + finally: + self.busy = False + + def run(self, query, **kwargs): + try: + asyncio.get_running_loop() + except RuntimeError: + async def once(): + try: + return await self.arun(query, **kwargs) + finally: + await self.aclose() + return asyncio.run(once()) + raise RuntimeError("Use await app.arun() inside an event loop") + + async def __aenter__(self): + await self.start() + return self + + async def __aexit__(self, *exc): + await self.aclose() diff --git a/miniagent/plugins.py b/miniagent/plugins.py new file mode 100644 index 0000000..eb23489 --- /dev/null +++ b/miniagent/plugins.py @@ -0,0 +1,64 @@ +"""Default Coding Tools composed as a plugin; shell explicitly authorized.""" +import asyncio +import os +import signal +import subprocess + +from .harness import Plugin +from .tools.registry import Tool +from .tools import code_tools, get_tool_description +from .utils.text_utils import smart_truncate + + +async def shell(cmd, *, cwd, timeout=0): + timeout = timeout or int(os.environ.get("BASH_TIMEOUT", "120")) + if timeout <= 0: + raise ValueError("Shell timeout must be positive") + options = {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} if os.name == "nt" else {"start_new_session": True} + process = await asyncio.create_subprocess_shell( + cmd, cwd=cwd, stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, **options, + ) + async def terminate(): + if os.name == "nt": + killer = await asyncio.create_subprocess_exec( + "taskkill", "/PID", str(process.pid), "/T", "/F", + stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL, + ) + await killer.wait() + else: + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + await process.wait() + try: + out, err = await asyncio.wait_for(process.communicate(), timeout) + except BaseException: + await asyncio.shield(terminate()) + raise + limit = int(os.environ.get("BASH_MAX_OUTPUT", "50000")) + return {"exit_code": process.returncode, + "stdout": smart_truncate(out.decode(errors="replace"), limit), + "stderr": smart_truncate(err.decode(errors="replace"), limit)} + + +def coding_tools(): + def setup(ctx): + for name in ("read", "write", "edit", "grep", "glob", "bash"): + func = getattr(code_tools, name) + description = get_tool_description(func) + if name == "bash": + async def executor(cmd, timeout=0): + return await shell(cmd, cwd=str(ctx.app.policy.workspace), timeout=timeout) + access = "shell" + else: + def executor(_func=func, **kwargs): + token = code_tools._workspace.set(ctx.app.policy.workspace) + try: + return _func(**kwargs) + finally: + code_tools._workspace.reset(token) + access = "write" if name in {"write", "edit"} else "read" + ctx.tool(Tool(name, description["description"], description["parameters"], executor, access)) + return Plugin("tools", setup) diff --git a/miniagent/policy.py b/miniagent/policy.py new file mode 100644 index 0000000..52f9a72 --- /dev/null +++ b/miniagent/policy.py @@ -0,0 +1,33 @@ +"""Authorization for managed tools; arbitrary shell/plugins are not isolated.""" +import inspect +from pathlib import Path + + +class Policy: + def __init__(self, workspace=None, mode="confirm", approve=None): + if mode not in {"readonly", "confirm", "trusted"}: + raise ValueError("Policy must be readonly, confirm or trusted") + self.workspace = Path(workspace or Path.cwd()).resolve() + self.mode, self.approve = mode, approve + + def path(self, value): + path = Path(value).expanduser() + path = (path if path.is_absolute() else self.workspace / path).resolve() + if not path.is_relative_to(self.workspace): + raise PermissionError("Path is outside workspace") + return path + + async def authorize(self, tool, arguments): + if tool.access in {"read", "write"}: + arguments["path"] = str(self.path(arguments.get("path", "."))) + if tool.access == "read": + return + if self.mode == "readonly": + raise PermissionError("Read-only policy") + if self.mode == "trusted": + return + accepted = self.approve(tool.name, dict(arguments)) if self.approve else False + if inspect.isawaitable(accepted): + accepted = await accepted + if accepted is not True: + raise PermissionError("Tool execution denied") diff --git a/miniagent/tools/code_tools.py b/miniagent/tools/code_tools.py index 72df5fa..3db5846 100644 --- a/miniagent/tools/code_tools.py +++ b/miniagent/tools/code_tools.py @@ -9,6 +9,7 @@ import os import re import subprocess +from contextvars import ContextVar from pathlib import Path from typing import Any, Dict, List, Optional, Tuple @@ -17,12 +18,17 @@ from ..utils.text_utils import smart_truncate logger = get_logger(__name__) +_workspace = ContextVar("miniagent_workspace", default=None) def _resolve_path(path: str) -> Path: p = Path(path).expanduser() if not p.is_absolute(): p = (Path.cwd() / p).resolve() + p = p.resolve() + workspace = _workspace.get() + if workspace is not None and not p.is_relative_to(workspace): + raise PermissionError("Path is outside workspace") return p @@ -42,7 +48,9 @@ def _iter_files(root: Path) -> List[Path]: return [root] if not root.exists(): return [] - return [p for p in root.rglob("*") if p.is_file()] + workspace = _workspace.get() + return [p for p in root.rglob("*") if p.is_file() + and (workspace is None or p.resolve().is_relative_to(workspace))] @register_tool @@ -146,7 +154,9 @@ def glob(pattern: str, path: str = ".") -> List[str]: # noqa: A002 return [] try: matches = root.glob(pattern) - return [str(p.resolve()) for p in matches] + workspace = _workspace.get() + return [str(p.resolve()) for p in matches + if workspace is None or p.resolve().is_relative_to(workspace)] except Exception as e: logger.exception("glob failed") return [f"error: glob failed: {e}"] diff --git a/miniagent/tools/registry.py b/miniagent/tools/registry.py new file mode 100644 index 0000000..995c0e9 --- /dev/null +++ b/miniagent/tools/registry.py @@ -0,0 +1,52 @@ +"""Instance-owned tools. The decorator registry is only a declaration catalog.""" +import inspect +from dataclasses import dataclass +from typing import Callable + +from jsonschema import Draft202012Validator + + +@dataclass +class Tool: + name: str + description: str + parameters: dict + executor: Callable + access: str = "external" + + def schema(self): + return {"type": "function", "function": { + "name": self.name, "description": self.description, + "parameters": self.parameters, + }} + + +class Registry: + def __init__(self): + self.tools = {} + self.allowed = None + + def add(self, tool): + if tool.name in self.tools: + raise ValueError(f"Duplicate tool: {tool.name}") + Draft202012Validator.check_schema(tool.parameters) + self.tools[tool.name] = tool + + def get(self, name): + if self.allowed is not None and name not in self.allowed: + raise PermissionError(f"Skill disallows tool: {name}") + if name not in self.tools: + raise LookupError(f"Unknown tool: {name}") + return self.tools[name] + + def schemas(self): + return [t.schema() for n, t in self.tools.items() + if self.allowed is None or n in self.allowed] + + async def execute(self, name, arguments, policy): + tool = self.get(name) + Draft202012Validator(tool.parameters).validate(arguments) + arguments = dict(arguments) + await policy.authorize(tool, arguments) + result = tool.executor(**arguments) + return await result if inspect.isawaitable(result) else result diff --git a/pyproject.toml b/pyproject.toml index 4f1ecd7..3168953 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,7 @@ name = "miniagent" version = "0.1.0" description = "A minimalist CLI Agent framework for learning AI Agents" readme = "README.md" -requires-python = ">=3.8" +requires-python = ">=3.11" license = { text = "Apache-2.0" } authors = [ { name = "MiniAgent Team", email = "miniagent@example.com" }, @@ -28,15 +28,13 @@ classifiers = [ "Intended Audience :: Science/Research", "License :: OSI Approved :: Apache Software License", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: Software Development :: Libraries :: Python Modules", ] dependencies = [ + "jsonschema>=4.20,<5", "distro>=1.8.0", "openai>=1.0.0", "psutil>=5.9.0", diff --git a/setup.py b/setup.py index 8d88689..313e069 100644 --- a/setup.py +++ b/setup.py @@ -1,66 +1,4 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- +"""Compatibility entry point; packaging metadata lives in pyproject.toml.""" +from setuptools import setup -from pathlib import Path - -from setuptools import find_packages, setup - -# Read README with explicit UTF-8 encoding (fixes Windows GBK error) -readme_path = Path(__file__).parent / "README.md" -long_description = readme_path.read_text(encoding="utf-8") if readme_path.exists() else "" - -setup( - name="miniagent", - version="0.1.0", - packages=find_packages(), - install_requires=[ - "openai>=1.0.0", - "python-dotenv>=0.19.0", - "tenacity>=8.0.0", - "requests>=2.31.0", - "psutil>=5.9.0", - "distro>=1.8.0", - "rich>=13.0.0", - ], - extras_require={ - "docx": ["python-docx>=0.8.11"], - "dev": ["pytest>=8.0.0,<9"], - }, - author="MiniAgent Team", - author_email="miniagent@example.com", - description="A minimalist CLI Agent framework — the best textbook for understanding AI Agents", - long_description=long_description, - long_description_content_type="text/markdown", - url="https://github.com/ZhuLinsen/MiniAgent", - project_urls={ - "Bug Tracker": "https://github.com/ZhuLinsen/MiniAgent/issues", - "Source": "https://github.com/ZhuLinsen/MiniAgent", - "Documentation": "https://github.com/ZhuLinsen/MiniAgent#readme", - }, - keywords=[ - "agent", "ai", "llm", "cli", "tool-calling", "miniagent", - "deepseek", "openai", "code-generation", "automation", "agentic", - ], - license="Apache-2.0", - classifiers=[ - "Development Status :: 3 - Alpha", - "Intended Audience :: Developers", - "Intended Audience :: Education", - "Intended Audience :: Science/Research", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - "Topic :: Scientific/Engineering :: Artificial Intelligence", - "Topic :: Software Development :: Libraries :: Python Modules", - ], - python_requires=">=3.8", - entry_points={ - "console_scripts": [ - "miniagent=miniagent.cli:main", - ] - }, -) +setup() diff --git a/tests/test_harness.py b/tests/test_harness.py new file mode 100644 index 0000000..cd8973b --- /dev/null +++ b/tests/test_harness.py @@ -0,0 +1,152 @@ +import asyncio +import sys + +import pytest + +from miniagent import Harness, Plugin +from miniagent.policy import Policy +from miniagent.plugins import coding_tools, shell +from miniagent.tools.registry import Tool + + +def run(coro): + return asyncio.run(coro) + + +def tool(name="add", executor=lambda n: n + 1): + return Tool(name, "add", {"type": "object", "properties": {"n": {"type": "integer"}}, + "required": ["n"], "additionalProperties": False}, executor) + + +def test_rollback_and_instance_isolation(): + async def scenario(): + first, second = Harness(), Harness() + first.use(Plugin("base", lambda c: c.service("value", 1))) + def broken(c): + c.tool(tool()) + c.on("test", lambda e: None) + raise RuntimeError("broken") + first.use(Plugin("broken", broken, ("base",))) + with pytest.raises(RuntimeError): + await first.start() + assert not first.services and not first.registry.tools and not first.active + assert first.events["test"] == [] + second.use(Plugin("base", lambda c: c.service("value", 2))) + await second.start() + assert second.services["value"] == 2 + assert not first.services + await second.aclose() + run(scenario()) + + +def test_dependency_order_cycle_and_unload(): + async def scenario(): + order = [] + app = Harness() + app.use(Plugin("child", lambda c: order.append(c.get("value")), ("base",))) + app.use(Plugin("base", lambda c: c.service("value", 42))) + await app.start() + assert order == [42] + with pytest.raises(ValueError): + await app.unuse("base") + await app.unuse("child") + await app.unuse("base") + app.use(Plugin("a", lambda c: None, ("b",))) + app.use(Plugin("b", lambda c: None, ("a",))) + with pytest.raises(ValueError): + await app.start() + run(scenario()) + + +def test_cleanup_continues_after_failure(): + async def scenario(): + cleaned = [] + app = Harness() + app.use(Plugin("good", lambda c: c.cleanup(cleaned.append, "good"))) + def bad(c): + c.service("x", 1) + def fail(): + raise ValueError("cleanup") + c.cleanup(fail) + app.use(Plugin("bad", bad)) + await app.start() + with pytest.raises(BaseExceptionGroup): + await app.aclose() + assert cleaned == ["good"] and not app.services + run(scenario()) + + +def test_policy_denial_validation_and_whitelist(): + async def scenario(): + app = Harness() + app.registry.add(tool()) + with pytest.raises(PermissionError): + await app.registry.execute("add", {"n": 1}, app.policy) + app.registry.allowed = set() + with pytest.raises(PermissionError): + await app.registry.execute("add", {"n": 1}, Policy(mode="trusted")) + app.registry.allowed = None + from jsonschema import ValidationError + with pytest.raises(ValidationError): + await app.registry.execute("add", {"n": "bad"}, Policy(mode="trusted")) + run(scenario()) + + +def test_workspace_escape_and_symlink(tmp_path): + outside = tmp_path / "outside" + outside.mkdir() + (outside / "secret").write_text("secret") + root = tmp_path / "root" + root.mkdir() + policy = Policy(root) + with pytest.raises(PermissionError): + policy.path("../outside/new") + try: + (root / "link").symlink_to(outside, target_is_directory=True) + except OSError: + return # Windows may require symlink privilege; traversal remains covered. + async def scenario(): + app = Harness(policy=policy).use(coding_tools()) + await app.start() + found = await app.registry.execute("grep", {"pattern": "secret"}, policy) + assert not found + await app.aclose() + run(scenario()) + + +def test_async_loop_busy_and_tool_results(): + class Backend: + async def complete(self, messages, tools, stream): + await asyncio.sleep(0) + if messages[-1]["role"] == "user": + return {"role": "assistant", "content": None, "tool_calls": [{ + "id": "call1", "type": "function", "function": {"name": "add", "arguments": '{"n": 1}'}}]} + assert messages[-1]["tool_call_id"] == "call1" + return {"role": "assistant", "content": messages[-1]["content"]} + async def scenario(): + app = Harness(Backend(), policy=Policy(mode="trusted")) + app.use(Plugin("math", lambda c: c.tool(tool()))) + task = asyncio.create_task(app.arun("go")) + await asyncio.sleep(0) + with pytest.raises(RuntimeError): + app.use(Plugin("other", lambda c: None)) + with pytest.raises(RuntimeError): + await app.arun("again") + assert await task == "2" + with pytest.raises(RuntimeError): + app.run("go") + await app.aclose() + run(scenario()) + + +def test_shell_timeout_and_cancel(tmp_path): + async def scenario(): + command = f'"{sys.executable}" -c "import time; time.sleep(30)"' + with pytest.raises(TimeoutError): + await shell(command, cwd=str(tmp_path), timeout=.1) + task = asyncio.create_task(shell(command, cwd=str(tmp_path))) + await asyncio.sleep(.1) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + run(scenario())