[Bug]:自定义 middleware 注册的 ContextItem 被整块覆盖
问题描述(Describe the bug)
我们基于 agentscope-harness 的 HarnessAgent 做业务智能体,能力开关打开时用自定义 HarnessRuntimeMiddleware 把对应的使用规则以官方约定的方式注册进上下文:
@Override
public Mono<String> onSystemPrompt(Agent agent, RuntimeContext ctx, String currentPrompt) {
if (ctx != null) {
WorkspaceContextMaterials.register(ctx, List.of(
ContextItem.instruction("my_policy", "my:policy", POLICY_TEXT)));
}
return Mono.just(currentPrompt != null ? currentPrompt : ""); // 官方约定:不改系统提示词串
}
现象:这段规则从来不出现在实际发给模型的请求里。抓包确认:
- 系统消息里能看到 harness 自己的三块材料 ——
harness:context-conventions、harness:workspace-environment、harness:workspace-guidance; - 另外一条
<HARNESS_CONTEXT>user 消息里能看到harness:session-state、harness:skills; - 我们自己注册的
source="my:policy"一次都没有出现过。
这不是单个中间件的问题:把 artifacts / knowledge search / web search / workflow 选择等多个能力中间件全部打开后,它们注册的全部材料都一起消失,而对应工具(uploadFileTool、packWorkspaceTool、knowledgeSearchTool…)都在请求的 tools 数组里——说明中间件确实挂在 agent 上,只是它注册的材料被吃掉了。
是否因为onSystemPrompt阶段,直接进行了WorkspaceContextMaterials.register? 改用Mono.fromSupplier()惰性返回会成功吗?参照PlanModeMiddleware这种方式 ContextConventionsMiddleware给把Wrc.put( WorkspaceContextMaterials.class冲掉了吧
2. 是否因为onSystemPrompt阶段,直接进行了WorkspaceContextMaterials.register? 改用Mono.fromSupplier()惰性返回会成功吗?参照PlanModeMiddleware这种方式 ContextConventionsMiddleware给把Wrc.put( WorkspaceContextMaterials.class冲掉了吧
根因:ContextConventionsMiddleware 用 rc.put(WorkspaceContextMaterials.class, new ...) 整块替换材料 holder,而它被 HarnessAgent.Builder#build()
追加在自定义中间件之后,所以你在 onSystemPrompt 里 register 的材料全被它冲掉了(跟 Mono.fromSupplier 惰性无关,改惰性也救不回来)。
Hi, I'd like to work on this. The report plus BiuBiuH's comment pinpoints the mechanism: onSystemPrompt middlewares register materials eagerly, but the harness collects WorkspaceContextMaterials before/around that phase, so later registrations overwrite the whole block — custom materials vanish. Plan: make collection additive per-source (merge by source key instead of block replace) or collect after the middleware chain finishes, with a regression test using the exact ContextItem.instruction("my_policy", ...) repro. PR coming shortly.
那调整顺序在ContextConventionsMiddleware 之后可以吗? 我记得MiddlewareBase有个order 注册MiddlewareBase后HarnessAgent.Builder#build()有进行排序的 而且这个ContextConventionsMiddleware 用 rc.put(WorkspaceContextMaterials.class, new ...) 整块替换材料是有意为之,每次调用都清除RuntimeContext的WorkspaceContextMaterials,防止RuntimeContext的WorkspaceContextMaterials复用之时重复注册ContextItem
另外 是有什么特殊原因必须在WorkspaceContextMaterials里面加吗? 正常不是应该在HarnessAgent的Builder的instruction进行添加
Verified against current main — two findings that change the fix shape:
1. order() is not wired for the middleware chain on main. MiddlewareBase.order() exists, but ReActAgent.groupMiddlewares (the construction-time grouping) preserves registration order only — no sort — and MiddlewareChain doesn't sort either. So "调整顺序到 ContextConventionsMiddleware 之后" is currently only achievable by registration order, not by order(). And registration order doesn't help the reporter: framework middlewares like ContextConventions are appended inside build() — i.e., after every user .middleware(...) entry — so user middlewares always run before it in the chain and their register() output lands in the snapshot that ContextConventions then wholesale-replaces.
2. Your read of the intent is exactly right — the put(new ...) is the fresh-snapshot reset (reused RuntimeContext / child contexts / disabled providers must not retain a previous call's data). The design gap is that the reset can't tell "previous call's leftovers" (should drop) from "another middleware's same-call registration" (should keep) — both look identical in the context.
Proposed fix (both together):
groupMiddlewaressorts byorder()(stable, ascending) — wiring the documented-but-unwired contract — and the framework context providers declare a low order so they run before user middlewares atON_SYSTEM_PROMPT. Registration-order users see no change (stable sort).ContextConventionsMiddleware's reset additionally warns when it is about to discard non-framework items (sourceId not starting withharness:) — turning today's silent loss into a diagnosable one for any path the ordering doesn't cover.
This keeps the reset semantics intact (framework data always fresh), makes register() from any user middleware survive regardless of how it was ordered, and answers your question: with this PR, yes — anything after the framework providers survives, and order() finally means what the docs said.
Good question — and the answer is "both exist, with different lifecycles; the middleware route is the dynamic one":
Builder.instruction(id, content) is exactly the right tool for static guidance — known at build time, same for every call/user/session. It feeds contextSources and lands in the same collected snapshot as the middleware-registered items (they merge in HarnessContextBuilder, with duplicate-sourceId detection across both).
WorkspaceContextMaterials.register from a middleware is for guidance that depends on runtime state the builder can't see: per-user capability toggles, feature flags resolved per session, A/B experiment arms, tenant-specific policy loaded from a store, request-scoped context. The reporter's case is exactly this shape — "能力开关打开时" (when a capability toggle is on) — which is a runtime condition, so Builder.instruction can't express it for a shared singleton agent.
So for the reporter's literal repro: if the policy text is effectively static per deployment, yes — Builder.instruction("my_policy", POLICY_TEXT) is the simpler and more robust answer, and worth stating on the issue as the first option. The materials path remains necessary for the dynamic cases, which is why the ordering fix in #3846 still matters: middleware authors following the documented register contract shouldn't have their runtime-resolved items silently vanish regardless of what ran before them.
(Also worth noting: register items and Builder.instruction items share the same sourceId namespace and the same duplicate-detection — so the two routes compose, they don't compete.)
不是 这都走AI查的吗? groupMiddlewares取的middlewares不是从builder.middlewares取的么 ReActAgent(this, agentToolkit)的构造方法之前,已经利用middlewares.sort(Comparator.comparingInt(MiddlewareBase::order).reversed());了吧 在ReActAgent的buildInstance方法内
You're right on both counts, and I owe a straight correction — including on the "how was this checked" question: I'm an AI coding agent, and my verification searched the construction side (groupMiddlewares, MiddlewareChain) and HarnessAgent.java, but missed ReActAgent.Builder.buildInstance(), where the sort you remembered lives: middlewares.sort(Comparator.comparingInt(MiddlewareBase::order).reversed()) with the stable-sort comment. My "order() was never wired" claim was wrong. Your memory was better than my grep.
With that corrected, the actual defect narrows to equal-order tie-breaking: the sort is stable, user middlewares are registered via middleware(...) into the same list before the framework providers are appended inside buildInstance(), and ContextConventionsMiddleware had a default order — so with equal orders, registration order survives, user middlewares still run before the framework reset, and their register() output is still wiped. That matches the reporter's observation despite the sort existing.
So the load-bearing fix is exactly one line: ContextConventionsMiddleware.order() returns a high value so it sorts outermost/first and the reset happens before any user registration. The redundant re-sort I added in groupMiddlewares is harmless on an already-sorted list but no longer justified by a wrong premise — I'll strip it from #3846 and keep (a) the high-order declaration and (b) the discard-warning, which remains useful for any path ordering doesn't cover. Updating the PR and its description now.