nexo_ai 0.13.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3ab3bc27263cfb9d2adc054a4579f983f8fa10ac2c94586116f3e6793d3d93b9
4
- data.tar.gz: e967f788db7fce3e9205199b7cbe8628a60d5678e9daa0db8802852d6e87b7bf
3
+ metadata.gz: d344ac737c8cf5b8e0a4de3afe5745718e1794556941cdd0512bf8d4d83d1eed
4
+ data.tar.gz: 414c446feec2a6307444f64324205a599363879e82b33ef36bc2cd8ace80e4e8
5
5
  SHA512:
6
- metadata.gz: 97a086e9d89990c89c0be4d9ba03de89ac2c77aa6e6d5fcd5086179c9d5c55845f2b08543984ea67b77eafa4b6e085e2c2d60d2d9c25020a80853c81bfab61bd
7
- data.tar.gz: 57b9cf4b4ab598badaad5cc59fa57b691ca3c4f8c88caa927ed3ef9bf9637587a029db2037ae04ac97b7e17341a41ac4c5a0435edbfe9d13f00d135b92efb375
6
+ metadata.gz: cd25708a4c1f9c35ff84e361ae06fa6aaf52050e3f663cecda12506ae0ad91d1af0f60db48f24147bd2cd92278f702bbd8feb6b7e49e5c1f090d343ef82864ac
7
+ data.tar.gz: 11e729c9e4695a178029b5fd01ba9cf206358fb952fec64bfb255f75dce74b0bc6e27d15b3c3de6c6f620694dd7b1e60446a95be752579adbb7d4ac325d87b9b
data/CHANGELOG.md CHANGED
@@ -1,5 +1,78 @@
1
1
  ## [Unreleased]
2
2
 
3
+ ## [0.14.0] - 2026-11-26
4
+
5
+ A security release. Three guarantees Nexo documented did not hold and now do, and a tool
6
+ you wrote yourself can be gated like Nexo's own.
7
+
8
+ **Upgrading:** four changes can affect a host.
9
+
10
+ 1. **The local shell no longer inherits your environment.** If a command an agent runs on
11
+ `sandbox :local` relied on an inherited variable, pass it with `env:`.
12
+ 2. **`resume(approved:)` answers one call.** A workflow whose agent makes several gated calls
13
+ now suspends once per distinct call. A host that drove an agent directly with
14
+ `Agent.new(decision:)` is unaffected.
15
+ 3. **Under `:read_only`, MCP tools outside `mcp_allow` are no longer attached.** They were
16
+ always denied when called; the model just stops seeing them.
17
+ 4. **Tools added by overriding `#chat` now warn once.** Move them to the `tools` macro.
18
+
19
+ ### Fixed
20
+
21
+ - **`Sandboxes::Local#shell` leaked the whole process environment.** The documented narrowing
22
+ to `PATH`/`HOME`/`LANG` never happened: those were added on top of an inherited environment,
23
+ so any secret in the host's `ENV` was readable by a model-run command. The child process now
24
+ gets only the narrowed set plus explicit `env:` entries.
25
+ - **A shell timeout did not stop the command.** `Timeout::Error` was raised only after the
26
+ command finished by itself. The command now runs in its own process group, which is killed
27
+ when the timeout fires. `Tools::Shell` returns the timeout to the model as `{error:}` instead
28
+ of failing the run.
29
+ - **One approval approved everything after it.** `Workflow.resume(id, approved: true)` handed
30
+ the re-driven agent a single global decision, so every later `:approve`-gated call in that
31
+ prompt ran without asking; the guide said it would suspend again. Answers are now filed per
32
+ call under the reserved `__approvals__` state key, keyed by capability and detail (and a
33
+ digest of the arguments for MCP tools). A call with no answer suspends.
34
+ - **`sandbox :local, env: {...}`** dropped `env:` in the Hash form. Every option now reaches
35
+ `Sandboxes::Local`.
36
+ - **`Tools::Fetch` failed on hosts whose first address was unreachable.** Only the first
37
+ resolved address was tried, so a host with an IPv6 record failed on a machine with no IPv6
38
+ route. Each vetted address is now tried in turn (up to four), and only on connect errors.
39
+
40
+ ### Added
41
+
42
+ - **`tools` macro on `Nexo::Agent`** for tools of your own, with an optional `capability:`.
43
+ A tool declared with one is wrapped in the new `Nexo::GatedTool`, so the agent's permissions
44
+ decide every call, and it is left out of the schema when the mode could never allow it.
45
+ - **`Nexo.config.strict_tools`.** One `around_tool_call` block catches calls to tools Nexo did
46
+ not attach. Default `false`: the call runs and Nexo warns once per tool. `true` refuses it.
47
+ This becomes the default in 1.0.
48
+ - **`isolation: :confined` on `Sandboxes::Local`** runs shell commands in an OS sandbox through
49
+ `ruby_llm`'s sandbox contract (the `mxc` gem, a soft dependency): writes only inside `cwd`,
50
+ no home directory, no network. `readable:` grants extra paths; `isolation:` also accepts an
51
+ `MXC::Sandbox` or any object answering the contract. Verified on macOS; opt-in.
52
+ - **`Sandbox#hardening_gaps`** on every sandbox. `Local` reports an unconfined shell.
53
+ - **`Permissions#decisions`, `#with_decisions`, `::approval_key`, `#never_allows_mcp?`** and
54
+ `Nexo::ApprovalRequired#key`.
55
+ - **Runs execute inside `RubyLLM.workflow`**, so `ruby_llm`'s instrumentation and usage records
56
+ carry the Nexo run id. `checkpoint` and `run_agent` are steps of it. No outcome changes.
57
+
58
+ ### Deprecated
59
+
60
+ - `Permissions#decision`, `#with_decision` and `Agent.new(decision:)`: one answer for every
61
+ gated call. `Workflow#run_agent` no longer uses them. Use `decisions:`.
62
+
63
+ ### Decided against, for now
64
+
65
+ Recorded so they are not re-litigated without new facts (all read from ruby_llm 2.2.3):
66
+
67
+ - **The permission check did not move into `around_tool_call`.** A skipped call can only give
68
+ the model `"The <name> call did not run."`; the block's return value is ignored. Nexo's
69
+ denial messages cannot travel through it, so the hook is the backstop, not the gate.
70
+ - **`:approve` was not rebuilt on ruby_llm's tool approvals.** Those are durable only with
71
+ `acts_as_chat`; without ActiveRecord the pending state lives in memory. Nexo's approvals
72
+ work with any run store.
73
+ - **`Nexo::Agent` is not a `RubyLLM::Agent` subclass**, and `Session`, `WebSearch`,
74
+ `ReadTracker` and `OutputTruncator` stay: ruby_llm has no plain-Ruby equivalent of them.
75
+
3
76
  ## [0.13.0] - 2026-11-26
