Class: SwarmSDK::Tools::Delegate

Inherits:
Base
  • Object
show all
Defined in:
lib/swarm_sdk/tools/delegate.rb

Overview

Delegate tool for working with other agents in the swarm

Creates agent-specific collaboration tools (e.g., WorkWithBackend) that allow one agent to work with another agent. Supports pre/post delegation hooks for customization.

Constant Summary collapse

TOOL_NAME_PREFIX =

Tool name prefix for delegation tools Change this to customize the tool naming pattern (e.g., "DelegateTaskTo", "AskAgent", etc.)

"WorkWith"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

removable, removable?, #removable?

Constructor Details

#initialize(delegate_name:, delegate_description:, delegate_chat:, agent_name:, swarm:, delegating_chat: nil, custom_tool_name: nil, preserve_context: true) ⇒ Delegate

Initialize a delegation tool

Parameters:

  • delegate_name (String)

    Name of the delegate agent (e.g., "backend")

  • delegate_description (String)

    Description of the delegate agent

  • delegate_chat (AgentChat, nil)

    The chat instance for the delegate agent (nil if delegating to swarm)

  • agent_name (Symbol, String)

    Name of the agent using this tool

  • swarm (Swarm)

    The swarm instance (provides hook_registry, swarm_registry)

  • delegating_chat (Agent::Chat, nil) (defaults to: nil)

    The chat instance of the agent doing the delegating (for accessing hooks)

  • custom_tool_name (String, nil) (defaults to: nil)

    Optional custom tool name (overrides auto-generated name)

  • preserve_context (Boolean) (defaults to: true)

    Whether to preserve conversation context between delegations (default: true)



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'lib/swarm_sdk/tools/delegate.rb', line 52

def initialize(
  delegate_name:,
  delegate_description:,
  delegate_chat:,
  agent_name:,
  swarm:,
  delegating_chat: nil,
  custom_tool_name: nil,
  preserve_context: true
)
  super()

  @delegate_name = delegate_name
  @delegate_description = delegate_description
  @delegate_chat = delegate_chat
  @agent_name = agent_name
  @swarm = swarm
  @delegating_chat = delegating_chat
  @preserve_context = preserve_context

  # Use custom tool name if provided, otherwise generate using canonical method
  @tool_name = custom_tool_name || self.class.tool_name_for(delegate_name)
  @delegate_target = delegate_name.to_s

  # Track concurrent delegations to this target.
  # When multiple parallel tool calls target the same delegate, only the first
  # preserves context; subsequent concurrent calls always clear context to
  # prevent cross-contamination between independent parallel work.
  #
  # No Mutex needed: Async Fibers run on a single thread and only switch at
  # explicit yield points (IO, sleep, semaphore.acquire). Integer increment
  # and decrement never yield, so they are inherently atomic.
  @active_count = 0
end

Instance Attribute Details

#delegate_chatObject (readonly)

Returns the value of attribute delegate_chat.



40
41
42
# File 'lib/swarm_sdk/tools/delegate.rb', line 40

def delegate_chat
  @delegate_chat
end

#delegate_nameObject (readonly)

Returns the value of attribute delegate_name.



40
41
42
# File 'lib/swarm_sdk/tools/delegate.rb', line 40

def delegate_name
  @delegate_name
end

#delegate_targetObject (readonly)

Returns the value of attribute delegate_target.



40
41
42
# File 'lib/swarm_sdk/tools/delegate.rb', line 40

def delegate_target
  @delegate_target
end

#preserve_contextObject (readonly)

Returns the value of attribute preserve_context.



40
41
42
# File 'lib/swarm_sdk/tools/delegate.rb', line 40

def preserve_context
  @preserve_context
end

#tool_nameObject (readonly)

Returns the value of attribute tool_name.



40
41
42
# File 'lib/swarm_sdk/tools/delegate.rb', line 40

def tool_name
  @tool_name
end

Class Method Details

.tool_name_for(delegate_name) ⇒ String

Generate tool name for a delegate agent

