Repository navigation
fix(agui): eliminate concurrent toolkit pollution via per-call RuntimeContext toolkit - #2463
xzxiaoshan wants to merge 19 commits into
Conversation
…ll toolkit via RuntimeContext, which now supports runtime toolkit override
This comment was marked as abuse.
This comment was marked as abuse.
This comment was marked as abuse.
This comment was marked as abuse.
# Conflicts: # agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui/src/main/java/io/agentscope/core/agui/adapter/AguiAgentAdapter.java
…lver 到 extensions-agui。 基于 PR#2306 进一步调整。PR#2306 在 Spring starter 的 common 包内引入了 AguiRuntimeContextRequest 和 AguiRuntimeContextResolver,但这两个类零 Spring 依赖(仅依赖 RuntimeContext 与 RunAgentInput),本质上是与 AgentEventConverter、AguiEventEnricher、AguiAgentAdapterFactory 同类的协议层 SPI,锁在 starter 里既违背了 starter 作为"Spring 装配层"的职责边界,也使非 Spring 接入方无法复用。 本次同步调整三件事:(1) 归位——将两个类下沉到 agentscope-extensions-agui 的 io.agentscope.core.agui.runtime 包,与同类扩展点同模块;(2) 类型安全——AguiRuntimeContextRequest 泛型化为 AguiRuntimeContextRequest<T>,用编译期泛型替代原 Object + 运行期 Class<T> 转型来刻画 transport-specific 的 nativeRequest;(3) 职责收口——以 AguiRequestProcessor#process(AguiRuntimeContextRequest<?>) 为基准入口,将 resolver 内置到 processor,MVC/WebFlux handler 不再各自持有 resolver、各自调用 resolve(),只负责将原生请求映射为 AguiRuntimeContextRequest<T> 后交给 processor 统一解析。
# Conflicts: # agentscope-extensions/agentscope-spring-boot-starters/agentscope-agui-spring-boot-starter/src/main/java/io/agentscope/spring/boot/agui/webflux/AguiWebFluxHandler.java
|
关于 agui-starter 模块的补充说明 |
# Conflicts: # agentscope-extensions/agentscope-spring-boot-starters/agentscope-agui-spring-boot-starter/src/main/java/io/agentscope/spring/boot/agui/mvc/AguiMvcController.java # agentscope-extensions/agentscope-spring-boot-starters/agentscope-agui-spring-boot-starter/src/main/java/io/agentscope/spring/boot/agui/webflux/AguiWebFluxHandler.java
这个建议拆出一个新PR,我会尽快合入。共享 toolkit 状态污染问题,待后续讨论 |
…njection Resolve conflict in AguiMvcController.java by combining the branch's single-arg process() refactor with main's BaseSubscriber-based subscription and interruptAndCancel() disconnect handling (adapted to the single-arg ProcessResult.interrupt() API). Update AguiMvcControllerTest to the single-arg process(AguiRuntimeContextRequest) signature.
8170840 to
8b954bb
Compare
Move AguiRuntimeContextRequest / AguiRuntimeContextResolver / AguiRequestBodyParser back to the Spring starter's `common` package and restore the multi-arg AguiRequestProcessor#process signature, so this branch only contains the per-call toolkit injection fix. The runtime SPI downcast has been split out to the refactor/agui-downcast-runtime-context branch.
8b954bb to
4163983
Compare
…ERNAL - Move ToolMergeMode from io.agentscope.core.agui.model to io.agentscope.core.tool so the per-call ToolRequestConfig can reference it from core (no core -> agui dep). - Rename FRONTEND_ONLY -> EXTERNAL_ONLY and MERGE_FRONTEND_PRIORITY -> MERGE_EXTERNAL_PRIORITY; AGENT_ONLY unchanged. - Migrate ToolMergeModeTest to agentscope-core alongside the enum. - Update imports and enum references in AguiAdapterConfig, AguiAgentAdapter, AguiProperties, and the AGUI test suite.
…Config composed with a shared toolkit instead of copying per call
…njection # Conflicts: # agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui/src/main/java/io/agentscope/core/agui/adapter/AguiAgentAdapter.java
…stConfig Add Toolkit.isExternalTool(String, ToolRequestConfig) and thread the per-call request config into AguiAgentAdapter's external-tool detector, so frontend- injected (schema-only) tools are recognised as external by the emitToolCallArgs gating instead of only backend-registered ones.
|
新增一轮代码优化:通过在请求层面的 ToolRequestConfig 与共享工具包组合来注入单次调用工具,而不是在每次调用时复制工具 把 per-call 的外部工具注入从「拷贝 Toolkit(思考了一下拷贝toolkit方式是一种内存资源使用不太优雅的实现_)」改为「不可变请求配置 + 共享无状态 toolkit 合成(永不复制、永不修改)」,使单个 ReActAgent 实例可安全服务并发会话。
已经自己做过2轮 review 。 |
The interface existed only to re-point middleware at the toolkit copy that ReActAgent.Builder.build() used to create. The toolkit is now a single immutable instance that is never copied or rebound, so the hook has no remaining meaning.
目的:让共享 toolkit 运行期只读、每次调用按会话安全解析工具面,从根源上 消除单实例并发会话间的 toolkit 串扰。 要点: - 工具注册前移到 build 期一次性完成;运行期经 RuntimeContext 解析 per-call SkillBox,不再每 call rebind/注册共享工具 - 以 content-addressed boxCache(签名含完整 metadata)取代共享单槽缓存, 内容不变不重写盘、不同用户视图互不串扰 - skill 激活收敛为写 per-session activatedGroups(synchronized + 原子 replace),移除运行期写共享 group manager 的路径
目的:让内置工具 load_skill_through_path 始终可见、可执行,不再被 reset_equipped_tools 的 META 整体替换从会话中误伤。 要点: - 移除 skill-build-in-tools(META scope)分组,两处注册( SkillToolFactory.registerRuntimeLoadTool / SkillBox.registerSkillLoadTool) 改为无分组注册
一、当前 PR 实际做了三件事(建议在 PR 描述澄清):
二、在 PR 描述中显式标注破坏性变更当前描述未列出破坏面,建议补一节,包括: 删除/更改的公共 API 破坏性语义变更
|
已更新完善修改 PR 正文内容。 |
…tConfig merge contract, legacy replaceMetaActiveGroups
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
Re-review of the delta pushed since my 2026-07-28 approval on 738ed6a2 (the branch has since taken 218 upstream commits; the author-side delta is the percall-toolkit-injection refactor in 41639834, 46949058, 2aa3a151, 660cdb42, 07d87deb, 082d0fa6, f2d41e30, 4fa5e2d0).
My verdict on the redesign itself is positive: replacing per-call Toolkit.copy() with an immutable ToolRequestConfig composed against a shared stateless toolkit is the right shape, and it removes the root cause of the concurrent-toolkit pollution this PR set out to fix. Concentrating the "external → hide-backend → registry" policy in ToolRequestConfig.resolveTool/hidesBackend/overrides so the schema path and the executor path cannot drift is a good structural choice, and turning external tools into a compile-time Map<String, SchemaOnlyTool> makes the "external ⇒ schema-only" invariant explicit instead of conventional.
Two design points and one compatibility point below — none of them disputes the approach.
Findings
- [Warning]
ToolRequestConfig.java:96—EXTERNAL_ONLYsilently degrades to merge semantics whenallowToolDeletionis false; the caller gets a wider tool surface than it asked for, with no signal. - [Warning]
Toolkit.java:254— the public 1-arggetTool(String)still exposes the shared-registry-only view, so schema and execution paths can disagree with the new per-call view. - [Info]
AguiAdapterConfig.java:21—ToolMergeModemoved out ofagui.modelinto core andFRONTENDrenamed; needs a deprecated alias or a release-notes line.
Note for maintainers
My previous APPROVED state was recorded against the pre-refactor design. The two warnings above are non-blocking in isolation but they are the kind of surface-consistency issue worth a second maintainer look, since agentscope-core changes cascade into harness, distribution and the extensions.
*Automated review by github-manager-bot"
Additional notes (not anchored to a changed line)
- [WARNING]
agentscope-core/src/main/java/io/agentscope/core/tool/Toolkit.java:254— [Warning] The 1-arggetTool(String)still resolves against the shared registry only, so it now disagrees with the 2-arg per-call view for any name shadowed by an external tool or hidden byEXTERNAL_ONLY. There are internal call sites outside the executor path (ToolSchemaProvider,McpClientManager,ReActAgent,SkillRuntime, harness skill runtime), and it remains public API, so a caller can build a schema list from one view and execute against the other — the exact class of drift theresolveToolsingle-home comment is meant to prevent. Suggest marking the 1-arg overload in javadoc as "shared-toolkit view only; never use for a call in flight" (or deprecating it for that use) so the per-call overload is the only correct answer on a request path. (line outside diff)
| * and {@link Toolkit#getToolSchemas(java.util.Collection, ToolRequestConfig)} so the policy | ||
| * cannot drift. | ||
| */ | ||
| boolean hidesBackend(boolean allowToolDeletion) { |
There was a problem hiding this comment.
[Warning] EXTERNAL_ONLY is only enforced when allowToolDeletion is true (hidesBackend = mergeMode == EXTERNAL_ONLY && allowToolDeletion). With deletion disabled, a caller that asked for EXTERNAL_ONLY silently gets MERGE_EXTERNAL_PRIORITY semantics: external tools win on name collisions, but every backend tool stays resolvable and schema-visible. That is a safe default, but it is invisible to the caller. Could you either (a) log/emit a one-time warning when the requested mode is degraded, or (b) reject the combination at the AG-UI boundary? A test pinning the degraded behaviour (EXTERNAL_ONLY + allowToolDeletion=false ⇒ backend still callable) would also make the contract explicit.
| import io.agentscope.core.agui.adapter.strategy.AguiEventEnricher; | ||
| import io.agentscope.core.agui.adapter.strategy.BaseEventPropertiesEnricher; | ||
| import io.agentscope.core.agui.model.ToolMergeMode; | ||
| import io.agentscope.core.tool.ToolMergeMode; |
There was a problem hiding this comment.
[Info] This is the visible half of a breaking move: io.agentscope.core.agui.model.ToolMergeMode is deleted and replaced by io.agentscope.core.tool.ToolMergeMode, and FRONTEND becomes EXTERNAL_ONLY (with MERGE_FRONTEND_PRIORITY presumably → MERGE_EXTERNAL_PRIORITY). Package move + constant rename is source- and binary-breaking for anyone who configured the AG-UI adapter, and agentscope-extensions-agui is a published artifact. A deprecated io.agentscope.core.agui.model.ToolMergeMode alias (or a one-line entry in docs/v2/{en,zh}/docs/others/release-notes.md under "Unreleased / 兼容性", the way #2862 documents its retryOn default change) would keep the migration discoverable.
…3283) Concurrent calls must not change another session's tool visibility, streaming callbacks, or skill resources. This PR builds on main after #3279 and adapts the request-scoped tool composition work from #2463, with additional fixes for construction-time isolation and explicit context propagation. Related: #2439, #2459. Credit to @xzxiaoshan for the original implementation in #2463. Co-authored-by: xzxiaoshan <[email protected]>
|
This PR currently conflicts with the target branch and cannot be merged. Please rebase or merge the latest target branch into your branch and resolve the conflicts: git fetch origin
git checkout fix/percall-toolkit-injection
git rebase origin/main
# resolve conflicts, then:
git push --force-with-leaseThis is a one-time reminder. Feel free to @mention me for a re-review after the conflicts are resolved. Automated notification by github-manager-bot |
|
该PR,已通过 #3279 聚合整理合入 main 分支。 |
问题
AguiAgentAdapter在运行时直接对 Agent 的共享 toolkit 执行registerAgentTool/removeTool,再通过ToolInjection.close()+doFinally做"借-还"恢复。该机制只保证单流自洽——同一 Agent 单例并发执行时,各流的注入与恢复会相互污染共享 toolkit 状态;工具组激活状态同样存在共享可变态,导致跨会话串扰(#2439)。本 PR 实际包含三项改动
根治 [Bug]:AgentScope 2.0 GA 单例 Agent 并发时工具组跨会话串扰 #2439:工具组激活状态 per-session 化
把激活组状态的真相源从共享 Toolkit 的
groupManager剥离到 per-session 的ToolContextState(新增add/remove/replace原子读改写方法)。共享 Toolkit 全程无激活态、无并发写。core 引入
ToolRequestConfig/ToolMergeMode:per-call 工具差异的不可变承载新增不可变
ToolRequestConfig值对象(外部 schema-only 工具 + merge mode,NONE表示原样使用共享 toolkit),与共享无状态 Toolkit 即时合成——永不复制、永不修改。schema 生成与单工具查找两条路径共用同一份「external 覆盖 /EXTERNAL_ONLY隐藏后端」策略,合并策略收口在ToolRequestConfig(resolveTool/hidesBackend/overrides)一处,供 schema 生成 / 权限 / 执行共用。reset_equipped_tools与内部 chunk 回调改为 call 级加工与参数下传。重构 agui 前端工具解析
ToolInjection借-还机制整体删除,injectFrontendTools改为产出ToolRequestConfig设入RuntimeContext;FRONTEND_ONLY→EXTERNAL_ONLY,语义对齐 tool 的 external 定义。最终效果: 单个
ReActAgent实例可安全服务并发会话——共享 toolkit 全程只读,per-call 差异全部通过不可变请求配置即时合成(新增并发回归测试覆盖:会话间激活组隔离、reset 只写本会话、chunk 回调不串流)。设计演进说明
第一版实现为 per-call
toolkit.copy()。复盘后认为拷贝 toolkit 在内存资源使用上不够优雅,遂重构为「不可变请求配置 + 共享无状态 toolkit 合成」。1.
SkillBox删除 / 变更的公共方法syncToolGroupStates()isSkillActive(String)AgentState#getToolContext().getActivatedGroups())setSkillActive(String, boolean)deactivateAllSkills()registerSkillLoadTool()skill-build-in-tools分组,改为 ungrouped 始终可见;同名工具已存在时告警跳过(静态skillBox()与动态skillRepositories()混用不受支持)2.
Toolkitcopy()getToolSchemas()/getToolSchemas(Collection)/getActiveGroups()/setActiveGroups(List)/updateToolGroups(...)/isActiveTool(String)3.
ReActAgent/BuilderBuilder.build()toolkit.copy();hook / meta 工具就地注册到调用方传入的 toolkit——同一 toolkit 传给多个 agent 将共享这些注册Builder.fromAgent()agent.getToolkit().copy()getToolkit()toolkit.setActiveGroups(...)(改为 schema 解析时按会话状态合成)4.
DynamicSkillMiddlewaregetCurrentSkillBox()RuntimeContext(rc.get(SkillBox.class))per-call 暴露,复用的 RuntimeContext 不会再读到过期 boxload_skill_through_path(运行时按 RuntimeContext 解析当前 box),不再每次调用重注册5.
ToolMergeMode包名与枚举更名(agui → core)io.agentscope.core.agui.model.ToolMergeMode→io.agentscope.core.tool.ToolMergeMode(旧 import 全部失效)FRONTEND_ONLYEXTERNAL_ONLYMERGE_FRONTEND_PRIORITYMERGE_EXTERNAL_PRIORITYAGENT_ONLYAguiAdapterConfig与 Spring starter 的AguiProperties.defaultToolMergeMode默认值改为MERGE_EXTERNAL_PRIORITY;配置文件中的default-tool-merge-mode: FRONTEND_ONLY / MERGE_FRONTEND_PRIORITY将绑定失败6. 运行时行为(语义)变更
load_skill_through_path)与reset_equipped_tools只写 per-session 的ToolContextState,绝不写共享 group manager。reset_equipped_tools:无 per-session RuntimeContext 时快速失败(返回 error,原行为是写共享状态);空列表响应文案All tool groups…→All META tool groups…(META 替换 / EXTERNAL 保留语义不变)。load_skill_through_path:无会话上下文时跳过激活并告警(不再静默写共享组);动态技能路径的工具参数不再枚举 skillId(技能目录经 system prompt 广播)。EXTERNAL_ONLY+ 禁止删除工具(allowToolDeletion=false) 时降级为合并语义(后端工具保留)。新增 API(非破坏,供迁移参考)
ToolRequestConfig(record,io.agentscope.core.tool):NONE哨兵、resolveTool/hidesBackend/overrides(包内)RuntimeContext#getToolRequestConfig / setToolRequestConfig及 Builder 方法Toolkit#getTool(String, ToolRequestConfig)、#isExternalTool(String, ToolRequestConfig)、#getToolSchemas(Collection, ToolRequestConfig)、#callTools(..., ToolRequestConfig, BiConsumer)重载ToolGroupManager#isActiveTool(String, Collection)(无状态判定变体)ToolContextState#addActivatedGroups / removeActivatedGroups / replaceActivatedGroups(原子读改写)语义保持
NONE)时原样使用共享 toolkit,默认调用路径行为不变;FRONTEND_ONLY→EXTERNAL_ONLY为对齐 external 定义的更名,对前端工具的实际效果不变;