nexo_ai 0.13.0 → 0.15.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,8 @@ 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
+ @context_budget @file_tools
28
29
  ].freeze
29
30
 
30
31
  class << self
@@ -90,6 +91,50 @@ module Nexo
90
91
  value.nil? ? @instructions : (@instructions = value)
91
92
  end
92
93
 
94
+ # Which file tools the agent gets. With no argument it reads the choice
95
+ # (default: Nexo.config.file_tools, which is `:nexo`).
96
+ #
97
+ # * `:nexo` — Nexo's own `ReadFile`, `WriteFile` and `Glob`.
98
+ # * `:core` — `ruby_llm`'s `list_files`, `read_file`, `search_files`,
99
+ # `write_file` and `edit_file`, over the agent's sandbox (see
100
+ # SandboxFileStore). Adds editing part of a file, searching contents, and
101
+ # a read-before-write guard that works on every sandbox.
102
+ #
103
+ # Either way the tools are behind the same permission gate: reading and
104
+ # listing are `:read`, writing and editing are `:write`, and under
105
+ # `:read_only` the writing tools are not attached at all. The two sets use
106
+ # different tool names and return different shapes, so a skill that names
107
+ # `nexo--tools--write_file`, or a host that reads tool events, must be
108
+ # updated when switching. `:core` is planned as the default in 1.0.
109
+ def file_tools(value = nil)
110
+ value.nil? ? (@file_tools || Nexo.config.file_tools) : (@file_tools = value)
111
+ end
112
+
113
+ # Keeps tool results within shares of the model's context window — a
114
+ # pass-through to `ruby_llm`'s `Chat#with_context_budget`. With no argument
115
+ # it reads the declared budget (default `nil`: `ruby_llm`'s own
116
+ # `config.context_budget`, which is off unless you set it).
117
+ #
118
+ # ```ruby
119
+ # class Researcher < Nexo::Agent
120
+ # context_budget per_result: 0.25, per_request: 0.7
121
+ # end
122
+ # ```
123
+ #
124
+ # `per_result:` cuts a single tool result longer than that share and tells
125
+ # the model to ask for less; `per_request:` leaves the oldest tool results
126
+ # out of a request that would exceed that share. Both need the model's
127
+ # context window, which `ruby_llm` knows only for models in its registry —
128
+ # for a local or unregistered model pass `window:` (tokens), or the budget
129
+ # does nothing and `ruby_llm` warns once. This bounds what ANY tool returns,
130
+ # including MCP tools and tools of your own; OutputTruncator still bounds
131
+ # shell output by lines, with or without a known window.
132
+ def context_budget(budget = nil, **shares)
133
+ return @context_budget if budget.nil? && shares.empty?
134
+
135
+ @context_budget = (budget || {}).to_h.merge(shares)
136
+ end
137
+
93
138
  # Declares the skills attached to this agent. With no args it returns the
94
139
  # configured list (default `[]`); with args it ACCUMULATES the names
95
140
  # (deduped), so multiple `skills` lines add up instead of the last one
@@ -163,6 +208,38 @@ module Nexo
163
208
  names.empty? ? (@produces || []) : (@produces = ((@produces || []) + names).uniq)
164
209
  end
165
210
 
211
+ # Declares tools of your own for this agent. Accumulating, like `skills`.
212
+ # With no arguments it reads the declarations (default `[]`).
213
+ #
214
+ # ```ruby
215
+ # class Archivist < Nexo::Agent
216
+ # tools Today, SumPayments # pure helpers: no gate
217
+ # tools ArchiveRun, capability: :write # gated like Nexo's write tool
218
+ # tools ->(agent) { Lookup.new(root: agent.cwd) }
219
+ # end
220
+ # ```
221
+ #
222
+ # Each entry is a `RubyLLM::Tool` class (instantiated with no arguments), an
223
+ # instance, or a lambda taking the agent and returning one — or an Array of
224
+ # them, for an agent whose tools depend on how it was built.
225
+ #
226
+ # `capability:` names what the tool does in Nexo's terms — `:read`, `:write`,
227
+ # `:shell`, `:fetch`, `:search`. The tool is then wrapped in Nexo::GatedTool:
228
+ # the agent's Permissions decide every call exactly as they do for Nexo's
229
+ # own tools (denied under `:read_only`, prompted under `:ask`, suspended
230
+ # under `:approve`), and it is left out of the schema when it could never be
231
+ # authorized. Without `capability:` the tool runs ungated — the right choice
232
+ # only for a tool with no side effects.
233
+ #
234
+ # Declare tools here instead of overriding `#chat` to call `with_tools`: a
235
+ # tool added that way is unknown to Nexo, which warns about it, and refuses
236
+ # it under `Nexo.config.strict_tools`.
237
+ def tools(*list, capability: nil)
238
+ return @tools || [] if list.empty?
239
+
240
+ @tools = (@tools || []) + list.flatten.map { |tool| {tool: tool, capability: capability} }
241
+ end
242
+
166
243
  # Declares an MCP server for this agent (Spec 6). Accumulating: multiple
167
244
  # `mcp` lines are collected. With no args (`name` nil and `opts` empty) it
168
245
  # reads the list (default `[]`); otherwise it appends the friendly,
@@ -226,14 +303,21 @@ module Nexo
226
303
  # Symbol shorthands (:virtual/:local, :read_only/:auto/:ask/:approve) and
227
304
  # pre-built Sandbox/Permissions instances are both accepted. `loop:` injects
228
305
  # the engine that drives a prompt — the provider-neutral Loops::RubyLLM by
229
- # default, or an opt-in backend like Loops::AgentSDK.
306
+ # default, or a backend of your own.
307
+ #
308
+ # `decisions:` (0.14, default `nil`) are the per-call approval answers for an
309
+ # `:approve` gate — a Hash of Permissions::approval_key → `true`/`false`. A
310
+ # call found there runs or is denied; any other call raises
311
+ # Nexo::ApprovalRequired. They only supply *answers* to an already-`:approve`
312
+ # gate — they never widen capability. Workflow#run_agent passes the approvals
313
+ # recorded on the run. `decision:` is the deprecated global form (one
314
+ # `{approved:}` answer for every gated call).
230
315
  #
231
- # `decision:` (Spec 16, default `nil`) is a per-run approval answer
232
- # (`{approved: true|false}`) threaded into the resolved Permissions so an
233
- # `:approve` gate allows/denies instead of raising Nexo::ApprovalRequired.
234
- # It only supplies the *answer* to an already-`:approve` gate — it never
235
- # widens capability. Workflow#run_agent passes it on the resume pass.
236
- def initialize(cwd: Dir.pwd, model: nil, sandbox: nil, permissions: nil, decision: nil, loop: Loops::RubyLLM.new)
316
+ # `mcp_owner:` (0.15) is whose OAuth credentials this agent's `oauth:` MCP
317
+ # servers use — a user record, or a stable String/Integer id.
318
+ def initialize(cwd: Dir.pwd, model: nil, sandbox: nil, permissions: nil, decision: nil, decisions: nil,
319
+ mcp_owner: nil, loop: Loops::RubyLLM.new)
320
+ @mcp_owner = mcp_owner
237
321
  @cwd = cwd
238
322
  @model = model || self.class.model || Nexo.config.default_model
239
323
  if @model.nil?
@@ -253,7 +337,8 @@ module Nexo
253
337
  # sharing the run's sandbox) is BORROWED — closing it would strand the owner.
254
338
  @owns_sandbox = sandbox.nil?
255
339
  @sandbox = resolve_sandbox(sandbox || self.class.sandbox)
256
- @permissions = resolve_permissions(permissions || self.class.permissions, decision: decision)
340
+ @permissions = resolve_permissions(permissions || self.class.permissions, decision: decision,
341
+ decisions: decisions)
257
342
  @instructions = self.class.instructions
258
343
  @loop = loop
259
344
  end
@@ -278,29 +363,18 @@ module Nexo
278
363
  c = base || RubyLLM.chat(**chat_model_options)
279
364
  c = apply_instructions(c)
280
365
 
281
- # One ReadTracker per chat, shared by ReadFile (records) and WriteFile
282
- # (enforces the read-before-write + stale guard) — R4.
283
- tracker = ReadTracker.new
284
- # A sandbox tool is attached only when the agent could actually use it, on
285
- # BOTH axes: the sandbox has to support the capability (R2 — a :virtual
286
- # sandbox has no shell) and the gate must not deny it statically (a
287
- # :read_only agent can never be authorized for :write or :shell). Otherwise
288
- # a guaranteed failure sits in the tool schema on every turn and models do
289
- # try it. This is the same attach-time gating apply_fetch/apply_search
290
- # already apply; #authorize! stays the actual boundary either way.
291
- tools = [Tools::ReadFile.new(sandbox: @sandbox, permissions: @permissions, tracker: tracker)]
292
- unless @permissions.never_allows?(:write)
293
- tools << Tools::WriteFile.new(sandbox: @sandbox, permissions: @permissions, tracker: tracker)
294
- end
295
- tools << Tools::Glob.new(sandbox: @sandbox, permissions: @permissions)
366
+ tools = file_tool_set
296
367
  if @sandbox.supports?(:shell) && !@permissions.never_allows?(:shell)
297
368
  tools << Tools::Shell.new(sandbox: @sandbox, permissions: @permissions)
298
369
  end
299
370
  c.with_tools(*tools)
371
+ apply_host_tools(c)
300
372
  apply_mcp(c)
301
373
  apply_fetch(c)
302
374
  apply_search(c)
303
- apply_tool_concurrency(c)
375
+ apply_tool_options(c)
376
+ apply_context_budget(c)
377
+ apply_tool_backstop(c)
304
378
  c
305
379
  end
306
380
 
@@ -390,6 +464,26 @@ module Nexo
390
464
 
391
465
  public
392
466
 
467
+ # The `ruby_llm` MCP server declared as `name` with the `mcp` macro, built
468
+ # with this agent's `mcp_owner`. For an `oauth:` server this is where a host
469
+ # drives the authorization (0.15):
470
+ #
471
+ # ```ruby
472
+ # agent = Assistant.new(mcp_owner: current_user)
473
+ # linear = agent.mcp_server(:linear)
474
+ # redirect_to linear.authorization_url(redirect_uri: callback_url) unless linear.authorized?
475
+ # # ...and in the callback action:
476
+ # agent.mcp_server(:linear).authorize(params)
477
+ # ```
478
+ #
479
+ # `#deauthorize` forgets the owner's credentials. Raises ConfigurationError
480
+ # for a name that was never declared.
481
+ def mcp_server(name)
482
+ index = self.class.mcp.index { |cfg| cfg[:name].to_s == name.to_s } or
483
+ raise ConfigurationError, "#{self.class} declares no mcp :#{name}"
484
+ mcp_clients[index]
485
+ end
486
+
393
487
  # Releases any MCP server connections held by this agent instance. Clients are
394
488
  # memoized on the instance and reused across prompts (Spec 6 lifecycle default),
395
489
  # so a long-lived agent holding stdio/SSE servers should call `#close` when
@@ -504,27 +598,162 @@ module Nexo
504
598
  def apply_mcp(chat)
505
599
  return if self.class.mcp.empty?
506
600
 
507
- @mcp_clients ||= self.class.mcp.map { |cfg| Nexo::MCP.build(**cfg) }
508
- gated = @mcp_clients.flat_map(&:tools).select { |tool| model_callable?(tool) }.map do |tool|
601
+ require_mcp_authorization!
602
+ gated = mcp_clients.flat_map(&:tools).select { |tool| attachable_mcp_tool?(tool) }.map do |tool|
509
603
  wrap_mcp_tool(Nexo::MCP::GatedTool.new(tool: tool, permissions: @permissions))
510
604
  end
511
605
  chat.with_tools(*gated) unless gated.empty?
512
606
  end
513
607
 
608
+ # The agent's MCP servers, built once from the `mcp` declarations (with this
609
+ # agent's `mcp_owner`) and reused until #close.
610
+ def mcp_clients
611
+ @mcp_clients ||= self.class.mcp.map { |cfg| Nexo::MCP.build(**cfg, owner: @mcp_owner) }
612
+ end
613
+
614
+ # Raises Nexo::AuthorizationRequired for the first server a person still has
615
+ # to authorize. Checked before any tool is listed, so the host gets one clear
616
+ # error to act on in place of a 401 from somewhere inside the first request.
617
+ # Reads the credential store only — no network.
618
+ def require_mcp_authorization!
619
+ self.class.mcp.zip(mcp_clients).each do |cfg, client|
620
+ next unless Nexo::MCP.user_authorized?(cfg)
621
+
622
+ raise Nexo::AuthorizationRequired.new(cfg[:name]) unless client.authorized?
623
+ end
624
+ end
625
+
626
+ # Whether an MCP tool is worth attaching: the model may call it, and the gate
627
+ # could authorize it. A tool `:read_only` can never allow is left out of the
628
+ # schema, as a sandbox tool is — it would only cost tokens and a wasted call.
629
+ def attachable_mcp_tool?(tool)
630
+ model_callable?(tool) && !@permissions.never_allows_mcp?(tool.name)
631
+ end
632
+
514
633
  # Whether the model may call this MCP tool. Only MCP App tools restrict it.
515
634
  def model_callable?(tool)
516
635
  !tool.respond_to?(:visibility) || tool.visibility.include?(:model)
517
636
  end
518
637
 
519
- # Applies Nexo.config.tool_concurrency to the chat through
520
- # `with_tool_options(concurrency:)` (ruby_llm 2.x moved tool execution settings
521
- # off `with_tools`). `nil` leaves RubyLLM's own setting alone.
522
- def apply_tool_concurrency(chat)
523
- mode = Nexo.config.tool_concurrency
524
- return if mode.nil?
638
+ # The agent's file tools, per the `file_tools` declaration.
639
+ #
640
+ # A tool is attached only when the agent could actually use it: the gate must
641
+ # not deny it statically (a :read_only agent can never be authorized for
642
+ # :write), otherwise a guaranteed failure sits in the tool schema on every
643
+ # turn and models do try it. #authorize! stays the actual boundary either way.
644
+ def file_tool_set
645
+ case self.class.file_tools
646
+ when :nexo then nexo_file_tools
647
+ when :core then core_file_tools
648
+ else raise ConfigurationError, "unknown file_tools #{self.class.file_tools.inspect} (use :nexo or :core)"
649
+ end
650
+ end
651
+
652
+ # Nexo's own file tools. One ReadTracker per chat, shared by ReadFile (records)
653
+ # and WriteFile (enforces the read-before-write + stale guard).
654
+ def nexo_file_tools
655
+ tracker = ReadTracker.new
656
+ tools = [Tools::ReadFile.new(sandbox: @sandbox, permissions: @permissions, tracker: tracker)]
657
+ unless @permissions.never_allows?(:write)
658
+ tools << Tools::WriteFile.new(sandbox: @sandbox, permissions: @permissions, tracker: tracker)
659
+ end
660
+ tools << Tools::Glob.new(sandbox: @sandbox, permissions: @permissions)
661
+ end
662
+
663
+ # `ruby_llm`'s file tools over one SandboxFileStore per chat, each behind
664
+ # Nexo::GatedTool. They are built here and attached with `with_tools` — NOT
665
+ # with `chat.with_file_store`, which would attach them with no place for the
666
+ # gate. The gate is told the path the call acts on, like Nexo's own tools.
667
+ #
668
+ # VERIFIED (ruby_llm 2.2.3): `FileStore::Tools.classes(names)` returns the
669
+ # tool classes for `:read` (list, read, search), `:write` and `:edit`, each
670
+ # built with `store:` (a callable). These are internal to `ruby_llm`; the
671
+ # real-loop tests are what catches a change.
672
+ def core_file_tools
673
+ store = SandboxFileStore.new(@sandbox)
674
+ groups = {read: :read}
675
+ groups = groups.merge(write: :write, edit: :write) unless @permissions.never_allows?(:write)
676
+ groups.flat_map do |group, capability|
677
+ ::RubyLLM::FileStore::Tools.classes([group]).map do |tool|
678
+ Nexo::GatedTool.new(tool: tool.new(store: -> { store }), permissions: @permissions,
679
+ capability: capability, detail: ->(arguments) { arguments[:path] })
680
+ end
681
+ end
682
+ end
683
+
684
+ # Attaches the tools declared with the `tools` macro. One declared with a
685
+ # `capability:` is wrapped in Nexo::GatedTool, and skipped altogether when the
686
+ # gate could never authorize it.
687
+ def apply_host_tools(chat)
688
+ built = self.class.tools.flat_map do |entry|
689
+ capability = entry[:capability]
690
+ next [] if capability && @permissions.never_allows?(capability)
691
+
692
+ build_host_tools(entry[:tool]).map do |tool|
693
+ capability ? Nexo::GatedTool.new(tool: tool, permissions: @permissions, capability: capability) : tool
694
+ end
695
+ end
696
+ chat.with_tools(*built) unless built.empty?
697
+ end
698
+
699
+ # A declared tool is a class, an instance, or a lambda taking the agent. The
700
+ # lambda may return several tools, and may return classes.
701
+ def build_host_tools(tool)
702
+ case tool
703
+ when Class then [tool.new]
704
+ when Proc then Array(tool.call(self)).flat_map { |built| build_host_tools(built) }
705
+ else [tool]
706
+ end
707
+ end
708
+
709
+ # The fail-closed backstop behind the gate. Every tool Nexo attached is on the
710
+ # chat by now; one `around_tool_call` block lets those run and catches any
711
+ # other — a tool the host added to the chat itself, which no gate ever saw.
712
+ # Under `Nexo.config.strict_tools` such a call is skipped (`ruby_llm` then
713
+ # tells the model the call did not run); otherwise it runs with a one-time
714
+ # warning.
715
+ #
716
+ # This is a backstop, not the gate: a skipped call can only produce
717
+ # `ruby_llm`'s fixed "did not run" text, so the gate that explains itself
718
+ # stays in the tools (VERIFIED, ruby_llm 2.2.3).
719
+ #
720
+ # The block is registered once per chat and reads the known names from the
721
+ # chat, so a Session that rebuilds over the same chat does not stack blocks.
722
+ # It runs on the tool's own thread under tool concurrency; the name set is
723
+ # frozen and only read.
724
+ def apply_tool_backstop(chat)
725
+ return unless chat.respond_to?(:around_tool_call) && chat.respond_to?(:tools)
726
+
727
+ chat.instance_variable_set(:@nexo_known_tools, chat.tools.keys.to_set(&:to_s).freeze)
728
+ return if chat.instance_variable_get(:@nexo_backstop)
729
+
730
+ chat.instance_variable_set(:@nexo_backstop, true)
731
+ chat.around_tool_call do |tool_call, &run|
732
+ name = tool_call.name.to_s
733
+ if chat.instance_variable_get(:@nexo_known_tools).include?(name)
734
+ run.call
735
+ elsif !Nexo.config.strict_tools
736
+ Nexo.warn_undeclared_tool(name, self.class)
737
+ run.call
738
+ end
739
+ end
740
+ end
741
+
742
+ # Applies the harness-wide tool execution settings through
743
+ # `with_tool_options` (ruby_llm 2.x moved them off `with_tools`):
744
+ # Nexo.config.tool_concurrency, where `nil` leaves RubyLLM's own setting
745
+ # alone, and Nexo.config.tool_calls_per_round, where `nil` sets no cap.
746
+ def apply_tool_options(chat)
525
747
  return unless chat.respond_to?(:with_tool_options)
526
748
 
527
- chat.with_tool_options(concurrency: mode)
749
+ options = {concurrency: Nexo.config.tool_concurrency, calls: Nexo.config.tool_calls_per_round}.compact
750
+ chat.with_tool_options(**options) unless options.empty?
751
+ end
752
+
753
+ # Applies the agent's `context_budget` declaration, when there is one.
754
+ def apply_context_budget(chat)
755
+ budget = self.class.context_budget
756
+ chat.with_context_budget(budget) if budget && chat.respond_to?(:with_context_budget)
528
757
  end
529
758
 
530
759
  # Hook: called once per MCP tool, AFTER it is wrapped in a permission-gating
@@ -596,12 +825,14 @@ module Nexo
596
825
  # by `:local`; container tiers keep their own `/workspace` default).
597
826
  def resolve_sandbox(value) = Sandboxes.resolve(value, cwd: @cwd)
598
827
 
599
- def resolve_permissions(value, decision: nil)
828
+ def resolve_permissions(value, decision: nil, decisions: nil)
600
829
  # A user-supplied Permissions sets its own mcp_allow: — leave it untouched.
601
- # Thread a per-run approval decision through a non-mutating copy (Spec 16)
830
+ # Thread the run's approval answers through a non-mutating copy (Spec 16)
602
831
  # so a shared, class-level :approve instance is never clobbered.
603
832
  if value.is_a?(Permissions)
604
- return decision ? value.with_decision(decision) : value
833
+ value = value.with_decision(decision) if decision
834
+ value = value.with_decisions(decisions) if decisions
835
+ return value
605
836
  end
606
837
 
607
838
  # Thread the class-level mcp_allow into each symbol branch (Spec 6) so the
@@ -611,7 +842,7 @@ module Nexo
611
842
  when :read_only then Permissions.new(mode: :read_only, mcp_allow: allow)
612
843
  when :auto then Permissions.new(mode: :auto, allow: %i[read glob write shell fetch search], mcp_allow: allow)
613
844
  when :ask then Permissions.new(mode: :ask, mcp_allow: allow) # pass a Permissions with on_ask for a real gate
614
- when :approve then Permissions.new(mode: :approve, mcp_allow: allow, decision: decision)
845
+ when :approve then Permissions.new(mode: :approve, mcp_allow: allow, decision: decision, decisions: decisions)
615
846
  else raise ConfigurationError, "unknown permissions: #{value.inspect}"
616
847
  end
617
848
  end
@@ -33,6 +33,15 @@ module Nexo
33
33
  # Distinct from #concurrency, which governs how Nexo itself runs blocking work.
34
34
  attr_accessor :tool_concurrency
35
35
 
36
+ # The most tool calls ONE model response may run, default `20`. A model can
37
+ # ask for any number of calls in a single response, and `max_turns` counts
38
+ # responses, not calls — so without this a single round is unbounded. Calls
39
+ # past the limit are answered with an error straight away and never run; the
40
+ # model sees that and can ask again. `nil` removes the limit. Must be 2 or
41
+ # more (to `ruby_llm`, `1` means "ask the provider for one call at a time").
42
+ # Passed to `ruby_llm` as `with_tool_options(calls:)`.
43
+ attr_accessor :tool_calls_per_round
44
+
36
45
  # Max in-flight tasks for Nexo.concurrent fan-out (Spec 5), default `8`.
37
46
  # The single most important knob for staying under provider rate limits.
38
47
  attr_accessor :max_in_flight
@@ -70,6 +79,19 @@ module Nexo
70
79
  # workflow jobs to a dedicated queue.
71
80
  attr_accessor :job_queue
72
81
 
82
+ # The file tools an agent gets when it does not say (see the `file_tools`
83
+ # macro): `:nexo` (default) for Nexo's own three, `:core` for `ruby_llm`'s five
84
+ # over the agent's sandbox. `:core` becomes the default in 1.0.
85
+ attr_accessor :file_tools
86
+
87
+ # What happens when the model calls a tool Nexo did not attach — one a host
88
+ # added to the chat itself, outside the `tools` macro, so no permission gate
89
+ # ever saw it. `false` (default in 0.14) runs it and warns once per tool;
90
+ # `true` refuses it, and the model is told the call did not run. Declare host
91
+ # tools with `tools` on the agent and turn this on. It becomes the default
92
+ # in 1.0.
93
+ attr_accessor :strict_tools
94
+
73
95
  # Seeds the safe, provider-neutral defaults (no model, `:virtual` sandbox,
