nexo_ai 0.14.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +56 -0
- data/docs/loops.md +5 -0
- data/docs/mcp.md +70 -0
- data/docs/sandboxes.md +27 -3
- data/docs/tools.md +53 -0
- data/lib/nexo/agent.rb +152 -26
- data/lib/nexo/configuration.rb +16 -0
- data/lib/nexo/gated_tool.rb +9 -2
- data/lib/nexo/mcp/credential_store.rb +86 -0
- data/lib/nexo/mcp.rb +51 -3
- data/lib/nexo/sandbox.rb +20 -0
- data/lib/nexo/sandbox_file_store.rb +87 -0
- data/lib/nexo/sandboxes/container.rb +1 -1
- data/lib/nexo/sandboxes/container_runner.rb +140 -0
- data/lib/nexo/sandboxes/local.rb +21 -40
- data/lib/nexo/sandboxes/subprocess.rb +62 -0
- data/lib/nexo/sandboxes/virtual.rb +7 -0
- data/lib/nexo/version.rb +1 -1
- data/lib/nexo.rb +16 -0
- data/sig/nexo/agent.rbs +4 -1
- metadata +5 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: d4e02e6148838d856eb464d7105863702c3b004a83b040ad9939d487eb2523d9
|
|
4
|
+
data.tar.gz: d0ed856bdf72315f79335e42ea6e037ca969c97fbc13035109ec81d986f32a81
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 50c7cdcc744e4b47e93816a88dfea4d7b1bcfe6fb7d538d1dc0eac01894b2299b0c06dbb19a0ed5acb4c569f377cc7816c3e74100599a67a3e086cf04e8f6b15
|
|
7
|
+
data.tar.gz: 49e9977881f2ca3fe49a3afbb45e253d945f34da81d624b29a65ab6789d1b22851270dc532f9d59a605aae9eb30d3e9d63cf94b446ba00465399e807f3635b3c
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,61 @@
|
|
|
1
1
|
## [Unreleased]
|
|
2
2
|
|
|
3
|
+
## [0.15.0] - 2026-11-26
|
|
4
|
+
|
|
5
|
+
Six things taken from ruby_llm 2.2, each behind Nexo's permission gate. Everything new is
|
|
6
|
+
opt-in except one default: a cap on tool calls per round.
|
|
7
|
+
|
|
8
|
+
**Upgrading:** one default changed. A model response may now run at most 20 tool calls;
|
|
9
|
+
the rest are answered with an error and the model can ask again. Raise or remove it with
|
|
10
|
+
`Nexo.config.tool_calls_per_round`. A custom sandbox class is unaffected unless you turn
|
|
11
|
+
on `file_tools :core`, which needs `#files`.
|
|
12
|
+
|
|
13
|
+
### Added
|
|
14
|
+
|
|
15
|
+
- **`Nexo.config.tool_calls_per_round`** (default `20`). `max_turns` counts model responses,
|
|
16
|
+
and one response may hold any number of tool calls, so a round was unbounded. Passed to
|
|
17
|
+
ruby_llm as `with_tool_options(calls:)`.
|
|
18
|
+
- **`context_budget` macro on `Nexo::Agent`**, a per-agent `Chat#with_context_budget`. It
|
|
19
|
+
bounds what any tool returns as a share of the model's context window. Off unless declared.
|
|
20
|
+
- **OAuth for MCP servers.** `mcp ..., oauth: true` (or a Hash of options) hands the server to
|
|
21
|
+
ruby_llm's MCP OAuth. `Agent.new(mcp_owner:)` says whose credentials to use,
|
|
22
|
+
`Agent#mcp_server(name)` exposes the server so a host can drive `authorization_url` /
|
|
23
|
+
`authorize` / `deauthorize`, and `Nexo::AuthorizationRequired` is raised before an
|
|
24
|
+
unauthorized server is used. `Nexo::MCP::CredentialStore` keeps tokens on disk for hosts
|
|
25
|
+
without ActiveRecord (plain JSON, `0600`, not encrypted).
|
|
26
|
+
- **`file_tools :core`.** Attaches ruby_llm's `list_files`, `read_file`, `search_files`,
|
|
27
|
+
`write_file` and `edit_file` over the agent's sandbox through the new
|
|
28
|
+
`Nexo::SandboxFileStore`, each wrapped in `Nexo::GatedTool`. Adds editing part of a file,
|
|
29
|
+
searching contents, and a read-before-write guard that works on every sandbox. Nexo's own
|
|
30
|
+
three tools remain the default until 1.0.
|
|
31
|
+
- **`Sandbox#files` and `#file_size`** on every sandbox (a container or remote sandbox lists
|
|
32
|
+
through its shell).
|
|
33
|
+
- **`Nexo::Sandboxes::ContainerRunner`** answers ruby_llm's sandbox contract with a throwaway,
|
|
34
|
+
hardened container per command. It works as `Sandboxes::Local`'s `isolation:` and as
|
|
35
|
+
`RubyLLM.config.sandbox`.
|
|
36
|
+
- `Nexo::GatedTool` takes `detail:`, a callable naming what a call acts on.
|
|
37
|
+
|
|
38
|
+
### Fixed
|
|
39
|
+
|
|
40
|
+
- **Container reconnect compared a short id with a full one.** The lookup now asks for the
|
|
41
|
+
full id (`ps -aq --no-trunc`). Found by running the reconnect smoke test against Docker for
|
|
42
|
+
the first time.
|
|
43
|
+
|
|
44
|
+
### Verified
|
|
45
|
+
|
|
46
|
+
- The container sandbox and its reconnect path, live against Docker 29 (through OrbStack).
|
|
47
|
+
Both were recorded as unverified since they shipped. Apple `container` parity is still not
|
|
48
|
+
verified.
|
|
49
|
+
- The confined local shell on Linux (Bubblewrap), in CI: a write and a read outside the
|
|
50
|
+
workspace and a network connection are refused.
|
|
51
|
+
- OAuth is tested against ruby_llm's real MCP class but not against a live authorization
|
|
52
|
+
server.
|
|
53
|
+
|
|
54
|
+
### Changed
|
|
55
|
+
|
|
56
|
+
- `Sandboxes::Local#shell` and `ContainerRunner` share `Sandboxes::Subprocess`, the
|
|
57
|
+
kill-on-timeout runner introduced in 0.14.
|
|
58
|
+
|
|
3
59
|
## [0.14.0] - 2026-11-26
|
|
4
60
|
|
|
5
61
|
A security release. Three guarantees Nexo documented did not hold and now do, and a tool
|
data/docs/loops.md
CHANGED
|
@@ -49,6 +49,11 @@ end
|
|
|
49
49
|
Inside a workflow the error fails the run like any other (`status: "failed"`, re-raised),
|
|
50
50
|
so a runaway agent cannot keep spending.
|
|
51
51
|
|
|
52
|
+
`max_turns` counts model responses, and one response may ask for any number of tool calls.
|
|
53
|
+
`Nexo.config.tool_calls_per_round` (default `20`) caps how many of them run: calls past the
|
|
54
|
+
cap are answered with an error straight away and never execute. With the defaults a prompt
|
|
55
|
+
is bounded at 25 rounds of 20 calls. Set it to `nil` for no cap.
|
|
56
|
+
|
|
52
57
|
Things to know:
|
|
53
58
|
|
|
54
59
|
- **Upgrading from 0.12:** `max_turns` used to be telemetry only — a run that passed it
|
data/docs/mcp.md
CHANGED
|
@@ -152,6 +152,76 @@ not police `ruby_llm`'s own debug logging (`RUBYLLM_DEBUG`) — that boundary is
|
|
|
152
152
|
> The `mcp` macro and `mcp_allow` are unchanged.
|
|
153
153
|
|
|
154
154
|
|
|
155
|
+
## HTTP servers + OAuth
|
|
156
|
+
|
|
157
|
+
For a server that signs users in — Linear, Slack, Google, your own — pass `oauth:` in place
|
|
158
|
+
of `token:`. `ruby_llm` runs the whole flow (discovery, client registration, PKCE, token
|
|
159
|
+
refresh, DPoP). Nexo adds three things: whose credentials are used, a clear stop before an
|
|
160
|
+
unauthorized server is touched, and somewhere to keep the tokens outside Rails.
|
|
161
|
+
|
|
162
|
+
```ruby
|
|
163
|
+
class Assistant < Nexo::Agent
|
|
164
|
+
model ENV.fetch("NEXO_MODEL")
|
|
165
|
+
mcp :linear, transport: :http, url: "https://mcp.linear.app/mcp", oauth: true
|
|
166
|
+
mcp :slack, transport: :http, url: "https://mcp.slack.com/mcp",
|
|
167
|
+
oauth: {client_id: ENV["SLACK_CLIENT_ID"], client_secret: ENV["SLACK_CLIENT_SECRET"]}
|
|
168
|
+
mcp_allow "list_issues", "search_messages"
|
|
169
|
+
end
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
`oauth:` is `true` or a Hash of the options `RubyLLM::MCP.oauth` takes: `client_id:`,
|
|
173
|
+
`client_secret:`, `scopes:`, `grant:`, `private_key:`, `assertion:`, `identity_provider:`,
|
|
174
|
+
`authorization_params:`.
|
|
175
|
+
|
|
176
|
+
**Whose credentials.** Pass the owner when you build the agent:
|
|
177
|
+
|
|
178
|
+
```ruby
|
|
179
|
+
agent = Assistant.new(mcp_owner: current_user)
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
Credentials are stored per owner and server. The owner must be a record with a GlobalID, or a
|
|
183
|
+
String, Symbol or Integer you keep stable. Anything else is refused, because it would be
|
|
184
|
+
filed under a name that changes every run.
|
|
185
|
+
|
|
186
|
+
**Authorizing.** `agent.mcp_server(name)` is the `ruby_llm` server object. Send the user
|
|
187
|
+
to its authorization URL and hand the callback's parameters back:
|
|
188
|
+
|
|
189
|
+
```ruby
|
|
190
|
+
linear = agent.mcp_server(:linear)
|
|
191
|
+
redirect_to linear.authorization_url(redirect_uri: mcp_callback_url), allow_other_host: true unless linear.authorized?
|
|
192
|
+
|
|
193
|
+
# in the callback action
|
|
194
|
+
Assistant.new(mcp_owner: current_user).mcp_server(:linear).authorize(params)
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`#deauthorize` forgets the owner's credentials.
|
|
198
|
+
|
|
199
|
+
**Before it is authorized.** Building the chat raises `Nexo::AuthorizationRequired`, whose
|
|
200
|
+
`#server` names the one to authorize. It is raised before any request is made, from the
|
|
201
|
+
credential store alone. Servers on the `client_credentials` or JWT-bearer grant need no
|
|
202
|
+
person and fetch their own token on first use.
|
|
203
|
+
|
|
204
|
+
**Where the tokens live.** `ruby_llm` keeps them in memory by default and in an encrypted
|
|
205
|
+
table under Rails (`rails g ruby_llm:install`). For a host with neither, Nexo ships a store
|
|
206
|
+
on disk:
|
|
207
|
+
|
|
208
|
+
```ruby
|
|
209
|
+
RubyLLM.configure do |config|
|
|
210
|
+
config.mcp_credential_store = Nexo::MCP::CredentialStore.new(dir: "~/.local/state/my-app/mcp")
|
|
211
|
+
end
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
⚠️ These files hold live access and refresh tokens as plain JSON. They are not encrypted.
|
|
215
|
+
The directory is created `0700` and each file `0600`, which is the protection an SSH key
|
|
216
|
+
has and no more. Do not put the directory anywhere shared or synced.
|
|
217
|
+
|
|
218
|
+
The permission gate is unchanged by any of this: an OAuth server's tools are still denied
|
|
219
|
+
unless `mcp_allow` lists them, and under `:approve` each call still asks.
|
|
220
|
+
|
|
221
|
+
> Not verified end to end. The settings, the owner key, the authorization check and the
|
|
222
|
+
> store are tested against `ruby_llm`'s real MCP class; a full sign-in against a live
|
|
223
|
+
> authorization server has not been run from Nexo.
|
|
224
|
+
|
|
155
225
|
## Decorating MCP tools
|
|
156
226
|
|
|
157
227
|
`wrap_mcp_tool` is called once per MCP tool, after it is wrapped in a permission-gating
|
data/docs/sandboxes.md
CHANGED
|
@@ -75,11 +75,35 @@ Things to know:
|
|
|
75
75
|
- **Bring your own policy.** `isolation:` also takes an `MXC::Sandbox` class or instance, or any
|
|
76
76
|
object answering `supported?` and `run(*command, timeout:, readable:, writable:, directory:,
|
|
77
77
|
env:, network:)`.
|
|
78
|
-
- **Verified on macOS (Seatbelt), `mxc` 0.4.1:** a write
|
|
79
|
-
|
|
78
|
+
- **Verified on macOS (Seatbelt) and on Linux (Bubblewrap, in CI), `mxc` 0.4.1:** a write
|
|
79
|
+
outside `cwd`, a read of a file outside it and a network connection were all refused. A
|
|
80
|
+
Linux host must allow unprivileged user namespaces for Bubblewrap; GitHub's Ubuntu runners
|
|
81
|
+
do.
|
|
80
82
|
- Unconfined remains the default in 0.14. Use a [container](#container-sandbox--docker--apple-container)
|
|
81
83
|
when you need a different filesystem, not only a fence.
|
|
82
84
|
|
|
85
|
+
### A container per command — `ContainerRunner`
|
|
86
|
+
|
|
87
|
+
`Nexo::Sandboxes::ContainerRunner` answers the same contract with a throwaway container
|
|
88
|
+
for each command, hardened like the container sandbox (no network, capabilities dropped,
|
|
89
|
+
read-only root). Use it where a process sandbox is not available or not enough:
|
|
90
|
+
|
|
91
|
+
```ruby
|
|
92
|
+
runner = Nexo::Sandboxes::ContainerRunner.new(image: "ruby:3.3-slim")
|
|
93
|
+
|
|
94
|
+
class Builder < Nexo::Agent
|
|
95
|
+
sandbox :local, isolation: runner # files on the host, commands in a container
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
RubyLLM.configure { |config| config.sandbox = runner } # or for ruby_llm's own run_code
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
The working directory is bound into the container at its own path, read-write, and nothing
|
|
102
|
+
else of the host is visible. Each command pays a container start. It cannot honour a host
|
|
103
|
+
allow-list: every run has the network the runner was built with, none by default. Verified
|
|
104
|
+
on Docker 29: a command wrote inside the workspace, could not read a file outside it, had
|
|
105
|
+
no network, and was killed at its timeout.
|
|
106
|
+
|
|
83
107
|
### Two fixes in 0.14 that change behaviour
|
|
84
108
|
|
|
85
109
|
- **The narrowed environment is now real.** Before 0.14 the shell inherited the whole process
|
|
@@ -416,7 +440,7 @@ The container starts **lazily** on first tool use and its id is memoized.
|
|
|
416
440
|
`Workflow.execute`'s `ensure` (on done, suspended, or failed), never per `run_agent` call.
|
|
417
441
|
- **Reconnect (`name:` + `reconnect: true`):** every container is tagged at `run` with an
|
|
418
442
|
**exact identity label** — `--label nexo.sandbox.id=<name>`. On start the sandbox looks up
|
|
419
|
-
that container by the **exact label filter** (`docker ps -
|
|
443
|
+
that container by the **exact label filter** (`docker ps -aq --no-trunc -f label=nexo.sandbox.id=<name>`),
|
|
420
444
|
**not** a name substring, and reuses/restarts it instead of creating a new one; `close`
|
|
421
445
|
leaves it running/stopped so a later sandbox with the same name reattaches. The default
|
|
422
446
|
container name is `nexo-<run-id>`.
|
data/docs/tools.md
CHANGED
|
@@ -21,6 +21,20 @@ ever allow:
|
|
|
21
21
|
`ReadFile` and `Glob` are always attached. This is a cost and description-accuracy measure, not
|
|
22
22
|
a security boundary: `Permissions#authorize!` remains the gate and still denies at call time.
|
|
23
23
|
|
|
24
|
+
To bound what **any** tool returns — an MCP tool, one of your own — declare a context
|
|
25
|
+
budget. It is `ruby_llm`'s `with_context_budget`, per agent:
|
|
26
|
+
|
|
27
|
+
```ruby
|
|
28
|
+
class Researcher < Nexo::Agent
|
|
29
|
+
context_budget per_result: 0.25, per_request: 0.7
|
|
30
|
+
end
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
`per_result:` cuts a single result longer than that share of the model's context window;
|
|
34
|
+
`per_request:` leaves the oldest results out of a request that would exceed its share. Both
|
|
35
|
+
need the window, which `ruby_llm` knows only for models in its registry: for a local or
|
|
36
|
+
unregistered model add `window: 128_000`, or the budget does nothing.
|
|
37
|
+
|
|
24
38
|
`Shell` truncates unbounded command output before it reaches the model:
|
|
25
39
|
|
|
26
40
|
- **Shell output truncation (`Nexo::OutputTruncator`).** Unbounded command output (`npm install`,
|
|
@@ -44,6 +58,45 @@ ever allow:
|
|
|
44
58
|
the stale check (read-before-write is the primary guard). Clobber-safety within a session only —
|
|
45
59
|
no versioning, locking, or VCS semantics.
|
|
46
60
|
|
|
61
|
+
## `file_tools :core` — `ruby_llm`'s file tools over your sandbox
|
|
62
|
+
|
|
63
|
+
`ruby_llm` 2.2 has its own file tools. Nexo can attach those in place of its own three,
|
|
64
|
+
over the same sandbox and behind the same permission gate:
|
|
65
|
+
|
|
66
|
+
```ruby
|
|
67
|
+
class Editor < Nexo::Agent
|
|
68
|
+
sandbox :local
|
|
69
|
+
file_tools :core
|
|
70
|
+
permissions Nexo::Permissions.new(mode: :read_only, allow: %i[read glob write])
|
|
71
|
+
end
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
| | `:nexo` (default) | `:core` |
|
|
75
|
+
|---|---|---|
|
|
76
|
+
| Tools | `read_file`, `write_file`, `glob` (as `nexo--tools--…`) | `list_files`, `read_file`, `search_files`, `write_file`, `edit_file` |
|
|
77
|
+
| Change part of a file | no, rewrite the whole file | yes, `edit_file` |
|
|
78
|
+
| Search file contents | no | yes, `search_files` |
|
|
79
|
+
| Read-before-write guard | by modification time, real filesystems only | by content digest, on every sandbox including `:virtual` |
|
|
80
|
+
| Large files | whole file, capped at 200 KB | paged: 1,000 lines or 20,000 characters a call |
|
|
81
|
+
| Dotfiles | listed | hidden |
|
|
82
|
+
|
|
83
|
+
Reading, listing and searching are `:read`; writing and editing are `:write`, and under
|
|
84
|
+
`:read_only` the two writing tools are not attached. Under `:approve`, a write suspends the
|
|
85
|
+
run with the file's path as the detail.
|
|
86
|
+
|
|
87
|
+
Things to know before switching:
|
|
88
|
+
|
|
89
|
+
- **The tool names and result shapes differ.** A skill that names `nexo--tools--write_file`,
|
|
90
|
+
or a host that reads tool events, needs updating.
|
|
91
|
+
- **Listing goes through the sandbox.** `:virtual` and `:local` answer directly. A container
|
|
92
|
+
or remote sandbox runs one `find`, and reads each file to report its size.
|
|
93
|
+
- **There is no delete**, because a sandbox has none.
|
|
94
|
+
- The tool classes are internal to `ruby_llm`; Nexo's tests drive them through the real
|
|
95
|
+
loop, which is what will catch a change there.
|
|
96
|
+
|
|
97
|
+
Set `Nexo.config.file_tools = :core` to switch every agent. `:core` is planned as the
|
|
98
|
+
default in 1.0.
|
|
99
|
+
|
|
47
100
|
## Tools of your own — the `tools` macro
|
|
48
101
|
|
|
49
102
|
Declare a `RubyLLM::Tool` you wrote on the agent, and say what it does in Nexo's terms:
|
data/lib/nexo/agent.rb
CHANGED
|
@@ -25,6 +25,7 @@ module Nexo
|
|
|
25
25
|
CONFIG_IVARS = %i[
|
|
26
26
|
@model @assume_model_exists @provider @sandbox @permissions @instructions
|
|
27
27
|
@skills @mcp @mcp_allow @fetch_allow @search_backend @requires @produces @tools
|
|
28
|
+
@context_budget @file_tools
|
|
28
29
|
].freeze
|
|
29
30
|
|
|
30
31
|
class << self
|
|
@@ -90,6 +91,50 @@ module Nexo
|
|
|
90
91
|
value.nil? ? @instructions : (@instructions = value)
|
|
91
92
|
end
|
|
92
93
|
|
|
94
|
+
# Which file tools the agent gets. With no argument it reads the choice
|
|
95
|
+
# (default: Nexo.config.file_tools, which is `:nexo`).
|
|
96
|
+
#
|
|
97
|
+
# * `:nexo` — Nexo's own `ReadFile`, `WriteFile` and `Glob`.
|
|
98
|
+
# * `:core` — `ruby_llm`'s `list_files`, `read_file`, `search_files`,
|
|
99
|
+
# `write_file` and `edit_file`, over the agent's sandbox (see
|
|
100
|
+
# SandboxFileStore). Adds editing part of a file, searching contents, and
|
|
101
|
+
# a read-before-write guard that works on every sandbox.
|
|
102
|
+
#
|
|
103
|
+
# Either way the tools are behind the same permission gate: reading and
|
|
104
|
+
# listing are `:read`, writing and editing are `:write`, and under
|
|
105
|
+
# `:read_only` the writing tools are not attached at all. The two sets use
|
|
106
|
+
# different tool names and return different shapes, so a skill that names
|
|
107
|
+
# `nexo--tools--write_file`, or a host that reads tool events, must be
|
|
108
|
+
# updated when switching. `:core` is planned as the default in 1.0.
|
|
109
|
+
def file_tools(value = nil)
|
|
110
|
+
value.nil? ? (@file_tools || Nexo.config.file_tools) : (@file_tools = value)
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# Keeps tool results within shares of the model's context window — a
|
|
114
|
+
# pass-through to `ruby_llm`'s `Chat#with_context_budget`. With no argument
|
|
115
|
+
# it reads the declared budget (default `nil`: `ruby_llm`'s own
|
|
116
|
+
# `config.context_budget`, which is off unless you set it).
|
|
117
|
+
#
|
|
118
|
+
# ```ruby
|
|
119
|
+
# class Researcher < Nexo::Agent
|
|
120
|
+
# context_budget per_result: 0.25, per_request: 0.7
|
|
121
|
+
# end
|
|
122
|
+
# ```
|
|
123
|
+
#
|
|
124
|
+
# `per_result:` cuts a single tool result longer than that share and tells
|
|
125
|
+
# the model to ask for less; `per_request:` leaves the oldest tool results
|
|
126
|
+
# out of a request that would exceed that share. Both need the model's
|
|
127
|
+
# context window, which `ruby_llm` knows only for models in its registry —
|
|
128
|
+
# for a local or unregistered model pass `window:` (tokens), or the budget
|
|
129
|
+
# does nothing and `ruby_llm` warns once. This bounds what ANY tool returns,
|
|
130
|
+
# including MCP tools and tools of your own; OutputTruncator still bounds
|
|
131
|
+
# shell output by lines, with or without a known window.
|
|
132
|
+
def context_budget(budget = nil, **shares)
|
|
133
|
+
return @context_budget if budget.nil? && shares.empty?
|
|
134
|
+
|
|
135
|
+
@context_budget = (budget || {}).to_h.merge(shares)
|
|
136
|
+
end
|
|
137
|
+
|
|
93
138
|
# Declares the skills attached to this agent. With no args it returns the
|
|
94
139
|
# configured list (default `[]`); with args it ACCUMULATES the names
|
|
95
140
|
# (deduped), so multiple `skills` lines add up instead of the last one
|
|
@@ -267,8 +312,12 @@ module Nexo
|
|
|
267
312
|
# gate — they never widen capability. Workflow#run_agent passes the approvals
|
|
268
313
|
# recorded on the run. `decision:` is the deprecated global form (one
|
|
269
314
|
# `{approved:}` answer for every gated call).
|
|
315
|
+
#
|
|
316
|
+
# `mcp_owner:` (0.15) is whose OAuth credentials this agent's `oauth:` MCP
|
|
317
|
+
# servers use — a user record, or a stable String/Integer id.
|
|
270
318
|
def initialize(cwd: Dir.pwd, model: nil, sandbox: nil, permissions: nil, decision: nil, decisions: nil,
|
|
271
|
-
loop: Loops::RubyLLM.new)
|
|
319
|
+
mcp_owner: nil, loop: Loops::RubyLLM.new)
|
|
320
|
+
@mcp_owner = mcp_owner
|
|
272
321
|
@cwd = cwd
|
|
273
322
|
@model = model || self.class.model || Nexo.config.default_model
|
|
274
323
|
if @model.nil?
|
|
@@ -314,21 +363,7 @@ module Nexo
|
|
|
314
363
|
c = base || RubyLLM.chat(**chat_model_options)
|
|
315
364
|
c = apply_instructions(c)
|
|
316
365
|
|
|
317
|
-
|
|
318
|
-
# (enforces the read-before-write + stale guard) — R4.
|
|
319
|
-
tracker = ReadTracker.new
|
|
320
|
-
# A sandbox tool is attached only when the agent could actually use it, on
|
|
321
|
-
# BOTH axes: the sandbox has to support the capability (R2 — a :virtual
|
|
322
|
-
# sandbox has no shell) and the gate must not deny it statically (a
|
|
323
|
-
# :read_only agent can never be authorized for :write or :shell). Otherwise
|
|
324
|
-
# a guaranteed failure sits in the tool schema on every turn and models do
|
|
325
|
-
# try it. This is the same attach-time gating apply_fetch/apply_search
|
|
326
|
-
# already apply; #authorize! stays the actual boundary either way.
|
|
327
|
-
tools = [Tools::ReadFile.new(sandbox: @sandbox, permissions: @permissions, tracker: tracker)]
|
|
328
|
-
unless @permissions.never_allows?(:write)
|
|
329
|
-
tools << Tools::WriteFile.new(sandbox: @sandbox, permissions: @permissions, tracker: tracker)
|
|
330
|
-
end
|
|
331
|
-
tools << Tools::Glob.new(sandbox: @sandbox, permissions: @permissions)
|
|
366
|
+
tools = file_tool_set
|
|
332
367
|
if @sandbox.supports?(:shell) && !@permissions.never_allows?(:shell)
|
|
333
368
|
tools << Tools::Shell.new(sandbox: @sandbox, permissions: @permissions)
|
|
334
369
|
end
|
|
@@ -337,7 +372,8 @@ module Nexo
|
|
|
337
372
|
apply_mcp(c)
|
|
338
373
|
apply_fetch(c)
|
|
339
374
|
apply_search(c)
|
|
340
|
-
|
|
375
|
+
apply_tool_options(c)
|
|
376
|
+
apply_context_budget(c)
|
|
341
377
|
apply_tool_backstop(c)
|
|
342
378
|
c
|
|
343
379
|
end
|
|
@@ -428,6 +464,26 @@ module Nexo
|
|
|
428
464
|
|
|
429
465
|
public
|
|
430
466
|
|
|
467
|
+
# The `ruby_llm` MCP server declared as `name` with the `mcp` macro, built
|
|
468
|
+
# with this agent's `mcp_owner`. For an `oauth:` server this is where a host
|
|
469
|
+
# drives the authorization (0.15):
|
|
470
|
+
#
|
|
471
|
+
# ```ruby
|
|
472
|
+
# agent = Assistant.new(mcp_owner: current_user)
|
|
473
|
+
# linear = agent.mcp_server(:linear)
|
|
474
|
+
# redirect_to linear.authorization_url(redirect_uri: callback_url) unless linear.authorized?
|
|
475
|
+
# # ...and in the callback action:
|
|
476
|
+
# agent.mcp_server(:linear).authorize(params)
|
|
477
|
+
# ```
|
|
478
|
+
#
|
|
479
|
+
# `#deauthorize` forgets the owner's credentials. Raises ConfigurationError
|
|
480
|
+
# for a name that was never declared.
|
|
481
|
+
def mcp_server(name)
|
|
482
|
+
index = self.class.mcp.index { |cfg| cfg[:name].to_s == name.to_s } or
|
|
483
|
+
raise ConfigurationError, "#{self.class} declares no mcp :#{name}"
|
|
484
|
+
mcp_clients[index]
|
|
485
|
+
end
|
|
486
|
+
|
|
431
487
|
# Releases any MCP server connections held by this agent instance. Clients are
|
|
432
488
|
# memoized on the instance and reused across prompts (Spec 6 lifecycle default),
|
|
433
489
|
# so a long-lived agent holding stdio/SSE servers should call `#close` when
|
|
@@ -542,13 +598,31 @@ module Nexo
|
|
|
542
598
|
def apply_mcp(chat)
|
|
543
599
|
return if self.class.mcp.empty?
|
|
544
600
|
|
|
545
|
-
|
|
546
|
-
gated =
|
|
601
|
+
require_mcp_authorization!
|
|
602
|
+
gated = mcp_clients.flat_map(&:tools).select { |tool| attachable_mcp_tool?(tool) }.map do |tool|
|
|
547
603
|
wrap_mcp_tool(Nexo::MCP::GatedTool.new(tool: tool, permissions: @permissions))
|
|
548
604
|
end
|
|
549
605
|
chat.with_tools(*gated) unless gated.empty?
|
|
550
606
|
end
|
|
551
607
|
|
|
608
|
+
# The agent's MCP servers, built once from the `mcp` declarations (with this
|
|
609
|
+
# agent's `mcp_owner`) and reused until #close.
|
|
610
|
+
def mcp_clients
|
|
611
|
+
@mcp_clients ||= self.class.mcp.map { |cfg| Nexo::MCP.build(**cfg, owner: @mcp_owner) }
|
|
612
|
+
end
|
|
613
|
+
|
|
614
|
+
# Raises Nexo::AuthorizationRequired for the first server a person still has
|
|
615
|
+
# to authorize. Checked before any tool is listed, so the host gets one clear
|
|
616
|
+
# error to act on in place of a 401 from somewhere inside the first request.
|
|
617
|
+
# Reads the credential store only — no network.
|
|
618
|
+
def require_mcp_authorization!
|
|
619
|
+
self.class.mcp.zip(mcp_clients).each do |cfg, client|
|
|
620
|
+
next unless Nexo::MCP.user_authorized?(cfg)
|
|
621
|
+
|
|
622
|
+
raise Nexo::AuthorizationRequired.new(cfg[:name]) unless client.authorized?
|
|
623
|
+
end
|
|
624
|
+
end
|
|
625
|
+
|
|
552
626
|
# Whether an MCP tool is worth attaching: the model may call it, and the gate
|
|
553
627
|
# could authorize it. A tool `:read_only` can never allow is left out of the
|
|
554
628
|
# schema, as a sandbox tool is — it would only cost tokens and a wasted call.
|
|
@@ -561,6 +635,52 @@ module Nexo
|
|
|
561
635
|
!tool.respond_to?(:visibility) || tool.visibility.include?(:model)
|
|
562
636
|
end
|
|
563
637
|
|
|
638
|
+
# The agent's file tools, per the `file_tools` declaration.
|
|
639
|
+
#
|
|
640
|
+
# A tool is attached only when the agent could actually use it: the gate must
|
|
641
|
+
# not deny it statically (a :read_only agent can never be authorized for
|
|
642
|
+
# :write), otherwise a guaranteed failure sits in the tool schema on every
|
|
643
|
+
# turn and models do try it. #authorize! stays the actual boundary either way.
|
|
644
|
+
def file_tool_set
|
|
645
|
+
case self.class.file_tools
|
|
646
|
+
when :nexo then nexo_file_tools
|
|
647
|
+
when :core then core_file_tools
|
|
648
|
+
else raise ConfigurationError, "unknown file_tools #{self.class.file_tools.inspect} (use :nexo or :core)"
|
|
649
|
+
end
|
|
650
|
+
end
|
|
651
|
+
|
|
652
|
+
# Nexo's own file tools. One ReadTracker per chat, shared by ReadFile (records)
|
|
653
|
+
# and WriteFile (enforces the read-before-write + stale guard).
|
|
654
|
+
def nexo_file_tools
|
|
655
|
+
tracker = ReadTracker.new
|
|
656
|
+
tools = [Tools::ReadFile.new(sandbox: @sandbox, permissions: @permissions, tracker: tracker)]
|
|
657
|
+
unless @permissions.never_allows?(:write)
|
|
658
|
+
tools << Tools::WriteFile.new(sandbox: @sandbox, permissions: @permissions, tracker: tracker)
|
|
659
|
+
end
|
|
660
|
+
tools << Tools::Glob.new(sandbox: @sandbox, permissions: @permissions)
|
|
661
|
+
end
|
|
662
|
+
|
|
663
|
+
# `ruby_llm`'s file tools over one SandboxFileStore per chat, each behind
|
|
664
|
+
# Nexo::GatedTool. They are built here and attached with `with_tools` — NOT
|
|
665
|
+
# with `chat.with_file_store`, which would attach them with no place for the
|
|
666
|
+
# gate. The gate is told the path the call acts on, like Nexo's own tools.
|
|
667
|
+
#
|
|
668
|
+
# VERIFIED (ruby_llm 2.2.3): `FileStore::Tools.classes(names)` returns the
|
|
669
|
+
# tool classes for `:read` (list, read, search), `:write` and `:edit`, each
|
|
670
|
+
# built with `store:` (a callable). These are internal to `ruby_llm`; the
|
|
671
|
+
# real-loop tests are what catches a change.
|
|
672
|
+
def core_file_tools
|
|
673
|
+
store = SandboxFileStore.new(@sandbox)
|
|
674
|
+
groups = {read: :read}
|
|
675
|
+
groups = groups.merge(write: :write, edit: :write) unless @permissions.never_allows?(:write)
|
|
676
|
+
groups.flat_map do |group, capability|
|
|
677
|
+
::RubyLLM::FileStore::Tools.classes([group]).map do |tool|
|
|
678
|
+
Nexo::GatedTool.new(tool: tool.new(store: -> { store }), permissions: @permissions,
|
|
679
|
+
capability: capability, detail: ->(arguments) { arguments[:path] })
|
|
680
|
+
end
|
|
681
|
+
end
|
|
682
|
+
end
|
|
683
|
+
|
|
564
684
|
# Attaches the tools declared with the `tools` macro. One declared with a
|
|
565
685
|
# `capability:` is wrapped in Nexo::GatedTool, and skipped altogether when the
|
|
566
686
|
# gate could never authorize it.
|
|
@@ -619,15 +739,21 @@ module Nexo
|
|
|
619
739
|
end
|
|
620
740
|
end
|
|
621
741
|
|
|
622
|
-
# Applies
|
|
623
|
-
# `with_tool_options
|
|
624
|
-
#
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
return if mode.nil?
|
|
742
|
+
# Applies the harness-wide tool execution settings through
|
|
743
|
+
# `with_tool_options` (ruby_llm 2.x moved them off `with_tools`):
|
|
744
|
+
# Nexo.config.tool_concurrency, where `nil` leaves RubyLLM's own setting
|
|
745
|
+
# alone, and Nexo.config.tool_calls_per_round, where `nil` sets no cap.
|
|
746
|
+
def apply_tool_options(chat)
|
|
628
747
|
return unless chat.respond_to?(:with_tool_options)
|
|
629
748
|
|
|
630
|
-
|
|
749
|
+
options = {concurrency: Nexo.config.tool_concurrency, calls: Nexo.config.tool_calls_per_round}.compact
|
|
750
|
+
chat.with_tool_options(**options) unless options.empty?
|
|
751
|
+
end
|
|
752
|
+
|
|
753
|
+
# Applies the agent's `context_budget` declaration, when there is one.
|
|
754
|
+
def apply_context_budget(chat)
|
|
755
|
+
budget = self.class.context_budget
|
|
756
|
+
chat.with_context_budget(budget) if budget && chat.respond_to?(:with_context_budget)
|
|
631
757
|
end
|
|
632
758
|
|
|
633
759
|
# Hook: called once per MCP tool, AFTER it is wrapped in a permission-gating
|
data/lib/nexo/configuration.rb
CHANGED
|
@@ -33,6 +33,15 @@ module Nexo
|
|
|
33
33
|
# Distinct from #concurrency, which governs how Nexo itself runs blocking work.
|
|
34
34
|
attr_accessor :tool_concurrency
|
|
35
35
|
|
|
36
|
+
# The most tool calls ONE model response may run, default `20`. A model can
|
|
37
|
+
# ask for any number of calls in a single response, and `max_turns` counts
|
|
38
|
+
# responses, not calls — so without this a single round is unbounded. Calls
|
|
39
|
+
# past the limit are answered with an error straight away and never run; the
|
|
40
|
+
# model sees that and can ask again. `nil` removes the limit. Must be 2 or
|
|
41
|
+
# more (to `ruby_llm`, `1` means "ask the provider for one call at a time").
|
|
42
|
+
# Passed to `ruby_llm` as `with_tool_options(calls:)`.
|
|
43
|
+
attr_accessor :tool_calls_per_round
|
|
44
|
+
|
|
36
45
|
# Max in-flight tasks for Nexo.concurrent fan-out (Spec 5), default `8`.
|
|
37
46
|
# The single most important knob for staying under provider rate limits.
|
|
38
47
|
attr_accessor :max_in_flight
|
|
@@ -70,6 +79,11 @@ module Nexo
|
|
|
70
79
|
# workflow jobs to a dedicated queue.
|
|
71
80
|
attr_accessor :job_queue
|
|
72
81
|
|
|
82
|
+
# The file tools an agent gets when it does not say (see the `file_tools`
|
|
83
|
+
# macro): `:nexo` (default) for Nexo's own three, `:core` for `ruby_llm`'s five
|
|
84
|
+
# over the agent's sandbox. `:core` becomes the default in 1.0.
|
|
85
|
+
attr_accessor :file_tools
|
|
86
|
+
|
|
73
87
|
# What happens when the model calls a tool Nexo did not attach — one a host
|
|
74
88
|
# added to the chat itself, outside the `tools` macro, so no permission gate
|
|
75
89
|
# ever saw it. `false` (default in 0.14) runs it and warns once per tool;
|
|
@@ -87,11 +101,13 @@ module Nexo
|
|
|
87
101
|
@skills_path = default_skills_path
|
|
88
102
|
@concurrency = :threaded # async is opt-in; :threaded stays the default
|
|
89
103
|
@max_in_flight = 8
|
|
104
|
+
@tool_calls_per_round = 20 # with max_turns 25: at most 500 tool calls a prompt
|
|
90
105
|
@buffer_workflow_events = false
|
|
91
106
|
@session_chat_model = "Chat" # ruby_llm's own default acts_as_chat host
|
|
92
107
|
@broadcast_events = false # safe default: opt in to the Turbo mirror
|
|
93
108
|
@run_store = nil # nil → the automatic choice (ActiveRecord under Rails, else Memory)
|
|
94
109
|
@job_queue = nil # nil → ActiveJob's default queue
|
|
110
|
+
@file_tools = :nexo # ruby_llm's own (:core) are opt-in until 1.0
|
|
95
111
|
@strict_tools = false # warn, do not refuse; flips to true in 1.0
|
|
96
112
|
end
|
|
97
113
|
|
data/lib/nexo/gated_tool.rb
CHANGED
|
@@ -25,10 +25,16 @@ module Nexo
|
|
|
25
25
|
class GatedTool
|
|
26
26
|
# Wraps `tool` so every call is authorized for `capability` (one of the
|
|
27
27
|
# Permissions capabilities, e.g. `:write`) through `permissions` first.
|
|
28
|
-
|
|
28
|
+
#
|
|
29
|
+
# `detail:` is an optional `->(arguments)` returning what the gate is told the
|
|
30
|
+
# call acts on — a path, say. Without it, or when it returns `nil`, the detail
|
|
31
|
+
# is the tool name and its arguments as JSON, so two different calls are never
|
|
32
|
+
# mistaken for one when an approval is recorded.
|
|
33
|
+
def initialize(tool:, permissions:, capability:, detail: nil)
|
|
29
34
|
@tool = tool
|
|
30
35
|
@permissions = permissions
|
|
31
36
|
@capability = capability
|
|
37
|
+
@detail = detail
|
|
32
38
|
end
|
|
33
39
|
|
|
34
40
|
# Authorizes the call, then delegates to the wrapped tool. A denial is
|
|
@@ -80,7 +86,8 @@ module Nexo
|
|
|
80
86
|
# approval is the tool name and its arguments, so a human can tell one call
|
|
81
87
|
# from another.
|
|
82
88
|
def authorize!(arguments)
|
|
83
|
-
@
|
|
89
|
+
detail = @detail&.call(arguments) || "#{name} #{JSON.generate(arguments)}"
|
|
90
|
+
@permissions.authorize!(@capability, detail)
|
|
84
91
|
end
|
|
85
92
|
end
|
|
86
93
|
end
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
require "fileutils"
|
|
5
|
+
require "json"
|
|
6
|
+
|
|
7
|
+
module Nexo
|
|
8
|
+
module MCP
|
|
9
|
+
# Keeps the OAuth credentials of MCP servers on disk, so a host outside Rails
|
|
10
|
+
# — a CLI, a script, a daemon — stays authorized across restarts. `ruby_llm`
|
|
11
|
+
# keeps them in memory by default and in an encrypted table under Rails; this
|
|
12
|
+
# is the third option, in the same spirit as RunStore::Disk.
|
|
13
|
+
#
|
|
14
|
+
# ```ruby
|
|
15
|
+
# RubyLLM.configure do |config|
|
|
16
|
+
# config.mcp_credential_store = Nexo::MCP::CredentialStore.new(dir: "~/.local/state/my-app/mcp")
|
|
17
|
+
# end
|
|
18
|
+
# ```
|
|
19
|
+
#
|
|
20
|
+
# It answers the store contract `ruby_llm` documents: `read(key)`,
|
|
21
|
+
# `write(key, data, owner:)`, `delete(key)` and `synchronize(key)`.
|
|
22
|
+
#
|
|
23
|
+
# ⚠️ SECURITY: the files hold live access and refresh tokens, in plain JSON.
|
|
24
|
+
# They are NOT encrypted. The directory is created `0700` and every file
|
|
25
|
+
# `0600`, so they are readable by your user and nobody else — the same
|
|
26
|
+
# protection an SSH key or a `gh` token has, and no more. Do not point this at
|
|
27
|
+
# a shared or synced directory, and prefer the encrypted Rails table when
|
|
28
|
+
# ActiveRecord is available. File names are a digest of the key, so the
|
|
29
|
+
# directory listing reveals neither owners nor servers.
|
|
30
|
+
class CredentialStore
|
|
31
|
+
# The directory the credentials live in (expanded).
|
|
32
|
+
attr_reader :dir
|
|
33
|
+
|
|
34
|
+
# Roots the store at `dir`, creating it `0700` if needed.
|
|
35
|
+
def initialize(dir:)
|
|
36
|
+
@dir = File.expand_path(dir)
|
|
37
|
+
FileUtils.mkdir_p(@dir, mode: 0o700)
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# The credentials stored under `key` as a Hash, or `nil`. A file that is
|
|
41
|
+
# missing or unreadable as JSON reads as `nil`: the server is then simply
|
|
42
|
+
# not authorized, which is the safe answer.
|
|
43
|
+
def read(key)
|
|
44
|
+
JSON.parse(File.read(path(key)))
|
|
45
|
+
rescue Errno::ENOENT, JSON::ParserError
|
|
46
|
+
nil
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# Stores `data` under `key`. Written to a temporary file and renamed, so a
|
|
50
|
+
# reader never sees half a file and a crash never leaves one. `owner:` is
|
|
51
|
+
# part of the contract and already part of the key.
|
|
52
|
+
def write(key, data, **)
|
|
53
|
+
target = path(key)
|
|
54
|
+
temporary = "#{target}.#{Process.pid}.#{Thread.current.object_id}.tmp"
|
|
55
|
+
File.open(temporary, File::WRONLY | File::CREAT | File::TRUNC, 0o600) { |file| file.write(JSON.generate(data)) }
|
|
56
|
+
File.rename(temporary, target)
|
|
57
|
+
data
|
|
58
|
+
ensure
|
|
59
|
+
File.delete(temporary) if temporary && File.exist?(temporary)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Forgets the credentials stored under `key`.
|
|
63
|
+
def delete(key)
|
|
64
|
+
File.delete(path(key))
|
|
65
|
+
rescue Errno::ENOENT
|
|
66
|
+
nil
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
# Runs the block while no other process holds `key`, so two processes
|
|
70
|
+
# sharing the directory never refresh the same token at once.
|
|
71
|
+
def synchronize(key)
|
|
72
|
+
File.open("#{path(key)}.lock", File::RDWR | File::CREAT, 0o600) do |lock|
|
|
73
|
+
lock.flock(File::LOCK_EX)
|
|
74
|
+
yield
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
private
|
|
79
|
+
|
|
80
|
+
# The file for `key`: a digest, so a key containing a URL is a safe name.
|
|
81
|
+
def path(key)
|
|
82
|
+
File.join(@dir, "#{Digest::SHA256.hexdigest(key.to_s)}.json")
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|
|
86
|
+
end
|
data/lib/nexo/mcp.rb
CHANGED
|
@@ -46,8 +46,17 @@ module Nexo
|
|
|
46
46
|
# the server's in-memory settings; the event path (Workflow#serializable)
|
|
47
47
|
# carries only tool `name`/`args` and return values, never connection config,
|
|
48
48
|
# so the token never reaches `emit` (see the no-leak test).
|
|
49
|
-
|
|
50
|
-
|
|
49
|
+
#
|
|
50
|
+
# `oauth:` (0.15) turns on `ruby_llm`'s MCP OAuth for an HTTP server: `true`,
|
|
51
|
+
# or a Hash of the options `RubyLLM::MCP.oauth` takes (`client_id:`,
|
|
52
|
+
# `client_secret:`, `scopes:`, `grant:`, `private_key:`, `assertion:`,
|
|
53
|
+
# `identity_provider:`, `authorization_params:`). `ruby_llm` runs the whole
|
|
54
|
+
# flow — discovery, registration, PKCE, refresh, DPoP — and keeps the
|
|
55
|
+
# credentials in `RubyLLM.config.mcp_credential_store`. Nexo adds nothing to
|
|
56
|
+
# it but the owner: `owner:` (normally `Agent.new(mcp_owner:)`) says whose
|
|
57
|
+
# credentials these are. `oauth:` and `token:` are mutually exclusive.
|
|
58
|
+
def build(name:, transport:, token: nil, owner: nil, **config)
|
|
59
|
+
client_factory.mcp(**settings(name: name, transport: transport, token: token, owner: owner, config: config))
|
|
51
60
|
rescue ArgumentError => e
|
|
52
61
|
raise ConfigurationError, "mcp :#{name} — #{e.message}"
|
|
53
62
|
end
|
|
@@ -73,16 +82,19 @@ module Nexo
|
|
|
73
82
|
private
|
|
74
83
|
|
|
75
84
|
# Maps the macro opts onto the keywords `RubyLLM.mcp` takes.
|
|
76
|
-
def settings(name:, transport:, token:, config:)
|
|
85
|
+
def settings(name:, transport:, token:, config:, owner: nil)
|
|
77
86
|
config = config.dup
|
|
78
87
|
mapped = {name: name.to_s}
|
|
88
|
+
oauth = config.delete(:oauth)
|
|
79
89
|
|
|
80
90
|
if transport.to_sym == :stdio
|
|
81
91
|
command = Array(config.delete(:command)) + Array(config.delete(:args))
|
|
82
92
|
raise ConfigurationError, "mcp :#{name} — a :stdio server needs a `command:`" if command.empty?
|
|
83
93
|
mapped[:command] = command.map(&:to_s)
|
|
94
|
+
raise ConfigurationError, "mcp :#{name} — `oauth:` needs an HTTP transport, not :stdio" if oauth
|
|
84
95
|
elsif HTTP_TRANSPORTS.include?(transport.to_sym)
|
|
85
96
|
mapped[:bearer_token] = bearer(token) unless token.nil?
|
|
97
|
+
mapped[:oauth] = oauth_settings(name, oauth, owner, token) if oauth
|
|
86
98
|
else
|
|
87
99
|
raise ConfigurationError,
|
|
88
100
|
"mcp :#{name} — unknown transport #{transport.inspect} (use :stdio, :http, :sse or :streamable)"
|
|
@@ -91,6 +103,42 @@ module Nexo
|
|
|
91
103
|
mapped.merge(config)
|
|
92
104
|
end
|
|
93
105
|
|
|
106
|
+
# The `oauth:` Hash handed to `ruby_llm`, with the owner filled in.
|
|
107
|
+
#
|
|
108
|
+
# `ruby_llm` files credentials under "<owner>@<server url>", taking the
|
|
109
|
+
# owner's GlobalID when it has one and `to_s` otherwise. An object with
|
|
110
|
+
# neither a GlobalID nor a meaningful `to_s` would be filed under its
|
|
111
|
+
# inspect string — a different key in every process, so the credentials
|
|
112
|
+
# could never be found again. Refuse that here.
|
|
113
|
+
def oauth_settings(name, oauth, owner, token)
|
|
114
|
+
raise ConfigurationError, "mcp :#{name} — use `oauth:` or `token:`, not both" unless token.nil?
|
|
115
|
+
|
|
116
|
+
oauth = (oauth == true) ? {} : oauth.to_h
|
|
117
|
+
owner = oauth[:owner] if owner.nil?
|
|
118
|
+
return oauth.except(:owner) if owner.nil?
|
|
119
|
+
|
|
120
|
+
unless owner.respond_to?(:to_gid) || [String, Symbol, Integer].any? { |type| owner.is_a?(type) }
|
|
121
|
+
raise ConfigurationError,
|
|
122
|
+
"mcp :#{name} — the OAuth owner must be a String, Symbol, Integer or a record with a GlobalID " \
|
|
123
|
+
"(got #{owner.class}); its credentials are stored under it"
|
|
124
|
+
end
|
|
125
|
+
oauth.merge(owner: -> { owner })
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# Whether a server declared with these `mcp` macro options needs a PERSON to
|
|
129
|
+
# authorize it before it can be used: OAuth with the authorization-code
|
|
130
|
+
# grant. The client-credentials and JWT-bearer grants fetch a token by
|
|
131
|
+
# themselves on the first request.
|
|
132
|
+
def user_authorized?(config)
|
|
133
|
+
oauth = config[:oauth]
|
|
134
|
+
return false unless oauth
|
|
135
|
+
|
|
136
|
+
oauth = {} if oauth == true
|
|
137
|
+
grant = oauth[:grant] || ((oauth[:assertion] || oauth[:identity_provider]) ? :jwt_bearer : :authorization_code)
|
|
138
|
+
grant.to_sym == :authorization_code
|
|
139
|
+
end
|
|
140
|
+
public :user_authorized?
|
|
141
|
+
|
|
94
142
|
# `ruby_llm` reads a Proc again for each request; any other callable is
|
|
95
143
|
# wrapped in one so it gets the same treatment.
|
|
96
144
|
def bearer(token)
|
data/lib/nexo/sandbox.rb
CHANGED
|
@@ -32,6 +32,26 @@ module Nexo
|
|
|
32
32
|
raise NotImplementedError
|
|
33
33
|
end
|
|
34
34
|
|
|
35
|
+
# Every regular file under the sandbox root, as paths relative to it,
|
|
36
|
+
# skipping dotfiles and anything inside a dot-directory. This is what a file
|
|
37
|
+
# listing is built from (see SandboxFileStore).
|
|
38
|
+
#
|
|
39
|
+
# The default asks the sandbox's own shell, which is right for a container or
|
|
40
|
+
# a remote box and costs one command; Virtual and Local answer from memory and
|
|
41
|
+
# the filesystem. A sandbox with neither raises `NotImplementedError`.
|
|
42
|
+
def files
|
|
43
|
+
raise NotImplementedError, "#{self.class} cannot list its files" unless supports?(:shell)
|
|
44
|
+
|
|
45
|
+
out = shell("find . -type f -not -path '*/.*'")
|
|
46
|
+
out[:stdout].to_s.split("\n").map { |path| path.delete_prefix("./") }.reject(&:empty?).sort
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# The size of the file at `path` in bytes. The default reads the file;
|
|
50
|
+
# sandboxes that can answer without reading override it.
|
|
51
|
+
def file_size(path)
|
|
52
|
+
read(path).bytesize
|
|
53
|
+
end
|
|
54
|
+
|
|
35
55
|
# Releases any resources the sandbox holds. No-op by default.
|
|
36
56
|
def close
|
|
37
57
|
nil
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Nexo
|
|
4
|
+
# A `RubyLLM::FileStore` over any Nexo sandbox, so `ruby_llm`'s own file tools
|
|
5
|
+
# (`list_files`, `read_file`, `search_files`, `write_file`, `edit_file`) work on
|
|
6
|
+
# the files an agent's sandbox holds — in memory, on the host, or in a
|
|
7
|
+
# container. Agent#chat builds one per chat when the agent declares
|
|
8
|
+
# `file_tools :core`.
|
|
9
|
+
#
|
|
10
|
+
# What the store adds over Nexo's own three file tools comes from `ruby_llm`:
|
|
11
|
+
# editing part of a file, searching file contents, and a read-before-write
|
|
12
|
+
# guard that compares content digests, so it works on every sandbox (Nexo's own
|
|
13
|
+
# guard compares modification times and is skipped on Virtual).
|
|
14
|
+
#
|
|
15
|
+
# Every path goes through the sandbox, so the sandbox's own confinement still
|
|
16
|
+
# applies: `RubyLLM::FileStore.path` refuses `..` before the store is asked, and
|
|
17
|
+
# Sandboxes::Local raises `SecurityError` for a symlink that leaves `cwd`.
|
|
18
|
+
#
|
|
19
|
+
# A sandbox has no delete, so neither has this store; `delete_file` is not
|
|
20
|
+
# among the tools Agent attaches.
|
|
21
|
+
#
|
|
22
|
+
# VERIFIED (ruby_llm 2.2.3): a store implements `list`, `[]`, `read`, `write`
|
|
23
|
+
# and `delete`; the tools also use the inherited `with_lock`, `read_digest`,
|
|
24
|
+
# `record_read` and `text_with_digest`.
|
|
25
|
+
class SandboxFileStore < ::RubyLLM::FileStore
|
|
26
|
+
# Wraps `sandbox` (a Nexo::Sandbox).
|
|
27
|
+
def initialize(sandbox)
|
|
28
|
+
super()
|
|
29
|
+
@sandbox = sandbox
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# The files inside the folder `prefix`, or every file, sorted by path. Sizes
|
|
33
|
+
# come from Sandbox#file_size; digests are left for the tools to compute when
|
|
34
|
+
# they read a file, so a listing does not read every file.
|
|
35
|
+
def list(prefix = nil)
|
|
36
|
+
@sandbox.files.select { |path| ::RubyLLM::FileStore.inside?(path, prefix) }.sort.map do |path|
|
|
37
|
+
stored(path, byte_size: @sandbox.file_size(path))
|
|
38
|
+
end
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
# The StoredFile at `path`, or `nil` when there is none.
|
|
42
|
+
def [](path)
|
|
43
|
+
path = ::RubyLLM::FileStore.path(path)
|
|
44
|
+
content = fetch(path) or return
|
|
45
|
+
stored(path, byte_size: content.bytesize, content: content)
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# The content of the file at `path`, as bytes.
|
|
49
|
+
def read(path)
|
|
50
|
+
path = ::RubyLLM::FileStore.path(path)
|
|
51
|
+
fetch(path) or raise ::RubyLLM::FileNotFoundError, "No file at #{path}"
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# Writes `content` to `path` through the sandbox and returns its StoredFile.
|
|
55
|
+
def write(path, content, content_type: nil)
|
|
56
|
+
path = ::RubyLLM::FileStore.path(path)
|
|
57
|
+
content = ::RubyLLM::FileStore.bytes(content)
|
|
58
|
+
with_lock { @sandbox.write(path, content) }
|
|
59
|
+
stored(path, byte_size: content.bytesize, content: content, content_type: content_type)
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# A sandbox cannot delete, so this store cannot either.
|
|
63
|
+
def delete(_path)
|
|
64
|
+
raise NotImplementedError, "a sandbox-backed file store cannot delete files"
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
private
|
|
68
|
+
|
|
69
|
+
# The bytes at `path`, or `nil` when the sandbox has no such file.
|
|
70
|
+
def fetch(path)
|
|
71
|
+
@sandbox.read(path).to_s.b
|
|
72
|
+
rescue Errno::ENOENT, Errno::EISDIR, IOError
|
|
73
|
+
nil
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# Builds the StoredFile for `path`. With the content at hand its digest and
|
|
77
|
+
# sniffed type are exact; a listing entry gets its type from the file name.
|
|
78
|
+
def stored(path, byte_size:, content: nil, content_type: nil)
|
|
79
|
+
::RubyLLM::StoredFile.new(
|
|
80
|
+
path: path,
|
|
81
|
+
byte_size: byte_size,
|
|
82
|
+
content_type: content_type || ::RubyLLM::FileStore.content_type_for(path, content || ""),
|
|
83
|
+
digest: content && ::RubyLLM::FileStore.digest(content)
|
|
84
|
+
)
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
end
|
|
@@ -293,7 +293,7 @@ module Nexo
|
|
|
293
293
|
# it with no daemon. Matches by the exact identity label set in `run_argv`
|
|
294
294
|
# (`label=nexo.sandbox.id=<name>`), NOT a `name=<name>` substring filter.
|
|
295
295
|
def reconnect_argv
|
|
296
|
-
[@bin, "ps", "-
|
|
296
|
+
[@bin, "ps", "-aq", "--no-trunc", "-f", "label=nexo.sandbox.id=#{@name}"]
|
|
297
297
|
end
|
|
298
298
|
|
|
299
299
|
# Runs `cmd` inside the started container, wall-clock bounded. Returns the
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Nexo
|
|
4
|
+
module Sandboxes
|
|
5
|
+
# Runs ONE command in a throwaway container and answers `ruby_llm`'s sandbox
|
|
6
|
+
# contract (`supported?` and `run`), so a Docker- or Apple-`container`-backed
|
|
7
|
+
# sandbox works anywhere that contract is accepted:
|
|
8
|
+
#
|
|
9
|
+
# ```ruby
|
|
10
|
+
# runner = Nexo::Sandboxes::ContainerRunner.new(image: "ruby:3.3-slim")
|
|
11
|
+
#
|
|
12
|
+
# # ruby_llm's own code execution, for any ruby_llm app:
|
|
13
|
+
# RubyLLM.configure { |config| config.sandbox = runner }
|
|
14
|
+
#
|
|
15
|
+
# # or as the isolation behind Nexo's local shell:
|
|
16
|
+
# class Builder < Nexo::Agent
|
|
17
|
+
# sandbox :local, isolation: runner
|
|
18
|
+
# end
|
|
19
|
+
# ```
|
|
20
|
+
#
|
|
21
|
+
# It is not a Nexo::Sandbox: it has no files of its own and keeps no container
|
|
22
|
+
# between calls. Every `run` is a fresh `<runtime> run --rm`, hardened like
|
|
23
|
+
# Sandboxes::Container (no network, all capabilities dropped,
|
|
24
|
+
# no-new-privileges, read-only root filesystem, a pids limit), with the paths
|
|
25
|
+
# the caller grants bound in at the SAME path they have on the host —
|
|
26
|
+
# `readable:` read-only, `writable:` read-write. Nothing else of the host is
|
|
27
|
+
# visible. Sandboxes::Container remains the choice when an agent needs a
|
|
28
|
+
# workspace that lives as long as the agent does.
|
|
29
|
+
#
|
|
30
|
+
# Limits, stated plainly:
|
|
31
|
+
#
|
|
32
|
+
# * `network:` from the contract (`{allow: [...]}`, which `ruby_llm` passes to
|
|
33
|
+
# install declared packages) is not honoured: a container CLI cannot express
|
|
34
|
+
# a host allow-list, so every run keeps the network this runner was built
|
|
35
|
+
# with — none by default. Package installs therefore fail unless you build
|
|
36
|
+
# the runner with `network: :bridge`, which allows ALL egress.
|
|
37
|
+
# * `denied:` hides a path by mounting an empty filesystem (a directory) or
|
|
38
|
+
# `/dev/null` (a file) over it.
|
|
39
|
+
# * Output is returned whole, not streamed; a block given to `run` is ignored.
|
|
40
|
+
# * Granted paths must exist on the host and be shared with the runtime's VM
|
|
41
|
+
# (on macOS, Docker Desktop and OrbStack share the home directory and
|
|
42
|
+
# `/private`; other locations may not be).
|
|
43
|
+
#
|
|
44
|
+
# VERIFIED (ruby_llm 2.2.3, Docker 29 through OrbStack): used as
|
|
45
|
+
# `Sandboxes::Local`'s `isolation:`, a command wrote inside the granted
|
|
46
|
+
# directory, could not see the rest of the host, and had no network.
|
|
47
|
+
class ContainerRunner
|
|
48
|
+
# What `run` returns: the contract's `stdout`, `stderr`, `exit_code` and
|
|
49
|
+
# `timed_out?`.
|
|
50
|
+
Result = Struct.new(:stdout, :stderr, :exit_code, :timed_out) do
|
|
51
|
+
# Whether the command was killed for running past its timeout.
|
|
52
|
+
def timed_out? = timed_out
|
|
53
|
+
end
|
|
54
|
+
|
|
55
|
+
# Builds a runner for `image` on `runtime` (`:docker` or `:apple`). `network:`
|
|
56
|
+
# is the container network every run gets (default `:none`); `memory:`,
|
|
57
|
+
# `cpus:`, `pids_limit:` and `user:` are passed to the runtime as they are
|
|
58
|
+
# for Sandboxes::Container. Raises ConfigurationError without an image or
|
|
59
|
+
# for an unknown runtime.
|
|
60
|
+
def initialize(image:, runtime: :docker, network: :none, memory: nil, cpus: nil, pids_limit: 512, user: nil)
|
|
61
|
+
raise ConfigurationError, "container runner requires image:" if image.to_s.empty?
|
|
62
|
+
|
|
63
|
+
@bin = Container::RUNTIMES.fetch(runtime) do
|
|
64
|
+
raise ConfigurationError, "unknown container runtime: #{runtime.inspect}"
|
|
65
|
+
end
|
|
66
|
+
@runtime = runtime
|
|
67
|
+
@image = image
|
|
68
|
+
@network = network
|
|
69
|
+
@memory = memory
|
|
70
|
+
@cpus = cpus
|
|
71
|
+
@pids_limit = pids_limit
|
|
72
|
+
@user = user
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
# Whether the runtime's CLI is installed and its daemon answers.
|
|
76
|
+
def supported?
|
|
77
|
+
system(@bin, "version", out: File::NULL, err: File::NULL) ? true : false
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
# Why #supported? is false, for the error a caller raises.
|
|
81
|
+
def reason
|
|
82
|
+
"The #{@bin} CLI is not installed or its daemon is not running."
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
# Runs `command` — one String for the shell, or a program and its arguments —
|
|
86
|
+
# in a fresh container and returns a Result. The command and its container
|
|
87
|
+
# are killed when `timeout` seconds pass.
|
|
88
|
+
def run(*command, timeout:, readable: [], writable: [], denied: [], directory: nil, env: {}, network: nil)
|
|
89
|
+
name = "nexo-run-#{Nexo.generate_run_id}"
|
|
90
|
+
argv = run_argv(name, command, readable: readable, writable: writable, denied: denied,
|
|
91
|
+
directory: directory, env: env)
|
|
92
|
+
# The CLI needs the host's own environment (its socket and config), so it
|
|
93
|
+
# is passed on whole; the COMMAND sees only `env:`, through `-e`.
|
|
94
|
+
stdout, stderr, status = Subprocess.capture(ENV.to_h, *argv, timeout: timeout)
|
|
95
|
+
Result.new(stdout, stderr, status, false)
|
|
96
|
+
rescue Timeout::Error => e
|
|
97
|
+
# Killing the CLI does not stop the container it started.
|
|
98
|
+
system(@bin, "rm", "-f", name, out: File::NULL, err: File::NULL)
|
|
99
|
+
Result.new("", e.message, nil, true)
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
private
|
|
103
|
+
|
|
104
|
+
# The exact `run` argv, built purely so the offline suite can assert it with
|
|
105
|
+
# no daemon. Every element is its own argv entry — nothing is interpolated
|
|
106
|
+
# into a shell string on the host.
|
|
107
|
+
def run_argv(name, command, readable:, writable:, denied:, directory:, env:)
|
|
108
|
+
argv = [@bin, "run", "--rm", "--name", name, "--network", @network.to_s, "--cap-drop", "ALL"]
|
|
109
|
+
argv += ["--security-opt", "no-new-privileges"] if @runtime == :docker
|
|
110
|
+
argv += ["--read-only", "--tmpfs", "/tmp:rw"]
|
|
111
|
+
argv += ["--pids-limit", @pids_limit.to_s] if @pids_limit && @runtime == :docker
|
|
112
|
+
argv += ["--memory", @memory.to_s] unless @memory.nil?
|
|
113
|
+
argv += ["--cpus", @cpus.to_s] unless @cpus.nil?
|
|
114
|
+
argv += ["--user", @user.to_s] unless @user.nil?
|
|
115
|
+
argv += mounts(readable, writable, denied)
|
|
116
|
+
env.each { |key, value| argv += ["-e", "#{key}=#{value}"] }
|
|
117
|
+
argv += ["-w", directory.to_s] if directory
|
|
118
|
+
argv << @image
|
|
119
|
+
argv + ((command.size == 1) ? ["sh", "-c", command.first.to_s] : command.map(&:to_s))
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# Bind mounts for the granted paths, each at its own host path. A path in
|
|
123
|
+
# both lists is writable. Denied paths come last so they cover what was
|
|
124
|
+
# granted around them.
|
|
125
|
+
def mounts(readable, writable, denied)
|
|
126
|
+
writable = writable.map(&:to_s).uniq
|
|
127
|
+
readable = readable.map(&:to_s).uniq - writable
|
|
128
|
+
readable.flat_map { |path| ["-v", "#{path}:#{path}:ro"] } +
|
|
129
|
+
writable.flat_map { |path| ["-v", "#{path}:#{path}:rw"] } +
|
|
130
|
+
denied.map(&:to_s).uniq.flat_map { |path| hide(path) }
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
# Covers `path` with nothing: an empty tmpfs over a directory, `/dev/null`
|
|
134
|
+
# over a file.
|
|
135
|
+
def hide(path)
|
|
136
|
+
File.directory?(path) ? ["--tmpfs", "#{path}:ro"] : ["-v", "/dev/null:#{path}:ro"]
|
|
137
|
+
end
|
|
138
|
+
end
|
|
139
|
+
end
|
|
140
|
+
end
|
data/lib/nexo/sandboxes/local.rb
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
|
-
require "open3"
|
|
4
3
|
require "fileutils"
|
|
5
4
|
require "timeout"
|
|
6
5
|
|
|
@@ -90,6 +89,22 @@ module Nexo
|
|
|
90
89
|
offload { Dir.glob(full) }.select { |match| real_within?(match) }
|
|
91
90
|
end
|
|
92
91
|
|
|
92
|
+
# Every regular file under `cwd`, relative to it. `Dir.glob` skips dotfiles
|
|
93
|
+
# by default, and a symlink whose target is outside the sandbox is left out.
|
|
94
|
+
def files
|
|
95
|
+
offload do
|
|
96
|
+
Dir.glob("**/*", base: @cwd).select do |path|
|
|
97
|
+
full = File.join(@cwd, path)
|
|
98
|
+
File.file?(full) && real_within?(full)
|
|
99
|
+
end.sort
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# The size of `path` in bytes, without reading it.
|
|
104
|
+
def file_size(path)
|
|
105
|
+
File.size(absolute(path))
|
|
106
|
+
end
|
|
107
|
+
|
|
93
108
|
def write(path, content)
|
|
94
109
|
offload do
|
|
95
110
|
full = absolute(path)
|
|
@@ -146,46 +161,12 @@ module Nexo
|
|
|
146
161
|
|
|
147
162
|
private
|
|
148
163
|
|
|
149
|
-
# The unconfined path: an ordinary host process
|
|
150
|
-
#
|
|
151
|
-
#
|
|
152
|
-
# child inherits the whole process environment and `@env` only adds to it.
|
|
164
|
+
# The unconfined path: an ordinary host process, given ONLY the narrowed
|
|
165
|
+
# environment and killed with everything it started when the timeout fires
|
|
166
|
+
# (see Subprocess).
|
|
153
167
|
def host_shell(command, timeout)
|
|
154
|
-
|
|
155
|
-
|
|
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
|
|
168
|
+
stdout, stderr, status = Subprocess.capture(@env, command, timeout: timeout, chdir: @cwd)
|
|
169
|
+
{stdout: stdout, stderr: stderr, status: status}
|
|
189
170
|
end
|
|
190
171
|
|
|
191
172
|
# The confined path: `ruby_llm`'s sandbox contract. The runner adds this
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "timeout"
|
|
4
|
+
|
|
5
|
+
module Nexo
|
|
6
|
+
module Sandboxes
|
|
7
|
+
# Runs a host process with a timeout that actually stops it.
|
|
8
|
+
#
|
|
9
|
+
# `Timeout.timeout { Open3.capture3(...) }` does not: Open3 waits for the child
|
|
10
|
+
# in its own `ensure`, so the timeout surfaces only once the command has
|
|
11
|
+
# finished by itself. This starts the command in its own process group, reads
|
|
12
|
+
# both streams on threads, and kills the whole group when the time is up —
|
|
13
|
+
# the command and everything it started.
|
|
14
|
+
module Subprocess
|
|
15
|
+
module_function
|
|
16
|
+
|
|
17
|
+
# Runs `argv` (a command String for the shell, or a program and its
|
|
18
|
+
# arguments) with exactly the environment `env` — nothing is inherited — and
|
|
19
|
+
# returns `[stdout, stderr, exit_status]`. Raises `Timeout::Error` after
|
|
20
|
+
# `timeout` seconds, with the process group already killed. `chdir:` sets
|
|
21
|
+
# the working directory.
|
|
22
|
+
def capture(env, *argv, timeout:, chdir: nil)
|
|
23
|
+
out_read, out_write = IO.pipe
|
|
24
|
+
err_read, err_write = IO.pipe
|
|
25
|
+
options = {in: File::NULL, out: out_write, err: err_write, pgroup: true, unsetenv_others: true}
|
|
26
|
+
options[:chdir] = chdir if chdir
|
|
27
|
+
pid = Process.spawn(env, *argv, **options)
|
|
28
|
+
out_write.close
|
|
29
|
+
err_write.close
|
|
30
|
+
readers = [out_read, err_read].map { |io| reader(io) }
|
|
31
|
+
_, status = Timeout.timeout(timeout) { Process.wait2(pid) }
|
|
32
|
+
[readers[0].value.to_s, readers[1].value.to_s, status.exitstatus]
|
|
33
|
+
rescue Timeout::Error
|
|
34
|
+
kill_group(pid)
|
|
35
|
+
raise Timeout::Error, "command timed out after #{timeout}s and was killed"
|
|
36
|
+
ensure
|
|
37
|
+
[out_read, out_write, err_read, err_write].each { |io| io&.close unless io&.closed? }
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Drains one pipe on its own thread so a chatty command cannot fill the
|
|
41
|
+
# pipe buffer and block. A read cut short by the timeout teardown is nil.
|
|
42
|
+
def reader(io)
|
|
43
|
+
Thread.new do
|
|
44
|
+
io.read
|
|
45
|
+
rescue IOError
|
|
46
|
+
nil
|
|
47
|
+
end.tap { |thread| thread.report_on_exception = false }
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# Kills the command's whole process group and reaps it. Best-effort: the
|
|
51
|
+
# group may already be gone.
|
|
52
|
+
def kill_group(pid)
|
|
53
|
+
return unless pid
|
|
54
|
+
|
|
55
|
+
Process.kill("KILL", -pid)
|
|
56
|
+
Process.wait(pid)
|
|
57
|
+
rescue Errno::ESRCH, Errno::ECHILD, Errno::EPERM
|
|
58
|
+
nil
|
|
59
|
+
end
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
end
|
|
@@ -28,6 +28,13 @@ module Nexo
|
|
|
28
28
|
@files.keys.select { |key| File.fnmatch(normalized, key) }
|
|
29
29
|
end
|
|
30
30
|
|
|
31
|
+
# The in-memory files, relative to `cwd`, without dotfiles.
|
|
32
|
+
def files
|
|
33
|
+
prefix = "#{@cwd.chomp("/")}/"
|
|
34
|
+
@files.keys.filter_map { |key| key.delete_prefix(prefix) if key.start_with?(prefix) }
|
|
35
|
+
.reject { |path| path.split("/").any? { |part| part.start_with?(".") } }.sort
|
|
36
|
+
end
|
|
37
|
+
|
|
31
38
|
def shell(_command, **)
|
|
32
39
|
raise NotImplementedError, "virtual sandbox has no shell"
|
|
33
40
|
end
|
data/lib/nexo/version.rb
CHANGED
data/lib/nexo.rb
CHANGED
|
@@ -36,6 +36,22 @@ module Nexo
|
|
|
36
36
|
# image or the sandbox wiring rather than in the Ruby.
|
|
37
37
|
class EnvironmentError < ConfigurationError; end
|
|
38
38
|
|
|
39
|
+
# Raised when an agent is about to use an MCP server that a person has not
|
|
40
|
+
# authorized yet (an `oauth:` server on the authorization-code grant). Carries
|
|
41
|
+
# the `server` so a host can send the user to
|
|
42
|
+
# `agent.mcp_server(server).authorization_url(redirect_uri:)`.
|
|
43
|
+
class AuthorizationRequired < Error
|
|
44
|
+
# The `mcp` macro name of the server that needs authorizing.
|
|
45
|
+
attr_reader :server
|
|
46
|
+
|
|
47
|
+
# Builds the error for the MCP server declared as `server`.
|
|
48
|
+
def initialize(server)
|
|
49
|
+
@server = server.to_sym
|
|
50
|
+
super("MCP server :#{server} is not authorized — send the user to " \
|
|
51
|
+
"agent.mcp_server(:#{server}).authorization_url(redirect_uri:) first")
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
|
|
39
55
|
# Control-flow signal raised by the `:approve` permission gate (Spec 16) when a
|
|
40
56
|
# capability needs a human decision and none has been threaded in yet. Unlike
|
|
41
57
|
# Permissions::Denied ("no, adapt" — tools rescue it into `{error:}`),
|
data/sig/nexo/agent.rbs
CHANGED
|
@@ -7,6 +7,8 @@ module Nexo
|
|
|
7
7
|
def self.permissions: (?untyped value) -> untyped
|
|
8
8
|
def self.instructions: (?String value) -> String?
|
|
9
9
|
def self.search_backend: (?untyped obj) -> untyped
|
|
10
|
+
def self.file_tools: (?Symbol value) -> Symbol
|
|
11
|
+
def self.context_budget: (?Hash[untyped, untyped]? budget, **untyped shares) -> Hash[untyped, untyped]?
|
|
10
12
|
def self.tools: (*untyped list, ?capability: Symbol?) -> Array[Hash[Symbol, untyped]]
|
|
11
13
|
|
|
12
14
|
attr_reader cwd: String
|
|
@@ -18,7 +20,8 @@ module Nexo
|
|
|
18
20
|
attr_reader instructions: String?
|
|
19
21
|
|
|
20
22
|
def initialize: (?cwd: String, ?model: untyped, ?sandbox: untyped, ?permissions: untyped,
|
|
21
|
-
?decision: Hash[Symbol, bool]?, ?decisions: Hash[String, bool]?, ?loop: untyped) -> void
|
|
23
|
+
?decision: Hash[Symbol, bool]?, ?decisions: Hash[String, bool]?, ?mcp_owner: untyped, ?loop: untyped) -> void
|
|
24
|
+
def mcp_server: (untyped name) -> untyped
|
|
22
25
|
def chat: (?base: untyped) -> RubyLLM::Chat
|
|
23
26
|
def prompt: (String text) ?{ (untyped) -> void } -> untyped
|
|
24
27
|
end
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: nexo_ai
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.
|
|
4
|
+
version: 0.15.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Mario Alberto Chávez
|
|
@@ -159,16 +159,20 @@ files:
|
|
|
159
159
|
- lib/nexo/loop.rb
|
|
160
160
|
- lib/nexo/loops/ruby_llm.rb
|
|
161
161
|
- lib/nexo/mcp.rb
|
|
162
|
+
- lib/nexo/mcp/credential_store.rb
|
|
162
163
|
- lib/nexo/mcp/gated_tool.rb
|
|
163
164
|
- lib/nexo/output_truncator.rb
|
|
164
165
|
- lib/nexo/permissions.rb
|
|
165
166
|
- lib/nexo/read_tracker.rb
|
|
166
167
|
- lib/nexo/run_store.rb
|
|
167
168
|
- lib/nexo/sandbox.rb
|
|
169
|
+
- lib/nexo/sandbox_file_store.rb
|
|
168
170
|
- lib/nexo/sandboxes.rb
|
|
169
171
|
- lib/nexo/sandboxes/container.rb
|
|
172
|
+
- lib/nexo/sandboxes/container_runner.rb
|
|
170
173
|
- lib/nexo/sandboxes/local.rb
|
|
171
174
|
- lib/nexo/sandboxes/remote.rb
|
|
175
|
+
- lib/nexo/sandboxes/subprocess.rb
|
|
172
176
|
- lib/nexo/sandboxes/virtual.rb
|
|
173
177
|
- lib/nexo/session.rb
|
|
174
178
|
- lib/nexo/skills.rb
|