robot_lab 0.5.1 → 0.6.1

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7830657dbfe2508c38884f5a117e3b1eb6db6223c0c5336ba8fdbdd3c8718732
4
- data.tar.gz: 3df367453aef2881e24e7e718c7778416e932e4f265deca27961bbe1952db483
3
+ metadata.gz: 0b6e840221fd580897fea9a5a13e27a9a245977054ed528474eba0dcf205008a
4
+ data.tar.gz: 5b430758c71fe3e21136c7805e6770454364a704bae24e203d33cd02173c7ee9
5
5
  SHA512:
6
- metadata.gz: 5f12198c217fa3465274de33a0dfac869eecc51e679f5f65d6d0ee3f0ad18ce9cb14e346b12f35fff6f0fc948ec8dc19e2dfc4eae66afd94a6e4f469a9d2458b
7
- data.tar.gz: 7e91d8448bc45512216c1e53ba4dee007c0f40f225a6a34b1b8a51238962b99fd6b26757a6dc842d332ed34ccc73f7a381e404d622ad1e847bfeff5da29c1df0
6
+ metadata.gz: 67de4c052378c46c4b11dd45206021a50a495bca1af49302d19e5aca92836bb1e08c00f220011c0781cf1cbdd9af9473881ca22c5dc2858962d04626df7ad4d7
7
+ data.tar.gz: de1cd93d4101be13c7881acb1829728f9855c9752a670506ee5d804d5c395b23099d56c7f2512aaf39c5f17b81f4336a9966a23ce98f5805b0a6e98489127c58
data/CHANGELOG.md CHANGED
@@ -8,6 +8,110 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.6.1] - 2026-11-18
12
+
13
+ ### Fixed
14
+
15
+ - `AgentSkill` rejects a SKILL.md whose front-matter `name` is not a String, so
16
+ `AgentSkillCatalog` skips it with a warning instead of raising `NoMethodError`
17
+ and leaving the catalog empty (#102).
18
+ - `AgentSkillCatalog#find` also resolves a skill by its folder name when the
19
+ front-matter `name` differs, so `skills: [:check_style]` finds
20
+ `check_style/SKILL.md` (#104).
21
+ - `Memory#get(key, wait: N)` returns a stored value of `:timeout` instead of
22
+ mistaking it for a wait timeout and raising `AwaitTimeout` (#100).
23
+ - `Memory#set` applies the same reserved-key handling as `Memory#[]=`, so
24
+ `set(:cache, x)` raises and `set(:data, h)` resets the `data` proxy (#99).
25
+ - A `Memory` subscriber that raises no longer stops later subscribers in the
26
+ same batch from being notified; the error is logged and delivery continues (#98).
27
+ - `Robot#with_bus` on a robot in a `Network` keeps the network's shared
28
+ `BusPoller` and group instead of starting a private poller (#103).
29
+ - Async `Robot#delegate` rejects its `DelegationFuture` when the delegated run
30
+ raises an exception outside `StandardError` (e.g. `NotImplementedError`), so
31
+ `future.value` re-raises it at once instead of timing out or blocking forever.
32
+ - `Memory#get(:a, :b, wait: N)` now treats `N` as one deadline for the whole
33
+ call instead of waiting up to `N` seconds per missing key (#92).
34
+ - Examples 09, 10 and 11 load `amazing_print` before `common.rb` so they no longer crash at startup.
35
+ - `HistoryCompressor` keeps an assistant message that has both text and tool calls, so its tool result is never orphaned.
36
+ - `Network#task` raises `ArgumentError` for a task name already in the network,
37
+ matching `add_robot`, instead of silently dropping the earlier task.
38
+ - `Network` with `parallel_mode: :ractor` now shuts the Ractor scheduler down
39
+ when `run_pipeline` raises, instead of leaking its worker pool on every failed
40
+ run.
41
+ - `BusPoller` keeps draining a robot's queued deliveries after one delivery
42
+ raises `BusError`, instead of stranding them until a later message arrived and
43
+ then running them out of order.
44
+ - `DotState` (`ctx.local` in hooks) supports `[]` and `[]=`; `ctx.local[:k] = v`
45
+ used to store the key name under `:[]` and drop the value.
46
+ - `HookContext#to_h` now includes inherited readers (such as `event`, and
47
+ `robot`/`request` on `LlmGenerationHookContext`) and no longer raises
48
+ `ArgumentError` on the base class.
49
+ - Removed the duplicate `Robot#hook_registries` from `robot.rb`; the `Hooking`
50
+ concern now owns the only definition, so changes there take effect.
51
+ - A budget reservation is now released when a run is cut off by an exception
52
+ outside `StandardError` (`Timeout.timeout` around `robot.run`, `Interrupt`),
53
+ so later runs are no longer refused as over budget.
54
+ - Examples: `examples/common.rb` sets RobotLab's `ruby_llm.model` and `provider`
55
+ to the examples' default, so a robot built without `model:` (the bare robot in
56
+ `09_chaining.rb`) no longer falls back to `claude-sonnet-4`.
57
+ - Docs and doc comments now describe `HistoryCompressor` and `Convergence` as
58
+ term-frequency cosine similarity (not TF-IDF) and quote the real
59
+ `ToolLoopError` message.
60
+ - `RobotResult.from_hash` now restores `duration` and `delegated_by`.
61
+ - `Hook.namespace` returns nil for an anonymous `Hook` subclass instead of raising
62
+ `NoMethodError`, so `HookRegistry#on` raises its intended "has no namespace"
63
+ `ArgumentError` and anonymous per-run hooks run.
64
+ - `DelegationFuture#value` keeps waiting after a spurious wakeup instead of
65
+ raising `DelegationTimeout` before the delegated task resolves.
66
+ - `ToolManifest#count` is now `Enumerable#count`, so it honours a block and an
67
+ argument; with neither it still returns the size.
68
+ - A `SKILL.md` whose front matter YAML can't be safely loaded (such as an
69
+ unquoted date) raises `ConfigurationError`, so `AgentSkillCatalog` skips it and
70
+ still loads the other skills.
71
+ - A budget reservation is now released when a run fails with a `StandardError`,
72
+ so later runs are no longer refused as over budget.
73
+ - A `doom_loop_threshold` below 1 or not an Integer raises `ArgumentError` instead
74
+ of `ZeroDivisionError` or "negative array size" mid-run.
75
+ - `Memory#wait_for_key` closes its waiter pipe on every exit path, so an early
76
+ return or a raise no longer leaks two file descriptors.
77
+ - `Robot#call` reports an error raised while extracting the run context instead
78
+ of masking it with a `TypeError`.
79
+ - `token_budget` is checked against the budget ledger, so a call that overruns
80
+ the budget after `reset_token_totals` is now flagged.
81
+ - `Narrator.enable!` registers the narrator once; calling it again only changes
82
+ the output instead of narrating every event twice.
83
+ - `tsort` is now a runtime dependency, so robot_lab loads under Bundler on Ruby
84
+ 4.1, where `tsort` is no longer a default gem.
85
+ - `Memory` with the `:auto` backend pings Redis and falls back to a Hash when
86
+ the server is unreachable, instead of raising.
87
+ - `Budget::Ledger#reserve!` can reserve exactly what `remaining` reports; Float
88
+ rounding no longer raises `BudgetExceeded` with budget left.
89
+ - Examples: `25_history_search.rb` requires `common` before `json`, so it no
90
+ longer raises `Gem::LoadError` when the bundle locks an older json.
91
+ - `Memory#subscribe_pattern` escapes every regex metacharacter in the glob, so
92
+ only `*` and `?` are wildcards: `"price(usd):*"` now matches
93
+ `price(usd):today`, and `"a+b"` matches `a+b` instead of `aab` (#91).
94
+
95
+ ### Changed
96
+
97
+ - Gemspec `documentation_uri` now points at the docs site
98
+ (https://madbomber.github.io/robot_lab) instead of the README.
99
+ - CI: a GitHub Actions `Test` workflow runs `bundle exec rake test` on Ruby 4.0
100
+ for pushes to `main`/`develop` and for pull requests.
101
+
102
+ ## [0.6.0] - 2026-11-02
103
+
104
+ ### Fixed
105
+
106
+ - **Tool classes in `local_tools:`.** A `RubyLLM::Tool` subclass passed as a class (`local_tools: [SharedTools::Tools::DnsTool]`) reached the chat as `dns`, but robot_lab's own checks used the Ruby class name `"SharedTools::Tools::DnsTool"`. As a result, a `tools: %w[dns]` allowlist dropped the tool without an error. The robot now instantiates tool classes on construction, so every check uses the tool's name. The new `ToolConfig.instantiate` does this here and for template `tools:` front matter, and `ToolConfig.tool_name` (now public) reads `tool_name` from a tool class.
107
+
108
+ ### Added
109
+
110
+ - **MCP server classes by constant name.** `RobotLab::MCP.build`, `name_of`, `Registry#add` and a robot's per-turn server selection accept a String naming a `RubyLLM::MCP` subclass. Template front matter can now list `mcp: ["SharedTools::MCP::GitHub"]` in the same way `tools:` lists tool classes. The new `RobotLab::MCP.resolve` does the lookup and raises `MCPError` for an undefined constant or a class that is not a `RubyLLM::MCP`.
111
+ - **Class-level descriptions in `mcp_discovery`.** `ServerDiscovery.description_for` now falls back to a server's class when the instance has no `description`. Plain `RubyLLM::MCP` subclasses that declare a description at class level, such as the shared_tools 0.7.1 MCP clients, are scored instead of looking blank.
112
+
113
+ ## [0.5.1] - 2026-11-01
114
+
11
115
  ### Fixed
12
116
 
13
117
  - **OAuth `grant:` from YAML.** An MCP server config such as `oauth: { grant: client_credentials }` raised `ArgumentError: Unknown OAuth grant`, because ruby_llm accepts the grant only as a Symbol. `RobotLab::MCP.define` now converts a String grant to a Symbol.
@@ -11,17 +11,18 @@ module RobotLab
11
11
  attr_reader :name, :description, :path, :capabilities
12
12
 
13
13
  # @param skill_md_path [String, Pathname] path to the SKILL.md file
14
- # @raise [ConfigurationError] if name or description is missing
14
+ # @raise [ConfigurationError] if name or description is missing, or the front matter is invalid YAML
15
15
  def initialize(skill_md_path)
16
16
  @path = Pathname.new(skill_md_path).dirname
17
17
  content = File.read(skill_md_path)
18
- front_matter, @_body = parse_skill_md(content)
18
+ front_matter, @_body = parse_skill_md(content, skill_md_path)
19
19
 
20
20
  @name = front_matter["name"]
21
21
  @description = front_matter["description"]
22
22
  @capabilities = Capabilities.from_front_matter(front_matter)
23
23
 
24
24
  raise ConfigurationError, "SKILL.md at #{skill_md_path} missing 'name'" if @name.to_s.strip.empty?
25
+ raise ConfigurationError, "SKILL.md at #{skill_md_path} 'name' must be a String" unless @name.is_a?(String)
25
26
  raise ConfigurationError, "SKILL.md at #{skill_md_path} missing 'description'" if @description.to_s.strip.empty?
26
27
  end
27
28
 
@@ -49,16 +50,23 @@ module RobotLab
49
50
  private
50
51
 
51
52
  # Split SKILL.md content into front matter Hash and body String.
52
- def parse_skill_md(content)
53
- if content.start_with?("---\n")
54
- parts = content.split(/^---\s*$/, 3)
55
- if parts.length >= 3
56
- fm = YAML.safe_load(parts[1])
57
- front_matter = fm.is_a?(Hash) ? fm : {}
58
- return [front_matter, parts[2]]
59
- end
60
- end
61
- [{}, content]
53
+ def parse_skill_md(content, skill_md_path)
54
+ yaml_text, body = split_front_matter(content)
55
+ return [{}, content] unless body
56
+
57
+ front_matter = YAML.safe_load(yaml_text)
58
+ [front_matter.is_a?(Hash) ? front_matter : {}, body]
59
+ rescue Psych::Exception => e
60
+ raise ConfigurationError, "SKILL.md at #{skill_md_path} has invalid front matter (#{e.message})"
61
+ end
62
+
63
+ # Pure: [front matter text, body] when +content+ opens with a "---"
64
+ # block, or nil when it has none.
65
+ def split_front_matter(content)
66
+ return unless content.start_with?("---\n")
67
+
68
+ _, yaml_text, body = content.split(/^---\s*$/, 3)
69
+ [yaml_text, body] if body
62
70
  end
63
71
  end
64
72
  end
@@ -31,7 +31,7 @@ module RobotLab
31
31
 
32
32
  # Return the AgentSkill for the given ID, or nil if not found.
33
33
  #
34
- # @param id [Symbol, String] skill folder name
34
+ # @param id [Symbol, String] skill folder name or front-matter name
35
35
  # @return [AgentSkill, nil]
36
36
  def find(id)
37
37
  load!
@@ -43,7 +43,7 @@ module RobotLab
43
43
  # @return [Array<AgentSkill>]
44
44
  def all
45
45
  load!
46
- @skills.values
46
+ @skills.values.uniq
47
47
  end
48
48
 
49
49
  private
@@ -66,6 +66,7 @@ module RobotLab
66
66
  begin
67
67
  skill = AgentSkill.new(skill_file)
68
68
  @skills[skill.name.to_sym] = skill
69
+ @skills[dir.basename.to_s.to_sym] ||= skill
69
70
  rescue ConfigurationError, Psych::SyntaxError => e
70
71
  RobotLab.config.logger.warn("AgentSkillCatalog: #{e.message}, skipping #{dir.basename}")
71
72
  end
@@ -18,9 +18,10 @@ module RobotLab
18
18
  #
19
19
  # @example
20
20
  # ledger = RobotLab::Budget::Ledger.new(limits: { tokens: 10_000, cost: 0.50 })
21
- # ledger.reserve!(:tokens, ledger.remaining(:tokens))
21
+ # held = ledger.remaining(:tokens)
22
+ # ledger.reserve!(:tokens, held)
22
23
  # # ... do the billable work ...
23
- # ledger.reconcile!(:tokens, ledger.remaining(:tokens), actual_tokens_used)
24
+ # ledger.reconcile!(:tokens, held, actual_tokens_used)
24
25
  class Ledger
25
26
  # @!attribute [r] limits
26
27
  # @return [Hash{Symbol=>Numeric}] per-dimension ceilings
@@ -51,9 +52,9 @@ module RobotLab
51
52
  limit = @limits[key]
52
53
  next unless limit
53
54
 
54
- committed = @consumed[key] + @reserved[key]
55
- if committed + amount > limit
56
- raise BudgetExceeded, "budget exceeded for #{key}: #{committed + amount} > #{limit}"
55
+ if amount > headroom(key, limit)
56
+ raise BudgetExceeded,
57
+ "budget exceeded for #{key}: #{@consumed[key] + @reserved[key] + amount} > #{limit}"
57
58
  end
58
59
 
59
60
  @reserved[key] += amount
@@ -90,9 +91,21 @@ module RobotLab
90
91
  limit = @limits[key]
91
92
  next Float::INFINITY unless limit
92
93
 
93
- [limit - @consumed[key] - @reserved[key], 0].max
94
+ [headroom(key, limit), 0].max
94
95
  end
95
96
  end
97
+
98
+ private
99
+
100
+ # Unfloored budget left for +key+ (negative after an overrun). Shared by
101
+ # #reserve! and #remaining so that, while headroom is non-negative, reserving
102
+ # exactly what #remaining reports can't trip on Float rounding.
103
+ # Caller must hold @mutex.
104
+ #
105
+ # @param key [Symbol] the budget dimension
106
+ # @param limit [Numeric] the configured limit for +key+
107
+ # @return [Numeric]
108
+ def headroom(key, limit) = limit - @consumed[key] - @reserved[key]
96
109
  end
97
110
  end
98
111
  end
@@ -114,12 +114,11 @@ module RobotLab
114
114
  private
115
115
 
116
116
  # Process one delivery, then drain any queued deliveries for the robot.
117
+ # A BusError on any delivery is logged and the drain carries on, so one
118
+ # failed message never strands the ones queued behind it.
117
119
  def process_and_drain(robot, delivery)
118
- robot.send(:process_delivery, delivery)
120
+ process_one(robot, delivery)
119
121
  drain_queued_deliveries(robot)
120
- rescue BusError => e
121
- release_robot(robot)
122
- RobotLab.config.logger.warn("BusPoller: delivery error: #{e.message}")
123
122
  rescue => e
124
123
  release_robot(robot)
125
124
  RobotLab.config.logger.warn("BusPoller: unexpected error: #{e.message}")
@@ -143,14 +142,17 @@ module RobotLab
143
142
 
144
143
  break unless next_delivery
145
144
 
146
- begin
147
- robot.send(:process_delivery, next_delivery)
148
- rescue BusError => e
149
- RobotLab.config.logger.warn("BusPoller: delivery error: #{e.message}")
150
- end
145
+ process_one(robot, next_delivery)
151
146
  end
152
147
  end
153
148
 
149
+ # Deliver one message, logging (not raising) a BusError.
150
+ def process_one(robot, delivery)
151
+ robot.send(:process_delivery, delivery)
152
+ rescue BusError => e
153
+ RobotLab.config.logger.warn("BusPoller: delivery error: #{e.message}")
154
+ end
155
+
154
156
  def release_robot(robot)
155
157
  @mutex.synchronize { @robot_busy[robot.name] = false }
156
158
  end
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module RobotLab
4
- # TF-IDF cosine similarity utilities for detecting semantic convergence
4
+ # Term-frequency cosine similarity utilities for detecting semantic convergence
5
5
  # between two texts.
6
6
  #
7
7
  # Common use cases:
@@ -23,7 +23,7 @@ module RobotLab
23
23
  # Default cosine similarity threshold above which texts are convergent.
24
24
  DEFAULT_THRESHOLD = 0.85
25
25
 
26
- # Minimum text length (characters) for meaningful TF-IDF scoring.
26
+ # Minimum text length (characters) for meaningful term-frequency scoring.
27
27
  # Texts shorter than this always return 0.0 similarity.
28
28
  MIN_TEXT_LENGTH = 30
29
29
 
@@ -56,9 +56,7 @@ module RobotLab
56
56
  # @raise [StandardError] re-raises any error thrown by the delegated task
57
57
  def value(timeout: nil)
58
58
  @mutex.synchronize do
59
- unless @resolved
60
- @cv.wait(@mutex, timeout)
61
- end
59
+ timeout ? wait_until_deadline(timeout) : (@cv.wait(@mutex) until @resolved)
62
60
 
63
61
  unless @resolved
64
62
  raise DelegationTimeout,
@@ -89,5 +87,19 @@ module RobotLab
89
87
  @cv.broadcast
90
88
  end
91
89
  end
90
+
91
+ private
92
+
93
+ # Waits on the condition variable until resolved or +timeout+ seconds
94
+ # have passed, looping past spurious wakeups. The caller holds @mutex.
95
+ def wait_until_deadline(timeout)
96
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
97
+ until @resolved
98
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
99
+ break if remaining <= 0
100
+
101
+ @cv.wait(@mutex, remaining)
102
+ end
103
+ end
92
104
  end
93
105
  end
@@ -24,7 +24,13 @@ module RobotLab
24
24
 
25
25
  attr_reader :sequence
26
26
 
27
+ # @param threshold [Integer] repetitions that count as a loop (must be >= 1)
28
+ # @raise [ArgumentError] if threshold is not a positive Integer
27
29
  def initialize(threshold: DEFAULT_THRESHOLD)
30
+ unless threshold.is_a?(Integer) && threshold >= 1
31
+ raise ArgumentError, "doom_loop_threshold must be an Integer >= 1, got #{threshold.inspect}"
32
+ end
33
+
28
34
  @threshold = threshold
29
35
  @sequence = []
30
36
  end
@@ -59,7 +59,7 @@ module RobotLab
59
59
  # Raised when a robot's tool call loop exceeds the configured limit.
60
60
  #
61
61
  # @example
62
- # raise ToolLoopError, "Circuit breaker: 26 tool calls exceeded max_tool_rounds (25)"
62
+ # raise ToolLoopError, "Circuit breaker triggered: 26 tool calls exceeded max_tool_rounds (25)"
63
63
  class ToolLoopError < InferenceError; end
64
64
 
65
65
  # Raised when a required optional gem dependency is not installed.
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module RobotLab
4
- # Compresses a robot's conversation history using TF-IDF relevance scoring.
4
+ # Compresses a robot's conversation history using term-frequency cosine similarity.
5
5
  #
6
6
  # Old conversation turns are tiered against the most recent context:
7
7
  # - High relevance (score >= keep_threshold) → kept verbatim
@@ -167,6 +167,10 @@ module RobotLab
167
167
  return true if role == :system
168
168
  return true if %i[tool tool_result].include?(role)
169
169
 
170
+ # Any assistant message that dispatches tool calls, even with text:
171
+ # dropping it would orphan the tool results that answer it.
172
+ return true if msg.respond_to?(:tool_calls) && msg.tool_calls && !msg.tool_calls.empty?
173
+
170
174
  # Assistant tool-call dispatcher: content is nil or blank
171
175
  if role == :assistant
172
176
  text = extract_text(msg)
@@ -39,12 +39,13 @@ module RobotLab
39
39
  attr_writer :namespace
40
40
 
41
41
  # Returns the hook's namespace symbol, derived from the class name by
42
- # default. Returns nil for the base Hook class itself.
42
+ # default. Returns nil for the base Hook class itself and for anonymous
43
+ # subclasses that have not set one.
43
44
  #
44
45
  # @return [Symbol, nil]
45
46
  def namespace
46
47
  return @namespace if @namespace
47
- return nil if self == Hook
48
+ return nil if self == Hook || !name
48
49
 
49
50
  name.split('::').last
50
51
  .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
@@ -33,14 +33,28 @@ module RobotLab
33
33
  public_snapshot.merge(metadata: metadata.to_h)
34
34
  end
35
35
 
36
+ # Readers excluded from #to_h: +local+ raises outside a hook namespace.
37
+ SNAPSHOT_EXCLUDED = %i[to_h local].freeze
38
+
39
+ # Names of the zero-argument public readers #to_h snapshots: those
40
+ # declared on this class and each ancestor up to and including
41
+ # HookContext, minus setters and SNAPSHOT_EXCLUDED.
42
+ #
43
+ # @api private
44
+ # @return [Array<Symbol>] sorted reader names
45
+ def self.snapshot_readers
46
+ ancestors.take(ancestors.index(HookContext) + 1)
47
+ .flat_map { |mod| mod.public_instance_methods(false) }
48
+ .uniq
49
+ .reject { |name| name.end_with?("=") || SNAPSHOT_EXCLUDED.include?(name) }
50
+ .select { |name| instance_method(name).arity.zero? }
51
+ .sort
52
+ end
53
+
36
54
  private
37
55
 
38
56
  def public_snapshot
39
- public_methods(false)
40
- .grep_v(/=\z/)
41
- .reject { |name| %i[to_h local].include?(name) }
42
- .sort
43
- .to_h { |name| [name, public_send(name)] }
57
+ self.class.snapshot_readers.to_h { |name| [name, public_send(name)] }
44
58
  end
45
59
  end
46
60
 
@@ -184,6 +198,16 @@ module RobotLab
184
198
  self
185
199
  end
186
200
 
201
+ # Hash-style read; shares storage with dot access (+state[:k]+ == +state.k+).
202
+ def [](key)
203
+ @data[key.to_sym]
204
+ end
205
+
206
+ # Hash-style write; shares storage with dot access.
207
+ def []=(key, value)
208
+ @data[key.to_sym] = value
209
+ end
210
+
187
211
  def method_missing(name, *args)
188
212
  key = name.to_s.delete_suffix('=').to_sym
189
213
 
@@ -24,9 +24,10 @@ module RobotLab
24
24
 
25
25
  # Register a server (or return the one already registered for +spec+).
26
26
  #
27
- # @param spec [Hash, RubyLLM::MCP, Class<RubyLLM::MCP>]
27
+ # @param spec [Hash, RubyLLM::MCP, Class<RubyLLM::MCP>, String]
28
28
  # @return [RubyLLM::MCP]
29
29
  def add(spec)
30
+ spec = MCP.resolve(spec)
30
31
  key = MCP.name_of(spec).to_sym
31
32
  existing = @servers[key]
32
33
  return existing if existing && same_spec?(key, spec, existing)
@@ -101,12 +101,18 @@ module RobotLab
101
101
  name.to_s.strip
102
102
  end
103
103
 
104
+ # An instance without its own +description+ falls back to its class's,
105
+ # so plain +RubyLLM::MCP+ subclasses that declare one at class level
106
+ # (SharedTools::MCP::GitHub, ...) are scored too.
107
+ #
104
108
  # @param server [Hash, RubyLLM::MCP, Class<RubyLLM::MCP>]
105
109
  # @return [String] description or empty string
106
110
  def self.description_for(server)
107
111
  desc = case server
108
112
  when Hash then server[:description] || server['description']
109
- else (server.description if server.respond_to?(:description))
113
+ else
114
+ owner = [server, server.class].find { it.respond_to?(:description) }
115
+ owner&.description
110
116
  end
111
117
  desc.to_s.strip
112
118
  end
data/lib/robot_lab/mcp.rb CHANGED
@@ -54,12 +54,14 @@ module RobotLab
54
54
  module_function
55
55
 
56
56
  # Build a server from a config Hash, or pass through an instance or class.
57
+ # A String names a +RubyLLM::MCP+ subclass constant, the form template
58
+ # front matter uses (+mcp: ["SharedTools::MCP::GitHub"]+).
57
59
  #
58
- # @param spec [Hash, RubyLLM::MCP, Class<RubyLLM::MCP>]
60
+ # @param spec [Hash, RubyLLM::MCP, Class<RubyLLM::MCP>, String]
59
61
  # @return [RubyLLM::MCP]
60
62
  # @raise [MCPError] for an unusable spec
61
63
  def build(spec)
62
- case spec
64
+ case (spec = resolve(spec))
63
65
  when RubyLLM::MCP then spec
64
66
  when Class
65
67
  raise MCPError, "#{spec} is not a RubyLLM::MCP subclass" unless spec <= RubyLLM::MCP
@@ -68,10 +70,29 @@ module RobotLab
68
70
  when Hash then define(spec).new
69
71
  else
70
72
  raise MCPError, "Cannot build an MCP server from #{spec.class}; " \
71
- 'pass a Hash, a RubyLLM::MCP, or a RubyLLM::MCP subclass'
73
+ 'pass a Hash, a RubyLLM::MCP, a RubyLLM::MCP subclass, or its constant name'
72
74
  end
73
75
  end
74
76
 
77
+ # Turn a String spec into the +RubyLLM::MCP+ subclass it names; any other
78
+ # spec is returned unchanged.
79
+ #
80
+ # @param spec [Hash, RubyLLM::MCP, Class<RubyLLM::MCP>, String]
81
+ # @return [Hash, RubyLLM::MCP, Class<RubyLLM::MCP>]
82
+ # @raise [MCPError] when the String does not name a RubyLLM::MCP subclass
83
+ def resolve(spec)
84
+ return spec unless spec.is_a?(String)
85
+
86
+ klass = begin
87
+ Object.const_get(spec)
88
+ rescue NameError
89
+ raise MCPError, "MCP server class '#{spec}' is not defined; require the file that defines it"
90
+ end
91
+ raise MCPError, "#{spec} is not a RubyLLM::MCP subclass" unless klass.is_a?(Class) && klass <= RubyLLM::MCP
92
+
93
+ klass
94
+ end
95
+
75
96
  # Turn a config Hash into an anonymous {Server} subclass with ruby_llm's
76
97
  # class-level DSL applied. Public so hosts can build classes once and
77
98
  # instantiate them per request (ruby_llm's recommended pattern).
@@ -88,11 +109,11 @@ module RobotLab
88
109
 
89
110
  # The name a spec will be registered under.
90
111
  #
91
- # @param spec [Hash, RubyLLM::MCP, Class<RubyLLM::MCP>]
112
+ # @param spec [Hash, RubyLLM::MCP, Class<RubyLLM::MCP>, String]
92
113
  # @return [String]
93
114
  # @raise [MCPError] when the spec has no name
94
115
  def name_of(spec)
95
- name = case spec
116
+ name = case (spec = resolve(spec))
96
117
  when Hash then spec[:name] || spec['name']
97
118
  when Class then spec.default_name
98
119
  when RubyLLM::MCP then spec.name
@@ -266,6 +266,8 @@ module RobotLab
266
266
  #
267
267
  def set(key, value)
268
268
  key = key.to_sym
269
+ return self[key] = value if RESERVED_KEYS.include?(key)
270
+
269
271
  old_value = nil
270
272
 
271
273
  # Store the value
@@ -727,7 +729,9 @@ module RobotLab
727
729
  def create_redis_backend
728
730
  return nil unless redis_available?
729
731
 
730
- RedisBackend.new
732
+ # Redis.new connects lazily, so ping to surface an unreachable server
733
+ # here and fall back to the Hash backend instead of failing later.
734
+ RedisBackend.new.tap(&:ping)
731
735
  rescue StandardError
732
736
  nil
733
737
  end
@@ -803,9 +807,10 @@ module RobotLab
803
807
 
804
808
  return results if missing.empty? || !wait
805
809
 
806
- # Wait for missing keys
807
- timeout = wait == true ? nil : wait
810
+ # Wait for missing keys; a numeric wait is one deadline for the whole call
811
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + wait unless wait == true
808
812
  missing.each do |key|
813
+ timeout = deadline && [deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC), 0].max
809
814
  results[key] = wait_for_key(key, timeout: timeout)
810
815
  end
811
816
 
@@ -814,25 +819,30 @@ module RobotLab
814
819
 
815
820
  # :reek:TooManyStatements -- double-check locking plus timeout cleanup must stay together for correctness.
816
821
  def wait_for_key(key, timeout:)
817
- waiter = Waiter.new
822
+ waiter = nil
818
823
 
819
824
  @waiter_mutex.synchronize do
820
825
  # Double-check - value might have arrived while setting up
821
826
  @mutex.synchronize { return @backend[key] if @backend.key?(key) }
822
827
 
828
+ waiter = Waiter.new
823
829
  @waiters[key] << waiter
824
830
  end
825
831
 
826
832
  result = waiter.wait(timeout: timeout)
827
- waiter.close
828
833
 
829
834
  if result == :timeout
835
+ # A stored value of :timeout looks like Waiter's timeout result
836
+ return @mutex.synchronize { @backend[key] } if waiter.signaled?
837
+
830
838
  # Clean up the waiter
831
839
  @waiter_mutex.synchronize { @waiters[key].delete(waiter) }
832
840
  raise AwaitTimeout, "Timeout waiting for :#{key} after #{timeout} seconds"
833
841
  end
834
842
 
835
843
  result
844
+ ensure
845
+ waiter&.close
836
846
  end
837
847
 
838
848
  # :reek:UncommunicativeVariableName -- single-char block vars are accepted style here (RuboCop allows them).
@@ -897,7 +907,11 @@ module RobotLab
897
907
  break if batch.empty?
898
908
 
899
909
  batch.each do |item|
900
- item[:callbacks].each { |cb| cb.call(item[:change]) }
910
+ item[:callbacks].each do |cb|
911
+ cb.call(item[:change])
912
+ rescue StandardError => e
913
+ RobotLab.config.logger.error("Memory subscriber error for :#{item[:change].key}: #{e.class}: #{e.message}")
914
+ end
901
915
  end
902
916
  end
903
917
  ensure
@@ -920,11 +934,10 @@ module RobotLab
920
934
  end
921
935
 
922
936
  def pattern_to_regex(pattern)
923
- # Convert glob pattern to regex
924
- regex_str = pattern
925
- .gsub(".", "\\.")
926
- .gsub("*", ".*")
927
- .gsub("?", ".")
937
+ # Convert glob pattern to regex; only * and ? are wildcards
938
+ regex_str = Regexp.escape(pattern)
939
+ .gsub("\\*", ".*")
940
+ .gsub("\\?", ".")
928
941
 
929
942
  Regexp.new("\\A#{regex_str}\\z")
930
943
  end
@@ -969,6 +982,13 @@ module RobotLab
969
982
  keys.each { |k| delete(k) }
970
983
  end
971
984
 
985
+ # Verifies the server is reachable.
986
+ #
987
+ # @raise [Redis::BaseConnectionError] if it is not
988
+ def ping
989
+ @redis.ping
990
+ end
991
+
972
992
  private
973
993
 
974
994
  def create_redis_connection(config = RobotLab.config)
@@ -32,12 +32,14 @@ module RobotLab
32
32
  end
33
33
 
34
34
  # Register the narrator globally and set its output.
35
+ # Calling it again only changes the output; the narrator is
36
+ # registered once.
35
37
  #
36
38
  # @param output [IO]
37
39
  # @return [Class] self
38
40
  def enable!(output: $stderr)
39
41
  self.output = output
40
- RobotLab.on(self)
42
+ RobotLab.on(self) unless RobotLab.hooks.registrations.any? { |reg| reg.handler_class == self }
41
43
  self
42
44
  end
43
45
 
@@ -113,6 +113,7 @@ module RobotLab
113
113
  # @param memory [Memory, Hash, nil] task-specific memory
114
114
  # @param depends_on [Symbol, Array<Symbol>] dependencies (:none, :optional, or task names)
115
115
  # @return [self]
116
+ # @raise [ArgumentError] if a task with this name already exists in the network
116
117
  #
117
118
  # @example Entry point task
118
119
  # task :classifier, classifier_robot, depends_on: :none
@@ -129,6 +130,8 @@ module RobotLab
129
130
  # :reek:LongParameterList -- one keyword per documented per-task option.
130
131
  def task(name, robot, context: {}, mcp: :none, tools: :none, memory: nil, config: nil, depends_on: :none,
131
132
  poller_group: :default)
133
+ raise ArgumentError, "Task '#{name}' already exists in network '#{@name}'" if @tasks.key?(name.to_s)
134
+
132
135
  task_wrapper = Task.new(
133
136
  name: name,
134
137
  robot: robot,
@@ -154,13 +157,14 @@ module RobotLab
154
157
  #
155
158
  # @param name [Symbol, nil] optional name for the parallel group
156
159
  # @param depends_on [Symbol, Array] dependencies for this group
157
- # @yield Block containing task definitions
160
+ # @yield Block containing step definitions. The block is evaluated by
161
+ # SimpleFlow's ParallelBlock, which supports +step+ (not +task+).
158
162
  # @return [self]
159
163
  #
160
164
  # @example Named parallel group
161
165
  # parallel :fetch_data, depends_on: :validate do
162
- # task :fetch_orders, orders_robot
163
- # task :fetch_products, products_robot
166
+ # step :fetch_orders, orders_robot
167
+ # step :fetch_products, products_robot
164
168
  # end
165
169
  # task :process, processor, depends_on: :fetch_data
166
170
  #
@@ -420,9 +424,12 @@ module RobotLab
420
424
  end
421
425
 
422
426
  scheduler = RactorNetworkScheduler.new(memory: @memory)
423
- results = scheduler.run_pipeline(specs_with_deps, message: message)
424
- scheduler.shutdown
425
- results
427
+ begin
428
+ scheduler.run_pipeline(specs_with_deps, message: message)
429
+ ensure
430
+ # run_pipeline raises when a robot fails; always release the worker Ractors.
431
+ scheduler.shutdown
432
+ end
426
433
  end
427
434
 
428
435
  # :reek:FeatureEnvy -- snapshotting a robot's identity fields into a Ractor-shareable spec is this method's job.
@@ -27,12 +27,16 @@ module RobotLab
27
27
  RobotLab::Budget::Ledger.new(limits: limits)
28
28
  end
29
29
 
30
+ # Reads the ledger rather than the robot's token totals, which
31
+ # reset_token_totals can zero without touching the budget.
30
32
  def enforce_token_budget!
31
33
  budget = @config.token_budget
32
- return unless budget && @total_input_tokens + @total_output_tokens > budget
34
+ return unless budget && @budget_ledger
33
35
 
34
- raise InferenceError,
35
- "Token budget exceeded: #{@total_input_tokens + @total_output_tokens} tokens used, budget is #{budget}"
36
+ consumed = @budget_ledger.consumed[:tokens]
37
+ return unless consumed > budget
38
+
39
+ raise InferenceError, "Token budget exceeded: #{consumed} tokens used, budget is #{budget}"
36
40
  end
37
41
 
38
42
  def enforce_cost_budget!
@@ -55,11 +59,28 @@ module RobotLab
55
59
  def reserve_budget!
56
60
  return {} unless @budget_ledger
57
61
 
58
- @budget_ledger.limits.each_key.with_object({}) do |dimension, reservation|
59
- amount = @budget_ledger.remaining(dimension)
60
- @budget_ledger.reserve!(dimension, amount)
61
- reservation[dimension] = amount
62
- end
62
+ reservation = {}
63
+ @budget_ledger.limits.each_key { |dimension| reserve_remaining!(dimension, reservation) }
64
+ reservation
65
+ rescue BudgetExceeded
66
+ release_budget!(reservation)
67
+ raise
68
+ end
69
+
70
+ # Reserves what remains of +dimension+ and records it in +reservation+,
71
+ # which reserve_budget! releases if a later dimension is exhausted.
72
+ def reserve_remaining!(dimension, reservation)
73
+ amount = @budget_ledger.remaining(dimension)
74
+ @budget_ledger.reserve!(dimension, amount)
75
+ reservation[dimension] = amount
76
+ end
77
+
78
+ # Drops a reservation from reserve_budget! without recording any
79
+ # consumption, for a call that failed before reconcile_budget!.
80
+ #
81
+ # @param reservation [Hash{Symbol=>Numeric}] the value returned by reserve_budget!
82
+ def release_budget!(reservation)
83
+ reservation.each_pair { |dimension, amount| @budget_ledger.release!(dimension, amount) }
63
84
  end
64
85
 
65
86
  # Replaces a reservation from reserve_budget! with the actual usage
@@ -212,12 +212,15 @@ module RobotLab
212
212
  end
213
213
 
214
214
  # Unsubscribe from the bus channel and stop the private poller if any.
215
+ # A poller assigned by a Network is kept, along with its group.
215
216
  def teardown_bus_channel
216
217
  channel_name = @name.to_sym
217
218
  @bus.unsubscribe(channel_name, @bus_subscriber_id) if @bus_subscriber_id
218
219
  @bus_subscriber_id = nil
219
220
 
220
- @private_bus_poller&.stop
221
+ return unless @private_bus_poller
222
+
223
+ @private_bus_poller.stop
221
224
  @private_bus_poller = nil
222
225
  @bus_poller = nil
223
226
  @bus_poller_group = :default
@@ -30,8 +30,16 @@ module RobotLab
30
30
  network: network, network_config: network_config)
31
31
  rerender_template(run_context) if @template && run_context.any?
32
32
  reservation = reserve_budget!
33
- response = invoke_ask(context: context, kwargs: kwargs, hooks: hooks, block: block)
34
- result = build_result(response, run_memory)
33
+ completed = false
34
+ begin
35
+ response = invoke_ask(context: context, kwargs: kwargs, hooks: hooks, block: block)
36
+ result = build_result(response, run_memory)
37
+ completed = true
38
+ ensure
39
+ # ensure, not rescue StandardError: Timeout and Interrupt
40
+ # must release the reservation too.
41
+ release_budget!(reservation) unless completed
42
+ end
35
43
  reconcile_budget!(reservation, response: response, result: result)
36
44
  enforce_token_budget!
37
45
  enforce_cost_budget!
@@ -136,7 +136,7 @@ module RobotLab
136
136
  # @param message [String, RubyLLM::MCP::Prompt, nil] this run's request
137
137
  # @return [Array<RubyLLM::MCP>]
138
138
  def servers_for(resolved, message: nil)
139
- specs = Array(resolved)
139
+ specs = Array(resolved).map { MCP.resolve(it) }
140
140
  specs = MCP::ServerDiscovery.select(discovery_query(message), from: specs) if @mcp_discovery && message
141
141
  specs.map { |spec| @mcp_registry.add(spec) }
142
142
  end
@@ -323,8 +323,7 @@ module RobotLab
323
323
  case name
324
324
  when String
325
325
  begin
326
- const = Object.const_get(name)
327
- const.is_a?(Class) && const < RubyLLM::Tool ? const.new : const
326
+ ToolConfig.instantiate(Object.const_get(name))
328
327
  rescue NameError
329
328
  RobotLab.config.logger.warn("Robot '#{@name}': tool '#{name}' not found, skipping")
330
329
  nil
@@ -293,12 +293,12 @@ module RobotLab
293
293
  # :reek:TooManyStatements -- SimpleFlow step: timing, run, and error-shielding belong together.
294
294
  # :reek:DuplicateMethodCall -- each clock_gettime samples a different instant (start/stop/rescue); a local would be wrong.
295
295
  def call(result)
296
+ start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
296
297
  run_context = extract_run_context(result)
297
298
 
298
299
  # Extract the message from run context
299
300
  message = run_context.delete(:message)
300
301
 
301
- start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
302
302
  robot_result = run(message, **run_context)
303
303
  robot_result.duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time
304
304
 
@@ -372,7 +372,7 @@ module RobotLab
372
372
  self
373
373
  end
374
374
 
375
- # Compress conversation history using TF-IDF relevance scoring.
375
+ # Compress conversation history using term-frequency cosine similarity.
376
376
  #
377
377
  # Old turns are tiered against the most recent context:
378
378
  # - High relevance (score >= keep_threshold) → kept verbatim
@@ -445,7 +445,8 @@ module RobotLab
445
445
  result.duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at
446
446
  result.delegated_by = delegator_name
447
447
  future.resolve!(result)
448
- rescue => e
448
+ rescue Exception => e # rubocop:disable Lint/RescueException
449
+ # Settle the future on any error, or value blocks until timeout.
449
450
  future.reject!(e)
450
451
  end
451
452
 
@@ -565,7 +566,7 @@ module RobotLab
565
566
  @system_prompt = system_prompt
566
567
  @build_context = context
567
568
  @description = description
568
- @local_tools = Array(local_tools)
569
+ @local_tools = Array(local_tools).map { ToolConfig.instantiate(it) }
569
570
  @skills = skills ? Array(skills).map(&:to_sym) : nil
570
571
  @expanded_skills = nil
571
572
  @pending_agent_skills = []
@@ -847,10 +848,6 @@ module RobotLab
847
848
  end
848
849
  end
849
850
 
850
- def hook_registries(network = nil)
851
- [RobotLab.hooks, network&.hooks, @hooks]
852
- end
853
-
854
851
  # Extract run context from SimpleFlow::Result
855
852
  # :reek:TooManyStatements -- one delete/re-add per robot-specific run param; a loop would hide which keys are special.
856
853
  def extract_run_context(result)
@@ -1003,11 +1000,7 @@ module RobotLab
1003
1000
  else
1004
1001
  case compact
1005
1002
  when :context_window
1006
- begin
1007
- compress_history
1008
- rescue DependencyError => e
1009
- RobotLab.config.logger.warn("[#{@name}] auto_compact: #{e.message}; skipping compaction")
1010
- end
1003
+ compact_context_window
1011
1004
  when Proc
1012
1005
  compact.call(self)
1013
1006
  end
@@ -1029,14 +1022,10 @@ module RobotLab
1029
1022
  estimated_tok >= window * threshold
1030
1023
  end
1031
1024
 
1032
- def compact_if_over_context_window
1033
- return unless over_compact_threshold?
1034
-
1035
- begin
1036
- compress_history
1037
- rescue DependencyError => e
1038
- RobotLab.config.logger.warn("[#{@name}] auto_compact: #{e.message}; skipping compaction")
1039
- end
1025
+ def compact_context_window
1026
+ compress_history
1027
+ rescue DependencyError => e
1028
+ RobotLab.config.logger.warn("[#{@name}] auto_compact: #{e.message}; skipping compaction")
1040
1029
  end
1041
1030
  end
1042
1031
  end
@@ -196,7 +196,10 @@ module RobotLab
196
196
  stop_reason: hash[:stop_reason],
197
197
  input_tokens: hash[:input_tokens] || 0,
198
198
  output_tokens: hash[:output_tokens] || 0
199
- )
199
+ ).tap do |result|
200
+ result.duration = hash[:duration]
201
+ result.delegated_by = hash[:delegated_by]
202
+ end
200
203
  end
201
204
 
202
205
  private
@@ -98,12 +98,28 @@ module RobotLab
98
98
  tools.select { |tool| allowed_set.include?(tool_name(tool)) }
99
99
  end
100
100
 
101
- private
101
+ # Turn a RubyLLM::Tool subclass into an instance; anything else is
102
+ # returned unchanged. Robots hold tool instances so every name check
103
+ # sees the tool's name (+current_date_time+), not its Ruby class name
104
+ # (+SharedTools::Tools::CurrentDateTimeTool+).
105
+ #
106
+ # @param tool [Class<RubyLLM::Tool>, RubyLLM::Tool, Object]
107
+ # @return [Object]
108
+ #
109
+ def instantiate(tool)
110
+ tool.is_a?(Class) && tool < RubyLLM::Tool ? tool.new : tool
111
+ end
102
112
 
113
+ # The name a tool is offered to the LLM under.
114
+ #
115
+ # @param tool [String, Symbol, Class<RubyLLM::Tool>, #name]
116
+ # @return [String]
117
+ #
103
118
  def tool_name(tool)
104
119
  case tool
105
120
  when String then tool
106
121
  when Symbol then tool.to_s
122
+ when Class then (tool.respond_to?(:tool_name) ? tool.tool_name : tool.name).to_s
107
123
  else tool.respond_to?(:name) ? tool.name.to_s : tool.to_s
108
124
  end
109
125
  end
@@ -120,11 +120,6 @@ module RobotLab
120
120
  @tools.size
121
121
  end
122
122
 
123
- # @!method count
124
- # Alias for {#size}.
125
- # @return [Integer]
126
- alias count size
127
-
128
123
  # @!method length
129
124
  # Alias for {#size}.
130
125
  # @return [Integer]
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module RobotLab
4
- VERSION = "0.5.1"
4
+ VERSION = "0.6.1"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: robot_lab
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.5.1
4
+ version: 0.6.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dewayne VanHoozer
@@ -141,6 +141,20 @@ dependencies:
141
141
  - - "~>"
142
142
  - !ruby/object:Gem::Version
143
143
  version: '0.4'
144
+ - !ruby/object:Gem::Dependency
145
+ name: tsort
146
+ requirement: !ruby/object:Gem::Requirement
147
+ requirements:
148
+ - - ">="
149
+ - !ruby/object:Gem::Version
150
+ version: '0.2'
151
+ type: :runtime
152
+ prerelease: false
153
+ version_requirements: !ruby/object:Gem::Requirement
154
+ requirements:
155
+ - - ">="
156
+ - !ruby/object:Gem::Version
157
+ version: '0.2'
144
158
  - !ruby/object:Gem::Dependency
145
159
  name: ractor_queue
146
160
  requirement: !ruby/object:Gem::Requirement
@@ -239,7 +253,7 @@ metadata:
239
253
  homepage_uri: https://github.com/MadBomber/robot_lab
240
254
  source_code_uri: https://github.com/MadBomber/robot_lab
241
255
  changelog_uri: https://github.com/MadBomber/robot_lab/blob/main/CHANGELOG.md
242
- documentation_uri: https://github.com/MadBomber/robot_lab#readme
256
+ documentation_uri: https://madbomber.github.io/robot_lab
243
257
  bug_tracker_uri: https://github.com/MadBomber/robot_lab/issues
244
258
  rubygems_mfa_required: 'true'
245
259
  rdoc_options: []