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: 2 additions & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@
- [修复] CLI 不再重复注入当前用户消息,日志不再输出 API Key 前缀。
- [改进] 默认 CLI 工具限制为 Coding Tools;原有基础工具保持显式可用。
- [文档] 记录六阶段迁移、权限边界和可复现源码统计。
- [新功能] 异步 Harness、实例级工具、静态插件生命周期和统一授权入口。
- [改进] Python 最低版本提升至 3.11,打包元数据统一到 pyproject.toml。
3 changes: 3 additions & 0 deletions miniagent/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
36 changes: 36 additions & 0 deletions miniagent/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
160 changes: 160 additions & 0 deletions miniagent/harness.py
Original file line number Diff line number Diff line change
@@ -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()
64 changes: 64 additions & 0 deletions miniagent/plugins.py
Original file line number Diff line number Diff line change
@@ -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)
33 changes: 33 additions & 0 deletions miniagent/policy.py
Original file line number Diff line number Diff line change
@@ -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")
14 changes: 12 additions & 2 deletions miniagent/tools/code_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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


Expand All @@ -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
Expand Down Expand Up @@ -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}"]
Expand Down
Loading
Loading