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.
@@ -2,72 +2,24 @@
2
2
 
3
3
  module Nexo
4
4
  module MCP
5
- # Wraps an MCP tool so the chat sees an identical tool but every invocation is
6
- # authorized through Nexo::Permissions#authorize_mcp! first. A denied call
7
- # returns `{ error: ... }` (recoverable) and never raises into the loop —
8
- # matching the sandbox-backed tools' authorize→act→rescue-`Denied`→`{error:}`
9
- # shape (see `lib/nexo/tools/write_file.rb`).
10
- #
11
- # Everything except the execution method is delegated to the wrapped tool, so
12
- # the chat cannot tell the wrapper apart from the raw MCP tool: it reports the
13
- # same `name`/`description`/`parameters_schema` and serializes identically.
5
+ # Nexo::GatedTool on the MCP axis: every invocation of the wrapped MCP tool is
6
+ # authorized by NAME through Nexo::Permissions#authorize_mcp! first, and a
7
+ # denied call returns `{ error: ... }` without reaching the server.
14
8
  #
15
9
  # VERIFIED (ruby_llm 2.2.3): a server's tools are `RubyLLM::MCP::Tool`
16
- # instances (a `RubyLLM::Tool` subclass). `Chat#with_tools` does not type-check
17
- # — it registers any object answering `qualified_name`/`namespace`/`name`/
18
- # `deferred?` — and the tool loop invokes `tool.call(**arguments, tool_call:)`
19
- # with KEYWORDS. So a delegating wrapper is accepted; `method_missing` forwards
20
- # every reader the chat and the provider renderers ask for.
21
- class GatedTool
10
+ # instances (a `RubyLLM::Tool` subclass), called with keywords.
11
+ class GatedTool < Nexo::GatedTool
22
12
  # Wraps `tool` (an MCP tool) so every call is authorized through
23
13
  # `permissions` (the MCP axis) before delegating.
24
14
  def initialize(tool:, permissions:)
25
- @tool = tool
26
- @permissions = permissions
27
- end
28
-
29
- # Authorizes the call by tool name, then delegates to the wrapped tool. A
30
- # denial is returned as `{ error: ... }` so the model can recover — never
31
- # raised into the loop.
32
- #
33
- # Arguments arrive as keywords from the chat loop. A single positional Hash
34
- # is accepted too, for direct callers. `tool_call:` is the chat's own
35
- # bookkeeping, not a tool argument, so the gate never sees it.
36
- def call(args = nil, **kwargs)
37
- arguments = (args || {}).to_h.merge(kwargs).transform_keys(&:to_sym)
38
- @permissions.authorize_mcp!(name, arguments.except(:tool_call))
39
- @tool.call(**arguments)
40
- rescue Nexo::Permissions::Denied => e
41
- {error: e.message}
42
- end
43
-
44
- # The wrapped tool's name — the key the gate authorizes on.
45
- def name = @tool.name
46
-
47
- # Routes `#execute` through the same gate, so the wrapper is safe whichever
48
- # entry point a caller uses.
49
- def execute(*args, **kwargs)
50
- call(args.first, **kwargs)
15
+ super(tool: tool, permissions: permissions, capability: :mcp)
51
16
  end
52
17
 
53
- # Forward description/parameters_schema/to_h/etc. to the wrapped tool so the
54
- # chat serializes it exactly like the raw MCP tool — but never `execute` (see
55
- # above).
56
- def respond_to_missing?(method_name, include_private = false)
57
- return true if method_name == :execute
58
-
59
- @tool.respond_to?(method_name, include_private) || super
60
- end
18
+ private
61
19
 
62
- # Delegates any unknown method to the wrapped tool (description,
63
- # parameters_schema, to_h, ...), so the wrapper serializes identically. `execute`
64
- # is handled explicitly above and never falls through here.
65
- def method_missing(method_name, *args, **kwargs, &block)
66
- if @tool.respond_to?(method_name)
67
- @tool.public_send(method_name, *args, **kwargs, &block)
68
- else
69
- super
70
- end
20
+ # The MCP gate authorizes on the tool's name, with the arguments as detail.
21
+ def authorize!(arguments)
22
+ @permissions.authorize_mcp!(name, arguments)
71
23
  end
