Skip to content

[Bug] 使用 @register_agent 装饰器注册 Subagent 时,加载插件会失败并报错 #5721

@evpeople

Description

@evpeople

What happened / 发生了什么

在插件中使用 @register_agent 装饰器注册 Subagent 时,加载插件会失败并报错

NameError: name 'AstrAgentContext' is not defined

这个 Bug 会导致第三方插件无法使用 @register_agent 装饰器在代码中注册 Subagent。

Reproduce / 如何复现?

from astrbot.core.star.register.star_handler import register_agent

@register_agent(
    name="test_agent",
    instruction="你是一个测试助手"
)
async def test_agent(event, context):
    return "hello"
  1. 启动 AstrBot,加载该插件
  2. 观察报错:NameError: name 'AstrAgentContext' is not defined

AstrBot version, deployment method (e.g., Windows Docker Desktop deployment), provider used, and messaging platform used. / AstrBot 版本、部署方式(如 Windows Docker Desktop 部署)、使用的提供商、使用的消息平台适配器

main分支当前最新代码 101580f

uv run main.py 启动

OS

Linux

Logs / 报错日志

[23:38:14.671] [Core] [ERRO] [v4.18.3] [star.star_manager:629]: Traceback (most recent call last):
File "/home/evpeople/pi_dev/AstrBot/astrbot/core/star/star_manager.py", line 621, in load
module = await self._import_plugin_with_dependency_recovery(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/evpeople/pi_dev/AstrBot/astrbot/core/star/star_manager.py", line 218, in _import_plugin_with_dependency_recovery
return import(path, fromlist=[module_str])
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/evpeople/pi_dev/AstrBot/data/plugins/astrbot_plugin_companion/main.py", line 454, in
@register_agent(
^^^^^^^^^^^^^^^
File "/home/evpeople/pi_dev/AstrBot/astrbot/core/star/register/star_handler.py", line 644, in decorator
AstrAgent = Agent[AstrAgentContext]
^^^^^^^^^^^^^^^^
NameError: name 'AstrAgentContext' is not defined

来自AI的问题根源分析

astrbot/core/star/register/star_handler.py 中:

  1. 最初版本(commit 1df49d1d)直接导入了 AstrAgentContext,功能正常
  2. 后来为了解决循环导入问题(commit 2a6863cf),改成了 TYPE_CHECKING 导入:
if TYPE_CHECKING:
    from astrbot.core.astr_agent_context import AstrAgentContext
  1. 但同时把 Agent[Any] 改成了 Agent[AstrAgentContext],导致运行时需要访问 AstrAgentContext 类,但该类并未被真正导入(TYPE_CHECKING 仅在类型检查时生效)

相关代码位置

  • Bug 引入 commit: 2a6863cf (2026-03-01)
  • 问题文件: astrbot/core/star/register/star_handler.py
  • 问题行号: 第 644 行、645 行
# star_handler.py 第 644-645 行
AstrAgent = Agent[AstrAgentContext]  # 运行时执行,但类未导入
agent = AstrAgent(
    ...
    run_hooks=run_hooks or BaseAgentRunHooks[AstrAgentContext](),
)

Are you willing to submit a PR? / 你愿意提交 PR 吗?

  • Yes!

Code of Conduct

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:coreThe bug / feature is about astrbot's core, backendbugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions