swarm_sdk 2.0.0.pre.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,170 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SwarmSDK
4
+ # NodeContext provides context information to node transformers
5
+ #
6
+ # This class is passed to input and output transformers, giving them access to:
7
+ # - The original user prompt
8
+ # - Results from all previous nodes
9
+ # - Current node metadata
10
+ # - Convenience accessors for common operations
11
+ #
12
+ # @example Input transformer
13
+ # input do |ctx|
14
+ # ctx.content # Previous node's content (convenience)
15
+ # ctx.original_prompt # Original user prompt
16
+ # ctx.all_results[:plan] # Access any previous node
17
+ # ctx.node_name # Current node name
18
+ # end
19
+ #
20
+ # @example Output transformer
21
+ # output do |ctx|
22
+ # ctx.content # Current result's content (convenience)
23
+ # ctx.original_prompt # Original user prompt
24
+ # ctx.all_results[:plan] # Access previous nodes
25
+ # end
26
+ class NodeContext
27
+ attr_reader :original_prompt, :all_results, :node_name, :dependencies
28
+
29
+ # For input transformers: result from previous node(s)
30
+ attr_reader :previous_result
31
+
32
+ # For output transformers: current node's result
33
+ attr_reader :result
34
+
35
+ class << self
36
+ # Create a NodeContext for input transformers
37
+ #
38
+ # @param previous_result [Result, Hash, String] Previous node's result or hash of results
39
+ # @param all_results [Hash<Symbol, Result>] Results from all completed nodes
40
+ # @param original_prompt [String] The original user prompt
41
+ # @param node_name [Symbol] Current node name
42
+ # @param dependencies [Array<Symbol>] Node dependencies
43
+ # @param transformed_content [String, nil] Already-transformed content from previous output transformer
44
+ # @return [NodeContext]
45
+ def for_input(previous_result:, all_results:, original_prompt:, node_name:, dependencies:, transformed_content: nil)
46
+ new(
47
+ previous_result: previous_result,
48
+ all_results: all_results,
49
+ original_prompt: original_prompt,
50
+ node_name: node_name,
51
+ dependencies: dependencies,
52
+ result: nil,
53
+ transformed_content: transformed_content,
54
+ )
55
+ end
56
+
57
+ # Create a NodeContext for output transformers
58
+ #
59
+ # @param result [Result] Current node's execution result
60
+ # @param all_results [Hash<Symbol, Result>] Results from all completed nodes (including current)
61
+ # @param original_prompt [String] The original user prompt
62
+ # @param node_name [Symbol] Current node name
63
+ # @return [NodeContext]
64
+ def for_output(result:, all_results:, original_prompt:, node_name:)
65
+ new(
66
+ result: result,
67
+ all_results: all_results,
68
+ original_prompt: original_prompt,
69
+ node_name: node_name,
70
+ dependencies: [],
71
+ previous_result: nil,
72
+ transformed_content: nil,
73
+ )
74
+ end
75
+ end
76
+
77
+ def initialize(previous_result:, all_results:, original_prompt:, node_name:, dependencies:, result:, transformed_content:)
78
+ @previous_result = previous_result
79
+ @result = result
80
+ @all_results = all_results
81
+ @original_prompt = original_prompt
82
+ @node_name = node_name
83
+ @dependencies = dependencies
84
+ @transformed_content = transformed_content
85
+ end
86
+
87
+ # Convenience accessor: Get content from previous_result or result
88
+ #
89
+ # For input transformers:
90
+ # - Returns transformed_content if available (from previous output transformer)
91
+ # - Otherwise returns previous_result.content (original content)
92
+ # - Returns nil for multiple dependencies (use all_results instead)
93
+ # For output transformers: returns result.content
94
+ #
95
+ # @return [String, nil]
96
+ def content
97
+ if @result
98
+ # Output transformer context: return current result's content
99
+ @result.content
100
+ elsif @transformed_content
101
+ # Input transformer with transformed content from previous output
102
+ @transformed_content
103
+ elsif @previous_result.respond_to?(:content)
104
+ # Input transformer context with Result object (original content)
105
+ @previous_result.content
106
+ elsif @previous_result.is_a?(Hash)
107
+ # Input transformer with multiple dependencies (hash of results)
108
+ nil # No single "content" - user must pick from all_results hash
109
+ else
110
+ # String or other type (initial prompt, no dependencies)
111
+ @previous_result.to_s
112
+ end
113
+ end
114
+
115
+ # Convenience accessor: Get agent from previous_result or result
116
+ #
117
+ # @return [String, nil]
118
+ def agent
119
+ if @result
120
+ @result.agent
121
+ elsif @previous_result.respond_to?(:agent)
122
+ @previous_result.agent
123
+ end
124
+ end
125
+
126
+ # Convenience accessor: Get logs from previous_result or result
127
+ #
128
+ # @return [Array, nil]
129
+ def logs
130
+ if @result
131
+ @result.logs
132
+ elsif @previous_result.respond_to?(:logs)
133
+ @previous_result.logs
134
+ end
135
+ end
136
+
137
+ # Convenience accessor: Get duration from previous_result or result
138
+ #
139
+ # @return [Float, nil]
140
+ def duration
141
+ if @result
142
+ @result.duration
143
+ elsif @previous_result.respond_to?(:duration)
144
+ @previous_result.duration
145
+ end
146
+ end
147
+
148
+ # Convenience accessor: Get error from previous_result or result
149
+ #
150
+ # @return [Exception, nil]
151
+ def error
152
+ if @result
153
+ @result.error
154
+ elsif @previous_result.respond_to?(:error)
155
+ @previous_result.error
156
+ end
157
+ end
158
+
159
+ # Convenience accessor: Check success status
160
+ #
161
+ # @return [Boolean, nil]
162
+ def success?
163
+ if @result
164
+ @result.success?
165
+ elsif @previous_result.respond_to?(:success?)
166
+ @previous_result.success?
167
+ end
168
+ end
169
+ end
170
+ end
@@ -0,0 +1,384 @@
1
+ # frozen_string_literal: true
2
+
3
+ module SwarmSDK
4
+ # NodeOrchestrator executes a multi-node workflow
5
+ #
6
+ # Each node represents a mini-swarm execution stage. The orchestrator:
7
+ # - Builds execution order from node dependencies (topological sort)
8
+ # - Creates a separate swarm instance for each node
9
+ # - Passes output from one node as input to dependent nodes
10
+ # - Supports input/output transformers for data flow customization
11
+ #
12
+ # @example
13
+ # orchestrator = NodeOrchestrator.new(
14
+ # swarm_name: "Dev Team",
15
+ # agent_definitions: { backend: def1, tester: def2 },
16
+ # nodes: { planning: node1, implementation: node2 },
17
+ # start_node: :planning
18
+ # )
19
+ # result = orchestrator.execute("Build auth system")
20
+ class NodeOrchestrator
21
+ attr_reader :swarm_name, :nodes, :start_node
22
+
23
+ def initialize(swarm_name:, agent_definitions:, nodes:, start_node:)
24
+ @swarm_name = swarm_name
25
+ @agent_definitions = agent_definitions
26
+ @nodes = nodes
27
+ @start_node = start_node
28
+
29
+ validate!
30
+ @execution_order = build_execution_order
31
+ end
32
+
33
+ # Execute the node workflow
34
+ #
35
+ # Executes nodes in topological order, passing output from each node
36
+ # to its dependents. Supports streaming logs if block given.
37
+ #
38
+ # @param prompt [String] Initial prompt for the workflow
39
+ # @yield [Hash] Log entry if block given (for streaming)
40
+ # @return [Result] Final result from last node execution
41
+ def execute(prompt, &block)
42
+ logs = []
43
+ current_input = prompt
44
+ results = {}
45
+ @original_prompt = prompt # Store original prompt for NodeContext
46
+
47
+ # Setup logging if block given
48
+ if block_given?
49
+ # Register callback to collect logs and forward to user's block
50
+ LogCollector.on_log do |entry|
51
+ logs << entry
52
+ block.call(entry)
53
+ end
54
+
55
+ # Set LogStream to use LogCollector as emitter
56
+ LogStream.emitter = LogCollector
57
+ end
58
+
59
+ @execution_order.each do |node_name|
60
+ node = @nodes[node_name]
61
+ node_start_time = Time.now
62
+
63
+ # Emit node_start event
64
+ emit_node_start(node_name, node)
65
+
66
+ # Transform input if node has transformer (Ruby block or bash command)
67
+ skip_execution = false
68
+ skip_content = nil
69
+
70
+ if node.has_input_transformer?
71
+ # Build NodeContext based on dependencies
72
+ #
73
+ # For single dependency: previous_result has original Result metadata,
74
+ # transformed_content has output from previous transformer
75
+ # For multiple dependencies: previous_result is hash of Results
76
+ # For no dependencies: previous_result is initial prompt string
77
+ previous_result = if node.dependencies.size > 1
78
+ # Multiple dependencies: pass hash of original results
79
+ node.dependencies.to_h { |dep| [dep, results[dep]] }
80
+ elsif node.dependencies.size == 1
81
+ # Single dependency: pass the original result
82
+ results[node.dependencies.first]
83
+ else
84
+ # No dependencies: initial prompt
85
+ current_input
86
+ end
87
+
88
+ # Create NodeContext for input transformer
89
+ input_context = NodeContext.for_input(
90
+ previous_result: previous_result,
91
+ all_results: results,
92
+ original_prompt: @original_prompt,
93
+ node_name: node_name,
94
+ dependencies: node.dependencies,
95
+ transformed_content: node.dependencies.size == 1 ? current_input : nil,
96
+ )
97
+
98
+ # Apply input transformer (passes current_input for bash command fallback)
99
+ # Bash transformer exit codes:
100
+ # - Exit 0: Use STDOUT as transformed content
101
+ # - Exit 1: Skip node execution, use current_input unchanged (STDOUT ignored)
102
+ # - Exit 2: Halt workflow with error from STDERR (STDOUT ignored)
103
+ transformed = node.transform_input(input_context, current_input: current_input)
104
+
105
+ # Check if transformer requested skipping execution
106
+ # (from Ruby block returning hash OR bash command exit 1)
107
+ if transformed.is_a?(Hash) && transformed[:skip_execution]
108
+ skip_execution = true
109
+ skip_content = transformed[:content] || transformed["content"]
110
+ else
111
+ current_input = transformed
112
+ end
113
+ end
114
+
115
+ # Execute node (or skip if requested)
116
+ if skip_execution
117
+ # Skip execution: return result immediately with provided content
118
+ result = Result.new(
119
+ content: skip_content,
120
+ agent: "skipped:#{node_name}",
121
+ logs: [],
122
+ duration: 0.0,
123
+ )
124
+ elsif node.agent_less?
125
+ # Agent-less node: run pure computation without LLM
126
+ result = execute_agent_less_node(node, current_input)
127
+ else
128
+ # Normal node: build mini-swarm and execute with LLM
129
+ # NOTE: Don't pass block to mini-swarm - LogCollector already captures all logs
130
+ mini_swarm = build_swarm_for_node(node)
131
+ result = mini_swarm.execute(current_input)
132
+
133
+ # If result has error, log it with backtrace
134
+ if result.error
135
+ RubyLLM.logger.error("NodeOrchestrator: Node '#{node_name}' failed: #{result.error.message}")
136
+ RubyLLM.logger.error(" Backtrace: #{result.error.backtrace&.first(5)&.join("\n ")}")
137
+ end
138
+ end
139
+
140
+ results[node_name] = result
141
+
142
+ # Transform output for next node using NodeContext
143
+ output_context = NodeContext.for_output(
144
+ result: result,
145
+ all_results: results,
146
+ original_prompt: @original_prompt,
147
+ node_name: node_name,
148
+ )
149
+ current_input = node.transform_output(output_context)
150
+
151
+ # For agent-less nodes, update the result with transformed content
152
+ # This ensures all_results contains the actual output, not the input
153
+ if node.agent_less? && current_input != result.content
154
+ results[node_name] = Result.new(
155
+ content: current_input,
156
+ agent: result.agent,
157
+ logs: result.logs,
158
+ duration: result.duration,
159
+ error: result.error,
160
+ )
161
+ end
162
+
163
+ # Emit node_stop event
164
+ node_duration = Time.now - node_start_time
165
+ emit_node_stop(node_name, node, result, node_duration, skip_execution)
166
+ end
167
+
168
+ results.values.last
169
+ ensure
170
+ # Reset logging state for next execution
171
+ LogCollector.reset!
172
+ LogStream.reset!
173
+ end
174
+
175
+ private
176
+
177
+ # Emit node_start event
178
+ #
179
+ # @param node_name [Symbol] Name of the node
180
+ # @param node [Node::Builder] Node configuration
181
+ # @return [void]
182
+ def emit_node_start(node_name, node)
183
+ return unless LogStream.emitter
184
+
185
+ LogStream.emit(
186
+ type: "node_start",
187
+ node: node_name.to_s,
188
+ agent_less: node.agent_less?,
189
+ agents: node.agent_configs.map { |ac| ac[:agent].to_s },
190
+ dependencies: node.dependencies.map(&:to_s),
191
+ timestamp: Time.now.utc.iso8601,
192
+ )
193
+ end
194
+
195
+ # Emit node_stop event
196
+ #
197
+ # @param node_name [Symbol] Name of the node
198
+ # @param node [Node::Builder] Node configuration
199
+ # @param result [Result] Node execution result
200
+ # @param duration [Float] Node execution duration in seconds
201
+ # @param skipped [Boolean] Whether execution was skipped
202
+ # @return [void]
203
+ def emit_node_stop(node_name, node, result, duration, skipped)
204
+ return unless LogStream.emitter
205
+
206
+ LogStream.emit(
207
+ type: "node_stop",
208
+ node: node_name.to_s,
209
+ agent_less: node.agent_less?,
210
+ skipped: skipped,
211
+ agents: node.agent_configs.map { |ac| ac[:agent].to_s },
212
+ duration: duration.round(3),
213
+ timestamp: Time.now.utc.iso8601,
214
+ )
215
+ end
216
+
217
+ # Execute an agent-less (computation-only) node
218
+ #
219
+ # Agent-less nodes run pure Ruby code without LLM execution.
220
+ # Creates a minimal Result object with the transformed content.
221
+ #
222
+ # @param node [Node::Builder] Agent-less node configuration
223
+ # @param input [String] Input content
224
+ # @return [Result] Result with transformed content
225
+ def execute_agent_less_node(node, input)
226
+ # For agent-less nodes, the "content" is just the input passed through
227
+ # The output transformer will do the actual work
228
+ Result.new(
229
+ content: input,
230
+ agent: "computation:#{node.name}",
231
+ logs: [],
232
+ duration: 0.0,
233
+ )
234
+ end
235
+
236
+ # Validate orchestrator configuration
237
+ #
238
+ # @return [void]
239
+ # @raise [ConfigurationError] If configuration is invalid
240
+ def validate!
241
+ # Validate start_node exists
242
+ unless @nodes.key?(@start_node)
243
+ raise ConfigurationError,
244
+ "start_node '#{@start_node}' not found. Available nodes: #{@nodes.keys.join(", ")}"
245
+ end
246
+
247
+ # Validate all nodes
248
+ @nodes.each_value(&:validate!)
249
+
250
+ # Validate node dependencies reference existing nodes
251
+ @nodes.each do |node_name, node|
252
+ node.dependencies.each do |dep|
253
+ unless @nodes.key?(dep)
254
+ raise ConfigurationError,
255
+ "Node '#{node_name}' depends on unknown node '#{dep}'"
256
+ end
257
+ end
258
+ end
259
+
260
+ # Validate all agents referenced in nodes exist (skip agent-less nodes)
261
+ @nodes.each do |node_name, node|
262
+ next if node.agent_less? # Skip validation for agent-less nodes
263
+
264
+ node.agent_configs.each do |config|
265
+ agent_name = config[:agent]
266
+ unless @agent_definitions.key?(agent_name)
267
+ raise ConfigurationError,
268
+ "Node '#{node_name}' references undefined agent '#{agent_name}'"
269
+ end
270
+
271
+ # Validate delegation targets exist
272
+ config[:delegates_to].each do |delegate|
273
+ unless @agent_definitions.key?(delegate)
274
+ raise ConfigurationError,
275
+ "Node '#{node_name}' agent '#{agent_name}' delegates to undefined agent '#{delegate}'"
276
+ end
277
+ end
278
+ end
279
+ end
280
+ end
281
+
282
+ # Build a swarm instance for a specific node
283
+ #
284
+ # Creates a new Swarm with only the agents specified in the node,
285
+ # configured with the node's delegation topology.
286
+ #
287
+ # @param node [Node::Builder] Node configuration
288
+ # @return [Swarm] Configured swarm instance
289
+ def build_swarm_for_node(node)
290
+ swarm = Swarm.new(name: "#{@swarm_name}:#{node.name}")
291
+
292
+ # Add each agent specified in this node
293
+ node.agent_configs.each do |config|
294
+ agent_name = config[:agent]
295
+ delegates_to = config[:delegates_to]
296
+
297
+ # Get global agent definition
298
+ agent_def = @agent_definitions[agent_name]
299
+
300
+ # Clone definition with node-specific delegation
301
+ node_specific_def = clone_with_delegation(agent_def, delegates_to)
302
+
303
+ swarm.add_agent(node_specific_def)
304
+ end
305
+
306
+ # Set lead agent
307
+ swarm.lead = node.lead_agent
308
+
309
+ swarm
310
+ end
311
+
312
+ # Clone an agent definition with different delegates_to
313
+ #
314
+ # @param agent_def [Agent::Definition] Original definition
315
+ # @param delegates_to [Array<Symbol>] New delegation targets
316
+ # @return [Agent::Definition] Cloned definition
317
+ def clone_with_delegation(agent_def, delegates_to)
318
+ config = agent_def.to_h
319
+ config[:delegates_to] = delegates_to
320
+ Agent::Definition.new(agent_def.name, config)
321
+ end
322
+
323
+ # Build execution order using topological sort (Kahn's algorithm)
324
+ #
325
+ # Processes all nodes in dependency order, starting from start_node.
326
+ # Ensures all nodes are reachable from start_node.
327
+ #
328
+ # @return [Array<Symbol>] Ordered list of node names
329
+ # @raise [CircularDependencyError] If circular dependency detected
330
+ def build_execution_order
331
+ # Build in-degree map and adjacency list
332
+ in_degree = {}
333
+ adjacency = Hash.new { |h, k| h[k] = [] }
334
+
335
+ @nodes.each do |node_name, node|
336
+ in_degree[node_name] = node.dependencies.size
337
+ node.dependencies.each do |dep|
338
+ adjacency[dep] << node_name
339
+ end
340
+ end
341
+
342
+ # Start with nodes that have no dependencies
343
+ queue = in_degree.select { |_, degree| degree == 0 }.keys
344
+ order = []
345
+
346
+ while queue.any?
347
+ # Process nodes with all dependencies satisfied
348
+ node_name = queue.shift
349
+ order << node_name
350
+
351
+ # Reduce in-degree for dependent nodes
352
+ adjacency[node_name].each do |dependent|
353
+ in_degree[dependent] -= 1
354
+ queue << dependent if in_degree[dependent] == 0
355
+ end
356
+ end
357
+
358
+ # Check for circular dependencies
359
+ if order.size < @nodes.size
360
+ unprocessed = @nodes.keys - order
361
+ raise CircularDependencyError,
362
+ "Circular dependency detected. Unprocessed nodes: #{unprocessed.join(", ")}"
363
+ end
364
+
365
+ # Verify start_node is in the execution order
366
+ unless order.include?(@start_node)
367
+ raise ConfigurationError,
368
+ "start_node '#{@start_node}' is not reachable in the dependency graph"
369
+ end
370
+
371
+ # Verify start_node is actually first (or rearrange to make it first)
372
+ # This ensures we start from the declared start_node
373
+ start_index = order.index(@start_node)
374
+ if start_index && start_index > 0
375
+ # start_node has dependencies - this violates the assumption
376
+ raise ConfigurationError,
377
+ "start_node '#{@start_node}' has dependencies: #{@nodes[@start_node].dependencies.join(", ")}. " \
378
+ "start_node must have no dependencies."
379
+ end
380
+
381
+ order
382
+ end
383
+ end
384
+ end
@@ -56,8 +56,9 @@ module SwarmSDK
56
56
  # @param description [String] Delegate agent description