4
77
 
5
78
  Nexo now runs on ruby_llm 2.2. MCP comes from ruby_llm itself, skills need no extra gem,
@@ -132,7 +132,7 @@ class ApprovedWrite < Nexo::Workflow
132
132
  end
133
133
  ```
134
134
 
135
- The loop is: **`:approve` gate with no decision → `Nexo::ApprovalRequired` → `run_agent`
135
+ The loop is: **`:approve` gate reaches a call nobody has decided → `Nexo::ApprovalRequired` → `run_agent`
136
136
  suspends → host renders the pending call → `resume(approved:)` threads the decision back
137
137
  through the gate.**
138
138
 
@@ -176,10 +176,20 @@ resumed.status # => "done" (the gate allowed the
176
176
  non-idempotent tool call *before* the approval gate re-runs on resume (agent tool calls
177
177
  generally aren't checkpointable). Put approval gates **early**, or after the expensive
178
178
  work is already `checkpoint`ed by the workflow.
179
- - **One approval per suspend cycle, global decision.** The `{approved:}` answers whichever
180
- gate the re-driven agent hits first. A *second* gate after an approved first one simply
181
- **suspends again** — the next resume decides it. There is no per-tool decision granularity
182
- in v1.
179
+ - **One answer decides one call.** `resume(approved:)` answers the call recorded under
180
+ `run.state["__approval__"]`, and nothing else. The answer is filed in
181
+ `run.state["__approvals__"]` under that call's key (capability plus path, command or URL; for
182
+ an MCP tool, its name plus a digest of the arguments). A *different* gated call later in the
183
+ same prompt **suspends again**, and the next resume decides it. Before 0.14 the first answer
184
+ silently applied to every later call.
185
+ - **A re-driven model may ask for something else.** Resume runs the prompt again, and nothing
186
+ forces the model to repeat the call you approved. If it writes `b.txt` where it asked for
187
+ `a.txt`, that is a new call and the run suspends for it. This is the safe direction.
188
+ - **`approved:` with nothing pending approves nothing.** An answer is recorded only when a call
189
+ is waiting.
190
+ - **A catch-all tool handler breaks it.** `RubyLLM::Tool.rescue_from StandardError` in the host
191
+ swallows the approval signal, and the call is reported to the model as an error instead of
192
+ suspending the run. Rescue specific classes.
183
193
  - **Cross-process approval needs the ActiveRecord store + ActiveJob** (like all durable resume).
184
194
  In-process `resume` works with the Memory store; a Memory run does not survive the process.
185
195
  - **Branch depends on upstream `ruby_llm`.** This works because `ruby_llm`'s tool loop lets a
data/docs/mcp.md CHANGED
@@ -40,6 +40,11 @@ exact-match allow-list threaded into the agent's permissions:
40
40
  | `:read_only` (default) | allow **only** tool names listed in `mcp_allow`; everything else is denied |
41
41
  | `:ask` | call `on_ask.call(:mcp, {tool:, args:})`; a truthy return allows, else deny |
42
42
  | `:approve` | names in `mcp_allow` are pre-approved; any other tool needs a human decision — undecided **suspends the run** (`Nexo::ApprovalRequired`), `approved: true` allows, `approved: false` denies (the durable sibling of `:ask`) |
43
+
44
+ Under `:read_only` an MCP tool that is not in `mcp_allow` is not attached at all (0.14): the
45
+ model never sees a tool it could not call. Under `:approve` each call is decided on its own —
46
+ the tool name and its arguments identify it — so approving one `send_email` does not approve
47
+ the next.
43
48
  | `:auto` | allow every MCP tool |
44
49
 
45
50
  `mcp_allow` defaults to `[]`, so attaching a powerful server under `:read_only` with no
data/docs/permissions.md CHANGED
@@ -11,9 +11,9 @@ and the agent loop continues — it does not raise. A path that escapes the work
11
11
  | `:read_only` (default) | ✅ | ✅ | ❌ not attached ‡ | ❌ not attached ‡ | ❌ not attached ‡ | ❌ not attached ‡ |
12
12
  | `:auto` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
13
13
  | `:ask` | ✅ | ✅ | per `on_ask` | per `on_ask` | per `on_ask` | per `on_ask` |
14
- | `:approve` | ✅ | ✅ | per `decision` | per `decision` | per `decision` | per `decision` |
14
+ | `:approve` | ✅ | ✅ | per call | per call | per call | per call |
15
15
  | `Virtual` sandbox | ✅ | ✅ | ✅ (in-memory) | ❌ `NotImplementedError`→`{error}` | ✅ † | ✅ † |
16
- | `Local` sandbox | ✅ (guarded) | ✅ | ✅ (guarded) | ✅ (narrowed ENV) | ✅ † | ✅ † |
16
+ | `Local` sandbox | ✅ (guarded) | ✅ | ✅ (guarded) | ✅ (narrowed ENV, unconfined ⚠) | ✅ † | ✅ † |
17
17
  | `Container` sandbox | ✅ (guarded) | ✅ | ✅ (guarded, scratch) | ✅ (in container) | ✅ † | ✅ † |
18
18
 
19
19
  `:read`/`:glob` are auto-allowed under **every** mode (they sit in the default
data/docs/sandboxes.md CHANGED
@@ -11,9 +11,9 @@ and the agent loop continues — it does not raise. A path that escapes the work
11
11
  | `:read_only` (default) | ✅ | ✅ | ❌ `{error}` | ❌ `{error}` | ❌ `{error}` | ❌ `{error}` |
12
12
  | `:auto` | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
13
13
  | `:ask` | ✅ | ✅ | per `on_ask` | per `on_ask` | per `on_ask` | per `on_ask` |
14
- | `:approve` | ✅ | ✅ | per `decision` | per `decision` | per `decision` | per `decision` |
14
+ | `:approve` | ✅ | ✅ | per call | per call | per call | per call |
15
15
  | `Virtual` sandbox | ✅ | ✅ | ✅ (in-memory) | ❌ `NotImplementedError`→`{error}` | ✅ † | ✅ † |
16
- | `Local` sandbox | ✅ (guarded) | ✅ | ✅ (guarded) | ✅ (narrowed ENV) | ✅ † | ✅ † |
16
+ | `Local` sandbox | ✅ (guarded) | ✅ | ✅ (guarded) | ✅ (narrowed ENV, unconfined ⚠) | ✅ † | ✅ † |
17
17
  | `Container` sandbox | ✅ (guarded) | ✅ | ✅ (guarded, scratch) | ✅ (in container) | ✅ † | ✅ † |
18
18
 
19
19
  `:read`/`:glob` are auto-allowed under **every** mode (they sit in the default
@@ -26,10 +26,11 @@ only by the capability gate above plus `fetch_allow` / the injected backend.
26
26
  - **`Virtual`** (default) — in-memory, zero host access. `#shell` raises