74
96
  # `:read_only` permissions, `:threaded` concurrency).
75
97
  def initialize
@@ -79,11 +101,14 @@ module Nexo
79
101
  @skills_path = default_skills_path
80
102
  @concurrency = :threaded # async is opt-in; :threaded stays the default
81
103
  @max_in_flight = 8
104
+ @tool_calls_per_round = 20 # with max_turns 25: at most 500 tool calls a prompt
82
105
  @buffer_workflow_events = false
83
106
  @session_chat_model = "Chat" # ruby_llm's own default acts_as_chat host
84
107
  @broadcast_events = false # safe default: opt in to the Turbo mirror
85
108
  @run_store = nil # nil → the automatic choice (ActiveRecord under Rails, else Memory)
86
109
  @job_queue = nil # nil → ActiveJob's default queue
110
+ @file_tools = :nexo # ruby_llm's own (:core) are opt-in until 1.0
111
+ @strict_tools = false # warn, do not refuse; flips to true in 1.0
87
112
  end
88
113
 
89
114
  private
@@ -0,0 +1,93 @@
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
+ #
29
+ # `detail:` is an optional `->(arguments)` returning what the gate is told the
30
+ # call acts on — a path, say. Without it, or when it returns `nil`, the detail
31
+ # is the tool name and its arguments as JSON, so two different calls are never
32
+ # mistaken for one when an approval is recorded.
33
+ def initialize(tool:, permissions:, capability:, detail: nil)
34
+ @tool = tool
35
+ @permissions = permissions
36
+ @capability = capability
37
+ @detail = detail
38
+ end
39
+
40
+ # Authorizes the call, then delegates to the wrapped tool. A denial is
41
+ # returned as `{ error: ... }` so the model can recover.
42
+ #
43
+ # Arguments arrive as keywords from the chat loop. A single positional Hash
44
+ # is accepted too, for direct callers. `tool_call:` is the chat's own
45
+ # bookkeeping, not a tool argument, so the gate never sees it.
46
+ def call(args = nil, **kwargs)
47
+ arguments = (args || {}).to_h.merge(kwargs).transform_keys(&:to_sym)
48
+ authorize!(arguments.except(:tool_call))
49
+ @tool.call(**arguments)
50
+ rescue Nexo::Permissions::Denied => e
51
+ {error: e.message}
52
+ end
53
+
54
+ # The wrapped tool's name.
55
+ def name = @tool.name
56
+
57
+ # Routes `#execute` through the same gate, so the wrapper is safe whichever
58
+ # entry point a caller uses.
59
+ def execute(*args, **kwargs)
60
+ call(args.first, **kwargs)
61
+ end
62
+
63
+ # Forward description/parameters_schema/to_h/etc. to the wrapped tool so the
64
+ # chat serializes it exactly like the raw tool — but never `execute` (see
65
+ # above).
66
+ def respond_to_missing?(method_name, include_private = false)
67
+ return true if method_name == :execute
68
+
69
+ @tool.respond_to?(method_name, include_private) || super
70
+ end
71
+
72
+ # Delegates any unknown method to the wrapped tool (description,
73
+ # parameters_schema, to_h, ...), so the wrapper serializes identically. `execute`
74
+ # is handled explicitly above and never falls through here.
75
+ def method_missing(method_name, *args, **kwargs, &block)
76
+ if @tool.respond_to?(method_name)
77
+ @tool.public_send(method_name, *args, **kwargs, &block)
78
+ else
79
+ super
80
+ end
81
+ end
82
+
83
+ private
84
+
85
+ # The gate. The detail handed to `ask_when`/`on_ask` and recorded with an
86
+ # approval is the tool name and its arguments, so a human can tell one call
87
+ # from another.
88
+ def authorize!(arguments)
89
+ detail = @detail&.call(arguments) || "#{name} #{JSON.generate(arguments)}"
90
+ @permissions.authorize!(@capability, detail)
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,86 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "digest"
4
+ require "fileutils"
5
+ require "json"
6
+
7
+ module Nexo
8
+ module MCP
9
+ # Keeps the OAuth credentials of MCP servers on disk, so a host outside Rails
10
+ # — a CLI, a script, a daemon — stays authorized across restarts. `ruby_llm`
11
+ # keeps them in memory by default and in an encrypted table under Rails; this
12
+ # is the third option, in the same spirit as RunStore::Disk.
13
+ #
14
+ # ```ruby
15
+ # RubyLLM.configure do |config|
16
+ # config.mcp_credential_store = Nexo::MCP::CredentialStore.new(dir: "~/.local/state/my-app/mcp")
17
+ # end
18
+ # ```
19
+ #
20
+ # It answers the store contract `ruby_llm` documents: `read(key)`,
21
+ # `write(key, data, owner:)`, `delete(key)` and `synchronize(key)`.
22
+ #
23
+ # ⚠️ SECURITY: the files hold live access and refresh tokens, in plain JSON.
24
+ # They are NOT encrypted. The directory is created `0700` and every file
25
+ # `0600`, so they are readable by your user and nobody else — the same
26
+ # protection an SSH key or a `gh` token has, and no more. Do not point this at
27
+ # a shared or synced directory, and prefer the encrypted Rails table when
28
+ # ActiveRecord is available. File names are a digest of the key, so the
29
+ # directory listing reveals neither owners nor servers.
30
+ class CredentialStore
31
+ # The directory the credentials live in (expanded).
32
+ attr_reader :dir
33
+
34
+ # Roots the store at `dir`, creating it `0700` if needed.
35
+ def initialize(dir:)
36
+ @dir = File.expand_path(dir)
37
+ FileUtils.mkdir_p(@dir, mode: 0o700)
38
+ end
39
+
40
+ # The credentials stored under `key` as a Hash, or `nil`. A file that is
41
+ # missing or unreadable as JSON reads as `nil`: the server is then simply
42
+ # not authorized, which is the safe answer.
43
+ def read(key)
44
+ JSON.parse(File.read(path(key)))
45
+ rescue Errno::ENOENT, JSON::ParserError
46
+ nil
47
+ end
48
+
49
+ # Stores `data` under `key`. Written to a temporary file and renamed, so a
50
+ # reader never sees half a file and a crash never leaves one. `owner:` is
51
+ # part of the contract and already part of the key.
52
+ def write(key, data, **)
53
+ target = path(key)
54
+ temporary = "#{target}.#{Process.pid}.#{Thread.current.object_id}.tmp"
55
+ File.open(temporary, File::WRONLY | File::CREAT | File::TRUNC, 0o600) { |file| file.write(JSON.generate(data)) }
56
+ File.rename(temporary, target)
57
+ data
58
+ ensure
59
+ File.delete(temporary) if temporary && File.exist?(temporary)
60
+ end
61
+
62
+ # Forgets the credentials stored under `key`.
63
+ def delete(key)
64
+ File.delete(path(key))
65
+ rescue Errno::ENOENT
66
+ nil
67
+ end
68
+
69
+ # Runs the block while no other process holds `key`, so two processes
70
+ # sharing the directory never refresh the same token at once.
71
+ def synchronize(key)
72
+ File.open("#{path(key)}.lock", File::RDWR | File::CREAT, 0o600) do |lock|
73
+ lock.flock(File::LOCK_EX)
74
+ yield
75
+ end
76
+ end
77
+
78
+ private
79
+
80
+ # The file for `key`: a digest, so a key containing a URL is a safe name.
81
+ def path(key)
82
+ File.join(@dir, "#{Digest::SHA256.hexdigest(key.to_s)}.json")
83
+ end
84
+ end
85
+ end
86
+ end