nexo_ai 0.12.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/nexo/agent.rb CHANGED
@@ -24,7 +24,7 @@ module Nexo
24
24
  # configuration instead of silently resetting to defaults.
25
25
  CONFIG_IVARS = %i[
26
26
  @model @assume_model_exists @provider @sandbox @permissions @instructions
27
- @skills @mcp @mcp_allow @fetch_allow @search_backend @requires @produces
27
+ @skills @mcp @mcp_allow @fetch_allow @search_backend @requires @produces @tools
28
28
  ].freeze
29
29
 
30
30
  class << self
@@ -163,6 +163,38 @@ module Nexo
163
163
  names.empty? ? (@produces || []) : (@produces = ((@produces || []) + names).uniq)
164
164
  end
165
165
 
166
+ # Declares tools of your own for this agent. Accumulating, like `skills`.
167
+ # With no arguments it reads the declarations (default `[]`).
168
+ #
169
+ # ```ruby
170
+ # class Archivist < Nexo::Agent
171
+ # tools Today, SumPayments # pure helpers: no gate
172
+ # tools ArchiveRun, capability: :write # gated like Nexo's write tool
173
+ # tools ->(agent) { Lookup.new(root: agent.cwd) }
174
+ # end
175
+ # ```
176
+ #
177
+ # Each entry is a `RubyLLM::Tool` class (instantiated with no arguments), an
178
+ # instance, or a lambda taking the agent and returning one — or an Array of
179
+ # them, for an agent whose tools depend on how it was built.
180
+ #
181
+ # `capability:` names what the tool does in Nexo's terms — `:read`, `:write`,
182
+ # `:shell`, `:fetch`, `:search`. The tool is then wrapped in Nexo::GatedTool:
183
+ # the agent's Permissions decide every call exactly as they do for Nexo's
184
+ # own tools (denied under `:read_only`, prompted under `:ask`, suspended
185
+ # under `:approve`), and it is left out of the schema when it could never be
186
+ # authorized. Without `capability:` the tool runs ungated — the right choice
187
+ # only for a tool with no side effects.
188
+ #
189
+ # Declare tools here instead of overriding `#chat` to call `with_tools`: a
190
+ # tool added that way is unknown to Nexo, which warns about it, and refuses
191
+ # it under `Nexo.config.strict_tools`.
192
+ def tools(*list, capability: nil)
193
+ return @tools || [] if list.empty?
194
+
195
+ @tools = (@tools || []) + list.flatten.map { |tool| {tool: tool, capability: capability} }
196
+ end
197
+
166
198
  # Declares an MCP server for this agent (Spec 6). Accumulating: multiple
167
199
  # `mcp` lines are collected. With no args (`name` nil and `opts` empty) it
168
200
  # reads the list (default `[]`); otherwise it appends the friendly,
@@ -217,20 +249,6 @@ module Nexo
217
249
  end
218
250
  end
219
251
 
220
- # The set of tool names handed to an opt-in backend that ships its own tools
221
- # (e.g. Loops::AgentSDK). The default Loops::RubyLLM ignores this — it
222
- # uses the agent's own sandbox-backed tools instead.
223
- ALLOWED_TOOLS = %w[Read Write Edit Bash Glob Grep].freeze
224
-
225
- # Maps Nexo's permission modes onto AgentSDK's own permission vocabulary,
226
- # consumed by Loops::AgentSDK. `:ask` maps to `:default` on purpose: human
227
- # gating stays in Nexo's own `on_ask` path and is not delegated to the SDK.
228
- PERMISSION_MODE_MAP = {
229
- read_only: :default,
230
- auto: :bypass_permissions,
231
- ask: :default
232
- }.freeze
233
-
234
252
  # The resolved per-instance configuration (arg → class macro → config): the
235
253
  # working directory, model, provider, `assume_model_exists` flag, the resolved
236
254
  # Sandbox and Permissions, the system instructions, and the injected Loop.
@@ -240,14 +258,17 @@ module Nexo
240
258
  # Symbol shorthands (:virtual/:local, :read_only/:auto/:ask/:approve) and
241
259
  # pre-built Sandbox/Permissions instances are both accepted. `loop:` injects
242
260
  # the engine that drives a prompt — the provider-neutral Loops::RubyLLM by
243
- # default, or an opt-in backend like Loops::AgentSDK.
261
+ # default, or a backend of your own.
244
262
  #
245
- # `decision:` (Spec 16, default `nil`) is a per-run approval answer
246
- # (`{approved: true|false}`) threaded into the resolved Permissions so an
247
- # `:approve` gate allows/denies instead of raising Nexo::ApprovalRequired.
248
- # It only supplies the *answer* to an already-`:approve` gate — it never
249
- # widens capability. Workflow#run_agent passes it on the resume pass.
250
- def initialize(cwd: Dir.pwd, model: nil, sandbox: nil, permissions: nil, decision: nil, loop: Loops::RubyLLM.new)
263
+ # `decisions:` (0.14, default `nil`) are the per-call approval answers for an
264
+ # `:approve` gate — a Hash of Permissions::approval_key → `true`/`false`. A
265
+ # call found there runs or is denied; any other call raises
266
+ # Nexo::ApprovalRequired. They only supply *answers* to an already-`:approve`
267
+ # gate — they never widen capability. Workflow#run_agent passes the approvals
268
+ # recorded on the run. `decision:` is the deprecated global form (one
269
+ # `{approved:}` answer for every gated call).
270
+ def initialize(cwd: Dir.pwd, model: nil, sandbox: nil, permissions: nil, decision: nil, decisions: nil,
271
+ loop: Loops::RubyLLM.new)
251
272
  @cwd = cwd
252
273
  @model = model || self.class.model || Nexo.config.default_model
253
274
  if @model.nil?
@@ -267,7 +288,8 @@ module Nexo
267
288
  # sharing the run's sandbox) is BORROWED — closing it would strand the owner.
268
289
  @owns_sandbox = sandbox.nil?
269
290
  @sandbox = resolve_sandbox(sandbox || self.class.sandbox)
270
- @permissions = resolve_permissions(permissions || self.class.permissions, decision: decision)
291
+ @permissions = resolve_permissions(permissions || self.class.permissions, decision: decision,
292
+ decisions: decisions)
271
293
  @instructions = self.class.instructions
272
294
  @loop = loop
273
295
  end
@@ -287,7 +309,7 @@ module Nexo
287
309
  # Re-applying `@instructions` on every resume stays idempotent because the
288
310
  # persisted-chat `#with_instructions` (default `append: false`) *replaces* the
289
311
  # stored `role: :system` messages rather than appending, so the thread keeps
290
- # exactly one copy across resumes (VERIFIED, ruby_llm 1.16.0).
312
+ # exactly one copy across resumes (VERIFIED, ruby_llm 2.2.3).
291
313
  def chat(base: nil)
292
314
  c = base || RubyLLM.chat(**chat_model_options)
293
315
  c = apply_instructions(c)
@@ -311,10 +333,12 @@ module Nexo
311
333
  tools << Tools::Shell.new(sandbox: @sandbox, permissions: @permissions)
312
334
  end
313
335
  c.with_tools(*tools)
336
+ apply_host_tools(c)
314
337
  apply_mcp(c)
315
338
  apply_fetch(c)
316
339
  apply_search(c)
317
340
  apply_tool_concurrency(c)
341
+ apply_tool_backstop(c)
318
342
  c
319
343
  end
320
344
 
@@ -404,33 +428,16 @@ module Nexo
404
428
 
405
429
  public
406
430
 
407
- # The agent's Nexo permission mode mapped onto an opt-in backend's own
408
- # permission vocabulary (see PERMISSION_MODE_MAP). Consumed by
409
- # Loops::AgentSDK; the default Loops::RubyLLM does its gating inside the
410
- # sandbox-backed tools and ignores this.
411
- def permission_mode
412
- PERMISSION_MODE_MAP.fetch(@permissions.mode, :default)
413
- end
414
-
415
- # The tool names handed to an opt-in backend that ships its own tools.
416
- def allowed_tools
417
- ALLOWED_TOOLS
418
- end
419
-
420
431
  # Releases any MCP server connections held by this agent instance. Clients are
421
432
  # memoized on the instance and reused across prompts (Spec 6 lifecycle default),
422
433
  # so a long-lived agent holding stdio/SSE servers should call `#close` when
423
434
  # done. Idempotent: safe to call with no MCP servers attached or more than once.
424
435
  #
425
- # VERIFY (Group 0, ruby_llm-mcp 1.0.0): the client teardown method is `#stop`
426
- # (guarded by `respond_to?`, falling back to `#close` for other client shapes).
436
+ # VERIFIED (ruby_llm 2.2.3): a `RubyLLM::MCP` server is torn down with `#close`,
437
+ # which stops a stdio process and ends an HTTP session.
427
438
  def close
428
439
  @mcp_clients&.each do |client|
429
- if client.respond_to?(:stop)
430
- client.stop
431
- elsif client.respond_to?(:close)
432
- client.close
433
- end
440
+ client.close if client.respond_to?(:close)
434
441
  rescue
435
442
  # Best-effort teardown: a failing stop on one client must not strand the
436
443
  # remaining clients or leave @mcp_clients set (breaking idempotency).
@@ -524,29 +531,103 @@ module Nexo
524
531
  # callbacks (wired in Loops::RubyLLM) and appear in the run's event log with
525
532
  # no extra wiring. Returns early when no server is declared.
526
533
  #
527
- # Clients are built once and memoized on the instance (Spec 6 lifecycle
528
- # default): the `ruby_llm-mcp` client connects on construction and is reusable
529
- # across prompts, so subsequent `#chat` calls reuse the live connections until
530
- # #close. VERIFY (Group 0): tools accessor is `client.tools` (an Array).
534
+ # Servers are built once and memoized on the instance: a `RubyLLM::MCP` server
535
+ # connects on its first request and is reusable across prompts, so subsequent
536
+ # `#chat` calls reuse the live connections until #close.
537
+ #
538
+ # The tools are attached with `with_tools` — NOT `chat.with_mcp(server)` — so
539
+ # each one can be wrapped in the permission gate first. VERIFIED (ruby_llm
540
+ # 2.2.3): `server.tools` is an Array of `RubyLLM::MCP::Tool`. Tools an MCP App
541
+ # reserves for its own UI are left out, as `with_mcp` would.
531
542
  def apply_mcp(chat)
532
543
  return if self.class.mcp.empty?
533
544
 
534
545
  @mcp_clients ||= self.class.mcp.map { |cfg| Nexo::MCP.build(**cfg) }
535
- gated = @mcp_clients.flat_map(&:tools).map do |tool|
546
+ gated = @mcp_clients.flat_map(&:tools).select { |tool| attachable_mcp_tool?(tool) }.map do |tool|
536
547
  wrap_mcp_tool(Nexo::MCP::GatedTool.new(tool: tool, permissions: @permissions))
537
548
  end
538
549
  chat.with_tools(*gated) unless gated.empty?
539
550
  end
540
551
 
541
- # Applies Nexo.config.tool_concurrency to the chat, LAST — every `with_tools` call
542
- # resets the chat's concurrency to its current value, so setting it before the
543
- # tools are attached would be undone. `nil` leaves RubyLLM's own setting alone.
552
+ # Whether an MCP tool is worth attaching: the model may call it, and the gate
553
+ # could authorize it. A tool `:read_only` can never allow is left out of the
554
+ # schema, as a sandbox tool is — it would only cost tokens and a wasted call.
555
+ def attachable_mcp_tool?(tool)
556
+ model_callable?(tool) && !@permissions.never_allows_mcp?(tool.name)
557
+ end
558
+
559
+ # Whether the model may call this MCP tool. Only MCP App tools restrict it.
560
+ def model_callable?(tool)
561
+ !tool.respond_to?(:visibility) || tool.visibility.include?(:model)
562
+ end
563
+
564
+ # Attaches the tools declared with the `tools` macro. One declared with a
565
+ # `capability:` is wrapped in Nexo::GatedTool, and skipped altogether when the
566
+ # gate could never authorize it.
567
+ def apply_host_tools(chat)
568
+ built = self.class.tools.flat_map do |entry|
569
+ capability = entry[:capability]
570
+ next [] if capability && @permissions.never_allows?(capability)
571
+
572
+ build_host_tools(entry[:tool]).map do |tool|
573
+ capability ? Nexo::GatedTool.new(tool: tool, permissions: @permissions, capability: capability) : tool
574
+ end
575
+ end
576
+ chat.with_tools(*built) unless built.empty?
577
+ end
578
+
579
+ # A declared tool is a class, an instance, or a lambda taking the agent. The
580
+ # lambda may return several tools, and may return classes.
581
+ def build_host_tools(tool)
582
+ case tool
583
+ when Class then [tool.new]
584
+ when Proc then Array(tool.call(self)).flat_map { |built| build_host_tools(built) }
585
+ else [tool]
586
+ end
587
+ end
588
+
589
+ # The fail-closed backstop behind the gate. Every tool Nexo attached is on the
590
+ # chat by now; one `around_tool_call` block lets those run and catches any
591
+ # other — a tool the host added to the chat itself, which no gate ever saw.
592
+ # Under `Nexo.config.strict_tools` such a call is skipped (`ruby_llm` then
593
+ # tells the model the call did not run); otherwise it runs with a one-time
594
+ # warning.
595
+ #
596
+ # This is a backstop, not the gate: a skipped call can only produce
597
+ # `ruby_llm`'s fixed "did not run" text, so the gate that explains itself
598
+ # stays in the tools (VERIFIED, ruby_llm 2.2.3).
599
+ #
600
+ # The block is registered once per chat and reads the known names from the
601
+ # chat, so a Session that rebuilds over the same chat does not stack blocks.
602
+ # It runs on the tool's own thread under tool concurrency; the name set is
603
+ # frozen and only read.
604
+ def apply_tool_backstop(chat)
605
+ return unless chat.respond_to?(:around_tool_call) && chat.respond_to?(:tools)
606
+
607
+ chat.instance_variable_set(:@nexo_known_tools, chat.tools.keys.to_set(&:to_s).freeze)
608
+ return if chat.instance_variable_get(:@nexo_backstop)
609
+
610
+ chat.instance_variable_set(:@nexo_backstop, true)
611
+ chat.around_tool_call do |tool_call, &run|
612
+ name = tool_call.name.to_s
613
+ if chat.instance_variable_get(:@nexo_known_tools).include?(name)
614
+ run.call
615
+ elsif !Nexo.config.strict_tools
616
+ Nexo.warn_undeclared_tool(name, self.class)
617
+ run.call
618
+ end
619
+ end
620
+ end
621
+
622
+ # Applies Nexo.config.tool_concurrency to the chat through
623
+ # `with_tool_options(concurrency:)` (ruby_llm 2.x moved tool execution settings
624
+ # off `with_tools`). `nil` leaves RubyLLM's own setting alone.
544
625
  def apply_tool_concurrency(chat)
545
626
  mode = Nexo.config.tool_concurrency
546
627
  return if mode.nil?
547
- return unless chat.respond_to?(:with_tools)
628
+ return unless chat.respond_to?(:with_tool_options)
548
629
 
549
- chat.with_tools(concurrency: mode)
630
+ chat.with_tool_options(concurrency: mode)
550
631
  end
551
632
 
552
633
  # Hook: called once per MCP tool, AFTER it is wrapped in a permission-gating
@@ -570,7 +651,7 @@ module Nexo
570
651
  # end
571
652
  #
572
653
  # A wrapper must keep the duck type the chat relies on — `#name`, `#description`,
573
- # `#params_schema` and `#call`. GatedTool delegates the rest through
654
+ # `#parameters_schema` and `#call`. GatedTool delegates the rest through
574
655
  # `method_missing`, so wrappers compose. Gating happens underneath, so a wrapper
575
656
  # only ever sees an already-authorized call: wrapping cannot widen what the agent
576
657
  # may do.
@@ -618,12 +699,14 @@ module Nexo
618
699
  # by `:local`; container tiers keep their own `/workspace` default).
619
700
  def resolve_sandbox(value) = Sandboxes.resolve(value, cwd: @cwd)
620
701
 
621
- def resolve_permissions(value, decision: nil)
702
+ def resolve_permissions(value, decision: nil, decisions: nil)
622
703
  # A user-supplied Permissions sets its own mcp_allow: — leave it untouched.
623
- # Thread a per-run approval decision through a non-mutating copy (Spec 16)
704
+ # Thread the run's approval answers through a non-mutating copy (Spec 16)
624
705
  # so a shared, class-level :approve instance is never clobbered.
625
706
  if value.is_a?(Permissions)
626
- return decision ? value.with_decision(decision) : value
707
+ value = value.with_decision(decision) if decision
708
+ value = value.with_decisions(decisions) if decisions
709
+ return value
627
710
  end
628
711
 
629
712
  # Thread the class-level mcp_allow into each symbol branch (Spec 6) so the
@@ -633,7 +716,7 @@ module Nexo
633
716
  when :read_only then Permissions.new(mode: :read_only, mcp_allow: allow)
634
717
  when :auto then Permissions.new(mode: :auto, allow: %i[read glob write shell fetch search], mcp_allow: allow)
635
718
  when :ask then Permissions.new(mode: :ask, mcp_allow: allow) # pass a Permissions with on_ask for a real gate
636
- when :approve then Permissions.new(mode: :approve, mcp_allow: allow, decision: decision)
719
+ when :approve then Permissions.new(mode: :approve, mcp_allow: allow, decision: decision, decisions: decisions)
637
720
  else raise ConfigurationError, "unknown permissions: #{value.inspect}"
638
721
  end
639
722
  end
@@ -65,7 +65,7 @@ module Nexo
65
65
  private
66
66
 
67
67
  # Lazily loads `async` and its coordination primitives, mirroring the
68
- # soft-dependency precedent in Skills.load! / Loops::AgentSDK: a bare
68
+ # soft-dependency pattern: a bare
69
69
  # `require` (so tests can stub it on the instance) rescuing stdlib `LoadError`
70
70
  # into a MissingDependencyError that names the gem and the exact remedy.
71
71
  def require_async!
@@ -70,6 +70,14 @@ module Nexo
70
70
  # workflow jobs to a dedicated queue.
71
71
  attr_accessor :job_queue
72
72
 
73
+ # What happens when the model calls a tool Nexo did not attach — one a host
74
+ # added to the chat itself, outside the `tools` macro, so no permission gate
75
+ # ever saw it. `false` (default in 0.14) runs it and warns once per tool;
76
+ # `true` refuses it, and the model is told the call did not run. Declare host
77
+ # tools with `tools` on the agent and turn this on. It becomes the default
78
+ # in 1.0.
79
+ attr_accessor :strict_tools
80
+
73
81
  # Seeds the safe, provider-neutral defaults (no model, `:virtual` sandbox,
74
82
  # `:read_only` permissions, `:threaded` concurrency).
75
83
  def initialize
@@ -84,6 +92,7 @@ module Nexo
84
92
  @broadcast_events = false # safe default: opt in to the Turbo mirror
85
93
  @run_store = nil # nil → the automatic choice (ActiveRecord under Rails, else Memory)
86
94
  @job_queue = nil # nil → ActiveJob's default queue
95
+ @strict_tools = false # warn, do not refuse; flips to true in 1.0
87
96
  end
88
97
 
89
98
  private
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Nexo
6
+ # Wraps any tool so every call is authorized through Nexo::Permissions before it
7
+ # runs. A denied call returns `{ error: ... }` (recoverable) and never raises
8
+ # into the loop — the same authorize → act → rescue-`Denied` → `{error:}` shape
9
+ # as Nexo's own sandbox tools. Nexo::ApprovalRequired is NOT rescued: under an
10
+ # `:approve` gate it has to leave the loop so Workflow#run_agent can suspend.
11
+ #
12
+ # This is how a tool the host wrote gets the same gate as Nexo's own: declare it
13
+ # with a capability (`tools ArchiveRun, capability: :write`) and Agent#chat wraps
14
+ # it here. MCP::GatedTool is the same wrapper on the MCP axis.
15
+ #
16
+ # Everything except the execution method is delegated to the wrapped tool, so
17
+ # the chat cannot tell the wrapper apart from the raw tool: it reports the same
18
+ # `name`/`description`/`parameters_schema` and serializes identically.
19
+ #
20
+ # VERIFIED (ruby_llm 2.2.3): `Chat#with_tools` does not type-check — it registers
21
+ # any object answering `qualified_name`/`namespace`/`name`/`deferred?` — and the
22
+ # tool loop invokes `tool.call(**arguments, tool_call:)` with KEYWORDS. So a
23
+ # delegating wrapper is accepted; `method_missing` forwards every reader the
24
+ # chat and the provider renderers ask for.
25
+ class GatedTool
26
+ # Wraps `tool` so every call is authorized for `capability` (one of the
27
+ # Permissions capabilities, e.g. `:write`) through `permissions` first.
28
+ def initialize(tool:, permissions:, capability:)
29
+ @tool = tool
30
+ @permissions = permissions
31
+ @capability = capability
32
+ end
33
+
34
+ # Authorizes the call, then delegates to the wrapped tool. A denial is
35
+ # returned as `{ error: ... }` so the model can recover.
36
+ #
37
+ # Arguments arrive as keywords from the chat loop. A single positional Hash
38
+ # is accepted too, for direct callers. `tool_call:` is the chat's own
39
+ # bookkeeping, not a tool argument, so the gate never sees it.
40
+ def call(args = nil, **kwargs)
41
+ arguments = (args || {}).to_h.merge(kwargs).transform_keys(&:to_sym)
42
+ authorize!(arguments.except(:tool_call))
43
+ @tool.call(**arguments)
44
+ rescue Nexo::Permissions::Denied => e
45
+ {error: e.message}
46
+ end
47
+
48
+ # The wrapped tool's name.
49
+ def name = @tool.name
50
+
51
+ # Routes `#execute` through the same gate, so the wrapper is safe whichever
52
+ # entry point a caller uses.
53
+ def execute(*args, **kwargs)
54
+ call(args.first, **kwargs)
55
+ end
56
+
57
+ # Forward description/parameters_schema/to_h/etc. to the wrapped tool so the
58
+ # chat serializes it exactly like the raw tool — but never `execute` (see
59
+ # above).
60
+ def respond_to_missing?(method_name, include_private = false)
61
+ return true if method_name == :execute
62
+
63
+ @tool.respond_to?(method_name, include_private) || super
64
+ end
65
+
66
+ # Delegates any unknown method to the wrapped tool (description,
67
+ # parameters_schema, to_h, ...), so the wrapper serializes identically. `execute`
68
+ # is handled explicitly above and never falls through here.
69
+ def method_missing(method_name, *args, **kwargs, &block)
70
+ if @tool.respond_to?(method_name)
71
+ @tool.public_send(method_name, *args, **kwargs, &block)
72
+ else
73
+ super
74
+ end
75
+ end
76
+
77
+ private
78
+
79
+ # The gate. The detail handed to `ask_when`/`on_ask` and recorded with an
80
+ # approval is the tool name and its arguments, so a human can tell one call
81
+ # from another.
82
+ def authorize!(arguments)
83
+ @permissions.authorize!(@capability, "#{name} #{JSON.generate(arguments)}")
84
+ end
85
+ end
86
+ end
data/lib/nexo/loop.rb CHANGED
@@ -3,26 +3,24 @@
3
3
  module Nexo
4
4
  # The loop seam: the engine that drives one prompt to completion. Swapping the
5
5
  # loop swaps *how* the agent's turns are run — the plain provider-neutral
6
- # `ruby_llm` tool loop, or an opt-in vendor-tuned backend — by constructor
7
- # injection, with no change to the agent class.
6
+ # `ruby_llm` tool loop, or a backend of your own — by constructor injection,
7
+ # with no change to the agent class.
8
8
  #
9
9
  # A loop implements the contract below. The base class raises so an incomplete
10
10
  # subclass fails loudly. The optional `&on_event` block, when given, is called
11
11
  # with `(type, payload)` as the run progresses (e.g. `:tool_call`,
12
12
  # `:tool_result`, `:done`) — observability only; it never steers the run.
13
13
  #
14
- # See Loops::RubyLLM (default, provider-neutral) and Loops::AgentSDK
15
- # (opt-in, Anthropic-oriented).
14
+ # See Loops::RubyLLM, the default and only backend Nexo ships.
16
15
  class Loop
17
16
  # Runs `prompt` through `agent` and returns the final response. `max_turns`
18
- # is a hint a backend may enforce as a hard cap (AgentSDK) or expose only as
19
- # observability (RubyLLM — see the turn-cap caveat in the README).
17
+ # caps how many tool rounds one prompt may run; Loops::RubyLLM enforces it.
20
18
  #
21
19
  # `chat:` (default `nil`) lets a Nexo::Session inject a hydrated, continuing
22
20
  # chat so the loop runs over the persisted thread. It is part of the base
23
- # contract so every backend accepts it: Loops::RubyLLM uses it; a backend
24
- # that runs its own in-process loop (Loops::AgentSDK) rejects a non-nil chat
25
- # rather than silently dropping the session's memory.
21
+ # contract so every backend accepts it; a backend that cannot continue a
22
+ # chat should reject a non-nil one rather than silently drop the session's
23
+ # memory.
26
24
  def run(agent:, prompt:, max_turns: 25, chat: nil, &on_event)
27
25
  raise NotImplementedError
28
26
  end
@@ -1,53 +1,55 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Nexo
4
- # Namespace for the pluggable loop backends that drive one prompt to
5
- # completion: Loops::RubyLLM (the default, provider-neutral) and
6
- # Loops::AgentSDK (opt-in, Anthropic-oriented). Selected per agent via the
7
- # `loop:` constructor injection; the base contract is Nexo::Loop.
4
+ # Namespace for the loop backends that drive one prompt to completion.
5
+ # Loops::RubyLLM is the default and the only one Nexo ships; a custom backend
6
+ # subclasses Nexo::Loop and is selected per agent via the `loop:` constructor
7
+ # injection.
8
8
  module Loops
9
- # The default, provider-neutral loop. It is the Spec 1 `Agent#prompt` body
10
- # extracted verbatim: build the agent's chat (with its four sandbox-backed
11
- # tools) and let `ruby_llm` run the whole tool loop inside `#ask`. It works
12
- # identically on any `ruby_llm`-supported model — Anthropic, OpenAI, Gemini,
13
- # Ollama/Gemma — because file/shell capability comes entirely from the
14
- # agent's own sandbox-backed tools, not from anything vendor-specific here.
9
+ # The default, provider-neutral loop: build the agent's chat (with its
10
+ # sandbox-backed tools) and let `ruby_llm` run the whole tool loop inside
11
+ # `#ask`. It works identically on any `ruby_llm`-supported model — Anthropic,
12
+ # OpenAI, Gemini, Ollama/Gemma — because file/shell capability comes entirely
13
+ # from the agent's own sandbox-backed tools, not from anything vendor-specific
14
+ # here.
15
15
  #
16
- # Tool-call *observability* (not a hard cap — see the turn-cap caveat in the
17
- # README) is wired through `ruby_llm`'s `before_tool_call`/`after_tool_result`
18
- # callbacks when the installed version exposes them, and is silently omitted
19
- # otherwise so an older/newer `ruby_llm` degrades to no observability rather
20
- # than crashing.
16
+ # Tool activity is reported through `ruby_llm`'s `before_tool_call` /
17
+ # `after_tool_result` callbacks, and the turn cap is `ruby_llm`'s own
18
+ # `with_tool_options(rounds:)`.
21
19
  class RubyLLM < Nexo::Loop
22
20
  # `chat:` lets a Nexo::Session inject the hydrated, continuing chat so the
23
21
  # loop runs over the persisted thread; left nil it builds the agent's own
24
- # fresh chat exactly as before — the default (no-session) path is unchanged.
25
- # `max_turns` is a BUDGET, not a hard stop. ruby_llm runs the whole tool loop
26
- # inside #ask and its callbacks cannot halt it, so this loop cannot cut a run
27
- # short. What it can do is COUNT the tool calls and say so: exceeding the budget
28
- # emits a `:turn_limit_exceeded` event (once) carrying the count and the limit.
22
+ # fresh chat.
29
23
  #
30
- # Previously the parameter was accepted and never read, which made it look like
31
- # a safety bound it has never been. Treat it as telemetry: if you need a hard
32
- # ceiling, bound the work inside your tools, or use Loops::AgentSDK whose engine
33
- # enforces its own max_turns natively.
24
+ # `max_turns` is a HARD CAP on tool rounds: the number of model responses
25
+ # that ask for tools within this one prompt, however many calls each holds.
26
+ # When the cap is reached `ruby_llm` raises `RubyLLM::ToolRoundLimitError`
27
+ # instead of asking the model again. Every tool call that ran has its
28
+ # result, so the conversation stays valid. This loop emits a
29
+ # `:turn_limit_exceeded` event and lets the error propagate — a run that
30
+ # blows its budget fails loudly rather than continuing unbounded. Pass
31
+ # `max_turns: nil` to run uncapped.
34
32
  def run(agent:, prompt:, max_turns: 25, chat: nil, &on_event)
35
33
  chat ||= agent.chat
36
34
 
37
35
  wire_observability(chat, max_turns: max_turns, &on_event)
36
+ chat.with_tool_options(rounds: max_turns) if chat.respond_to?(:with_tool_options)
38
37
 
39
38
  response = chat.ask(prompt)
40
39
  on_event&.call(:done, response)
41
40
  response
41
+ rescue ::RubyLLM::ToolRoundLimitError
42
+ report_turn_limit(chat, max_turns)
43
+ raise
42
44
  end
43
45
 
44
46
  private
45
47
 
46
- # Tool-call OBSERVABILITY only: ruby_llm runs the whole tool loop inside
47
- # #ask, so these callbacks report tool activity but cannot halt the loop.
48
- # BOTH callbacks must be present to wire — confirmed on ruby_llm 1.16.0
49
- # (legacy aliases of #on_tool_call/#on_tool_result); a chat missing either
50
- # degrades to no observability rather than crashing on the one it has.
48
+ # Tool-call OBSERVABILITY: these callbacks report tool activity; the cap
49
+ # itself is `with_tool_options(rounds:)` in #run. BOTH callbacks must be
50
+ # present to wire (verified on ruby_llm 2.2.3, where they are additive); a
51
+ # chat double missing either degrades to no observability rather than
52
+ # crashing on the one it has.
51
53
  #
52
54
  # A continuing Nexo::Session runs the loop repeatedly over the SAME chat, so
53
55
  # the wiring is done once per chat (flagged with an ivar) — otherwise ruby_llm
@@ -77,16 +79,23 @@ module Nexo
77
79
  end
78
80
  end
79
81
 
80
- # Counts one tool call and reports the first time the budget is passed. Reported
81
- # once per prompt, not per call, so a long run does not drown its own event log.
82
+ # Counts one tool call. A round may hold several calls, so the count can pass
83
+ # `max_turns` before the round cap trips; the first time it does, that is
84
+ # reported once per prompt so a long run does not drown its own event log.
82
85
  def count_turn(chat)
83
86
  limit = chat.instance_variable_get(:@nexo_max_turns)
84
87
  turns = chat.instance_variable_get(:@nexo_turns).to_i + 1
85
88
  chat.instance_variable_set(:@nexo_turns, turns)
86
- return unless limit && turns > limit
89
+ report_turn_limit(chat, limit) if limit && turns > limit
90
+ end
91
+
92
+ # Emits `:turn_limit_exceeded` at most once per prompt, carrying the tool-call
93
+ # count so far and the limit.
94
+ def report_turn_limit(chat, limit)
87
95
  return if chat.instance_variable_get(:@nexo_turns_reported)
88
96
 
89
97
  chat.instance_variable_set(:@nexo_turns_reported, true)
98
+ turns = chat.instance_variable_get(:@nexo_turns).to_i
90
99
  chat.instance_variable_get(:@nexo_on_event)&.call(:turn_limit_exceeded, {turns: turns, max_turns: limit})
91
100
  end
92
101
  end