nexo_ai 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. checksums.yaml +4 -4
  2. data/.rdoc_options +5 -0
  3. data/CHANGELOG.md +95 -0
  4. data/README.md +13 -14
  5. data/Rakefile +5 -0
  6. data/docs/concurrency.md +1 -2
  7. data/docs/durable-workflows.md +5 -3
  8. data/docs/getting-started.md +1 -1
  9. data/docs/loops.md +62 -89
  10. data/docs/mcp.md +57 -51
  11. data/docs/rails.md +1 -1
  12. data/docs/sessions.md +7 -3
  13. data/docs/skills.md +20 -11
  14. data/docs/workflows.md +2 -2
  15. data/examples/mcp_filesystem.rb +1 -1
  16. data/lib/generators/nexo/artifacts/artifacts_generator.rb +9 -7
  17. data/lib/generators/nexo/artifacts/templates/add_artifacts_to_nexo_workflow_runs.rb +1 -1
  18. data/lib/generators/nexo/install/install_generator.rb +7 -5
  19. data/lib/generators/nexo/skill/skill_generator.rb +10 -8
  20. data/lib/generators/nexo/state/state_generator.rb +9 -7
  21. data/lib/generators/nexo/state/templates/add_state_to_nexo_workflow_runs.rb +1 -1
  22. data/lib/generators/nexo/workflows/templates/create_nexo_workflow_runs.rb +3 -3
  23. data/lib/generators/nexo/workflows/workflows_generator.rb +7 -5
  24. data/lib/nexo/agent.rb +159 -169
  25. data/lib/nexo/concurrent.rb +18 -16
  26. data/lib/nexo/configuration.rb +21 -21
  27. data/lib/nexo/engine.rb +1 -1
  28. data/lib/nexo/loop.rb +12 -14
  29. data/lib/nexo/loops/ruby_llm.rb +43 -34
  30. data/lib/nexo/mcp/gated_tool.rb +31 -27
  31. data/lib/nexo/mcp.rb +73 -68
  32. data/lib/nexo/output_truncator.rb +9 -9
  33. data/lib/nexo/permissions.rb +44 -46
  34. data/lib/nexo/read_tracker.rb +4 -4
  35. data/lib/nexo/run_store.rb +30 -28
  36. data/lib/nexo/sandbox.rb +29 -27
  37. data/lib/nexo/sandboxes/container.rb +75 -75
  38. data/lib/nexo/sandboxes/local.rb +15 -15
  39. data/lib/nexo/sandboxes/remote.rb +25 -23
  40. data/lib/nexo/sandboxes/virtual.rb +2 -2
  41. data/lib/nexo/sandboxes.rb +9 -9
  42. data/lib/nexo/session.rb +31 -29
  43. data/lib/nexo/skills/skill.rb +89 -0
  44. data/lib/nexo/skills.rb +33 -58
  45. data/lib/nexo/tools/fetch.rb +21 -21
  46. data/lib/nexo/tools/glob.rb +6 -6
  47. data/lib/nexo/tools/read_file.rb +8 -8
  48. data/lib/nexo/tools/shell.rb +7 -7
  49. data/lib/nexo/tools/web_search.rb +16 -16
  50. data/lib/nexo/tools/write_file.rb +11 -11
  51. data/lib/nexo/turbo_broadcaster.rb +1 -1
  52. data/lib/nexo/version.rb +2 -2
  53. data/lib/nexo/workflow.rb +207 -193
  54. data/lib/nexo/workflow_job.rb +6 -6
  55. data/lib/nexo/workflow_run.rb +10 -10
  56. data/lib/nexo.rb +28 -26
  57. data/sig/nexo/agent.rbs +1 -1
  58. metadata +7 -34
  59. data/lib/nexo/loops/agent_sdk.rb +0 -68
data/lib/nexo/agent.rb CHANGED
@@ -3,19 +3,21 @@
3
3
  module Nexo
4
4
  # The DSL that composes a model, a sandbox, permissions, and instructions into
5
5
  # a working tool-using agent. Subclass it and declare the pieces with class
6
- # macros, then call +#prompt+:
6
+ # macros, then call `#prompt`:
7
7
  #
8
- # class CodeReviewer < Nexo::Agent
9
- # model ENV.fetch("NEXO_MODEL")
10
- # sandbox :local
11
- # permissions :read_only
12
- # instructions "You are a careful code reviewer."
13
- # end
8
+ # ```ruby
9
+ # class CodeReviewer < Nexo::Agent
10
+ # model ENV.fetch("NEXO_MODEL")
11
+ # sandbox :local
12
+ # permissions :read_only
13
+ # instructions "You are a careful code reviewer."
14
+ # end
14
15
  #
15
- # CodeReviewer.new(cwd: "/path/to/repo").prompt("Review the auth module")
16
+ # CodeReviewer.new(cwd: "/path/to/repo").prompt("Review the auth module")
17
+ # ```
16
18
  #
17
19
  # No sandbox, permission, or tool object is instantiated by hand. Defaults are
18
- # safe: +:virtual+ sandbox + +:read_only+ permissions unless overridden.
20
+ # safe: `:virtual` sandbox + `:read_only` permissions unless overridden.
19
21
  class Agent
