Skip to content

fix: preserve skill isolation and tool result history - #2319

Merged
chickenlj merged 1 commit into
agentscope-ai:mainfrom
RainYuY:fix/static-skills-when-dynamic-disabled
Jul 23, 2026
Merged

chickenlj merged 1 commit into
agentscope-ai:mainfrom
RainYuY:fix/static-skills-when-dynamic-disabled

Conversation

@RainYuY

@RainYuY RainYuY commented Jul 20, 2026

Copy link
Copy Markdown
Collaborator

AgentScope-Java Version

2.0.1-SNAPSHOT

Description

Background

This PR fixes several correctness, compatibility, and session-isolation issues in the Harness skill runtime and tool-result eviction flow.

Previously:

  • Fresh sessions could lose tool groups that were active when the agent was built.
  • Explicitly persisted empty tool-group state could be mistaken for missing state.
  • Static skill mode bypassed skill and visibility filters and lost access to lazily loaded skill resources.
  • Concurrent sessions shared a mutable SkillCatalog, allowing one session to overwrite or observe another session's filtered skill view.
  • WorkspaceSkillRepository could resolve skills using another concurrent session's active runtime context.
  • Persisted sessions with an empty active-group list could not see load_skill_through_path after upgrading.
  • Tool-result eviction modified canonical agent state but could leave the copied reasoning input unchanged.
  • Reused tool-call IDs could overwrite previously evicted results.
  • Cached eviction replacements could overwrite metadata or state rewritten by pre-reasoning hooks.
  • Real tool output beginning with the eviction placeholder text could bypass eviction.

Changes

Session and toolkit state

  • Capture the toolkit's initially active groups after agent construction.
  • Apply those groups only when creating a genuinely new session.
  • Preserve explicitly persisted empty active-group state.
  • Distinguish a missing legacy toolkit_activeGroups key from a present but empty value.
  • Preserve the complete RuntimeContext when merging toolkit-level execution context.

Skill runtime

  • Use HarnessSkillMiddleware for both live and frozen repository modes.
  • Freeze repository enumeration when dynamic skills are disabled while retaining per-request filtering.
  • Apply SkillFilter and SkillVisibilityFilter before staging, prompt rendering, and catalog installation.
  • Preserve the source repository association needed for lazy resource loading.
  • Add RuntimeContextSkillRepository for repositories whose contents depend on the current request.
  • Make WorkspaceSkillRepository enumerate skills using the supplied request context.
  • Store SkillCatalog in the request-scoped RuntimeContext instead of a shared mutable reference.
  • Resolve load_skill_through_path authorization from the tool call's runtime context.
  • Register the skill loader as an ungrouped tool during agent construction so persisted sessions can continue to access it.
  • Retain the previous public constructors and methods as deprecated compatibility overloads.

Tool-result eviction

  • Evict oversized results from both canonical AgentState and the hook-modified ReasoningInput.
  • Preserve hook deletions, rewrites, metadata, result state, message metadata, timestamps, and usage.
  • Use content-addressed paths so reused tool-call IDs do not overwrite historical results.
  • Include result text in the in-call eviction fingerprint.
  • Cache only the generated placeholder instead of an entire ToolResultBlock.
  • Mark evicted results with dedicated metadata instead of recognizing them by text prefix.
  • Change the default eviction directory to the workspace-relative large_tool_results path.
  • Update the English and Chinese memory documentation accordingly.

Compatibility

The following previously published APIs remain available as deprecated compatibility paths:

  • SkillRuntime.currentCatalog()
  • SkillRuntime.install(SkillCatalog, Toolkit)
  • SkillLoadTool(AtomicReference<SkillCatalog>)

Context-bearing tool calls never fall back to the legacy shared catalog, preserving session isolation.

How to test

The focused core and Harness regression suite can be run with:

mvn -pl agentscope-harness -am \
  -Dtest=ReActAgentPerSessionStateTest,ToolExecutionContextIntegrationTest,ToolResultEvictionMiddlewareTest,HarnessSkillMiddlewareContextIsolationTest,WorkspaceSkillRepositoryTest,SkillRuntimeTest,SkillLoadToolFrontmatterViewTest,HarnessAgentDynamicHookBuilderTest \
  -Dsurefire.failIfNoSpecifiedTests=false \
  test

@RainYuY

RainYuY commented Jul 21, 2026

Copy link
Copy Markdown
Collaborator Author

@chickenlj @jujn PTAL

@chickenlj
chickenlj merged commit a7008d0 into agentscope-ai:main Jul 23, 2026
5 checks passed
gxgeek-n added a commit to gxgeek-n/agentscope-java that referenced this pull request Jul 23, 2026
…ol on fresh sessions

Add end-to-end tests pinning the fix for agentscope-java#2169: a fresh-session
ReActAgent built with a SkillBox must be able to execute
load_skill_through_path instead of receiving
"Unauthorized tool call: 'load_skill_through_path' is not available".

The tests drive a scripted model through a real ReAct loop with a registered
skill and assert on the tool result exactly as the model observes it:

- fresh session: the load tool executes and returns the skill content
- fresh session: ToolContextState keeps skill-build-in-tools activated
- second call in the same session: the load tool stays authorized

Verified both directions: all three tests fail on the v2.0.0 tag with the
exact "Unauthorized tool call" error from the issue, and pass on main with
the fresh-slot group seeding from agentscope-ai#2319.
wzl521 pushed a commit to wzl521/agentscope-java that referenced this pull request Aug 12, 2026
birdie7761 added a commit to birdie7761/agentscope-java that referenced this pull request Sep 28, 2026
…ning

