Skip to content

feat(core): add InputMessageDeduplicationMiddleware to deduplicate full-history resent input and keep only the incremental delta - #3467

Closed
xzxiaoshan wants to merge 15 commits into
agentscope-ai:mainfrom
xzxiaoshan:feat/message-anchor-merge-middleware
Closed

xzxiaoshan wants to merge 15 commits into
agentscope-ai:mainfrom
xzxiaoshan:feat/message-anchor-merge-middleware

Conversation

@xzxiaoshan

@xzxiaoshan xzxiaoshan commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

AG-UI clients (e.g. CopilotKit) resend the full message history on every turn. When the server
persists conversation context through an AgentState store, the resent prefix gets replayed
into the agent and duplicates the persisted context.

InputMessageDeduplicationMiddleware strips this overlapping prefix at the call boundary — the
last persisted context message acts as the anchor — so only the incremental messages reach the
agent.

This is not AG-UI specific. Any application layer that passes in the full message history while
the server persists context (protocol adapters, chat frontends, replayed event sources) hits the
same duplication; the middleware is protocol-neutral and lives in agentscope-core alongside
the other standard middlewares. It is opt-in: developers register it on agents whose input
source resends history, e.g.

ReActAgent agent = ReActAgent.builder()
        // ...
        .middleware(new InputMessageDeduplicationMiddleware())
        .build();

Agents whose frontend message list is the single source of truth (no server-side history)
should not register it.

Changes

  • Add InputMessageDeduplicationMiddleware in agentscope-core (io.agentscope.core.middleware),
    with id-first / role+content fallback anchor matching, pending-tool resume, and regenerate
    semantics
  • Simplify AguiRequestProcessor: input messages now pass through in full; dedup
    responsibility moves to the middleware, replacing the old hasMemory-based last-message
    extraction
  • Tests: algorithm + ReAct agent integration in core, AG-UI converter round-trip contract in the
    agui extension, harness path in HarnessInputMessageDeduplicationTest
  • Register the middleware in the agui/copilotkit documentation examples
  • Update EN/ZH AG-UI integration docs with applicability and migration notes

Fixes #2023

…ll-history resent input and keep only the incremental delta
# Conflicts:
#	agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui/src/main/java/io/agentscope/core/agui/adapter/AguiAgentAdapter.java
@codecov

codecov Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.04950% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...iddleware/InputMessageDeduplicationMiddleware.java 95.45% 1 Missing and 3 partials ⚠️
...cope/core/agui/converter/AguiMessageConverter.java 91.66% 0 Missing and 1 partial ⚠️

📢 Thoughts on this report? Let us know!

xzxiaoshan and others added 5 commits October 14, 2026 13:34
…ing ids

Upstream agentscope-ai#3239 rewrote every outbound AG-UI message id to
agui::<sourceId>-<UUID>, which silently broke the id round-trip
contract that InputMessageDeduplicationMiddleware anchoring relies on
(R2): resent history could never match the persisted context by id, so
the converter round-trip test failed after merging main.

Restore id fidelity while keeping agentscope-ai#3239's goal of distinct ids for
expanded messages:

- one-to-one conversions keep the source id unchanged
- an expansion keeps the source id on exactly one sibling: the
  standard message of a reasoning split, or the last result of a
  multi-result tool message (the anchor matches the last resent
  sibling, so earlier siblings strip together with it)
- every other sibling gets a deterministic derived id
  <sourceId>::<qualifier> ("reasoning", or the tool call id), making
  repeated conversions idempotent instead of regenerating UUIDs
Resolve conflicts with main:

- AguiRequestProcessorTest.java: keep assertNull import (used by main's
  new first-class userId tests), drop assertSame (its
  extractLatestUserMessage test was removed by this branch's
  InputMessageDeduplicationMiddleware rework).
- HarnessInputMessageDeduplicationTest: exclude main's new per-turn
  synthetic state projections (METADATA_SYNTHETIC: subagent catalog,
  session-state context items) from conversationTexts assertions; the
  dedup regression asserts caller history appears exactly once and the
  request-only projections are orthogonal.
@mintlify

