本文最后更新于85 天前,其中的信息可能已经过时,如有错误请发送邮件到 2915475627@qq.com
介绍
整个函数主要这三件事
-
解析命令行参数
-
初始化 run_agent
-
交互模式/非交互模式
cli.py 是 main() 函数,整个程序的入口。
agent.py 只定义了 run(),在 cli.py 里根据 交互模式/非交互模式 调用。
解析命令行参数
def main():
args = parse_args() # ① 解析命令行参数
if args.command == "log": # ② 子命令:看日志
show_log_directory(...)
return
workspace_dir = ... # ③ 确定工作目录
asyncio.run(run_agent(workspace_dir, task=args.task))
mini-agent # 交互模式,当前目录
mini-agent --workspace /path # 交互模式,指定目录
mini-agent --task "创建文件" # 一次性任务
mini-agent log # 查看日志目录
mini-agent log agent_run_xxx.log # 查看指定日志
初始化 run_agent
① 加载配置 Config.from_yaml(config.yaml)
② 初始化 LLMClient 根据 provider 创建,配重试
③ 加载基础工具 BashOutput, BashKill, Skills, MCP ← 不依赖 workspace
④ 加载 workspace 工具 Bash, Read, Write, Edit, SessionNote ← 需要知道工作目录
⑤ 加载 System Prompt 从文件读,注入 Skills metadata
⑥ 创建 Agent 传入 llm_client + tools + system_prompt
⑦ 非交互模式 add_user_message → run → 打印统计 → 退出
⑧ 交互模式 prompt_toolkit 循环,每轮 add → run
交互模式
斜杠命令
while True:
user_input = await session.prompt_async() # prompt_toolkit 输入
if user_input.startswith("/"):
/help → 打印帮助
/clear → 清空消息历史(保留 system prompt)
/history → 查看消息数
/stats → 会话统计
/log → 日志目录
/log xxx → 查看日志文件
/exit → 退出
普通任务
# 非命令 → 交给 Agent 执行
agent.add_user_message(user_input)
cancel_event = asyncio.Event() # 创建取消信号
esc线程监听 Esc 键 → cancel_event.set()
agent_task = asyncio.create_task(agent.run()) # Agent 跑起来
while not agent_task.done(): # 轮询取消
if esc_pressed:
cancel_event.set()
await asyncio.sleep(0.1)
非交互模式
# 8.5 Non-interactive mode: execute task and exit
if task:
print(f"\n{Colors.BRIGHT_BLUE}Agent{Colors.RESET} {Colors.DIM}›{Colors.RESET} {Colors.DIM}Executing task...{Colors.RESET}\n")
agent.add_user_message(task)
try:
await agent.run()
except Exception as e:
print(f"\n{Colors.RED}❌ Error: {e}{Colors.RESET}")
finally:
print_stats(agent, session_start)