57
57
  # @param delegate_chat [Agent::Chat] The delegate's chat instance
58
58
  # @param agent_name [Symbol] Name of the delegating agent
59
+ # @param delegating_chat [Agent::Chat, nil] The chat instance of the agent doing the delegating
59
60
  # @return [Tools::Delegate] Delegation tool
60
- def create_delegation_tool(name:, description:, delegate_chat:, agent_name:)
61
+ def create_delegation_tool(name:, description:, delegate_chat:, agent_name:, delegating_chat: nil)
61
62
  Tools::Delegate.new(
62
63
  delegate_name: name,
63
64
  delegate_description: description,
@@ -65,6 +66,7 @@ module SwarmSDK
65
66
  agent_name: agent_name,
66
67
  swarm: @swarm,
67
68
  hook_registry: @hook_registry,
69
+ delegating_chat: delegating_chat,
68
70
  )
69
71
  end
70
72
 
@@ -120,8 +122,34 @@ module SwarmSDK
120
122
 
121
123
  chat.setup_logging if chat.respond_to?(:setup_logging)
122
124
 
123
- # Emit any model lookup warnings that occurred during initialization
124
- chat.emit_model_lookup_warning(agent_name) if chat.respond_to?(:emit_model_lookup_warning)
125
+ # Emit validation warnings for this agent
126
+ emit_validation_warnings(agent_name, agent_definition)
127
+ end
128
+ end
129
+
130
+ # Emit validation warnings as log events
131
+ #
132
+ # This validates the agent definition and emits any warnings as log events
133
+ # through LogStream (so formatters can handle them).
134
+ #
135
+ # @param agent_name [Symbol] Agent name
136
+ # @param agent_definition [Agent::Definition] Agent definition to validate
137
+ # @return [void]
138
+ def emit_validation_warnings(agent_name, agent_definition)
139
+ warnings = agent_definition.validate
140
+
141
+ warnings.each do |warning|
142
+ case warning[:type]
143
+ when :model_not_found
144
+ LogStream.emit(
145
+ type: "model_lookup_warning",
146
+ agent: agent_name,
147
+ model: warning[:model],
148
+ error_message: warning[:error_message],
149
+ suggestions: warning[:suggestions],
150
+ timestamp: Time.now.utc.iso8601,
151
+ )
152
+ end
125
153
  end
126
154
  end
127
155
 
@@ -214,6 +242,7 @@ module SwarmSDK
214
242
  description: delegate_definition.description,
215
243
  delegate_chat: delegate_agent,
216
244
  agent_name: agent_name,
245
+ delegating_chat: chat,
217
246
  )
218
247
 
219
248
  chat.with_tool(tool)