This is the single source of truth for delegation tool naming. Used both when creating Delegate instances and when predicting tool names for agent context setup.

Converts names to PascalCase: backend → Backend, slack_agent → SlackAgent

Examples:

Simple name

tool_name_for(:backend) # => "WorkWithBackend"

Name with underscore

tool_name_for(:slack_agent) # => "WorkWithSlackAgent"

Parameters:

  • delegate_name (String, Symbol)

    Name of the delegate agent

Returns:

  • (String)

    Tool name (e.g., "WorkWithBackend", "WorkWithSlackAgent")



33
34
35
36
37
# File 'lib/swarm_sdk/tools/delegate.rb', line 33

def tool_name_for(delegate_name)
  # Convert to PascalCase: split on underscore, capitalize each part, join
  pascal_case = delegate_name.to_s.split("_").map(&:capitalize).join
  "#{TOOL_NAME_PREFIX}#{pascal_case}"
end

Instance Method Details

#descriptionObject

Override description to return dynamic string based on delegate



88
89
90
# File 'lib/swarm_sdk/tools/delegate.rb', line 88

def description
  "Work with #{@delegate_name} to delegate work, ask questions, or collaborate. #{@delegate_description}"
end

#execute(message:, reset_context: false) ⇒ String

Execute delegation with pre/post hooks

Uses Fiber-local path tracking for circular dependency detection. Each concurrent delegation runs in its own Fiber (via Async), so the path is isolated per execution path. This correctly distinguishes parallel fan-out (A→B, A→B) from true circular dependencies (A→B→A).

Parameters:

  • message (String)

    Message to send to the agent

  • reset_context (Boolean) (defaults to: false)

    Whether to reset the agent's conversation history before delegation

Returns:

  • (String)

    Result from delegate agent or error message



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
# File 'lib/swarm_sdk/tools/delegate.rb', line 143

def execute(message:, reset_context: false)
  # Save the current delegation path so we can restore it after execution.
  # The extended path (with our target) is only needed during chat.ask() so
  # child Fibers (nested delegations) inherit it. After delegation returns,
  # this Fiber's path should be unchanged.
  saved_delegation_path = Fiber[:delegation_path]

  # Access swarm infrastructure
  hook_registry = @swarm.hook_registry
  swarm_registry = @swarm.swarm_registry

  # Check for circular dependency using Fiber-local path
  # Each Fiber inherits the parent's path, so nested delegations
  # accumulate the full chain while parallel siblings remain isolated
  delegation_path = saved_delegation_path || []
  if delegation_path.include?(@delegate_target)
    emit_circular_warning(delegation_path)
    return "Error: Circular delegation detected: #{delegation_path.join(" -> ")} -> #{@delegate_target}. " \
      "Please restructure your delegation to avoid infinite loops."
  end

  # Get agent-specific hooks from the delegating chat instance
  agent_hooks = if @delegating_chat&.respond_to?(:hook_agent_hooks)
    @delegating_chat.hook_agent_hooks || {}
  else
    {}
  end

  # Trigger pre_delegation callback
  context = Hooks::Context.new(
    event: :pre_delegation,
    agent_name: @agent_name,
    swarm: @swarm,
    delegation_target: @delegate_target,
    metadata: {
      tool_name: @tool_name,
      message: message,
      timestamp: Time.now.utc.iso8601,
    },
  )

  executor = Hooks::Executor.new(hook_registry, logger: RubyLLM.logger)
  pre_agent_hooks = agent_hooks[:pre_delegation] || []
  result = executor.execute_safe(event: :pre_delegation, context: context, callbacks: pre_agent_hooks)

  # Check if callback halted or replaced the delegation
  if result.halt?
    return result.value || "Delegation halted by callback"
  elsif result.replace?
    return result.value
  end

  # Determine delegation type and proceed
  delegation_result = if @delegate_chat
    # Delegate to agent
    delegate_to_agent(message, reset_context: reset_context)
  elsif swarm_registry&.registered?(@delegate_target)
    # Delegate to registered swarm
    delegate_to_swarm(message, swarm_registry, reset_context: reset_context)
  else
    raise ConfigurationError, "Unknown delegation target: #{@delegate_target}"
  end

  # Trigger post_delegation callback
  post_context = Hooks::Context.new(
    event: :post_delegation,
    agent_name: @agent_name,
    swarm: @swarm,
    delegation_target: @delegate_target,
    delegation_result: delegation_result,
    metadata: {
      tool_name: @tool_name,
      message: message,
      result: delegation_result,
      timestamp: Time.now.utc.iso8601,
    },
  )

  post_agent_hooks = agent_hooks[:post_delegation] || []
  post_result = executor.execute_safe(event: :post_delegation, context: post_context, callbacks: post_agent_hooks)

  # Return modified result if callback replaces it
  if post_result.replace?
    post_result.value
  else
    delegation_result
  end