20
22
  # The class-level ivars every macro reads/writes. Copied to a subclass in
21
23
  # .inherited so `class Child < ConfiguredAgent; end` keeps the parent's
@@ -27,7 +29,7 @@ module Nexo
27
29
 
28
30
  class << self
29
31
  # Carries the parent's macro configuration onto a subclass. Arrays/Hashes are
30
- # duped so a subclass extending an accumulating macro (e.g. a second +mcp+
32
+ # duped so a subclass extending an accumulating macro (e.g. a second `mcp`
31
33
  # line) never mutates the parent's collection; scalars and shared config
32
34
  # instances (a class-level Permissions) are copied by reference.
33
35
  def inherited(subclass)
@@ -42,24 +44,24 @@ module Nexo
42
44
  end
43
45
 
44
46
  # Each macro is a reader with no argument and a writer with one. Unset
45
- # +sandbox+/+permissions+ fall back to the harness-wide config defaults.
47
+ # `sandbox`/`permissions` fall back to the harness-wide config defaults.
46
48
  def model(value = nil)
47
49
  value.nil? ? @model : (@model = value)
48
50
  end
49
51
 
50
52
  # Opt out of ruby_llm's models.json registry validation for this agent so
51
53
  # it can run unregistered models (Ollama tags, self-hosted, brand-new
52
- # releases). Boolean opt-in: because +nil?+ still distinguishes read from
53
- # write, +assume_model_exists false+ is an explicit write (sets +false+),
54
- # not a read. Unset reads as +false+, keeping registry validation on.
54
+ # releases). Boolean opt-in: because `nil?` still distinguishes read from
55
+ # write, `assume_model_exists false` is an explicit write (sets `false`),
56
+ # not a read. Unset reads as `false`, keeping registry validation on.
55
57
  def assume_model_exists(value = nil)
56
58
  value.nil? ? (@assume_model_exists || false) : (@assume_model_exists = value)
57
59
  end
58
60
 
59
- # The provider symbol/string (e.g. +:ollama+) passed straight through to
60
- # +RubyLLM.chat+. Required whenever +assume_model_exists+ is set, since
61
+ # The provider symbol/string (e.g. `:ollama`) passed straight through to
62
+ # `RubyLLM.chat`. Required whenever `assume_model_exists` is set, since
61
63
  # ruby_llm cannot infer a provider once the registry lookup is skipped.
62
- # Unset resolves to +nil+.
64
+ # Unset resolves to `nil`.
63
65
  def provider(value = nil)
64
66
  value.nil? ? @provider : (@provider = value)
65
67
  end
@@ -67,8 +69,8 @@ module Nexo
67
69
  # The sandbox macro. With no argument it reads the configured value
68
70
  # (falling back to the harness-wide default). With a bare value it stores a
69
71
  # symbol/instance as before; with keywords it stores an options Hash
70
- # (+{ type: value, **opts }+) resolved by Nexo::Sandboxes.resolve — e.g.
71
- # +sandbox :docker, image: "node:22-slim", binds: {...}+.
72
+ # (`{ type: value, **opts }`) resolved by Nexo::Sandboxes.resolve — e.g.
73
+ # `sandbox :docker, image: "node:22-slim", binds: {...}`.
72
74
  def sandbox(value = nil, **opts)
73
75
  return @sandbox || Nexo.config.default_sandbox if value.nil? && opts.empty?
74
76
 
@@ -76,28 +78,30 @@ module Nexo
76
78
  end
77
79
 
78
80
  # The permissions macro. With no argument it reads the configured value
79
- # (falling back to the harness-wide default, +:read_only+); with a value it
81
+ # (falling back to the harness-wide default, `:read_only`); with a value it
80
82
  # records the mode symbol or a pre-built Permissions instance.
81
83
  def permissions(value = nil)
82
84
  value.nil? ? (@permissions || Nexo.config.default_permissions) : (@permissions = value)
83
85
  end
84
86
 
85
87
  # The instructions macro. With no argument it reads the stored system
86
- # prompt (default +nil+); with a value it records it.
88
+ # prompt (default `nil`); with a value it records it.
87
89
  def instructions(value = nil)
88
90
  value.nil? ? @instructions : (@instructions = value)
89
91
  end
90
92
 
91
93
  # Declares the skills attached to this agent. With no args it returns the
92
- # configured list (default +[]+); with args it ACCUMULATES the names
93
- # (deduped), so multiple +skills+ lines add up instead of the last one
94
- # silently replacing the earlier ones — consistent with +mcp+.
94
+ # configured list (default `[]`); with args it ACCUMULATES the names
95
+ # (deduped), so multiple `skills` lines add up instead of the last one
96
+ # silently replacing the earlier ones — consistent with `mcp`.
95
97
  #
96
- # class TriageAgent < Nexo::Agent
97
- # model ENV.fetch("NEXO_MODEL")
98
- # skills :triage # one macro, no loader setup
99
- # skills :formatting # adds to :triage, does not replace it
100
- # end
98
+ # ```ruby
99
+ # class TriageAgent < Nexo::Agent
100
+ # model ENV.fetch("NEXO_MODEL")
101
+ # skills :triage # one macro, no loader setup
102
+ # skills :formatting # adds to :triage, does not replace it
103
+ # end
104
+ # ```
101
105
  def skills(*names)
102
106
  names.empty? ? (@skills || []) : (@skills = ((@skills || []) + names).uniq)
103
107
  end
@@ -105,22 +109,24 @@ module Nexo
105
109
  # What this agent needs from whatever sandbox it runs in — checked once,
106
110
  # before the first turn, against Sandbox#environment:
107
111
  #
108
- # class Publisher < Nexo::Agent
109
- # skills :dashboard_designer
110
- # requires commands: {"ruby" => ">= 3.1"}, locale: :utf8
111
- # end
112
+ # ```ruby
113
+ # class Publisher < Nexo::Agent
114
+ # skills :dashboard_designer
115
+ # requires commands: {"ruby" => ">= 3.1"}, locale: :utf8
116
+ # end
117
+ # ```
112
118
  #
113
119
  # Declared HERE, in Nexo's own vocabulary, rather than in the skill file:
114
120
  # whoever wires an agent to a sandbox is the only person who can *fix* a
115
121
  # gap, so the declaration and the fix live in the same place. A skill states
116
- # its needs in prose via +compatibility:+, which is the spec's field for it
122
+ # its needs in prose via `compatibility:`, which is the spec's field for it
117
123
  # and is aimed at a human or a model.
118
124
  #
119
- # +commands:+ maps a command that must be on +PATH+ to a version constraint
120
- # — a Gem::Requirement string (+">= 3.1"+) or +"*"+ for "any version". A
121
- # command whose version cannot be read (busybox +sh+ prints none) satisfies
125
+ # `commands:` maps a command that must be on `PATH` to a version constraint
126
+ # — a Gem::Requirement string (`">= 3.1"`) or `"*"` for "any version". A
127
+ # command whose version cannot be read (busybox `sh` prints none) satisfies
122
128
  # any constraint by being present: an unreadable version is not evidence of
123
- # a wrong one. +locale:+ takes +:utf8+ (any UTF-8 locale — the useful case)
129
+ # a wrong one. `locale:` takes `:utf8` (any UTF-8 locale — the useful case)
124
130
  # or an exact String.
125
131
  #
126
132
  # Deliberately coarse, and never packages: gems, wheels and npm modules
@@ -135,16 +141,18 @@ module Nexo
135
141
  # workflow copies out of the sandbox and records on the run as soon as the
136
142
  # agent finishes:
137
143
  #
138
- # class Publisher < Nexo::Agent
139
- # produces "dashboard.html", "digest.json", "out/*.csv"
140
- # end
144
+ # ```ruby
145
+ # class Publisher < Nexo::Agent
146
+ # produces "dashboard.html", "digest.json", "out/*.csv"
147
+ # end
148
+ # ```
141
149
  #
142
- # Accumulating and deduped, like +skills+: an agent may produce many
143
- # artifacts, and several +produces+ lines add up rather than replacing.
150
+ # Accumulating and deduped, like `skills`: an agent may produce many
151
+ # artifacts, and several `produces` lines add up rather than replacing.
144
152
  #
145
- # This is the agent's OUTPUT, not a template. Workflow#artifact's +from:+
153
+ # This is the agent's OUTPUT, not a template. Workflow#artifact's `from:`
146
154
  # mode renders ERB and is only ever for files you wrote; what an agent
147
- # produces is model output and is copied verbatim (Workflow#artifact +path:+).
155
+ # produces is model output and is copied verbatim (Workflow#artifact `path:`).
148
156
  #
149
157
  # Declared rather than inferred because a sweep of the sandbox would also
150
158
  # collect staged skill scripts, templates and scratch files — and because
@@ -156,15 +164,17 @@ module Nexo
156
164
  end
157
165
 
158
166
  # Declares an MCP server for this agent (Spec 6). Accumulating: multiple
159
- # +mcp+ lines are collected. With no args (+name+ nil and +opts+ empty) it
160
- # reads the list (default +[]+); otherwise it appends the friendly,
167
+ # `mcp` lines are collected. With no args (`name` nil and `opts` empty) it
168
+ # reads the list (default `[]`); otherwise it appends the friendly,
161
169
  # transport-shaped config consumed by Nexo::MCP.build.
162
170
  #
163
- # class InboxDigest < Nexo::Agent
164
- # model ENV.fetch("NEXO_MODEL")
165
- # mcp :gmail, transport: :stdio, command: "npx", args: %w[-y srv-gmail]
166
- # mcp :fetch, transport: :sse, url: "http://localhost:8080/sse"
167
- # end
171
+ # ```ruby
172
+ # class InboxDigest < Nexo::Agent
173
+ # model ENV.fetch("NEXO_MODEL")
174
+ # mcp :gmail, transport: :stdio, command: "npx", args: %w[-y srv-gmail]
175
+ # mcp :fetch, transport: :sse, url: "http://localhost:8080/sse"
176
+ # end
177
+ # ```
168
178
  def mcp(name = nil, **opts)
169
179
  return @mcp || [] if name.nil? && opts.empty?
170
180
 
@@ -172,70 +182,56 @@ module Nexo
172
182
  end
173
183
 
174
184
  # The MCP tool-name allow-list threaded into this agent's Permissions (see
175
- # +mcp_allow:+ in #resolve_permissions). Exact tool-name match only — no
176
- # globs. Like +skills+, with args it ACCUMULATES the flattened names as
177
- # strings (deduped); with none it reads the list (default +[]+).
185
+ # `mcp_allow:` in #resolve_permissions). Exact tool-name match only — no
186
+ # globs. Like `skills`, with args it ACCUMULATES the flattened names as
187
+ # strings (deduped); with none it reads the list (default `[]`).
178
188
  def mcp_allow(*names)
179
189
  names.empty? ? (@mcp_allow || []) : (@mcp_allow = ((@mcp_allow || []) + names.flatten.map(&:to_s)).uniq)
180
190
  end
181
191
 
182
192
  # The host allow-list scoping this agent's Nexo::Tools::Fetch (Spec 9).
183
193
  # Subdomain-aware, exact-host-suffix matching only — no globs. Like
184
- # +skills+/+mcp_allow+, with args it ACCUMULATES the flattened hosts as
185
- # strings (deduped); with none it reads the list (default +[]+).
194
+ # `skills`/`mcp_allow`, with args it ACCUMULATES the flattened hosts as
195
+ # strings (deduped); with none it reads the list (default `[]`).
186
196
  #
187
- # Declaring +fetch_allow+ only SCOPES hosts — it does not grant the +:fetch+
188
- # capability, which is default-denied like +:shell+. An agent that wants
189
- # egress must also run under +:auto+ or carry an explicit
190
- # +Permissions.new(mode: :read_only, allow: %i[read glob fetch])+. Both locks
197
+ # Declaring `fetch_allow` only SCOPES hosts — it does not grant the `:fetch`
198
+ # capability, which is default-denied like `:shell`. An agent that wants
199
+ # egress must also run under `:auto` or carry an explicit
200
+ # `Permissions.new(mode: :read_only, allow: %i[read glob fetch])`. Both locks
191
201
  # must open before a fetch happens.
192
202
  def fetch_allow(*hosts)
193
203
  hosts.empty? ? (@fetch_allow || []) : (@fetch_allow = ((@fetch_allow || []) + hosts.flatten.map(&:to_s)).uniq)
194
204
  end
195
205
 
196
206
  # The host-injected search backend for this agent's Nexo::Tools::WebSearch
197
- # (Spec 19). Reader/writer by nil-check, matching the +model+ macro
198
- # convention. Any object responding to +search(query, **opts)+ that
199
- # returns an Enumerable of +{title:, url:, snippet:}+ rows works — Nexo ships
200
- # no backend. Unset reads as +nil+, in which case no search tool is attached.
207
+ # (Spec 19). Reader/writer by nil-check, matching the `model` macro
208
+ # convention. Any object responding to `search(query, **opts)` that
209
+ # returns an Enumerable of `{title:, url:, snippet:}` rows works — Nexo ships
210
+ # no backend. Unset reads as `nil`, in which case no search tool is attached.
201
211
  #
202
- # Declaring +search_backend+ does not grant the +:search+ capability, which is
203
- # default-denied like +:fetch+/+:shell+. An agent that wants web discovery must
204
- # also run under +:auto+ or carry an explicit +allow: [..., :search]+.
212
+ # Declaring `search_backend` does not grant the `:search` capability, which is
213
+ # default-denied like `:fetch`/`:shell`. An agent that wants web discovery must
214
+ # also run under `:auto` or carry an explicit `allow: [..., :search]`.
205
215
  def search_backend(obj = nil)
206
216
  obj.nil? ? @search_backend : (@search_backend = obj)
207
217
  end
208
218
  end
209
219
 
210
- # The set of tool names handed to an opt-in backend that ships its own tools
211
- # (e.g. Loops::AgentSDK). The default Loops::RubyLLM ignores this — it
212
- # uses the agent's own sandbox-backed tools instead.
213
- ALLOWED_TOOLS = %w[Read Write Edit Bash Glob Grep].freeze
214
-
215
- # Maps Nexo's permission modes onto AgentSDK's own permission vocabulary,
216
- # consumed by Loops::AgentSDK. +:ask+ maps to +:default+ on purpose: human
217
- # gating stays in Nexo's own +on_ask+ path and is not delegated to the SDK.
218
- PERMISSION_MODE_MAP = {
219
- read_only: :default,
220
- auto: :bypass_permissions,
221
- ask: :default
222
- }.freeze
223
-
224
220
  # The resolved per-instance configuration (arg → class macro → config): the
225
- # working directory, model, provider, +assume_model_exists+ flag, the resolved
221
+ # working directory, model, provider, `assume_model_exists` flag, the resolved
226
222
  # Sandbox and Permissions, the system instructions, and the injected Loop.
227
223
  attr_reader :cwd, :model, :provider, :assume_model_exists, :sandbox, :permissions, :instructions, :loop
228
224
 
229
225
  # Every argument is optional; each resolves arg -> class macro -> config.
230
226
  # Symbol shorthands (:virtual/:local, :read_only/:auto/:ask/:approve) and
231
- # pre-built Sandbox/Permissions instances are both accepted. +loop:+ injects
227
+ # pre-built Sandbox/Permissions instances are both accepted. `loop:` injects
232
228
  # the engine that drives a prompt — the provider-neutral Loops::RubyLLM by
233
229
  # default, or an opt-in backend like Loops::AgentSDK.
234
230
  #
235
- # +decision:+ (Spec 16, default +nil+) is a per-run approval answer
236
- # (+{approved: true|false}+) threaded into the resolved Permissions so an
237
- # +:approve+ gate allows/denies instead of raising Nexo::ApprovalRequired.
238
- # It only supplies the *answer* to an already-+:approve+ gate — it never
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
239
235
  # widens capability. Workflow#run_agent passes it on the resume pass.
240
236
  def initialize(cwd: Dir.pwd, model: nil, sandbox: nil, permissions: nil, decision: nil, loop: Loops::RubyLLM.new)
241
237
  @cwd = cwd
@@ -253,7 +249,7 @@ module Nexo
253
249
  end
254
250
 
255
251
  # The agent owns (and so closes) its sandbox only when it resolved one from
256
- # its own config. A sandbox injected via +sandbox:+ (e.g. Workflow#run_agent
252
+ # its own config. A sandbox injected via `sandbox:` (e.g. Workflow#run_agent
257
253
  # sharing the run's sandbox) is BORROWED — closing it would strand the owner.
258
254
  @owns_sandbox = sandbox.nil?
259
255
  @sandbox = resolve_sandbox(sandbox || self.class.sandbox)
@@ -266,18 +262,18 @@ module Nexo
266
262
  # instances bound to this agent's sandbox and permissions, then layers on the
267
263
  # instructions of every declared skill.
268
264
  #
269
- # +base:+ lets a Nexo::Session pass a persisted +acts_as_chat+ record
270
- # (hydrated via ruby_llm's +#to_llm+ delegation) so the very same wiring —
265
+ # `base:` lets a Nexo::Session pass a persisted `acts_as_chat` record
266
+ # (hydrated via ruby_llm's `#to_llm` delegation) so the very same wiring —
271
267
  # instructions, the four sandbox tools, skills, MCP, fetch — is applied onto
272
- # the continuing thread instead of a fresh chat. When +base+ is nil the path
273
- # is byte-for-byte the standalone-agent build: a fresh +RubyLLM.chat+. A
268
+ # the continuing thread instead of a fresh chat. When `base` is nil the path
269
+ # is byte-for-byte the standalone-agent build: a fresh `RubyLLM.chat`. A
274
270
  # session therefore changes only *memory/persistence*, never authority or
275
271
  # execution — the record supplies the thread, the agent supplies the wiring.
276
272
  #
277
- # Re-applying +@instructions+ on every resume stays idempotent because the
278
- # persisted-chat +#with_instructions+ (default +append: false+) *replaces* the
279
- # stored +role: :system+ messages rather than appending, so the thread keeps
280
- # exactly one copy across resumes (VERIFIED, ruby_llm 1.16.0).
273
+ # Re-applying `@instructions` on every resume stays idempotent because the
274
+ # persisted-chat `#with_instructions` (default `append: false`) *replaces* the
275
+ # stored `role: :system` messages rather than appending, so the thread keeps
276
+ # exactly one copy across resumes (VERIFIED, ruby_llm 2.2.3).
281
277
  def chat(base: nil)
282
278
  c = base || RubyLLM.chat(**chat_model_options)
283
279
  c = apply_instructions(c)
@@ -310,8 +306,8 @@ module Nexo
310
306
 
311
307
  # Runs one prompt through the agent by delegating to the injected loop. The
312
308
  # loop body that used to live here is now in Loops::RubyLLM (the default),
313
- # so swapping +loop:+ swaps the engine without touching this class. The
314
- # optional +&on_event+ block receives +(type, payload)+ progress events.
309
+ # so swapping `loop:` swaps the engine without touching this class. The
310
+ # optional `&on_event` block receives `(type, payload)` progress events.
315
311
  def prompt(text, max_turns: 25, &on_event)
316
312
  verify_environment!
317
313
  @loop.run(agent: self, prompt: text, max_turns: max_turns, &on_event)
@@ -323,7 +319,7 @@ module Nexo
323
319
  #
324
320
  # Fails BEFORE the model is called, because the alternative is what this
325
321
  # exists to prevent: the agent spends turns deciding to run a script, runs it,
326
- # and gets +sh: ruby: not found+ or an Encoding::InvalidByteSequenceError three
322
+ # and gets `sh: ruby: not found` or an Encoding::InvalidByteSequenceError three
327
323
  # frames into a JSON parse. One legible sentence naming what is missing and
328
324
  # where beats a stack trace after the fact.
329
325
  #
@@ -366,8 +362,8 @@ module Nexo
366
362
  missing
367
363
  end
