swarm_sdk 2.1.2 → 2.2.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.
Files changed (49) hide show
  1. checksums.yaml +4 -4
  2. data/lib/swarm_sdk/agent/builder.rb +33 -0
  3. data/lib/swarm_sdk/agent/chat/context_tracker.rb +33 -0
  4. data/lib/swarm_sdk/agent/chat/hook_integration.rb +41 -0
  5. data/lib/swarm_sdk/agent/chat/system_reminder_injector.rb +11 -27
  6. data/lib/swarm_sdk/agent/chat.rb +198 -51
  7. data/lib/swarm_sdk/agent/context.rb +6 -2
  8. data/lib/swarm_sdk/agent/context_manager.rb +6 -0
  9. data/lib/swarm_sdk/agent/definition.rb +15 -22
  10. data/lib/swarm_sdk/agent/llm_instrumentation_middleware.rb +180 -0
  11. data/lib/swarm_sdk/configuration.rb +420 -103
  12. data/lib/swarm_sdk/events_to_messages.rb +181 -0
  13. data/lib/swarm_sdk/log_collector.rb +31 -5
  14. data/lib/swarm_sdk/log_stream.rb +37 -8
  15. data/lib/swarm_sdk/model_aliases.json +4 -1
  16. data/lib/swarm_sdk/node/agent_config.rb +33 -8
  17. data/lib/swarm_sdk/node/builder.rb +39 -18
  18. data/lib/swarm_sdk/node_orchestrator.rb +293 -26
  19. data/lib/swarm_sdk/proc_helpers.rb +53 -0
  20. data/lib/swarm_sdk/prompts/base_system_prompt.md.erb +0 -126
  21. data/lib/swarm_sdk/providers/openai_with_responses.rb +22 -15
  22. data/lib/swarm_sdk/restore_result.rb +65 -0
  23. data/lib/swarm_sdk/snapshot.rb +156 -0
  24. data/lib/swarm_sdk/snapshot_from_events.rb +386 -0
  25. data/lib/swarm_sdk/state_restorer.rb +491 -0
  26. data/lib/swarm_sdk/state_snapshot.rb +369 -0
  27. data/lib/swarm_sdk/swarm/agent_initializer.rb +360 -55
  28. data/lib/swarm_sdk/swarm/all_agents_builder.rb +28 -1
  29. data/lib/swarm_sdk/swarm/builder.rb +208 -12
  30. data/lib/swarm_sdk/swarm/swarm_registry_builder.rb +67 -0
  31. data/lib/swarm_sdk/swarm/tool_configurator.rb +46 -11
  32. data/lib/swarm_sdk/swarm.rb +367 -90
  33. data/lib/swarm_sdk/swarm_loader.rb +145 -0
  34. data/lib/swarm_sdk/swarm_registry.rb +136 -0
  35. data/lib/swarm_sdk/tools/delegate.rb +92 -7
  36. data/lib/swarm_sdk/tools/read.rb +17 -5
  37. data/lib/swarm_sdk/tools/scratchpad/scratchpad_list.rb +23 -2
  38. data/lib/swarm_sdk/tools/scratchpad/scratchpad_read.rb +23 -2
  39. data/lib/swarm_sdk/tools/scratchpad/scratchpad_write.rb +21 -4
  40. data/lib/swarm_sdk/tools/stores/read_tracker.rb +47 -12
  41. data/lib/swarm_sdk/tools/stores/scratchpad_storage.rb +45 -0
  42. data/lib/swarm_sdk/tools/stores/storage.rb +4 -4
  43. data/lib/swarm_sdk/tools/think.rb +4 -1
  44. data/lib/swarm_sdk/tools/todo_write.rb +20 -8
  45. data/lib/swarm_sdk/utils.rb +18 -0
  46. data/lib/swarm_sdk/validation_result.rb +33 -0
  47. data/lib/swarm_sdk/version.rb +1 -1
  48. data/lib/swarm_sdk.rb +362 -21
  49. metadata +17 -5
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a77daa5d8abcd0cae1b1edad441d93421d25ecbf15a0713697d9eabb6c4dc00e
4
- data.tar.gz: 97c037f892d03992b12292a31bc3ab9359ccacead39d37466af84ef5660e4933
3
+ metadata.gz: 024c305673af374d59df3e51afef83508bd787abb57465140d78d9acd5db5943
4
+ data.tar.gz: 8a762c50cf958e39f86a16935bc155c75fab57cfb2c334bd5e96017578ad003e
5
5
  SHA512:
