Repository navigation
feat(middleware): add activePoints() extension-point participation declaration - #3371
Conversation
…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
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
oss-maintainer
left a comment
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
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.
Summary
Introduce a declarative participation mechanism for middleware extension points:
MiddlewareBasegains a nestedExtensionPointenum and anactivePoints()method (defaulting to all points), andReActAgentgroups 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 inapplySystemPromptMiddlewares.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:
MiddlewareChain.buildwrapped every registered middleware at every onion point (onAgent/onReasoning/onActing), even middleware that never overrides that point — costing one lambda + onenext.applydelegation per layer per point.applySystemPromptMiddlewaresprobed each middleware viagetMethod(...).getDeclaringClass() != MiddlewareBase.classon every call, just to detect whether anyone actually overridesonSystemPrompt(with a known misjudgment risk on JDK dynamic proxies).What changed
API (
MiddlewareBase, purely additive)MiddlewareBase.ExtensionPoint:ON_AGENT,ON_REASONING,ON_ACTING,ON_MODEL_CALL,ON_SYSTEM_PROMPT,ON_AGENT_STATE_READY.default Set<ExtensionPoint> activePoints()returningEnumSet.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'sactivePoints()once at construction (nulltreated as full set, results defensively copied), producing an immutableEnumMapshared across concurrent calls.MiddlewareChain.buildcall site (6 in total, including bothonModelCallpaths and bothonActingpaths) and theonAgentStateReadynotification loop now use only that point's participant list;MiddlewareChainitself is unchanged (empty list already returns the core directly, which is exactly the zero-wrapping behavior we want).applySystemPromptMiddlewaresis deleted; the point now short-circuits when it has no participants.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 inagentscope-harness, 4 inagentscope-extensions) now declare their precise active sets matching their actual overrides — includingSandboxLifecycleMiddleware, which legitimately declares an empty set (it only implements theHarnessRuntimeMiddlewarelifecycle contract called explicitly byHarnessAgent).Docs
Updated
docs/v2/en/docs/building-blocks/middleware.mdanddocs/v2/zh/docs/building-blocks/middleware.md(kept aligned): semantics ofactivePoints(), the four declaration/override states, orthogonality withorder(), and the recommended practice of declaring precise sets. Runnable examples underagentscope-examples/documentation/.../middleware/updated accordingly.Compatibility
defaultmethod + nested enum); no public contract broken.activePoints()behave exactly as before at all six points. The only microscopic difference: atonSystemPromptthey 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).activePoints()is new opt-in API with no existing users; the consequence of a wrong declaration (a point not firing) is documented behavior.