368
364
 
369
- # Whether a found command's version fails +constraint+. A missing version, an
370
- # unparseable constraint, or +"*"+ all pass: presence is the requirement, and
365
+ # Whether a found command's version fails `constraint`. A missing version, an
366
+ # unparseable constraint, or `"*"` all pass: presence is the requirement, and
371
367
  # an unreadable version is not evidence of a wrong one.
372
368
  def version_short?(version, constraint)
373
369
  return false if version.nil? || constraint.nil? || constraint.to_s.strip == "*"
@@ -377,7 +373,7 @@ module Nexo
377
373
  false
378
374
  end
379
375
 
380
- # +:utf8+ asks for any UTF-8 locale (the only case that comes up in practice);
376
+ # `:utf8` asks for any UTF-8 locale (the only case that comes up in practice);
381
377
  # a String asks for that exact locale. An unset locale never satisfies either
382
378
  # — that is the container default, and the bug this catches.
383
379
  def locale_unmet?(required, actual)
@@ -394,33 +390,16 @@ module Nexo
394
390
 
395
391
  public
396
392
 
397
- # The agent's Nexo permission mode mapped onto an opt-in backend's own
398
- # permission vocabulary (see PERMISSION_MODE_MAP). Consumed by
399
- # Loops::AgentSDK; the default Loops::RubyLLM does its gating inside the
400
- # sandbox-backed tools and ignores this.
401
- def permission_mode
402
- PERMISSION_MODE_MAP.fetch(@permissions.mode, :default)
403
- end
404
-
405
- # The tool names handed to an opt-in backend that ships its own tools.
406
- def allowed_tools
407
- ALLOWED_TOOLS
408
- end
409
-
410
393
  # Releases any MCP server connections held by this agent instance. Clients are
411
394
  # memoized on the instance and reused across prompts (Spec 6 lifecycle default),
412
- # so a long-lived agent holding stdio/SSE servers should call +#close+ when
395
+ # so a long-lived agent holding stdio/SSE servers should call `#close` when
413
396
  # done. Idempotent: safe to call with no MCP servers attached or more than once.
414
397
  #
415
- # VERIFY (Group 0, ruby_llm-mcp 1.0.0): the client teardown method is +#stop+
416
- # (guarded by +respond_to?+, falling back to +#close+ for other client shapes).
398
+ # VERIFIED (ruby_llm 2.2.3): a `RubyLLM::MCP` server is torn down with `#close`,
399
+ # which stops a stdio process and ends an HTTP session.
417
400
  def close
418
401
  @mcp_clients&.each do |client|
419
- if client.respond_to?(:stop)
420
- client.stop
421
- elsif client.respond_to?(:close)
422
- client.close
423
- end
402
+ client.close if client.respond_to?(:close)
424
403
  rescue
425
404
  # Best-effort teardown: a failing stop on one client must not strand the
426
405
  # remaining clients or leave @mcp_clients set (breaking idempotency).
@@ -429,9 +408,9 @@ module Nexo
429
408
  @mcp_clients = nil
430
409
 
431
410
  # Release the sandbox too, so a container/remote-backed agent doesn't leak
432
- # its container/connection when the caller only remembers +close+. Only close
411
+ # its container/connection when the caller only remembers `close`. Only close
433
412
  # a sandbox this agent OWNS (resolved from its own config) — a borrowed one
434
- # (injected via +sandbox:+, e.g. Workflow#run_agent's shared run sandbox) is
413
+ # (injected via `sandbox:`, e.g. Workflow#run_agent's shared run sandbox) is
435
414
  # the injector's to close. The base Sandbox#close is a no-op, so this is safe
436
415
  # and idempotent for :virtual/:local. Best-effort: never raise out of close.
437
416
  if @owns_sandbox
@@ -445,10 +424,10 @@ module Nexo
445
424
 
446
425
  private
447
426
 
448
- # Builds the +RubyLLM.chat+ options conditionally so the default agent's
449
- # call is byte-for-byte what it was before this feature: +{model: @model}+.
450
- # +provider+ is added only when resolved; +assume_model_exists: true+ only
451
- # when opted in (never passed as +false+).
427
+ # Builds the `RubyLLM.chat` options conditionally so the default agent's
428
+ # call is byte-for-byte what it was before this feature: `{model: @model}`.
429
+ # `provider` is added only when resolved; `assume_model_exists: true` only
430
+ # when opted in (never passed as `false`).
452
431
  def chat_model_options
453
432
  opts = {model: @model}
454
433
  opts[:provider] = @provider if @provider
@@ -456,18 +435,18 @@ module Nexo
456
435
  opts
457
436
  end
458
437
 
459
- # Applies the full system-prompt stack to +chat+ in deterministic order: the
438
+ # Applies the full system-prompt stack to `chat` in deterministic order: the
460
439
  # agent's own instructions, then the self-describing sandbox instructions (R1),
461
440
  # then each declared skill's body. A skill contributes instructions only — it
462
441
  # ships no independent tools (its scripts/references are reached through the
463
442
  # already-gated sandbox tools), so attaching one never widens the agent.
464
443
  #