6
- metadata.gz: e7620b869014c9f1b889795310ec1d648cbcc55fc53a3cbb7023c37b403f83c57e5f3645b4f8ffdd38d60fa4877fa24d9ab3f0ccf0de3b2be6a45420516dbf50
7
- data.tar.gz: bc081f3a444bb410a22dc2e5971f258dd43dadaa69d53558e799d036149412bfecf8d95396aa0f6e1f0c39cf6716b986722669265b32cc2b550f7daa0a6e9c2c
6
+ metadata.gz: 50caef0938990e2d4c352cbf1254ed8ceea26f23cd6b3aa1490a35d2efb676de0d3b38a7735f72e6e2d490840258d6fa6c8450d5dda75e5e64ad181ad7eff97b
7
+ data.tar.gz: b5977d7388e96144b3a2c19e604f2e146e77bd85ca8a92f546e4accb5d3c1cbae384020189965fe27a996eada0fb62b0f5331fba5d9bd41171dbcf0be848b4bc
@@ -24,6 +24,13 @@ module SwarmSDK
24
24
  # Expose mcp_servers for tests
25
25
  attr_reader :mcp_servers
26
26
 
27
+ # Get tools list as array for validation
28
+ #
29
+ # @return [Array<Symbol>] List of tools
30
+ def tools_list
31
+ @tools.to_a
32
+ end
33
+
27
34
  def initialize(name)
28
35
  @name = name
29
36
  @description = nil
@@ -52,6 +59,7 @@ module SwarmSDK
52
59
  @permissions_config = {}
53
60
  @default_permissions = {} # Set by SwarmBuilder from all_agents
54
61
  @memory_config = nil
62
+ @shared_across_delegations = nil # nil = not set (will default to false in Definition)
55
63
  end
56
64
 
57
65
  # Set/get agent model
@@ -267,6 +275,30 @@ module SwarmSDK
267
275
  @permissions_config = PermissionsBuilder.build(&block)
268
276
  end
269
277
 
278
+ # Configure delegation isolation mode
279
+ #
280
+ # @param enabled [Boolean] If true, allows sharing instances across delegations (old behavior)
281
+ # If false (default), creates isolated instances per delegation
282
+ # @return [self] Returns self for method chaining
283
+ #
284
+ # @example
285
+ # shared_across_delegations true # Allow sharing (old behavior)
286
+ def shared_across_delegations(enabled)
287
+ @shared_across_delegations = enabled
288
+ self
289
+ end
290
+
291
+ # Set permissions directly from hash (for YAML translation)
292
+ #
293
+ # This is intentionally separate from permissions() to keep the DSL clean.
294
+ # Called by Configuration when translating YAML permissions.
295
+ #
296
+ # @param hash [Hash] Permissions configuration hash
297
+ # @return [void]
298
+ def permissions_hash=(hash)
299
+ @permissions_config = hash || {}
300
+ end
301
+
270
302
  # Check if model has been explicitly set (not default)
271
303
  #
272
304
  # Used by Swarm::Builder to determine if all_agents model should apply.
@@ -374,6 +406,7 @@ module SwarmSDK
374
406
  agent_config[:permissions] = @permissions_config if @permissions_config.any?
375
407
  agent_config[:default_permissions] = @default_permissions if @default_permissions.any?
376
408
  agent_config[:memory] = @memory_config if @memory_config
409
+ agent_config[:shared_across_delegations] = @shared_across_delegations unless @shared_across_delegations.nil?
377
410
 
378
411
  # Convert DSL hooks to HookDefinition format
379
412
  agent_config[:hooks] = convert_hooks_to_definitions if @hooks.any?
@@ -13,6 +13,25 @@ module SwarmSDK
13
13
  # - Check context warnings
14
14
  #
15
15
  # This is a stateful helper that's instantiated per Agent::Chat instance.