pruneToolResults rebuilt each pruned ToolResultBlock with only id and
name, silently discarding metadata and resetting the execution state to
RUNNING (the constructor default). Eviction markers
(agentscope.tool_result_evicted), suspension markers
(agentscope_suspended) and error states were wiped, so a pruned block no
longer matched the consumers that branch on them
(ToolResultEvictionMiddleware.isEvicted, ToolResultBlock.isSuspended).
The carrying message also lost its usage.

Copy metadata and state from the original block and keep usage on the
rebuilt Msg, mirroring the lossless rebuild discipline of
ToolResultEvictionMiddleware (agentscope-ai#2319). Only the output text is replaced
with the head+tail preview.
birdie7761 added a commit to birdie7761/agentscope-java that referenced this pull request Sep 28, 2026
…ning

pruneToolResults rebuilt each pruned ToolResultBlock with only id and
name, silently discarding metadata and resetting the execution state to
RUNNING (the constructor default). Eviction markers
(agentscope.tool_result_evicted), suspension markers
(agentscope_suspended) and error states were wiped, so a pruned block no
longer matched the consumers that branch on them
(ToolResultEvictionMiddleware.isEvicted, ToolResultBlock.isSuspended).
The carrying message also lost its usage.

Copy metadata and state from the original block and keep usage on the
rebuilt Msg, mirroring the lossless rebuild discipline of
ToolResultEvictionMiddleware (agentscope-ai#2319). Only the output text is replaced
with the head+tail preview.
Buktal pushed a commit that referenced this pull request Oct 13, 2026
…3326)

## AgentScope-Java Version

2.0.4-SNAPSHOT (based on `main` @ `9c8b10d4e`)

## Description

`ConversationCompactor.pruneToolResults` trims old oversized tool
results to a head+tail preview. When rebuilding the trimmed block it
copies only `id` and `name`, which silently discards the rest of the
block's identity:

- **metadata** — wiped. Markers that downstream code branches on are
lost: the eviction marker `agentscope.tool_result_evicted` (written by
`ToolResultEvictionMiddleware`, #2319) and the suspension marker
`agentscope_suspended` (consumed by `ToolResultBlock.isSuspended()` and
ReActAgent's suspend/resume matching), plus any integrator-supplied
metadata.
- **state** — reset to `RUNNING` (the `ToolResultBlock` constructor
default for null), so a pruned `ERROR` result is rewritten as `RUNNING`.
`MessageUtils` result-state maps and event-side state reporting observe
the corrupted value.
- **`Msg.usage`** — dropped by the message rebuild.

The eviction middleware already follows a lossless rebuild discipline
(`withPlaceholder` preserves metadata and adds its own marker). This PR
applies the same discipline to prune: the rebuilt block now copies
`metadata` and `state` from the original block, and the rebuilt `Msg`
keeps `usage`. Only the output text is replaced with the preview.

Context size is strictly reduced, never grown — the preserved fields
were already in the conversation before pruning, and formatters do not
render block metadata into the model prompt. This matters once
lightweight pruning results reach the working `AgentState` (e.g. once
#2970/#2971 is addressed): a persisted-and-replayed pruned block
currently loses every field downstream consumers branch on.

### Compatibility

- No serialization/format change: `metadata`, `state`, `usage` are
existing `@JsonProperty` fields of `ToolResultBlock`/`Msg`.
- No context growth: only the output text shrinks relative to the
pre-prune message.
- Sessions persisted by older builds read back unchanged (those blocks
already carry the default values).

### Tests

New `ConversationCompactorPruneTest` (5 cases). The preservation case
was red-verified against pre-fix code — verbatim failure output:

```
org.opentest4j.AssertionFailedError: expected: <{agentscope.tool_result_evicted=true, agentscope_suspended=true, custom_key=custom_value}> but was: <{}>
```

| Test | Asserts |
|---|---|
| `pruneToolResults_preservesMetadataStateAndUsageWhenTrimming` |
metadata map, `isSuspended()`, `state=ERROR`, block id/name and `Msg`
id/metadata/timestamp/usage all survive; preview actually trimmed |
| `pruneToolResults_multiBlockMessagePrunesOnlyOversizedBlock` | a
message carrying several results is rebuilt with only the oversized
block replaced; untouched blocks keep their original reference (pinned
via `assertSame`, so the rebuild is surgical rather than destructive) |
| `pruneToolResults_skipsExcludedTools` | excluded tool is never pruned
(original list reference returned) |
| `pruneToolResults_returnsOriginalWhenBelowMinimum` | below-threshold
conversation returned unchanged |
| `pruneToolResults_handlesBlockWithoutMetadataOrState` | metadata-less
block prunes without failure, defaults intact |

Regression: `ConversationCompactorTest` 7/7,
`ToolResultEvictionMiddlewareTest` green, full `agentscope-harness`
suite green, `spotless:check` clean.

### Out of scope

The `truncateArgs` rebuilds in the same class keep even less
(`truncateToolUseArgs` drops the message id/metadata/usage;
`truncateToolUseBlock` drops `ToolUseBlock` metadata). They are masked
by the same #2970 discard path and left for a follow-up to keep this
change single-purpose.

One pre-existing interaction edge is worth recording: an eviction
placeholder larger than prune's `maxOutputChars` is itself prunable, and
the head+tail preview may cut the embedded `read_file` pointer text.
This PR preserves the eviction *marker* through that rewrite, but cannot
recover the pointer text itself; in practice the default placeholder
(~4K chars) only hits this under a custom `maxOutputChars` at or above
that size.

## Checklist

- [x] Code has been formatted with `mvn spotless:apply`
- [x] All tests are passing (`mvn test`)
- [x] Javadoc comments are complete and follow project conventions
- [x] Related documentation has been updated (PruneConfig has no
user-facing docs today; the method Javadoc documents the preservation
contract)
- [x] Code is ready for review
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants