fix(middleware): expose runtime context in onAgent#1673
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
|
@LearningGp 麻烦审核一下谢谢 |
AgentScopeJavaBot
left a comment
There was a problem hiding this comment.
🤖 AI Review
This PR cleanly resolves issue #1672 by promoting getRuntimeContext() to the Agent interface as a default method, eliminating the need for instanceof AgentBase casts throughout middleware code. The lifecycle management for RuntimeContext in ReActAgent is well-designed — Flux.defer() ensures lazy context creation at subscription time, ensurePendingRuntimeContext() guarantees availability before middleware execution, and clearPendingRuntimeContextIfUnbound() handles both normal completion and short-circuit scenarios correctly. Test coverage is comprehensive, covering live context access, caller-supplied contexts, short-circuit cleanup, and post-invocation nullness. One minor cleanup opportunity exists (dead-code null check), but no functional issues were found.
AgentScope-Java Version
2.0.0-SNAPSHOTDescription
背景
当前
MiddlewareBase#onAgent(...)中传入的Agent参数没有稳定可用的getRuntimeContext()访问入口,导致 middleware 想读取或修改运行时上下文时,只能依赖instanceof AgentBase之类的实现细节判断。这会带来两个问题:
MiddlewareBase的公共扩展点和Agent的公共契约不一致;onAgent阶段即使拿到了Agent,也可能无法直接访问有效的RuntimeContext。这个 PR 主要是修复 issue #1672,让 middleware 在
onAgent阶段可以通过统一 API 访问运行时上下文。目的
让
MiddlewareBase#onAgent(...)中的agent参数具备稳定、统一的RuntimeContext访问能力,避免 middleware 依赖AgentBase的具体实现细节。主要改动
Agent接口中新增默认方法getRuntimeContext(),将运行时上下文暴露为公共契约的一部分。AgentBase/HarnessAgent上对该能力进行对接,保持现有实现一致。ReActAgent的 runtime context 生命周期:onAgentmiddleware 执行前即可访问当前调用对应的RuntimeContext;call()生命周期后复用同一份上下文对象;AgentBase的instanceof依赖,统一改为使用agent.getRuntimeContext()。agent == null的兼容处理,避免已有单元测试或边界调用因为直接访问新接口而触发 NPE。onAgent可以拿到 liveRuntimeContextonAgent中写入的上下文数据可以继续被后续 hook / phase 读取如何测试
已执行以下定向验证:
重点关注:
ReActAgentMiddlewareIntegrationTest#onAgentHookCanAccessLiveRuntimeContext
AtPathExpansionMiddlewareTest
Checklist
Code has been formatted with mvn spotless:apply
All tests are passing (mvn test)
Javadoc comments are complete and follow project conventions
Related documentation has been updated (e.g. links, examples, etc.)
Code is ready for review