27
27
  `NotImplementedError` on purpose: in-memory means no command execution. That is the
28
28
  safety property, not a gap.
29
- - **`Local`** — host filesystem + shell, for trusted dev/CI. Two guards: every path is
30
- expanded against `cwd` and must stay inside it (else `SecurityError`), and the shell sees
31
- only `PATH`, `HOME`, `LANG` (plus explicit `env:` additions) — never the full process
32
- environment.
29
+ - **`Local`** — host filesystem + shell, for trusted dev/CI. Every file path is expanded
30
+ against `cwd` and must stay inside it (else `SecurityError`). The shell sees only `PATH`,
31
+ `HOME`, `LANG` (plus explicit `env:` additions), and a command that outlives its timeout is
32
+ killed with everything it started. ⚠ The path guard does not cover what a shell command
33
+ touches: see [Confining the local shell](#confining-the-local-shell).
33
34
  - **`Container`** — run the tools inside a throwaway local container via the `docker`
34
35
  (default) or Apple `container` CLI. Shell-out only, no client gem. **Hardened by default**
35
36
  (no network, dropped caps, read-only rootfs + ephemeral scratch, read-only host binds);
@@ -38,6 +39,57 @@ only by the capability gate above plus `fetch_allow` / the injected backend.
38
39
  your own) by injecting a client. Escalating to `:remote` is always an explicit choice in