72
24
  end
73
25
  end
@@ -1,5 +1,8 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "digest"
4
+ require "json"
5
+
3
6
  module Nexo
4
7
  # The authorization gate for a sandbox's capabilities. Each tool asks
5
8
  # `authorize!` before it touches the sandbox, so gating is provider-independent
@@ -9,10 +12,11 @@ module Nexo
9
12
  # * `:auto` — allow everything.
10
13
  # * `:read_only` — allow `:read`/`:glob`, deny `:write`/`:shell`/`:fetch`/`:search` (the default).
11
14
  # * `:ask` — defer to `on_ask`; a truthy return allows, anything else denies.
12
- # * `:approve` — durable, cross-process sibling of `:ask` (Spec 16): with no
13
- # `decision` it raises Nexo::ApprovalRequired (→ Workflow#run_agent
14
- # suspends the run); with `{approved: true}` it allows, with
15
- # `{approved: false}` it Denied denies.
15
+ # * `:approve` — durable, cross-process sibling of `:ask` (Spec 16): a call
16
+ # with no recorded decision raises Nexo::ApprovalRequired (→
17
+ # Workflow#run_agent suspends the run); a call approved in `decisions` runs,
18
+ # one declined there is Denied. Decisions are per call (0.14): approving one
19
+ # write does not approve the next.
16
20
  #
17
21
  # Capabilities are `:read`, `:glob`, `:write`, `:shell`, `:fetch`, `:search`.
18
22
  # Anything listed in `allow:` is permitted regardless of mode.
@@ -32,11 +36,41 @@ module Nexo
32
36
  # The configured Nexo permission mode (one of MODES).
33
37
  attr_reader :mode
34
38
 
35
- # The approval decision under `:approve` (Spec 16): `nil` (undecided ⇒
36
- # suspend) or a `{approved: true|false}` Hash. Writable after construction so
37
- # Workflow#run_agent can thread a resume decision into an
38
- # already-resolved `:approve` gate without rebuilding it. Ignored by every
39
+ # The per-call approval decisions under `:approve` (0.14): a Hash of
40
+ # ::approval_key → `true`/`false`, or `nil` when the gate was built without
41
+ # one. A call whose key is absent is undecided and suspends. Ignored by every
39
42
  # other mode.
43
+ attr_reader :decisions
44
+
45
+ # The key one gated call is decided under: the capability and its detail (a
46
+ # path, a command, a URL), plus a digest of the arguments when there are any
47
+ # (MCP calls). Two calls share a key only when they are the same call, which
48
+ # is what lets a resumed run recognize the call that was approved and still
49
+ # ask about a different one. Keys and nested argument keys are normalized to
50
+ # Strings, so a decision survives the JSON round trip of a run store.
51
+ def self.approval_key(capability, detail, args = nil)
52
+ key = "#{capability}:#{detail}"
53
+ return key if args.nil? || (args.respond_to?(:empty?) && args.empty?)
54
+
55
+ "#{key}:#{Digest::SHA256.hexdigest(JSON.generate(canonical(args)))[0, 16]}"
56
+ end
57
+
58
+ # `value` with Hash keys stringified and sorted, recursively, so equal
59
+ # arguments always serialize to the same JSON.
60
+ def self.canonical(value)
61
+ case value
62
+ when Hash then value.map { |k, v| [k.to_s, canonical(v)] }.sort_by(&:first).to_h
63
+ when Array then value.map { |v| canonical(v) }
64
+ else value
65
+ end
66
+ end
67
+ private_class_method :canonical
68
+
69
+ # DEPRECATED (0.14) — one answer for EVERY gated call: `nil` (undecided ⇒
70
+ # suspend) or a `{approved: true|false}` Hash. Approving this way approves
71
+ # whatever the agent does next, so Workflow#run_agent no longer uses it;
72
+ # #decisions decides per call and wins when both are set. Kept for hosts that
73
+ # pass `Agent.new(decision:)` themselves. Ignored by every other mode.
40
74
  attr_accessor :decision
41
75
 
42
76
  # `ask_when:` is an optional `->(capability, detail)` predicate that scopes
@@ -49,9 +83,10 @@ module Nexo
49
83
  # #authorize_mcp!. `approve_when:` is an alias that maps onto the same
50
84
  # predicate (there is one predicate, not two — Spec 16 Q4).
51
85
  #
52
- # `decision:` (default `nil`) seeds the `:approve` decision (see #decision).
86
+ # `decisions:` (default `nil`) seeds the per-call `:approve` decisions (see
87
+ # #decisions). `decision:` is the deprecated global answer (see #decision).
53
88
  def initialize(mode: :read_only, allow: %i[read glob], mcp_allow: [], on_ask: nil, ask_when: nil,
54
- approve_when: nil, decision: nil)
89
+ approve_when: nil, decision: nil, decisions: nil)
55
90
  raise ArgumentError, "unknown mode #{mode}" unless MODES.include?(mode)
56
91
 
57
92
  @mode = mode
@@ -60,6 +95,7 @@ module Nexo
60
95
  @on_ask = on_ask
61
96
  @ask_when = ask_when || approve_when
62
97
  @decision = decision
98
+ @decisions = decisions&.transform_keys(&:to_s)
63
99
  end
64
100
 
65
101
  # Returns a copy of this gate carrying `decision` (a `{approved: …}` Hash or
@@ -70,6 +106,13 @@ module Nexo
70
106
  dup.tap { |copy| copy.decision = decision }
71
107
  end
72
108
 
109
+ # Returns a copy of this gate carrying the per-call `decisions` (see
110
+ # #decisions), leaving the receiver untouched. Used to thread a run's recorded
111
+ # approvals into a user-supplied, class-level `:approve` `Permissions`.
112
+ def with_decisions(decisions)
113
+ dup.tap { |copy| copy.instance_variable_set(:@decisions, decisions&.transform_keys(&:to_s)) }
114
+ end
115
+
73
116
  # Authorizes `capability` (with optional `detail` passed to an `:ask` hook).
74
117
  # Returns `true` when allowed; raises Denied otherwise.
75
118
  def authorize!(capability, detail = nil)
@@ -97,16 +140,14 @@ module Nexo
97
140
  # ask_when = approve for everything.
98
141
  return true if @ask_when && !@ask_when.call(capability, detail)
99
142
 
100
- if @decision.nil?
101
- # Undecided ⇒ pause the run for a human (Branch A): the signal
102
- # propagates out of the tool loop; run_agent turns it into a suspend.
103
- raise Nexo::ApprovalRequired.new(capability, detail)
104
- elsif @decision[:approved]
105
- true
106
- else
107
- # Explicitly denied on resume ⇒ never auto-allow; the tool rescues
108
- # Denied into {error:} and the model adapts.
109
- raise Denied, "#{capability} (#{detail}) not approved"
143
+ # Undecided ⇒ pause the run for a human (Branch A): the signal propagates
144
+ # out of the tool loop; run_agent turns it into a suspend. Declined ⇒
145
+ # never auto-allow; the tool rescues Denied into {error:} and the model
146
+ # adapts.
147
+ case approval(capability, detail)
148
+ when nil then raise Nexo::ApprovalRequired.new(capability, detail)
149
+ when true then true
150
+ else raise Denied, "#{capability} (#{detail}) not approved"
110
151
  end
111
152
  end
112
153
  end
@@ -130,6 +171,14 @@ module Nexo
130
171
  @mode == :read_only && PRIVILEGED.include?(capability)
131
172
  end
132
173
 
174
+ # Whether the MCP tool `tool_name` can NEVER be authorized by this gate. The
175
+ # MCP sibling of #never_allows?, true only under `:read_only` for a name
176
+ # absent from `mcp_allow`. Agent uses it to leave such a tool out of the
177
+ # schema; #authorize_mcp! remains the gate.
178
+ def never_allows_mcp?(tool_name)
179
+ @mode == :read_only && !@mcp_allow.include?(tool_name.to_s)
180
+ end
181
+
133
182
  # Authorizes an MCP tool *call* by name. A deliberate sibling of #authorize!