16
+ #
17
+ # ## Thread Safety and Fiber-Local Storage
18
+ #
19
+ # IMPORTANT: LogStream.emit calls in this class DO NOT explicitly pass
20
+ # swarm_id, parent_swarm_id, or execution_id. These values are automatically
21
+ # injected from Fiber-local storage (Fiber[:swarm_id], etc.) by LogStream.emit.
22
+ #
23
+ # Why: In threaded environments (Puma, Sidekiq), swarm/agent instances may be
24
+ # reused across multiple requests/jobs. If we explicitly pass @agent_context.swarm_id,
25
+ # callbacks would use STALE values from the first request, causing events to be
26
+ # lost or misattributed.
27
+ #
28
+ # By relying on Fiber-local storage, each request/job gets the correct context
29
+ # even when reusing the same swarm instance. Fiber storage is set at the start
30
+ # of Swarm#execute and inherited by child fibers (tool calls, delegations).
31
+ #
32
+ # This design works correctly in both:
33
+ # - Single-threaded environments (rails runner, console)
34
+ # - Multi-threaded environments (Puma, Sidekiq)
16
35
  class ContextTracker
17
36
  include LoggingHelpers
18
37
 
@@ -74,11 +93,20 @@ module SwarmSDK
74
93
  # Mark threshold as hit and emit warning
75
94
  @agent_context.hit_warning_threshold?(threshold)
76
95
 
96
+ # Emit context_threshold_hit event for snapshot reconstruction
97
+ LogStream.emit(
98
+ type: "context_threshold_hit",
99
+ agent: @agent_context.name,
100
+ threshold: threshold,
101
+ current_usage_percentage: current_percentage.round(2),
102
+ )
103
+
77
104
  # Trigger automatic compression at 60% threshold
78
105
  if threshold == Context::COMPRESSION_THRESHOLD
79
106
  trigger_automatic_compression
80
107
  end
81
108
 