39
40
  your code — the default stays `:virtual`.
40
41
 
42
+ ## Confining the local shell
43
+
44
+ On `:local`, `read`/`write`/`glob` are guarded to `cwd`. A shell command is not: it is a host
45
+ process that can read and write wherever your user can, and reach the network. `#hardening_gaps`
46
+ says so, so a host can show it before trusting the sandbox with a model:
47
+
48
+ ```ruby
49
+ Nexo::Sandboxes::Local.new(cwd: dir).hardening_gaps
50
+ # => ["shell commands are not confined: they can read and write outside /path and reach the network …"]
51
+ ```
52
+
53
+ `isolation: :confined` runs every command inside an OS sandbox — Seatbelt on macOS, Bubblewrap
54
+ on Linux — through `ruby_llm`'s sandbox contract. A confined command can write only inside
55
+ `cwd`, cannot read your home directory, and has no network:
56
+
57
+ ```ruby
58
+ # Gemfile
59
+ gem "mxc" # a soft dependency: Nexo loads it only for a confined shell
60
+
61
+ class Builder < Nexo::Agent
62
+ sandbox :local, isolation: :confined, readable: [RbConfig::CONFIG["prefix"]]
63
+ permissions Nexo::Permissions.new(mode: :read_only, allow: %i[read glob write shell])
64
+ end
65
+ ```
66
+
67
+ Things to know:
68
+
69
+ - **A confined command cannot read outside `cwd` either.** That includes a Ruby, Node or Python
70
+ installed under your home directory: `ruby` starts but cannot load its gems. Grant the
71
+ toolchain with `readable:`. Tools that link Homebrew libraries need those paths too.
72
+ - **It never falls back.** If the sandbox cannot run on the machine, the first `shell` raises
73
+ `Nexo::ConfigurationError` with the reason. A missing `mxc` gem raises
74
+ `Nexo::MissingDependencyError`.
75
+ - **Bring your own policy.** `isolation:` also takes an `MXC::Sandbox` class or instance, or any
76
+ object answering `supported?` and `run(*command, timeout:, readable:, writable:, directory:,
77
+ env:, network:)`.
78
+ - **Verified on macOS (Seatbelt), `mxc` 0.4.1:** a write outside `cwd`, a read of the home
79
+ directory and a network request were all refused. Linux (Bubblewrap) is not verified here.
80
+ - Unconfined remains the default in 0.14. Use a [container](#container-sandbox--docker--apple-container)
81
+ when you need a different filesystem, not only a fence.
82
+
83
+ ### Two fixes in 0.14 that change behaviour
84
+
85
+ - **The narrowed environment is now real.** Before 0.14 the shell inherited the whole process
86
+ environment, API keys included; the `PATH`/`HOME`/`LANG` list was only added on top. A command
87
+ that relied on an inherited variable now needs it passed with `env:`
88
+ (`sandbox :local, env: {"BUNDLE_GEMFILE" => "..."}`).
89
+ - **A timeout now stops the command.** Before 0.14 `Timeout::Error` was raised only after the
90
+ command had finished on its own. Now the command's whole process group is killed, and the
91
+ `Shell` tool reports the timeout to the model as `{error: ...}` instead of failing the run.
92
+
41
93
  ## Safety refinements — safer, more legible real-FS sandboxes
42
94
 
43
95
  Five small refinements tighten the real-filesystem sandboxes (`Local`, `Container`) and make
data/docs/tools.md CHANGED
@@ -15,6 +15,9 @@ ever allow:
15
15
  neither `WriteFile` nor `Shell` is attached. `:auto`, `:ask` and `:approve` decide per call
16
16
  and always attach — `:approve` in particular *must* reach the gate so it can suspend the run.
17
17
 
18
+ The same rule covers a host tool declared with `capability:` and, since 0.14, an MCP tool:
19
+ under `:read_only` one that is not in `mcp_allow` is not attached.
20
+
18
21
  `ReadFile` and `Glob` are always attached. This is a cost and description-accuracy measure, not
19
22
  a security boundary: `Permissions#authorize!` remains the gate and still denies at call time.
20
23
 
@@ -41,6 +44,50 @@ ever allow:
41
44
  the stale check (read-before-write is the primary guard). Clobber-safety within a session only —
42
45
  no versioning, locking, or VCS semantics.
43
46
 
47
+ ## Tools of your own — the `tools` macro
48
+
49
+ Declare a `RubyLLM::Tool` you wrote on the agent, and say what it does in Nexo's terms:
50
+
51
+ ```ruby
52
+ class Archivist < Nexo::Agent
53
+ model ENV.fetch("NEXO_MODEL")
54
+
55
+ tools Today, SumPayments # no side effects: no gate
56
+ tools ArchiveRun, capability: :write # gated exactly like WriteFile
57
+ tools ->(agent) { Lookup.new(root: agent.cwd) }
58
+ end
59
+ ```
60
+
61
+ Each entry is a tool class (built with no arguments), an instance, or a lambda that takes the
62
+ agent and returns a tool or an Array of tools. The macro accumulates and is inherited.
63
+
64
+ With `capability:` (`:read`, `:write`, `:shell`, `:fetch` or `:search`) the tool is wrapped in
65
+ `Nexo::GatedTool`, and the agent's permissions decide every call the same way they do for Nexo's
66
+ own tools: refused under `:read_only`, put to `on_ask` under `:ask`, suspended under `:approve`.
67
+ A denied call returns `{error: ...}` and the tool body never runs. A gated tool the mode can never
68
+ allow is left out of the schema. The detail your `on_ask`/`ask_when` hook receives is the tool
69
+ name followed by its arguments as JSON.
70
+
71
+ Without `capability:` the tool runs ungated. That is right only for a tool with no side effects.
72
+
73
+ ### `strict_tools` — refuse what was never declared
74
+
75
+ A tool added to the chat any other way — typically by overriding `#chat` and calling
76
+ `with_tools` — is one no permission gate ever saw. Nexo catches those calls with a single
77
+ `around_tool_call` block:
78
+
79
+ - By default the call runs and Nexo warns once per tool name.
80
+ - With `Nexo.config.strict_tools = true` the call is refused, and the model is told the call did
81
+ not run.
82
+
83
+ ```ruby
84
+ Nexo.configure { |config| config.strict_tools = true }
85
+ ```
86
+
87
+ Declare your tools with the macro and turn this on. It becomes the default in 1.0. The block is a
88
+ backstop, not the gate: a refused call can only carry `ruby_llm`'s fixed "did not run" text, so
89
+ the gate that explains itself stays with the tool.
90
+
44
91
  These are sandbox refinements as much as tool behavior — see [Sandboxes](sandboxes.md) for the
45
92
  guard details behind each capability. The `fetch` tool for reading the web lives in
46
93
  [Web](web.md), gated by its own `:fetch` capability plus a host allow-list.
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,
@@ -226,14 +258,17 @@ module Nexo
226
258
  # Symbol shorthands (:virtual/:local, :read_only/:auto/:ask/:approve) and
227
259
  # pre-built Sandbox/Permissions instances are both accepted. `loop:` injects
228
260
  # the engine that drives a prompt — the provider-neutral Loops::RubyLLM by
229
- # default, or an opt-in backend like Loops::AgentSDK.
261
+ # default, or a backend of your own.
230
262
  #
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)
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)
237
272
  @cwd = cwd