134
183
  # on a separate capability axis: an MCP tool runs inside the MCP server,
135
184
  # outside the sandbox, so this gates the authority to *invoke* it — a different
@@ -168,16 +217,26 @@ module Nexo
168
217
  # decision gate as #authorize!'s :approve branch.
169
218
  return true if @mcp_allow.include?(name)
170
219
 
171
- if @decision.nil?
172
- raise Nexo::ApprovalRequired.new(:mcp, name, args)
173
- elsif @decision[:approved]
174
- true
175
- else
176
- raise Denied, "mcp tool #{name} not approved"
220
+ case approval(:mcp, name, args)
221
+ when nil then raise Nexo::ApprovalRequired.new(:mcp, name, args)
222
+ when true then true
223
+ else raise Denied, "mcp tool #{name} not approved"
177
224
  end
178
225
  else
179
226
  raise Denied, "mcp tool #{name} denied (unhandled mode #{@mode})"
180
227
  end
181
228
  end
229
+
230
+ private
231
+
232
+ # The recorded answer for one gated call under `:approve`: `true`, `false`,
233
+ # or `nil` when nobody has decided it. Per-call #decisions win; without them
234
+ # the deprecated global #decision answers every call alike.
235
+ def approval(capability, detail, args = nil)
236
+ return @decisions[self.class.approval_key(capability, detail, args)] if @decisions
237
+ return nil if @decision.nil?
238
+
239
+ @decision[:approved] ? true : false
240
+ end
182
241
  end
183
242
  end
data/lib/nexo/sandbox.rb CHANGED
@@ -54,6 +54,14 @@ module Nexo
54
54
  capability != :shell
55
55
  end
56
56
 
57
+ # What this sandbox does not contain, as short human-readable strings a host
58
+ # can show before trusting it with a model. Empty by default; Sandboxes::Local
59
+ # reports an unconfined shell and Sandboxes::Container the hardening its
60
+ # runtime cannot express.
61
+ def hardening_gaps
62
+ []
63
+ end
64
+
57
65
  # The last-modified time of `path`, used by the read-before-write + stale
58
66
  # guard for real-filesystem sandboxes. Base returns `nil` (no external
59
67
  # mutation to guard against, e.g. Virtual), which disables the guard.
@@ -7,32 +7,72 @@ require "timeout"
7
7
  module Nexo
8
8
  module Sandboxes
9
9
  # Host filesystem + shell sandbox, for trusted dev/CI use. The developer opts
10
- # into this explicitly (the default is Virtual); two guards keep a
11
- # model-driven agent contained:
10
+ # into this explicitly (the default is Virtual). What keeps a model-driven
11
+ # agent contained:
12
12
  #
13
13
  # * Path-escape guard — every `read`/`write` path is expanded against `cwd`
14
14
  # and must stay inside it, otherwise `SecurityError` is raised.
15
15
  # * Narrowed ENV — the shell sees only PATH, HOME, LANG (plus explicit
16
16
  # `env:` additions), never the full process environment.
17
+ # * A real timeout — a command that outlives `timeout:` is killed together
18
+ # with everything it started.
19
+ #
20
+ # ⚠️ The path guard covers `read`/`write`/`glob` only. A shell command is a
21
+ # host process: unless `isolation: :confined` is set it can read and write
22
+ # anywhere the user can, and reach the network. #hardening_gaps reports this
23
+ # so a host can show it.
24
+ #
25
+ # ## Confining the shell
26
+ #
27
+ # `isolation: :confined` runs each command inside an OS sandbox (Seatbelt on
28
+ # macOS, Bubblewrap on Linux) through `ruby_llm`'s sandbox contract, so it can
29
+ # write only inside `cwd`, cannot read the home directory, and has no network.
30
+ # It needs the `mxc` gem (a soft dependency: add `gem "mxc"` to the host
31
+ # Gemfile). A confined command cannot read outside `cwd` either, which
32
+ # includes a Ruby or Node installed under the home directory — grant those
33
+ # with `readable:`.
34
+ #
35
+ # ```ruby
36
+ # sandbox :local, isolation: :confined, readable: [RbConfig::CONFIG["prefix"]]
37
+ # ```
38
+ #
39
+ # `isolation:` also takes any object answering `ruby_llm`'s sandbox contract
40
+ # (`supported?` and `run`), or an `MXC::Sandbox` class or instance carrying a
41
+ # policy of your own.
17
42
  #
18
43
  # Under a fiber reactor (Spec 5) these blocking file/shell syscalls would
19
44
  # stall every other concurrent fiber. When `Nexo.config.concurrency == :async`
20
45
  # each operation is offloaded to a worker thread (see #offload); otherwise
21
- # it runs inline, byte-for-byte the Spec 1 behavior with zero overhead. The
22
- # offload never changes return values or the security properties below.
46
+ # it runs inline with zero overhead. The offload never changes return values
47
+ # or the security properties above.
23
48
  class Local < Sandbox
24
49
  # The expanded workspace root; every path is guarded to stay inside it.
25
50
  attr_reader :cwd
26
51
 
52
+ # How the shell is isolated: `:none`, `:confined`, or the sandbox object given.
53
+ attr_reader :isolation
54
+
27
55
  # Roots the sandbox at `cwd` (expanded, default `Dir.pwd`) and narrows the
28
56
  # shell environment to `PATH`/`HOME`/`LANG` plus any explicit `env:` entries.
29
- def initialize(cwd: Dir.pwd, env: {})
57
+ #
58
+ # `isolation:` is `:none` (default — the shell is an ordinary host process),
59
+ # `:confined` (an OS sandbox through the `mxc` gem), or a sandbox object.
60
+ # `readable:` lists extra paths a confined command may read. Raises
61
+ # ConfigurationError for an unknown `isolation:`; a `:confined` sandbox that
62
+ # cannot run on this machine raises on the first #shell, not here.
63
+ def initialize(cwd: Dir.pwd, env: {}, isolation: :none, readable: [])
30
64
  @cwd = File.expand_path(cwd)
31
65
  # The physical root (symlinks resolved), used by the escape guards so a
32
66
  # symlink inside cwd can't leak a target outside it.
33
67
  @real_cwd = File.exist?(@cwd) ? File.realpath(@cwd) : @cwd
34
68
  # Deliberately narrow env — never hand a model-driven shell the whole ENV.
35
- @env = ENV.to_h.slice("PATH", "HOME", "LANG").merge(env)
69
+ @env = ENV.to_h.slice("PATH", "HOME", "LANG").merge(env.transform_keys(&:to_s))
70
+ @isolation = isolation
71
+ @readable = Array(readable).map { |path| File.expand_path(path.to_s) }
72
+ return if %i[none confined].include?(isolation) || contract?(isolation) || mxc_sandbox?(isolation)
73
+
74
+ raise Nexo::ConfigurationError,
75
+ "unknown isolation #{isolation.inspect} (use :none, :confined, or a sandbox object)"
36
76
  end
37
77
 
38
78
  def read(path)
@@ -59,11 +99,28 @@ module Nexo
59
99
  end
60
100
 
61
101
  # A plain-text description of this host environment for the agent's system
62
- # prompt: the host cwd, that the real host filesystem and shell are
63
- # reachable, and that access is guarded to `cwd`.
102
+ # prompt: the host cwd, and what a shell command can and cannot reach.
64
103
  def instructions
65
- "You run on the host machine, cwd #{@cwd}. The real host filesystem " \
66
- "and shell are reachable; file access is guarded to #{@cwd}."
104
+ if confined?
105
+ "You run on the host machine, cwd #{@cwd}. File access is guarded to " \
106
+ "#{@cwd}. Shell commands run in an OS sandbox: they can write only " \
107
+ "inside #{@cwd} and have no network access."
108
+ else
109
+ "You run on the host machine, cwd #{@cwd}. The real host filesystem " \
110
+ "and shell are reachable; file access is guarded to #{@cwd}."
111
+ end
112
+ end
113
+
114
+ # Whether shell commands run inside an OS sandbox.
115
+ def confined? = @isolation != :none
116
+
117
+ # What this sandbox does NOT contain, as short human-readable strings — the
118
+ # same contract as Container#hardening_gaps. Empty when the shell is confined.
119
+ def hardening_gaps
120
+ return [] if confined?
121
+
122
+ ["shell commands are not confined: they can read and write outside #{@cwd} " \
123
+ "and reach the network (set isolation: :confined, or use a container sandbox)"]
67
124
  end
68
125
 
69
126
  # Supports all four capabilities — unlike Virtual, a real process runs
@@ -80,18 +137,111 @@ module Nexo
80
137
  File.exist?(full) ? File.mtime(full) : nil
81
138
  end
82
139
 
140
+ # Runs `command` through `sh`, in `cwd`, with the narrowed environment.
141
+ # Raises `Timeout::Error` after `timeout` seconds — and by then the command
142
+ # and every process it started have been killed.
83
143
  def shell(command, timeout: 30)
84
- offload do
85
- # ruby_llm's target Ruby has no `timeout:` kwarg on Open3.capture3
86
- # (verified), so the wall-clock bound lives in Timeout.timeout.
87
- out, err, status = Timeout.timeout(timeout) do
88
- Open3.capture3(@env, command, chdir: @cwd)
144
+ offload { confined? ? confined_shell(command, timeout) : host_shell(command, timeout) }
145
+ end
146
+
147
+ private
148
+
149
+ # The unconfined path: an ordinary host process in its own process group,
150
+ # so a timeout can kill the whole tree and not only the `sh` at its root.
151
+ # `unsetenv_others` is what makes the narrowed ENV real — without it the
152
+ # child inherits the whole process environment and `@env` only adds to it.
153
+ def host_shell(command, timeout)
154
+ out_read, out_write = IO.pipe
155
+ err_read, err_write = IO.pipe
156
+ pid = Process.spawn(@env, command, chdir: @cwd, in: File::NULL, out: out_write, err: err_write,
157
+ pgroup: true, unsetenv_others: true)
158
+ out_write.close
159
+ err_write.close
160
+ readers = [out_read, err_read].map { |io| reader(io) }
161
+ _, status = Timeout.timeout(timeout) { Process.wait2(pid) }
162
+ {stdout: readers[0].value.to_s, stderr: readers[1].value.to_s, status: status.exitstatus}
163
+ rescue Timeout::Error
164
+ kill_group(pid)
165
+ raise Timeout::Error, "command timed out after #{timeout}s and was killed"
166
+ ensure
167
+ [out_read, out_write, err_read, err_write].each { |io| io&.close unless io&.closed? }
168
+ end
169
+
170
+ # Drains one pipe on its own thread so a chatty command cannot fill the
171
+ # pipe buffer and block. A read cut short by the timeout teardown is nil.
172
+ def reader(io)
173
+ Thread.new do
174
+ io.read
175
+ rescue IOError
176
+ nil
177
+ end.tap { |thread| thread.report_on_exception = false }
178
+ end
179
+
180
+ # Kills the command's whole process group and reaps it. Best-effort: the
181
+ # group may already be gone.
182
+ def kill_group(pid)
183
+ return unless pid
184
+
185
+ Process.kill("KILL", -pid)
186
+ Process.wait(pid)
187
+ rescue Errno::ESRCH, Errno::ECHILD, Errno::EPERM
188
+ nil
189
+ end
190
+
191
+ # The confined path: `ruby_llm`'s sandbox contract. The runner adds this
192
+ # run's grants (cwd readable and writable, the declared `readable:` paths)
193
+ # to its own policy; `network: nil` keeps that policy's network access,
194
+ # which is none for the default sandbox.
195
+ def confined_shell(command, timeout)
196
+ result = runner.run("sh", "-c", command, timeout: timeout, directory: @real_cwd,
197
+ readable: [@real_cwd, *@readable], writable: [@real_cwd], env: @env, network: nil)
198
+ raise Timeout::Error, "command timed out after #{timeout}s and was killed" if result.timed_out?
199
+
200
+ {stdout: result.stdout.to_s, stderr: result.stderr.to_s, status: result.exit_code}
201
+ end
202
+
203
+ # The object that runs a confined command, resolved once. Raises
204
+ # ConfigurationError when it cannot run on this machine, so a host that
205
+ # asked for confinement never silently gets an unconfined shell.
206
+ def runner
207
+ @runner ||= begin
208
+ candidate = contract?(@isolation) ? @isolation : mxc_runner
209
+ unless candidate.supported?
210
+ reason = candidate.reason if candidate.respond_to?(:reason)
211
+ raise Nexo::ConfigurationError,
212
+ ["the shell sandbox cannot run on this machine.", reason].compact.join(" ")
89
213
  end
90
- {stdout: out, stderr: err, status: status.exitstatus}
214
+ candidate
91
215
  end
92
216
  end
93
217
 
94
- private
218
+ # Wraps an `MXC::Sandbox` (the default one for `:confined`, or the host's
219
+ # own) in `ruby_llm`'s adapter, which speaks the sandbox contract.
220
+ def mxc_runner
221
+ require_mxc!
222
+ ::RubyLLM::Sandbox.resolve((@isolation == :confined) ? ::MXC::Sandbox.new : @isolation)
223
+ end
224
+
225
+ # `mxc` is a soft dependency, like `async`: required only on this path.
226
+ def require_mxc!
227
+ require "mxc"
228
+ rescue LoadError
229
+ raise Nexo::MissingDependencyError,
230
+ "isolation: :confined needs the mxc gem — add `gem \"mxc\"` to your Gemfile"
231
+ end
232
+
233
+ # Whether `value` answers `ruby_llm`'s sandbox contract.
234
+ def contract?(value)
235
+ value.respond_to?(:run) && value.respond_to?(:supported?)
236
+ end
237
+
238
+ # Whether `value` is an `MXC::Sandbox` class or instance. False when the
239
+ # gem is not loaded: a host holding one has necessarily loaded it.
240
+ def mxc_sandbox?(value)
241
+ return false unless defined?(::MXC::Sandbox)
242
+
243
+ value.is_a?(::MXC::Sandbox) || (value.is_a?(Class) && value <= ::MXC::Sandbox)
244
+ end
95
245
 
96
246
  # Runs a blocking block off the reactor when async concurrency is enabled,
97
247
  # inline otherwise. The decision is driven by config, not by
@@ -116,6 +266,8 @@ module Nexo
116
266
  end
117
267
  end
118
268
 
269
+ # `path` expanded against `cwd`, or `SecurityError` when it would land
270
+ # outside the sandbox.
119
271
  def absolute(path)
120
272
  full = File.expand_path(path, @cwd)
121
273
  # Check the PHYSICAL location (symlinks resolved), not the lexical path, so
@@ -29,13 +29,14 @@ module Nexo
29
29
  # Resolves the `{ type:, **opts }` Hash form. `:docker`/`:apple` pass every
30
30
  # other key straight through to Sandboxes::Container (so an explicit Hash
31
31
  # `cwd:` or the `/workspace` default wins — never the host `cwd`); `:local`
32
- # honors an explicit Hash `cwd:`, otherwise falls back to the host `cwd`.
32
+ # honors an explicit Hash `cwd:`, otherwise falls back to the host `cwd`, and
33
+ # passes every other key (`env:`, `isolation:`, `readable:`) to Sandboxes::Local.
33
34
  def resolve_hash(opts, cwd)
34
35
  type = opts.fetch(:type)
35
36
  rest = opts.except(:type)
36
37
  case type
37
38
  when :docker, :apple then Container.new(runtime: type, **rest)
38
- when :local then Local.new(cwd: rest.fetch(:cwd, cwd))
39
+ when :local then Local.new(**rest, cwd: rest.fetch(:cwd, cwd))
39
40
  else raise Nexo::ConfigurationError, "unknown sandbox type: #{type.inspect}"
40
41
  end
41
42
  end
@@ -60,15 +60,15 @@ module Nexo
60
60
  end
61
61
 
62
62
  # Resolve ONCE: reject if any resolved address is unsafe, then connect
