robot_lab 0.6.0 → 0.6.2

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: c0a38d5eaca5ddd1d558581dd57db81c94c461b0d9bf7bffbbf325f529e5a8ef
4
- data.tar.gz: 7541f4d1fd133333d667a528f8f96da5287a76a4c6642a3677334496740934b6
3
+ metadata.gz: 5618a855d768bbcbf613979fd8ccf8ce9a49cf27e1fad3e842355c3203bcdf76
4
+ data.tar.gz: cef1a665af0616abbdb1d92e6326fa11e7efd51dca0a51bd2b72877758a20c5b
5
5
  SHA512:
6
- metadata.gz: 6501bd24004fc28a105555a74ca5ae40d4e713d4485d1c581bfb6a77e810119b8e5a9c939c29fd19ec770e7b51eb10b43825c6ebddb7ef34fd60c4915e93639d
7
- data.tar.gz: 70b65d1afb7fa35c48c278455ed7dd33fb7ff3c506eaf259ae885bb2b681efbeb0f4d9d8dfa7f99676817f07328c40ca7428ddf0ffe2110503bdf290524bf65c
6
+ metadata.gz: 30b8395d1dde27a1f9e2137ea1e4d9374d97ee7ac6d1157e75cf037ca8016439e958fe247c8290b2c8250a2ad4e98d93c856290a140b21e1c9c73df6c2f60bf7
7
+ data.tar.gz: 0d73bdb4d4a767e5a412b08bf134731ce04bd9c2634f1073912c10532a1344b3cfbaecb4f02d3b9e449c7b8ad9aa3acb8a42cf582af75f81ebfe23aef1955257
data/CHANGELOG.md CHANGED
@@ -8,6 +8,126 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ### Changed
12
+
13
+ - **ruby_llm 2.2.0 or newer is required** (`ruby_llm ">= 2.2.0", "< 3"`). ruby_llm 2.2
14
+ replaced `Chat#pending_approvals` / `#pending_inputs` / `#deny` with `#pending_questions`
15
+ and `#decline`; robot_lab now uses the new API (#43).
16
+ - `on_input_request:` receives a `RubyLLM::Question` (`RubyLLM::MCP::InputRequest` is now an
17
+ alias for it), and also answers questions a plain `RubyLLM::Tool` asks with `Tool#ask`.
18
+ `on_tool_approval:` still receives the `RubyLLM::ToolCall`.
19
+ - An MCP server failing mid-call now yields ruby_llm's own error text,
20
+ `{ error: "The <server> MCP server failed: <message>" }`, instead of
21
+ `{ error: "<tool>: <message>" }`. `:tool_call` hooks still see the failure as
22
+ `tool_error` (a `RobotLab::MCPError`).
23
+ - `defaults.yml` ships `ruby_llm.provider: null` instead of `:anthropic`, so robots that name
24
+ no provider keep letting RubyLLM infer it from the model (#113).
25
+
26
+ ### Fixed
27
+
28
+ - A robot built without `provider:` falls back to the configured `ruby_llm.provider`
29
+ (config file or `ROBOT_LAB_RUBY_LLM__PROVIDER`), the same way `model` falls back to
30
+ `ruby_llm.model`. Templates can name a `provider:` in front matter. Precedence:
31
+ constructor, then front matter, then config (#113).
32
+ - With ruby_llm 2.2, runs that paused for a tool approval, an MCP input request or an MCP
33
+ task raised `NoMethodError: undefined method 'pending_approvals'` (#43).
34
+ - README and `docs/` tool examples use ruby_llm 2.x's `parameter :x, description:` DSL
35
+ instead of `param :x, desc:`, and call tools with keywords (`tool.call`, not
36
+ `tool.call({})`) (#35).
37
+
38
+ ## [0.6.1] - 2026-11-18
39
+
40
+ ### Fixed
41
+
42
+ - `AgentSkill` rejects a SKILL.md whose front-matter `name` is not a String, so
43
+ `AgentSkillCatalog` skips it with a warning instead of raising `NoMethodError`
44
+ and leaving the catalog empty (#102).
45
+ - `AgentSkillCatalog#find` also resolves a skill by its folder name when the
46
+ front-matter `name` differs, so `skills: [:check_style]` finds
47
+ `check_style/SKILL.md` (#104).
48
+ - `Memory#get(key, wait: N)` returns a stored value of `:timeout` instead of
49
+ mistaking it for a wait timeout and raising `AwaitTimeout` (#100).
50
+ - `Memory#set` applies the same reserved-key handling as `Memory#[]=`, so
51
+ `set(:cache, x)` raises and `set(:data, h)` resets the `data` proxy (#99).
52
+ - A `Memory` subscriber that raises no longer stops later subscribers in the
53
+ same batch from being notified; the error is logged and delivery continues (#98).
54
+ - `Robot#with_bus` on a robot in a `Network` keeps the network's shared
55
+ `BusPoller` and group instead of starting a private poller (#103).
56
+ - Async `Robot#delegate` rejects its `DelegationFuture` when the delegated run
57
+ raises an exception outside `StandardError` (e.g. `NotImplementedError`), so
58
+ `future.value` re-raises it at once instead of timing out or blocking forever.
59
+ - `Memory#get(:a, :b, wait: N)` now treats `N` as one deadline for the whole
60
+ call instead of waiting up to `N` seconds per missing key (#92).
61
+ - Examples 09, 10 and 11 load `amazing_print` before `common.rb` so they no longer crash at startup.
62
+ - `HistoryCompressor` keeps an assistant message that has both text and tool calls, so its tool result is never orphaned.
63
+ - `Network#task` raises `ArgumentError` for a task name already in the network,
64
+ matching `add_robot`, instead of silently dropping the earlier task.
65
+ - `Network` with `parallel_mode: :ractor` now shuts the Ractor scheduler down
66
+ when `run_pipeline` raises, instead of leaking its worker pool on every failed
67
+ run.
68
+ - `BusPoller` keeps draining a robot's queued deliveries after one delivery
69
+ raises `BusError`, instead of stranding them until a later message arrived and
70
+ then running them out of order.
71
+ - `DotState` (`ctx.local` in hooks) supports `[]` and `[]=`; `ctx.local[:k] = v`
72
+ used to store the key name under `:[]` and drop the value.
73
+ - `HookContext#to_h` now includes inherited readers (such as `event`, and
74
+ `robot`/`request` on `LlmGenerationHookContext`) and no longer raises
75
+ `ArgumentError` on the base class.
76
+ - Removed the duplicate `Robot#hook_registries` from `robot.rb`; the `Hooking`
77
+ concern now owns the only definition, so changes there take effect.
78
+ - A budget reservation is now released when a run is cut off by an exception
79
+ outside `StandardError` (`Timeout.timeout` around `robot.run`, `Interrupt`),
80
+ so later runs are no longer refused as over budget.
81
+ - Examples: `examples/common.rb` sets RobotLab's `ruby_llm.model` and `provider`
82
+ to the examples' default, so a robot built without `model:` (the bare robot in
83
+ `09_chaining.rb`) no longer falls back to `claude-sonnet-4`.
84
+ - Docs and doc comments now describe `HistoryCompressor` and `Convergence` as
85
+ term-frequency cosine similarity (not TF-IDF) and quote the real
86
+ `ToolLoopError` message.
87
+ - `RobotResult.from_hash` now restores `duration` and `delegated_by`.
88
+ - `Hook.namespace` returns nil for an anonymous `Hook` subclass instead of raising
89
+ `NoMethodError`, so `HookRegistry#on` raises its intended "has no namespace"
90
+ `ArgumentError` and anonymous per-run hooks run.
91
+ - `DelegationFuture#value` keeps waiting after a spurious wakeup instead of
92
+ raising `DelegationTimeout` before the delegated task resolves.
93
+ - `ToolManifest#count` is now `Enumerable#count`, so it honours a block and an
94
+ argument; with neither it still returns the size.
95
+ - A `SKILL.md` whose front matter YAML can't be safely loaded (such as an
96
+ unquoted date) raises `ConfigurationError`, so `AgentSkillCatalog` skips it and
97
+ still loads the other skills.
98
+ - A budget reservation is now released when a run fails with a `StandardError`,
99
+ so later runs are no longer refused as over budget.
100
+ - A `doom_loop_threshold` below 1 or not an Integer raises `ArgumentError` instead
101
+ of `ZeroDivisionError` or "negative array size" mid-run.
102
+ - `Memory#wait_for_key` closes its waiter pipe on every exit path, so an early
103
+ return or a raise no longer leaks two file descriptors.
104
+ - `Robot#call` reports an error raised while extracting the run context instead
105
+ of masking it with a `TypeError`.
106
+ - `token_budget` is checked against the budget ledger, so a call that overruns
107
+ the budget after `reset_token_totals` is now flagged.
108
+ - `Narrator.enable!` registers the narrator once; calling it again only changes
109
+ the output instead of narrating every event twice.
110
+ - `tsort` is now a runtime dependency, so robot_lab loads under Bundler on Ruby
111
+ 4.1, where `tsort` is no longer a default gem.
112
+ - `Memory` with the `:auto` backend pings Redis and falls back to a Hash when
113
+ the server is unreachable, instead of raising.
114
+ - `Budget::Ledger#reserve!` can reserve exactly what `remaining` reports; Float
115
+ rounding no longer raises `BudgetExceeded` with budget left.
116
+ - Examples: `25_history_search.rb` requires `common` before `json`, so it no
117
+ longer raises `Gem::LoadError` when the bundle locks an older json.
118
+ - `Memory#subscribe_pattern` escapes every regex metacharacter in the glob, so
119
+ only `*` and `?` are wildcards: `"price(usd):*"` now matches
120
+ `price(usd):today`, and `"a+b"` matches `a+b` instead of `aab` (#91).
121
+
122
+ ### Changed
123
+
124
+ - Gemspec `documentation_uri` now points at the docs site
125
+ (https://madbomber.github.io/robot_lab) instead of the README.
126
+ - CI: a GitHub Actions `Test` workflow runs `bundle exec rake test` on Ruby 4.0
127
+ for pushes to `main`/`develop` and for pull requests.
128
+
129
+ ## [0.6.0] - 2026-11-02
130
+
11
131
  ### Fixed
12
132
 
13
133
  - **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.
data/README.md CHANGED
@@ -343,11 +343,11 @@ tool = RobotLab::Tool.create(name: "fetch_data") do |args|
343
343
  raise IOError, "connection refused"
344
344
  end
345
345
 
346
- result = tool.call({})
346
+ result = tool.call
347
347
  # => "Error (fetch_data): connection refused"
348
348
  ```
349
349
 
350
- This applies to every `RobotLab::Tool` — subclasses and factory tools. (MCP tools are `RubyLLM::MCP::Tool` instances; a `RubyLLM::MCP::Error` raised during one of their calls becomes an `{ error: }` tool result through the robot's tool-call bridge instead.) For critical tools where you want exceptions to propagate, opt out per class:
350
+ This applies to every `RobotLab::Tool` — subclasses and factory tools. (MCP tools are `RubyLLM::MCP::Tool` instances; a server failing one of their calls becomes an `{ error: }` tool result instead, and `:tool_call` hooks see it as `tool_error`.) For critical tools where you want exceptions to propagate, opt out per class:
351
351
 
352
352
  ```ruby
353
353
  class CriticalTool < RobotLab::Tool
@@ -363,7 +363,7 @@ end
363
363
  class Magic8Ball < RubyLLM::Tool
364
364
  description "Consult the mystical Magic 8-Ball for guidance on yes/no questions"
365
365
 
366
- param :question, type: "string", desc: "A yes/no question to ask the oracle"
366
+ parameter :question, type: "string", description: "A yes/no question to ask the oracle"
367
367
 
368
368
  RESPONSES = [
369
369
  { answer: "It is certain", certainty: 0.95, vibe: "positive" },
@@ -552,7 +552,7 @@ robot.run(robot.mcp[:git_hub].prompt("code_review", code: diff), mcp: :inherit)
552
552
  robot.disconnect # closes every server (stopping stdio processes); they reconnect on next use
553
553
  ```
554
554
 
555
- Connection failures are logged, recorded in `robot.mcp_failures` and retried on the next run that selects the server; they are not raised, and one failing server does not stop the others. A `RubyLLM::MCP::Error` during a tool call becomes an `{ error: }` tool result rather than aborting the run. See the [MCP Integration guide](docs/guides/mcp-integration.md), including its "Migrating from 0.3" section.
555
+ Connection failures are logged, recorded in `robot.mcp_failures` and retried on the next run that selects the server; they are not raised, and one failing server does not stop the others. A server failing during a tool call becomes an `{ error: }` tool result rather than aborting the run. See the [MCP Integration guide](docs/guides/mcp-integration.md), including its "Migrating from 0.3" section.
556
556
 
557
557
  ## Message Bus
558
558
 
@@ -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
@@ -54,7 +54,7 @@ defaults:
54
54
 
55
55
  # RubyLLM Configuration Section
56
56
  ruby_llm:
57
- provider: :anthropic
57
+ provider: null # default provider for robots built without provider: (null = let RubyLLM infer it from the model)
58
58
  model: claude-sonnet-4-6
59
59
  assume_model_exists: false # (dep of assume_exists in chat section) set true for Ollama and other local LLM providers
60
60
  # Provider API Keys (null = use env vars directly)
@@ -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
 
@@ -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!
@@ -5,7 +5,8 @@ module RobotLab
5
5
  # Template loading, rendering, and front-matter extraction.
6
6
  #
7
7
  # Owns: @expanded_skills, @pending_agent_skills, @agent_skill_store
8
- # Reads: @chat, @template, @build_context, @name, @name_from_constructor, @description, @local_tools, @mcp_config, @config
8
+ # Reads: @chat, @template, @build_context, @name, @name_from_constructor, @description, @local_tools, @mcp_config, @config, @provider
9
+ # (front-matter provider: goes through Robot#adopt_front_matter_provider)
9
10
  # Contract: called during initialize after assign_identity_ivars and build_effective_config
10
11
  module TemplateRendering
11
12
  # Front matter keys that map to chat configuration methods
@@ -16,7 +17,7 @@ module RobotLab
16
17
 
17
18
  # Front matter keys for robot identity and capabilities.
18
19
  # Note: uses `robot_name` because PM::Metadata reserves `name` for the filename.
19
- FRONT_MATTER_EXTRA_KEYS = %i[tools mcp robot_name description skills].freeze
20
+ FRONT_MATTER_EXTRA_KEYS = %i[tools mcp robot_name description skills provider].freeze
20
21
 
21
22
  # Apply a prompt_manager template to the robot's chat
22
23
  #
@@ -245,6 +246,8 @@ module RobotLab
245
246
  # @param metadata [PM::Metadata] front matter metadata
246
247
  # @param extras [Hash] accumulator hash
247
248
  def accumulate_extras(metadata, extras)
249
+ extras[:provider] = metadata.provider if metadata.respond_to?(:provider) && metadata.provider
250
+
248
251
  if metadata.respond_to?(:robot_name) && metadata.robot_name
249
252
  extras[:robot_name] = metadata.robot_name.to_s
250
253
  end
@@ -265,6 +268,8 @@ module RobotLab
265
268
  #
266
269
  # @param extras [Hash] accumulated extras from skills + main template
267
270
  def apply_accumulated_extras(extras)
271
+ adopt_front_matter_provider(extras[:provider])
272
+
268
273
  if extras[:robot_name] && !@name_from_constructor
269
274
  @name = extras[:robot_name]
270
275
  end
@@ -285,6 +290,8 @@ module RobotLab
285
290
  # Constructor-provided values take precedence over frontmatter.
286
291
  # :reek:FeatureEnvy -- copying front-matter metadata fields into this robot's ivars is the method's purpose.
287
292
  def apply_front_matter_extras(metadata)
293
+ adopt_front_matter_provider(metadata.provider) if metadata.respond_to?(:provider)
294
+
288
295
  if metadata.respond_to?(:robot_name) && metadata.robot_name && !@name_from_constructor
289
296
  @name = metadata.robot_name.to_s
290
297
  end
@@ -10,9 +10,9 @@ module RobotLab
10
10
  # execution of such tools (RobotLab::Tool runs them itself in #call),
11
11
  # and turns an MCP transport failure mid-call into an error result so
12
12
  # the model can recover instead of the run aborting.
13
- # - The settlement loop answers what ruby_llm pauses a run for: tool
14
- # calls that require approval, MCP input requests (elicitation), and
15
- # long-running MCP tasks. A run never returns half-finished.
13
+ # - The settlement loop answers what ruby_llm pauses a run for: the
14
+ # questions in Chat#pending_questions (tool calls that require
15
+ # approval, MCP input requests, Tool#ask) and long-running MCP tasks. A run never returns half-finished.
16
16
  #
17
17
  # Owns: nothing (uses @chat, @tool_approval, @on_tool_approval, @on_input_request)
18
18
  # Reads: @name
@@ -40,7 +40,8 @@ module RobotLab
40
40
  # Run :tool_call hooks around a chat-executed tool call. Yields to the
41
41
  # chat's own execution; the PAUSED sentinel it returns for approvals,
42
42
  # input requests and tasks passes through untouched.
43
- # :reek:TooManyStatements -- context build, hook wrap and the MCP rescue are one guarded dispatch.
43
+ # :reek:TooManyStatements :reek:FeatureEnvy -- context build, hook wrap and the MCP rescue are one guarded
44
+ # dispatch that fills the hook context.
44
45
  def bridge_tool_call(tool_call)
45
46
  tool = @chat.tools[tool_call.name.to_sym]
46
47
  return yield if tool.nil? || tool.is_a?(RobotLab::Tool)
@@ -52,6 +53,7 @@ module RobotLab
52
53
  registries: scope[:registries] || hook_registries,
53
54
  per_run_hooks: scope[:per_run_hooks]) do
54
55
  context.tool_result = yield
56
+ context.tool_error = mcp_failure_error(context.tool_result)
55
57
  rescue RubyLLM::MCP::Error => e
56
58
  context.tool_error = e
57
59
  context.tool_result = { error: "#{tool.name}: #{e.message}" }
@@ -59,6 +61,19 @@ module RobotLab
59
61
  context.tool_result
60
62
  end
61
63
 
64
+ # ruby_llm (>= 2.2) catches a server failing an MCP call itself and
65
+ # returns the error Hash as the result, so the rescue in
66
+ # #bridge_tool_call never sees it. Surface it to :tool_call hooks as an
67
+ # MCPError all the same.
68
+ #
69
+ # @param result [Object] what the chat's tool execution returned
70
+ # @return [RobotLab::MCPError, nil]
71
+ def mcp_failure_error(result)
72
+ return unless result.is_a?(RubyLLM::MCP::Outages::Failure)
73
+
74
+ MCPError.new(result[:error].to_s)
75
+ end
76
+
62
77
  # Keep completing the chat until nothing waits on the outside world:
63
78
  # decide approvals, answer input requests, wait on tasks, complete again.
64
79
  #
@@ -67,20 +82,27 @@ module RobotLab
67
82
  def settle_pending_tool_calls(response, &)
68
83
  deadline = nil
69
84
  while @chat.waiting?
70
- decide_pending_approvals
71
- answer_pending_inputs
85
+ settle_pending_questions
72
86
  deadline = wait_for_mcp_tasks(deadline)
73
87
  response = @chat.complete(&)
74
88
  end
75
89
  response
76
90
  end
77
91
 
78
- def decide_pending_approvals
79
- @chat.pending_approvals.each do |tool_call|
80
- approve_tool_call?(tool_call) ? @chat.approve(tool_call) : @chat.deny(tool_call)
92
+ # Answer every question the chat waits on: approvals go through the
93
+ # approval policy; the rest (MCP input requests, Tool#ask) go to
94
+ # on_input_request.
95
+ def settle_pending_questions
96
+ @chat.pending_questions.each do |question|
97
+ question.approval? ? decide_approval(question) : settle_input_request(question)
81
98
  end
82
99
  end
83
100
 
101
+ # @param question [RubyLLM::Question] an approval question
102
+ def decide_approval(question)
103
+ approve_tool_call?(question.tool_call) ? @chat.approve(question) : @chat.decline(question)
104
+ end
105
+
84
106
  # Approval policy: an on_tool_approval Proc decides; else tool_approval
85
107
  # :approve allows; else deny with a warning naming the two settings.
86
108
  #
@@ -97,14 +119,10 @@ module RobotLab
97
119
  false
98
120
  end
99
121
 
100
- def answer_pending_inputs
101
- @chat.pending_inputs.each { |request| settle_input_request(request) }
102
- end
103
-
104
122
  # An on_input_request Proc answers a request with a Hash of field
105
123
  # values (or +true+ to accept a URL request); anything else declines.
106
124
  #
107
- # @param request [RubyLLM::MCP::InputRequest]
125
+ # @param request [RubyLLM::Question] a pending question that is not an approval
108
126
  def settle_input_request(request)
109
127
  answer = @on_input_request&.call(request)
110
128
  case answer
@@ -155,8 +155,9 @@ module RobotLab
155
155
  # on_tool_approval is given: :deny (default) or :approve
156
156
  # @param on_tool_approval [Proc, nil] called with each RubyLLM::ToolCall that requires approval;
157
157
  # a truthy return approves it
158
- # @param on_input_request [Proc, nil] called with each RubyLLM::MCP::InputRequest an MCP server
159
- # raises; return a Hash of field values (or true for a URL request) to answer, anything else declines
158
+ # @param on_input_request [Proc, nil] called with each RubyLLM::Question a tool call waits on that is
159
+ # not an approval (MCP input requests, Tool#ask); return a Hash of field values (or true for a
160
+ # URL request) to answer, anything else declines
160
161
  # @param mcp_discovery [Boolean] select only the MCP servers relevant to each message (see MCP::ServerDiscovery)
161
162
  # @param enable_cache [Boolean] whether to enable semantic caching
162
163
  # @param bus [TypedBus::MessageBus, nil] optional message bus for inter-robot communication
@@ -231,8 +232,12 @@ module RobotLab
231
232
  resolved_model = @config.model || lab_config.ruby_llm.model
232
233
  chat_kwargs = { model: resolved_model }
233
234
 
234
- # RubyLLM auto-sets assume_model_exists for local providers when provider is specified.
235
- @provider = provider
235
+ # Provider precedence: constructor > template front matter (applied
236
+ # later, see TemplateRendering#adopt_front_matter_provider) > config.
237
+ # A named provider routes the model there without a registry lookup,
238
+ # so assume_model_exists is set for it whatever its source.
239
+ @provider_from_constructor = !provider.nil?
240
+ @provider = resolve_provider(provider, lab_config)
236
241
  if @provider
237
242
  chat_kwargs[:provider] = @provider
238
243
  chat_kwargs[:assume_model_exists] = true
@@ -293,12 +298,12 @@ module RobotLab
293
298
  # :reek:TooManyStatements -- SimpleFlow step: timing, run, and error-shielding belong together.
294
299
  # :reek:DuplicateMethodCall -- each clock_gettime samples a different instant (start/stop/rescue); a local would be wrong.
295
300
  def call(result)
301
+ start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
296
302
  run_context = extract_run_context(result)
297
303
 
298
304
  # Extract the message from run context
299
305
  message = run_context.delete(:message)
300
306
 
301
- start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
302
307
  robot_result = run(message, **run_context)
303
308
  robot_result.duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start_time
304
309
 
@@ -372,7 +377,7 @@ module RobotLab
372
377
  self
373
378
  end
374
379
 
375
- # Compress conversation history using TF-IDF relevance scoring.
380
+ # Compress conversation history using term-frequency cosine similarity.
376
381
  #
377
382
  # Old turns are tiered against the most recent context:
378
383
  # - High relevance (score >= keep_threshold) → kept verbatim
@@ -445,7 +450,8 @@ module RobotLab
445
450
  result.duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started_at
446
451
  result.delegated_by = delegator_name
447
452
  future.resolve!(result)
448
- rescue => e
453
+ rescue Exception => e # rubocop:disable Lint/RescueException
454
+ # Settle the future on any error, or value blocks until timeout.
449
455
  future.reject!(e)
450
456
  end
451
457
 
@@ -555,6 +561,30 @@ module RobotLab
555
561
  "(e.g. RobotLab.build(local_tools: [MyTool.new]))."
556
562
  end
557
563
 
564
+ # The provider a robot starts with: the constructor's, else the
565
+ # configured ruby_llm.provider (nil when neither names one). A configured
566
+ # String (e.g. from ROBOT_LAB_RUBY_LLM__PROVIDER) becomes a Symbol.
567
+ #
568
+ # @param provider [String, Symbol, nil] the constructor argument
569
+ # @param lab_config [RobotLab::Config]
570
+ # @return [String, Symbol, nil]
571
+ def resolve_provider(provider, lab_config)
572
+ return provider unless provider.nil?
573
+
574
+ configured = lab_config.ruby_llm.provider
575
+ configured.to_s.empty? ? nil : configured.to_sym
576
+ end
577
+
578
+ # A template's +provider:+ replaces the configured provider, but never
579
+ # one passed to the constructor.
580
+ #
581
+ # @param value [String, Symbol, nil] the front matter provider
582
+ def adopt_front_matter_provider(value)
583
+ return if @provider_from_constructor || value.to_s.empty?
584
+
585
+ @provider = value.to_sym
586
+ end
587
+
558
588
  # :reek:LongParameterList :reek:TooManyStatements -- one keyword and one assignment per identity ivar;
559
589
  # a hash would lose keyword checking.
560
590
  def assign_identity_ivars(name:, template:, system_prompt:, context:, description:,
@@ -847,10 +877,6 @@ module RobotLab
847
877
  end
848
878
  end
849
879
 
850
- def hook_registries(network = nil)
851
- [RobotLab.hooks, network&.hooks, @hooks]
852
- end
853
-
854
880
  # Extract run context from SimpleFlow::Result
855
881
  # :reek:TooManyStatements -- one delete/re-add per robot-specific run param; a loop would hide which keys are special.
856
882
  def extract_run_context(result)
@@ -1003,11 +1029,7 @@ module RobotLab
1003
1029
  else
1004
1030
  case compact
1005
1031
  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
1032
+ compact_context_window
1011
1033
  when Proc
1012
1034
  compact.call(self)
1013
1035
  end
@@ -1029,14 +1051,10 @@ module RobotLab
1029
1051
  estimated_tok >= window * threshold
1030
1052
  end
1031
1053
 
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
1054
+ def compact_context_window
1055
+ compress_history
1056
+ rescue DependencyError => e
1057
+ RobotLab.config.logger.warn("[#{@name}] auto_compact: #{e.message}; skipping compaction")
1040
1058
  end
1041
1059
  end
1042
1060
  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
@@ -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.6.0"
4
+ VERSION = "0.6.2"
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.6.0
4
+ version: 0.6.2
5
5
  platform: ruby
6
6
  authors:
7
7
  - Dewayne VanHoozer
@@ -43,7 +43,7 @@ dependencies:
43
43
  requirements:
44
44
  - - ">="
45
45
  - !ruby/object:Gem::Version
46
- version: 2.1.1
46
+ version: 2.2.0
47
47
  - - "<"
48
48
  - !ruby/object:Gem::Version
49
49
  version: '3'
@@ -53,7 +53,7 @@ dependencies:
53
53
  requirements:
54
54
  - - ">="
55
55
  - !ruby/object:Gem::Version
56
- version: 2.1.1
56
+ version: 2.2.0
57
57
  - - "<"
58
58
  - !ruby/object:Gem::Version
59
59
  version: '3'
@@ -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: []