agentscope-java icon indicating copy to clipboard operation
agentscope-java copied to clipboard

[Bug]: ReActAgent.Builder.build() toolkit deep copy causes dynamically-registered middleware tools to be missing from the agent's actual toolkit

Open lwx11111 opened this issue 5 months ago • 6 comments

Summary

ReActAgent.Builder.build() performs a defensive toolkit.copy() (line 3077), which creates a second copy of the toolkit. When a middleware (e.g., HarnessSkillMiddleware) holds a reference to the first copy and dynamically registers tools onto it during call(), those tools are invisible to the agent because the agent uses the second copy. This results in Tool not found errors at runtime.

Environment

  • AgentScope Java: current main
  • Component: agentscope-core (ReActAgent), agentscope-harness (HarnessAgent, HarnessSkillMiddleware)

Root Cause

In HarnessAgent.Builder.build() (HarnessAgent.java ~L1520-1902):

// Step 1: First defensive copy
Toolkit agentToolkit = this.toolkit.copy();          // ← Copy 1

// Step 2: Middleware receives Copy 1
inner.middleware(
    new HarnessSkillMiddleware(
        orderedSkillRepos,
        agentToolkit,                                 // ← Copy 1 passed to middleware
        skillFilter, ...));

// Step 3: Pass Copy 1 to inner builder
inner.toolkit(agentToolkit);                          // ← Copy 1

// Step 4: inner.build() does ANOTHER copy
ReActAgent delegate = inner.build();
// → ReActAgent.Builder.build() line 3077:
//    Toolkit agentToolkit = this.toolkit.copy();     // ← Copy 2 (the one the agent actually uses)

The lifecycle at call() time:

agent.call()
  → seedSystemMsg()
    → applySystemPromptMiddlewares()
      → HarnessSkillMiddleware.onSystemPrompt()
        → runtime.install(catalog, toolkit)
          → toolkit.registerAgentTool(loadTool)       // ← Registered on Copy 1
  → ...
  → toolkit.getToolSchemas()                          // ← Reads from Copy 2 → load_skill_through_path is MISSING
  → LLM generates tool_call: load_skill_through_path
  → Toolkit.getTool("load_skill_through_path")        // ← Looks up in Copy 2 → returns null
  → "Error: Tool not found: load_skill_through_path"

Reproduction Steps

  1. Build a HarnessAgent with skillRepository(...) configured
  2. Call agent.call() with a user message
  3. The LLM sees the <available_skills> prompt block (rendered by middleware) and generates a load_skill_through_path tool call
  4. The framework returns "Error: Tool not found: load_skill_through_path"

Debug Evidence

Setting breakpoints at the following locations confirms the issue:

# Class Line Observation
1 HarnessSkillMiddleware mergeRepositories() repo.getAllSkills() returns 2 skills — correct
2 HarnessSkillMiddleware onSystemPrompt() ~L177 catalog.ids() contains 2 skill IDs — correct
3 SkillLoadTool getParameters() Breakpoint never hit — ToolSchemaProvider uses registered.getExtendedParameters() (captured at registration time), not tool.getParameters()
4 ToolSchemaProvider getToolSchemas() Returns 17 tools — load_skill_through_path is absent
5 ReActAgent ~L1045 toolkit.getToolSchemas() returns 17 tools — load_skill_through_path is absent
6 Toolkit getTool("load_skill_through_path") toolRegistry has 17 tools, load_skill_through_path is not among them

The middleware registers load_skill_through_path on Copy 1, but the agent's toolkit (Copy 2) never receives it.

Impact

  • Any middleware that dynamically registers tools during onSystemPrompt() or onReasoning() is affected, not just HarnessSkillMiddleware
  • The DynamicSkillMiddleware in agentscope-core (ReActAgent.java ~L3104-3110) has the same problem — it receives agentToolkit (which is already a copy) and registers tools onto it, but the agent uses a further copy
  • This makes the entire skill-loading feature non-functional for HarnessAgent

Suggested Fix

Option A (Recommended): In ReActAgent.Builder.build(), after creating the deep copy, propagate the copy back to any middleware that holds a reference to the old toolkit. For example, add a rebindToolkit(Toolkit newToolkit) method to MiddlewareBase (default no-op), and call it for each middleware after the copy:

// ReActAgent.Builder.build()
Toolkit agentToolkit = this.toolkit.copy();

// Rebind middlewares to the new toolkit copy
for (MiddlewareBase mw : middlewares) {
    mw.rebindToolkit(agentToolkit);  // default no-op, HarnessSkillMiddleware overrides
}

Option B: In HarnessAgent.Builder.build(), skip the first copy and pass the builder's toolkit directly to inner, letting ReActAgent.Builder.build() be the single point of deep copy. Then pass the same agentToolkit reference (the one from inner.build()) to the middleware. This requires restructuring the build sequence.

Option C (Minimal): In HarnessSkillMiddleware.onSystemPrompt(), instead of registering the tool on the toolkit passed at construction time, resolve the agent's actual toolkit from the Agent parameter and register there:

