Skip to content

feat(middleware): add activePoints() extension-point participation declaration - #3371

Merged
jujn merged 3 commits into
agentscope-ai:mainfrom
xzxiaoshan:feat/middleware-extensionpoint
Sep 30, 2026
Merged

jujn merged 3 commits into
agentscope-ai:mainfrom
xzxiaoshan:feat/middleware-extensionpoint

Conversation

@xzxiaoshan

Copy link
Copy Markdown
Collaborator

Summary

Introduce a declarative participation mechanism for middleware extension points: MiddlewareBase gains a nested ExtensionPoint enum and an activePoints() method (defaulting to all points), and ReActAgent groups middlewares per extension point once at construction, building each point's chain from active participants only. This enables zero-wrapper-layer pass-through for extension points with no participants and removes the per-call reflection detection in applySystemPromptMiddlewares.

This change is strictly positive: it eliminates redundant wrapper layers and runtime reflection, adds a participation switch for debugging/gradual rollout, and makes the middleware execution plan visible at construction time — while remaining fully backward compatible, with zero changes required for existing users.

Motivation

Previously the framework treated all extension points uniformly:

  • Onion chains wrapped everything: MiddlewareChain.build wrapped every registered middleware at every onion point (onAgent / onReasoning / onActing), even middleware that never overrides that point — costing one lambda + one next.apply delegation per layer per point.
  • Runtime reflection: applySystemPromptMiddlewares probed each middleware via getMethod(...).getDeclaringClass() != MiddlewareBase.class on every call, just to detect whether anyone actually overrides onSystemPrompt (with a known misjudgment risk on JDK dynamic proxies).
  • No participation switch: a middleware could not declare "I implement this method but am temporarily inactive at this point" without commenting out code or unregistering.

What changed

API (MiddlewareBase, purely additive)

  • New nested enum MiddlewareBase.ExtensionPoint: ON_AGENT, ON_REASONING, ON_ACTING, ON_MODEL_CALL, ON_SYSTEM_PROMPT, ON_AGENT_STATE_READY.
  • New default Set<ExtensionPoint> activePoints() returning EnumSet.allOf(ExtensionPoint.class) — middlewares that do not override it keep today's behavior at every point, including extension points added in future releases.

Framework (ReActAgent)

  • groupMiddlewares(...) reads each middleware's activePoints() once at construction (null treated as full set, results defensively copied), producing an immutable EnumMap shared across concurrent calls.
  • Every MiddlewareChain.build call site (6 in total, including both onModelCall paths and both onActing paths) and the onAgentStateReady notification loop now use only that point's participant list; MiddlewareChain itself is unchanged (empty list already returns the core directly, which is exactly the zero-wrapping behavior we want).
  • The per-call reflection detection in applySystemPromptMiddlewares is deleted; the point now short-circuits when it has no participants.
  • New accessor middlewaresAt(ExtensionPoint) exposes the construction-time participant list per point (useful for diagnostics/tracing).

Built-in middlewares

All 27 built-in implementations (5 in agentscope-core, 18 in agentscope-harness, 4 in agentscope-extensions) now declare their precise active sets matching their actual overrides — including SandboxLifecycleMiddleware, which legitimately declares an empty set (it only implements the HarnessRuntimeMiddleware lifecycle contract called explicitly by HarnessAgent).

Docs

Updated docs/v2/en/docs/building-blocks/middleware.md and docs/v2/zh/docs/building-blocks/middleware.md (kept aligned): semantics of activePoints(), the four declaration/override states, orthogonality with order(), and the recommended practice of declaring precise sets. Runnable examples under agentscope-examples/documentation/.../middleware/ updated accordingly.

Compatibility

  • Purely additive API (default method + nested enum); no public contract broken.
  • Middlewares that do not override activePoints() behave exactly as before at all six points. The only microscopic difference: at onSystemPrompt they now run through the default pass-through chain instead of being reflection-skipped — logically equivalent in semantics, and the code is structurally sounder (deterministic construction-time grouping replaces per-call reflection probing).
  • Overriding activePoints() is new opt-in API with no existing users; the consequence of a wrong declaration (a point not firing) is documented behavior.

…claration

Introduce a nested ExtensionPoint enum and an activePoints() method defaulting to all points on MiddlewareBase. ReActAgent reads declarations once at construction and builds each extension point's chain from active participants only, so points with no participants pass straight through with zero wrapper layers, and the per-call reflection detection in applySystemPromptMiddlewares is removed. All 27 built-in middlewares declare their precise active sets, with EN/ZH docs and examples updated accordingly.
# Conflicts:
#	agentscope-core/src/main/java/io/agentscope/core/tracing/OtelTracingMiddleware.java

@oss-maintainer oss-maintainer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary

Adds MiddlewareBase.activePoints() plus ExtensionPoint, a per-middleware participation switch, and replaces the reflection-based override probe in applySystemPromptMiddlewares with construction-time grouping (groupedMiddlewares / middlewaresAt(point)) in ReActAgent. ~25 shipped middlewares across core, harness, extensions (aistio, judge/jev) and the doc examples declare their points explicitly; new core + harness tests and EN/ZH docs come along.

I checked the compatibility-critical parts myself against the patch: the new contract method is a default returning EnumSet.allOf(ExtensionPoint.class), so existing third-party implementors keep all-points-active behavior (including points added later, since grouping iterates values()); a null return is normalized through Objects.requireNonNullElse to the full set; grouping runs after the builder order() sort so onion order is preserved; and dispatch is an immutable EnumMap lookup with no per-invocation allocation, replacing per-build reflection. Spot-checks on the shipped declarations matched implemented hooks (SandboxLifecycleMiddleware declaring EnumSet.noneOf(...) is intentional and documented — its lifecycle is driven explicitly by HarnessAgent, not by a hook). CI is green on build (ubuntu-latest) / codecov/patch, license/cla signed.

Approved. One info-level note inline about subclassing a shipped non-final middleware, which silently opts the subclass out of any hook it adds.


Automated review by github-manager-bot

* a participation switch, not a statement about which methods are
* overridden: a point declared active but not overridden simply runs
* its default (pass-through / no-op), and a point omitted is never
* invoked — even if overridden.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The documented semantics ("a point omitted is never invoked — even if overridden") make subclassing shipped middlewares a silent-skip footgun: TaskReminderMiddleware, FinalAnswerFilterMiddleware, CompactionMiddleware, PlanModeMiddleware, and SubagentsMiddleware are all public non-final classes with narrow declarations (e.g. TaskReminderMiddleware declares only ON_SYSTEM_PROMPT+ON_REASONING), so a user subclass that adds an onModelCall override will be silently skipped. The docs table covers the general rule, but consider marking the shipped middlewares final or adding one line to their class javadoc ("subclasses must re-declare activePoints()") to make the trap discoverable at the point of use.

…larations

Review feedback: shipped middlewares are public non-final classes with
narrow declarations, so a subclass adding a new hook override would be
silently skipped. Add a one-line contract note at each of the 27
built-in activePoints() overrides (subclasses overriding more hooks
must extend the set) and a matching recommended-practice paragraph in
the EN/ZH middleware docs.
@jujn
jujn merged commit addf82b into agentscope-ai:main Sep 30, 2026
7 checks passed
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.

3 participants