109
+ # Emit legacy context_limit_warning for backwards compatibility
82
110
  LogStream.emit(
83
111
  type: "context_limit_warning",
84
112
  agent: @agent_context.name,
@@ -107,6 +135,9 @@ module SwarmSDK
107
135
  cumulative_input_tokens: @chat.cumulative_input_tokens,
108
136
  cumulative_output_tokens: @chat.cumulative_output_tokens,
109
137
  cumulative_total_tokens: @chat.cumulative_total_tokens,
138
+ cumulative_cached_tokens: @chat.cumulative_cached_tokens,
139
+ cumulative_cache_creation_tokens: @chat.cumulative_cache_creation_tokens,
140
+ effective_input_tokens: @chat.effective_input_tokens,
110
141
  context_limit: @chat.context_limit,
111
142
  tokens_used_percentage: "#{@chat.context_usage_percentage}%",
112
143
  tokens_remaining: @chat.tokens_remaining,
@@ -118,6 +149,8 @@ module SwarmSDK
118
149
  {
119
150
  input_tokens: message.input_tokens,
120
151
  output_tokens: message.output_tokens,
152
+ cached_tokens: message.cached_tokens,
153
+ cache_creation_tokens: message.cache_creation_tokens,
121
154
  total_tokens: (message.input_tokens || 0) + (message.output_tokens || 0),
122
155
  input_cost: cost_info[:input_cost],
123
156
  output_cost: cost_info[:output_cost],
@@ -186,9 +186,13 @@ module SwarmSDK
186
186
  def trigger_post_tool_use(result, tool_call:)
187
187
  return result unless @hook_executor
188
188
 
189
+ # Extract tracking digest for Read/MemoryRead tools
190
+ metadata_with_digest = extract_tool_tracking_digest(tool_call, result)
191
+
189
192
  context = build_hook_context(
190
193
  event: :post_tool_use,
191
194
  tool_result: wrap_tool_result(tool_call.id, tool_call.name, result),
195
+ metadata: metadata_with_digest,
192
196
  )
193
197
 
194
198
  agent_hooks = @hook_agent_hooks[:post_tool_use] || []
@@ -335,6 +339,43 @@ module SwarmSDK
335
339
  )
336
340
  end
337
341
 
342
+ # Extract tracking digest for Read/MemoryRead tools
343
+ #
344
+ # Queries the appropriate tracker after tool execution to get the digest
345
+ # that was calculated and stored during the read operation.
346
+ #
347
+ # @param tool_call [RubyLLM::ToolCall] Tool call with arguments
348
+ # @param result [Object] Tool execution result (to check for errors)
349
+ # @return [Hash] Metadata hash with digest if applicable
350
+ def extract_tool_tracking_digest(tool_call, result)
351
+ # Only add digest for successful Read/MemoryRead tool calls
352
+ return {} if result.is_a?(StandardError)
353
+ return {} unless ["Read", "MemoryRead"].include?(tool_call.name)
354
+
355
+ # Extract path from arguments
356
+ path = case tool_call.name
357
+ when "Read"
358
+ tool_call.arguments[:file_path] || tool_call.arguments["file_path"]
359
+ when "MemoryRead"
360
+ tool_call.arguments[:file_path] || tool_call.arguments["file_path"]
361
+ end
362
+
363
+ return {} unless path
364
+
365
+ # Query tracker for digest
366
+ digest = case tool_call.name
367
+ when "Read"
368
+ Tools::Stores::ReadTracker.get_read_files(@agent_context.name)[File.expand_path(path)]
369
+ when "MemoryRead"
370
+ # Only query if SwarmMemory is loaded (optional dependency)
371
+ if defined?(SwarmMemory::Core::StorageReadTracker)
372
+ SwarmMemory::Core::StorageReadTracker.get_read_entries(@agent_context.name)[path]
373
+ end
374
+ end
375
+
376
+ digest ? { read_digest: digest, read_path: path } : {}
377
+ end
378
+
338
379
  # Wrap a tool result in our Hooks::ToolResult value object
339
380
  #
340
381
  # @param tool_call_id [String] Tool call ID
@@ -12,23 +12,6 @@ module SwarmSDK
12
12
  #
13
13
  # This class is stateless - it operates on the chat's message history.
14
14
  class SystemReminderInjector
15
- # System reminder to inject BEFORE the first user message
16
- BEFORE_FIRST_MESSAGE_REMINDER = <<~REMINDER.strip
17
- <system-reminder>
18
- As you answer the user's questions, you can use the following context:
19
-
20
- # important-instruction-reminders
21
-
22
- Do what has been asked; nothing more, nothing less.
23
- NEVER create files unless they're absolutely necessary for achieving your goal.
24
- ALWAYS prefer editing an existing file to creating a new one.
25
- NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.
26
-
27
- IMPORTANT: this context may or may not be relevant to your tasks. You should not respond to this context unless it is highly relevant to your task.
28
-
29
- </system-reminder>
30
- REMINDER
31
-
32
15
  # System reminder to inject AFTER the first user message
33
16
  AFTER_FIRST_MESSAGE_REMINDER = <<~REMINDER.strip
34
17
  <system-reminder>Your todo list is currently empty. DO NOT mention this to the user. If this task requires multiple steps: (1) FIRST analyze the scope by searching/reading files, (2) SECOND create a COMPLETE todo list with ALL tasks before starting work, (3) THIRD execute tasks one by one. Only skip the todo list for simple single-step tasks. Do not mention this message to the user.</system-reminder>
@@ -51,16 +34,14 @@ module SwarmSDK
51
34
  chat.messages.none? { |msg| msg.role == :user }
52
35
  end
53
36
 
54
- # Inject first message reminders (before + after user message)
37
+ # Inject first message reminders
55
38
  #
56
- # This manually constructs the first message sequence with system reminders
57
- # sandwiching the actual user prompt.
39
+ # This manually constructs the first message sequence with system reminders.
58
40
  #
59
41
  # Sequence:
60
- # 1. BEFORE_FIRST_MESSAGE_REMINDER (general reminders)
42
+ # 1. User's actual prompt
61
43
  # 2. Toolset reminder (list of available tools)
62
- # 3. User's actual prompt
63
- # 4. AFTER_FIRST_MESSAGE_REMINDER (todo list reminder)
44
+ # 3. AFTER_FIRST_MESSAGE_REMINDER (todo list reminder - only if TodoWrite available)
64
45
  #
65
46
  # @param chat [Agent::Chat] The chat instance
66
47
  # @param prompt [String] The user's actual prompt
@@ -68,12 +49,15 @@ module SwarmSDK
68
49
  def inject_first_message_reminders(chat, prompt)
69
50
  # Build user message with embedded reminders
70
51
  # Reminders are embedded in the content, not separate messages
71
- full_content = [
52
+ parts = [
72
53
  prompt,
73
- BEFORE_FIRST_MESSAGE_REMINDER,
74
54
  build_toolset_reminder(chat),
75
- AFTER_FIRST_MESSAGE_REMINDER,
76
- ].join("\n\n")
55
+ ]
56
+
57
+ # Only include todo list reminder if agent has TodoWrite tool
58
+ parts << AFTER_FIRST_MESSAGE_REMINDER if chat.tools.key?("TodoWrite")
59
+
60
+ full_content = parts.join("\n\n")
77
61
 
78
62
  # Extract reminders and add clean prompt to persistent history
79
63
  reminders = chat.context_manager.extract_system_reminders(full_content)
@@ -150,6 +150,7 @@ module SwarmSDK
150
150
  raise StateError, "Agent context not set. Call setup_context first." unless @agent_context
151
151
 
152
152
  @context_tracker.setup_logging
153
+ inject_llm_instrumentation
153
154
  end
154
155
 
155
156
  # Emit model lookup warning if one occurred during initialization
@@ -164,6 +165,8 @@ module SwarmSDK
164
165
  LogStream.emit(
165
166
  type: "model_lookup_warning",
166
167
  agent: agent_name,
168
+ swarm_id: @agent_context&.swarm_id,
169
+ parent_swarm_id: @agent_context&.parent_swarm_id,
167
170
  model: @model_lookup_error[:model],
168
171
  error_message: @model_lookup_error[:error_message],
169
172
  suggestions: @model_lookup_error[:suggestions].map { |s| { id: s.id, name: s.name, context_window: s.context_window } },
@@ -221,6 +224,17 @@ module SwarmSDK
221
224
  !@active_skill_path.nil?
222
225
  end
223
226
 
227
+ # Clear conversation history
228
+ #
229
+ # Removes all messages from the conversation history and clears tool executions.
230
+ # Used by composable swarms when keep_context: false is specified.
231
+ #
232
+ # @return [void]
233
+ def clear_conversation
234
+ @messages.clear if @messages.respond_to?(:clear)
235
+ @context_manager&.clear_ephemeral
236
+ end
237
+
224
238
  # Override ask to inject system reminders and periodic TodoWrite reminders
225
239
  #
226
240
  # Note: This is called BEFORE HookIntegration#ask (due to module include order),
@@ -230,63 +244,72 @@ module SwarmSDK
230
244
  # @param options [Hash] Additional options to pass to complete
231
245
  # @return [RubyLLM::Message] LLM response
232
246
  def ask(prompt, **options)
233
- # Check if this is the first user message
234
- is_first = SystemReminderInjector.first_message?(self)
235
-
236
- if is_first
237
- # Collect plugin reminders first
238
- plugin_reminders = collect_plugin_reminders(prompt, is_first_message: true)
239
-
240
- # Build full prompt with embedded plugin reminders
241
- full_prompt = prompt
242
- plugin_reminders.each do |reminder|
243
- full_prompt = "#{full_prompt}\n\n#{reminder}"
244
- end
245
-
246
- # Inject first message reminders (includes system reminders + toolset + after)
247
- # SystemReminderInjector will embed all reminders in the prompt via add_message
248
- SystemReminderInjector.inject_first_message_reminders(self, full_prompt)
247
+ # Serialize ask() calls to prevent message corruption from concurrent fibers
248
+ # Uses Async::Semaphore (not Mutex) because SwarmSDK runs in fiber context
249
+ # This protects against parallel delegation scenarios where multiple delegation
250
+ # instances call the same underlying primary agent (e.g., tester@frontend and
251
+ # tester@backend both calling database in parallel).
252
+ @ask_semaphore ||= Async::Semaphore.new(1)
253
+
254
+ @ask_semaphore.acquire do
255
+ # Check if this is the first user message
256
+ is_first = SystemReminderInjector.first_message?(self)
257
+
258
+ if is_first
259
+ # Collect plugin reminders first
260
+ plugin_reminders = collect_plugin_reminders(prompt, is_first_message: true)
261
+
262
+ # Build full prompt with embedded plugin reminders
263
+ full_prompt = prompt
264
+ plugin_reminders.each do |reminder|
265
+ full_prompt = "#{full_prompt}\n\n#{reminder}"
266
+ end
249
267
 
250
- # Trigger user_prompt hook manually since we're bypassing the normal ask flow
251
- if @hook_executor
252
- hook_result = trigger_user_prompt(prompt)
268
+ # Inject first message reminders (includes system reminders + toolset + after)
269
+ # SystemReminderInjector will embed all reminders in the prompt via add_message
270
+ SystemReminderInjector.inject_first_message_reminders(self, full_prompt)
271
+
272
+ # Trigger user_prompt hook manually since we're bypassing the normal ask flow
273
+ if @hook_executor
274
+ hook_result = trigger_user_prompt(prompt)
275
+
276
+ # Check if hook halted execution
277
+ if hook_result[:halted]
278
+ # Return a halted message instead of calling LLM
279
+ return RubyLLM::Message.new(
280
+ role: :assistant,
281
+ content: hook_result[:halt_message],
282
+ model_id: model.id,
283
+ )
284
+ end
253
285
 
254
- # Check if hook halted execution
255
- if hook_result[:halted]
256
- # Return a halted message instead of calling LLM
257
- return RubyLLM::Message.new(
258
- role: :assistant,
259
- content: hook_result[:halt_message],
260
- model_id: model.id,
261
- )
286
+ # NOTE: We ignore modified_prompt for first message since reminders already injected
262
287
  end
263
288
 
264
- # NOTE: We ignore modified_prompt for first message since reminders already injected
265
- end
289
+ # Call complete to get LLM response
290
+ complete(**options)
291
+ else
292
+ # Build prompt with embedded reminders (if needed)
293
+ full_prompt = prompt
294
+
295
+ # Add periodic TodoWrite reminder if needed (only if agent has TodoWrite tool)
296
+ if tools.key?("TodoWrite") && SystemReminderInjector.should_inject_todowrite_reminder?(self, @last_todowrite_message_index)
297
+ full_prompt = "#{full_prompt}\n\n#{SystemReminderInjector::TODOWRITE_PERIODIC_REMINDER}"
298
+ # Update tracking
299
+ @last_todowrite_message_index = SystemReminderInjector.find_last_todowrite_index(self)
300
+ end
266
301
 
267
- # Call complete to get LLM response
268
- complete(**options)
269
- else
270
- # Build prompt with embedded reminders (if needed)
271
- full_prompt = prompt
272
-
273
- # Add periodic TodoWrite reminder if needed
274
- if SystemReminderInjector.should_inject_todowrite_reminder?(self, @last_todowrite_message_index)
275
- full_prompt = "#{full_prompt}\n\n#{SystemReminderInjector::TODOWRITE_PERIODIC_REMINDER}"
276
- # Update tracking
277
- @last_todowrite_message_index = SystemReminderInjector.find_last_todowrite_index(self)
278
- end
302
+ # Collect plugin reminders and embed them
303
+ plugin_reminders = collect_plugin_reminders(full_prompt, is_first_message: false)
304
+ plugin_reminders.each do |reminder|
305
+ full_prompt = "#{full_prompt}\n\n#{reminder}"
306
+ end
279
307
 
280
- # Collect plugin reminders and embed them
281
- plugin_reminders = collect_plugin_reminders(full_prompt, is_first_message: false)
282
- plugin_reminders.each do |reminder|
283
- full_prompt = "#{full_prompt}\n\n#{reminder}"
308
+ # Normal ask behavior for subsequent messages
309
+ # This calls super which goes to HookIntegration's ask override
310
+ # HookIntegration will call add_message, and we'll extract reminders there
311
+ super(full_prompt, **options)
284
312
  end
285
-
286
- # Normal ask behavior for subsequent messages
287
- # This calls super which goes to HookIntegration's ask override
288
- # HookIntegration will call add_message, and we'll extract reminders there
289
- super(full_prompt, **options)
290
313
  end
291
314
  end
292
315
 
@@ -674,7 +697,15 @@ module SwarmSDK
674
697
  # This is needed for setting agent_name and other provider-specific settings.
675
698
  #
676
699
  # @return [RubyLLM::Provider::Base] Provider instance
677
- attr_reader :provider, :global_semaphore, :local_semaphore, :real_model_info, :context_tracker, :context_manager
700
+ attr_reader :provider, :global_semaphore, :local_semaphore, :real_model_info, :context_tracker, :context_manager, :agent_context, :last_todowrite_message_index, :active_skill_path
701
+
702
+ # Setters for snapshot/restore
703
+ attr_writer :last_todowrite_message_index, :active_skill_path
704
+
705
+ # Expose messages array (inherited from RubyLLM::Chat but not publicly accessible)
706
+ #
707
+ # @return [Array<RubyLLM::Message>] Conversation messages
708
+ attr_reader :messages
678
709
 
679
710
  # Get context window limit for the current model
680
711
  #
@@ -718,6 +749,37 @@ module SwarmSDK
718
749
  messages.select { |msg| msg.role == :assistant }.sum { |msg| msg.output_tokens || 0 }
719
750
  end
720
751
 
752
+ # Calculate cumulative cached tokens across all assistant messages
753
+ #
754
+ # Cached tokens are portions of prompts served from the provider's cache.
755
+ # OpenAI reports this automatically for prompts >1024 tokens.
756
+ # Anthropic/Bedrock expose cache control via Content::Raw blocks.
757
+ #
758
+ # @return [Integer] Total cached tokens used in conversation
759
+ def cumulative_cached_tokens
760
+ messages.select { |msg| msg.role == :assistant }.sum { |msg| msg.cached_tokens || 0 }
761
+ end
762
+
763
+ # Calculate cumulative cache creation tokens
764
+ #
765
+ # Cache creation tokens are written to the cache (Anthropic/Bedrock only).
766
+ # These are charged at the normal input rate when first created.
767
+ #
768
+ # @return [Integer] Total tokens written to cache
769
+ def cumulative_cache_creation_tokens
770
+ messages.select { |msg| msg.role == :assistant }.sum { |msg| msg.cache_creation_tokens || 0 }
771
+ end
772
+
773
+ # Calculate effective input tokens (excluding cache hits)
774
+ #
775
+ # This represents the actual tokens charged for input, excluding cached portions.
776
+ # Useful for accurate cost tracking when using prompt caching.
777
+ #
778
+ # @return [Integer] Actual input tokens charged (input minus cached)
779
+ def effective_input_tokens
780
+ cumulative_input_tokens - cumulative_cached_tokens
781
+ end
782
+
721
783
  # Calculate total tokens used (input + output)
722
784
  #
723
785
  # @return [Integer] Total tokens used in conversation
@@ -777,6 +839,85 @@ module SwarmSDK
777
839
 
778
840
  private
779
841
 
842
+ # Inject LLM instrumentation middleware for API request/response logging
843
+ #
844
+ # This middleware captures HTTP requests/responses to LLM providers and
845
+ # emits structured events via LogStream. Only injected when logging is enabled.
846
+ #
847
+ # @return [void]
848
+ def inject_llm_instrumentation
849
+ # Safety checks
850
+ return unless @provider
851
+
852
+ faraday_conn = @provider.connection&.connection
853
+ return unless faraday_conn
854
+
855
+ # Check if middleware is already present to prevent duplicates
856
+ return if @llm_instrumentation_injected
857
+
858
+ # Get provider name for logging
859
+ provider_name = @provider.class.name.split("::").last.downcase
860
+
861
+ # Inject middleware at beginning of stack (position 0)
862
+ # This ensures we capture raw requests before any transformations
863
+ # Use fully qualified name to ensure Zeitwerk loads it
864
+ faraday_conn.builder.insert(
865
+ 0,
866
+ SwarmSDK::Agent::LLMInstrumentationMiddleware,
867
+ on_request: method(:handle_llm_api_request),
868
+ on_response: method(:handle_llm_api_response),
869
+ provider_name: provider_name,
870
+ )
871
+
872
+ # Mark as injected to prevent duplicates
873
+ @llm_instrumentation_injected = true
874
+
875
+ RubyLLM.logger.debug("SwarmSDK: Injected LLM instrumentation middleware for agent #{@agent_name}")
876
+ rescue StandardError => e
877
+ # Don't fail initialization if instrumentation fails
878
+ RubyLLM.logger.error("SwarmSDK: Failed to inject LLM instrumentation: #{e.message}")
879
+ end
880
+
881
+ # Handle LLM API request event
882
+ #
883
+ # Emits llm_api_request event via LogStream with request details.
884
+ #
885
+ # @param data [Hash] Request data from middleware
886
+ # @return [void]
887
+ def handle_llm_api_request(data)
888
+ return unless LogStream.emitter
889
+
890
+ LogStream.emit(
891
+ type: "llm_api_request",
892
+ agent: @agent_name,
893
+ swarm_id: @agent_context&.swarm_id,
894
+ parent_swarm_id: @agent_context&.parent_swarm_id,
895
+ **data,
896
+ )
897
+ rescue StandardError => e
898
+ RubyLLM.logger.error("SwarmSDK: Error emitting llm_api_request event: #{e.message}")
899
+ end
900
+
901
+ # Handle LLM API response event
902
+ #
903
+ # Emits llm_api_response event via LogStream with response details.
904
+ #
905
+ # @param data [Hash] Response data from middleware
906
+ # @return [void]
907
+ def handle_llm_api_response(data)
908
+ return unless LogStream.emitter
909
+
910
+ LogStream.emit(
911
+ type: "llm_api_response",
912
+ agent: @agent_name,
913
+ swarm_id: @agent_context&.swarm_id,
914
+ parent_swarm_id: @agent_context&.parent_swarm_id,
915
+ **data,
916
+ )
917
+ rescue StandardError => e
918
+ RubyLLM.logger.error("SwarmSDK: Error emitting llm_api_response event: #{e.message}")
919
+ end
920
+
780
921
  # Call LLM with retry logic for transient failures
781
922
  #
782
923
  # Retries up to 10 times with fixed 10-second delays for:
@@ -802,10 +943,13 @@ module SwarmSDK
802
943
  LogStream.emit(
803
944
  type: "llm_retry_exhausted",
804
945
  agent: @agent_name,
946
+ swarm_id: @agent_context&.swarm_id,
947
+ parent_swarm_id: @agent_context&.parent_swarm_id,
805
948
  model: @model&.id,
806
949
  attempts: attempts,
807
950
  error_class: e.class.name,
808
951
  error_message: e.message,
952
+ error_backtrace: e.backtrace,
809
953
  )
810
954
  raise
811
955
  end
@@ -814,11 +958,14 @@ module SwarmSDK
814
958
  LogStream.emit(
815
959
  type: "llm_retry_attempt",
816
960
  agent: @agent_name,
961
+ swarm_id: @agent_context&.swarm_id,
962
+ parent_swarm_id: @agent_context&.parent_swarm_id,
817
963
  model: @model&.id,
818
964
  attempt: attempts,
819
965
  max_retries: max_retries,
820
966
  error_class: e.class.name,
821
967
  error_message: e.message,
968
+ error_backtrace: e.backtrace,
822
969
  retry_delay: delay,
823
970
  )
824
971
 
@@ -33,15 +33,19 @@ module SwarmSDK
33
33
  # Threshold at which automatic compression is triggered
34
34
  COMPRESSION_THRESHOLD = 60
35
35
 
36
- attr_reader :name, :delegation_tools, :metadata, :warning_thresholds_hit
36
+ attr_reader :name, :delegation_tools, :metadata, :warning_thresholds_hit, :swarm_id, :parent_swarm_id
37
37
 
38
38
  # Initialize a new agent context
39
39
  #
40
40
  # @param name [Symbol, String] Agent name
41
+ # @param swarm_id [String] Swarm ID for event tracking
42
+ # @param parent_swarm_id [String, nil] Parent swarm ID (nil for root swarms)
41
43
  # @param delegation_tools [Array<String>] Names of tools that are delegations
42
44
  # @param metadata [Hash] Optional metadata about the agent
43
- def initialize(name:, delegation_tools: [], metadata: {})
45
+ def initialize(name:, swarm_id:, parent_swarm_id: nil, delegation_tools: [], metadata: {})
44
46
  @name = name.to_sym
47
+ @swarm_id = swarm_id
48
+ @parent_swarm_id = parent_swarm_id
45
49
  @delegation_tools = Set.new(delegation_tools.map(&:to_s))
46
50
  @metadata = metadata
47
51
  @delegation_call_ids = Set.new
@@ -18,10 +18,16 @@ module SwarmSDK
18
18
  class ContextManager
19
19
  SYSTEM_REMINDER_REGEX = %r{<system-reminder>.*?</system-reminder>}m
20
20
 
21
+ # Expose compression state for snapshot/restore
22
+ # NOTE: @compression_applied initializes to nil (not false), only set to true when compression runs
23
+ attr_reader :compression_applied
24
+ attr_writer :compression_applied
25
+
21
26
  def initialize
22
27
  # Ephemeral content to append to messages for this turn only
23
28
  # Format: { message_index => [array of reminder strings] }
24
29
  @ephemeral_content = {}
30
+ # NOTE: @compression_applied is NOT initialized here - starts as nil
25
31
  end
26
32
 
27
33
  # Track ephemeral content to append to a specific message