rescue Faraday::TimeoutError, Net::ReadTimeout => e
  # Log timeout error as JSON event
  LogStream.emit(
    type: "delegation_error",
    agent: @agent_name,
    swarm_id: @swarm.swarm_id,
    parent_swarm_id: @swarm.parent_swarm_id,
    delegate_to: @tool_name,
    error_class: e.class.name,
    error_message: "Request timed out",
    error_backtrace: e.backtrace&.first(5) || [],
  )
  "Error: Request to #{@tool_name} timed out. The agent may be overloaded or the LLM service is not responding. Please try again or simplify the task."
rescue Faraday::Error => e
  # Log network error as JSON event
  LogStream.emit(
    type: "delegation_error",
    agent: @agent_name,
    swarm_id: @swarm.swarm_id,
    parent_swarm_id: @swarm.parent_swarm_id,
    delegate_to: @tool_name,
    error_class: e.class.name,
    error_message: e.message,
    error_backtrace: e.backtrace&.first(5) || [],
  )
  "Error: Network error communicating with #{@tool_name}: #{e.class.name}. Please check connectivity and try again."
rescue StandardError => e
  # Log unexpected error as JSON event
  backtrace_array = e.backtrace&.first(5) || []
  LogStream.emit(
    type: "delegation_error",
    agent: @agent_name,
    swarm_id: @swarm.swarm_id,
    parent_swarm_id: @swarm.parent_swarm_id,
    delegate_to: @tool_name,
    error_class: e.class.name,
    error_message: e.message,
    error_backtrace: backtrace_array,
  )
  # Return error string for LLM
  backtrace_str = backtrace_array.join("\n  ")
  "Error: #{@tool_name} encountered an error: #{e.class.name}: #{e.message}\nBacktrace:\n  #{backtrace_str}"
ensure
  # Restore the calling Fiber's delegation path.
  # The extended path was only needed during chat.ask() so child Fibers
  # (spawned for nested tool calls) could inherit it for circular detection.
  Fiber[:delegation_path] = saved_delegation_path
end

#initialize_delegate!Agent::Chat

Force initialization of lazy delegate

If the delegate is lazy-loaded, this will trigger immediate initialization. For eager delegates, this is a no-op.

Returns:



129
130
131
# File 'lib/swarm_sdk/tools/delegate.rb', line 129

def initialize_delegate!
  resolve_delegate_chat
end

#initialized?Boolean

Check if this delegate has been initialized

Returns:

  • (Boolean)

    True if delegate chat is ready (either eager or lazy-initialized)



117
118
119
120
121
# File 'lib/swarm_sdk/tools/delegate.rb', line 117

def initialized?
  return true unless lazy?

  @delegate_chat.initialized?
end

#lazy?Boolean

Check if this delegate uses lazy loading

Returns:

  • (Boolean)

    True if delegate is lazy-loaded



110
111
112
# File 'lib/swarm_sdk/tools/delegate.rb', line 110

def lazy?
  @delegate_chat.is_a?(Swarm::LazyDelegateChat)
end

#nameObject

Override name to return custom delegation tool name



103
104
105
# File 'lib/swarm_sdk/tools/delegate.rb', line 103

def name
  @tool_name
end