Repository navigation
fix(tools): isolate request tool views and session skill resources - #3283
Conversation
Build on #3279 and adapt #2463 with construction-time registry isolation, explicit contextual repositories, consistent execution entrypoints, and content-addressed skill resources. Co-authored-by: xzxiaoshan <[email protected]>
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Critical agent-isolation and concurrent skill-cache issues remain unresolved.
Get a fresh assessment by requesting another Copilot review.
Review effort: Lite
Findings: 2
Open (4)
What changed in this PR
This PR isolates request-scoped tool visibility, session skill state, callbacks, and dynamic skill resources for concurrent executions.
Changes:
- Adds immutable request tool configuration and Core merge modes.
- Moves skill context and activation into explicit runtime/session state.
- Updates AG-UI, Harness, documentation, and regression tests.
| File | Summary |
|---|---|
docs/v2/zh/integration/protocol/agui.md |
Documents request-scoped AG-UI tools. |
docs/v2/zh/docs/building-blocks/tool.md |
Documents tool and skill isolation. |
docs/v2/en/integration/protocol/agui.md |
Updates AG-UI tool semantics. |
docs/v2/en/docs/building-blocks/tool.md |
Documents request-scoped tools. |
agentscope-harness/src/main/java/io/agentscope/harness/agent/skill/WorkspaceSkillRepository.java |
Uses the Core contextual repository contract. |
agentscope-harness/src/main/java/io/agentscope/harness/agent/middleware/HarnessSkillMiddleware.java |
Propagates contextual repository usage. |
agentscope-extensions/agentscope-spring-boot-starters/agentscope-agui-spring-boot-starter/src/main/java/io/agentscope/spring/boot/agui/common/AguiProperties.java |
Updates merge-mode configuration. |
agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui/src/test/java/io/agentscope/core/agui/model/AguiModelTest.java |
Removes migrated enum tests. |
agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui/src/test/java/io/agentscope/core/agui/adapter/AguiAgentAdapterV2Test.java |
Tests request-scoped tool configuration. |
agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui/src/test/java/io/agentscope/core/agui/adapter/AguiAgentAdapterTest.java |
Tests AG-UI tool isolation. |
agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui/src/test/java/io/agentscope/core/agui/adapter/AguiAdapterConfigTest.java |
Updates merge-mode tests. |
agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui/src/main/java/io/agentscope/core/agui/model/ToolMergeMode.java |
Removes the obsolete enum. |
agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui/src/main/java/io/agentscope/core/agui/adapter/ToolInjection.java |
Removes shared toolkit injection. |
agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui/src/main/java/io/agentscope/core/agui/adapter/AguiAgentAdapter.java |
Builds per-call tool configurations. |
agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui/src/main/java/io/agentscope/core/agui/adapter/AguiAdapterConfig.java |
Uses Core merge modes. |
agentscope-core/src/test/java/io/agentscope/core/tool/ToolRequestConfigTest.java |
Tests request tool composition. |
agentscope-core/src/test/java/io/agentscope/core/tool/ToolMergeModeTest.java |
Tests Core merge modes. |
agentscope-core/src/test/java/io/agentscope/core/tool/ToolEmitterIntegrationTest.java |
Tests per-call callbacks. |
agentscope-core/src/test/java/io/agentscope/core/tool/ReActAgentToolkitConcurrencyTest.java |
Adds concurrency regression coverage. |
agentscope-core/src/test/java/io/agentscope/core/tool/MetaToolFactoryTest.java |
Tests session-scoped activation. |
agentscope-core/src/test/java/io/agentscope/core/skill/SkillRuntimeIntegrationTest.java |
Updates contextual skill tests. |
agentscope-core/src/test/java/io/agentscope/core/skill/SkillRegistryTest.java |
Tests the simplified skill registry. |
agentscope-core/src/test/java/io/agentscope/core/skill/SkillHookTest.java |
Updates skill prompt tests. |
agentscope-core/src/test/java/io/agentscope/core/skill/SkillBoxToolsTest.java |
Tests contextual skill loading. |
agentscope-core/src/test/java/io/agentscope/core/skill/SkillBoxTest.java |
Removes shared activation tests. |
agentscope-core/src/test/java/io/agentscope/core/skill/RegisteredSkillTest.java |
Removes obsolete activation tests. |
agentscope-core/src/test/java/io/agentscope/core/skill/DynamicSkillMiddlewareTest.java |
Tests contextual skill caching. |
agentscope-core/src/test/java/io/agentscope/core/skill/AgentSkillPromptProviderTest.java |
Updates registry usage. |
agentscope-core/src/test/java/io/agentscope/core/legacy/hook/HookToolsRegistrationTest.java |
Tests agent-specific registrations. |
agentscope-core/src/main/java/io/agentscope/core/tool/ToolRequestConfig.java |
Defines immutable request tool views. |
agentscope-core/src/main/java/io/agentscope/core/tool/ToolRegistry.java |
Copies registration metadata independently. |
agentscope-core/src/main/java/io/agentscope/core/tool/ToolMergeMode.java |
Defines Core merge modes. |
agentscope-core/src/main/java/io/agentscope/core/tool/ToolkitAware.java |
Removes obsolete rebinding APIs. |
agentscope-core/src/main/java/io/agentscope/core/tool/Toolkit.java |
Composes request views and callbacks. |
agentscope-core/src/main/java/io/agentscope/core/tool/ToolGroupManager.java |
Adds stateless group resolution. |
agentscope-core/src/main/java/io/agentscope/core/tool/ToolExecutor.java |
Applies request configuration per call. |
agentscope-core/src/main/java/io/agentscope/core/tool/MetaToolFactory.java |
Uses session tool context. |
agentscope-core/src/main/java/io/agentscope/core/state/ToolContextState.java |
Adds session activation state. |
agentscope-core/src/main/java/io/agentscope/core/skill/SkillToolFactory.java |
Makes skill loading context-aware. |
agentscope-core/src/main/java/io/agentscope/core/skill/SkillRegistry.java |
Removes shared activation bookkeeping. |
agentscope-core/src/main/java/io/agentscope/core/skill/SkillBox.java |
Uses contextual skill activation. |
agentscope-core/src/main/java/io/agentscope/core/skill/repository/RuntimeContextSkillRepository.java |
Moves the contextual repository contract to Core. |
agentscope-core/src/main/java/io/agentscope/core/skill/RegisteredSkill.java |
Removes obsolete skill metadata state. |
agentscope-core/src/main/java/io/agentscope/core/skill/DynamicSkillMiddleware.java |
Adds contextual, content-addressed skill caching. |
agentscope-core/src/main/java/io/agentscope/core/skill/AgentSkillPromptProvider.java |
Uses the simplified registry. |
agentscope-core/src/main/java/io/agentscope/core/ReActAgent.java |
Integrates request-scoped tool state. |
agentscope-core/src/main/java/io/agentscope/core/agent/RuntimeContext.java |
Carries request tool configuration. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
oss-maintainer
left a comment
There was a problem hiding this comment.
Summary
This removes the shared-mutation model for tools and skills instead of patching it: Toolkit is now treated as shared and stateless, the per-call difference travels on an immutable ToolRequestConfig carried by RuntimeContext, activation lives on the per-session ToolContextState, and AG-UI's borrow-mutate-restore ToolInjection is gone. I verified the isolation claims rather than taking them on faith, and the core of them holds:
- The four deleted public types (
RegisteredSkill,ToolkitAware,agui.model.ToolMergeMode,ToolInjection) and the deletedsetInternalChunkCallback/syncToolGroupStates/isSkillActive/replaceMetaActiveGroupsmembers have no remaining callers anywhere in the tree — the removals are complete, and the new "external → hide-backend → registry" policy genuinely has one home (ToolRequestConfig.resolveTool), shared byToolkit.getTooland the executor. replaceActivatedGroups/addActivatedGroupsmake the group mutations real read-modify-write under the per-session monitor, andMetaToolFactorycorrectly refuses to fall back to mutating shared group state when no per-session context exists.- Per-call
internalChunkCallbackthreading throughcallTools/executeAll/executeremoves a genuine cross-call leak, and keepinguserChunkCallbackonToolkit.copy()preserves the build-time contract. ToolRequestConfig's compile-timeMap<String, SchemaOnlyTool>typing plus eager key/name validation is the right shape for this.
Findings are all in the skill-cache and legacy-API corners, and only one is behavioural — the rest are hardening and doc accuracy. None of them contradicts the PR's stated design, so I'm leaving this as COMMENT for the author and other reviewers to weigh rather than blocking:
- [Warning]
DynamicSkillMiddleware.java:337—computeSignaturehashes each resourcekeyandvalwith no delimiter between them, so{"ab":"c"}and{"a":"bc"}collide and anullvalue looks like an empty one. Pre-existing, but this PR turns the signature from a prompt-reuse hint into both the cache key and the on-disk directory name, which raises the stakes. - [Warning]
DynamicSkillMiddleware.java:223—boxCache.clear()bounds the heap but never deletes the per-signature resource directories (only the shutdown hook removes the root), so multi-tenant per-user namespaces grow disk without limit and also grow the staticSkillBox.FILE_LOCKSkey set. The base had one shared directory, so this is a new failure mode. - [Warning]
DynamicSkillMiddleware.java:216— check-then-act onboxCache: concurrent first loads of the same signature can both build and both upload into the same directory before either publishes. - [Warning]
ToolExecutor.java:334—resolveActiveGroupsreturnsnullwithout anAgentState, andisActiveToolreadsnullas "use the shared flags", so a caller that omits per-session state is silently gated by shared state; the write path inMetaToolFactoryalready fails fast on exactly that condition. - [Warning]
Toolkit.java:870—setActiveGroupsis still public but now has no callers and no effect on the per-call decision, while its own javadoc still says ReActAgent calls it on session restore;@Deprecatedwould make the no-op discoverable. - [Info]
ToolRequestConfig.java:44— mixed-language comment, and three different phrasings of theAGENT_ONLY+ external-tools rule (coerce / ignore / reject) acrossToolRequestConfig, its constructor andToolMergeMode.
Notable strengths
- The author-reported 371 targeted tests (not run here) map onto the actual risk:
ReActAgentToolkitConcurrencyTest(381 new lines) for overlapping managed executions,ToolRequestConfigTestfor the fail-fast combinations, and theA → B → Aresource-stability case for the content-addressed cache. docs/v2/enanddocs/v2/zhare updated in lockstep, including theEXTERNAL_ONLY-with-empty-list subtlety, which is the kind of edge callers otherwise discover by accident.- Dropping
syncToolkitToStateremoves a real persistence hazard: the previous write path copied shared toolkit activation into the session state at save time, so whichever session saved last could rewrite another's activation set.
Validation note
I did not build or run tests — git transport to github.com was unavailable in this environment, so I reconstructed the exact 3e63abfcb1 tree file-by-file through the contents API and reviewed against it. The PR's own checklist already notes the full repository suite was not run; that plus mergeStateStatus=BLOCKED is worth resolving before merge regardless of these findings.
Automated review by github-manager-bot
| : new byte[0]); | ||
| md.update((byte) 0); | ||
| hashMetadata(md, s.getMetadata()); | ||
| md.update((byte) 0); |
There was a problem hiding this comment.
[Warning] This resource loop is the only place in computeSignature that hashes two values with no delimiter between them: key and val go into the digest back-to-back, with 0x00 only after the value. So {"ab": "c"} and {"a": "bc"} produce identical bytes, and a null value is indistinguishable from an empty-string one. Every other field in this method (name/source/metadata/content) is separated by (byte) 0, and the new hashMetadata at line 368 gets it right on both sides of the pair — this loop just diverges from that convention.
To be precise about attribution: the missing separator is pre-existing, not introduced here. What this PR changes is what the signature is for. Previously it only compared against lastSignature to reuse one box, so a collision cost a stale prompt. Now the same string is both the boxCache key and the on-disk resource directory name (line 234), so a collision makes two different skill views share one box and one file tree — which is the A-overwrites-B failure the content-addressing was added to prevent. Low probability, and the fix is one line while this file is already open: md.update((byte) 0); between key and value.
| // Only bound retained boxes. Active requests may still reference evicted | ||
| // boxes and their files, so resource directories must remain available. | ||
| boxCache.clear(); | ||
| } |
There was a problem hiding this comment.
[Warning] clear() bounds the heap but not the disk. Per-signature resource directories are never deleted anywhere: the only deleteRecursively call is the JVM shutdown hook on the root stableWorkDir, so each distinct visible skill view permanently adds a full copy of every skill file under stableWorkDir/<signature>. The comment here says the cache "grows only when skills change or per-user namespaces produce new content" — that is exactly the multi-tenant case where the number of distinct views is large and unbounded, and dropping the map entries doesn't reclaim a byte of what they already wrote.
This is a new failure mode relative to the base, which passed the one shared ensureStableWorkDir() to every box and therefore had a single bounded directory. It also amplifies SkillBox.FILE_LOCKS (static, line 57): its keys are absolute target paths, so per-signature paths make that map's key cardinality grow the same way, and nothing ever evicts it.
Suggest an LRU eviction (a remove/access-order map with a removal hook) that deletes the evicted box's own signature directory, instead of an all-or-nothing clear() that keeps every orphan.
| if (signature.equals(lastSignature) && currentSkillBox != null) { | ||
| return; | ||
| synchronized (boxCache) { | ||
| SkillBox box = boxCache.get(signature); |
There was a problem hiding this comment.
[Warning] Check-then-act on boxCache. Two concurrent first-time loads of the same content can both miss here, both run buildBox → uploadSkillFiles() into the same stableWorkDir/<signature> directory, and then race the put/clear in the block below. FILE_LOCKS only serialises individual file writes, so the outcome is duplicated work and a redundant rewrite of a directory another thread may already be publishing, not corruption.
Since the signature is already computed here, boxCache.computeIfAbsent(signature, k -> buildBox(visible, k)) would collapse the build onto one winner — with the caveat that the MAX_CACHED_BOXES/clear() eviction needs to stay outside the mapping function, as doing that inside computeIfAbsent would mutate the map during its own update.
| * Resolve the per-call active groups from the tool call's runtime context, or {@code null} when | ||
| * unavailable (falling back to the shared activation flags in {@code ToolGroupManager}). | ||
| */ | ||
| private Collection<String> resolveActiveGroups(ToolCallParam param) { |
There was a problem hiding this comment.
[Warning] This returns null whenever the ToolCallParam carries no RuntimeContext/AgentState, and ToolGroupManager.isActiveTool(name, activeGroups) (line 364) reads null as "fall back to the shared activation flags". So the isolation this PR installs is conditional in a way that fails silently: an integration that forgets to populate AgentState on the context gets its tool gate decided by group state that other concurrent sessions own.
The write path for the same condition already takes the opposite decision. MetaToolFactory.resetEquippedToolsImpl refuses to fall back — "No per-session context: never fall back to mutating the shared group manager ... fail fast instead" — and returns an error. Worth making the read path agree: deny the call, or at minimum log.warn once, so a missing context surfaces as a bug rather than as non-deterministic behaviour under load.
| * | ||
| * <p>This method is typically called by ReActAgent when restoring state from a session. | ||
| * | ||
| * <p><b>Legacy single-session API:</b> mutates the shared activation flags. Per-call paths |
There was a problem hiding this comment.
[Warning] Two related problems with this now-legacy mutator, which is still public and still callable.
- The sentence directly above (line 868) still claims this method "is typically called by ReActAgent when restoring state from a session" — but this PR deletes exactly that call from
activateSlotForContext, and nothing in anysrc/maincalls it any more. The javadoc now points readers at a call site that no longer exists. - For any existing caller that was using it to control visibility, the effect is now silently discarded rather than rejected. The new pipeline resolves schemas and the activation gate from
state.getToolContext().getActivatedGroups(), andsyncToolkitToState(which used to copytoolkit.getActiveGroups()into the state on save) is removed too — sosetActiveGroups(...)can no longer reach the decision at all. The PR states no compatibility shims are being added, which is a fair call for the API surface, but here the outcome is an existing public setter that quietly does nothing instead of failing.
Please drop the stale sentence and add @Deprecated pointing at AgentState#getToolContext()'s activated-groups API, so the no-op is discoverable.
| public record ToolRequestConfig( | ||
| Map<String, SchemaOnlyTool> externalTools, // name -> external (schema-only) tool, overrides | ||
| // backend | ||
| ToolMergeMode mergeMode // AGENT_ONLY implies NONE; otherwise MERGE_EXTERNAL_PRIORITY or |
There was a problem hiding this comment.
[Info] Two nits on the same line, both cheap to fix in a new public Core type whose whole job is to make the merge policy unambiguous.
- The comment mixes Chinese into an otherwise English-only file (
AGENT_ONLY ⇒ NONE;否则 …). This is the only source file underagentscope-core/src/maincontaining CJK; the repo keeps its Chinese content indocs/v2/zh/, which is the right split. Worth normalising. AGENT_ONLY ⇒ NONEreads as a coercion, but the constructor at line 70 does the opposite: it throwsIllegalArgumentException("AGENT_ONLY cannot include external tools"). TheToolMergeMode.AGENT_ONLYjavadoc separately says frontend tools "are ignored" for that mode. Three files, three phrasings of one rule — rejecting vs. ignoring are different contracts for a caller, so please pick one wording and use it in all three.
Upstream PR agentscope-ai#3283 added ToolValidator.validateInput which uses toolCall.getContent() for schema validation. The three new callTool single-param tests only set .input(Map) but omitted .content(String), causing silent validation failures (error ToolResultBlocks still get id/name attached by executeWithInfrastructure, so the first two tests passed by accident). Align ToolUseBlock construction with upstream convention by setting .content(JsonUtils.getJsonCodec().toJson(input)).
…ai#3283 request-scoped tool views Upstream agentscope-ai#3283 replaced shared tool-group activation with per-session ToolContextState activation and removed syncToolGroupStates / SkillBox.isSkillActive / ensureSkillToolGroupsActive. Rebased the dedup work onto that architecture: - loadSkillResourceImpl now takes (skillId, path, tcs, scope, reload); the dedup short-circuit reconciles the session's activation set via activateSkill(skillId, tcs) instead of mutating the shared toolkit. - reload flows through both the static tool call site and SkillBox.loadSkillResource, and is declared in both tool schemas and the shared description constant. - Dropped the now-orphaned SkillRegistry.isSkillActive accessor, the SkillBox delegation, and SkillRegistryGuardTest (their only producer and consumer were each other under the new architecture). - dedupPathResyncsExternallyDisabledToolGroup rewritten to the new contract: an externally cleared session activation set is re-synced by the deduplicated repeat load; the shared toolkit group is never mutated per call. Verified: mvn spotless:apply, full agentscope-core suite green. Co-Authored-By: Claude Code <[email protected]>
Upstream PR agentscope-ai#3283 added ToolValidator.validateInput which uses toolCall.getContent() for schema validation. The three new callTool single-param tests only set .input(Map) but omitted .content(String), causing silent validation failures (error ToolResultBlocks still get id/name attached by executeWithInfrastructure, so the first two tests passed by accident). Align ToolUseBlock construction with upstream convention by setting .content(JsonUtils.getJsonCodec().toJson(input)).
Upstream PR agentscope-ai#3283 added ToolValidator.validateInput which uses toolCall.getContent() for schema validation. The three new callTool single-param tests only set .input(Map) but omitted .content(String), causing silent validation failures (error ToolResultBlocks still get id/name attached by executeWithInfrastructure, so the first two tests passed by accident). Align ToolUseBlock construction with upstream convention by setting .content(JsonUtils.getJsonCodec().toJson(input)).



AgentScope-Java Version
2.0.4-SNAPSHOT
Description
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.
Resulting behavior
ToolRequestConfigcomposes external schemas with the agent registry per invocation. AG-UI no longer borrows, mutates, or restores shared tools. External tools suspend for client execution.ToolContextState; internal streaming callbacks travel with each invocation. This also works through fix(runtime): isolate contexts and control individual agent runs #3279'sprepareCallexecution handles.callTooland batchcallToolshonor the explicit RuntimeContext's request configuration.RuntimeContextSkillRepositoryinto Core and propagate the exact request context through both Core and Harness skill discovery.EXTERNAL_ONLYalways hides backend tools, including with an empty external list and with registry deletion disabled; request visibility does not delete registrations. Invalid AGENT_ONLY/external-map combinations and mismatched schema names fail fast.Public API and documentation
The current APIs use
io.agentscope.core.tool.ToolMergeMode(EXTERNAL_ONLY,MERGE_EXTERNAL_PRIORITY,AGENT_ONLY) and the Core repository contract. Remove shared skill activation/bookkeeping and toolkit-binding APIs in favor of explicit request/session state. No compatibility shims are added. English and Chinese tool and AG-UI guides include the new semantics and usage.Custom tool instances remain shared and must support concurrent use. Callers own cleanup of explicitly supplied skill working directories after executions stop using them.
Validation
371 targeted tests passed, with zero failures/errors/skips across Core, AG-UI, and Harness. Coverage includes request override/hiding through direct and batch entrypoints, overlapping managed executions, group/callback isolation, construction-time registry/metadata/meta-tool isolation, A → B → A resource stability, and contextual repositories. The AG-UI Spring Boot starter and dependencies also compiled.
Ran scoped Maven test invocations plus
spotless:applyandgit diff --check. Full repository tests and deployment were intentionally not run, following the requested targeted local validation scope.Checklist
mvn spotless:applymvn test) — full repository suite not run; 371 targeted tests passed