@Override
public Mono<String> onSystemPrompt(Agent agent, String currentPrompt) {
    // Resolve the agent's actual toolkit instead of using the construction-time reference
    Toolkit actualToolkit = resolveToolkit(agent);
    runtime.install(catalog, actualToolkit);
    ...
}

This requires AgentBase or ReActAgent to expose a getToolkit() method (which HarnessAgent already does, but Agent interface does not).

Workaround

We currently work around this by using reflection after agentBuilder.build() to extract the SkillLoadTool from the middleware's SkillRuntime and register it onto the agent's actual toolkit:

HarnessAgent agent = agentBuilder.build();
fixSkillLoadToolAfterBuild(agent);

private void fixSkillLoadToolAfterBuild(HarnessAgent agent) {
    ReActAgent delegate = agent.getDelegate();
    Field middlewaresField = ReActAgent.class.getDeclaredField("middlewares");
    middlewaresField.setAccessible(true);
    List<MiddlewareBase> middlewares = (List<MiddlewareBase>) middlewaresField.get(delegate);
    for (MiddlewareBase mw : middlewares) {
        if (mw.getClass().getSimpleName().equals("HarnessSkillMiddleware")) {
            Method runtimeMethod = mw.getClass().getMethod("runtime");
            Object runtime = runtimeMethod.invoke(mw);
            Method loadToolMethod = runtime.getClass().getMethod("loadTool");
            Object loadTool = loadToolMethod.invoke(runtime);
            Toolkit actualToolkit = agent.getToolkit();
            if (actualToolkit.getTool("load_skill_through_path") == null) {
                actualToolkit.registerAgentTool((AgentTool) loadTool);
            }
            return;
        }
    }
}

This works because SkillLoadTool holds an AtomicReference<SkillCatalog> shared with the middleware, so catalog updates from subsequent onSystemPrompt() calls are automatically visible.

lwx11111 avatar Jun 04 '26 11:06 lwx11111

ReActAgent.Builder.build() 执行了防御性的 toolkit.copy()(第 3077 行),创建了 toolkit 的第二份拷贝。当中间件(如 HarnessSkillMiddleware)持有第一份拷贝的引用并在 call() 期间动态注册工具时,这些工具对 agent 是不可见的,因为 agent 使用的是第二份拷贝。这会导致运行时出现 Tool not found 错误。

环境

  • AgentScope Java:当前 main 分支
  • 组件:agentscope-core(ReActAgent)、agentscope-harness(HarnessAgent、HarnessSkillMiddleware)

根因

在 HarnessAgent.Builder.build() 中(HarnessAgent.java 约第 1520-1902 行):

// 第一步:第一次防御性拷贝
Toolkit agentToolkit = this.toolkit.copy();          // ← 拷贝1

// 第二步:中间件接收拷贝1
inner.middleware(
    new HarnessSkillMiddleware(
        orderedSkillRepos,
        agentToolkit,                                 // ← 拷贝1 传给中间件
        skillFilter, ...));

// 第三步:将拷贝1 传给内部 builder
inner.toolkit(agentToolkit);                          // ← 拷贝1

// 第四步:inner.build() 又做了一次拷贝
ReActAgent delegate = inner.build();
// → ReActAgent.Builder.build() 第 3077 行:
//    Toolkit agentToolkit = this.toolkit.copy();     // ← 拷贝2(agent 实际使用的)

call() 时的生命周期:

agent.call()
  → seedSystemMsg()
    → applySystemPromptMiddlewares()
      → HarnessSkillMiddleware.onSystemPrompt()
        → runtime.install(catalog, toolkit)
          → toolkit.registerAgentTool(loadTool)       // ← 注册到拷贝1 上
  → ...
  → toolkit.getToolSchemas()                          // ← 从拷贝2 读取 → load_skill_through_path 不存在
  → LLM 生成 tool_call: load_skill_through_path
  → Toolkit.getTool("load_skill_through_path")        // ← 在拷贝2 中查找 → 返回 null
  → "Error: Tool not found: load_skill_through_path"

复现步骤

  1. 构建一个配置了 skillRepository(...) 的 HarnessAgent
  2. 用用户消息调用 agent.call()
  3. LLM 看到中间件渲染的 <available_skills> 提示块,生成 load_skill_through_path 工具调用
  4. 框架返回 "Error: Tool not found: load_skill_through_path"

调试验证

在以下位置设置断点可确认问题:

# 类 行 观察结果
1 HarnessSkillMiddleware mergeRepositories() repo.getAllSkills() 返回 2 个 skill — 正确
2 HarnessSkillMiddleware onSystemPrompt() 约第 177 行 catalog.ids() 包含 2 个 skill ID — 正确
3 SkillLoadTool getParameters() 断点未命中 — ToolSchemaProvider 使用 registered.getExtendedParameters()(注册时捕获的快照),而非 tool.getParameters()
4 ToolSchemaProvider getToolSchemas() 返回 17 个工具 — load_skill_through_path 缺失
5 ReActAgent 约第 1045 行 toolkit.getToolSchemas() 返回 17 个工具 — load_skill_through_path 缺失
6 Toolkit getTool("load_skill_through_path") toolRegistry 有 17 个工具,load_skill_through_path 不在其中