465
- # The FIRST contribution is applied with +append: false+ and the rest with
466
- # +append: true+. On a fresh chat that is byte-for-byte the prior behavior; on
467
- # a Nexo::Session's persisted, re-hydrated chat the leading +append: false+
468
- # collapses all prior +role: :system+ messages to one before the rest
444
+ # The FIRST contribution is applied with `append: false` and the rest with
445
+ # `append: true`. On a fresh chat that is byte-for-byte the prior behavior; on
446
+ # a Nexo::Session's persisted, re-hydrated chat the leading `append: false`
447
+ # collapses all prior `role: :system` messages to one before the rest
469
448
  # re-append, so N resumes keep exactly ONE copy of the stack — even when the
470
- # agent declares no +instructions+ (the case that previously let skills/sandbox
449
+ # agent declares no `instructions` (the case that previously let skills/sandbox
471
450
  # instructions accumulate a fresh copy per resume).
472
451
  def apply_instructions(chat)
473
452
  texts = []
@@ -482,9 +461,9 @@ module Nexo
482
461
  end
483
462
 
484
463
  # One skill's contribution to the system prompt: its body, plus its
485
- # +compatibility:+ frontmatter when set.
464
+ # `compatibility:` frontmatter when set.
486
465
  #
487
- # +compatibility:+ is the Agent Skills spec's own field for what a skill needs
466
+ # `compatibility:` is the Agent Skills spec's own field for what a skill needs
488
467
  # in order to run ("requires a Ruby interpreter and a UTF-8 locale"), and it is
489
468
  # free text by design — the spec deliberately does not make it machine-checkable.
490
469
  # Nexo parsed it and then dropped it, so the one place an author can state a
@@ -494,9 +473,9 @@ module Nexo
494
473
  # the thing.
495
474
  #
496
475
  # Labelled rather than concatenated, so the model can tell a requirement from an
497
- # instruction. Absent or blank +compatibility:+ contributes nothing, leaving the
498
- # prompt byte-for-byte as before for every skill that does not set it. +license:+
499
- # and +allowed-tools:+ are deliberately NOT surfaced: the first is prompt noise,
476
+ # instruction. Absent or blank `compatibility:` contributes nothing, leaving the
477
+ # prompt byte-for-byte as before for every skill that does not set it. `license:`
478
+ # and `allowed-tools:` are deliberately NOT surfaced: the first is prompt noise,
500
479
  # and the second would be a second source of truth about what an agent may do,
501
480
  # competing with Nexo::Permissions, which is the real gate.
502
481
  def skill_instructions(skill)
@@ -510,33 +489,42 @@ module Nexo
510
489
  # Lazily connects the declared MCP servers and attaches their tools, each
511
490
  # wrapped in a MCP::GatedTool so every invocation is authorized through this
512
491
  # agent's Permissions first. Attached after the four sandbox tools and the
513
- # skills, so MCP tools fire the chat's +before_tool_call+/+after_tool_result+
492
+ # skills, so MCP tools fire the chat's `before_tool_call`/`after_tool_result`
514
493
  # callbacks (wired in Loops::RubyLLM) and appear in the run's event log with
515
494
  # no extra wiring. Returns early when no server is declared.
516
495
  #
517
- # Clients are built once and memoized on the instance (Spec 6 lifecycle
518
- # default): the +ruby_llm-mcp+ client connects on construction and is reusable
519
- # across prompts, so subsequent +#chat+ calls reuse the live connections until
520
- # #close. VERIFY (Group 0): tools accessor is +client.tools+ (an Array).
496
+ # Servers are built once and memoized on the instance: a `RubyLLM::MCP` server
497
+ # connects on its first request and is reusable across prompts, so subsequent
498
+ # `#chat` calls reuse the live connections until #close.
499
+ #
500
+ # The tools are attached with `with_tools` — NOT `chat.with_mcp(server)` — so
501
+ # each one can be wrapped in the permission gate first. VERIFIED (ruby_llm
502
+ # 2.2.3): `server.tools` is an Array of `RubyLLM::MCP::Tool`. Tools an MCP App
503
+ # reserves for its own UI are left out, as `with_mcp` would.
521
504
  def apply_mcp(chat)
522
505
  return if self.class.mcp.empty?
523
506
 
524
507
  @mcp_clients ||= self.class.mcp.map { |cfg| Nexo::MCP.build(**cfg) }
525
- gated = @mcp_clients.flat_map(&:tools).map do |tool|
508
+ gated = @mcp_clients.flat_map(&:tools).select { |tool| model_callable?(tool) }.map do |tool|
526
509
  wrap_mcp_tool(Nexo::MCP::GatedTool.new(tool: tool, permissions: @permissions))
527
510
  end
528
511
  chat.with_tools(*gated) unless gated.empty?
529
512
  end
530
513
 
531
- # Applies Nexo.config.tool_concurrency to the chat, LAST — every +with_tools+ call
532
- # resets the chat's concurrency to its current value, so setting it before the
533
- # tools are attached would be undone. +nil+ leaves RubyLLM's own setting alone.
514
+ # Whether the model may call this MCP tool. Only MCP App tools restrict it.
515
+ def model_callable?(tool)
516
+ !tool.respond_to?(:visibility) || tool.visibility.include?(:model)
517
+ end
518
+
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.
534
522
  def apply_tool_concurrency(chat)
