2626import io .agentscope .core .state .StateModule ;
2727import io .agentscope .core .tracing .TracerRegistry ;
2828import java .util .ArrayList ;
29+ import java .util .Comparator ;
2930import java .util .List ;
3031import java .util .Map ;
3132import java .util .UUID ;
@@ -98,6 +99,8 @@ public abstract class AgentBase implements StateModule, Agent {
9899 // Interrupt state management (available to all agents)
99100 private final AtomicBoolean interruptFlag = new AtomicBoolean (false );
100101 private final AtomicReference <Msg > userInterruptMessage = new AtomicReference <>(null );
102+ // Hook non-null
103+ private static final Comparator <Hook > HOOK_COMPARATOR = Comparator .comparingInt (Hook ::priority );
101104
102105 /**
103106 * Constructor for AgentBase.
@@ -133,6 +136,7 @@ public AgentBase(String name, String description, boolean checkRunning, List<Hoo
133136 this .checkRunning = checkRunning ;
134137 this .hooks = new CopyOnWriteArrayList <>(hooks != null ? hooks : List .of ());
135138 this .hooks .addAll (systemHooks );
139+ sortHooks ();
136140 }
137141
138142 @ Override
@@ -474,9 +478,14 @@ public List<Hook> getHooks() {
474478 protected void addHook (Hook hook ) {
475479 if (hook != null ) {
476480 hooks .add (hook );
481+ sortHooks ();
477482 }
478483 }
479484
485+ private void sortHooks () {
486+ this .hooks .sort (HOOK_COMPARATOR );
487+ }
488+
480489 /**
481490 * Remove a hook from this agent dynamically.
482491 *
@@ -498,7 +507,7 @@ protected void removeHook(Hook hook) {
498507 * @return Sorted list of hooks
499508 */
500509 protected List <Hook > getSortedHooks () {
501- return hooks . stream (). sorted ( java . util . Comparator . comparingInt ( Hook :: priority )). toList () ;
510+ return hooks ;
502511 }
503512
504513 /**
@@ -692,7 +701,7 @@ private Flux<Event> createEventStream(StreamOptions options, Supplier<Mono<Msg>>
692701 new StreamingHook (sink , options );
693702
694703 // Add temporary hook
695- hooks . add (streamingHook );
704+ addHook (streamingHook );
696705
697706 // Use Mono.defer to ensure trace context propagation
698707 // while maintaining streaming hook functionality
0 commit comments