238
273
  @model = model || self.class.model || Nexo.config.default_model
239
274
  if @model.nil?
@@ -253,7 +288,8 @@ module Nexo
253
288
  # sharing the run's sandbox) is BORROWED — closing it would strand the owner.
254
289
  @owns_sandbox = sandbox.nil?
255
290
  @sandbox = resolve_sandbox(sandbox || self.class.sandbox)
256
- @permissions = resolve_permissions(permissions || self.class.permissions, decision: decision)
291
+ @permissions = resolve_permissions(permissions || self.class.permissions, decision: decision,
292
+ decisions: decisions)
257
293
  @instructions = self.class.instructions
258
294
  @loop = loop
259
295
  end
@@ -297,10 +333,12 @@ module Nexo
297
333
  tools << Tools::Shell.new(sandbox: @sandbox, permissions: @permissions)
298
334
  end
299
335
  c.with_tools(*tools)
336
+ apply_host_tools(c)
300
337
  apply_mcp(c)
301
338
  apply_fetch(c)
302
339
  apply_search(c)
303
340
  apply_tool_concurrency(c)
341
+ apply_tool_backstop(c)
304
342
  c
305
343
  end
306
344
 
@@ -505,17 +543,82 @@ module Nexo
505
543
  return if self.class.mcp.empty?
