Download testing/nano_simulation_agents/src/nano_python_agents/cli.py from yuhanqin/ut-evaluation: direct link, hf CLI and curl.
- Browser
- Download file 8.34 kB
-
https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/nano_simulation_agents/src/nano_python_agents/cli.py
- Command line
-
hf download hf://datasets/yuhanqin/ut-evaluation/testing/nano_simulation_agents/src/nano_python_agents/cli.py
-
curl -L -o cli.py https://huggingface.co/datasets/yuhanqin/ut-evaluation/resolve/main/testing/nano_simulation_agents/src/nano_python_agents/cli.py
8.34 kB
| """Command-line entry point, approvals, and interactive sessions.""" | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| from pathlib import Path | |
| from nano_python_agents.config import ConfigError, Settings, load_config | |
| from nano_python_agents.events import EventLogger | |
| from nano_python_agents.gateway import ApprovalRequest, Gateway | |
| from nano_python_agents.loop import AgentLoop, MaxTurnsExceeded | |
| from nano_python_agents.prompt_loader import PromptError, PromptRegistry | |
| from nano_python_agents.providers.base import ProviderError, RetryingProvider | |
| from nano_python_agents.providers.openai_api import OpenAIChatCompletionsProvider | |
| from nano_python_agents.skill_registry import SkillError, SkillRegistry | |
| from nano_python_agents.tools import WorkspaceTools | |
| from nano_python_agents.todo import TodoError, TodoStore | |
| def terminal_approval(request: ApprovalRequest) -> bool: | |
| print("\n" + "=" * 72) | |
| print(request.summary) | |
| print("-" * 72) | |
| print(request.detail or "(no detail)") | |
| print("=" * 72) | |
| while True: | |
| answer = input("Approve? [y/N] ").strip().lower() | |
| if answer in {"y", "yes"}: | |
| return True | |
| if answer in {"", "n", "no"}: | |
| return False | |
| def _build_provider(settings: Settings) -> RetryingProvider: | |
| environment_name = settings.provider.api_key_env | |
| api_key = os.environ.get(environment_name) | |
| if not api_key: | |
| raise ConfigError(f"required API key environment variable is not set: {environment_name}") | |
| provider = OpenAIChatCompletionsProvider( | |
| api_key=api_key, | |
| base_url=settings.provider.base_url, | |
| model=settings.provider.model, | |
| max_tokens=settings.provider.max_tokens, | |
| temperature=settings.provider.temperature, | |
| ) | |
| return RetryingProvider(provider, max_attempts=3) | |
| def _run_one(loop: AgentLoop, task: str) -> int: | |
| try: | |
| answer = loop.run(task) | |
| except KeyboardInterrupt: | |
| print("\n[cancelled] The interrupted tool batch was paired with cancellation results.", file=sys.stderr) | |
| return 130 | |
| except MaxTurnsExceeded as error: | |
| print(f"\n[stopped] {error}", file=sys.stderr) | |
| return 1 | |
| except ProviderError as error: | |
| print(f"\n[provider error: {error.kind}] {error}", file=sys.stderr) | |
| return 1 | |
| print("\n" + answer) | |
| return 0 | |
| def _resolve_asset_dirs(workspace_root: Path, configured: list[str]) -> list[Path]: | |
| return [path if path.is_absolute() else workspace_root / path for path in map(Path, configured)] | |
| def main(argv: list[str] | None = None) -> int: | |
| parser = argparse.ArgumentParser( | |
| prog="nano-agent", | |
| description="Minimal native-tool coding agent for a fixed local workspace.", | |
| ) | |
| parser.add_argument( | |
| "-w", | |
| "--workspace", | |
| default=".", | |
| help="workspace root directory (default: current directory)", | |
| ) | |
| parser.add_argument( | |
| "--system-prompt", | |
| dest="system_prompts", | |
| action="append", | |
| metavar="ID", | |
| help="prompt identifier to use (repeatable); overrides config [prompts].system", | |
| ) | |
| parser.add_argument( | |
| "--list-prompts", | |
| action="store_true", | |
| help="list available prompt identifiers and exit", | |
| ) | |
| parser.add_argument( | |
| "--list-skills", | |
| action="store_true", | |
| help="list available skill identifiers and exit", | |
| ) | |
| parser.add_argument( | |
| "--list-tools", | |
| action="store_true", | |
| help="list native tools available for this workspace and exit", | |
| ) | |
| parser.add_argument("task", nargs="?", help="task text; omit for interactive mode") | |
| args = parser.parse_args(argv) | |
| workspace_root = Path(args.workspace).resolve() | |
| if not workspace_root.is_dir(): | |
| print(f"error: workspace does not exist: {workspace_root}", file=sys.stderr) | |
| return 2 | |
| try: | |
| settings = load_config(workspace_root) | |
| except (ConfigError, OSError) as error: | |
| print(f"error: {error}", file=sys.stderr) | |
| return 2 | |
| extra_prompt_dirs = _resolve_asset_dirs(workspace_root, settings.prompts.directories) | |
| extra_skill_dirs = _resolve_asset_dirs(workspace_root, settings.skills.directories) | |
| try: | |
| prompt_registry = PromptRegistry(extra_dirs=extra_prompt_dirs) | |
| skill_registry = SkillRegistry(extra_dirs=extra_skill_dirs) | |
| except (PromptError, SkillError) as error: | |
| print(f"error: {error}", file=sys.stderr) | |
| return 2 | |
| if args.list_prompts: | |
| for info in prompt_registry.infos(): | |
| print(f"{info.name} {info.source}") | |
| return 0 | |
| if args.list_skills: | |
| for entry in skill_registry.compact_index(): | |
| print(f"{entry['name']} v{entry['version']} {entry['description']}") | |
| return 0 | |
| prompt_ids = args.system_prompts if args.system_prompts else settings.prompts.system | |
| try: | |
| system_prompt = prompt_registry.compose( | |
| prompt_ids, | |
| workspace=str(workspace_root), | |
| ) | |
| except PromptError as error: | |
| print(f"error: {error}", file=sys.stderr) | |
| return 2 | |
| skill_reg = skill_registry if skill_registry.names() else None | |
| events = EventLogger(workspace_root) | |
| todo_store = None | |
| if settings.todo.enabled: | |
| try: | |
| todo_store = TodoStore( | |
| workspace_root, | |
| ledger_path=settings.todo.ledger_path, | |
| contract_path=settings.todo.contract_path, | |
| run_id=settings.todo.run_id, | |
| writer_session=settings.todo.writer_session, | |
| event_logger=events, | |
| ) | |
| except TodoError as error: | |
| print(f"error: {error}", file=sys.stderr) | |
| return 2 | |
| workspace_tools = WorkspaceTools( | |
| workspace_root, | |
| max_output_chars=settings.agent.max_tool_output_chars, | |
| test_command=settings.workspace.test_command, | |
| test_timeout_seconds=settings.workspace.test_timeout_seconds, | |
| ) | |
| gateway = Gateway( | |
| workspace_tools, | |
| terminal_approval, | |
| events, | |
| skill_registry=skill_reg, | |
| todo_store=todo_store, | |
| ) | |
| if args.list_tools: | |
| # Diagnostics must work without an API credential; provider startup is | |
| # intentionally deferred until an actual task is requested. | |
| workspace_tools = WorkspaceTools( | |
| workspace_root, | |
| max_output_chars=settings.agent.max_tool_output_chars, | |
| test_command=settings.workspace.test_command, | |
| test_timeout_seconds=settings.workspace.test_timeout_seconds, | |
| ) | |
| gateway = Gateway( | |
| workspace_tools, | |
| terminal_approval, | |
| events, | |
| skill_registry=skill_reg, | |
| todo_store=todo_store, | |
| ) | |
| for schema in gateway.schemas(): | |
| print(schema.name) | |
| return 0 | |
| try: | |
| provider = _build_provider(settings) | |
| except (ConfigError, OSError) as error: | |
| print(f"error: {error}", file=sys.stderr) | |
| return 2 | |
| if skill_reg is not None: | |
| index_lines = "\n".join( | |
| f"- {e['name']} (v{e['version']}): {e['description']}" | |
| for e in skill_reg.compact_index() | |
| ) | |
| system_prompt = system_prompt + f"\n\n## Available Skills\n\n{index_lines}" | |
| loop = AgentLoop( | |
| provider, | |
| gateway, | |
| system_prompt=system_prompt, | |
| max_turns=settings.agent.max_turns, | |
| event_logger=events, | |
| ) | |
| print(f"workspace: {workspace_root}") | |
| print(f"provider: openai-compatible | model: {settings.provider.model}") | |
| print(f"max_turns: {settings.agent.max_turns} | session log: {events.path}") | |
| if settings.workspace.test_command: | |
| print("test command: " + " ".join(settings.workspace.test_command)) | |
| else: | |
| print("test command: (none configured; run_tests disabled)") | |
| if args.task: | |
| return _run_one(loop, args.task) | |
| print("interactive mode; empty line or Ctrl-D to exit") | |
| while True: | |
| try: | |
| task = input("\ntask> ").strip() | |
| except EOFError: | |
| print() | |
| return 0 | |
| except KeyboardInterrupt: | |
| print() | |
| return 130 | |
| if not task: | |
| return 0 | |
| _run_one(loop, task) | |