535
523
  mode = Nexo.config.tool_concurrency
536
524
  return if mode.nil?
537
- return unless chat.respond_to?(:with_tools)
525
+ return unless chat.respond_to?(:with_tool_options)
538
526
 
539
- chat.with_tools(concurrency: mode)
527
+ chat.with_tool_options(concurrency: mode)
540
528
  end
541
529
 
542
530
  # Hook: called once per MCP tool, AFTER it is wrapped in a permission-gating
@@ -547,30 +535,32 @@ module Nexo
547
535
  # recording timings, redacting a field. A third-party MCP server's response shape
548
536
  # is not yours to change, and its tools are attached by the harness rather than by
549
537
  # you, so without this seam the only way in was to override the private
550
- # +#apply_mcp+.
538
+ # `#apply_mcp`.
551
539
  #
552
- # class MailAgent < Nexo::Agent
553
- # mcp :mail, transport: :stdio, command: "apple-mail-mcp"
540
+ # ```ruby
541
+ # class MailAgent < Nexo::Agent
542
+ # mcp :mail, transport: :stdio, command: "apple-mail-mcp"
543
+ # ```
554
544
  #
555
545
  # def wrap_mcp_tool(tool)
556
546
  # CappedTool.new(tool: tool, max_chars: 4_000)
557
547
  # end
558
548
  # end
559
549
  #
560
- # A wrapper must keep the duck type the chat relies on — +#name+, +#description+,
561
- # +#params_schema+ and +#call+. GatedTool delegates the rest through
562
- # +method_missing+, so wrappers compose. Gating happens underneath, so a wrapper
550
+ # A wrapper must keep the duck type the chat relies on — `#name`, `#description`,
551
+ # `#parameters_schema` and `#call`. GatedTool delegates the rest through
552
+ # `method_missing`, so wrappers compose. Gating happens underneath, so a wrapper
563
553
  # only ever sees an already-authorized call: wrapping cannot widen what the agent
564
554
  # may do.
565
555
  def wrap_mcp_tool(tool)
566
556
  tool
567
557
  end
568
558
 
569
- # Attaches a single Nexo::Tools::Fetch scoped to the agent's +fetch_allow+
559
+ # Attaches a single Nexo::Tools::Fetch scoped to the agent's `fetch_allow`
570
560
  # hosts (Spec 9). Returns early when no host is declared, so an agent that never
571
- # calls +fetch_allow+ gets no fetch tool. Attached right after +apply_mcp+ so
572
- # the tool participates in the chat's +before_tool_call+/+after_tool_result+
573
- # event stream (wired in Loops::RubyLLM) with no extra wiring. The +:fetch+
561
+ # calls `fetch_allow` gets no fetch tool. Attached right after `apply_mcp` so
562
+ # the tool participates in the chat's `before_tool_call`/`after_tool_result`
563
+ # event stream (wired in Loops::RubyLLM) with no extra wiring. The `:fetch`
574
564
  # capability itself is gated through Permissions#authorize! at call time — the
575
565
  # allow-list only scopes hosts, it is not the capability grant.
576
566
  def apply_fetch(chat)
@@ -586,11 +576,11 @@ module Nexo
586
576
  end
587
577
 
588
578
  # Attaches a single Nexo::Tools::WebSearch bound to the agent's injected
589
- # +search_backend+ (Spec 19). Returns early when no backend is declared, so an
590
- # agent that never calls +search_backend+ gets no search tool — existing agents
591
- # are byte-for-byte unchanged. Attached right after +apply_fetch+ so the tool
592
- # rides the same +before_tool_call+/+after_tool_result+ event stream (wired in
593
- # Loops::RubyLLM) with no extra wiring. The +:search+ capability itself is gated
579
+ # `search_backend` (Spec 19). Returns early when no backend is declared, so an
580
+ # agent that never calls `search_backend` gets no search tool — existing agents
581
+ # are byte-for-byte unchanged. Attached right after `apply_fetch` so the tool
582
+ # rides the same `before_tool_call`/`after_tool_result` event stream (wired in
583
+ # Loops::RubyLLM) with no extra wiring. The `:search` capability itself is gated
594
584
  # through Permissions#authorize! at call time.
595
585
  def apply_search(chat)
596
586
  backend = self.class.search_backend or return
@@ -602,8 +592,8 @@ module Nexo
602
592
  end
603
593
 
604
594
  # Resolves this agent's sandbox declaration via the shared resolver (Spec 15),
605
- # passing the agent's instance +@cwd+ as the host working directory (used only
606
- # by +:local+; container tiers keep their own +/workspace+ default).
595
+ # passing the agent's instance `@cwd` as the host working directory (used only
596
+ # by `:local`; container tiers keep their own `/workspace` default).
607
597
  def resolve_sandbox(value) = Sandboxes.resolve(value, cwd: @cwd)
608
598
 
609
599
  def resolve_permissions(value, decision: nil)