mintlify Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 3c2896d.

Approve preview

Conflict resolution in AguiMessageConverter: adopt main's list-based
structure with media/document InputContents while keeping this branch's
stable message-ID scheme (source ID on exactly one sibling, deterministic
sourceId::qualifier derived IDs for the others; random generatedMessageId
removed).

InputMessageDeduplicationMiddlewareConverterTest fixture moved to a user
media message: main now maps assistant media to structured blocks, which
toMsg rejects by design (user/tool only, pinned upstream).
…-merge-middleware

# Conflicts:
#	docs/v2/en/integration/protocol/agui.md
#	docs/v2/zh/integration/protocol/agui.md
# Conflicts:
#	agentscope-extensions/agentscope-extensions-protocol/agentscope-extensions-agui/src/main/java/io/agentscope/core/agui/converter/AguiMessageConverter.java
#	docs/v2/en/integration/protocol/agui.md
#	docs/v2/zh/integration/protocol/agui.md
…on test

HarnessInputMessageDeduplicationTest counted the model calls seen by the
agent's Model after dropping only the memory-extraction ones. The harness
also runs a fire-and-forget memory consolidation after each agent call,
whose prompt that filter does not match. Whether the call happens depends
on which background task wins the race between the flush writing the daily
ledger and the maintenance reading it, so it lands in the capture at a
timing-dependent position:

- fullTranscriptDedup_survivesSessionDefaultsDerivation: expected <2> but
  was <3> (ubuntu CI, d4bdf6a)
- dedupedInput_sparesTheCallerImmutableList_throughDerivation: expected
  <[first, done, second]> but was <[Current MEMORY.md: ... (ubuntu CI,
  642d8bc)

Disable the memory hooks on both agents so only reasoning calls reach the
model, and assert on every captured call instead of a filtered view.
@jujn

This comment was marked as outdated.

@xzxiaoshan

This comment was marked as outdated.

Replace the bundled InputMessageDeduplicationMiddleware with a
declaration: the developer states whether the front end sends the whole
conversation or only new messages, and the adapter passes the request
messages to the agent unchanged in both modes.

- Add the core enum InputMessageMode (FULL, INCREMENTAL), carried on the
  RuntimeContext as a typed attribute. AguiAdapterConfig.messageMode and
  the starter property agentscope.agui.message-mode declare it, and the
  adapter publishes it for agent-side code.
- Clear the attribute for subagent calls in SubAgentTool and
  DefaultAgentManager: a child's input is its task prompt.
- Remove the middleware, its three tests and the registrations in the
  documentation examples.
- Document the modes, the CopilotKit messageFilter alternative and a
  custom-middleware outline for full-history resends in the AG-UI guide
  (EN/ZH, v2 and dev).
@xzxiaoshan xzxiaoshan changed the title feat(core): add InputMessageDeduplicationMiddleware to deduplicate full-history resent input and keep only the incremental delta feat(agui): replace transcript trimming with a declared input message mode Dec 1, 2026
… middleware"

This reverts commit 5a3a92f.

PR agentscope-ai#3467 returns to the original middleware approach and is kept as a
backup. The documentation-only direction was carried by PR agentscope-ai#4523.
@xzxiaoshan xzxiaoshan changed the title feat(agui): replace transcript trimming with a declared input message mode feat(core): add InputMessageDeduplicationMiddleware to deduplicate full-history resent input and keep only the incremental delta Dec 1, 2026
@xzxiaoshan

Copy link
Copy Markdown
Collaborator Author

Superseded by #4523 and #4535.

#4523 (merged) removes the hasMemory() trim from AguiRequestProcessor and documents the options for a front end that resends the whole history. #4535 ships the server-side InputMessageDeduplicationMiddleware in the AG-UI extension instead of core.

The outbound id preservation in AguiMessageConverter is not carried over: #4535 matches resent assistant messages by content, because the ids the stream gives them are not the persisted message ids.

@xzxiaoshan xzxiaoshan closed this Dec 2, 2026
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.

[Feature] AG-UI 应在 Harness + AgentStateStore 场景下自动裁剪全量 messages(CopilotKit)

2 participants