Module: SwarmSDK::Swarm::HookTriggers

Included in:
SwarmSDK::Swarm
Defined in:
lib/swarm_sdk/swarm/hook_triggers.rb

Overview

Hook triggering methods for swarm lifecycle events

Extracted from Swarm to reduce class size and centralize hook execution logic. These methods build contexts and execute hooks via the hook registry.

Instance Method Summary collapse

Instance Method Details

#add_default_callback(event, matcher: nil, priority: 0, &block) ⇒ self

Add a default callback for an event

Parameters:

  • Event type (:pre_tool_use, :post_tool_use, etc.)

  • (defaults to: nil)

    Optional matcher to filter events

  • (defaults to: 0)

    Callback priority (higher = later)

  • Hook implementation

Returns:



17
18
19
20
# File 'lib/swarm_sdk/swarm/hook_triggers.rb', line 17

def add_default_callback(event, matcher: nil, priority: 0, &block)
  @hook_registry.add_default(event, matcher: matcher, priority: priority, &block)
  self
end

#trigger_swarm_stop(result) ⇒ Hooks::Result?

Trigger swarm_stop hooks and check for reprompt

Parameters:

  • The execution result

Returns:

  • Hook result (reprompt action if applicable)



26
27
28
29
30
31
32
33
34
# File 'lib/swarm_sdk/swarm/hook_triggers.rb', line 26

def trigger_swarm_stop(result)
  context = build_swarm_stop_context(result)
  executor = Hooks::Executor.new(@hook_registry, logger: RubyLLM.logger)
  executor.execute_safe(event: :swarm_stop, context: context, callbacks: [])
rescue StandardError => e
  LogStream.emit_error(e, source: "hook_triggers", context: "swarm_stop", agent: @lead_agent)
  RubyLLM.logger.debug("SwarmSDK: Error in swarm_stop hook: #{e.message}")
  nil
end

#trigger_swarm_stop_final(result, start_time, logs) ⇒ void

This method returns an undefined value.

Trigger swarm_stop for final event emission (called in ensure block)

Parameters:

  • Execution result

  • Execution start time

  • Collected logs



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/swarm_sdk/swarm/hook_triggers.rb', line 42

def trigger_swarm_stop_final(result, start_time, logs)
  result ||= Result.new(
    content: nil,
    agent: @lead_agent&.to_s || "unknown",
    logs: logs,
    duration: Time.now - start_time,
    error: StandardError.new("Unknown error"),
  )

  context = build_swarm_stop_context(result)
  executor = Hooks::Executor.new(@hook_registry, logger: RubyLLM.logger)
  executor.execute_safe(event: :swarm_stop, context: context, callbacks: [])
rescue StandardError => e
  LogStream.emit_error(e, source: "hook_triggers", context: "swarm_stop_final", agent: @lead_agent)
  RubyLLM.logger.debug("SwarmSDK: Error in swarm_stop final emission: #{e.message}")
end