506
544
 
507
545
  @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|
546
+ gated = @mcp_clients.flat_map(&:tools).select { |tool| attachable_mcp_tool?(tool) }.map do |tool|
509
547
  wrap_mcp_tool(Nexo::MCP::GatedTool.new(tool: tool, permissions: @permissions))
510
548
  end
511
549
  chat.with_tools(*gated) unless gated.empty?
512
550
  end
513
551
 
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
+
514
559
  # Whether the model may call this MCP tool. Only MCP App tools restrict it.
515
560
  def model_callable?(tool)
516
561
  !tool.respond_to?(:visibility) || tool.visibility.include?(:model)
517
562
  end
518
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
+
519
622
  # Applies Nexo.config.tool_concurrency to the chat through
520
623
  # `with_tool_options(concurrency:)` (ruby_llm 2.x moved tool execution settings
521
624
  # off `with_tools`). `nil` leaves RubyLLM's own setting alone.
@@ -596,12 +699,14 @@ module Nexo
596
699
  # by `:local`; container tiers keep their own `/workspace` default).
597
700
  def resolve_sandbox(value) = Sandboxes.resolve(value, cwd: @cwd)
598
701
 
599
- def resolve_permissions(value, decision: nil)
702
+ def resolve_permissions(value, decision: nil, decisions: nil)
600
703
  # 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)
704
+ # Thread the run's approval answers through a non-mutating copy (Spec 16)
602
705
  # so a shared, class-level :approve instance is never clobbered.
603
706
  if value.is_a?(Permissions)
604
- 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
605
710
  end
606
711
 
607
712
  # Thread the class-level mcp_allow into each symbol branch (Spec 6) so the
@@ -611,7 +716,7 @@ module Nexo
611
716
  when :read_only then Permissions.new(mode: :read_only, mcp_allow: allow)
612
717
  when :auto then Permissions.new(mode: :auto, allow: %i[read glob write shell fetch search], mcp_allow: allow)
613
718
  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)
719
+ when :approve then Permissions.new(mode: :approve, mcp_allow: allow, decision: decision, decisions: decisions)
615
720
  else raise ConfigurationError, "unknown permissions: #{value.inspect}"
616
721
  end
617
722
  end
@@ -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