中间件将 load_skill_through_path 注册到了拷贝1,但 agent 的 toolkit(拷贝2)从未收到它。

影响范围

  • 任何在 onSystemPrompt() 或 onReasoning() 期间动态注册工具的中间件都会受影响,不仅限于 HarnessSkillMiddleware
  • agentscope-core 中的 DynamicSkillMiddleware(ReActAgent.java 约第 3104-3110 行)也有同样的问题 — 它接收的 agentToolkit 已经是一份拷贝,在上面注册工具后,agent 使用的却是更深一层的拷贝
  • 这导致 HarnessAgent 的整个 skill 加载功能完全不可用

建议修复方案

方案 A(推荐): 在 ReActAgent.Builder.build() 中,创建深拷贝后,将新拷贝回传给所有持有旧 toolkit 引用的中间件。例如,在 MiddlewareBase 中添加 rebindToolkit(Toolkit newToolkit) 方法(默认空实现),深拷贝后对每个中间件调用:

// ReActAgent.Builder.build()
Toolkit agentToolkit = this.toolkit.copy();

// 将中间件重新绑定到新的 toolkit 拷贝
for (MiddlewareBase mw : middlewares) {
    mw.rebindToolkit(agentToolkit);  // 默认空实现,HarnessSkillMiddleware 覆写
}

方案 B: 在 HarnessAgent.Builder.build() 中,跳过第一次拷贝,直接将 builder 的 toolkit 传给 inner,让 ReActAgent.Builder.build() 成为唯一的深拷贝点。然后将 inner.build() 产生的 agentToolkit 引用传给中间件。这需要重构构建顺序。

方案 C(最小改动): 在 HarnessSkillMiddleware.onSystemPrompt() 中,不再使用构造时传入的 toolkit 注册工具,而是从 Agent 参数解析 agent 的实际 toolkit 并在上面注册:

@Override
public Mono<String> onSystemPrompt(Agent agent, String currentPrompt) {
    // 解析 agent 的实际 toolkit,而非使用构造时的引用
    Toolkit actualToolkit = resolveToolkit(agent);
    runtime.install(catalog, actualToolkit);
    ...
}

这需要 AgentBase 或 ReActAgent 暴露 getToolkit() 方法(HarnessAgent 已有,但 Agent 接口没有)。

临时解决方案

我们目前通过在 agentBuilder.build() 之后使用反射,从中间件的 SkillRuntime 中提取 SkillLoadTool,然后注册到 agent 的实际 toolkit 上来绕过此问题:

HarnessAgent agent = agentBuilder.build();
fixSkillLoadToolAfterBuild(agent);

private void fixSkillLoadToolAfterBuild(HarnessAgent agent) {
    ReActAgent delegate = agent.getDelegate();
    Field middlewaresField = ReActAgent.class.getDeclaredField("middlewares");
    middlewaresField.setAccessible(true);
    List<MiddlewareBase> middlewares = (List<MiddlewareBase>) middlewaresField.get(delegate);
    for (MiddlewareBase mw : middlewares) {
        if (mw.getClass().getSimpleName().equals("HarnessSkillMiddleware")) {
            Method runtimeMethod = mw.getClass().getMethod("runtime");
            Object runtime = runtimeMethod.invoke(mw);
            Method loadToolMethod = runtime.getClass().getMethod("loadTool");
            Object loadTool = loadToolMethod.invoke(runtime);
            Toolkit actualToolkit = agent.getToolkit();
            if (actualToolkit.getTool("load_skill_through_path") == null) {
                actualToolkit.registerAgentTool((AgentTool) loadTool);
            }
            return;
        }
    }
}

此方案可行,因为 SkillLoadTool 持有与中间件共享的 AtomicReference<SkillCatalog>,所以后续 onSystemPrompt() 调用更新 catalog 后,工具参数会自动同步。

lwx11111 avatar Jun 04 '26 11:06 lwx11111

好坑啊。。方案和我一样的

LumenWang956 avatar Jun 04 '26 12:06 LumenWang956

临时解决方案好使的

tanzzj avatar Jun 05 '26 13:06 tanzzj

I have submitted the RP to fix this bug and am now waiting for it to be merged. https://github.com/agentscope-ai/agentscope-java/pull/1607

lwx11111 avatar Jun 10 '26 02:06 lwx11111

搞了1天,升级v2后一直触发不了skill,都是read_file读取skill.md,最后发现tools列表中没有携带load_skill_through_path

lldacing avatar Jun 11 '26 05:06 lldacing

用临时方案可以激活skill,但是和skill绑定的工具还是激活不了

lldacing avatar Jun 11 '26 06:06 lldacing