63
- # pinned to that same vetted IP so DNS can't rebind to a private address
64
- # between the check and the connect. Unresolvable hosts fail open to a
65
- # hostname connect (which then errors naturally), preserving prior behavior.
63
+ # pinned to a vetted IP so DNS can't rebind to a private address between
64
+ # the check and the connect. Unresolvable hosts fail open to a hostname
65
+ # connect (which then errors naturally), preserving prior behavior.
66
66
  addresses = resolve(uri.host)
67
67
  if addresses.any? { |ip| unsafe_ip?(ip) }
68
68
  raise Permissions::Denied, "private/loopback address refused: #{uri.host}"
69
69
  end
70
70
 
71
- {body: get(uri, addresses.first).byteslice(0, MAX_BYTES)}
71
+ {body: get_any(uri, addresses).byteslice(0, MAX_BYTES)}
72
72
  rescue Permissions::Denied => e
73
73
  {error: e.message}
74
74
  rescue Nexo::ApprovalRequired
@@ -114,6 +114,36 @@ module Nexo
114
114
  UNSAFE_RANGES.any? { |range| range.include?(addr) }
115
115
  end
116
116
 
117
+ # Failures that mean "this address cannot be reached", as opposed to "the
118
+ # server answered badly". Only these move on to the next vetted address, so
119
+ # a request is never sent twice.
120
+ CONNECT_ERRORS = [
121
+ Errno::EHOSTUNREACH, Errno::ENETUNREACH, Errno::ECONNREFUSED, Errno::EADDRNOTAVAIL,
122
+ Net::OpenTimeout, SocketError
123
+ ].freeze
124
+ private_constant :CONNECT_ERRORS
125
+
126
+ # How many resolved addresses to try. Each attempt can wait out the 5s
127
+ # connect timeout, so this bounds the worst case.
128
+ MAX_ADDRESSES = 4
129
+ private_constant :MAX_ADDRESSES
130
+
131
+ # GETs `uri` from the first vetted address that accepts a connection. A host
132
+ # commonly resolves to both an IPv6 and an IPv4 address, and a machine with
133
+ # no IPv6 route cannot reach the first — trying only that one made every
134
+ # fetch to such a host fail. Every address tried was vetted by the caller.
135
+ def get_any(uri, addresses)
136
+ return get(uri) if addresses.empty?
137
+
138
+ failure = nil
139
+ addresses.first(MAX_ADDRESSES).each do |ip|
140
+ return get(uri, ip)
141
+ rescue *CONNECT_ERRORS => e
142
+ failure = e
143
+ end
144
+ raise failure
145
+ end
146
+
117
147
  # GETs `uri`, pinned to the pre-vetted `ip` when one was resolved (so the
118
148
  # socket connects to the exact address the guard approved — no re-resolution,
119
149
  # no DNS-rebinding window). `ip` may be nil for an unresolvable host, in which
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "timeout"
4
+
3
5
  module Nexo
4
6
  module Tools
5
7
  # Runs a shell command in the agent's sandbox. Authorizes `:shell` first.
@@ -18,7 +20,8 @@ module Nexo
18
20
 
19
21
  # Authorizes `:shell`, runs `command`, and returns
20
22
  # `{ stdout:, stderr:, status: }` (stdout/stderr truncated via OutputTruncator) — or
21
- # `{ error: ... }` on a denial or a sandbox with no shell.
23
+ # `{ error: ... }` on a denial, a sandbox with no shell, or a command that
24
+ # ran past the sandbox's timeout (it has been killed by then).
22
25
  def execute(command:)
23
26
  @permissions.authorize!(:shell, command)
24
27
  out = @sandbox.shell(command)
@@ -27,7 +30,7 @@ module Nexo
27
30
  stderr: OutputTruncator.call(out[:stderr]),
28
31
  status: out[:status]
29
32
  }
30
- rescue Permissions::Denied, NotImplementedError => e
33
+ rescue Permissions::Denied, NotImplementedError, Timeout::Error => e
31
34
  {error: e.message}
32
35
  end
33
36
  end
data/lib/nexo/version.rb CHANGED
@@ -2,5 +2,5 @@
2
2
 
3
3
  module Nexo
4
4
  # The gem version (also used as `spec.version` in the gemspec).
5
- VERSION = "0.13.0"
5
+ VERSION = "0.14.0"
6
6
  end